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

8.1k Views Asked by At

I have 2 forms for editing and inserting in my project and I am using form model binding.

During insertion, there is a field that is required called code. This code is associated with the image of the product. So I want that I during the editing, the code field should become readOnly ?

How do I achieve this ?

insertion:

{!! 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() !!}

editing:

{!! 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>
3

There are 3 best solutions below

0
On BEST ANSWER

While including the form in the editing view, you can pass another parameter as follows:

editing:

{!! 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() !!}

Then in the included form you can do check for this parameter and render the input field accordingly,

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>

This way, you have the input field being readOnly if editing, else writable.

0
On

You can achieve this by disabling the input field in edit view by passing parameter or manually:

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

Instead of duplicate many elements. on controller

$readonly = [];

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

on view

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