Yii dropdownlist depending on two dropdownlists - php

I have seen this wiki where they populate a dropdownlist of cities, depending of the value of another dropdownlists that contains countries, using an ajax call with the update option. I need to implement something similar, but my dropdownlist depends on two dropdownlists:
<div class="row">
<?php echo CHtml::label('Countries', 'country_id'); ?>
<?php echo CHtml::dropdownlist('country_id', '',$countries); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'globaladmin'); ?>
<?php echo $form->dropDownList($model,'globaladmin',User::itemAlias('AdminStatus')); ?>
<?php echo $form->error($model,'globaladmin'); ?>
</div>
The user must select a country, and then only if in the second list "No" is selected, a new dropdown lists must be populated with the cities info (just like in the wiki example).
As I said it is similar to the example, but the new dropdown depends on 2 values (the id of the contry selected on the first list and if "No" is selected in the second one). How could I solve it?
EDIT: Explaining a little more
In the example, the country dropdown which contains the ajax call is like:
echo CHtml::dropDownList('country_id','', array(1=>'USA',2=>'France',3=>'Japan'),
array(
'ajax' => array(
'type'=>'POST', //request type
'url'=>CController::createUrl('currentController/dynamiccities'), //url to call.
'update'=>'#city_id', //selector to update
)));
I can't define such a ajax call in my country list, because I must wait the value of the second dropbox. Only if "No" is selected in this list, the ajax will be executed (and the city dropdownlist populated and showed). If "Yes" is selected then the city dropdownlist must be hidden.

Just add an ID to your globaladmin drop down and then do like below:
$("#THE ID YOU HAVE SET").on('change',function(){
// You can use $(this).val()
// and send it via an ajax request into your own url
var valueOfMyGlobalAdminDropDown=$(this).val();
if(valueOfMyGlobalAdminDropDown=="yes"){
//DO SOMETHING
}else{
//DO SOMETHING ELSE
}
});
it is also strongly recommended to use jquery live(in jquery version -1.7) or jquery ON(in jquery version +1.7) to keep your page alive in ajax requests.

Related

how to save all dropdowns values from php foreach loop in local storage?

In my cart i have my products added, there are stored in sessions.
I want to store my selected option from all dropdown when the page is refreshed.
I need to refresh my page so my sessions can be updated so i can post in my database all the updated values.
What is wrong...
if i select an option for the first row of my product it saves in local storage.but when i select another product option from other row,it overwrites the local storage,so my local storage is saving only one option,and when selected other option from other products it is rewriting my only one save option in local storage.i have to save multiple option.
Without refresh what happens is...
lets say that i've selected 1 cushion in my gallery.
So in my cart this cushion will be 1 product, and if i add two more by clicking plus button and then click on confirm order,it will post in my DB the value of 1.
But not 3.
So my page needs to refresh, so for that i need to save all dropdown selection so i can refresh the page.
So far i tried to save it,but it saves the first row of my cart.
This is what i tried...
$(function() {
if (localStorage.getItem('fabric')) {
$(".fabric option").eq(localStorage.getItem('fabric')).prop('selected', true);
}
$(".fabric").on('change', function() {
localStorage.setItem('fabric', $('option:selected', this).index());
});
});
$(function() {
if (localStorage.getItem('size')) {
$(".size option").eq(localStorage.getItem('size')).prop('selected', true);
}
$(".size").on('change', function() {
localStorage.setItem('size', $('option:selected', this).index());
});
});
this is my foreach loop if needed to understand it better.
this script below is not important for this question,but it shows how i am handling my dropdowns to make ajax get values based on dropdown selection using data attribute.
script that gets cost and subtotal
Ok... Took a liitle time, but you will like my solution (I think).
We have to set storage row by row...
So an .each() loop has to be done on product rows.
We use the index of the .each() as a part of the storage name to ensure no overwriting.
Given this HTML that I made just for this example:
<div class="row">
<!-- other elements like img etc... -->
<select class="fabric">
<option>jeans</option>
<option>leather</option>
<option>cotton</option>
</select>
<select class="size">
<option>small</option>
<option>medium</option>
<option>large</option>
</select>
</div>
<div class="row">
<!-- other elements like img etc... -->
<select class="fabric">
<option>jeans</option>
<option>leather</option>
<option>cotton</option>
</select>
<select class="size">
<option>small</option>
<option>medium</option>
<option>large</option>
</select>
</div>
Here is the script:
$(function() {
$(".row").each(function(index){
// Fabric selection
if (localStorage.getItem('row_'+index+'_fabric')) {
$(this).find('.fabric option').prop('selected', false).eq(localStorage.getItem('row_'+index+'_fabric')).prop('selected', true);
console.log("Row#"+index+" get-fabric: "+localStorage.getItem('row_'+index+'_fabric'));
}
$(this).find(".fabric").on('change', function() {
localStorage.setItem('row_'+index+'_fabric', $(this).find('option:selected').index());
console.log("Row#"+index+" set-fabric: "+$(this).find('option:selected').index());
});
// Size selection
if (localStorage.getItem('row_'+index+'_size')) {
$(this).find('.size option').prop('selected', false).eq(localStorage.getItem('row_'+index+'_size')).prop('selected', true);
console.log("Row#"+index+" get-size: "+localStorage.getItem('row_'+index+'_size'));
}
$(this).find(".size").on('change', function() {
localStorage.setItem('row_'+index+'_size', $(this).find('option:selected').index());
console.log("Row#"+index+" set size: "+$(this).find('option:selected').index());
});
});
});
Try it on this CodePen!
(Change the selects and hit "Run" to refresh)

