php - plantillas - variables en blade laravel
Laravel usa la misma forma para crear y editar (9)
Soy bastante nuevo en Laravel y tengo que crear un formulario para crear y un formulario para editar. En mi forma, tengo bastantes publicaciones de jquery ajax. Me pregunto si Laravel me proporciona una manera fácil de usar el mismo formulario para editar y crear sin tener que agregar toneladas de lógica en mi código. No quiero verificar si estoy en modo de edición o creación cada vez que asigno valores a los campos cuando se carga el formulario. ¿Alguna idea sobre cómo puedo lograr esto con una codificación mínima?
Bastante fácil en tu controlador que haces:
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''));
}
Y solo tienes que usar de esta manera:
{{ Form::model($user, [''action'' => $action]) }}
{{ Form::input(''email'') }}
{{ Form::input(''first_name'') }}
{{ Form::close() }}
En Rails, tiene form_for helper, por lo que podríamos hacer una función como form_for.
Podemos hacer una macro de formulario, por ejemplo en resource / macro / html.php:
(Si no sabes cómo configurar una macro, puedes googlear "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;
});
El controlador:
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''));
}
Luego en la vista _form.blade.php:
{!! Form::start($category, ''admin.categories'', [''class'' => ''definewidth m20'']) !!}
// here the Form fields
{{!! Form::close() !!}}
Luego vea create.blade.php:
@include ''_form''
Luego vea edit.blade.php:
@include ''_form''
En lugar de crear dos métodos, uno para crear una nueva fila y otro para actualizar, debe usar el método findOrNew()
. Asi que:
public function edit(Request $request, $id = 0)
{
$user = User::findOrNew($id);
$user->fill($request->all());
$user->save();
}
Otro método limpio con un pequeño controlador, dos vistas y una vista parcial:
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'']) }}
Puede usar el enlace de formulario y 3 métodos en su Controller
. Esto es lo que hago
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();
}
}
Y en mi opinión tengo
{{ Form::model($activity, array(''url'' => "/admin/activities/form/{$activity->id}", ''method'' => ''post'')) }}
{{ Form::model($object, array(''url'' => "/admin/activities/form/{$object->id}", ''method'' => ''post'')) }}
{{ Form::close() }}
Simple y limpio :)
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() }}
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() }}
Me gusta utilizar el model binding
formulario para poder llenar fácilmente los campos de un formulario con el valor correspondiente, por lo que sigo este enfoque (utilizando un modelo de user
por ejemplo):
@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() }}
Entonces, por ejemplo, desde un controlador, básicamente uso el mismo formulario para crear y actualizar, como:
// 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);
}
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'');
}