I have a ‘single line’ dropdownlist wich obtains its $data (id and description) from my db.
The dropdownlist is ‘independent’ and thus does not store the selected id in a model.
I use ajax to send the selected id (obtained with ‘js:this.value’) to my controller.
My question is:
How can I also send the description to my controller.
Currently, in the controller, I have to use the received id to read the database again - just to get the description. But it should be possible to send both the id and description to the controller at the same time.
I think we misunderstood each other. My problem is not getting data for the dropdownlist, but rather to get the selected data out - ALL of it, not just the id.
I have solution but its not a perfect solution. Don’t use CHtml::listData… Create your own array. You make an array whose index contains id and description combination. For example id=1 and description=‘test’ then make index like 1,test. So using ajax request you get 1,test in your controller then you can perform string operation like explode. Hope its working.
Apart from that the other way I see is to create a hidden field, and when the user selects an option from the dropdown list, you can create a JS that has “onChange” event that puts the value of the ID of the option selected concatenated with the description into a hidden field’s value.
Or 2 hidden fields, one with the ID, other with the Description, so you don’t have to do explodes in the controller and could access the parameters like
You wrote: “you can create a JS that has “onChange” event that puts the value of the ID of the option selected concatenated with the description into a hidden field’s value.”
This is my whole problem. How does that JS function look like (getting both the id and description)?
<script type="text/javascript">
$(document).ready(function(){
$("#<id_of_dropdown>").change(function() {
var seleted_id = $(this).val();
var selected_description = $(this).text();
$("#<hidden_field_id").val(seleted_id);
$("#<hidden_field_description").val(selected_description);
});
});
</script>
Then you can catch it with through $_POST, and since it is not related to any model, it would probably be just $_POST[‘name of hidden field’].
But like I said, be sure to validate the input of the controller as the user might hack it by inserting non-matching ID’s with Descriptions in the DOM.
Ya SilverPT, I quickly tried ‘js:this.text’ and it did not work. But maybe, as you said, it is more secure to just pass the id and get the description again from the db. So I think I will go with that.