Description
category component class code:
<?php
namespace App\View\Components;
use Closure;
use App\Models\Category;
use Illuminate\View\Component;
use Illuminate\Contracts\View\View;
class Categories extends Component
{
/**
* Create a new component instance.
*/
public $categories;
public $selected;
public $depth;
public function __construct($categories, $selected=null, $depth=null,)
{
$this->categories = $categories;
$this->depth = $depth;
$this->selected = $selected;
}
public function buildSelectOptions($categories, $selected='', $depth = 0,) {
// Generate HTML for current category
$options = "";
foreach ($categories as $category) {
$options .= "<option selected( old('name', $selected) == '".$category['id']."')
value='".$category['id']."'>".str_repeat('- ', $depth).$category['name']."</option>";
if ($category->children) {
$options .= self::buildSelectOptions($category->children,$selected, $depth + 1);
}
}
return $options;
}
/**
* Get the view / contents that represent the component.
*/
public function render(): View|Closure|string
{
return view('components.categories');
}
}
Category Blade file:
{!! $buildSelectOptions($categories) !!}
Edit Blade File:
<div class="row mb-3">
<div class="col">
<label for="parent_id">Parent Category</label> <span class="star-color">*</span>
<select class="form-control" id="parent_id" name="parent_id" required>
<option value="">Select a Parent Category</option>
<option value="0" selected><b>Root</b></option>
<x-categories :categories="$categories" :selected="$category->id" />
</select>
</div>
</div>
Controller Class:
public function edit(string $id)
{
$category = Category::find($id);
$categories = Category::where('parent_id', '=', 0)->get();
$categoryOptions = Category::buildCategoryOptions($categories);
if(!$category){
abort(404);
}
return view('auth.categories.edit', ['category'=>$category, 'categories'=>$categories, 'categoryOptions'=>$categoryOptions]);
}
View Code
Dear Sir/Ma'am,
I have created the tree level dropdown with component class, its showing fine but problem is when we edit particular category then category not showing selected. could u pls guide me how to make it selected in edit blade file. or is there any other easier way to do this.
You are passing the selected attribute as string, concate the value and then pass it.
~~~
selected=" ' . ( old('name', $selected) == '".$category['id']."') .' "
~~~
0 Likes 0 Comments