How to submit unchecked checkboxes to controller - php

Ok first I have a "settings" table on my database in which I have the fields "name" and "value" its a configuration kind of table where the value could be anything from string to boolean values etc.
Now on my blade, I have a form with various inputs "texts" "selects" "checkboxes" etc. When submitting the form on the controller I run a foreach where for each attribute of the $request I store its key as the name and its value as its value on the database.
$agency_id = Auth::user()->agency->id;
$settings = AgencySettings::whereAgencyId($agency_id)->get();
foreach ($request->except('_token') as $key => $value)
{
$setting = $settings->where('name','=',$key)->first();
if (boolval($setting))
{
$setting->value = $value;
$setting->update();
}else{
$setting = new AgencySettings;
$setting->agency_id = $agency_id;
$setting->name = $key;
$setting->value = $value;
$setting->save();
}
}
All works well except the unchecked checkboxes which are not inside the $request.
I know I can handle them like so $request->has('name_of_checkbox') but because of the dynamic nature of the table on the database, I don't want to have hardcoded on my Controller the name of a specific setting.
My goal is that the code on my Controller will be the same regardless the number of different settings I will use on my frontend (maybe in the future there will be a need to add more).
So my question, is there a way to handle those checkboxes serverside without having to refer to them specifically, or a way to always return the value of the checkboxes to the server despite its state?
My first thought is to go with javascript and hidden inputs, but maybe there is a better way.

You could add a hidden field with the same name before every checkbox you want to receive, like :
<input type="hidden" name="checkbox-1" value="0" />
<input type="checkbox" name="checkbox-1" value="1" /> My checbox 1
That will send the hidden field with the 0 value when the field is unchecked and send the proper truthy value when it's checked.
NOTE: Just make sure you're adding the hidden field first so you'll receive just the checked one when the field is checked.

Other solution is to simply check if value for "checkbox-1" is set in post array.
So you will set default to 0 on your controller side and check if value exists instead of checking if it is 0 or 1.
(M.)

Related

Gravityforms populate selected value on dropdown within theme functions.php

I am working in gravityforms to pre-populate a form with database values dynamically, which is working. I need to be able to specity which of these options is selected by default when the form is built, but I can't find the option to do so. I have seen the placeholder, but I presume this doesnt actualy select anything on the dropdown. I have been unable to find any docs or references that allow me to set the "selected" options once I have built all the text/value pairs in the array and set the choices.
The function (which I have redacted here) works fine and populates the field, I just need to populate a placeholder and/or default selected value.
add_filter('gform_pre_render_1', 'getFieldValues');
add_filter('gform_pre_validation_1', 'getFieldValues');
add_filter('gform_pre_submission_filter_1', 'getFieldValues');
function getFieldValues($form) {
global $wpdb;
foreach ($form['fields'] as $field) {
if ($field->id == '40') {
// get the list of values from the Database
$list1Q = "SELECT <data> FROM <table> WHERE <params> = <value>";
$list1R = $wpdb->get_results($list1Q);
// Generate a nice array that Gravity Forms can understand
if (!empty($list1R)) {
$list1A[] = array();
foreach ($list1A as $listItem) {
// Add current value to the array for dropdown choices
$list1C[] = array('text' => $listItem->variable, 'value' => $listItem->variable);
}
}
// Set choices to field
$field->choices = $List1C;
***** THIS IS WHERE I WOULD LIKE TO SET THE SELECTED VALUE *****
}
}
return $form;
}
If there is a better way to go about populating this field, I am open to suggestions at it seems that the form loads a bit slow using this method. Otherwise, I would love to know how to set a selected choice value after populating the choices.
the quick answer is, there is an option that i found for "isSelected" that can be included in the array when defining choices. I added a ternary operation to match on what I wanted selected and it set the "selected value for me.
$isSelected = ($listItem->variable == "value I want to select") ? true : false;
$list1C[] = array('text' => $listItem->variable, 'value' => $listItem->variable, 'isSelected' => $isSelected);
Adding the ternary choice and changing the array push allowed me to set a value as selected.

Grouping a checkbox with a corresponding input field

