How to get form_dropdown() show the selected value in Codeigniter? - codeigniter

I am trying to populate a dropdown list from database. In my view file I have the following code
$batch= $query ['batch']; // I pull this data from a separate model
echo form_dropdown('shirts', $options, $batch);
Now the drop down list is populating data fine but the problem is I don't get the value-"$batch" automatically selected when the page loads. Interestingly if I echo $batch, elsewhere in the page it shows the correct data, which means $batch is okay.
Here is my Controller
function update($id){
$this->load->model('mod_studentprofile');
$data['query']= $this->mod_studentprofile->student_get($id);
$data['options']= $this->mod_studentprofile->batchget();
$data['tab'] = "Update Student Information";
$data['main_content']='update_studentprofile';
$this->load->view('includes/template',$data);
}
And here is my model
function batchget() {
$this->db->select('batchname');
$records=$this->db->get('batch');
$data=array();
foreach ($records->result() as $row)
{
$data[$row->batchname] = $row->batchname;
}
return ($data);
}
Would you please kindly help me to solve this problem. I want to have the value- "$batch" automatically selected in the dropdown list when the page loads.
Thanks in Advance.
EDit... my Model for student_get($id)
function student_get($id)
{
$query=$this->db->get_where('student',array('studentid'=>$id));
return $query->row_array();
}
Thanks :)

I think that what's probably happening is that the value in $batch may be matching what's rendering in the dropdown but not the actual key in $options for that particular option which would be the value="" portion of the html.
for example...
// this wouldn't select 'foo' as you may be thinking
$options => array('0' => 'foo', '1' => 'bar');
$batch = 'foo';
echo form_dropdown('shirts', $options, $batch);
// this would select foo
$options => array('foo' => 'foo', 'bar' => 'bar');
$batch = 'foo';
echo form_dropdown('shirts', $options, $batch);
Edit in response to OP's comment:
The batchget() method looks like it returns your $options array in the proper format and your student_get() method is returning a row_array. It appears that in the view you're assigning the value of one of the keys returned by the student_get method to be the selected value stored in $batch which is then passed in as the third argument to form_dropdown().
This all appears to be correct. As long as the value of $batch is indeed one of the array keys that is in $options then form_dropdown() will set one of the dropdown options as having been selected.

Debug stuff.
var_dump() $options, var_dump() $batch, look at the two and see where you went wrong.
The third option must be the value of the key, not the value of the label.
Anthony Jack is probably right.

Related

Is there a shorter way than this to check values when using same Add form for Edit

I have the same code for an Add and an Edit form. Therefore in the controller I need a check to check if a) POST vars submitted (for saving), and if not then b) the original values (for editing) and if not then no value (blank for Adding). I put them in a $data array to pass to the view. Then in the form I can put:
value="<?php echo $member_id;?>"
So my question is, in Codeigniter is there a shorter way than the following to check if POST, then if not check if the original data exists, and if not then its nothing.
$data = array(
'member_id' => ( isset($_POST['member_id']) ? $_POST['member_id'] : (isset($member->member_id ) ? $member->member_id : '') )
);
I know about set_value() but looks like that wont add in the current data when editing a form, so have not used that.
You can allways make function for it.
function get_value_or_default($array, $key, $default) {
return isset($array[$key] ? $array[$key] :
isset($default) ? $default : '';
}
Or even better:
function update_from_post($object) {
$data = array();
foreach ($object as $prop_name => value) {
$value = get_value_or_default($_POST, $prop_name, $object->{$prop_name});
$data[$prop_name] = $value;
}
Assuming you have different methods in the controller for create vs edit: (you can use the same view in different methods by specifying it in $this->load->view()):
Your create method would assume it was new, and always read the $_POST variables (if $_POST)
Your edit method would first load the object from the database, and then overwrite with $_POST variables if present.
Finally, CodeIgniter has the input helper:
$this->input->post('field_name');
returns false if that field is not in $_POST.
To use your code above:
create
$data = array(
'member_id' => $this->input->post('member_id') ? $this->input->post('member_id') : '')
);
edit
$data = array(
'member_id' => $this->input->post('member_id') ? $this->input->post('member_id') : $member->member_id )
);