Adding some more fields to the form in yii2 using ajax

I have a Yii2 form:
<?php $form = ActiveForm::begin(['id' => 'que']); ?>
<?php echo $form->field($model, 'type')
->dropDownList($questionTypes, [
'class' => 'form-control ng-pristine ng-valid ng-touched',
'prompt' => 'Select question type',
'ng-model' => 'que.type',
'ng-change' => 'addAnswerOptions(que);',
]);
?>
<?php ActiveForm::end(); ?>
On the basis of selected dropdown value, I have to add some more fields to the same form of the same model. What fields will be added, is totally depend on the dropdown value.
How can I do this?
From the information you give out here is what I would suggest.
1) Dynamic - no AJAX
Build your form with all the fields you need, just contain each "scenario" in a separate div like follows:
<?php $form = ActiveForm::begin(['id' => 'que']); ?>
<?php echo $form->field($model, 'type')
->dropDownList($questionTypes, [
'class' => 'form-control ng-pristine ng-valid ng-touched',
'prompt' => 'Select question type',
'ng-model' => 'que.type',
'ng-change' => 'addAnswerOptions(que);',
]);
?>
<div class="form-option" data-type="class" style="display:none;">
<?php
// ... fields here for case type == class
?>
</div>
<div class="form-option" data-type="prompt" style="display:none;">
<?php
// ... fields here for case type == prompt
?>
</div>
<div class="form-option" data-type="ng-model" style="display:none;">
<?php
// ... fields here for case type == ng-model
?>
</div>
<div class="form-option" data-type="ng-change" style="display:none;">
<?php
// ... fields here for case type == ng-change
?>
</div>
<?php ActiveForm::end(); ?>
Then you will want to register Javascript code to display the correct blocs depending on which dropdown option was selected.
Bellow is an example using JQuery:
$(document).ready(function(){
$('select.form-control').change(function(){
$('.form-option').hide(); // hide all options if an option is showing
var index = $('select.form-control').index();
$('div[data-type="'+index+'"]').show(); //show the correct fields
});
});
If you're going to go this way I suggest you use AJAX validation for your form. It will avoid you having to deal with a headache on page reload.
Once your form is submitted you will have to handle each case in your controller. You can either use a simple set of if() statements that check the drop down value. Or you can set your model validation scenario according to the drop down value.
The advantage of this is that it will be quicker and you will be able to take advantage of ActiveForm. the cons are that you need to know which fields you want to display for each option, and it doesn't allow you to cumulate n number of fields when you don't know how much n is.
2) Using Ajax
In the event that you want to use ajax calls to load the extra form fields you will have to make a controller/action combination that will return the fields depending on the type that you pass in the GET
This action will generate the html of the fields you want to display. Here's an example:
public function actionAjaxFields($type)
{
$html = '';
if($type == "class")
{
$html .= Html::textInput('Field1');
}
elseif($type == "prompt")
{
$html .= Html::textInput('Field2');
}
else
{
// etc...
}
return $html;
}
Note that you can also pass a user id to this method which will allow you to generate a model and use Html::activeTextInput(), however you will not be able to take advantage of ActiveForm features.
Once this is done, you should bind a function to the change event of the dropdown and use something along the lines of :
var responsePromise = $http.get("controller/ajax-fields", {params: {type: <type-from-dropdown>}});
Unfortunately I do not know much about angularjs so this is the extent of the help I can give on the javascript side of things. I'm sure there's more than enough information on google/stackoverflow about binding events and appending data to the DOM in angularjs to get you running.
Let me know if I can be of any extra help on the Yii2 side.

How to get selected from jmultiselect2side in yii and display in a new page

