I have two tables: product and product_type (related to the models resp. Product and Product_type):
product : product_id, product_type_id, name, etc...
product_type : product_type_id, name, desc, etc...
Both are related with key "product_type_id".
I have created the crud for both tables using gii crud generator. Now on Product form page I want to display the listing of all product_type name in dropdown field using Yii ActiveRecord. I have added this line in views/product/_form.php script:
<?php
$list = CHtml::listData(ProductType::model()->findAll(array('order' => 'product_type_name')), 'id', 'id');
echo $form->dropDownList($model, 'product_type_id', $list);
?>
But it's showing blank dropdown field :(
How can I do this?
Solved MySelf :)
By just providing product_type_name.
<?php
$list = CHtml::listData(ProductType::model()->findAll(array('order' => 'product_type_name')), 'product_type_id', 'product_type_name');
echo $form->dropDownList($model, 'product_type_id', $list);
?>
In Yii2 the class CHtml does not exist anymore.
Below is a solution, based on the following assumptions:
The Yii2 framework is used;
The table product_type is associated with the model Product_type;
The product_type table has a field called "type-name".
<?php
// get all product types from the corresponding table:
$productTypes = Product_type::find()->orderBy('type-name')->asArray()->all();
// create an array of pairs ('id', 'type-name'):
$productTypeList = ArrayHelper::map($productTypes, 'id', 'type-name');
// finally create the drop-down list:
$form->field($model, 'product_type_id')->dropDownList($productTypeList)
?>
Change your code like bellow
<?php
$list = CHtml::listData(ProductType::model()->findAll(array('order' => 'product_type_name')), 'table_col_name1', 'table_col_name2'); //table_col_name1 is value of option, table_col_name2 is label of option
// echo $form->dropDownList($model, 'product_type_id', $list);
echo CHtml::dropDownList('name_of_the_dropdown', $model, $list);
?>
Related
I'm developing a dropdown list that gets the values and his related from the same table.
AssetType
asset_type_id
name
order
parent_asset_type (related to AssetType.asset_type_id) - the top type as value = NULL
<?= $form->field($model, 'asset_type_id')->dropDownList(
ArrayHelper::map(AssetType::find()->where("parent_asset_type IS NOT NULL")->all(), 'asset_type_id', 'name', 'parent_asset_type'),
['prompt'=>'Choose a Category']);?>
And with this Yii2 arrayHelper i can save 3 values, the id of the asset which is not null, his name and the parent_asset_type (Which shows the ID)
Basically:
DropDownList
Choose a Category
1
T-Shirts
Jeans
2
Computers
Cellphones
Instead of the group Id i would love to know how can i make it show the name of that Asset Type.
I hope this will help you...
I have created a function in the model modelname.php
public function getAssetType(){
return $this->name .'-'.$this->parent_asset_type;
}
view.php
<?php
$asset = ArrayHelper::map(AssetType::find()->all(),'id','AssetType');
echo $form->field($model, 'asset_type_id')->dropDownList($asset,
['prompt'=>'Choose a Category']);
?>
Thank You...
I want to load only main categories(not sub-categories) name in drop down list. i have tried enough but could not succeed. There are numbers of answer on this site and I tried to solve my problem in that way but can't. The category table is given below, it is same as on cakephp docs in Tree.
categories table attribute
id | parent_id | lft| rght |name |
i tried these techniques given on following links
How to populate drop-down list with database values in CakePHP
full code of controller to create category is given below.
if ($this->request->is('post')) {
$this->Category->create();
if ($this->Category->save($this->request->data)) {
$this->Session->setFlash(__('Category has been saved.'));
return $this->redirect(array('action' => 'index'));
}
$this->Session->setFlash(__('Unable to add Category.'));
}
else
$categories = $this->Category->find('list');
$this->set(compact('categories'));
return $this;
}
code of category.ctp is
<?php echo $this->Form->create('Category'); ?>
<fieldset>
<legend><?php echo __('Add Category'); ?>
</legend>
<?php
$form->input('id');
// echo $this->Form->input('id');
echo $this->Form->input('name');
?>
</fieldset>
<?php echo $this->Form->end(__('Submit')); ?>
</div>
now please suggest me solution to load data in drop down list.
Stick to the conventions and everything's going to be ok. I assume you need the list in your add form to select the parent category (your intent btw is something that you should clarify in your question).
With trees you want to order by lft, so if you use find('list') you'll have to pass that in the order option, and in order to retrieve only the top-level categories you'll have to pass in a condition that matches all categories where parent_id is null (or the ID of a parent category whichs sub-categories are your "main" categories).
Controller
$parents = $this->Category->find('list', array(
'conditions' => array(
'Category.parent_id' => null
),
'order' => array(
'Category.lft' => 'asc'
)
));
$this->set('parents', $parents);
View
echo $this->Form->input('parent_id');
For more information see
http://book.cakephp.org/2.0/en/core-libraries/behaviors/tree.html
http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#creating-form-elements
you can put in controller
$this->loadModel('Category');
$categories = $this->Category->find('list');
$this->set('categories',$categories));
put code of category.ctp is
<?php if(isset($categories )){
foreach ($categories as $key => $value) {
$id= $value['Category']['id'];
$options[$id]=$value['Category']['name'];
}
}
echo $this->Form->select('Category.id', $options,array('class'=>'select2','data- placeholder'=>'Choose a category','empty'=>''));
?>
It will work.
I have a Product model with a 'categories' column. This column should be able to contain data from a Checkboxlist.
Whenever a user creates a new Product I want the form to display the 'categories' Checkbox, with the items set as active from the user's last created Product.
So for instance: the 'categories' Checkboxlist contains items 'Movies' and 'Music'. When the user checks 'Movies' and creates the Product, the next time the user goes to create a Product, 'Movies' is already selected (because it saves the selection from the user's previous product creation).
I believe these are the most effective steps to code in order to achieve this goal:
When Product is created: checked items are saved to 'categories' column in Product Model & a 'categories' column in the User's 'Profile' model
User's last saved categories ('categories' column in Profile model) should be retrieved at the Product's Create form.
Code in Product model's _form view:
<?php echo $form->checkBoxList($model, 'categories', array('movies'=>'Movies','music'=>'Music')); ?>
(I'm unsure as to where to set an array for active values)
I'll need to convert the Array of the selected Checkboxes to a string using explode(",", $model->categories) so I can put it inside the 'categories' columns of the 'Product' and 'Profile' models by using the ProductController's actionCreate function.
Then to set the user's last selected Checkboxlist items as active in the Product _form view I need to convert the $model->categories data back to an array by imploding the column ie implode(",", $user->profile->categories).
How would you code this in Yii?
Use CHtml::ckeckboxList instead of activecheckbox.
It have selected parameter. Selected there is array of key=>value pairs. yiiframework.com/doc/api/1.1/CHtml#checkBoxList-detail
Or you can rewrite (extend) you CHtml helper to resolve your format.
For example:
public static function activeCheckBoxList($model,$attribute,$data,$htmlOptions=array())
{
self::resolveNameID($model,$attribute,$htmlOptions);
if(array_key_exists('explode_format',$htmlOptions))
{
$selection=explode($model->$attribute);
unset($htmlOptions['explode_format']);
}
else{
$selection=self::resolveValue($model,$attribute);
}
if($model->hasErrors($attribute))
self::addErrorCss($htmlOptions);
$name=$htmlOptions['name'];
unset($htmlOptions['name']);
if(array_key_exists('uncheckValue',$htmlOptions))
{
$uncheck=$htmlOptions['uncheckValue'];
unset($htmlOptions['uncheckValue']);
}
else
$uncheck='';
$hiddenOptions=isset($htmlOptions['id']) ? array('id'=>self::ID_PREFIX.$htmlOptions['id']) : array('id'=>false);
$hidden=$uncheck!==null ? self::hiddenField($name,$uncheck,$hiddenOptions) : '';
return $hidden . self::checkBoxList($name,$selection,$data,$htmlOptions);
}
Then just add 'explode_format'=>true to your htmloptions for activecheckboxlist. Something like this will work.
I have table types and i want to build selectbox with all values from this table
In my controller i wrote this code
$allRegistrationTypes = RegistrationType::model()->findAll();
$this->render('index', array('allRegistrationTypes' => $allRegistrationTypes))
How build selectbox in view file ?
Well then its pretty simple all you need to do is first create List Data like
CHtml::ListData(allRegistrationTypes,'value you want to pass when item is selected','value you have to display');
for ex
typeList = CHtml::ListData(allRegistrationTypes,'id','type');
now remember both id and type are fields in table
now all you have to do is if you are using form then
<?php echo $form->dropDownList($model, 'type_id', $typeList, array('empty'=>'Select a tyoe')); ?>
and if you need multiple you can pass multiple => multiple in the array as htmlOptions
You would use CHtml::dropDownList, or activeDropDownList if there is a "parent" model and you want to leverage its validation rules.
If you want to make the <select> element multiple-selection-capable, pass in 'multiple' => 'multiple' and 'size' => X as part of the $htmlOptions parameter.
Simplest Method to get "Select Box" in YII Framework:
<div class="row">
<?php
echo $form->labelEx($model,'county');
$data = CHtml::listData(County::model()->findAll(), 'id', 'county');
$htmlOptions = array('size' => '1', 'prompt'=>'-- select county --', );
echo $form->listBox($model,'county', $data, $htmlOptions);
echo $form->error($model,'county');
?>
</div>
Good Luck..
I have Tarifs, each tarif hasMany Price and Price also belongsTo UserGroup. So basically prices change when user's group is changed - doesn't matter that much.
The view looks like this
<?php echo $this->Form->create('Tarif');?>
...
$i=0;
foreach ($this->data['Price'] as $price) {
echo "<tr><td>".$this->Form->input("Price.$i.price", array('label' => false))."</td>";
echo "<td>".$this->Form->input("Price.$i.currency", array('label' => false))."</td>";
echo "<td>".$this->Form->input("Price.$i.UserGroup.id", array('label' => false))."</td>";
...
And I need the UserGroup.id input to display as a select, where each option displays group name and has its id as value. The user_group_id values are fine, but the are displayed in a text input. I've tried $this->Form->select and $this->Form->input(...,'type'=>'select') but both of them provided select boxes with no options.
How do I set the input to do what I want?
Thanks
In your controller, you need to add:
$user_groups = $this->UserGroup->find('list');
$this->set(compact('user_groups');
Then in the view, you setup the drop down like:
<?php echo $this->Form->input('user_group', array('options' => $user_groups)); ?>
You can then add $user_groups as an option to any Form->input and it will become a dropdown when using:
array('options' => $user_groups)