작성 및 편집에 동일한 양식을 사용하는 레이블
라라벨은 처음이라 작성 양식과 편집 양식을 만들어야 합니다.제 폼에는 꽤 많은 jquery agax 게시물이 있습니다.라라벨이 코드에 수많은 논리를 추가하지 않고도 동일한 양식을 편집 및 작성할 수 있는 쉬운 방법을 제공하는지 궁금합니다.양식을 로드할 때 필드에 값을 할당할 때마다 편집 모드인지 작성 모드인지 확인하고 싶지 않습니다.최소한의 코딩으로 이를 수행할 수 있는 방법에 대한 아이디어가 있습니까?
나는 형태를 사용하는 것을 좋아합니다.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);
}
컨트롤러를 사용하면 다음과 같은 작업을 쉽게 수행할 수 있습니다.
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() }}
작성을 위해 빈 개체를 보기에 추가합니다.
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
작은 컨트롤러, 두 개의 보기 및 부분 보기가 있는 또 다른 클린 방법:
UsersController.php
public function create()
{
return View::('create');
}
public function edit($id)
{
$user = User::find($id);
return View::('edit')->with(compact('user'));
}
create.blade.vmdk
{{ Form::open( array( 'route' => ['users.index'], 'role' => 'form' ) ) }}
@include('_fields')
{{ Form::close() }}
편집.블레이드.블레이드.블레이드.블레이드
{{ Form::model( $user, ['route' => ['users.update', $user->id], 'method' => 'put', 'role' => 'form'] ) }}
@include('_fields')
{{ Form::close() }}
_fields.blade.sys
{{ Form::text('fieldname1') }}
{{ Form::text('fieldname2') }}
{{ Form::button('Save', ['type' => 'submit']) }}
심플하고 깔끔한 :)
사용자 컨트롤러.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'));
}
편집.블레이드.블레이드.블레이드.블레이드
{{ Form::model($user, ['url' => ['/user', $user->id]]) }}
{{ Form::text('name') }}
<button>save</button>
{{ Form::close() }}
예를 들어, 컨트롤러에서 데이터를 검색하고 보기를 배치합니다.
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>
그리고 POST 메서드가 요청할 경우를 대비하여 csrf_field를 추가합니다.따라서 입력을 반복하고 요소를 선택한 후 각 옵션을 비교합니다.
<select name="x_select">
@foreach($field as $subfield)
@if ($subfield == $field->name)
<option val="i" checked>
@else
<option val="i" >
@endif
@endforeach
</select>
을 새로 하는 방법을 만드는 방법 에 새행을만들기위업위를트한방데이두법합가만다니대드야사는해신용를을 사용해야 합니다.findOrNew()
방법.그래서:
public function edit(Request $request, $id = 0)
{
$user = User::findOrNew($id);
$user->fill($request->all());
$user->save();
}
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');
}
Rails에서는 form_for 도우미가 있으므로 form_for와 같은 함수를 만들 수 있습니다.
예를 들어 resource/macro/html.php에서 Form 매크로를 만들 수 있습니다.
(매크로 설정 방법을 모르는 경우 "라벨 5 매크로"를 구글로 검색할 수 있습니다.)
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() !!}}
그런 다음 생성 보기.blade.sys:
@include '_form'
그런 다음 편집을 봅니다.blade.sys:
@include '_form'
3지방사수용있다습니할법을에 과 3가지 할 수 .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();
}
}
그리고 내 견해로는
{{ Form::model($activity, array('url' => "/admin/activities/form/{$activity->id}", 'method' => 'post')) }}
{{ Form::close() }}
다음은 동일한 양식을 사용하여 레코드를 만들거나 편집하는 간단한 방법입니다. Form.blade를 만들었습니다.생성 및 편집을 위한 php 파일
@extends('layouts.admin')
@section('content')
<div class="card shadow mb-4">
<div class="card-header py-3 d-flex justify-content-between">
<h6 class="m-0 font-weight-bold text-primary">Create User</h6>
</div>
<div class="card-body">
<form method="post" action="{{isset($user)? route('users.update',$user->id):route('users.store')}}">
@csrf
@if (isset($user))
@method('PUT')
@endif
<div class="row mb-3">
<div class="col-md-4">
<label>Name</label>
<input class="form-control @error('name') is-invalid @enderror" value="{{isset($user->name) ? $user->name: old('name')}}" type="text" name="name" required>
@error('name')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
@enderror
</div>
<div class="col-md-4">
<label>Email address</label>
<input class="form-control @error('email') is-invalid @enderror" value="{{isset($user->email) ? $user->email:old('email')}}" type="email" name="email" required>
@error('email')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
@enderror
</div>
<div class="col-md-4">
<label>Password</label>
<input class="form-control @error('password') is-invalid @enderror" value="{{old('password')}}" type="text" name="password" required>
@error('password')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
@enderror
</div>
</div>
<div class="col-md-3">
<button class="btn btn-sm btn-success btn-icon-split">
<span class="text">Save</span>
</button>
<a href="{{route('users.index')}}" class="btn btn-sm btn-dark btn-icon-split">
<span class="text">Cancel</span>
</a>
</div>
</form>
</div>
</div>
@endsection
그리고 내 컨트롤러에서.
public function create()
{
return view('admin.user.form');
}
public function edit($id){
$user= User::find($id);
return view('admin.user.form', compact('user'));
}
사용자 컨트롤러.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.vmdk
@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() }}
이것이 당신에게 도움이 되기를 바랍니다!!
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');
}
}
경로에 any를 사용합니다.
Route::any('cr', [CreateContent::class, 'create_content'])
->name('create_resource');
콘트롤러 사용중.
User::UpdateOrCreate([id=>$user->id], ['field_name'=>value, ...]);
언급URL : https://stackoverflow.com/questions/22844022/laravel-use-same-form-for-create-and-edit
'programing' 카테고리의 다른 글
자바스크립트에서 "|"(단일 파이프)는 무엇을 합니까? (0) | 2023.08.30 |
---|---|
웹 페이지를 인쇄할 때 요소를 숨기려면 어떻게 해야 합니까? (0) | 2023.08.30 |
CORS + Cordova : 다음 문제: 액세스-제어-원산지 허용 (0) | 2023.08.25 |
구글 크롬에서 실패한 아약스 요청을 디버그하는 방법은 무엇입니까? (0) | 2023.08.25 |
SQL 서버:인덱스 열은 유사하게 사용됩니까? (0) | 2023.08.25 |