Doubts about parameter in the URL - php

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 --']);

Related

Yii drop down with ajax

So what I want to do is populate a dropdown in Yii framework with ajax using my database values in drop down. I using Kartik widget in it here is my dropdown code,
<?php $primaryfield = [1 => 'Business Development(Sales)', 2 => 'Graphic Design', 3 => 'Social Media Marketing', 4 => 'Web Development']; ?>
<?= $form->field($model, 'primaryfield')->widget(Select2::classname(), ['data' => $primaryfield,
'options' => ['placeholder' => 'Enter Your Primary Field', 'multiple' => false], 'pluginOptions' => ['tags' => false, 'tokenSeprators' => [',', ' '], 'maximumInputLength' => 20],])->label(false); ?>
I know everything about Ajax in PHP but don't know how to use it in Yii framework using Kartik widget I have all the primary fields value in my database but unfortunately, I am only able to display them in static basis not dynamic basis using ajax
If I get you clear, you want to have a drop-down list in which their items are dynamically generated by your database.
This is the way you can achieve with kartik dropdown widget.
I'll first create active form field which contains predefined categories as follows
<?php $form = ActiveForm::begin();
//Initialize predefined categories
$data = [
'1' => 'Business Development(Sales)',
'2' => 'Graphic Design',
'3' => 'Social Media Marketing',
'4' => 'Web Development',
];
?>
These field will prompt database to retrieve items for particular category via AJAX
<?= $form->field($model, 'primaryfield')->widget(Select2::classname(), [
'data' => $data,
'options' => ['placeholder' => 'Enter your primary field'],
'pluginOptions' => [
//'allowClear' => true
],
'pluginEvents' => [
"change" => "function() {
var id = $(this).val(); //extract the id of selected category
$.ajax({
method : 'GET',
dataType : 'text',
url : '../yourcontroller/populate?id=' + id,
success : function (response) {
var response = JSON.parse(response);
var myDropDownList = document.getElementById(\"model-item\");
$.each(response, function(index, value) {
var option = document.createElement(\"option\");
option.text = value;
option.value = index;
try {
myDropDownList.options.add(option);
}
catch (e) {
alert(e);
}
});
}
});
}",
],
]);
?>
<?= $form->field($model,'item')->dropdownList(
['prompt'=>'Select Item']
);
?>
Now create action in your controller that will query items from your database based on the category selected and return it to the Item field via ajax.
<?php
public function actionPopulate($id)
{
// the id above is the one selected from the category field so you can use
// that Id now to retrieve items from your item-field with ajax
/* in you case */
$results = Category::find()
->select('items')
->where(['id' => $id])
->asArray()
->all();
//these hard-coded values are for the demonstration
$results = [
'1'=>'maziwa',
'2'=>'ugali',
'3'=>'samaki',
'4'=>'kuku',
'5'=>'mtetea',
];
return json_encode($results);
}
?>
Hope this helps!

I'm trying to retrieve from a database for a select box with cakePHP but the data isn't being retrieved properly

I am using cakephp 3.3
I have in the controller
$employee = TableRegistry::get('employees');
$allNames = $employee->find('list', array('employee_name' => array('employee_name') ) );
$allNames = $allNames->toArray();
$this->set('name', $allNames);
and in my template
<?= $this->Form->input('employee', array('type'=>'select','label' => false,
'options' => $name,'value'=>$name));?>
The only thing being retrieved and displayed is the number of entries i have in the database, $name only contains an array(1,2,3,4) when it should be actual people names.
Did you read the documentation about how find('list') works?'
$allNames = $employee->find('list', [
'keyField' => 'employee_name'
'valueField' => 'employee_name'
]);
$this->set('name', $allNames);
<?= $this->Form->input('employee', ['type'=>'select','label' => false,
'options' => $name]);?>
You can map id and value by keyField and valueField in list query
in your controller
$employee = TableRegistry::get('employees');
$allNames = $employee->find('list', array('valueField' =>employee_name','keyField'=>'employee_id' )); // correct employee_id with your table id field.
$this->set('name', $allNames);
In your View
<?= $this->Form->input('employee', array('type'=>'select','label' => false,
'options' => $name));?>

jQuery: How to get the input value from an input field made with PHP/CakePHP?

I've tried a couple of things and still can't get the value to be returned correctly. Im using CakePHP 2.0v.
Here is my first input field
echo $this->Form->input('semesterFrom', array(
'options' => $semesterOptions,
'empty' => 'Select',
'label' => false,
'class' => 'form-control',
'name' => 'data[student][semester]'));
Here is my second input/select field
echo $this->Form->year('class_yearFrom', date('Y'), 2030, array(
'empty' => __('Select Year'),
'class' => 'form-control year',
'name' => 'data[student][class_year]'));
Ive tried the following.
var attendanceSemesterValue = app.myGoalForm().find('#StudentSemesterFrom').val(); //also variations of :selected and .text()/.val()
var attendanceYearValue = app.myGoalForm().find('#StudentClassYearFromYear :selected').val();
if (attendanceSemesterValue === "Select" && attendanceYearValue === "Select Year") {
var wantedYearValue;
wantedYearValue = 0;
} else {
wantedYearValue = {
'semesterFrom': app.myGoalForm().find('#StudentSemesterFrom :selected').val(),
'yearFrom': app.myGoalForm().find('#StudentClassYearFromYear :selected').val(),
};
var studentRangeValue = app.myGoalForm().find('#StudentRange').is(':checked');
if (studentRangeValue) {
$.extend(wantedYearValue, {
'semesterTo': app.myGoalForm().find('#StudentSemesterTo :selected').text(),
'yearTo': app.myGoalForm().find('#StudentClassYearToYear :selected').text(),
});
}
}

Trying to create a dependent combobox in yii using ajax

I am trying to create a dependent combobox system in my Yii application.
First combobox is populated with States and the second one is dynamically generated with ajax and renderPartial() method.
Code below:
View
<?php
$this->widget('ext.combobox.EJuiComboBox', array(
'model' => $adMulti,
'attribute' => 'state_id',
// data to populate the select. Must be an array.
'data' => CHtml::listData(State::model()->findAll(), 'id', 'name'),
'assoc' => true,
// options passed to plugin
'options' => array(
// JS code to execute on 'select' event, the selected item is
// available through the 'item' variable.
'onSelect' => 'getCities(item.value);',
// If false, field value must be present in the select.
// Defaults to true.
'allowText' => false,
),
// Options passed to the text input
'htmlOptions' => array(
'style' => 'height: 36px',
),
));
?>
<script type="text/javascript">
function getCities(state) {
$.ajax({
url: '<?php echo $this->createUrl('ad/ajaxCities'); ?>',
data: {state_name: state},
type: 'POST',
success: function (data) {
$('#city_id-carrier').html(data);
}
});
}
</script>
<div id="city_id-carrier" class="textboxes"></div>
AdController
public function actionAjaxCities()
{
$stateName = isset($_POST['state_name']) ? $_POST['state_name'] : FALSE;
if ($stateName) {
$state = State::model()->findByAttributes(array(
'name' => $stateName
));
$stateId = $state->id;
$cities = City::model()->findAllByAttributes(array(
'state_id' => $stateId
));
$this->renderPartial('_cities', array(
'cities' => $cities,
'stateId' => $stateId
), FALSE, TRUE
);
}
}
_cities.php
<?php
$this->widget('ext.combobox.EJuiComboBox', array(
'model' => AdMulti::model(),
'attribute' => 'city_id',
// data to populate the select. Must be an array.
'data' => CHtml::listData($cities, 'id', 'name'),
'assoc' => true,
// options passed to plugin
'options' => array(
// JS code to execute on 'select' event, the selected item is
// available through the 'item' variable.
// 'onSelect' => 'getLocalities(item.value);',
// If false, field value must be present in the select.
// Defaults to true.
'allowText' => false,
),
));
?>
The code is working and creating the combobox for the first time. But when I change the value in state combobox, something weird happens. A new combobox is created, but the values shown are still from the first combobox generated.
I am getting an error "TypeError: this.input is undefined" in Firebug Console.
I tried creating unique id for combobox using uniqid() but it isn't affecting the id of select element of the combobox.
If I change
$('#city_id-carrier').html(data)
to
$('#city_id-carrier').append(data)
it is working well but with multiple combobox generated.
Any ideas/suggestions to make this work?
I've found a solution to get this working. Instead of creating the combobox dynamically, place the combobox once and then populate it dynamically upon each request. Much like dependent dropdown.
A combobox is a combination of a dropdown and textbox. So, note down the id of the hidden dropdown and update it upon ajax update.
Code:
View:
<?php
$this->widget('ext.combobox.EJuiComboBox', array(
'model' => $adMulti,
'attribute' => 'state_id',
// data to populate the select. Must be an array.
'data' => CHtml::listData(State::model()->findAll(), 'id', 'name'),
'assoc' => true,
// options passed to plugin
'options' => array(
// JS code to execute on 'select' event, the selected item is
// available through the 'item' variable.
'onSelect' => 'getCities(item.value);',
// If false, field value must be present in the select.
// Defaults to true.
'allowText' => false,
),
));
?>
<script type="text/javascript">
function getCities(state) {
$.ajax({
url: '<?php echo $this->createUrl('ad/ajaxCities'); ?>',
data: {state_id: state},
type: 'POST',
beforeSend: function() {
$('#AdMulti_city_id_combobox').val(''); // emptying textbox in case a value is previously selected.
},
success: function (data) {
$('#AdMulti_city_id').html(data); // populating the hidden dropdown.
}
});
}
</script>
<?php
$this->widget('ext.combobox.EJuiComboBox', array(
'model' => $adMulti,
'attribute' => 'city_id',
// data to populate the select. Must be an array.
'data' => CHtml::listData(array(''), 'id', 'name'),
'assoc' => true,
// options passed to plugin
'options' => array(
'allowText' => false,
),
));
?>
AdController
public function actionAjaxCities()
{
$stateName = isset($_POST['state_id']) ? $_POST['state_id'] : FALSE;
if ($stateName) {
$state = State::model()->findByAttributes(array(
'name' => $stateName
));
$cities = City::model()->findAllByAttributes(array(
'state_id' => $state->id
));
$data = CHtml::listData($cities, 'id', 'name');
foreach ($data as $id => $name) {
echo CHtml::tag('option', array('value' => $id),
CHtml::encode($name), TRUE);
}
}
}

Yii. Dependent Dropdown

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.

Categories