Grouping a checkbox with a corresponding input field - php

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

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.

How to submit unchecked checkboxes to controller

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.)

Allow users to update their gravity form single unique entry

I am trying to make a form which will allow them to update their entered unique entry. Suppose there is form which is used to collect, the User Specializations
And this Specializations field is gravity forms multiselect field which is dynamically set. And as they update their specializations also updated in entries tab.
So, i just want to allow they to have this multiselect field updation.
I came across a solution to add multiselect choice dynamically but that only populate the field with all the choices not the user selected also.
So, is there is way to set the user entered choices dynamically?
Possible Solution:
Like we can get the entries and then set search criterion to current user and will get a unique entry and then after we can set these selected values in the choices.
Issue Exists with the above possible solution:
but still there is issue like it will be creating new entry as form dont know it is update operation. So can anyone help?
//Auto Populate Service Field in Form ID=
add_filter('gform_pre_render_2', 'populate_services');
add_filter('gform_pre_validation_2', 'populate_services');
add_filter('gform_pre_submission_filter_2', 'populate_services');
add_filter('gform_admin_pre_render_2', 'populate_services');
function populate_services($form)
{
foreach ($form['fields'] as &$field) {
if ($field->type != 'multiselect' || strpos($field->cssClass, 'populate_services') === false) {
continue;
}
$services = get_specializations();
$choices = array();
foreach ($services as $service) {
$title = stripslashes($service->name);
$choices[] = array(
'value' => $service->ID,
'text' => esc_html($title)
);
}
// update 'Select Duration' to whatever you'd like the instructive option to be
$field->placeholder = 'Select Services';
$field->choices = $choices;
}
return $form;
}

How to create dynamically disable a single check box of checkboxlist in YII

In a form, I have checkboxlist which has two check box (Male and Female)
User can select both of them or any of them. And values are getting save in DB.
When we populate it from DB then I want to do like if male was selected then it should select Male checkbox and disable the Female checkbox or vice versa.
The code in my View file is:
<?php if(isset($model['gender'])){
$data = $model['gender'];
if (isset($data)) {
if($data == 0)
$htmlOptions = array(
'0' => array('label'=>'MALE'),
'1' => array('disabled'=>'disabled','label'=>'FEMALE'),);
}
if($data == 1){
$htmlOptions = array(
'0' => array('disabled'=>'disabled','label'=>'MALE', ),
'1' => array('label'=>'FEMALE'),);
}
}
echo $form->checkBoxList($model, 'gender', $htmlOptions); ?>
Problem is when I am populating it is selecting the one,I selected while saving but not disabling the other one.
For this you have to use javascript because there is no way you can handle it only with PHP. Now I don't know that much JS, but the steps are easy:
Get the checkbox id's
check which one is selected
disable the other one with innerHTML in JS.
Here you have an example on how you disable checkboxes in JS
Just so you know, the JS should be placed inside the view.

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