I am trying to find a way to group a checkbox and input field so a user can only input data into the field if the checkbox has been selected. I currently have a generated checkbox field (values from table) with a corresponding input field.
My current solution is:
#foreach($labourTypes as $id => $name)
<div class="checkbox">
<label>
{!! Form::checkbox("labour_types[]", $id) !!} {{$name}}
</label>
{!! Form::input('number', 'required_labour_type_hours[]', '') !!}
</div>
#endforeach
And for inputting into the database:
$required_labour_hours = array_filter($required_labour_hours);
$required_labour_hours = array_values($required_labour_hours);
foreach(array_combine($labour_types, $required_labour_hours) as $labour_type => $hours) {
DB::table('required_labour_type')->insert([
'id' => null,
'labour_type_id' => $labour_type,
'required_labour_type_hours' => $hours
]);
}
This is my current workaround, but it does not prevent (and messes up inserting) if the user were to fill out an input field that does not have the corresponding checkbox ticked.
This is what it looks like at the moment:
http://i.imgur.com/sVhnFMc.png
I am trying to find a way to make it so input is only allowed if the corresponding checkbox is selected, or to group them into an array prior inserting, and drop the ones that have no checkbox selected before inputting? I am new to laravel and php in general, so I am having a hard time coming up with a fool-proof workaround.
Thanks.
I would use jQuery on the front end to control the input from the user. I would also validate the data on the server side just be to safe. Using jQuery, you could easily make the input fields readonly if the checkbox was not checked, and update as needed. This code assumes that the input field is one of type="text". You could easily update to support multiple input types.
jQuery(document).ready(function($) {
$('.checkbox').each(function() {
var cbox = $(this).find('input[type=checkbox]'),
inp = $(this).find('input[type=text]');
cbox.on('change', function(evt) {
if( $(this).is(':checked') )
inp.removeAttr('readonly');
else
inp.attr('readonly', true);
});
//init
if( ! cbox.is(':checked') )
inp.attr('readonly', true);
});
});
On the server side, this would be as simple as checking for the existence of the checkbox. If a checkbox is not checked, it is not sent to the server during the form submission. So using something like:
if( isset($_POST['some_checkbox']) ) {
//sanitize, validate, and save the value of the corresponding text field
} // else do nothing with this text field

How to set default values for CodeIgniter Form Validation?

I know to use set_value() for setting default values in a CodeIgniter form, but how can I set the default values for the validation if either the value isnt submitted or its before a form submission?
public function index($uri = NULL)
{
$this->load->helper('form');
$this->load->library('form_validation');
//pull from DB or Session
$data = array(
'Status' => 'users_default_status',
'Order' => 'users_default_order',
'Asc' => 'users_default_asc'
);
$this->form_validation->set_data($data);
$this->form_validation->set_rules('Status', 'Status', 'numeric|trim|required|strtolower');
$this->form_validation->set_rules('Order', 'Order', 'trim|required');
$this->form_validation->set_rules('Asc', 'Asc', 'trim|required|strtolower');
if ($this->form_validation->run() === FALSE) // validation failed
{
// validation failed but maintain submitted values in form/feedback
}else{
// validation successful, do whatever
}
}
So that if there was a form submission it uses the POST values, and if not it uses defaults (but still validated). I would like the defaults to work on a variable by variable basis, so some can be defaults some can be user submitted.
I know to use set_value() for setting default values in a CodeIgniter form, but how can I set the default values for the validation if either the value isn't submitted or it's before a form submission?
Simply check if the value exists and use it as the default, otherwise it's blank (or a different default).
In the Controller, decide if you're going to load a blank form, if not, send the data for the fields....
$data['fieldname'] = "whatever"; // from the database
$this->load->view('yourpage', $data);
Then in your View, check for the existence of this data for each field. If the data was sent, use it. Otherwise, set a blank value.
<?php $value = isset($fieldname) ? $fieldname : ''; ?>
<input name="fieldname" value="<?php echo set_value('fieldname', $value); ?>" type="text" />
If you do not send the data from the Controller, the field will be blank (you could also set a default)
If you send the data from the Controller, the field will be filled out with this data from your Controller (database).
If you submit the form and validation fails, set_value() function will reload the field with the data from the most recent post array.
These are just some thoughts...
The validation rules act upon the posted data. So if you are using set_value('order',$default_order), when the form is submitted it will either take the new user entered value or the one you provided.
If the user empties a prefilled or default input, you can't have it set as "required" in the rules. What you would do is use a callback function to handle that case to check if it's empty and provide a default value and return TRUE.

Should I use set_value() to repopulate a form in CodeIgniter

