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

时间:2014-04-03 16:47:29

标签: php forms laravel

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

13 个答案:

答案 0 :(得分:59)

我喜欢使用表单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() }}

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

// 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);
}

答案 1 :(得分:25)

你的控制器很容易:

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'));
}

你只需要这样使用:

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

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

{{ Form::close() }}

答案 2 :(得分:13)

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

<强> UsersController.php

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

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

<强> create.blade.php

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

<强> edit.blade.php

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

<强> _fields.blade.php

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

答案 3 :(得分:3)

简单干净:)

<强> UserController.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

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

答案 4 :(得分:2)

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

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

答案 5 :(得分:2)

对于创建,在视图中添加一个空对象。

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

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

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

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

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

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

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

答案 6 :(得分:1)

您可以在Controller中使用表单绑定和3种方法。这就是我的工作

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(); 
    }
}

在我看来,我有

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

答案 7 :(得分:1)

在Rails中,它有form_for帮助器,所以我们可以创建一个类似form_for的函数。

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

(如果你不知道如何设置宏,你可以google&#34; laravel 5 Macro&#34;)

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;
});

控制器:

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'));
}

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

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

然后查看create.blade.php:

@include '_form'

然后查看edit.blade.php:

@include '_form'

答案 8 :(得分:1)

    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');
    } 

答案 9 :(得分:0)

UserController.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

@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() }}

答案 10 :(得分:0)

例如,您的控制器,检索数据并放置视图

class ClassExampleController extends Controller
{

    public function index()
    {   

        $test = Test::first(1);

        return view('view-form',[
            'field' => $test,
        ]);
    }
}

以相同的形式添加默认值,创建和编辑,非常简单

<!-- view-form file -->
<form action="{{ 
    isset($field) ? 
    @route('field.updated', $field->id) : 
    @route('field.store')
}}">
    <!-- Input case -->
    <input name="name_input" class="form-control" 
    value="{{ isset($field->name) ? $field->name : '' }}">
</form>

并且,您还记得添加csrf_field,以防POST方法请求。因此,重复输入,然后选择元素,比较每个选项

<select name="x_select">
@foreach($field as $subfield)

    @if ($subfield == $field->name)
        <option val="i" checked>
    @else
        <option val="i" >
    @endif

@endforeach
</select>

答案 11 :(得分:-1)

希望这对您有帮助!

form.blade.php

@php
$name         = $user->name ?? null;
$email        = $user->email ?? null;
$info         = $user->info ?? null;
$role         = $user->role ?? null;
@endphp

<div class="form-group">
        {!! Form::label('name', 'Name') !!}
        {!! Form::text('name', $name, ['class' => 'form-control']) !!}
</div>

<div class="form-group">
        {!! Form::label('email', 'Email') !!}
        {!! Form::email('email', $email, ['class' => 'form-control']) !!}
</div>

<div class="form-group">
        {!! Form::label('role', 'Função') !!}
        {!! Form::text('role', $role, ['class' => 'form-control']) !!}
</div>

<div class="form-group">
        {!! Form::label('info', 'Informações') !!}
        {!! Form::textarea('info', $info, ['class' => 'form-control']) !!}
</div>

<a class="btn btn-danger float-right" href="{{ route('users.index') }}">CANCELAR</a>

create.blade.php

@extends('layouts.app')

@section('title', 'Criar usuário')

@section('content')
        {!! Form::open(['action' => 'UsersController@store', 'method' => 'POST'])  !!}
            @include('users.form')
            <div class="form-group">
                {!! Form::label('password', 'Senha') !!}
                {!! Form::password('password', ['class' => 'form-control']) !!}
            </div>
            <div class="form-group">
                {!! Form::label('password', 'Confirmação de senha') !!}
                {!! Form::password('password_confirmation', ['class' => 'form-control']) !!}
            </div>
            {!! Form::submit('ADICIONAR', array('class' => 'btn btn-primary')) !!}
        {!! Form::close() !!}
@endsection

edit.blade.php

@extends('layouts.app')

@section('title', 'Editar usuário')

@section('content')
        {!! Form::model($user, ['route' => ['users.update', $user->id], 'method' => 'PUT']) !!}
            @include('users.form', compact('user'))
            {!! Form::submit('EDITAR', ['class' => 'btn btn-primary']) !!}
        {!! Form::close() !!}
        <a href="{{route('users.editPassword', $user->id)}}">Editar senha</a>
@endsection

UsersController.php

use App\User;

Class UsersController extends Controller {
  #... 
    public function create()
    {
        return view('users.create';
    }

    public function edit($id)
    {
        $user  = User::findOrFail($id);
        return view('users.edit', compact('user');
    }
}

答案 12 :(得分:-1)

您可以在单个刀片文件中使用@ $ variable进行创建和编辑。未定义变量时不会出错。

<input name="name" value="@{{$your_variable->name}}">