How do I pass a selectbox variable to the View from the Controller in CodeIgniter?

I want to pass a variable (selectbox id, which comes from database) to the view from the controller, but do not know how to do it.
Your original question wasn't that clear, but after reading the comments you could do this.
Controller
//whatever function you're using to populate your original array below.
$data['all'] = $this->model_name->getData();
//then run that data through a foreach loop to populate the dropdown variable.
foreach($data['all'])
{
$data['idDropDown'][$data['all']['id']]=$data['all']['ad'];
}
This will pass an array like: [455]=>Aliağa, [456]=>Balçova to the view as $idDropDown along with your original data as $all
Then in the view just used CI's form dropdown.
echo form_dropdown('id',$idDropDown);
Let's say you have a controller called article and a method index then in your view you will have :
<?php
echo form_open('article/index');
echo form_input('text');
echo form_close;
?>
And in your controller something like:
public function index()
{
if($this->input->post()) {
$this_is_catched_text = $_POST['text'];
}
}
This is without validation and other stuff. Just you get the idea how it works.
In your case it will be like this
$ilce = array(array("id" => 455, "il_id" => 35,"ad" => "Aliağa"),
array("id" => 456, "il_id" => 35, "ad" => "Balçova"));
$options = array();
foreach($ilce as $x) {
$options[$x['id']] = $x['ad'];
}
echo form_dropdown('names', $options);

Magento add to cart object doesn't contain custom options

I'm using SCP with success, I don't think the problem is there. Basically I've got an observer that looks for the "Add to cart" event and goes from there. Here's my observer method:
public function catalogProductLoadAfter(Varien_Event_Observer $observer)
{
// set the additional options on the product
$action = Mage::app()->getFrontController()->getAction();
if ($action->getFullActionName() == 'checkout_cart_add') {
// assuming you are posting your custom form values in an array called extra_options...
if ($options = $action->getRequest()->getParam('extra_options')) {
$product = $observer->getProduct();
// add to the additional options array
$additionalOptions = array();
if ($additionalOption = $product->getCustomOption('additional_options')) {
$additionalOptions = (array)unserialize($additionalOption->getValue());
}
foreach ($options as $key => $value) {
$additionalOptions[] = array(
'label' => $key,
'value' => $value,
'value' => $value,
);
}
// add the additional options array with the option code additional_options
$observer->getProduct()->addCustomOption('additional_options', serialize($additionalOptions));
}
}
}
All looks well and functions just fine. I've dropped in some Zend_Debug::dump statements at various points and have found where I think the issue is. $product doesn't contain any custom options, or at least doesn't appear to! I've done Zend_Debug::dump($product); and this gives me the following: https://gist.github.com/720a111bc299501726d7 The important thing to see here is that the product object shown is a child product of the configurable. ALL child products have custom options (I just had to set them to get to this stage!).
In the cart page the custom options are displayed correctly, as I've just set them. So why at this midpoint when I do Zend_Debug::dump($product); just before the foreach does the above gist not show any custom options, specifically line 9. My observer fails to do it's job because $additionalOptions ends up being blank, just displays as array {}. As such the foreach doesn't fire and the script falls over. So why are no custom options shown in the gist, yet they ARE there as they show on the product page AND they show after this script executes on the cart page?
To further "prove" this, I'm getting an Invalid argument for foreach() as a result.

Code Igniter - form_dropdown selecting correct value from the database

