Yii - Widgets - Explanation - yii

I am trying to use drop down list widget :
$this->widget('ext.multiselect.JMultiSelect',array(
'model'=>$model,
'attribute'=>'attribute',
'data'=>$data,
// additional javascript options for the MultiSelect plugin
'options'=>array()
));
What I want to know is that Details of each option available in the widget array Like what is 'attribute' , 'model' and'data' represent , as I an unable to understand it form the documentation.

The model param is the model you are creating the multi select for.
The attribute is the model attribute you are creating the multi select for.
The data is an array of key/value pairs for the list items you want to display in the multi select.
For example, if you had a model 'User' and in that model you had a field 'access_rights' and you wanted to have that field as a multi select box with a few values, you might do something like:
In your controller:
$model = new User;
$data = array(
'admin_area'=>'Admin Area Access',
'product_area'=>'Product Area Access',
'customer_area'=>'Customer Area Access',
... etc
);
In your form in your view file:
$this->widget('ext.multiselect.JMultiSelect',array(
'model'=>$model,
'attribute'=>'access_rights',
'data'=>$data,
// additional javascript options for the MultiSelect plugin
'options'=>array()
));
Edit:
To add data to the multi select options from another model you can use the CHtml::listData() method, this takes an active record result set and converts it into an array of key/value pairs so you can use in any of the other CHtml methods that require a key/value pair. To do this you simply get the records you're after from the database using active record, eg;
$myData = Data::model->findAll();
You can then put that into the listData() method and it'll create your array:
$this->widget('ext.multiselect.JMultiSelect',array(
'model'=>$model,
'attribute'=>'access_rights',
'data'=>CHtml::listData($myData, 'id', 'name'),
// additional javascript options for the MultiSelect plugin
'options'=>array()
));
(where 'id' and 'name' are the fields from the model table that you want to be the 'key' and 'value' within the array)

echo $form->dropDownList($model, 'category', CHtml::listData(TblCategory::model()->findAll(),
'id', 'category_name'), array('empty' => '---Select Category---',
'style' => 'width:350px;')), array() ?>
<?php echo $form->error($model, 'category'); ?>

Related

yii2 name field attribute using variable

I'm trying to create in an activeform a series of controls using a loop for not being to declare the various fields of the model in order to have a generic template to which I pass only the name of the table and it creates the edit form.
So that if I pass the table A and it has 3 fields it creates three fields, the b has 5 fields it creates 5 fields etc etc.
$tfields= Array ( [0] => id [1] => brand_id [2] => group_id)
and i create this code
foreach($tfields as $key => $value) {
if (strlen($value)>0){
echo $form->field($model, $value)->textInput();
}
}
but when i run the code i get this error
Calling unknown method: yii\data\ActiveDataProvider::isAttributeRequired()
any ideas?
tks a lot!
the problem was tha i use an ActiveDataProvider as model, using instead and DynamicModel
in the controller
$model2= new \yii\base\DynamicModel([
]);
in the form
foreach(explode(',',$fields) as $item){
if (strlen($item)<>0){ //to avoid empty
echo $form->field($model2, $item)->textInput();
}
}

My cgridview is showing only one record in yii

i am newbii in yii development and have an issue while displaying data using cgridview as it is showing only first record
Motel,Hotel,Roomcategory and halls are models in which PK and FK are passing ...
Code is here
$sponsorm = Motel::model()->find('MotelId=:MotelId', array(':MotelId'=>Yii::app()->user->id));
$sponsorhotel = Hotel::model()->find('hotelId=:hotelId', array(':hotelId'=>$sponsorm->MotelId));
$room = Roomcategory::model()->find('hotelId=:hotelId', array(':hotelId'=>$sponsorhotel->hotelId));
$halls = Halls::model()->find('hotelId=:hotelId', array(':hotelId'=>$sponsorhotel->hotelId));
echo CHtml::image(Yii::app()->request->baseUrl.'/img/4.png');
$this->widget('zii.widgets.grid.CGridView', array(
'id'=>'businessowner-grid',
'dataProvider'=>$room->search(),
//'filter'=>$sponsore,
'columns'=>array(
'roomCategoryNames',
'noOfRooms',
'price',
),
));
$this->widget('zii.widgets.grid.CGridView', array(
'id'=>'businessowner-grid',
'dataProvider'=>$halls->search(),
//'filter'=>$sponsore,
'columns'=>array(
'Type',
//'noOfHalls',
'seats',
'price',
),
));
Right now you are finding only one record because you use find to get one specific record. So you assign this record data to model variables and then you do
$model->search();
This searches from specific table multiple values but you have set the attributes so, that it matches only one record.
To get Motel gridview data use following code:
$sponsorm = $dataProvider=new CActiveDataProvider('Motel', array(
'criteria'=>array(
'condition'=>'MotelId = :MotelId',
'params' => array(':MotelId'=>Yii::app()->user->id)
),
));
It is doing the same as search() but the difference is that searching criteria is different. You can use also code below.
$motelModel = new Model();
$motelModel->MotelId = Yii::app()->user->id;
Now there is only one attribute assigned an is setting a criteria to match all rows what has this user id in MotelId field.
$modelModel->search();
Also, I see that you echo something between logic. Please do not do that. Output data only in views and keep the logic out of views. :)

