how to use Chtml::DropDownList() - php

i'm currently a newbie when it comes to the yii framework / php. I would like some assistance creating this Chtml::DropDownList.
http://www.yiiframework.com/doc/api/1.1/CHtml#dropDownList-detail
Chtml::dropDownList($name, $select, $data)
I understand that $data is the array of data I will be loading in from my Database.
But can someone explain to me how $name, and $select truly works. I have a hard time finding documentation that explains this at a extremely dumbdown level.
I manage to get this piece of code working, but I would prefer using Chtml::dropdownlist.
<div class="row">
<?php
echo $form->dropDownList($model, 'id',
Chtml::listData(UsersTeam::model()->findAllByAttributes(array('coachId'=>$model->id)), 'id', 'teamName'),
array('empty'=>'Select Team'))
?>
</div>
I would like to be able to display all teamName for the current user that he is enlisted in.
I'm currently displaying this in the model view of a User, but the information I need is from UserTeam which holds the teams for the users.
'memberOfTeams' => array(self::MANY_MANY, 'UsersTeam', '{{teamMembers}}(userId, teamId)'),
'coachOfTeams' => array(self::HAS_MANY, 'UsersTeam', 'coachId'),

$name is the name="mySelect" form value it will have (the one that will be passed if sent as a form i.e. $_POST['mySelect']).
$select is the preselected ID. Say you have an array...
$options = array('12' => 'Twelve', '10' => 'Ten');
And your dropdown looks like this...
echo CHtml::dropDownList('mySelect', '12', $options);
Then 'Twelve' will be the preselected item in the dropdown and $_POST['mySelect'] will be the value passed when the form is sent.
You can add additional html options to each <option> tag, using the fourth parameter CHtml::dropDownList accepts, like so:
$htmlOptions = array(
// adds to the select element
'style' => 'cursor: pointer;',
// adds to the actual options
'options' => array(
'12' => array('title' => '12')
)
);
And updating the call to:
echo CHtml::dropDownList('mySelect', '12', $options, $htmlOptions);
The finished list would look like this:
<select name="mySelect" style="cursor: pointer;">
<option value="12" selected="selected" title="12">Twelve</option>
<option value="10">Ten</option>
</select>

You can easily do the same with CHtml::activeDropDownList.
So your code will look like:
<div class="row">
<?php
echo CHtml::activeDropDownList($model, 'id',
Chtml::listData(UsersTeam::model()->findAllByAttributes(array('coachId'=>$model->id)), 'id', 'teamName'),
array('empty'=>'Select Team'))
?>
</div>

Related

Clone form select box with option .CakePHP

Usually, I always used CakePHP form helper to list down select box with options.
I would like to know,if I can create it manually(I mean without CakePHP form helper) ?
Example:
Using cakephp form helper to create select box
<?php echo $this->Form->input('product_name',array('options'=>$myoptions));?>
But I want to do something like below
<select name="data[Product][product_name]" id="product">
<options value="1">One</options>
<options value="2">Two</options>
<options value="3">Three</options>
</select>
Any ideas?
Thanks
CakePHP 2.5.7
--EDIT--
I want to clone multiple select box that will follow CakePHP form structure.
Okay the problem start here.
By default I'd use CakePHP form helper to draw the select box and their options.
I wrote this kind of code:
<?php echo $this->Form->input('Redemption.0.type_id',array('class'=>'form-control','id'=>'selectProduct','label'=>false,'empty'=>'Choose Type','options'=>$types));?>
It will return in HTML structure like below:
<select name="data[Redemption][0][type_id]" class="form-control" id="selectProduct">
<option value="">Choose Type</option>
<option value="1">Toner</option>
<option value="2">Ink Catridge</option>
</select>
I want to clone the existing select box above to new select box but with different name value like this:
<select name="data[Redemption][1][type_id]" class="form-control" id="selectProduct">
<option value="">Choose Type</option>
<option value="1">Toner</option>
<option value="2">Ink Catridge</option>
</select>
Notice that integer value on name="data[Redemption][1][type_id]" has increased.That is what I wanted.
But now,I've no idea to do cloning with data changing as stated.
I have try several jquery method such as .clone() .append() but it's not work as the options data inside the select box become redundant.
Can you please enlighten me how to duplicate/clone select box in CakePHP?
Thanks.
CakePHP 2.5.7
<?php
echo $this->Form->input( 'product_name', array(
'type' => 'select',
'options' => array(
'key1' => 'val1',
'key2' => 'val2',
),
'empty' => true,
));
?>
You can add other conditional values to your select options just by adding values to the variable array like this:
$myOptions = array(
'1' => 'One',
'2' => 'Two',
'3' => 'Three'
);
// If user make some action
if($someAjaxAction == true) {
$myOptions[4] = 'Four';
}
echo $this->Form->input('product_name', array('options' => $myOptions));

Yii: Show value to textfield from database on page laod

