CodeIgniter form_radio with set_value - codeigniter

I am having a bit of trouble with my form and radio buttons, with input text I do this:
<?php echo form_input('lastname', set_value('lastname'), 'id=lastname'); ?>
<?php echo form_error('lastname'); ?>
and when the validation runs and that input field that is filled out gets the valued returned...what I am looking for is a way to do this with radio buttons
<tr><td><?php echo form_label('Gender: ', 'gender'); ?></td><td><?php echo form_label('Male', 'male') . form_radio('gender', 'M', '', 'id=male'); ?><br><?php echo form_label('Female', 'female') . form_radio('gender', 'F', '', 'id=female'); ?></td><td><?php echo form_error('gender'); ?></td></tr>
as you can see both my radio buttons have values already F or M.....how do I have the button that is selected returned selected?

From the user guide: https://www.codeigniter.com/user_guide/helpers/form_helper.html
form_radio()
This function is identical in all respects to the form_checkbox()
function above except that is sets it as a "radio" type.
So reading further:
form_checkbox()
Lets you generate a checkbox field. Simple example:
echo form_checkbox('newsletter', 'accept', TRUE);
Would produce:
<input type="checkbox" name="newsletter" value="accept" checked="checked" />
The third parameter contains a boolean TRUE/FALSE to determine whether
the box should be checked or not.
So in your case, it might be something like this:
// Pass boolean value to third param
// Example:
$radio_is_checked = $this->input->post('gender') === 'F';
echo form_radio('gender', 'F', $radio_is_checked, 'id=female');
Since set_radio() just returns a string checked="checked", you could wedge it in to the fourth paramter if you really wanted to but it makes for some ugly looking code:
echo form_radio('gender', 'F', NULL, 'id="female" '.set_radio('gender', 'F'));

I use Ternary Operator for this.
Suppose you got return value of "M" (Male). I am making $selected variable for example and assume that it has value of M.
<tr>
<td>
<?php echo form_label('Gender: ', 'gender'); ?>
</td>
<td>
<?php echo form_label('Male', 'male') . form_radio(array('name' => 'gender', 'value' => 'M', 'checked' => ('M' == $selected) ? TRUE : FALSE, 'id' => 'male')); ?><br>
<?php echo form_label('Female', 'female') . form_radio(array('name' => 'gender', 'value' => 'F', 'checked' => ('F' == $selected) ? TRUE : FALSE, 'id' => 'female')); ?>
</td>
<td>
<?php echo form_error('gender'); ?>
</td>
</tr>

This worked well for me. Even though I didnt use form_helper, this was much easier way. Everyone face issue to take input for gender field :)
<input id="gender" name="gender" type="radio" class="" <?php if($gender=='0') echo "checked='checked'"; ?> value="0" <?php echo $this->form_validation->set_radio('gender', 0); ?> />
<label for="gender" class="">Male</label>
<input id="gender" name="gender" type="radio" class="" <?php if($gender=='1') echo "checked='checked'"; ?> value="1" <?php echo $this->form_validation->set_radio('gender', 1); ?> />
<label for="gender" class="">Female</label>
<input id="gender" name="gender" type="radio" class="" <?php if($gender=='2') echo "checked='checked'"; ?> value="2" <?php echo $this->form_validation->set_radio('gender', 2); ?> />
<label for="gender" class="">Others</label>
I hope it will help someone :)

This works forsure....
<tr><td><?php echo form_label('Gender: ', 'gender'); ?></td><td><?php echo form_label('Male', 'male') . form_radio(array("name"=>"gender","id"=>"male","value"=>"M", 'checked'=>set_radio('gender', 'M', FALSE))); ?><br><?php echo form_label('Female', 'female') . form_radio(array("name"=>"gender","id"=>"female","value"=>"F", 'checked'=>set_radio('gender', 'F', FALSE))); ?></td><td><?php echo form_error('gender'); ?></td></tr>
wrote my radio buttons like so
<?php form_radio(array("name"=>"gender","id"=>"female","value"=>"F", 'checked'=>set_radio('gender', 'F', FALSE))); ?>

