Yii active dropdownlist with optgroup - php

I try to create dropdown-list with Yii, using listData and activeDropDownList.
I use the examples found on the web, but it refuses to create the optgroups for me.
$data = CHtml::listData(MyModel::model()->getEntries(0), 'id', 'text', 'group');
Generates an array as expected:
Array([group1] => Array([10]=>FirstEntry, [20]=>SecondEntry),
[group2]=>Array([30]=>firstEntryGroup2, [40]=>firstEntryGroup2))
And so on. So it's an associative array filled with sub-arrays...
But when I use
echo CHtml::activeDropDownList($model, 'dropdownName', $data);
All I get is a flat dropdown without the optgroups. Just the entries from the sub-arrays...
Yii 1.1.6 (I read something about safe-attributes and tried to implement it, but with no success...

The old answer below is incorrect. Sorry. You create optgroups using a 'group' attribute in your drop down data array.
array(
array('id'=>256,'text'=>'TV','group'=>'Electrical'),
array('id'=>257,'text'=>'Radio','group'=>'Electrical'),
);
http://www.yiiframework.com/forum/index.php/topic/6903-how-can-i-generate-a-select-list-with-optgroup/
Old answer:
There is a great gist here that shows how do create what you're after: https://gist.github.com/StandardNerd/2909111
<?php echo CHtml::dropDownList('Cars', 'car_id', array(
'Mazda'=>array(
'mazda-rx7'=>'RX7',
'mazda-rx5'=>'RX5',
),
'Volvo'=>array(
'volvo-b9tl'=>'B9TL',
'volvo-l90e-radlader'=>'L90E Radlader',
),
)); ?>
You're currently using an activeDropDownList which should only be different because you add your $model variable instead of 'Cars' and tweak the function

One of solutions is anonymous function.
$data = CHtml::listData(
MyModel::model()->getEntries(0),
'id',
'text',
function(MyModel $aMyModelInstance){
return $aMyModelInstance->getLocalizedGroupNameForThisInstance();
});

Related

is it possible to display content from cgridview to dropdown in yii?

I have modified my model so that the data displayed in cgridview is unique per user, depending on the account type...
However I need to create a form from another model where I could get the data from the cgridview via dropdown...
I used this code at first...
<?php
$this->widget('ext.select2.ESelect2',array(
'model'=>$model,
'attribute'=>'pr_id',
'data'=>$model->searchPatient(),//function to provide data
// or
//'data'=>CHtml::listData(PatientRecord::model()->findAll(), 'id', 'first_name')
);
?>
but it returns all of the contents of the PatientRecord model, I tried using a condition before planning to retrieve the contents from the cgridview...
$doctor= Yii::app()->user->id;
CHtml::listData(PatientRecord::model()->findAll( array(
'condition'=>'doctor_id=:doctor_id',
'params' => array(':doctor_id' => $doctor)
)
);), 'id', 'first_name')
it didn't have an error but it didn't display anything on the dropdown either...
any suggestions?
I think the problem is with a ; and ) in your model code, try this:
$doctor= Yii::app()->user->id;
CHtml::listData(PatientRecord::model()->findAll( array(
'condition'=>'doctor_id=:doctor_id',
'params' => array(':doctor_id' => $doctor)
)
), 'id', 'first_name');
You should always enable error logging in local environment, this will help you find any errors in your code. Here is a link on how to enable error logging.
Hope that helps :)

Yii CArrayDataProvider Keyfield As Button Id In CGridView

My issue is two-fold. First, I'm unable to correctly set the keyField for CArrayDataProvider, all I'm getting back is a string instead of a value. Second, I'm trying to use the keyField inside of CArrayDataProvider to set an id on the button in each row inside of CGridView. The reason I want to do this is so that I can pass the id value onward to an ajax function (if there's a better way to do this in Yii, I'm all ears). Any help would be much appreciated, thanks in advance!
I also posted this question once on Yii's forums. I normally wouldn't repost, but I have had a hard time getting answers there, as opposed to stack overflow, you guys are the best! Here's the link to my original post if anyone is interested.
Here is how I'm building the array that I'm using as my RAW data:
foreach ($items as $item) {
$tableRow = array("id"=>$item["Id"], "Organization"=>$item["Organization"], "Roles"=>$item["Roles"]);
$return_items[] = $tableRow;
}
Here is the CArrayDataProvider setup I'm using. I noticed that 'keyField' is not being given the id value, just the string 'id':
$dataProvider=new CArrayDataProvider($return_items, array(
'keyField'=>'id',
'sort'=>array(
'attributes'=>array(
'Organization',
'Roles',
),
),
'pagination'=>array(
'pageSize'=>10,
),
));
Lastly, here is the CGridView I'm trying to setup in the view. All that appears on the button is the id tag, but no value:
$this->widget('zii.widgets.grid.CGridView', array(
'dataProvider'=>$authItems,
'columns'=>array(
'Organization',
'Roles',
array('name'=>'',
'type'=>'raw',
'htmlOptions'=>array('id'=>'id'),
'value'=>'CHtml::button("Edit Roles", array("data-toggle"=>"modal", "data-target"=>"#roles-modal"))'),
),
));
Try passing it via CHtml::button which you have already applied. E.g.
'value'=>'CHtml::button("Edit Roles", array(
"id"=>$data["id"],
"data-toggle"=>"modal",
"data-target"=>"#roles-modal"
))'),

