Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Define default values for Laravel form fields

To pre-populate form field, we can add 'value' to form field in create.blade.php:

{{ Form::text('title', 'Some default title') }}

Is there a way to do that task elsewhere (maybe in model or controller?). I'd like to have code for form fields identical in create & edit view. Thanks!

like image 465
my2c Avatar asked Jul 07 '13 08:07

my2c


1 Answers

Okay, so here we are... I used Laravel's form model binding in the example. (I work with User model/db table). If this topic is not clear for you, take a look at this http://laravel.com/docs/html#form-model-binding

// Controller

class UsersController extends BaseController
{

    ...

    // Method to show 'create' form & initialize 'blank' user's object
    public function create()
    {
        $user = new User;
        return View::make('users.form', compact('user'));
    }

    // This method should store data sent form form (for new user)
    public function store()
    {
        print_r(Input::all());
    }

    // Retrieve user's data from DB by given ID & show 'edit' form   
    public function edit($id)
    {
        $user = User::find($id);
        return View::make('users.form', compact('user'));
    }

    // Here you should process form data for user that exists already.
    // Modify/convert some input data maybe, save it then...
    public function update($id)
    {
        $user = User::find($id);
        print_r($user->toArray());
    }

    ...

}

And here come the view file served by controller.

// The view file - self describing I think
<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
    @if(!$user->id)
    {{ Form::model($user, ['route' => 'admin.users.store']) }}
    @else
    {{ Form::model($user, ['route' => ['admin.users.update', $user->id], 'method' => 'put']) }}
    @endif
        {{ Form::text('firstName') }}

        {{ Form::text('lastName') }}

        {{ Form::submit() }}
    {{ Form::close() }}
</body>
</html>
like image 184
Andreyco Avatar answered Sep 27 '22 18:09

Andreyco