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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22844022/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 16:18:59  来源:igfitidea点击:

Laravel use same form for create and edit

phpformslaravel

提问by Kevin Joymungol

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?

我对 Laravel 很陌生,我必须创建一个用于创建的表单和一个用于编辑的表单。在我的表单中,我有很多 jquery ajax 帖子。我想知道 Laravel 是否确实为我提供了一种简单的方法来使用相同的表单进行编辑和创建,而无需在我的代码中添加大量逻辑。在表单加载时为字段分配值时,我不想每次都检查是否处于编辑或创建模式。关于如何以最少的编码完成此任务的任何想法?

回答by The Alpha

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

我喜欢使用表单,model binding所以我可以轻松地用相应的值填充表单的字段,所以我遵循这种方法(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')) }}
    {{-- 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);
}

回答by Antonio Carlos Ribeiro

Pretty easy in your controller you do:

在您的控制器中很容易做到:

public function create()
{
    $user = new User;

    $action = URL::route('user.store');

    return View::('viewname')->with(compact('user', 'action'));
}

public function edit($id)
{
    $user = User::find($id);

    $action = URL::route('user.update', ['id' => $id]);

    return View::('viewname')->with(compact('user', 'action'));
}

And you just have to use this way:

你只需要这样使用:

{{ Form::model($user, ['action' => $action]) }}

   {{ Form::input('email') }}
   {{ Form::input('first_name') }}

{{ Form::close() }}

回答by Samuel De Backer

Another clean method with a small controller, two views and a partial view :

另一种带有小控制器、两个视图和一个局部视图的干净方法:

UsersController.php

用户控制器.php

public function create()
{
    return View::('create');
}    

public function edit($id)
{
    $user = User::find($id);
    return View::('edit')->with(compact('user'));
}

create.blade.php

创建.blade.php

{{ Form::open( array( 'route' => ['users.index'], 'role' => 'form' ) ) }}
    @include('_fields')
{{ Form::close() }}

edit.blade.php

编辑刀片.php

{{ Form::model( $user, ['route' => ['users.update', $user->id], 'method' => 'put', 'role' => 'form'] ) }}
    @include('_fields')
{{ Form::close() }}

_fields.blade.php

_fields.blade.php

{{ Form::text('fieldname1') }}
{{ Form::text('fieldname2') }}
{{ Form::button('Save', ['type' => 'submit']) }}

回答by pasquale

For the creation add an empty object to the view.

为了创建,向视图添加一个空对象。

return view('admin.profiles.create', ['profile' => new Profile()]);

Old function has a second parameter, default value, if you pass there the object's field, the input can be reused.

旧函数有第二个参数,默认值,如果你传递对象的字段,输入可以被重用。

<input class="input" type="text" name="name" value="{{old('name', $profile->name)}}">

For the form action, you can use the correct endpoint.

对于表单操作,您可以使用正确的端点。

<form action="{{ $profile->id == null ? '/admin/profiles' :  '/admin/profiles/' . $profile->id }} " method="POST">

And for the update you have to use PATCH method.

对于更新,您必须使用 PATCH 方法。

@isset($profile->id)
 {{ method_field('PATCH')}}
@endisset

回答by Mantas D

Simple and clean :)

简单干净:)

UserController.php

用户控制器.php

public function create() {
    $user = new User();

    return View::make('user.edit', compact('user'));
}

public function edit($id) {
    $user = User::find($id);

    return View::make('user.edit', compact('user'));
}

edit.blade.php

编辑刀片.php

{{ Form::model($user, ['url' => ['/user', $user->id]]) }}
   {{ Form::text('name') }}
   <button>save</button>
{{ Form::close() }}

回答by Bald

Instead of creating two methods - one for creating new row and one for updating, you should use findOrNew()method. So:

您应该使用findOrNew()method ,而不是创建两种方法 - 一种用于创建新行,一种用于更新。所以:

public function edit(Request $request, $id = 0)
{
    $user = User::findOrNew($id);
    $user->fill($request->all());
    $user->save();
}

