Yii and Dropdown in a form - drop-down-menu

I am new to Yii framework.
I have a form with three fields. I need one of those be a select drop down element that its data comes from previously added data which are in mysql table.
How can I do it ?

If you have a model set up for the table that contains the data you want to use in your dropdown list you can use the CHtml::dropDownList() method the render a dropdown list, and CHtml::listData() to render that model into items for the list, for example;
echo CHtml::dropDownList(
'attribute_name',
'',
CHtml::listData(MyOtherModel::model()->findAll(),'id','name')
);
I use Gii a lot, which uses CActiveForm widget to display forms, if your form uses CActiveForm too you could render your dropdown something like;
$form=$this->beginWidget('CActiveForm', array(
'action'=>Yii::app()->createUrl($this->route),
'method'=>'get',
));
...
echo $form->label($model,'attribute_name');
echo $form->dropDownList(
$model,
'attribute_name',
CHtml::listData(MyOtherModel::model()->findAll(),'id','name')
);
...
$this->endWidget();
Note that CActiveForm uses CHtml::activeDropDownList() rather than CHtml::dropDownList() that I used in my first example, hence the slight difference in syntax between my two examples.

Related

Symfony2, dynamically refresh form choices

I am creating a simple Blog system with symfony2. Each blog Post is bound to a certain amount of Tags.
Tags can be selected with checkboxes when creating a new blog post. Now I want to be able to dynamically add new tag-checkboxes to the form.
The AJAX part is done and working, I can add new tag names to the Tag entity and append the new checkboxes to the form.
The problem is when I submit the form, symfony2 doesn't recognize the new added tags because they don't belong to the Tag entity yet (at the time the form was generated).
For example: after submitting the form, I dump:
$tags = $form->get('tags')->getData();
The controller ignores the tags that were added through ajax.
I know it has to be solved with events somehow, I already read this documentation: http://symfony.com/doc/current/cookbook/form/dynamic_form_modification.html but can't figure out how to implement it for this specific case.
Here is my form builder for "PostType":
$builder
->add('title')
->add('content', 'textarea')
->add('tags', 'entity', array(
'class' => 'Bundle:Tag',
'property' => 'name',
'multiple' => true,
'expanded' => true,
))
->add('save', 'submit')
;
You can try to use this: Form Collection
Make sure you persist the newly added Tags before submit the form, and the checkboxes has the right names and values.
Names should be like "post[tags][]" and values should be the database ids of the Tag entities.

Dropdown in Yii cGrid - 2 variables

I have $model1, $model2 and OwnerID populated in my controller and it renders the data in my zii.widgets.grid.CGridView Problem comes in when I want to send $model2 to the view as well like so:
$this->render('listView', array('model1'=>$model, 'model2' => $model2, 'OwnerID' => 14));
and in the view I have:
$this->widget('zii.widgets.grid.CGridView', array(
'id'=>'listKeys',
'dataProvider'=>$model1->search($OwnerID),
'summaryText'=>'Showing {start} to {end} of {count} keys.',
'columns'=>array(
array('value'=>'$data["id"]', 'header'=>'Key ID'),
array(
'type'=>'raw',
'header'=>'Edit',
'value'=>'CHtml::dropDownList("partyList","owner_party_id", $model2)'
),
),
));
I get "Undefined variable: model2" There is data in $model2, if I comment out the dropDown in the grid and have the dropdown list outside the grid like so:
<?php echo CHtml::dropDownList("partyList","owner_party_id", $model2) ?>
then everything works fine. How can I add the dropDownList in CGridView? $model1 is a list of file and $model2 is a list of users.
$model2 needs to be a string or a variable recognized by CGridView.
To get a string representation of the array use var_export()
...
'value'=>'CHtml::dropDownList("partyList","owner_party_id",'.var_export($model2).')',
...
To make $model2 a CGridView variable you'd need to extend CGridView as explained in this Yii wiki page

How do I repopulate fields BEFORE validation is passed?

The fields I am making required to fill out, should repopulate the correctly filled out fields, while NOT submitting the form and posing errors for the incorrectly filled out fields. What is the best way to do that?
Please note that with this code, I am repopulating the fields as they should be upon submitting the form correctly and they are all displaying when page is reloaded.
<div class="dropdown_structure">
<?php
if($user['location'] == "empty")
{
echo country_dropdown('location');
}
else
{
echo country_dropdown('location',$user['location']);
}
?>
</div>
Also please note that I've tried inserting the value in the input fields.
$data = array( 'name' => 'location', 'value' => $this->input->post('location'));
echo relation_dropdown('location');
Thanks in advance
Hi if you are using the following country dropdown helper you can set value validation in following way
Country dropdown helper
country_dropdown('location',array(),set_value('location'))
even in your second dropdown use set_value('field_name') will work. if validation is failed your selected value will be remain.

