编辑表单时在选择框下拉列表中获取数据 - Laravel 5.2

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36480158/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 13:33:45  来源:igfitidea点击:

Get data in select-box dropdown when editing form - Laravel 5.2

phplaravellaravel-5.2

提问by David

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.

只是为了让您知道,当我选择父类别时,将触发 ajax 调用并检索所有父子类别。我没有把它包括在这个问题中。

回答by LewiG

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         

回答by julee dadhaniya

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>

回答by Bj?rn

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

回答by Islam Al-Rayan

This is an explanation to @LewiG's answer.

这是对@LewiG 的回答的解释。

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.

创建项目时,如果输入无效,我们将返回输入,在这种情况下,我们应该准备我们的视图来处理old($key)输入。

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

因此,对于我们的特定<select></select>标签,我们将选项与旧输入进行比较。例如

@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.

当我们编辑一个项目时,例如一个具有类别的产品,我们通过比较我们产品中的 category_id 属性(例如)来预先选择当前类别。例如

@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

现在 $product 或 $model 或 $whatever 是从哪里来的?数据库、Eloquent、查询或只是您创建的对象,然后我们使用

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

or

或者

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