How to pass variable from actionCreate to _form.php? - yii

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
]) ?>

Related

cakephp fat model still undefined variable in the view action

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'));

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

View another attribute of related table - yii

I want to display country name instead of country id in user profile view( country id is FK in user profile tbl) .
anyone can help me with this ?
This is my view controller/action in which I have Country model as well:
public function actionView($id)
{
$model = new TblUserProfile;
$model = TblUserProfile::model()->find('user_id=:user_id', array(':user_id' => $id));
$countrymodel = new Country;
$countrymodel = Country::model()->findAll();
// var_dump($countrymodel->name);
// die();
$this->render('view', array(
'model' => $model ,
'country' =>$countrymodel
));
}
This is my view
<div class="view">
<b><?php echo CHtml::encode($data->getAttributeLabel('id')); ?>:</b>
<?php echo CHtml::link(CHtml::encode($data->id), array('view', 'id'=>$data->id)); ?>
<br />
<b><?php echo CHtml::encode($data->getAttributeLabel('user_id')); ?>:</b>
<?php echo CHtml::encode($data->user_id); ?>
<br />
<b><?php echo CHtml::encode($data->getAttributeLabel('user_occuption')); ?>:</b>
<?php echo CHtml::encode($data->user_occuption); ?>
<br />
<b><?php
// $model = TblUserProfile::model()->find('country_id=:country_id', array(':user_id' => $id));
//echo CHtml::encode($model->getAttributeLabel('country')); ?>:</b>
<?php// echo CHtml::encode($model->name);
?>
<br />
</div>
Now I want to display country name in above view.
These are the relationships of country and user profile table
public function relations() {
// NOTE: you may need to adjust the relation name and the related
// class name for the relations automatically generated below.
return array(
'user' => array(self::BELONGS_TO, 'TblUser', 'user_id'),
'country' => array(self::BELONGS_TO, 'country', 'country_id'),
'state' => array(self::BELONGS_TO, 'state', 'state_id'),
'city' => array(self::BELONGS_TO, 'city', 'city_id')
);
}
Use the following code:
<b><?php echo CHtml::encode($data->country->getAttributeLabel('name')); ?>:</b>
<?php echo CHtml::encode($data->country->name); ?>
<br />
Provided that in your country model, the country name column is name.
Since the relation is in place we can use it to access the related country for each user.
In detailview it'll change to:
// instead of 'country_id'
array(
'name'=>'country_id',
'value'=>$model->country->name
)
Read the CDetailView doc to see how you can change even more things.
I would use:
$model = TblUserProfile::model()->with('country')->find('user_id=:user_id', array(':user_id' => $id));
with('country') explained: the string country comes from the array relations key.
Then to display in the view you would use:
$model->country->CountryName;
$model contains
country contains a "model" of country joined by the relation foreign key
CountryName is the column name in the Country table
This is the recommended way to do it in the MVC way. Both my example and the one above work, but the one above has more process/logic decisions in the view, which breaks the concept of MVC where the Model should be the fat one and contain all logic/processing possible, then controller will pull this data and provide it to the view.
You can also follow this below answer:
Just put the below code in your view.php file
[
"attribute"=>"User_Country_Id",
'value' =>$model->country->conName ,
],
[
"attribute"=>"User_State_Id",
'value' =>$model->states->stsName ,
],
[
"attribute"=>"User_City_Id",
'value' =>$model->cities->ctName ,
],

Yii - Modifing html generated by CListView

