How do I validate a checkbox array in laravel? - html

I've been trying to validate all 10 checkbox array items but I cannot seem to find or understand how to use Laravels validator to validate a checkbox array.
The below code is my array HTML.
<div id="CLAagree" style="display: none;">
<div class="form-group form-check">
<div class="col-sm-2">
<div class="checkbox checkbox-green ck-button">
<input type="checkbox" class="form-check-input" oninput="this.className = ''" name="claAgree[]" id="CLAagreeCB1" onclick="saveOnboard()" >
</div>
</div>
</div>
I have tried to get all info that I can about this but I just can't seem to understand arrays in validation for some reason.
I know adding "required" made the inputs required but I have 10 so at least one will be required but I need 10 to be required. Does anyone have any options? I'm just lost at this point lol
$rules = array(
"claAgree" => "required",
"claAgree.*" => "required",
);
$validation = Validator::make($request->all(),$rules);
if($validation->fails()) return back()->with('error',$validation->messages()->first());
Here is a link to show how the array is posted

You can do like that ,check you request array name (claAgree.*.claAgree) ,
then define the input value , if same then you can use same like that
$rules = array(
"claAgree" => "required",
"claAgree.*.claAgree" => "required",
);
$validation = Validator::make($request->all(),$rules);
if($validation->fails()) return back()->with('error',$validation->messages()->first());

Related

How to change the field value in update form in Yii2

In my update form, I want to show the original value rather than it's id. Below is my _form.
<div class="mdc-meter-config-form">
<?php $form = ActiveForm::begin(['id'=>'con','options' => ['enctype' => 'multipart/form-data']]) ?>
<label class="control-label">Select Meters</label><br />
<input type="text" id="the-mter-id" class="form-control col-md-12" value="<?=$model->meter_id?>" />
<div style="clear: both;"></div>
<div id="selected_mters_container"></div>
<div style="clear: both;"></div>
<br/>
<?= $form->field($model, 'p_id')->dropDownList([''=>'Please Select']+\common\models\MdcProtocol::toArrayList()) ?>
<?= $form->field($model, 'time')
->dropDownList([''=>'Please Select','5' => '5', '10' => '10', '15' => '15','20'=>'20'])->label("Set Time (in seconds)") ?>
<div class="form-group">
<?= Html::submitButton(Yii::t('app', 'Save'), ['class' => 'btn btn-success']) ?>
</div>
<?php ActiveForm::end(); ?>
In above view I want to change the 2 value to its actual one which is 4A60193390662
Dont know why you are not using the relation here for the meter to display the meter serial rather than the id.
Easiet way to avoid any further work as you want to just display it, 2 things you need to do
Assign the value to the input manually via relation.
Make the field disabled to exclude it out of the model collection array. (in case you use active form for the field).
I assume you have a relation to the meter in your current model with name getMeter() and the number you are trying to display 4A60193390662 is in field serial_number. You can change accordingly.
If you havent defined a relation than define one now
public function getMeter(){
return $this->hasOne(Meter::class,['id'=>'meter_id']);
}
Although you are using a custom html field you can still use the active form and mark the field disabled so that the activeform wont submit it with the model collection array and there wont be errors when saving the records like
meter_id should be an integer.
echo $form->field($model, 'meter_id')->textInput(['disabled' => 'disabled', 'value' => $model->meter->serial_number]);
try add an entry also for the field with value 4A60193390662 eg: $model->meter_name
<input type="text" id="the-mter-name" class="form-control col-md-12" value="<?=$model->meter_name?>" />
and if you don't want see the entry for meter_id .. you could use hidden input for this so mantain the related avlue for the model loading and popolation
And as suggested in comment by Michal Hyncica (sorry for improper charset ) you could wrap the input inside a check fo new record
<?php
if(!$model->isNewRecord) {
echo '<input type="text" id="the-mter-name" class="form-control col-md-12" value="' . $model->meter_name . '" />';
}

angular 2 validation on dynamic generated fields in loop

I have a list of input fields that are generated with a model. I am trying to add validation to them.
The requirement is they should not be empty or less than 2 characters.
problem is in the documentation only shows validation with non-dynamically generated variable Name. My fields are all generated dynamically. So there is no tempVariableName I can hardcode (otherwise they conflict), so I created temp variable from the name of the property I binded the field to. So I came up with something like this :
<div *ngFor="let field of connector.configFields">
<label>{{field.name}}</label>
<input [(ngModel)]="field.value" [type]="field.name === 'Password' ? 'password' : 'text'"
placeholder="{{field.name}} (required)"
ngControl="[fieldName+field.name]"
required minlength="2"
#fieldName+[field.name]="ngModel" />
<div *ngIf="(fieldName+[field.name]).errors && ((fieldName+[field.name]).dirty || (fieldName+[field.name]).touched)">
<span *ngIf="(fieldName+[field.name]).errors.required">Enter Name</span>
<span *ngIf="(fieldName+[field.name]).errors.minlength">Name minimum at 2 characters</span>
</div>
</div>
and the configFields in typescript look like this :
export class FieldModel {
public name: string;
public type: string;
public value: any;
}
But this simply would not work. I am new to angular 2 so I am not exactly sure what I did wrong.
You can use the unique index for each field in the array. Use this together with the name attribute (and ngModel) which will evaluate each form controls separately. So each input field gets the unique name, eg:
name="f{{i}}"
where we get {{i}} from the iteration:
<div *ngFor="let field of connector.configFields; let i = index">
So finally, your template could look like this:
<form #myForm="ngForm">
<div *ngFor="let field of connector.configFields; let i = index">
<input name="f{{i}}" [(ngModel)]="field.value" [type]="field.name === 'Password' ? 'password' : 'text'" required #f="ngModel" minlength="2"/>
<div *ngIf="f.errors && (f.dirty || f.touched)">
<div *ngIf="f.errors.required"> This field is required </div>
<div *ngIf="f.errors.minlength"> Min 2 chars </div>
</div>
</div>
</form>
Here's a live
Demo
Prepare data in model and return to angular. Angular and hard logic in the template = bad friends.
But if you have a select option and if has *ngFor for option then error message loses its mapping, due second *ngFor loop
better to define custom class for error message and use css display: none or **block*
.custom-valid-box{
display: none;
}
.form-control-danger + .custom-valid-box{
display: block;
}