How to filter the rows of a gridview in yii using radio buttons

I used the below code to create two radio buttons(approved messages and rejected messages) in Yii framework
<?php echo CHtml::activeRadioButtonList($model, 'Approved', array('Approved Messages', 'Rejected Messages'), array('labelOptions'=>array('style'=>'display:inline'),'separator'=>'')) ?>
Now I have to filter and display all the rows in CGridView of the table where column 'approved' has value=1 when I click on "approved messages" radio button and all the rows in CGridView of the table where column 'Approved' has value=0 when I click on "rejected messages" radio button. How can I do this
I used a drop down for this, the values are Yes and No. Just translate the approved column into text using the following code:
array(
'name' => 'approved',
'value' => '($data->approved ? "Yes" : "No")',
'filter' = >CHtml::dropDownList('Approved', '',
array(
' '=>'All',
'1'=>'On',
'0'=>'Off',
)
),
)
This link is where I got this info: http://www.yiiframework.com/forum/index.php/topic/30694-cgridview-filter-dropdown-from-array/
I googled using cgridview filter example
Alright, lets put in the radio buttons instead of all the dropdowns haha.
I assume you have your view set up something like this:
// view/index.php (or similar)
$this->widget('zii.widgets.grid.CGridView', array(
'dataProvider'=>$model->search(),
'filter'=>Message::model(),
'columns'=>
[
'id',
'username',
'email:email',
'approved'=>[
'name'=>'approved',
'filter'=>$this->approvedFilter(),
// I like moving stuff like this out of the way.
// But maybe it's smarter to put it in your model instead?
]
]
));
Next for the controller.
// MessageController.php (or similar)
public function actionIndex()
{
$model = Message::model();
// All we need to do is to assign the incoming value to the model we are using...
if ( isset( $_GET['Message']['Approved'] )){
$model->approved = $_GET['Message']['Approved'];
}
$this->render('index', ['model'=>$model]);
}
// Oh yeah the filter. I just copied your code.
public function approvedFilter(){
return CHtml::activeRadioButtonList(
Message::model(), 'approved', array(0,1),
array(
'labelOptions'=>array('style'=>'display:inline'),
'separator'=>''
)
);
}
This code has been tested, but I made some last minute changes, so sorry if it blows up!
And I still think a simple 'approved:boolean' is much cleaner. ;)

Need help to create CRUD screen with dropdown (relation) using yii-framework