$_fldProyectoMostrar = array(
"id" => "_FLDPROYDER",
"name" => "_FLDPROYDER"
);
<?php echo form_radio($_fldProyectoMostrar, "FALSE", set_radio("_FLDPROYDER", "FALSE", TRUE)); ?>NO
<?php echo form_radio($_fldProyectoMostrar, "TRUE", set_radio("_FLDPROYDER", "TRUE", FALSE )); ?>SI
Donde el el segundo valor del set radio, debe ser = al string value del form_radio

Related

submit multiple inputs within a forloop in codeigniter

My code is to fetch questions of users saved in the database by a foreach loop and let the admin answer each question and save the answer of each question after checking of validation rules in the database , Here we go :
Model is :
public function get_questions(){
$this->db->select('id,user_name, question, date');
$this->db->order_by("id", "desc");
$query=$this->db->get('t_questions');
return $query->result();
}
My view is:
foreach ($questions as $id => $row) :
?>
<?php
echo "<h5>".$row->question;
echo "<br>";
echo "from : ".$row->user_name."</h5>";
echo date('Y-m-d H:i');
echo "<br>";
$q_no='save'.$row->id;
$ans_no='answer'.$row->id;
echo "<h4> Answer:</h4>";
echo form_open('control_panel');
?>
<textarea name='<?php echo 'answer'.$row->id; ?>' value="set_value('<?php echo 'answer'.$row->id; ?>')" class='form-control' rows='3'> </textarea>
<input type='hidden' name='<?php echo $q_no ; ?>' value='<?php echo $q_no; ?>' />
<input type='hidden' name='<?php echo $ans_no ; ?>' value='<?php echo $ans_no ; ?>' />
<?php
echo form_error($ans_no);
echo "
<div class='form-group'>
<div >
<label class='checkbox-inline'>
<input type='checkbox' name='add_faq' value='yes' />
Adding to FAQ page .
</label>
</div>
</div>
<p>";
?>
<input type='submit' name='<?php echo 'save'.$row->id; ?>' value='<?php echo 'save'.$row->id; ?>' class='btn btn-success btn-md'/>
<?php
echo 'answer'.$row->id;
?>
<hr>
<?php endforeach; ?>
and my controller is :
$this->load->model('control_panel');
$data['questions']=$this->control_panel->get_questions();
$data['no_of_questions']=count($data['questions']);
if($this->input->post($q_no))
{
$this->form_validation->set_rules($ans_no,'Answer','required|xss_clean');
if($this->form_validation->run())
{
/* code to insert answer in database */
}
}
of course it did not work with me :
i get errors :
Severity: Notice
Message: Undefined variable: q_no
i do not know how to fix it
I am using codeigniter as i said in the headline.
In your controller on your post() you have a variable called q_no you need to set variable that's why not picking it up.
I do not think name="" in input can have php code I think it has to be text only.
Also would be best to add for each in controller and the call it into view.
Please make sure on controller you do some thing like
$q_no = $this->input->post('q_no');
$ans_no = $this->input->post('ans_no');
Below is how I most likely would do lay out
For each Example On Controller
$this->load->model('control_panel');
$data['no_of_questions'] = $this->db->count_all('my_table');
$data['questions'] = array();
$results = $this->control_panel->get_questions();
foreach ($results as $result) {
$data['questions'][] = array(
'question_id' => $result['question_id'],
'q_no' => $result['q_no'],
'ans_no' => $result['ans_no']
);
}
//Then validation
$this->load->library('form_validation');
$this->form_validation->set_rules('q_no', '', 'required');
$this->form_validation->set_rules('ans_no', '', 'required');
if ($this->input->post('q_no')) { // Would Not Do It This Way
if ($this->form_validation->run() == TRUE) {
// Run Database Insert / Update
// Redirect or load same view
} else {
// Run False
$this->load->view('your view', $data);
}
}
Example On View
<?php foreach ($questions as $question) {?>
<input type="text" name="id" value="<?php echo $question['question_id'];?>"/>
<input type="text" name="q_no" value"<?php echo $question['q_no'];?>"/>
<input type="text"name="a_no" value="<?php echo $question['a_no'];?>"/>
<?php }?>
Model
public function get_questions(){
$this->db->select('id,user_name, question, date');
$this->db->order_by("id", "desc");
$query=$this->db->get('t_questions');
return $query->result_array();
}

