Laravel使用相同的表单进行创建和编辑 [英] Laravel use same form for create and edit

查看:148
本文介绍了Laravel使用相同的表单进行创建和编辑的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于Laravel来说,我很新,我必须创建一个创建表单和一个编辑表单。在我的表单中,我有相当多的jQuery ajax帖子。我想知道Laravel是否为我提供了一种简单的方式来使用相同的表单进行编辑并创建,而不必在代码中添加大量的逻辑。每次在窗体加载时将值赋给字段时,我都不想检查是处于编辑模式还是创建模式。关于如何以最少的代码完成此任务的任何想法?

解决方案

我喜欢使用form model绑定,所以我可以很容易地使用相应的值填充表单的字段,所以我遵循这种方法(例如使用 user 模型):

  @if(isset($ user))
{{Form :: model($ user,['route'=> ; ['updateroute',$ user-> id],'method'=>'patch'])}}
@else
{{Form :: open(['route'=> ;'createroute'])}}
@endif

{{Form :: text('fieldname1',Input :: old('fieldname1'))}}
{ {Form :: text('fieldname2',Input :: old('fieldname2'))}}
{{更多字段... - }}
{{Form :: submit 'Save',['name'=>'submit'])}}
{{Form :: close()}}

因此,例如,从一个控制器,我基本上使用相同的表单来创建和更新,如:

  //创建一个新用户
public function create()
{
// Load user / createOrUpdate.blade.php view
return View :: make ( 'user.createOrUpdate');
}

//更新现有用户(加载编辑)
公共功能编辑($ id)
{
$ user =用户: :查找($ ID);
//载入user / createOrUpdate.blade.php查看
返回View :: make('user.createOrUpdate') - > with('user',$ user);
}


Am quite new to Laravel and I have to create a form for create and a form for edit. In my form I have quite some jquery ajax posts. Am wondering whether Laravel does provide for an easy way for me to use the same form for my edit and create without having to add tons of logic in my code. I don't want to check if am in edit or create mode every time when assigning values to fields when the form loads. Any ideas on how I can accomplish this with minimum coding?

解决方案

I like like to use form model binding so I can easily populate a form's fields with corresponding value, so I follow this approach (using a user model for example):

@if(isset($user))
    {{ Form::model($user, ['route' => ['updateroute', $user->id], 'method' => 'patch']) }}
@else
    {{ Form::open(['route' => 'createroute']) }}
@endif

    {{ Form::text('fieldname1', Input::old('fieldname1')) }}
    {{ Form::text('fieldname2', Input::old('fieldname2')) }}
    {{-- More fields... --}}
    {{ Form::submit('Save', ['name' => 'submit']) }}
{{ Form::close() }}

So, for example, from a controller, I basically use the same form for creating and updating, like:

// To create a new user
public function create()
{
    // Load user/createOrUpdate.blade.php view
    return View::make('user.createOrUpdate');
}

// To update an existing user (load to edit)
public function edit($id)
{
    $user = User::find($id);
    // Load user/createOrUpdate.blade.php view
    return View::make('user.createOrUpdate')->with('user', $user);
}

这篇关于Laravel使用相同的表单进行创建和编辑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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