Magento - Can't delete mulitple select value in the product admin

I created a new attribute (multiple select) with some values, everything works fine but when I want to delete all the selected values for a product, I get the message "The product attribute has been saved." but the values are still selected.
Notes:
I press Ctrl + Click to unselect the last value before I save.
I set the parameter Value Required of my attribute to No
If I save a product without any value selected yet, then no values get selected
My Indexes are properly refreshed
See below two screens, on the left the parameters of my attribute and on the right my multiple select.
I'm running out of ideas so thanks for your help.
This is a known (annoying) behaviour of the Magento Adminhtml forms.
The problem is that if no value is selected for the multiselect, no value for that attribute is posted when the form is submitted.
On the server side Magento then loads the model, sets all the posted attribute values on the model and saves it.
Because no value was posted the original value that was loaded on the model wasn't updated.
As a solution for attributes with a custom source model I tend to provide an empty option with a special option value (e.g. -1). That value must not be 0 or an empty string.
Then I specify a backend model for that attribute that checks for that special value in the _beforeSave() method. If it is found the backend model unsets the attribute on the model instance.
Here is an example:
Source Model:
class Your_Module_Model_Entity_Attribute_Source_Example
extends Mage_Eav_Model_Entity_Attribute_Source_Abstract
{
const EMPTY = '-1';
public function getAllOptions()
$options = array(
array('value' => 1, 'label' => 'One'),
array('value' => 2, 'label' => 'Two'),
array('value' => 3, 'label' => 'Three')
);
if ($this->getAttribute()->getFrontendInput() === 'multiselect')
{
array_unshift($options, array('value' => self::EMPTY, 'label' => ''));
}
return $options;
}
}
Backend Model:
class Your_Module_Model_Entity_Attribute_Backend_Example
extends Mage_Eav_Model_Entity_Attribute_Backend_Abstract
{
public function beforeSave($object)
{
$code = $this->getAttribute()->getAttributeCode();
$value = $object->getData($code);
if ($value == Your_Module_Model_Entity_Attribute_Source_Example::EMPTY)
{
$object->unsetData($code);
}
return parent::beforeSave($object);
}
}
If you find a better workaround please let me know.
There is a feature called <can_be_empty> you need to go to your system.xml and add this configuration into your file:
<can_be_empty>1</can_be_empty>
then inspect the element and remove the selected="selected" and hit save, now you can save the multi-select without any values.
Yes I found this a big pain in the bum too BUT it is an improvement on the previous bug which caused drop down attribute selections to be wiped if you tried to update attributes for several products at once.
Anyway, here is my what I do if I want to remove an option from products using a drop down attribute:
Go to Manage attributes
Click Manage Label Options
Add a temporary option to the list
Assign this new attribute option to all the products you want to
change
Delete the temporary attribute option
All solved.
Add a non existent option to html via chrome/firefox developer tool, select that option and save.
eg.
<option value="99999999">Click this to unselect option</option>
Just ran into this problem in Magento 1.7.0.2, my solution :
Use Firefox with Firebug
right-click the multiselect list, choose Inspect with Element and you'll see something like this at the bottom in Firebug :
XLarge
Double-click on selected, right-click, cut, no more selected attribute and just save the page.

Yii Displaying Image dynamically dependent on dropdown

I'm trying to display an image but is dependent on a dropdown list in Yii. I can get the image from the database and display it, but how to do it dynamically depending on the choice from the dropdown?
Here is the reference: http://www.yiiframework.com/wiki/24/creating-a-dependent-dropdown#hh0 but, let me show you how to do it.
First all all, we need a div where the image will be displayed; I'll create one whose id will be 'img'. Then, the ajax request is specified inside the dropdownlist() as follows:
<?php echo $form->labelEx($model,'attribue'); ?>
<?php echo $form->dropDownList($model,'attribute',
array(/*The options in the DropDownList*/),
array(
'ajax'=>array(
'type'=>'POST',
'url'=>CController::createUrl('YourController/actionWhichEchoesTheImage'),
'update'=>'#img',
)));
?>
<div id="img"> // <---- the result of the ajax call will be displayed here
</div>
In the 'url' attribute we specify the function which will be called when the ajax request triggers. In the 'update' attribute we specified the div where will be displayed the result of calling that function (the image).
Finally, we have to declare the action actionWhichEchoesTheImage(). Let's declare it in the current controller. It would look something like this:
public function actionWhichEchoesTheImage()
{
if(isset($_POST['ModelName']['attribute']))
/*Here goes your code to load the image*/
echo CHtml::image(//Check the reference to see how to set this function);
}
Check CHtml::image() here: http://www.yiiframework.com/doc/api/1.1/CHtml/#image-detail

Resources