Yii. Dependent Dropdown - php

I try make dependent select.
My Model
Region
id
region
City
id
city
region_id
Customer
id
region
city
address
phone
In my views(Customer form):
<div class="row">
<?php
echo $form->dropDownList($model,'region',CHtml::listData(Region::model()->findAll(), 'id', 'region'),
array(
'prompt'=>'Select Region',
'ajax' => array(
'type' => 'POST', //My method type
'url' => CController::createUrl('myController/LoadRegions'), //This is my request/ajax URL
array('id'=>'js:this.value'), //I'm passing the selected dropdonw value.
'dataType' => 'JSON',
'success'=>'js:function(data)' //The functionaliy after success
. '{'
. ' var html="";'
. ' $.each(data,function(i,obj)'
. ' {'
. ' html+="<option value=obj.City_id>"+obj.City_city+"</option>"'
. ' });'
. ' $("#User_City_id").html(html);' //ID of regions dropdown list
. '}'
)));
echo CHtml::dropDownList($model,'City_id', array(), array('prompt'=>'Select City'));
?>
And in my controller(Customer):
public function actionLoadRegions()
{
$Region_id=$_POST['region'];
$criteria=new CDbCriteria();
$criteria->select=array('Region_id, Region_region');
$criteria->condition='Region_id='.$Region_id;
$criteria->order='Region_region';
$RegionAry= Region::model()->findAll($criteria);
$ary=array();
foreach($RegionAry as $i=>$obj)
{
$ary[$i]['Region_id']=$obj->Region_id;
$ary[$i]['Region_region']=$obj->Region_region;
}
echo json_encode($ary);
}
But code is not work. Error Object of class Customer could not be converted to string. Why?

This will work
Your Form
'success' => 'js:function(data) {
$("#User_City_id").html(data);
}'
Your Controller function
public function actionLoadRegions()
{
$Region_id=$_POST['region'];
$criteria=new CDbCriteria();
$criteria->select=array('Region_id, Region_region');
$criteria->condition='Region_id='.$Region_id;
$criteria->order='Region_region';
$RegionAry= Region::model()->findAll($criteria);
$ary=array();
foreach($RegionAry as $i=>$obj)
{
$ary[$i]['Region_id']=$obj->Region_id;
$ary[$i]['Region_region']=$obj->Region_region;
}
echo CHtml::dropDownList('dropdown_name', $selected, $ary);
}

I am not familier with Yii but I think you are treating a integer variable as a string so that its showing error .
You sure about this-
echo CHtml::dropDownList($model,'City_id', array(), array('prompt'=>'Select City'));
try instead
echo CHtml::dropDownList($model,City_id, array(), array('prompt'=>'Select City'));

use something like this:
echo $form->dropDownList(
$model,
'state_id',
$array,
array(
'class' => 'form-control',
'ajax' => array(
'type' => 'POST',
'url' => $this->createUrl('getregions'),
'update' => '#Customers_region_id',
'data'=>array('state_id'=>'js:this.value')
)
)
); ?>
but you have to change name of field state_id, update and url on your defining of dropDownList.
maybe it will help.

Related

Cannot update textfield based on dropdown list Yii

