只有在laravel 5中编辑时才在表单模型绑定中添加readonly属性


Add readonly attribute in form model binding only when editing in laravel 5

我有2个表单用于编辑和插入我的项目,我使用表单模型绑定。

在插入过程中,需要一个名为code的字段。此代码与产品的image相关联。所以我希望我在编辑时,code字段应该变成readOnly ?

我如何做到这一点?

插入

:

{!! Form::open(['url' => '/admin/products', 'autocomplete' => 'off', 'id' => 'formAddProduct', 'files' => true, 'name' => 'formAddProduct']) !!}
    <div class="errors"></div>
    @include('admin.products.form', ['submitButtonText' => 'Add Product', 'submitButtonId' => 'btnAddProduct'])
{!! Form::close() !!}

编辑:

{!! Form::model($product, ['method' => 'PATCH', 'action' => ['AdminProductsController@update', $product->id], 'autocomplete' => 'off', 'id' => 'formEditProduct', 'files' => true]) !!}
    <div class="errors"></div>
    @include('admin.products.form', ['submitButtonText' => 'Edit Product', 'submitButtonId' => 'btnEditProduct'])
{!! Form::close() !!}

form.blade.php :

<div class="form-group">
    {!! Form::label('code', 'Code') !!}
    {!! Form::text('code', null, ['class' => 'form-control']) !!}
</div>
<div class="form-group">
    {!! Form::label('name', 'Name:') !!}
    {!! Form::text('name', null, ['class' => 'form-control']) !!}
</div>
<div class="form-group">
    {!! Form::label('category_id', 'Category:') !!}
    {!! Form::select('category_id', $categories, null, ['class' => 'form-control']) !!}
</div>

在编辑视图中包含表单时,您可以传递另一个参数,如下所示:

编辑:

{!! Form::model($product, ['method' => 'PATCH', 'action' => ['AdminProductsController@update', $product->id], 'autocomplete' => 'off', 'id' => 'formEditProduct', 'files' => true]) !!}
    <div class="errors"></div>
    @include('admin.products.form', ['submitButtonText' => 'Edit Product', 'submitButtonId' => 'btnEditProduct', 'editMode' => true])
{!! Form::close() !!}

然后在包含的表单中,您可以检查该参数并相应地呈现输入字段,

form.blade.php

    <div class="form-group">
        {!! Form::label('code', 'Code') !!}
    @if(isset($editMode))
        {!! Form::text('code', null, ['class' => 'form-control', 'readonly' => true]) !!}
    @else
        {!! Form::text('code', null, ['class' => 'form-control']) !!}
    </div>

这样,您的输入字段在编辑时为只读,否则为可写。

您可以通过传递参数或手动禁用编辑视图中的输入字段来实现这一点:

{!! Form::text('code', null, ['class' => 'form-control', 'disabled' => 'true']) !!}

不重复多个元素。控制器

$readonly = [];
if($edit)
 $readonly = ['readonly' => true];

{!! Form::text('code', null, (['class' => 'form-control'] + $readonly)) !!}