I'm new to yii and I don't understand the extensions much
but I used this extension called jmultiselect2side because I'm trying to make a site where users could reserve stuff like apparatuses in the lab
Anyway, I need a code that would get the Selected Items and then display them in another page for viewing purposes
I haven't put anything in the controller but the name of my controller and model is Apparatus
Here is my view:
<?php
$model= Apparatus::model()->findByAttributes(array('ApparatusCode'=>'1'));
// complete user list to be shown at multiselect order by ApparatusCode
$Apparatus= Apparatus::model()->findAll(
array('order' => 'ApparatusCode'));
?>
<center>
<?php
$this- >widget('application.extensions.jmultiselect2side.Jmultiselect2side',array(
'model'=>$model,
'attribute'=>'ApparatusName', //selected items
'labelsx'=>'Available',
'labeldx'=>'Selected',
'moveOptions'=>false,
'autoSort'=>'true',
'search'=>'Search:',
'list'=>CHtml::listData( // available items
$Apparatus,
'ApparatusCode',
'ApparatusName'),
));
?>
please help as soon as possible :/
put all above elements in a form. Set action for the form. Submit the form then the action in which you are handling this submit request, you can write there
if(isset($_POST))
{
foreach($_POST['Apparatus']['ApparatusName'] as $name)
{
do what ever you want
}
}
$name will represent the each selected item

dropdown menu with links to the functions

I currently have two buttons. 1 to change a mysql variable to 1 and one to change it to 0
This works fine but i would like to have them in a dropdown. So i dont have 2 buttons showing.
<td>
<i class="fa fa-check"></i>
<i class="fa fa-check"></i>
</td>
the first one sets "complete" to 1 and the second one sets "complete" to 0.
Prepare options array as below
$opts=array(
'' =>'--Select--',
'0'=>'Option 1',
'1'=>'Option 2'
);
Generate dropdown with below CI Code:
<?php echo form_dropdown('dropdown_name',$opts,'','onchange="gotopage(this.value)"');?>
In js:
function gotopage(val)
{
if(val!="")
{
window.location = "<?php echo site_url("PATH_TO_GO");?>/"+val; // pass parameter in url
}
}
Without seeing the code only we can tell you in general what to do to make a drop down in codeignitor. In your view page, you should put this to generate a select combination box. The value can be received only if, its in a form. if you don't want a form, then you may need to incorporate Ajax with this.
<?php echo form_dropdown('cmb',$select_options,'0');?>
The first variable will become the name of the variable and the third variable is the default option that that has to be select (in this case Option 1 will be selected). The third variable is the data array which contains the options of the dropdown.
The data array, have to be like this, which have to be passed from controller into the view.
$select_options=array(
'0'=>'Option 1';
'1'=>'Option 2'
);

Yii 1.1.3 setting selected value of dependent dropdown part 2

Previously I've created a question where I was wondering how to set selected value for dependent dropdown. That was easy, man adviced me just set second parameter.
echo CHtml::dropDownList('OpenLessons[Building]', $buildingClassID, $buildingList,array(
'ajax' => array(
'type'=>'POST',
'url'=>CController::createUrl('ajax/floorList'),
'update'=>'#OpenLessons_Floor',
)));
echo CHtml::dropDownList('OpenLessons[Floor]',$model->Class_ID, array(),array(
'ajax' => array(
'type'=>'POST', //request type
'url'=>CController::createUrl('ajax/roomList'),
'update'=>'#OpenLessons_Class_ID',
)));
echo CHtml::dropDownList('OpenLessons[Class_ID]',$model->Class_ID, array());
where $buildingClassId is value of select. So that works fine for first select. But how can I set the same for dependent ones? When I look at it's code it looks like this:
<select name="OpenLessons[Floor]" id="OpenLessons_Floor">
</select>
I expected it to have some options, because I set default value for first one. So even if I put as second parameter of seconddropdown some value it wouln't be selected.
Any advices/suggestions?
UPDATE I'd mention that I don't see at XHR console call of floorlist. How can I make it?
UPDATE
$(document).ready(function()
{
$('#OpenLessons_Building').trigger('change');
$('#OpenLessons_Building option').trigger('click');
}).on('change','#OpenLessons_Building',function()
{
console.log('changed');
}).on('click','#OpenLessons_Building option',function()
{
console.log('clicked');
});
Tried like this. Both actions - change and click has happened because I can see output in console, but the dependent arrays are still empty.
You should use $("#OpenLessions_Building").on("change", function() { your code here });
The trigger function was actually does is execute the action (change or click in your case) of the dropdown as soon as the page loads.

Categories