how to handle an array as a field in CGridView

I'm using CGridView but one of the field is an array ['xx' ,'yy' , 'zz',...]
How can I display that i searched for an answer but did not find
is it possible to use something like DropDownlist to display the values in the array
I have a static array special_offer in a model;
It will filter by the value; This is a drop down list example;
I replaced a field within the cgridview with a array as follows:
array(
'name' => 'special_offer',
'value' => 'Package::$special_offer[$data->special_offer]',
'filter' => Package::$special_offer,
),
In order to use dropDownList in a CGridView column, your array needs to be associative. I recommend that you create a method in your model which converts it into an associative array, something like:
public function getAssociativeArray()
{
$array = array('xx', 'yy', 'zz'); // or use an attribute value
return array_combine(array_values($array), $array);
}
Then in your CGridView, add this as a column, replacing the model/field names with your own:
array(
'name' => 'yourFieldName',
'type' => 'raw',
'value' => 'CHtml::activeDropDownList($data, "yourFieldName", YourModel::model()->associativeArray)',
),

multiple checkbox valiadation for any one in YII frame work for this example

Hi can you please tell how can i validate the multiple checkbox any one is checked in yii framework
array('accept', 'required', 'requiredValue' => 1, 'message' => 'You should select alteast one')
As these value are usually sent as arrays, I wrote an array validator for these cases once: https://github.com/schmunk42/p3extensions/blob/master/validators/P3ArrayValidator.php
Usage example:
array('accept',
'ext.validators.P3ArrayValidator',
'min'=>1,
'allowEmpty'=>false,
'message' => 'You should select at least one'
),
sorry for the late reply.
But, I found a solution without installing any extension.
Take a hidden field with the same name [Checkboxes list field].
<?php echo $form->hiddenField($model,'categories');?>
Display a list of categories with name different from our field name (multiple checkboxes).
But, remember the 'class', and play with the class to save the values.
<?php
echo CHtml::checkBoxList(
'group',
//you can pass the array here which you want to be pre checked
explode(',', trim($model->attributes['categories'], ',')),
CHtml::listData(Category::model()->findAll(),'id','name'),
array('separator'=>'', 'template'=>'<tr><td style="width:5%;">{input}</td><td>{label}</td></tr>', 'class' => 'group')
);
?>
This way validation should work also, you get category ids as comma separated e.g. [,1,2,6,]
<script>
$(function(){
$(".group").click(function(){
var str = $('.group:checked').map(function() {
return this.value;
}).get().join();
var groupCats = (str.length > 0) ? ','+str+',' : '';
$('#ModelNAME_field').val(groupCats);
// Get the 'ModelNAME_field' by viewing source of HTML of hidden field.
});
});
</script>

how to add static elements to yii dropDownList?

echo $form->dropDownList(
$model,'categoryId',
CHtml::listData(Category::model()->findAllBySql(
'SELECT * from category where isnull(parent_id)'),
'id', 'name'),
array(
'empty'=>Yii::t('fim','Search All'),
Yii::t('fim','Jobs'),
Yii::t('fim','Training'),
Yii::t('fim','Events'),
Yii::t('fim','News')
)
);
Jobs, Training, Events and News are not appearing.
How can/should we build this, in order to add those values to the select box ?
Thanks
You cannot add static elements by using the $htmlOptions parameter. Here is how I do it:
$data = CHtml::listData(Category::model()->findAllBySql(
'SELECT * from category where isnull(parent_id)'),
'id', 'name');
// Add extra options here: I am actually prepending with this syntax,
// but you are free to append or interleave instead. Array keys are the values.
$static = array(
'jobs' => Yii::t('fim','Jobs'),
'training' => Yii::t('fim','Training'),
'events' => Yii::t('fim','Events'),
'news' => Yii::t('fim','News'),
);
echo $form->dropDownList(
$model,
'categoryId',
$static + $data,
array('empty'=>Yii::t('fim','Search All')));
For me, what i did is i added jquery code, i append an html option
$("#categoryId").append("<option value='0'>Additional Field</option>");
its less complicated and it works for me