Answer the question
In order to leave comments, you need to log in
Yii2 how to display checkboxes using an example?
Good night everybody!
There is a category, it has a subcategory, and it also has another category.
I want to do as in the example of the picture
1 - Spoiler of the category name.
2 - In the subcategory they should not be active, only text
3 - But under the subcategories should be checkboxes
I can't figure out how to implement this.
In the components folder there is a CategoryWidget.php file
below the code
<?php
namespace app\components;
use Yii;
use yii\base\Widget;
use app\models\Category;
class CategoryWidget extends Widget
{
public $tpl;
public $model;
public $data;
public $tree;
public $menuHtml;
public function init()
{
parent::init();
if ($this->tpl === null) {
$this->tpl = 'category';
}
$this->tpl .= '.php';
}
public function run()
{
// get cache
// if ($this->tpl == 'category.php') {
// $menu = Yii::$app->cache->get('category');
// if ($menu) return $menu;
// }
$this->data = Category::find()
->indexBy('id')
->orderBy('sortOrder')
->asArray()
->all();
$this->tree = $this->getTree();
$this->menuHtml = $this->getMenuHtml($this->tree);
// set cache
// if ($this->tpl == 'category.php') {
// Yii::$app->cache->set('category', $this->menuHtml, 60);
// }
return $this->menuHtml;
}
protected function getTree()
{
$tree = [];
foreach ($this->data as $id => &$node) {
if (!$node['parent_id']) {
$tree[$id] = &$node;
} else {
$this->data[$node['parent_id']]['children'][$node['id']] = &$node;
}
}
return $tree;
}
protected function getMenuHtml($tree){
$str = '';
foreach ($tree as $category) {
$str .= $this->catToTemplate($category);
}
return $str;
}
protected function catToTemplate($category)
{
ob_start();
include __DIR__ . '/category_tpl/' . $this->tpl;
return ob_get_clean();
}
}
<ul>
<li>
<div class="spoiler-title"><?= $category['title'] ?></div>
<div class="spoiler-body">
<?php if (isset($category['children'])): ?><br/>
<?= $this->getMenuHtml($category['children']) ?>
<?php endif; ?>
</div>
</li>
</ul>
<br/>
Answer the question
In order to leave comments, you need to log in
1. It is easier to store multilevel trees according to the nestedSets principle
2. What is /category_tpl/' . $this->tpl
incomprehensible to you and most importantly, it is not clear why include is there.
3. First, form the desired array (in your case, with the third level of nesting), then transfer it to the view and build there at least checkboxes, at least sandcastles. To do this, apparently you need to read about recursive functions.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question