I have 3 dependent dropdowns, and a textfield being dependent to the last dropdown. If one of the value in the last dropdown, I want the textfield value dynamically changes based on the selected value (it's from the same Database table).
This is the view of the third dropdown:
<div class="row" id="id_subkeg">
<?php echo $form->labelEx($model, 'id_subkeg'); ?>
<?php
echo $form->dropDownList($model, 'id_subkeg', array(), array(
'style' => 'width: 100%',
'ajax' => array(
'type' => 'POST',
'url' => CController::createUrl('dynamicSatuan'),
'update' => '#' . CHtml::activeId($model, 'satuan'),
//'update'=>'#seksi',
'data' => array('id_subkeg' => 'js:this.value'),
)
)
);
?>
<?php echo $form->error($model, 'id_subkeg'); ?>
</div>
This is the textfield view:
<div class="row" id="satuan">
<?php echo $form->labelEx($model, 'satuan'); ?>
<p class="hint" style="font-size: 80%">Contoh: Dokumen.</p>
<?php echo $form->textField($model, 'satuan', array('style' => 'width: 98%;', 'readonly' => FALSE)); ?>
<?php echo $form->error($model, 'satuan'); ?>
</div>
And this is the action in the controller:
public function actionDynamicSatuan() {
//$data = Subkegiatan::model()->findByPk($_POST['id_subkeg']);
$data = Subkegiatan::model()->findByPk('id_subkeg=:id_subkeg', array(':id_subkeg' => (int) $_POST['id_subkeg']));
echo $data->satuan;
}
But it's not been working for days. I don't know which part I've missed. My guess is that the dropdown is a dependent dropdown to the one above it. So I must have missed at some part.
Any help is highly appreciated.
UPDATE:
After days of searching, finally got it:
public function actionDynamicSatuan() {
$param_country = (int) $_POST['id_subkeg'];
$maxOrderNumber = Yii::app()->db->createCommand()
->select('satuan')
->from('subkegiatan')
->where('id_subkeg = ' . $param_country)
->queryScalar();
echo '<b>SATUAN: '. $maxOrderNumber.'</b>';
//echo CHtml::tag('input', array('type' => 'text', 'value' => $maxOrderNumber));
}
Instead of update, use success callback:
echo $form->dropDownList($model, 'id_subkeg', array(), array(
'style' => 'width: 100%',
'ajax' => array(
'type' => 'POST',
'url' => CController::createUrl('dynamicSatuan'),
'data' => array('id_subkeg' => 'js:this.value'),
'success'=> 'function(data) {
$("#your_id_here").empty();
$("#your_id_here").append(data);
}'
)
)
);

Doubts about parameter in the URL

I have the following form to the address below:
http://localhost/myapp/web/index.php?r=cashbook%2Faccomplishment
$form = ActiveForm::begin([
'id' => 'accomplishment-form',
'options' => ['class' => 'form-horizontal'],
'action' => Url::to(['/cashbook/accomplishment']),
'method' => 'get',
]);
$form->field($model, 'category_id')->dropDownList(ArrayHelper::map(
Category::find()->where(['user_id' => Yii::$app->user->identity->id])
->orderBy("desc_category ASC")
->all(), 'id_category', 'desc_category'),
['onchange'=>'this.form.submit()','prompt'=>'-- Select --']);
ActiveForm::end();
Who processes and generates the following URL:
http://localhost/myapp/web/index.php?r=cashbook%2Faccomplishment&Cashbook%5Bcategory_id%5D=18
But I need only the category_id value (selected in dropDownList). That is, the URL should be:
http://localhost/myapp/web/index.php?r=cashbook%2Faccomplishment&category_id=19
How to stay that way or get just the category_id
In view add registerJs:
$this->registerJs('var submit = function (val){
if (val > 0) {
window.location.href = "' . Url::to(['/cashbook/accomplishment']) . '/?category_id=" + val;
}
}', View::POS_HEAD);
And not use ActiveForm::begin... and all your code. Instead of use this:
echo Html::activeDropDownList($model, 'id_category', ArrayHelper::map(
Category::find()->where(['user_id' => Yii::$app->user->identity->id])
->orderBy("desc_category ASC")
->all(), 'id_category', 'desc_category'), ['onchange'=>'submit(this.value);','prompt'=>'-- Select --']);

Cakephp form has no data on submit

Using cakephp 1.3 I fill out a form, and upon debugging the submit, I notice that
data:$("#submit-478065271").closest("form").serialize()
is empty. Why would something like that happen? I've checked that the form actually has data, which I can serialize manually. Here is the submit code:
echo $this->Js->submit(
'Sign up',
array(
'class' => 'btn btn_submit fr register_submit register_btn_align',
'url' => array('controller' => 'email_guides', 'action' => 'subscribe'),
'before' => '$(".error-message").remove();' . $this->Js->get('#loading')->effect(
'fadeIn',
array('buffer' => false)
),
'complete' => $this->Js->get('#loading')->effect(
'fadeOut',
array('buffer' => false)
) . 'debugger;',
'success' => 'if(data.success) {
$("#CustomUserFirstName").val("");
$("#CustomUserEmail").val("");
$("#EmailGuidesUserStartDate").val("' . date('d/m/Y', strtotime('+1 Weekday')) . '");
$("#EmailGuidesUserTerms").attr("checked", false);
$("#signupModal").hide();
} else {
$("#signupModal").hide();
}
'type' => 'json'
)
);
?>
<?php echo $this->Form->end(); ?>
UPDATE: I've noticed that the form is not a parent of the submit element ... which is very bizarre. This would explain why .closest("form") returns an empty array.

View Sending an Action to a Controller and returning a query