回答by Arun Upadhyay

    Article is a model containing two fields - title and content 
    Create a view as pages/add-update-article.blade.php   

        @if(!isset($article->id))
            <form method = "post" action="add-new-article-record">
            @else
             <form method = "post" action="update-article-record">
            @endif
                {{ csrf_field() }} 

                <div class="form-group">
                    <label for="title">Title</label>            
                    <input type="text" class="form-control" id="title" placeholder="Enter title" name="title" value={{$article->title}}>
                    <span class="text-danger">{{ $errors->first('title') }}</span>
                </div>
                <div class="form-group">
                    <label for="content">Content</label>
                    <textarea class="form-control" rows="5" id="content" name="content">
                    {{$article->content}}

                    </textarea>
                    <span class="text-danger">{{ $errors->first('content') }}</span>
                </div>
                <input type="hidden" name="id" value="{{{ $article->id }}}"> 
                <button type="submit" class="btn btn-default">Submit</button>
            </form>

Route(web.php): Create routes to controller 

        Route::get('/add-new-article', 'ArticlesController@new_article_form');
        Route::post('/add-new-article-record', 'ArticlesController@add_new_article');
        Route::get('/edit-article/{id}', 'ArticlesController@edit_article_form');
        Route::post('/update-article-record', 'ArticlesController@update_article_record');

Create ArticleController.php
       public function new_article_form(Request $request)
    {
        $article = new Articles();
        return view('pages/add-update-article', $article)->with('article', $article);
    }

    public function add_new_article(Request $request)
    {
        $this->validate($request, ['title' => 'required', 'content' => 'required']);
        Articles::create($request->all());
        return redirect('articles');
    }

    public function edit_article_form($id)
    {
        $article = Articles::find($id);
        return view('pages/add-update-article', $article)->with('article', $article);
    }

    public function update_article_record(Request $request)
    {
        $this->validate($request, ['title' => 'required', 'content' => 'required']);
        $article = Articles::find($request->id);
        $article->title = $request->title;
        $article->content = $request->content;
        $article->save();
        return redirect('articles');
    } 

回答by Fredyang

In Rails, it has form_for helper, so we could make a function like form_for.

在 Rails 中,它有 form_for 助手,所以我们可以制作一个类似 form_for 的函数。

We can make a Form macro, for example in resource/macro/html.php:

我们可以制作一个 Form 宏,例如在 resource/macro/html.php 中:

(if you don't know how to setup a macro, you can google "laravel 5 Macro")

(如果你不知道如何设置宏,你可以谷歌“laravel 5 Macro”)

Form::macro('start', function($record, $resource, $options = array()){
    if ((null === $record || !$record->exists()) ? 1 : 0) {
        $options['route'] = $resource .'.store';
        $options['method'] = 'POST';
        $str = Form::open($options);
    } else {
        $options['route'] = [$resource .'.update', $record->id];
        $options['method'] = 'PUT';
        $str = Form::model($record, $options);
    }
    return $str;
});

The Controller:

控制器:

public function create()
{
    $category = null;
    return view('admin.category.create', compact('category'));
}

public function edit($id)
{
    $category = Category.find($id);
    return view('admin.category.edit', compact('category'));
}

Then in the view _form.blade.php:

然后在视图 _form.blade.php 中:

{!! Form::start($category, 'admin.categories', ['class' => 'definewidth m20']) !!}
// here the Form fields
{{!! Form::close() !!}}

Then view create.blade.php:

然后查看create.blade.php:

@include '_form'

Then view edit.blade.php:

然后查看edit.blade.php:

@include '_form'

回答by afarazit

You can use form binding and 3 methods in your Controller. Here's what I do

您可以在Controller. 这就是我所做的

class ActivitiesController extends BaseController {
    public function getAdd() {
        return $this->form();
    }
    public function getEdit($id) {
        return $this->form($id);
    }
    protected function form($id = null) {
        $activity = ! is_null($id) ? Activity::findOrFail($id) : new Activity;

        //
        // Your logic here
        //

        $form = View::make('path.to.form')
            ->with('activity', $activity);

        return $form->render(); 
    }
}

And in my views I have

在我看来,我有

{{ Form::model($activity, array('url' => "/admin/activities/form/{$activity->id}", 'method' => 'post')) }}
{{ Form::close() }}

回答by Brynner Ferreira

UserController.php

用户控制器.php

use View;

public function create()
{
    return View::make('user.manage', compact('user'));
}

public function edit($id)
{
    $user = User::find($id);
    return View::make('user.manage', compact('user'));
}

user.blade.php

用户.blade.php

@if(isset($user))
    {{ Form::model($user, ['route' => ['user.update', $user->id], 'method' => 'PUT']) }}
@else
    {{ Form::open(['route' => 'user.store', 'method' => 'POST']) }}
@endif

// fields

{{ Form::close() }}