My question is whether I should use set_value() at all to re-populate a form. It might seem odd to say that, however I am creating a shared controller function and view which can be used to either add a new record or edit an existing one. It seems to make sense to do this since the functionality is so incredibly alike.
As such, if we call up an existing record to edit I do this:
$data['fields'] = $this->customer_model->get_customer($id);
If the form is submitted to save the record, or if we're adding a record for the first time, the form has the potential to reload if the user makes a mistake so I populate $data['fields'] this way instead:
$data['fields'] = array(
'company' => $this->input->post('company') ?: '',
'website' => $this->input->post('website') ?: '',
'credit_limit' => $this->input->post('credit_limit') ?: ''
);
My form element looks like this:
<input type="text" name="company" value="<?php echo set_value('company', $fields['company']); ?>" />
But I'm thinking it may as well look like this:
<input type="text" name="company" value="<?php echo escape_html($fields['company']); ?>" />
Since the form data could come from either user input (when adding or saving) or from the database (when retrieving a record to edit) I cannot rely entirely on post() or set_value() without the 2nd parameter. Furthermore, the second parameter for set_value() will always exist ($fields['company'] in this example) because it's initialized from the start, which is why I am thinking of just using it directly.
Is there a problem with this approach?
If you want to populate form fields on FALSE return of Form Validation or insert data for editing operations, I suggest you to use following helper:
Usage
<input type="text" name="last_name" value="<?=vset_value('last_name','',$rs);?>">
Explanation
$rs here is the $db data for record (if you are sending it to view). To stay at the safe side please include $this->data['rs'] = false; at your controller. If $rs is set and true, helper take results from it and display it. Otherwise it displays if the key exist in $_POST. If both don't exists, it display default value.
Helper
/**
* vayes_helper::vset_value
*
* Retains state of INPUT text after Form Validation
*
* #access public
* #param string name of INPUT tag
* #param string default value for INPUT tag
* #param mixed DB Result (array or object)
* #return string
*/
if(!function_exists('vset_value')) {
function vset_value ($name_of_input,$default_state='',$db_result_array='') {
$CI = &get_instance();
$render_state = $default_state;
if($CI->input->post()) {
$render_state = $CI->input->post($name_of_input);
} else {
if(is_object($db_result_array) && isset($db_result_array->$name_of_input)) {
$render_state = (isset($db_result_array->$name_of_input)) ? $db_result_array->$name_of_input : $default_state;
} else if($db_result_array != '' && array_key_exists($name_of_input,$db_result_array)) {
$render_state = (isset($db_result_array[$name_of_input])) ? $db_result_array[$name_of_input] : $default_state;
}
}
return $render_state;
}
}
If you like the way, let me know. I can supply for more form input type like select, checkbox, etc.
The approach is correct, as mentioned in the CodeIgniter docs. In fact, you don't need to include the second parameter in set_value.
set_value definition:
string set_value(string $field = '', string $default = '')
//$field: If there is a submitted field with this name, its value is returned.
//$default: If there is no matching submitted field, this value is returned.
Yes,You should.
set_value() is used to re-populate a form has failed validation.
There is no additional filtering on it, so it faster.
But, I prefer some times to use $this->input->post() for the secure.

how to set an option for form->input( 'multiple'=>'checkbox')

i plan to set a checkbox with selected option in my form.
but i am unable to show my checkbox content in the form, i cant see any value instead of just a box for me to select.
how to show value while i using checkbox? i able to show my value while i using select.
this is in a HABTM model. any hints?
here is my selection code.
input('User',array('label'
=> 'Select Related Potential',
'multiple'=>'checkbox',
//'options' => $users,
'legend'=>$users,
//'value'=>$users,
//'id'=>$ownUserId,
'default'=>$ownUserId,
'style'=>'width:200px;height:100px',
'selected' => $ownUserId, )); ?>
This may be relevant:
You cannot use default to check a checkbox - instead you might set the value in $this->data in your controller, $form->data in your view, or set the input option checked to true.
For example:
// in Controller
$this->data['Model']['field'] = true;
Causes the field to have the value true, which will result in a checked checkbox for this field.
Or:
$form->input('Model.field', array('checked' => true));
Always checks the checkbox.
Or:
$form->input('Model.field', array(
'checked' => ($this->data['Model']['field'] == 'xxx')
));
Dynamically sets the checkbox based on whether $this->data['Model']['field'] is 'xxx' or not.
Sorry, completely misunderstood the question.
Did you find your users via list? The options array needs to be in a particular format, a normal find() won't do that.

Categories