cakephp fat model still undefined variable in the view action - variables

I have created a method in my model that successfully displays the correct data when I pr($variable) to the screen. However without the print I am receiving the 'Notice (8): Undefined variable' message.
The model in question 'industry' has many 'news and events'.
What I'm trying to do in the view for a specific industry is display news that is of two different conditions. One type of news is news.type = highlight(displaying just one highlight story), and the second is a list of active stories.
This is the method in my model.
// industry highlight news
public function getHighlightNews() {
$newsHeadline = $this->News->find('first', array(
'conditions' => array('News.type' => 'highlight','News.active' => 'yes'),
'limit' => 1,
'recursive' => 0,
'fields' => array(
'News.slug',
'News.title',
'News.date',
'News.imgPathThumb',
'News.alt_tag',
'News.id',
'News.caption',
'News.body'
),
));
return $newsHeadline;
}
public function getNewsList() {
$newslist = $this->News->find('all', array(
'conditions' => array('News.active = "Yes"','News.industry_id = 1'),
'limit' => 4,
'recursive' => 0,
'fields' => array(
'News.slug',
'News.title',
'News.date',
'News.industry_id',
'News.imgPathThumb',
'News.alt_tag',
'News.id',
'News.caption',
'News.body'
),
));
return $newslist;
}
And this is what is in my industry controller. I've created similar model methods for the news list and event lists.
public function view($id = null) {
$this->layout='default';
$this->Industry->id = $id;
if (!$this->Industry->exists()) {
throw new NotFoundException(__('Invalid industry'));
}
$eventlist = $this->Industry->getEventsList($id);
$newslist = $this->Industry->getNewsList($id);
$highlights = $this->Industry->getHighlightNews($id);
//pr($newslist); die;
$this->set('eventlist', $eventlist, 'newslist', $newslist, 'highlights', $highlights);
}
And this is my view:
<div class="first articles">
<?php foreach ($highlights as $highlight): ?>
<h1><?php echo $highlight['Industry']['title']; ?></h1>
<p><?php echo $highlight['Industry']['body']; ?>
<?php endforeach; ?>
</p>
</div><!-- /articles -->
the message I get in the view is:
Notice (8): Undefined variable: highlights [APP\View\Industries\view.ctp, line 12]
Warning (2): Invalid argument supplied for foreach() [APP\View\Industries\view.ctp, line 12]
I suspect it's something small I'm overlooking.
Thanks, Paul

Setting variables doesn't work like that. You need to change this:
$this->set('eventlist', $eventlist, 'newslist', $newslist, 'highlights', $highlights);
To this:
$this->set('eventlist', $eventlist);
$this->set('newslist', $newslist);
$this->set('highlights', $highlights);
Or this:
$this->set(compact('eventlist','newslist','highlights'));

Related

Yii framework: how to get id from DB, when choosing related record from DB

I have text edit box with Autocomplete::widget on the web page.
Autocomplete populates from DB. When I start to type and choose Autocomplete item (which is the First Name from DB, in my case) I need to get the associated id from DB. How could this get implemented?
<?php
use yii\helpers\ArrayHelper;
use yii\helpers\Html;
use yii\widgets\ActiveForm;
use app\models\Rating;
use app\models\Teacher;
use yii\jui\AutoComplete;
use yii\web\JsExpression;
/* #var $this yii\web\View */
/* #var $model app\models\Rating */
/* #var $form ActiveForm */
$data = Teacher::find()
->select(['lname as value', 'lname as label','id as id'])
->asArray()
->all();
//print_r($data[0].id);//exit;
?>
<div class="rating-input">
ФИО
<?php
echo AutoComplete::widget([
'name' => 'Teacher',
'id' =>'ddd',
'clientOptions' => [
'source' => $data,
'autoFill'=>true,
'minLength'=>'1',
],
]);
https://paste.ee/p/BtQav
try this
<input type="hidden" name="teacher_id" id="teacher_id" value="">
<?php
echo AutoComplete::widget([
'name' => 'Teacher',
'id' =>'ddd',
'clientOptions' => [
'source' => $data,
'autoFill'=>true,
'minLength'=>'1',
'select' => new \yii\web\JsExpression("function( event, ui ) {
// $('#teacher_id').val(ui.item.id);//#teacher_id is the id of hiddenInput.
console.log(ui.item.id);
}")
],
]);
You have more information in documentation page : http://www.yiiframework.com/wiki/830/simple-jui-autocomplete-in-yii2/