I need to create CRUD screen using yii-framework. Simple CRUD screen using one table is working perfectly fine. I'm facing problem/issue while using dropdown (linking table).
I have installed giix extension which is suppose to create CRUD with dropdown if FK is specified but I dnt have MySql Engine InnoDB on my hosting provider, so I'm not able to use that extension. I need to do it manually.
I have two tables
main:-
id
store_id
prefix
store:-
id
name
Now store_id of main is FK to id of store table. And I want to create CRUD for main table.
So that Add Screen should show:-
Store Name:- Dropdown
prefix:- Textbox
View screen should use name column of store table instead of showing store_id
Thanks in anticipation.
Generate CRUD using Gii, then read my blog. http://jmmurphy.blogspot.com/2013/05/using-yii-model-relations.html
Basically you will have something like this for your store_id field after Gii Generation
<?php echo $form->labelEx($model,'store_id'); ?>
<?php echo $form->textField($model, 'store_id', array('size'=>60,'maxlength'=>255));?>
<?php echo $form->error($model,'store_id'); ?>
The textField line is replaced by:
<?php $list = CHtml::listData(Store::model()->findAll(), 'id', 'name'); ?>
<?php echo $form->dropDownList($model, 'store_id', $list, array('empty'=>'(Select a Store)')); ?>
You also need to define relations in your Main model so that you can access related tables (even if your database does not support foreign keys) like this:
public function relations()
{
return array(
'store'=>array(self::BELONGS_TO, 'Store', 'store_id'),
);
}
And to complete this relation, you should also add the following relation to your Store model:
public function relations()
{
return array(
'main'=>array(self::HAS_MANY, 'Main', 'store_id'),
);
}
These relations define a One to Many relation between Store and Main where store is the parent, and Main is the Child. To make it a One to One relationship change HAS_MANY to HAS_ONE. The HAS_* goes in the parent model and points to the foreign key attribute in the child table. The BELONGS_TO goes in the child and tells the attribute in the child table that points to the primary key in the parent.
Now to see the store name in the view action, you need to change 'store_id' in your view.php to an array that looks like:
array(
'name' => 'store_id',
'value' => $model->store->name,
)
The admin view is slightly different. I am not sure exactly why, but to view the store name instead of the id in the admin view you will need to use an array that looks like:
array(
'name' => 'store_id',
'value' => '$data->store->name',
)
Note that Gii generates this so that $data is the model instead of $model, and also it does a funky double indirection thing so that you need to put the variable declaration in single quotes.
Thanks jmarkmurphy for your help. You helped me lot and I have marked your answer as correct only as you gave me guidance. Just posting exact code in detail.
I changed view.php with below code:-
<?php $this->widget('zii.widgets.CDetailView', array(
'data'=>$model,
'attributes'=>array(
'id',
'store.name',
'prefix',
),
));
Also changed admin.php with below code:-
<?php echo CHtml::encode($data->store->name); ?>
<?php $this->widget('zii.widgets.grid.CGridView', array(
'id'=>'main-grid',
'dataProvider'=>$model->search(),
'filter'=>$model,
'columns'=>array(
'id',
'store.name',
'prefix',
array(
'class'=>'CButtonColumn',
),
),
)); ?>
Thanks once again jmarkmurphy. Thanks a lot . My application is now working and exactly the way I wanted.

How do I set the 'value' in my Zend form checkbox?

The Zend Form is proving to be a bit tricky for me, even as much as I am working with it lately...
I have this form and I am attempting to dynamically create the several checkboxes for it. It is working out alright, except I cannot seem to get the 'value' attribute to change.
In my Zend form class I have this snippet...
// psychotic symptoms
$this->addElement('checkbox', 'psychoticsymptom', array(
'label' => 'psychoticsymptom',
'name' => 'psychoticsymptom',
));
In my view (phtml) I am calling it like this...
<div class="element">
<?php // Psychotic Symptoms
$Criteria = new Criteria();
$Criteria->add( DictionaryPeer::CATEGORY, 'MAR: Psychotic Symptoms' );
$Criteria->addAscendingOrderByColumn( 'Ordinal' );
$this->PsychoticSymptomsList = DictionaryPeer::doSelect( $Criteria );
foreach( $this->PsychoticSymptomsList as $Symptom ) {
$form->psychoticsymptom->setValue($Symptom->getDictionaryId());
$form->psychoticsymptom->setAttrib('name', $Symptom->getWord());
echo $Symptom->getDictionaryId(); // prove my id is coming through... (it is)
$form->psychoticsymptom->getDecorator('label')->setTag(null);
echo $form->psychoticsymptom->renderViewHelper();
$form->psychoticsymptom->setLabel($Symptom->getWord());
echo $form->psychoticsymptom->renderLabel();
echo '<br />';
}
?>
</div>
Everything seems to be working fine, except the value attribute on each checkbox is rendering a value of '1'. I have tried moving the 'setValue' line to several different positions, as to set the value before the form element renders but I am having no luck getting this to work. It's worth any effort to me because I need to do the same type of operation in many areas of my application. I would have done this a bit different too, but I am re-factoring another application and am trying to keep some things unchanged (like the database for instance).
Any help is much appriciated
Thanks
you can try to overwrite the "checkedValue" and "uncheckedValue". check this reference
$this->addElement('checkbox', 'psychoticsymptom', array(
'label' => 'psychoticsymptom',
'name' => 'psychoticsymptom',
'checkedValue' => 'checked Value',
'uncheckedValue' => 'unchecked Value'
));
You seem to only have one psychoticsymptom element "checkbox" which your adding (changing) the value too for each $this->PsychoticSymptomsList.
Maybe you would be better off using a multicheckbox element instead.

Categories