CakePHP paginate action - pagination

Can you also tell why sorting don't work with this action:
public function admin_view($id = null)
{
if (!$this->Category->exists($id)) {
throw new NotFoundException(__('Invalid product'));
}
$this->Paginator->settings = array(
'conditions' => array(
'Category.' . $this->Category->primaryKey => $id),
'limit' => $this->limit
);
$this->set('category', $this->paginate('Category'));
}
and view looks this:
<th><?php echo $this->Paginator->sort('price'); ?></th>
<?php foreach ($category[0]['Product'] as $product): ?>
<tr>
<td><?php echo h($product['price']); ?> </td>
</tr>
<?php endforeach; ?>
When I click on price it refresh my page, but sorting not working. Something wrong, I don't know why.

public function view($id = null)
{
if (!$this->Product->exists($id)) {
throw new NotFoundException(__('Invalid product'));
}
$this->Paginator->settings = array(
'conditions' => array(
'Product.' . $this->Product->primaryKey => $id)
);
$this->set('product', $this->paginate('Product');
}

Related

Codeigniter 4 ErrorException Undefined variable: table

I am facing this issue of Undefined variable as shown in the image attached which I am not sure what is wrong.
My code as follows:
Routes
$routes->get('account/game_reg', 'Game::index');
$routes->match(['get', 'post'], 'account/game_reg', 'Game::game_reg');
Controller
public function index()
{
$data = [];
if(!session()->get('isLoggedIn')):
return redirect()->to(base_url('account/login'));
endif;
$games = new GamelistModel();
$data['table'] = $games->getList();
echo view('templates/header', $data);
echo view('account/game_reg');
echo view('templates/footer');
}
public function game_reg()
{
$data = [];
helper(['form']);
$validation = \Config\Services::validation();
if($this->request->getMethod() == 'post'){
$user_id = session()->get('user_id');
//validations
$rules = [
'game_id' => 'required',
'ign' => 'required|is_unique[game_reg.ign]',
'acc_id' => 'required'
];
$errors = [
'ign' => [
'is_unique' => 'IGN already exist!'
],
'acc_id' => [
'is_unique' => 'Account ID already exist!'
]
];
if(!$this->validate($rules, $errors)){
$data['validation'] = $this->validator;
}else{
//store information into database
$model = new GameregModel();
$newData = [
'game_id' => $this->request->getVar('game_id'),
'ign' => $this->request->getVar('ign'),
'acc_id' => $this->request->getVar('acc_id'),
'user_id' => session()->get('user_id'),
'created_by' => session()->get('username')
];
$model->save($newData);
$session = session();
$session->setFlashdata('success', 'Game Successfully Added!');
return redirect()->to(base_url('account/game_reg'));
}
}
echo view('templates/header', $data);
echo view('account/game_reg');
echo view('templates/footer');
}
GameregModel
<?php namespace App\Models;
use CodeIgniter\Model;
class GameregModel extends Model{
protected $table = 'game_reg';
protected $allowedFields = [
'user_id',
'game_id',
'ign',
'acc_id',
'created_at',
'updated_at',
'created_by'
];
}
?>
GamelistModel
<?php namespace App\Models;
use CodeIgniter\Model;
class GamelistModel extends Model{
protected $table = 'game_list';
protected $primarykey = 'game_id';
protected $allowedFields = [
'game_id',
'game_name'
];
public function getList()
{
return $this->orderBy('game_id', 'ASC')->findAll();
}
}
?>
Views
<select id="myDropdown">
<?php
$i = 1;
foreach($table as $t) :
$i++;
?>
<option value="<?= $t['game_id']; ?>" data-imagesrc="/img/logo_<?= strtolower($t['game_name']); ?>.jpg"><?= $t['game_name']; ?></option>
<?php endforeach; ?>
</select>
If I remove away the is_unique function, everything works perfectly fine but when I include the is_unique, I get the error. What I am trying to do is, I would retrieve a list of games updated by admin, user will then choose from this list and save into their profile.
Hope someone can help me out of this.
Thanks in advance guys!
You are only sending the data into one of your views. The one using the $table variable does not have access to it.
So in your loading views code you have to do the following:
echo view('templates/header', $data);
echo view('account/game_reg', $data);
echo view('templates/footer', $data);
It's better to just send the data across all views.
The other thing I noticed (nothing to do with the problem here) is that you're closing the php tags inside your models. Never do that. Your classes should never have the php closing tag ?>.

Assignment to a string variable in which is another variable

Hi i have this controler in Yii2 which render me view. Then i can write in console yii generator/generate example example and then This action generate me skeleton od model and controller which i have in my views. This is code
<?php
namespace console\controllers;
use yii\console\Controller;
class GeneratorController extends Controller {
private $viewControllerPath = "rest/modules/crm/v1/controllers/";
private $viewModelPath = 'rest/modules/crm/v1/models/';
public function actionGenerate($className, $modelClass) {
$controller = $this->renderFile('#app/views/generator/restController.php', ['className' => $className, 'modelClass' =>
$modelClass]);
file_put_contents(\Yii::getAlias($this->viewControllerPath . $className . 'Controller' . '.php'), $controller);
$model = $this->renderFile('#app/views/generator/restModel.php', ['className' => $className, 'modelClass' => $modelClass]);
file_put_contents(\Yii::getAlias($this->viewModelPath . $className . 'Model' . '.php'), $model);
}
}`
And this is this view:
`
<?php
echo "<?php\n";
?>
namespace rest\modules\<?= $modelClass ?>\v1\models;
use common\models\<?= $modelClass ?>\<?= $className ?> as CommonModel;
class <?= $className ?> extends CommonModel {
}`
The last think what i should to do is put mz variable $modelClass in this path
private $viewControllerPath = "rest/modules/crm/v1/controllers/";
instead of crm. Then my model and controler will be appear in in appropriate folders.
I try to do this but it isnt work:
private $viewControllerPath = "rest/modules/'.$modelClass.'/v1/controllers/";
Anyone can help me? Maybe i can use __constructor there but i dont know how to do it
Just replace crm word of your variables with $modelClass inside your actionGenerate function like this:
public function actionGenerate($className, $modelClass) {
// replacing 'crm' with $modelClass
if( ! empty($modelClass) ) {
$this->viewControllerPath = str_replace ( 'crm' , $modelClass , $this->viewControllerPath );
$this->viewModelPath = str_replace ( 'crm' , $modelClass , $this->viewModelPath );
}
$controller = $this->renderFile('#app/views/generator/restController.php', ['className' => $className, 'modelClass' =>
$modelClass]);
file_put_contents(\Yii::getAlias($this->viewControllerPath . $className . 'Controller' . '.php'), $controller);
$model = $this->renderFile('#app/views/generator/restModel.php', ['className' => $className, 'modelClass' => $modelClass]);
file_put_contents(\Yii::getAlias($this->viewModelPath . $className . 'Model' . '.php'), $model);
}

Issue for a "two dimentionnal 'add another item' " with FormStateInterface::getTriggeringElement()

I'm learning drupal 8. I want create a page who contain a 'two dimensionnal' 'add another item' form. My code works well almost, but I have a strange behavior when I add rooms to a house (there is a strange value in my debug logs from the FormStateInterface::getTriggeringElement(), see to the bottom for the code and log)
First : I have two structures, houses and rooms. The user can create some houses and for each house, he can create some rooms :
When I add some houses, the form works fine :
When I add some rooms to the last house, the form works fine too :
But when I add some rooms to any "no-last" house, the form doesn't work fine (in the screenshot, I click one time to the "add room" in the block house '1', the label of the "house 1" became "house 2" (?!) and on click add 5 rooms (?!) :
Here my code and a strange debug log, I don't explain why I get this value (from the getTriggeringElement() in the room_addMoreSubmit callback and this is the problem I think)
<?php
namespace Drupal\projet\Form;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
class HouseForm extends FormBase {
public function getFormId(){
return 'custom_rooms_form';
}
function buildForm(array $form, FormStateInterface $form_state) {
$house_count = $form_state->get('house_count');
if (is_null($house_count)) {
$house_count = 1;
$form_state->set('house_count', $house_count);
}
$form['house'] = array(
//'#tree' => TRUE,
'#prefix' => '<div id="house-replace">',
'#suffix' => '</div>'
);
for ($house_delta = 0; $house_delta < $house_count; $house_delta++) {
if (!isset($form['house'][$house_delta])) {
$room_count[$house_delta] = $form_state->get('room_count_'.$house_delta);
if (is_null($room_count[$house_delta])) {
$room_count[$house_delta] = 1;
$form_state->set('room_count_'.$house_delta, $room_count[$house_delta]);
}
dd($room_count, "room_COUNT");
$form['house'][$house_delta]['room'] = array(
'#type' => 'fieldset',
'#title' => t('house : '.$house_delta),
//'#tree' => TRUE,
'#prefix' => '<div id="room-replace-'.$house_delta.'">',
'#suffix' => '</div>'
);
for ($room_delta = 0; $room_delta < $room_count[$house_delta]; $room_delta++) {
if (!isset($form['house'][$house_delta]['room'][$room_delta])) {
$room = array(
'#type' => 'textfield'
);
$check = array(
'#type' => 'checkbox'
);
$form['house'][$house_delta]['room'][$room_delta] = array(
'#type' => 'fieldset',
'#title' => t('room : '.$house_delta.'.'.$room_delta),
);
$form['house'][$house_delta]['room'][$room_delta]['text'] = $room;
$form['house'][$house_delta]['room'][$room_delta]['check'] = $check;
}
}
$form['house'][$house_delta]['room']['add'] = array(
'#type' => 'submit',
'#name' => 'add',
'#value' => t('Add room'),
'#attributes' => array('class' => array('field-add-more-submit'), 'house_delta' => array($house_delta)),
'#submit' => array(array(get_class($this), 'room_addMoreSubmit')),
'#ajax' => array(
'callback' => array($this, 'room_addMoreCallback'),
'wrapper' => 'room-replace-'.$house_delta,
'effect' => 'fade',
),
);
}
}
$form['house']['add'] = array(
'#type' => 'submit',
'#name' => 'add',
'#value' => t('Add house'),
'#attributes' => array('class' => array('field-add-more-submit')),
'#submit' => array(array(get_class($this), 'house_addMoreSubmit')),
'#ajax' => array(
'callback' => array($this, 'house_addMoreCallback'),
'wrapper' => 'house-replace',
'effect' => 'fade',
),
);
$form['submit'] = array(
'#type' => 'submit',
'#value' => t('Create'),
);
return $form;
}
public function room_addMoreSubmit(array $form, FormStateInterface $form_state) {
dd($form_state->getTriggeringElement(), "room : getTriggeringElement()"); // below, the log when I add a room to the house '1' (result see above with the last screenshot: "the house 1" became "house 2" and one click add 5 rooms)
$house = $form_state->getTriggeringElement()["#array_parents"][1];
$c = $form_state->get('room_count_'.$house) + 1;
$form_state->set('room_count_'.$house, $c);
$form_state->setRebuild(TRUE);
}
public function room_addMoreCallback(array $form, FormStateInterface $form_state) {
$house = $form_state->getTriggeringElement()["#array_parents"][1];
return $form['house'][$house]['room'];
}
public function house_addMoreSubmit(array $form, FormStateInterface $form_state) {
dd($form_state->getTriggeringElement()["#array_parents"], "house : getTriggeringElement()");
$c = $form_state->get('house_count') + 1;
$form_state->set('house_count', $c);
$form_state->setRebuild(TRUE);
}
public function house_addMoreCallback(array $form, FormStateInterface $form_state) {
return $form['house'];
}
}
The log ('dd' in the room_addMoreSubmit) when I click on the "add room" button in the house "1":
When I click on the "add room" button in the house number 1, getTriggeringElement return the array parents of the add button. And, as you can see, the parent is "2" not "1" (the house 1)
So when I click on the "add room" button of the house 1, this is the house "2" which is identified and not the house "1".
I don't understand why...Use the getTriggeringElement is not the good way ?
The solution :
$form['house'][$house_delta]['room']['add'] = array(
'#type' => 'submit',
'#name' => 'add-'.$house_delta,
'#value' => t('Add room'),
'#attributes' => array('class' => array('field-add-more-submit'), 'house_delta' => array($house_delta)),
'#submit' => array(array(get_class($this), 'room_addMoreSubmit')),
'#ajax' => array(
'callback' => array($this, 'room_addMoreCallback'),
'wrapper' => 'room-replace-'.$house_delta,
'effect' => 'fade',
),
);
The unique name was the issue of my problem. So, I change the name attribute.

Moodle 2.7 - Update core_renderer.php not applying changes - Custom menu

I am developing a custom theme based on bootstrap for moodle 2.7. I am adding a simple class to the custom menu function (render_custom_menu) on line 80. I simply addded the navbar-right class that is applied to the standard menu shown in both code blocks below.
Custom menu:
protected function render_custom_menu(custom_menu $menu) {
global $CFG, $USER;
// TODO: eliminate this duplicated logic, it belongs in core, not
// here. See MDL-39565.
$content = '<ul class="nav navbar-nav navbar-right">';
foreach ($menu->get_children() as $item) {
$content .= $this->render_custom_menu_item($item, 1);
}
return $content.'</ul>';
}
Standard Menu:
protected function render_user_menu(custom_menu $menu) {
global $CFG, $USER, $DB;
$addusermenu = true;
$addlangmenu = true;
$langs = get_string_manager()->get_list_of_translations();
if (count($langs) < 2
or empty($CFG->langmenu)
or ($this->page->course != SITEID and !empty($this->page->course->lang))) {
$addlangmenu = false;
}
if ($addlangmenu) {
$language = $menu->add(get_string('language'), new moodle_url('#'), get_string('language'), 10000);
foreach ($langs as $langtype => $langname) {
$language->add($langname, new moodle_url($this->page->url, array('lang' => $langtype)), $langname);
}
}
if ($addusermenu) {
if (isloggedin()) {
$usermenu = $menu->add(fullname($USER), new moodle_url('#'), fullname($USER), 10001);
$usermenu->add(
'<span class="glyphicon glyphicon-off"></span>' . get_string('logout'),
new moodle_url('/login/logout.php', array('sesskey' => sesskey(), 'alt' => 'logout')),
get_string('logout')
);
$usermenu->add(
'<span class="glyphicon glyphicon-user"></span>' . get_string('viewprofile'),
new moodle_url('/user/profile.php', array('id' => $USER->id)),
get_string('viewprofile')
);
$usermenu->add(
'<span class="glyphicon glyphicon-cog"></span>' . get_string('editmyprofile'),
new moodle_url('/user/edit.php', array('id' => $USER->id)),
get_string('editmyprofile')
);
} else {
$usermenu = $menu->add(get_string('login'), new moodle_url('/login/index.php'), get_string('login'), 10001);
}
}
$content = '<ul class="nav navbar-nav navbar-right">';
foreach ($menu->get_children() as $item) {
$content .= $this->render_custom_menu_item($item, 1);
}
return $content.'</ul>';
}
I'm not sure why this change is not taking effect. Anyone have experience with this and how to solve it. I'm sure I'm overlooking something very simple.
FYI: I have purged the moodle cache many times, reset the server and cleared the history in the browser.
Thanks!

Yii search method get don't work and don't compare with data in database

Hi yesterday i tried one way to create search by datetime, and you can see link: Search task on the next post.
Today I try one another way: When I succed i will put sollution back thank you.
This is my search file:
<?php Yii::app()->clientScript->registerCoreScript('jquery'); ?>
<?php
/* #var $this ApplicationController */
/* #var $model Application */
/* #var $form CActiveForm */
?>
<div class="wide form">
<?php $form=$this->beginWidget('CActiveForm', array(
'action'=>Yii::app()->createUrl($this->route),
'method'=>'get',
'enableAjaxValidation'=>false,
//$model->search(),
)); ?>
<div class="row">
<?php echo $form->label($model,'AUUsername'); ?>
<?php echo $form->textField($model,'AUUsername',array('size'=>45,'maxlength'=>45)); ?>
</div>
<div class="row">
<?php
//datepicker for date_from
echo CHtml::label("From date", 'datepicker');
$this->widget('zii.widgets.jui.CJuiDatePicker', array(
'name' => 'filters[date_from]',
//'value' => $filters['date_from'],
// additional javascript options for the date picker plugin
'options' => array(
'showButtonPanel' => true,
'showAnim' => 'slide', //'slide','fold','slideDown','fadeIn','blind','bounce','clip','drop'
'dateFormat'=>'yyyy-mm-dd hh:mm:ss',
),
'htmlOptions' => array(
'id'=>'date_from',
),
));?>
</div>
<div class="row">
<?php
//datepicker for date to
echo CHtml::label("To date", 'datepicker');
$this->widget('zii.widgets.jui.CJuiDatePicker', array(
'name' => 'filters[date_to]',
//'value' => $filters['date_to'],
// additional javascript options for the date picker plugin
'options' => array(
'showButtonPanel' => true,
'showAnim' => 'slide', //'slide','fold','slideDown','fadeIn','blind','bounce','clip','drop'
'dateFormat'=>'yyyy-mm-dd hh:mm:ss',
),
'htmlOptions' => array(
'id'=>'date_to',
),
));?>
</div>
<div class="row buttons">
<?php echo CHtml::submitButton('Search'); ?>
</div>
<?php $this->endWidget(); ?>
</div>
This is my model file:
<?php
class AppLog extends AltActiveRecord
{
private $_ActionName=null;
public $date_from;
public $date_to;
public function getDbConnection(){
return Yii::app()->connectionManager->getConnection(Yii::app()->user->getState('application'));
}
public function relations ()
{
return array (
'actions'=>array(self::HAS_ONE, 'Actions', array('ActionID'=>'ActionID')),
);
}
public function getActionName()
{
if ($this->_ActionName === null && $this->actions !== null)
{
$this->_ActionName = $this->actions->ActionName;
}
return $this->_ActionName;
}
public function setActionName($value)
{
$this->_ActionName = $value;
}
public function tableName()
{
return 'applog';
}
public function rules()
{
return array(
array('AppUserID','length', 'max'=>11),
array('AUUsername','length', 'max'=>45),
array('AUActionTime','type','type'=>'datetime','datetimeFormat'=>'yyyy-mm-dd hh:mm:ss'),
// The following rule is used by search().
// #todo Please remove those attributes that should not be searched.
array('AppUserID,AUUsername, date_from, date_to', 'safe', 'on'=>'search'),
);
}
public function attributeLabels()
{
return array(
'ActionID' => 'ID',
'AUUsername' => 'Naziv korisnika',
'AUActionTime' => 'Vrijeme akcije',
);
}
public function search()
{
$criteria=new CDbCriteria;
$criteria->compare('APUsername',$this->AUUsername,true);
$criteria->compare('AUActionTime',$this->AUActionTime,true);
$criteria->compare('date_from',$this->date_from,true);
$criteria->compare('date_to',$this->date_to,true);
return new CActiveDataProvider($this, array(
'criteria'=>$criteria,
));
}
public static function model($className=__CLASS__)
{
return parent::model($className);
}
}
?>
THIS IS MY CONTROLLER ACTION FOR SEARCH
public function actionLista()
{
$model = new Datalist;
$this->layout='column1';
//
if($_GET!=null)
{
$date_from = $_GET['filters']['date_from'];
$params[':date_from'] = date('yyyy-mm-dd hh:mm:ss', strtotime($_GET['filters']['date_from']));
$date_to = $_GET['filters']['date_to'];
$params[':date_to'] = date('yyyy-mm-dd hh:mm:ss', strtotime($_GET['filters']['date_to']));
if($date_from == '') $params[':date_from'] = date('yyyy-mm-dd hh:mm:ss', strtotime('2014-01-01 00:00:00'));
if($date_to == '') $params[':date_to'] = date('yyyy-mm-dd hh:mm:ss', strtotime('2999-01-01 00:00:00'));
//$condition = '(AUActionTime>:date_from OR AUActionTime<:date_to)';
//set filters
//$this->setFilters($_GET['filters']);
//die(CVarDumper::dump($params,10,true));
}
else {
$this->filters = array(
'date_from' => date('yyyy-mm-dd hh:mm:ss', strtotime('2014-01-01')),
'date_to' => date('yyyy-mm-dd hh:mm:ss', strtotime('today + 1 day')),
);
}
1) In your controller you should set the scenario as "search" like this
$model = new Datalist('search');
$model->unSetAttributes();
2) You need to assign the $_GET values to the model before view is rendered like this
// If your get vars are different then accordingly
if(isset($_GET['AppLog'])){
$model->attributes = $_GET['AppLog'];
....
$model->date_to = $date_to // After you retrieved and formatted from $_GET as above
$model->date_from = $date_from
Your controller action does not seem to rendering a view; i am assuming that you have omitted it here, but you are displaying the output in someway

Resources