定义Laravel表单字段的默认值 [英] Define default values for Laravel form fields

查看:2115
本文介绍了定义Laravel表单字段的默认值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

要预先填充表单字段,我们可以在create.blade.php中的表单字段中添加值":

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

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

是否有其他方法可以完成此任务(可能是在模型中还是在控制器中)?我想让create&中的表单字段代码相同编辑视图.谢谢!

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!

推荐答案

好的,所以在这里...我在示例中使用了Laravel的表单模型绑定. (我使用用户模型/数据库表). 如果您不清楚此主题,请查看此 http://laravel.com/docs/html#表单模型绑定

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>

这篇关于定义Laravel表单字段的默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