0
votes

How would I keep my data in my select box when going back and editing a product?

Here is my form with parent and sub-categories:

          <form role="form" method="POST" action="{{ route('admin.product.update', $product->id) }}">
                {{ csrf_field() }}


                <div class="col-xs-12 col-sm-6 col-md-6">
                    <div class="form-group{{ $errors->has('category') ? ' has-error' : '' }}">
                        <label>Parent Category</label>
                        <select class="form-control" name="category" id="category" data-url="{{ url('api/dropdown')}}">
                            <option value=""></option>
                            @foreach($categories as $category)
                                <option value="{{ $category->id }}">{{ $category->category }}</option>
                            @endforeach
                        </select>
                         @if($errors->has('category'))
                            <span class="help-block">{{ $errors->first('category') }}</span>
                        @endif
                    </div>
                    <br>
                </div>

                <div class="col-xs-12 col-sm-6 col-md-6">
                    <div class="form-group{{ $errors->has('cat_id') ? ' has-error' : '' }}">
                        <label>Sub-Category Category</label>
                        <select class="form-control" name="cat_id" id="sub_category">
                            <option value=""></option>
                        </select>
                        @if($errors->has('cat_id'))
                            <span class="help-block">{{ $errors->first('cat_id') }}</span>
                        @endif
                    </div>
                    <br>
                </div>


                <div class="form-group col-md-12">
                    <button type="submit" class="btn btn-primary waves-effect waves-light">Edit Product</button>
                </div>

            </form>

Here is my function to get the results to edit form:

 /**
     * Return the view to edit & Update the Products
     *
     * @param $id
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function editProduct($id) {

        // Find the product ID
        $product = Product::findOrFail($id);

        // Get all Categories where parent_id = NULL
        $categories = Category::whereNull('parent_id')->get();


        // Return view with products and categories
        return view('admin.product.edit', compact('product', 'categories'));

    }

Here is my Category Model for my categories and sub categories:

class Category extends Model {

    protected $table = 'categories';

    protected $fillable = ['category'];


    /**
     * One sub category, belongs to a Main Category ( Or Parent Category ).
     *
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function parent() {
        return $this->belongsTo('App\Category', 'parent_id');
    }


    /**
     * A Parent Category has many sub categories
     *
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function children() {
        return $this->hasMany('App\Category', 'parent_id');
    }


    /**
     * One Category can have many Products.
     *
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function product() {
        return $this->hasMany('App\Product', 'id');
    }

}

Here is my Product Model for my products table:

class Product extends Model {

    protected $table = 'products';

    protected $fillable = [
        'product_name',
        'price',
        'cat_id',
        'featured',
        'brand_id',
    ];


    /**
     * One Product can have one Category.
     *
     * @return \Illuminate\Database\Eloquent\Relations\HasOne
     */
    public function category() {
        return $this->hasOne('App\Category', 'id');
    }


}

And here is how my categories and products table is set up: My Categories Table

My Products table

Just to let you know, when I choose a parent category, a ajax call fires off and retrieves all the parent sub-categories. I have not included that in this question.

4

4 Answers

3
votes

For Creation forms:

@foreach($categories as $category)
    <option value="{{ $category->id }}" @if(old('category')&&old('category')== $category->id) selected='selected' @endif >{{ $category->category }}</option>
@endforeach

For edit forms:

@foreach($categories as $category)
    <option value="{{ $category->id }}"  @if($category->id==$model->category) selected='selected' @endif >{{ $category->category }}</option>
@endforeach         
1
votes

make this change and try

              <div class="form-group">
                 <label>Parent Category</label>
                        <select class="form-control" name="category" id="category" data-url="{{ url('api/dropdown')}}" >
                            <option value=""></option>
                            @foreach($categories as $category)
                                <option value="{{ $category->id }}" {{$product->Category->parent->id == $category->id ? "selected" : "" }}>{{ $category->category}}</option>
                            @endforeach
                        </select>


                    <br>
                </div>
0
votes

First make sure your input gets redirected back to the form:

return redirect('form')->withInput();

Then check the key with your old input data:

@foreach($categories as $category)
    <option value="{{ $category->id }}" {{ ($category->id == old('category') ? 'selected="selected"' : '') }}>{{ $category->category }}</option>
@endforeach
0
votes

This is an explanation to @LewiG's answer.

When creating an item we return the input if it's invalid, in which case we should prepare our views to handle old($key) input.

So for our particular <select></select> tags we compare the options against the old input. e.g.

@foreach($categories as $category)
    <option value="{{ $category->id }}" @if(old('category')&&old('category')== $category->id) selected='selected' @endif >{{ $category->category }}</option>
@endforeach

When we edit an item, for example a product that has a category, we pre-select the current category by comparing the category_id property (for example) in our product. e.g.

@foreach($categories as $category)
    <option value="{{ $category->id }}"  @if($category->id==$product->category_id) selected='selected' @endif >{{ $category->category }}</option>
@endforeach 

Now where does the $product or $model or $whatever comes from? Database, Eloquent, query, or just an object that you've created then we return it to the view using

return view('product.edit')->withProduct($product);

or

return view('product.edit')->with('product',$product);