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

别来无恙 提交于 2019-12-06 07:21:52

问题


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,


回答1:


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.




回答2:


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!




回答3:


Make it more simple and clean

<input type="text" name="subject" value="{{ (Input::old('subject')) ?: $letter->subject }}">



回答4:


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



来源:https://stackoverflow.com/questions/23762841/laravel-4-showing-edit-form-with-old-data-input-as-well-as-db-information

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!