duanmu3049 2014-04-03 16:47
浏览 227
已采纳

Laravel使用相同的表单进行创建和编辑

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?

  • 写回答

12条回答 默认 最新

  • doutang1946 2014-04-03 17:23
    关注

    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);
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(11条)

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog