Используйте ту же форму для создания и редактирования в Laravel 5.3

Я пытаюсь использовать только одну форму для моей формы создания и редактирования. Это простая форма, я использую только HTML, а я использую Laravel 5.3. и я не знаю, как заполнить данные, когда я в режиме редактирования. Я не знаю, использовать создание и редактирование в одной форме или только для просмотра. потому что у моего другого представления для редактирования есть значения, но теперь я хочу сделать это одной формой для моей формы создания и редактирования. Я надеюсь, что вы можете помочь мне. Кстати, я использую ajax для создания и обновления.

add.blade.php

@extends('main_layout')

@section('content')

<!-- MAIN PANEL -->
<div id="main" role="main">

<!-- RIBBON -->
<div id="ribbon">
<div class="row">

<!-- breadcrumb -->
<section class="col-sm-6 col-md-6 col-lg-6">
<ol class="breadcrumb">
<li>
{{$breadcrumb}}
</li>
</ol>
</section>
<!-- end breadcrumb -->
<section class="col-sm-6 col-md-6 col-lg-6 header-button">
<button class="btn btn-primary"  type="submit" form="form1" id="btnAdd">{{$saveButtonText}}</button>

</section>
</div>

</div>
<!-- END RIBBON -->

<!-- MAIN CONTENT -->

<div id="content">
<section id="" class="">
<!-- START ROW -->
<div class="row">

<!-- NEW COL START -->
<article class="col-sm-8 col-md-8 col-lg-8">

<!-- Widget ID (each widget will need unique ID)-->
<div class="jarviswidget jarviswidget-color-red" id="wid-id-0" data-widget-sortable="false" data-widget-deletebutton="false" data-widget-colorbutton="false" data-widget-editbutton="false" data-widget-custombutton="false"><header>
<span class="widget-icon"> <i class="fa fa-user"></i> </span>
<h2>Personal Information</h2>

</header>

<!-- widget div-->
<div>

<!-- widget content -->
<div class="widget-body no-padding">

<form class="smart-form" method="post" action="/register" name="myForm" id="form1">
<input type="hidden" name="_token" value="<?php echo csrf_token(); ?>">

<div class="alert alert-success fade in" id="alertSuccess">
<i class="fa-fw fa fa-check"></i>
<strong>Success!</strong> Indicates a successful or positive action.
</div>
<div class="alert alert-danger fade in" id="alertDanger">
<i class="fa-fw fa fa-times"></i>
<strong>Failed!</strong> Please Indicate the following info.
</div>

<fieldset>
<div class="row">
<section class="col col-4">
<label class="label">Full Name</label>
<label class="input">
<input type="text" name="first_name" id="first_name" placeholder="First Name">

</label>
</section>
<section class="col col-4">
<label class="label">&nbsp;</label>
<label class="input">
<input type="text" name="middle_name" id="middle_name" placeholder="Middle Name">

</label>
</section>
<section class="col col-4">
<label class="label">&nbsp;</label>
<label class="input">
<input type="text" name="last_name" id="last_name"placeholder="Last Name">

</label>
</section>
</div>
<section>
<label class="label">Present Address</label>
<label class="input">
<input type="text" id="present_address" name="present_address" placeholder="Present Address">
</label>
</section>
<section>
<label class="label">Permanent Address &nbsp;&nbsp;<span class="permanent-address">
<input type="checkbox" name="billingtoo" onClick="FillBilling(this.form)"> Same with Present Address</span></label>
<label class="input">
<input type="text" id="permanent_address" name="permanent_address" id="lay" placeholder="Permanent Address">
</label>
</section>
<div class="row">
<section class="col col-4">
<label class="label">Gender</label>
<label class="select">
<select name="gender" id="Gender" placeholder="Gender">
<option value="" disabled selected>Gender</option>
@foreach (Config::get('constants.GENDER') as $gender)
<option value="{{$gender}}">{{$gender}}</option>
@endforeach
</select>
<i></i>
<!-- <input type="text" name="fname" placeholder="First Name"> -->
</label>
</section>
<section class="col col-4">
<label class="label">Birthday</label>
<label class="input"> <i class="icon-append fa fa-calendar"></i>
<input type="text" name="birthday" placeholder="Birthday" class="datepicker" data-dateformat='mm/dd/yy'>
</label>
</section>
<section class="col col-4">
<label class="label">Email</label>
<label class="input">
<input type="email" id="email" name="email" placeholder="E-mail">
</label>
</section>
</div>
<div class="row">
<section class="col col-4">
<label class="label">Work Phone #</label>
<label class="input">
<input type="tel" name="work_phone" placeholder="Work Phone #" data-mask="(999) 999-9999" class="valid"/>

</label>
</section>
<section class="col col-4">
<label class="label">Home Phone #</label>
<label class="input">
<input type="tel" name="home_phone" placeholder="Home Phone #" data-mask="(999) 999-9999" class="valid"/>
</label>
</section>
<section class="col col-4">
<label class="label">Mobile Phone #</label>
<label class="input">
<input type="tel" name="mobile_phone" placeholder="Mobile Phone #" data-mask="(+63) 999-999-9999" class="valid"/>
</label>
</section>
</div>
<div class="row">
<section class="col col-4">
<label class="label">Religion</label>
<label class="input">
<input type="text" name="religion" placeholder="Religion">
</label>
</section>
<section class="col col-4">
<label class="label">Citizenship</label>
<label class="input">
<input type="text" name="citizenship" placeholder="Citizenship">
</label>
</section>
<section class="col col-4">
<label class="label">Civil Status</label>
<label class="input">
<input type="text" name="civil_status" placeholder="Civil Status">
</label>
</section>
</div>
<section class="">
<label class="label"><br/>Emergency Contacts</label>
</section>
<div class="row">
<section class="col col-4">
<label class="label">Name</label>
<label class="input">
<input type="text" name="emergency_name1" placeholder="Emergency Contact Name 1" id="emergency_name1">
</label>
</section>
<section class="col col-4">
<label class="label">Relationship</label>
<label class="input">
<input type="text" name="emergency_rel1" placeholder="Emergency Relationship 1">
</label>
</section>
<section class="col col-4">
<label class="label">Contact #</label>
<label class="input">
<input type="text" name="emergency_contact1" placeholder="Emergency Contact # 1"onkeypress="return isNumber(event)" />
</label>
</section>
</div>
<div class="row">
<section class="col col-4">
<label class="input">
<input type="text" name="emergency_name2" placeholder="Emergency Contact Name 2">
</label>
</section>
<section class="col col-4">
<label class="input">
<input type="text" name="emergency_rel2" placeholder="Emergency Relationship 2">
</label>
</section>
<section class="col col-4">
<label class="input">
<input type="text" name="emergency_contact2" placeholder="Emergency Contact # 2"onkeypress="return isNumber(event)" />
</label>
</section>
</div>
<div class="row">
<section class="col col-4">
<label class="input">
<input type="text" name="emergency_name3" placeholder="Emergency Contact Name 3">
</label>
</section>
<section class="col col-4">
<label class="input">
<input type="text" name="emergency_rel3" placeholder="Emergency Relationship 3">
</label>
</section>
<section class="col col-4">
<label class="input">
<input type="text" name="emergency_contact3" placeholder="Emergency Contact # 3"onkeypress="return isNumber(event)" />
</label>
</section>
</div>
</fieldset></div>
<!-- end widget content -->

</div>
<!-- end widget div -->

</div>
<!-- end widget -->

</article>
</form>

Это маршруты

    Route::get('/employee/add', 'PagesController@addEmployee');
Route::get('/employee/add/{paramStatus}', 'PagesController@addEmployee');
Route::get('/employee/{id}/add', 'EmployeesController@editEmployee');
Route::post('employee/{id}/ajaxShow', 'EmployeesController@ajaxShow');
Route::post('employee/{id}/ajaxUpdate', 'EmployeesController@ajaxUpdate');

PagesController.php

    <?php

namespace App\Http\Controllers;
use Illuminate\Http\Request;
use View;
use App\Entry;
use App\SSSSetting;
use Request as Req;
use App\manage;
use DB;
use App\Employee;

class PagesController extends Controller
{
public function addEmployee()
{
$breadcrumb = 'Employees > Add Employee';
$pageTitle = 'CollabUX | Add Employee';
$saveButtonText = "Add Employee";
$prepath ='../';
$currentURL = Req::url();
$resultem = Employee::all();
$EmployeeInfo = DB::table('employees')->get();

return View::make('employee.add')->with(
array('breadcrumb' => $breadcrumb,'pageTitle' => $pageTitle,'currentURL' => $currentURL,
'saveButtonText' => $saveButtonText,'prepath' => $prepath,'resultem' => $resultem,'EmployeeInfo' => $EmployeeInfo));
}

public function editEmployee($id)
{

$breadcrumb = 'Employees > Manage Employees > Edit';
$pageTitle = 'CollabUX | Edit Employee';
$saveButtonText = "Save Changes";
$prepath ='../';
$currentURL = Req::url();
$resultem = manage::all();
$EmployeeInfo = DB::table('employees')->where('id', $id)->get();

return View::make('employee.add')->with(
array('breadcrumb' => $breadcrumb,'pageTitle' => $pageTitle,'currentURL' => $currentURL,
'saveButtonText' => $saveButtonText,'prepath' => $prepath,'resultem' => $resultem, ));
}
}

EmployeeController.php

<?php

namespace App\Http\Controllers;
use Illuminate\Http\Request;
use DB;
use Session;
use App\Employee;
use Request as Req;
use App\Http\Requests;
use App\Http\Controllers\Controller;

class EmployeesController extends Controller
{
public function insert(Request $request){

$first_name = $request->input('first_name');
$middle_name = $request->input('middle_name');
$last_name = $request->input('last_name');
$present_address = $request->input('present_address');
$permanent_address = $request->input('permanent_address');
$gender = $request->input('gender');
$birthday = $request->input('birthday');
$email = $request->input('email');
$work_phone = $request->input('work_phone');
$home_phone = $request->input('home_phone');
$mobile_phone = $request->input('mobile_phone');
$religion = $request->input('religion');
$citizenship = $request->input('citizenship');
$civil_status = $request->input('civil_status');$data = array('id'=>$employeeNum,'first_name'=>$first_name,'middle_name'=>$middle_name,'last_name'=>$last_name,'present_address'=>$present_address,'permanent_address'=>$permanent_address,'email'=>$email,'work_phone'=>$work_phone,'home_phone'=>$home_phone,'mobile_phone'=>$mobile_phone,'religion'=>$religion,'gender'=>$gender,'birthday'=>$birthday,'citizenship'=>$citizenship);
$save = DB::table('employees')->insert($data);

return redirect('/employee/add');

return view('add');

}

public function ajaxShow(Request $request, $id) {
$manageEmployee = Employee::find($id);

return array('status' => 'OK', 'result' => $manageEmployee);
}

public function editEmployee($id)
{
$breadcrumb = 'Employees > Manage Employees > Edit';
$pageTitle = 'CollabUX | Edit Employee';
$saveButtonText = "Save Changes";
$currentURL = Req::url();
$prepath ='../';
$resultem = Employee::all();

$EmployeeInfo = DB::table('employees')->where('id', $id)->get();

return view('employee.add')->with(array('breadcrumb'=>$breadcrumb,'pageTitle'=>$pageTitle,'currentURL' => $currentURL,'prepath'=>$prepath,'saveButtonText'=>$saveButtonText,'EmployeeInfo'=>$EmployeeInfo, 'resultem' => $resultem));

}
public function update(Request $request, $id)
{
// validate the data
$this->validate($request, [
'first_name' => 'required',
'middle_name' => 'required',
'last_name' => 'required',
'present_address' => 'required',
'permanent_address' => 'required',
'gender' => 'required',
'birthday' => 'required',
'email' => 'required',
'work_phone' => 'required',
'home_phone' => 'required',
'religion' => 'required',
'citizenship' => 'required'
]);

$manageEmployee = Employee::where('id', '!=', $id)->where(array('first_name' => $request->first_name, 'middle_name' => $request->middle_name,'last_name' => $request->last_name,'present_address' => $request->present_address,'permanent_address' => $request->permanent_address,'gender' => $request->gender,'birthday' => $request->birthday,'email' => $request->email,'work_phone' => $request->work_phone,'home_phone' => $request->home_phone,'religion' => $request->religion,'citizenship' => $request->citizenship,'civil_status' => $request->civil_status,'employeeNum' => $request->employeeNum,'Position' => $request->Position,'Supervisor' => $request->Supervisor,'starting_salary' => $request->starting_salary,'status' => $request->status,'tin' => $request->tin,'SSS' => $request->SSS,'philhealth' => $request->philhealth,'pagibig' => $request->pagibig,'no_dependents' => $request->no_dependents))->first();

if ($manageEmployee)
return array('status' => 'ERROR', 'error' => 'Record already exists.');

$manageEmployee = Employee::find($id);

if ($manageEmployee) {
$manageEmployee->first_name = $request->first_name;
$manageEmployee->middle_name = $request->middle_name;
$manageEmployee->last_name = $request->last_name;
$manageEmployee->present_address = $request->present_address;
$manageEmployee->permanent_address = $request->permanent_address;
$manageEmployee->gender = $request->gender;
$manageEmployee->birthday = $request->birthday;
$manageEmployee->email = $request->email;
$manageEmployee->work_phone = $request->work_phone;
$manageEmployee->home_phone = $request->home_phone;
$manageEmployee->religion = $request->religion;
$manageEmployee->citizenship = $request->citizenship;
$manageEmployee->civil_status = $request->civil_status;
$manageEmployee->employeeNum = $request->employeeNum;
$manageEmployee->Position = $request->Position;
$manageEmployee->Supervisor = $request->Supervisor;
$manageEmployee->starting_salary = $request->starting_salary;
$manageEmployee->status = $request->status;
$manageEmployee->tin = $request->tin;
$manageEmployee->SSS = $request->SSS;
$manageEmployee->philhealth = $request->philhealth;
$manageEmployee->pagibig = $request->pagibig;
$manageEmployee->no_dependents = $request->no_dependents;

$manageEmployee->save();
}
return array('status' => 'OK', 'result' => $manageEmployee);
}

}

3

Решение

У вас есть очень простое решение для этого; а именно Форм-модель привязки

Сделайте три просмотра файлов

 1. create.blade.php
2. edit.blade.php
3. _form.blade.php

_form.blade.php является частичным файлом, который будет включен в оба create а также edit,

Примечание: вам придется использовать laravelcollective/html пакет.

create.blade.php

<!-- Your template HTML code here -->

{!! Form::open([
'action' => 'EmployeesController@store',
'id' => 'employee-form'
]) !!}
@include('employee._form')
{!! Form::close() !!}

<!-- Continue with your template HTML code here -->

edit.blade.php

<!-- Your template HTML code here -->

{!! Form::model([
$employee,
'method' => 'POST', <!-- Or whatever you have used for update() -->
'action' => ['EmployeesController@update', $employee->id],
'id' => 'employee-form'
]) !!}
@include('employee._form')
{!! Form::close() !!}

<!-- Continue with your template HTML code here -->

_form.blade.php

<fieldset>
<div class="row">
<section class="col col-4">
<label class="label">Full Name</label>
<label class="input">
{!! Form::text('first_name', null, ['placeholder => 'First Name']) !!}
</label>
</section>
<section class="col col-4">
<label class="label">&nbsp;</label>
<label class="input">
<input type="text" name="middle_name" id="middle_name" placeholder="Middle Name">
{!! Form::text('middle_name', null, ['placeholder' => 'Middle Name']) !!}
</label>
</section>
...
</fieldset>

Привязка модели формы позаботится о заполнении полей редактирования формы сохраненными значениями из базы данных.


Если вы хотите избежать просмотра нескольких файлов:

Просто один взгляд, скажем employee_form.blade.php

<!-- Your template HTML code here -->
@if($employee instanceof \App\Employee)
{!! Form::model([
$employee,
'method' => 'POST', <!-- Or whatever you have used for update() -->
'action' => ['EmployeesController@update', $employee->id],
'id' => 'employee-form'
]) !!}
@else
{!! Form::model([
$employee = new \App\Employee,
'method' => 'POST', <!-- Or whatever you have used for store() -->
'action' => ['EmployeesController@store', $employee->id],
'id' => 'employee-form'
]) !!}
@endif
@include('employee._form')
{!! Form::close() !!}

<!-- Continue with your template HTML code here -->

Еще одно предложение

Пожалуйста, не помещайте всю свою бизнес-логику в контроллеры.

использование Request классы для валидации.

Попробуйте перенести свою бизнес-логику в другие классы (например, Service а также Repository классы), чтобы ваши контроллеры были легкими. обращаться этот например, как использовать классы Helper, чтобы ваш код был чистым и управляемым.

3

Другие решения

Поскольку привязка Form-модели больше не включена в ядро ​​Laravel, я лично не рекомендовал бы это как лучшее решение. Посмотрите на привязку модели маршрута и чистые HTML-формы и партиалы.

3

По вопросам рекламы [email protected]