Convert Laravel validation rules to html form fields - validation

Say I have a validation rules for some Model, for example validation for a person model will be:
'first_name' => ['required', 'string'],
'last_name' => ['required', 'string'],
'birthday' => ['before:today', 'date'],
'salary' => ['min:0', 'max:2000', numeric],
....
So if I wrote that rules, it feels wrong to write the same rules manually but for the HTML form fields like:
<input type="text" name="first_name" required />
<input type="text" name="last_name" required />
<input type="date" name="birthday" max="2016-06-09"/>
<input type="number" name="salary" min="0" max="2000"/>
So if the product owner ask me for change the rules like changing the mandatory fields, or even change the maximum salary from 2000 to 5000, I have to change it manually in the validation rules and the form itself.
So it makes me wonder, is there any automatic way to convert Laravel validation rules to the HTML form fields?

You have to parse your rules, then loop on the parsed datas for building a form. And then, I suggest you to use partial views for doing the trick.
I already did this for building automatic forms and documentations. So i wrote a Laravel package here : https://github.com/Ifnot/ValidationParser.
In the example of my package you just have to create two files :
A form blade view (contains the code for parsing the validation)
A field blade view (used for display a form item)

To have the validation rules be in one place, set the rules to variables. Then, pass the variables into the laravel validation page and in your blade template (html).
So, where you are setting the variable:
$MaxSalary = 2000;
Next, pass in your variable to the Laravel form validation rules:
'salary' => ['min:0', "max:$MaxSalary", numeric],
Then, pass it into your blade template form:
return view('form', ['MaxSalary' => $MaxSalary]);
Then, in your blade template, use the variable:
<input type="number" name="salary" min="0" max="{{ MaxSalary }}"/>

I had problems finding some one else thinking about this same idea. I must have not been using the right terms for the search. I implemented this same concept today 2023 in the following project: https://github.com/arielenter/ValidationRulesToInputAttributes
In it, I'm using laravel's Illuminate\Validation\ValidationRuleParser to explode and parse the rules, and later I used a 'translator' that convert applicable rules to input attributes.
My concern is why it seems nobody has made a laravel package that can do this on 2023. I'm not sure if I'm up to the task, but if nobody has done it I'll try. I just think it'll be very odd if nobody more capable has done it. The most difficult part I think would be to make an extend dictionary for every possible attribute that could be apply depending of the rule. I might end up leaving to the user to provide its own dictionary or something, but some cases are conditional so I'm not sure if that could work. For now I'll just keep adding translation every time I need it.

Related

Laravel Livewire wire:model binding time attributes to input type="time"

I understand how to bind dates to <input type="date"> (as of v2.3 of Laravel Livewire), by adding the cast date:Y-m-d to a model's attribute. However, I can't find any information on whether it is similarly possible to bind a model's time attribute (i.e. an attribute with datatype of TIME) to <input type="time"> through a cast to datetime (with some appropriate serialization format). Is this possible? Or has it not been implemented in Livewire as of yet?
I've experimented with a few different variations of casts and serialization formats myself, none have worked so far.
Casting the time attribute to H:i
In the model, I cast the time attribute (in the database it has the time datatype, and it can be interpolated into blade templates fine using any of the options available to Carbon as usual) to datetime, with the format H:i which is 24 hour time with leading zeroes as per the value usually required by <input type="time">. [0]
The model's $casts field looks like this:
protected $casts = [
'time' => 'datetime:H:i',
];
The view has this input field:
<input type="time" wire:model="item.time" />
This does not work (the input remains blank).
I also tried this with the format set to H:i:s, H-i, H-i-s, Hi, His, none of which work either.
Whoops! Seems I had simply forgotten to add a validation for the time attribute in the Livewire. By adding the rule:
public Item $item;
protected $rules = [
'item.time' => 'required|date_format:H:i',
];
and using either H:i or H:i:s for the format, the attribute was bound. This may have something to do with the way I validate my fields in this Livewire as well.
I suspect that in general any input with a value can be bound as long as the attribute is cast to the correct value.

How to save JavaScript generate value into mysql? [Laravel]