I'm using ClistView to display the content of a dataprovider.
ClistView is supposed to call a partial view, that will loop for each model.
I would like to display something (i.e. a tag) before the first model and something (i.e. a ) after the last model of the pagination.
Assume that I have a view (index.php):
$this->widget('zii.widgets.CListView', array(
'dataProvider'=>$localDataProvider,
'itemView'=>'_view', // refers to the partial view named '_post'
'summaryText'=>'Sono visualizzati i record da {start} a {end} su un totale di {count} libri',
'pager' => Array(
'header' => 'Vai alla pagina',
'prevPageLabel' => 'Indietro',
'nextPageLabel' => 'Avanti',
),
));
In _view.php I have just the cells of a table.
If I put before the widget the html to render the table header and just after the html to render the table footer I obtain that inside the div there is the html of the pager.
How I can shift the header and the footer directly in _view.php?
Thanks
With this class extension:
Yii::import('zii.widgets.CListView');
class PlainCListView extends CListView
{
public $preItemsTag = '';
public $postItemsTag = '';
public function renderItems()
{
echo $this->preItemsTag."\n";
$data=$this->dataProvider->getData();
if(($n=count($data))>0)
{
$owner=$this->getOwner();
$render=$owner instanceof CController ? 'renderPartial' : 'render';
$j=0;
foreach($data as $i=>$item)
{
$data=$this->viewData;
$data['index']=$i;
$data['data']=$item;
$data['widget']=$this;
$owner->$render($this->itemView,$data);
if($j++ < $n-1)
echo $this->separator;
}
}
else
$this->renderEmptyText();
echo $this->postItemsTag."\n";
}
}
I's possible to override the lines of the base version of the class
echo CHtml::openTag($this->itemsTagName,array('class'=>$this->itemsCssClass))."\n";
echo CHtml::closeTag($this->itemsTagName);
With this solution with code:
$pre_html = '<table><thead><th>Codice Account</th><th>Nome</th></thead><tbody>';
$post_html = '</tbody></table>';
$this->widget('zii.widgets.PlainCListView', array(
'dataProvider'=>$dataProvider,
'itemView'=>'_view',
'preItemsTag'=>$pre_html,
'postItemsTag'=>$post_html,
'summaryText'=>'Sono visualizzati i record da {start} a {end} su un totale di {count} libri',
'pager' => Array(
'header' => 'Vai alla pagina',
'prevPageLabel' => 'Indietro',
'nextPageLabel' => 'Avanti',
),
'sortableAttributes'=>array('titolo'),
'enableSorting'=>0,
));
It's possible to get in the output what I need.
Since you are trying to generate a table, you should be trying to do it using CGridView instead of CListView.
Try setting the template for the CClistView as
'template' => "<your header tag>{items}<your footer tag>{pager}",
you might arrange the template stuff as you need.

How to add span to a label using $form->labelEx from Yii?

I wish to generate the following markup:
<label>some label here <span>(optional)</span></label>
Is there a way to do this, by using Yii labelEx or just label?
Thanks
If the attribute is required
You can set the CHtml static properties like this
CHtml::$beforeRequiredLabel = '';
CHtml::$afterRequiredLabel = '<span>(optional)</span>';
Yii will generate a tag
<label>CHtml::$beforeRequiredLabel.$label.CHtml::$afterRequiredLabel</label>
but the static properties will effect all labels generated by $form->labelEx() (#see CHtml::activeLabelEx())
if you don't need, you must set the static properties to default
If the attribute is not required
you can set the htmlOptions
$form->labelEx($model, $attribute, array('label' => 'your label'))
It's simple, make use of the Decorator pattern:
<?php
// components/CustomCHtml.php
class CustomCHtml extends CHtml
{
public static function activeLabelEx($model,$attribute,$htmlOptions=array())
{
if (isset($htmlOptions['optional']) && $htmlOptions['optional']) {
if (isset($htmlOptions['label']) && $htmlOptions['label']) {
$htmlOptions['label'] .= $htmlOptions['optional'];
} else {
$htmlOptions['label'] = $htmlOptions['optional'];
}
}
return parent::activeLabelEx($model,$attribute,$htmlOptions);
}
}
use case:
<?php echo CustomCHtml::activeLabelEx($model, 'field', array('optional'=>' <span>(optional)</span>')); ?>
Here is a little hack to make it possible.
<?php
$username = $form->field($model, 'username')
->input('text', ['class' => 'form-control input-lg'])
->label(true, 'username', ['class' => 'fa fa-user signin-form-icon']);
$username->parts['{label}'] = '<span class="fa fa-user signin-form-icon">dwe</span>';
echo $username;
?>
You could use CHtml::$afterRequiredLabel and/or CHtml::$beforeRequiredLabel
$initValue = CHtml::$afterRequiredLabel;
CHtml::$afterRequiredLabel = $initValue.'<span>(optional)</span>';
echo $form->labelEx($model, $fname, array('class' => ''));
echo $form->textField($model, $fname, array('class' => ''));
CHtml::$afterRequiredLabel = $initValue;
This way the label will be applied only on the specified form field. You actually set the initial value of CHtml::$afterRequiredLabel and/or CHtml::$beforeRequiredLabel on a temp variable, you overwrite the value that you need, and then reset it to original value.