Im having a few problems with the form_dropdown function in CodeIgniter .... My application is in 2 parts, a user goes in, enters a form and submits it .... once its submitted a admin can go in and edit that persons form and then save it to database.
So, to display the dropdown in the initial form, im using the following ( all the options in the dropdown are coming from the database )
Model:
function get_salaries_dropdown()
{
$this->db->from($this->table_name);
$this->db->order_by('id');
$result = $this->db->get();
$return = array();
if($result->num_rows() > 0){
$return[''] = 'please select';
foreach($result->result_array() as $row){
$return[$row['id']] = $row['salaryrange'];
}
}
return $return;
}
Then in the Controller:
$data['salaries'] = $this->salary_expectation->get_salaries_dropdown();
Then finally the View:
<?php echo form_dropdown('salaries', $salaries, set_value('salaries', $salaries)); ?>
That bit works perfect in displaying the dropdown filled with values for the user to select.
So, when the user selects a value, then hits save, its saved to the database.
On the Edit page which the admin see's, im using the same code to display the dropdown filled with options, but how do i get it to automatically choose the one thats been selected by the user in the initial stage?
Cheers,
According to Codeigniter documentation
The first parameter will contain the
name of the field, the second
parameter will contain an associative
array of options, and the third
parameter will contain the value you
wish to be selected. You can also pass
an array of multiple items through the
third parameter, and CodeIgniter will
create a multiple select for you.
Your admin controller should have something like
$data['selected'] = $this->salary_expectation->get_salary_selected();
According to this, the admin view should be like this
<?php echo form_dropdown('salaries', $salaries, $selected_value); ?>
one nasty solution to select the <option> element of <select> generated by form_dropdown() function of the form_helper is using the post input sended.
I made this because any solutions I found doesn't display the value that the user select in the form neither set_selected nor set_vaule.
Well, in my controller I have:
$countries = $this->country_model->get_dropdown_array(); // The array have something like $countries[COUNTRY_ID] = COUNTRY_NAME
$data['countries']=$countries;
In my view:
$selected_country = $this->input->post('country');
echo form_dropdown('country',$countries,$selected_country);
And works fine !!! :)
The form_dropdown function has a third parameter for the selected option. Use it like this:
<?php echo form_dropdown('piece_type',
array(
'type1' => 'Firts type',
'type2' => 'Second option'
$selected_value,
'id = "piece_type"') ?>
I had the same problem but i have overcome on this problem using code igniter syntex.
Here is the solution.
Fisrt step
Before the loop initialize two arrays
$options = array();
$select = array();
Then in the loop write this instruction
foreach($result->result_array() as $row)
{
/////////Your Condition ////////////
if($row['id'] == $myarray['mycolumn'])
{
$options [$row['id']] = $row['salaryrange'];
$select = $row['id'] ;
}else{
$options [$row['id']] = $row['salaryrange'];
}
}
Now
echo form_dropdown('dropdown_name' , $options , $select);
It is working ok
For update case, you have pass corresponding value to view, if passing variable is like $ind_post(from controller ) then write this code like:
<?php echo form_dropdown('salaries', $salaries, $ind_post->salaries,''); ?>

Why does my data not pass into my view correctly?

I have a model, view and controller not interacting correctly, and I do not know where the error lies.
First, the controller. According to the Code Igniter documentation, I'm passing variables correctly here.
function view() {
$html_head = array( 'title' => 'Estimate Management' );
$estimates = $this->Estimatemodel->get_estimates();
$this->load->view('html_head', $html_head);
$this->load->view('estimates/view', $estimates);
$this->load->view('html_foot');
}
The model (short and sweet):
function get_estimates() {
$query = $this->db->get('estimates')->result();
return $query;
}
And finally the view, just to print the data for initial development purposes:
<? print_r($estimates); ?>
Now it's undefined when I navigate to this page. However, I know that $query is defined, because it works when I run the model code directly in the view.
$estimates = $this->Estimatemodel->get_estimates();
$this->load->view('estimates/view', $estimates);
You're loading the return of $this->Estimatemodel->get_estimates() as the array of view variables. In other words, all the children of $estimates (assuming it can be treated as an array) are available in your view. But not the parent element.
The key here is when loading a view the second parameter needs to be an array of values, not just a single value.
$this->load->view('estimates/view', array('estimates' => $estimates));
That should get the result you're looking for, in fact, you're already doing that for the html header view. Even though that view only has one variable, it's passed as the single element of an array:
$html_head = array( 'title' => 'Estimate Management' );
$this->load->view('html_head', $html_head);
The documentation shows that the object you pass to the view must be an associative array.
$data = array(
'estimates' => $estimates
);
$this->load->view('estimates/view', $data);
Docs here

Resources