I'm kinda noob yet using cakephp, but I would love to know how to use it, for that, I'm trying to develop something pretty simple.
I have a form, that has an input type = 'text' and I wanna search in my database what I just type in this input.
How can I do that ?
I know that I have to get what is inside of my input text and execute a function in my controller that will receive a parameter and execute the query and return the same query to my view.
Other thing that I couldn't do it yet is this:
<button type="submit" class="btn"><i class="icon-search"></i></button>
I wanna change this to cake format, like:
echo $this->Form->input('button', array('class' => 'btn', type = 'submit'));
but no idea how to add the icon.
Thanks.
You can specify the button text like.
<?php
echo $this->Form->button(
"<i class='icon-search'></i>",
array(
'class' => 'btn',
'type' => 'submit',
'escape' => false
)); // make sure you've use escap = false with html input.
?>
and for the search you can define the action like this.
<?php
public function search() {
$conditions = array();
$params = $this->passedArgs;
if(isset($params['text_field_name']) && !empty($params['text_field_name'])){
$conditions['ModelName.text_field_name like'] = $params['text_field_name'].'%';
}
$this->Paginate->settings = array(
'conditions' => $conditions
);
$this->set('variable_name', $this->Paginator->paginate());
}
?>
you can also use this for searching
---- in your .ctp file
<?php echo $this->Form->create('ModelName'); ?>
<?php echo $this->Form->input('ModelName.search_word'); ?>
<?php echo $this->Form->submit(" <i class='icon-search'></i> " , array('escape' => false , 'class' => 'btn' ) ); ?>
<?php echo $this->Form->end(); ?> // note that no params for end() method
---- in your controller file
$searchWord = $this->request->data['ModelName']['search_word'] ;
$this->paginate = array('limit' => 30 ,
'conditions' => array('OR' => array('ModelName.field1' => "%".$searchWord."%" ,
'ModelName.field2 LIKE' => "%".$searchWord."%" )));
$this->set('searchResults', $this->paginate());

Yii Dropdown List Empty Value as Default

I have a dropdownlist in my _form model and I want to add a empty value (which I want as default). I have the following:
In _form:
<?php echo $form->labelEx($model,'country_id'); ?>
<?php echo $form->dropDownList($model,'country_id',Country::items(),array('empty' => '--Select a country--')); ?>
<?php echo $form->error($model,'country_id'); ?>
In Model Country:
public static function items()
{
return CHtml::listData(Country::model()->findAllBySql(
'SELECT * from country'),
'id', 'name');
}
Even my empty option is in the first row in dropdownlist, the 1st country in list shows as default.
I tried:
<?php echo $form->dropDownList($model,'country_id',
Country::items(),array('empty'=>'--Select a country--',
'options'=>
array(
'3'=>array('selected'=>'selected')
)
));
?>
In this way I can choose the default option, but cant set it to empty value, just countries that came from model:items.
Any idea?
Are you sure that country_id property of your model is not set to anything when you print the dropdown list? The following works for me if $model instance is created using new Country() operator but not by populating properties from database:
<?php echo $form->dropDownList(
$model,
'country_id',
Country::items(),
array(
'empty'=>'--Select a country--')
);
?>
Read documentation. There is 'prompt' parameter.
Try this:
<?php
echo $form->dropDownList($model,'country_id',Country::items(), array(
'prompt' => '--Select a country--'
));
?>
See more details here http://www.yiiframework.com/forum/index.php/topic/11195-how-to-edit-the-default-option-in-dropdownlist/
You always can do something like array_merge in your items method
public static function items()
{
return array_merge(array(''=>'--Select a country--'), CHtml::listData(Country::model()->findAllBySql(
'SELECT * from country'),
'id', 'name'));
}
I believe youre looking for:
echo $form->dropDownList($model,'country_id',Country::items(),array('prompt'=>''));
if you use yiibooster maybe this will help
<?php echo $form->dropDownListGroup(
$model,
'kode_cuti_sub2',
array(
'empty'=>'--Select a country--',
'widgetOptions' => array(
'data' => array('Something ...', 'Pilih Jenis Cuti'=>Chtml::listData(Cuti::model()->cuti_sub2(),'kode','jenis_cuti')),
'options' => array(
'placeholder' => 'Pilih NIP Pegawai',
'width' => '100%',
),
),
'wrapperHtmlOptions' => array(
'class' => 'col-sm-5',
),
)
); ?>
in my case it's worked

Categories