How to pass variable from actionCreate to _form.php?

I have a create action of controller where I passed $ingredients array into the view
public function actionCreate()
{
return $this->render('create',
['model' => $model, 'ingredients' => Ingredient::find()->all()]
);
}
In create.php I can acess $ingredients variable.
But if I try to access $ingredients in the _form.php
<?= $form->field($model, 'ingredient_id')->checkbox(
ArrayHelper::map($ingredients, 'id', 'name')
) ?>
I get error
Undefined variable: ingredients
This can be done by two ways
//first render the view file like this
$params = [];
$params['eqpType'] = $eqpType;
$params['discountModel'] = $discountModel;
$params['tabActive'] = $tabActive;
$params['discountLabel'] = $discountLabel;
echo $this->render('_form', $params);
//or you can include the code file directly ..in this case do not need to pass all perameters
<?php include_once "_form.php";?>
Your are passing the variables to the create view, and your widget is in another view called _form. Go to the create view and make sure that all variables are passed to the _form view.
in create.php
<?php echo $this->render('_form', [
'model' => $model,
'ingredients' => $ingredients
]) ?>

how to integrate multimodelform with echmultiselect yii?

I am running into a little snag with combining extensions "EchMultiSelect" and "MultiModelForm" of YII framework.
What I'm trying to do is copy a set of form elements one of which elements is an EchMultiSelect widget.
According to tutorial on the jqRelCopy page, I would need to pass a copy of the element (datePicker in their example) to the 'jsAfterNewId' option:
'jsAfterNewId' => JQRelcopy::afterNewIdDatePicker($datePickerConfig),
So, I tried to modify that to:
'jsAfterNewId' => MultiModelForm::afterNewIdMultiSelect($memberFormConfig['elements']),
Where I also added the following to MultiModelForm.php:
public static function afterNewIdMultiSelect($element)
{
$options = isset($element['options']) ? $element['options'] : array();
$jsOptions = CJavaScript::encode($options);
return "if(this.attr('multiple')=='multiple'){this.multiselect(jQuery.extend({$jsOptions}));};";
}
its copied and working properly when i am using Add Person link but what happens if i am adding/cloning three items for example and when i change the third item multiselct option then its reflecting to the first multiselect dropdown only this is same for other as well also when i am adding new items by clicking on the Add Person link then its cloning the same element to the new row item
here is the code for the form configuration variables and multimodel widget call.
//$userList=array of the userIds from users table
$memberFormConfig = array(
'elements'=>array(
'userId'=>array(
'type'=>'ext.EchMultiSelect.EchMultiSelect',
'model' => $User,
'dropDownAttribute' => 'userId',
'data' => $userList,
'dropDownHtmlOptions'=> array(
'style'=>'width:500px;',
),
),
...
...
));
calling the MultiModelForm widget from the same view file
$this->widget('ext.multimodelform.MultiModelForm',array(
'id' => 'id_member', //the unique widget id
'formConfig' => $memberFormConfig, //the form configuration array
'model' => $model, //instance of the form model
'tableView' => true,
'validatedItems' => $validatedMembers,
'data' => Person::model()->findAll('userId=:userId', array(':userId'=>$model->id)),
'addItemText' => 'Add Person',
'showAddItemOnError' => false, //not allow add items when in validation error mode (default = true)
'fieldsetWrapper' => array('tag' => 'div',
'htmlOptions' => array('class' => 'view','style'=>'position:relative;background:#EFEFEF;')
),
'removeLinkWrapper' => array('tag' => 'div',
'htmlOptions' => array('style'=>'position:absolute; top:1em; right:1em;')
),
'jsAfterNewId' => MultiModelForm::afterNewIdMultiSelect($memberFormConfig['elements']),
));
Can someone help me with this please?
Thanks in advance!
After a long searching and googleing i found the solution for this, just replace the function in your MultiModelForm.php:
public static function afterNewIdMultiSelect($element)
{
$options = isset($element['options']) ? $element['options'] : array();
$jsOptions = CJavaScript::encode($options);
return "if ( this.hasClass('test123456') )
{
var mmfComboBoxParent = this.parent();
// cloning autocomplete and select elements (without data and events)
var mmfComboBoxClone = this.clone();
var mmfComboSelectClone = this.prev().clone();
// removing old combobox
mmfComboBoxParent.empty();
// addind new cloden elements ()
mmfComboBoxParent.append(mmfComboSelectClone);
mmfComboBoxParent.append(mmfComboBoxClone);
// re-init autocomplete with default options
mmfComboBoxClone.multiselect(jQuery.extend({$jsOptions}));
}";
}
Thats It....!!
Thanks...!!!