CodeIgniter validation and checkbox

i have problem with my checkbox i want to add validation but i don't know how should look my name field in validation rule.
My view
<?php
foreach( $tab1 as $row){
?>
<a>
<input type="checkbox" name="<?php echo 'id_user_'.$row->id_user; ?>" value=" <?php echo $row->id_user; ?>" />
</a>
<?php
When i do this i get result (name of the checkbox )for example:
id_user_1
id_user_2
id_user_3
Now i want to add validation but:
$this->form_validation->set_rules(' WHAT SHOULD I WRITE HERE ??? ', 'User','required');
EDIT:
$this->form_validation->set_rules('id_uzytkownika', 'Uzytkownika','required');
if ($this->form_validation->run())
{
$todo = array(
'tytul_projektu'=>$this->input->post('tytul_projektu'),
'opis_projektu'=>$this->input->post('opis_projektu'),
'data_zakonczenia'=>$this->input->post('datepicker')
);
$user_projekty = array(
'id_uzytkownika'=>$this->input->post('id_uzytkownika'),
'id_projektu'=>$this->input->post('id'),
);
$users = array();
foreach($_POST as $key => $value)
{
if(strpos($key, 'id_uzytkownika') === 0)
{
$users[] = $value;
}
}
$this->Todo_model->add($todo,$user_projekty,$users);
VIEW:
<?php
foreach( $tab1 as $row){
?>
<a>
<input type="checkbox" name="<?php echo 'id_uzytkownika['.$row->id_uzytkownika.']'; ?>" value="<?php echo $row->id_uzytkownika; ?>" />
MODEL:
function add($data,$data2,$users)
{
$this->db->insert('projekty', $data);
$id = $this->db->insert_id('projekty');
$data2['id_projektu'] = $id;
$query = $this->db->query("SELECT * FROM uzytkownicy");
foreach($users as $user) {
$data2['id_uzytkownika'] = $user;
$this->db->insert('projekty_uzytkownicy', $data2); }
return $query->result();
}
There are a few approaches you can take with this. Using your existing code, the first would be to create a loop that defines all unique input names.
foreach($users as $user) {
$this->form_validation->set_rules('id_user_'.$user->id_user, 'User','required');
}
However, this logic would require every checkbox to be checked. Which I am not sure in what circumstance this would be used for.
Another approach would be to change your html a little bit.
Instead of
<input type="checkbox" name="<?php echo 'id_user_'.$row->id_user; ?>"
value="<?php echo $row->id_user; ?>" />
you can try using something like
<input type="checkbox" name="<?php echo 'id_user['.$row->id_user.']'; ?>"
value="1" />
This way you could make a form validation rule based on id_user instead of unique names.

Laravel 4 - Input::old for radio buttons

I was wondering if some Laravel guys can help out.
I have a form in which i have 2 radio buttons, when the form submits it goes through the validator, if the validator fails it comes back to the form, populates the fields with the input and displays error messages.
I cant seem to do this for radio buttons, if one is clicked when the form is submitted and there was an error, it comes back to the form with everything filled out EXCEPT the radio button that was checked is now empty.
My radio buttons are as follows:
<input type="radio" name="genre" value="M" class="radio" id="male" />
<input type="radio" name="genre" value="F" class="radio" id="female" />
<span class="error">{{ $errors->first('genre') }}</span>
Any help would be greatly appreciated.
You can try this using Laravel's out of the box HTML radio...
Laravel Docs Form checkboxes and Radio
Using blade,
{{ Form::radio('genre', 'M', (Input::old('genre') == 'M'), array('id'=>'male', 'class'=>'radio')) }}
{{ Form::radio('genre', 'F', (Input::old('genre') == 'F'), array('id'=>'female', 'class'=>'radio')) }}
Or just php,
echo Form::radio('genre', 'M', (Input::old('genre') == 'M'), array('id'=>'male', 'class'=>'radio'));
echo Form::radio('genre', 'F', (Input::old('genre') == 'F'), array('id'=>'female', 'class'=>'radio'));
You could do this:
<input type="radio" name="genre" value="M" class="radio" id="male" <?php if(Input::old('genre')== "M") { echo 'checked="checked"'; } ?> >
<input type="radio" name="genre" value="F" class="radio" id="female" <?php if(Input::old('genre')== "F") { echo 'checked="checked"; } ?> >
The bug is known :
- https://github.com/laravel/laravel/issues/2069
- https://github.com/laravel/framework/issues/1564
You have a temporary solution in the second link.
I've just stumbled into this and I don't want to keep repeating such conditions on every form, so I've created a function on my Helper class.
Helper.php:
class Helper {
// other functions
public static function oldRadio($name, $value, $default = false) {
if(empty($name) || empty($value) || !is_bool($default))
return '';
if(null !== Input::old($name)) {
if(Input::old($name) == $value) {
return 'checked';
} else {
return '';
}
} else {
if($default) {
return 'checked';
} else {
return '';
}
}
// Or, short version:
return null !== Input::old($name) ? (Input::old($name) == $value ? 'checked' : '') : ($default ? 'checked' : '');
}
}
So, now on my forms, I just use it like this:
<label>Please select whatever you want</label>
<div class="radio-inline"><label><input type="radio" name="whatever" value="1" required {{ Helper::oldRadio('whatever', '1', true) }}> One</label></div>
<div class="radio-inline"><label><input type="radio" name="whatever" value="2" {{ Helper::oldRadio('whatever', '2') }}> Two</label></div>
<div class="radio-inline"><label><input type="radio" name="whatever" value="3" {{ Helper::oldRadio('whatever', '3') }}> Three</label></div>
Each option passes its name and value to the helper function and the previously selected one will print 'checked'. Additionally, an option can pass 'true' as the third parameter so it gets selected if there was no old input.
Using with the Bootstrap & Automatic checking
Add this code at end of file: app/start/global.php
//...
Form::macro('radio2', function($group ='group-name', $value_model = 'value-model', $label ='label-radio', $value_radio = 'value-radio', $attrs = array())
{
$item = "<div class='radio'>";
$item .= "<label>";
$item .= Form::radio($group, $value_radio, ($value_model == $value_radio) ? true : false, $attrs);
$item .= $label;
$item .= "</label>";
$item .= "</div>";
return $item;
});
In your view.php
{{ Form::radio2('status', Input::old('status'), 'Online', '1', array()) }}
{{ Form::radio2('status', Input::old('status'), 'Offline', '0', array()) }}
Final result:
I tried simply using Input::get() instead of Input::old().... and it's worked!!{{Form::radio('estado','V',(Input::get('estado')=="V"))}}
My approach is a nested shorthand if/else statement with blade syntax. This solution considers also the initial value that is set in the database.
<div class="form-check form-check-inline">
<input class="form-check-input" type="radio" name="sex" id="male" value="male"{!! ((old('sex') == 'male') ? ' checked="checked"' : ((empty(old('sex')) && $user->sex == 'male') ? ' checked="checked"' : '')) !!}/>
<label class="form-check-label" for="male">Männlich</label>
</div>
<div class="form-check form-check-inline">
<input class="form-check-input" type="radio" name="sex" id="female" value="female"{!! ((old('sex') == 'female') ? ' checked="checked"' : ((empty(old('sex')) && $user->sex == 'female') ? ' checked="checked"' : '')) !!}/>
<label class="form-check-label" for="female">Weiblich</label>
</div>
Tested with Laravel 5.7.

Magento addField() does not give you default checkbox

The module I'm extending adds fields to an admin form using addField(). I copied this behavior as I thought I would try to stick to their setup. However, I can not figure out how to add the "use default" checkbox to the right of any of these fields. This is an issue as I have a field to add that needs to be site-specific.
Code for posterity sake:
$fieldset->addField('enable_coupon', 'select', array(
'label' => Mage::helper('affiliatepluscoupon')->__('Enable Coupon'),
'name' => 'enable_coupon',
'note' => Mage::helper('affiliatepluscoupon')->__('If yes then it will create a magento salesrule for this store.'),
'values' => Mage::getSingleton('adminhtml/system_config_source_yesno')->toOptionArray(),
));
To clarify, I am looking for the dynamic checkbox that gets put by admin fields that changes based on what view you are on. This shows up automatically when creating fields through the XML but seems to be left out when adding fields with addField().
One way you could add a checkbox is
$fieldset->addField('enable_coupon', 'select', array(
....
))->setAfterElementHtml("
<span id='span_use_default'>
<input type='checkbox' value='1' name='use_default' id='use_default' />
Use Default
</span>
");
Also did you check the way they do it in their module?
I know this is a bit late, but I just wanted to post my solution to this and perhaps spark some other ideas. (and feedback on my way of working)
My initial source: http://marius-strajeru.blogspot.be/2013/02/create-system-config-section-with.html
So to add a field (eg: text field):
$field = $element->addField( 'myFieldID', 'text',
array(
'name' => 'groups[model_name][fields][var_name][value]', // this value will be saved to the database as module_name/model_name/var_name and you can get it by Mage::getStoreConfig(..)
'label' => 'Title', // This is the human readable label up front
// See how to get the saved value and define inherit in the link above, this is not in scope for this question. Like this you can't ever see the value that you saved.
'value' => 'My Title', // The initial value
'inherit' => true, // Checks the inherit cb after the field
'can_use_default_value' => true, // Can inherit from default level
'can_use_website_value' => true, // Can inherit from website level
))->setRenderer(Mage::getBlockSingleton('adminhtml/system_config_form_field')); // Use the same renderer as for the system fields (this adds the cb at the end)
This is all you need to do to add a checkbox to your fields.
if you wish to add those gray scope texts (eg: [WEBSITE]):
$field['scope'] = true; // Display scope label
$field['scope_label'] = '[WEBSITE]';
This can be done because the basic Varien Object is defined to implement ArrayAccess
class Varien_Object implements ArrayAccess
now to render the field just go:
echo $field->toHtml();
Look in Mage_Adminhtml_Block_Catalog_Product_Edit_Tab_Inventory
and also catalog/product/tab/inventory.phtml
This looks promising.
<legend><?php echo Mage::helper('catalog')->__('Inventory') ?></legend>
<table cellspacing="0" class="form-list" id="table_cataloginventory">
<tr>
<td class="label"><label for="inventory_manage_stock"><?php echo Mage::helper('catalog')->__('Manage Stock') ?></label></td>
<td class="value"><select id="inventory_manage_stock" name="<?php echo $this->getFieldSuffix() ?>[stock_data][manage_stock]" class="select" <?php echo $_readonly;?>>
<option value="1"><?php echo Mage::helper('catalog')->__('Yes') ?></option>
<option value="0"<?php if ($this->getConfigFieldValue('manage_stock') == 0): ?> selected="selected"<?php endif; ?>><?php echo Mage::helper('catalog')->__('No') ?></option>
</select>
<input type="hidden" id="inventory_manage_stock_default" value="<?php echo $this->getDefaultConfigValue('manage_stock'); ?>" />
<?php $_checked = ($this->getFieldValue('use_config_manage_stock') || $this->IsNew()) ? 'checked="checked"' : '' ?>
<input type="checkbox" id="inventory_use_config_manage_stock" name="<?php echo $this->getFieldSuffix() ?>[stock_data][use_config_manage_stock]" value="1" <?php echo $_checked ?> onclick="toggleValueElements(this, this.parentNode);" class="checkbox" <?php echo $_readonly;?>/>
<label for="inventory_use_config_manage_stock" class="normal"><?php echo Mage::helper('catalog')->__('Use Config Settings') ?></label>
<?php if (!$this->isReadonly()):?><script type="text/javascript">toggleValueElements($('inventory_use_config_manage_stock'), $('inventory_use_config_manage_stock').parentNode);</script><?php endif; ?></td>
<td class="value scope-label"><?php echo Mage::helper('adminhtml')->__('[GLOBAL]') ?></td>
</tr>
Well, this is quite an ugly solution, but maybe it will work for you. First of all, on product pages there is a custom renderer for each element, that is why it is shown there. So, if you have the following element:
$name = $fieldset->addField('name', 'text', array(
'name' => 'name',
'required' => true,
'class' => 'required-entry',
'label' => Mage::helper('some_helper')->__('Name'),
));
you will have to render it with a custom renderer:
if ($name)
{
$name->setRenderer(
$this->getLayout()->createBlock('adminhtml/catalog_form_renderer_fieldset_element')
);
}
At this point you should have the third column with the scope-label class. But the checkbox near it still won't show up. For that we have to set the following for the form:
$storeObj = new Varien_Object();
$storeId = $this->getRequest()->getParam("store");
$storeObj->setId($storeId);
$storeObj->setStoreId($storeId);
$form->setDataObject($storeObj);
Now you should see also the checkbox.
This solution is from:
http://code007.wordpress.com/2014/03/20/how-to-show-the-default-checkbox-near-a-magento-attribute/
OP's solution moved from question to an answer:
The more I look into it the more I realize that the system used with
the XML is a pretty in-depth system that would be kind of ridiculous
to replicate all just to stick with some bad programming practices. I
am going to simply add to the XML.
For those wondering how to do it using addField(), I did figure it
out. Here is my final code:
$inStore = Mage::app()->getRequest()->getParam('store');
$defaultLabel = Mage::helper('affiliateplusprogram')->__('Use Default');
$defaultTitle = Mage::helper('affiliateplusprogram')->__('-- Please Select --');
$scopeLabel = Mage::helper('affiliateplusprogram')->__('STORE VIEW');
$fieldset->addField('enable_coupon', 'select', array(
'label' => Mage::helper('affiliatepluscoupon')->__('Enable Coupon'),
'name' => 'enable_coupon',
'note' => Mage::helper('affiliatepluscoupon')->__('If yes then it will create a magento salesrule for this store.'),
'values' => Mage::getSingleton('adminhtml/system_config_source_yesno')->toOptionArray(),
'disabled' => ($inStore && !$data['name_in_store']),
'after_element_html' => $inStore ? '</td><td class="use-default">
<input id="name_default" name="name_default" type="checkbox" value="1" class="checkbox config-inherit" ' . ($data['name_in_store'] ? '' : 'checked="checked"') . ' onclick="toggleValueElements(this, Element.previous(this.parentNode))" />
<label for="name_default" class="inherit" title="' . $defaultTitle . '">' . $defaultLabel . '</label>
</td><td class="scope-label">
[' . $scopeLabel . ']
' : '</td><td class="scope-label">
[' . $scopeLabel . ']',
));

can't POST data from <textarea> in codeigniter

I have been trying to retrieve this data from a textarea using post, but i keep geeting no data back. any help would be appreciated.
Here is my form
<?php echo validation_errors(); ?>
<?php echo form_open('s2e/contactValidation'); ?>
<ul>
<li><label>Subject<input type="text" id="emailsubject" name="subject" placeholder="example#site.com" width="200"></label></li>
<li><label>From<input type="email" id="emailfrom" name="from" ></label></li>
<li><label>Message</label><textarea id="message" name="message" rows="6" cols="200" form="contact" ></textarea></li>
</ul>
<button type"submit" name="sendemail">Send</button>
</form>
My controller looks like this
public function contactValidation(){
$this->load->library('form_validation');
$this->form_validation->set_error_delimiters('<div id="rerror">', '</div>');
$this->form_validation->set_rules('subject', 'Subject', 'trim|required|xss_clean');
$this->form_validation->set_rules('from', 'From', 'trim|required|valid_email');
$this->form_validation->set_rules('message', 'Message', 'trim|required');
$subject = $this->input->post('subject');
$from = $this->input->post('from');
$message = $this->input->post('message');
if($this->form_validation->run() == FALSE)
{
print_r('failed');
} else {
print_r('good');
}
var_dump($subject);
var_dump($from);
var_dump($message);// this is the culprit that's failing
}
Any help would be appreciated
Why don't you use Codeigniter's Form Helper:
<?php
echo validation_errors();
echo form_open('s2e/contactValidation');
echo form_labe('Subject', 'subject');
echo form_input('subject', 'Value Here', 'id="" placeholder=""');
echo form_label('Email', 'email');
echo form_input('email', '', 'attributes=""');
echo form_textarea('msg', '')
echo form_submit('submit', 'Send Form');
echo form_close();
?>

Resources