I made contact form in Laravel.
some of input field are just normal input field.
And rest of them are JS generate data which are 'product', 'quantity' and 'price'.
I can store ONLY normal input field data.
Here is my dd() image.
And this is my blade file.
<select id="product" name="product" onchange="caliculate()"></select>
<input id="v_product" type="hidden" name="product">
Controller
//Store data in database
Contact::create($request->all());
Could you teach me how to store product, quantity and price data into Mysql please?
If you want to exclude the other fields when getting request parameters, you can do the following:
Contact::create($request->only(['product', 'quantity', 'price']));

Laravel 4 - Showing edit form with OLD data input as well as DB information

Im making a edit form for my app and i was wondering if someone could tell me how to get the data from the database into my text field.
I can locate the record i need to edit based on the users click, and i can display the information if i do the following:
value="{{ $letter->subject }}"
BUT, the problem im having is that when i run it through the validation and there is an error, it comes back with the database information instead of the OLD data.
So my questions is. Is there a way to serve up the database information first and then when it goes through the validatior, validate the information the user has edited?
Currently to validate the text field and bring the data back incase of error, im using
Input::old('subject')
Is there a parameter for that old bit that allows me to put in the DB data?
Cheers,
Hey you could validate and return ->withInput() and then in your actual form, check if there is Input::old() and display it, otherwise display from the db.
example:
<input type="text" name="subject"
value="{{ (Input::old('subject')) ? Input::old('subject') : $letter->subject }}">
Or you could go the other way and define the variable and do a regular if statement, instead of the ternary one! Up to you to decide what you want to use!
All you need is form model binding http://laravel.com/docs/html#form-model-binding:
{{ Form::model($letter, ['route' => ['letters.update', $letter->id], 'method' => 'put']) }}
// your fields like:
{{ Form::text('someName', null, ['class' => 'someHTMLclass' ...]) }}
// no default values like Input::old or $letter->something!
{{ Form::close() }}
This way you form will be populated by the $letter data (passed from the controller for example).
Now, if you have on your countroller:
// in case of invalid data
return Redirect::back()->withInput();
then on the redirect your form will be repopulated with input values first, not the original model data.
Make it more simple and clean
<input type="text" name="subject" value="{{ (Input::old('subject')) ?: $letter->subject }}">
I'm not sure for Laravel 4 but in Laravel 5, function old takes second param, default value if no old data in session.
Please check this answer Best practice to show old value

How can i put HTML5 required field using form_input() function in Codeigniter framework

I am new in codeigniter.But now i am developing a project using codeigniter.
My Html code like this:
<input type="text" class="get_started_frm_reg" name="first_name" required />
Now i want to convert it through function form_input() function.I wrote my code like that
$first_name=array(
"name"=>"first_name",
"class"=>"get_started_frm_reg",
"type"=>"text"
);
But i don't understand how can i put required field.Please help me.
$first_name=array("name"=>"first_name",
"class"=>"get_started_frm_reg",
"type"=>"text",
"required"=>"required");
This is working
I would recommend the following:
form_input('first_name', $value, 'class="get_started_frm_reg" required');
// if you don't want to pass a variable for value, pass 'null'
form_input('first_name', null, 'class="get_started_frm_reg" required');
The above will output exactly how you were asking in your question.
I like using this method better then passing an array to form_input because you have better control over boolean input values, like required. Also, you don't need to pass text="type" since it is the default on form_input.
The best is to use it like this:
<?=form_input(['name'=>'first_name', 'class'=>'get_started_frm_reg'],'','required');?>
Produces:
<input type="text" class="get_started_frm_reg" name="first_name" required />

adding class and id in form_dropdown

Is there any possible way of adding class and id attributes in form_dropdown of CodeIgniter?
I tried form_dropdown('name',$array,'class','id') and it's not changing anything, please tell me how to implement it?
Edited:
with my dropdown form like this form_dropdown('name',$array,set_value('someValue'),'id="myId"'); if I see my source from my browser it's look like this <select name="provinsi" id="provinsi_id">, but if I write like your way form_dropdown('name',$array,set_value('someValue'),'class="myClass"','id="myId"'); than like this in my browser source <select name="provinsi" class="myClass">
that was I mean
thank you
Like this:
form_dropdown('name', $array, '', 'class="my_class" id="my_id"')
The third parameter is for the value you wish to be selected and the fourth is for the additional data. Read more.
You can defined class, id or any other HTML attribute in the forth parameter of form_dropdown() function as an associative array like below:
form_dropdown('name', $array, set_value('someValue'), ['class' => 'myClass', 'id' => 'myId']);

Resources