"Object of class Accounts could not be converted to string" in Yii dropDownList

similarly I have 2 tables in database,accounts and banks,and One to Many Relation between them.
'banks' => array(self::BELONGS_TO, 'Banks', 'banks_id'), in Accounts model.
I need to use Chtml::dropDownList in account creation form,so I edit _form.php to it:
<div class="row">
<?php echo $form->labelEx($model,'banks_id'); ?>
<?php echo CHtml::dropDownList($model, 'banks_id', CHtml::listData(Banks::getBanksList(), 'id', 'title','country')); ?>
<?php echo $form->error($model,'banks_id'); ?>
</div>
and also in Banks model develop `getBanksList by:
public static function getBanksList()
{
$userLanguage = Yii::app()->user->getState('lang');
$result = array();
$banks = self::model()->findAll();
foreach ($banks as $bank){
array_push($result, array(
'id' => $bank->id,
'title' => ($userLanguage == $bank->default_lang)?$bank->default_name:$bank->en_name,
'country' => Yii::t('countries',$bank->country),
));
}
return $result;
}
but it raise Object of class Accounts could not be converted to string error ,and in trace it occured at
public static function getIdByName($name)
{
return str_replace(array('[]', '][', '[', ']', ' '), array('', '_', '_', '', '_'), $name);
}
in Chtml.php file.where is the problem?I searched a lot,but I couldn't solve the problem.
I understood where is my problem,I should use $form instead of Chtml.

ZF2 form element description

in ZF1 form and form elements had a setDescription method that was outputted as <p>description here</p> in view ....
ZF2 seems that doesn't have this method
so my question is how can i add description to form elements ?
this is my view :
<div>
<?
$form = $this->form;
$form->prepare();
echo $this->form()->openTag($form);
foreach ($form->getElements() as $el) {
?>
<div class="form_element">
<?=$this->formRow($el);?>
</div>
<?
}
echo $this->partial('system/form/buttons_form_part.phtml', array('form' => $form));
echo $this->form()->closeTag();
?>
</div>
Using ZF 2.1.5, one solution might be setOptions().
In the form definiton:
$file = new Element\File('file');
$file->setLabel('Photo (.jpg, .gif, .png)');
$file->setOptions(array('description' => 'test description'));
…
When rendering the form element:
$element = $form->get(…);
var_dump($element->getOptions());
Will give you access to:
array(1) { ["description"]=> string(16) "test description" }
If you mean a label for an Element you can use the setLabel method when you create the form (in Controller).
$name = new Element('name');
$name->setLabel('Your name');
Or if you use an array to create your form elements use this:
array(
'spec' => array(
'name' => 'name',
'options' => array(
'label' => 'Your name',
),
'attributes' => array(
'type' => 'text'
),
)
),
Here is a link:
enter link description here