HTML Form: POST an array of objects

Submitting a class roster. Adding 3 students at once. Each student has first, last, age.
Question: How can we get all of the students in an array of arrays?
students[0] => Array (
["first"] => "first name for 0",
["last"] => "last name for 0",
["age"] => "age for 0"
),
students[1] => Array (
["first"] => "first name for 1",
["last"] => "last name for 1",
["age"] => "age for 1"
),
...
Details
For one student:
<input type="text" name="first">
<input type="text" name="last">
<input type="text" name="age">
We can return multiple students in separate arrays like this:
<input type="text" name="students[first][]">
<input type="text" name="students[last][]">
<input type="text" name="students[age][]">
which returns an array of firsts, lasts and ages
students["first"] = [array of first names]
students["last"] = [array of last names]
students["age"] = [array of ages]
Theoretically we can get all the info for a student by accessing the same index (say "3" for each array).
We do not want to programatically add an index in the form.
Do not want:
<input type="text" name="students[hardcoded_index][first]">
<input type="text" name="students[hardcoded_index][last]">
<input type="text" name="students[hardcoded_index][age]">
If for any reason it matters, we are using Rails for views but can use form helpers or HTML.
tl;dr: Add empty brackets ([]) after students to the input names.
Fiddling with Rack::Utils.parse_nested_query it seems you can get the payload you want like this:
<!-- first student -->
<input type="text" name="students[][first]">
<input type="text" name="students[][last]">
<input type="text" name="students[][age]">
<!-- second student -->
<input type="text" name="students[][first]">
<input type="text" name="students[][last]">
<input type="text" name="students[][age]">
Note the empty brackets ([]) after students. This tells Rack you want the students param to be an array. Subsequent params encountered (with the same name) will start a new element.
POST /myroute?students[][first]=foo&students[][last]=bar&students[][age]=21&students[][first]=baz&students[][last]=qux&students[][age]=19
Gets parsed like this:
{"students" => [
{
"first" => "foo",
"last" => "bar",
"age" => "21"
},
{
"first" => "baz",
"last" => "qux",
"age" => "19"
}
]}
Further reading: http://codefol.io/posts/How-Does-Rack-Parse-Query-Params-With-parse-nested-query
I know the question is old , but I would like to add my experiences
also for future readers.
For those of you who want to process the data in a PHP enviroment ,
#messanjah's method won't work ,
The methods for parsing data like the built-in serializeArray or serialize are not parsing it as expected either.
This is what I tried so far ...
students[name]
students[][name] - Very Strange since it was meant to automatically index the array
students[name][]
Neither of them worked, but this students[<hardcoded-index>][name] worked for PHP ,
I know that although the question is against this method , but it
will be useful for PHP users who will land here in the nearby future
as the asker needed it for Ruby On Rails.
The method you choose to hard code the indexes is upto you , you can use a cleaner method by using javascript or you can manually hard code them initially in your form element.
Cheers

Yii2: how to stop inbuilt id generation by yii2 for each field in form

When i am adding form to view & specifying parameters as
<?= $form->field($model, 'form_name', ['options' => ['id' => 'formName', 'name' => 'formName']])->textInput(); ?>
But, when i run in the browser & check for view page source, there it shows me
<input type="text" id="submitform-form_name" class="form-control" name="SubmitForm[form_name]">
this disturbs my javascript calling for field input. How to stop yii2 from generating its own id???
You are passing options to ActiveField. If you want override id and name attributes, pass them in textInput() options like so:
<?= $form->field($model, 'form_name')->textInput(['id' => 'formName', 'name' => 'formName']) ?>
Generated html output will be:
<input type="text" name="formName" class="form-control" id="formName">
Note that after that client validation for this attribute will stop working and that attribute won't be massively assigned.

Formgenerator with div

I want to create forms in symfony2. I need this HTML structur for each control.
<div class="form-group">
<label class="col-md-2 control-label">Firstname:</label>
<div class="col-md-10"><input type="text" name="firstname" class="form-control">/div>
</div>
Now is my question, how can i add the div with the class form-group and how can i surround the input element with the div .col-md-10?
$builder->add('firstname', 'text', array(
'attr' => array(
'class' => 'form-control'),
'label_attr' => array(
'class' => 'col-md-2 control-label'
)
)
);
Check How to customize Form Rendering section of the documentation.
You may need to override the form_widget block (form_widget_compound block to go into details).
Find here the default behavior of each twig form helper.
The Form Theming Sub Chapter contains many relevant examples on how to customize any given form field block.