I have a textfield in yii, and want to insert data from database upon that page load. How can I achieve this?
I am able to successfully echo that database value, but not knowing how to insert it.
Lets say the textfield name is 'text', and stored value from db is 'val'.
$this->text = $val //I tried this way
Try like this normal way
CHtml::fileField('name' , 'value', array('id' => 'MuID','class'=>'MyClass'));
If you sending the model data to the View, you can use CActiveForm (check the basic CRUD operations in YII, Generate from GII)
Example: i have fetched user data which has id 0001 and i sent the model to the view
My View
<?php
$form = $this->beginWidget('CActiveForm', array(
'id' => 'my-form',
'enableAjaxValidation' => true,
'enableClientValidation' => true,
'clientOptions' => array(
'hideErrorMessage' => true,
'validateOnSubmit' => true,
)
));
?>
//It will show user name in textbox
<?php echo $form->fileField($model, 'user_name'); ?>
<?php $this->endWidget(); ?>
The db value is probably in a model right? You can use activeTextField to display database values in a textfield
Take a look at:
http://www.yiiframework.com/doc/api/1.1/CHtml#activeTextField-detail
It will probably look like this:
<?php
// simple textfield which will display the value
echo CHtml::activeTextField($yourmodel, 'field_that_contains_value');
// or if you're using a form:
echo $form->textField($yourmodel, 'field_that_contains_value');
// or if the value isn't in a model
echo CHtml::textField('name_of_field', $value);
?>
<input type="text" name="input_name" value="<?=$val?>"/>
Using CHtml helper:
echo CHtml::textField('name',$val);
Using ActiveForm
echo $form->activeTextField($model, 'attribute', array('value'=>$val));

Show title or span in select box (Cakephp 1.3)?

Problem
Show lengthy options on mouse hover in select box with a fixed width.
Names are hidden here:
Rendered HTML in browser
<select id="prim" size="5" multiple="multiple" scroabble="1" name="prim[]">
<option value="Applied Research Associates Inc.">Applied Research Associates Inc.</option>
</select>
Required Output
Show span or title as below
Expected HTML
<select id="prim" size="5" multiple="multiple" scroabble="1" name="prim[]">
<option value="Applied Research Associates Inc." title="Applied Research Associates Inc.">Applied Research Associates Inc.</option>
</select>
My CakePHP Code
echo $form->input('prim',
array('options'=>$refined_list,
'type'=>'select',
'scrollable'=>true,
'multiple'=>true,
'name'=>'prim',
'label'=>false,
'size'=>'5'));
What attribute should I add to make desired changes?
EDIT/UPDATE: One way might be to update my $refined_list array with title field as suggested by #ammu. I must wait for a better solution.
There is no such way to add attribute to select option in cakephp documentation.Have a look at this, it might help you for adding attributes to select option.
http://www.dereuromark.de/2012/03/01/some-new-crazy-cakephp-tricks/
Well use it like this and you'll get what you want:
$options = array(
...
array('name' => 'United states', 'value' => 'USA', 'title' => 'the title that you want'),
array('name' => 'USA', 'value' => 'USA', 'title' => 'the other title that you want'),
);
echo $this->Form->input('test', array('type'=>'select', 'options'=>$options));
you can also add any attribute that you want in the form of array for each option (class, placeholder, etc).

Yii: On validation error: Need to preserve the selected country and city

I'm working on signup form and I have 2 steps to user register in some website, so step 1 is a create action and step 2 is update action on profile controller.
so my problem is how can preserve the selected country and city on validation error but it's already ?! check the image
view:
<div class="row">
<?php echo $form->labelEx($model,'countryId'); ?>
<?php echo $form->dropDownList($model, 'countryId',
CHtml::listData(SysCountry::model()->findAll(), 'id', 'name'),
array(
'empty'=>'Select country',
'ajax' => array(
'type'=>'POST', //request type
'url'=>CController::createUrl('profile/dynamiccity'), //url to call.
//Style: CController::createUrl('currentController/methodToCall')
'update'=>'#Profile_cityId', //selector to update
//'data'=>'js:javascript statement'
//leave out the data key to pass all form values through
)));
?>
<?php echo $form->error($model,'countryId'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'cityId'); ?>
<?php echo $form->dropDownList($model, 'cityId', array('empty'=>'Please select country first')
); ?>
<?php echo $form->error($model,'cityId'); ?>
</div>
Check this, to update the second drop down you need to use
'update'=>'#'.CHtml::activeId($model,'tracanton'),
echo CActiveForm::dropDownList
(
$model,'traprovincia',
CHtml::listData
(
CatUbicacionGeografica::model()->findAll('cat_ubigeo_nivel=? ORDER BY cat_ubigeo_descripcion', array('2') ),
'cat_ubigeo_codigo', 'cat_ubigeo_descripcion'
),
array(
'ajax'=>array(
'type' => 'POST',
'url' => CController::createUrl('tramite/updatecanton'),
'data'=>array('padre'=>'js:this.value'),
'update'=>'#'.CHtml::activeId($model,'tracanton'),
),
'prompt' => '( Seleccione Provincia )',
'style' => "width: 300px;",
// 'onchange'=>'js:$("#tracanton").focus()',
)
);
Is it javascript or PHP validation? If its the former use JS to take the values of the dropdown boxes and then repopulate (ikll post some code if its this). If its PHP then do the following on your drop downs
<select>
//-- If 'save' has been entered and validation has been caught
if (isset($_POST/GET['country'])) {
echo '<option value=". $_POST/GET['country'] . '" selected="selected">' . $_POST/GET['country'] . '</option>';
} else {
//-- if validation hasnt been actioned
}
</select>
Whilst this may not work for your code i hope you get the idea. If you can post your validation code ill be able to amend properly so it works for you.

Select or Dropdown list from CActiveRecord in Yii

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..

Categories