Как получить в select2 данные из модели

Общие вопросы по использованию второй версии фреймворка. Если не знаете как что-то сделать и это про Yii 2, вам сюда.
Ответить
Аватара пользователя
svil
Сообщения: 563
Зарегистрирован: 2018.02.12, 22:41

Как получить в select2 данные из модели

Сообщение svil »

Знаю, что можно из контроллера передать $data для select2(use kartik\select2\Select2).
Но хочу разобраться, можно ли обойтись данными из модели.
Один ко многим две модели Courses(id, name) и Categories(id, course_id, parent_id, name).
"Внутри" модели Categories дерево категорий id и parent_id(то есть у категории может быть родительская категория в пределах курса course_id )
В виде Categories (_form) вывожу 2 select2
Первый select2 должен выводить без права редактирования наименование курса ( по course_id из таблицы Categories)
Второй select2 выводит список категорий в пределах данного курса course_id
Ошибка

Код: Выделить всё

Trying to get property of non-object
 in /Users/svetlanailina/Sites/boxic/backend/views/categories/_form.php at line 17
891011121314151617181920212223242526/* @var $model app\models\Categories */
/* @var $form yii\widgets\ActiveForm */
?>
 
<div class="categories-form">
 
    <?php $form = ActiveForm::begin(); ?>
 
    <?= $form->field($model, 'course_id')->widget(Select2::classname(), [
        'data' => $model->courses->name, //тут красным
        'language' => 'ru',
        'options' => ['placeholder' => 'Выбор курса ...'],
        'pluginOptions' => [
            'allowClear' => true
        ],
    ]);
 
    ?>
    <?= $form->field($model, 'parent_id')->widget(Select2::classname(), [
2. in /Users/svetlanailina/Sites/boxic/backend/views/categories/_form.php at line 17 – yii\base\ErrorHandler::handleError(8, 'Trying to get property of non-ob...', '/Users/svetlanailina/Sites/boxic...', 17, ...)
11121314151617181920212223 
<div class="categories-form">
 
    <?php $form = ActiveForm::begin(); ?>
 
    <?= $form->field($model, 'course_id')->widget(Select2::classname(), [
        'data' => $model->courses->name, //тут красным
        'language' => 'ru',
        'options' => ['placeholder' => 'Выбор курса ...'],
        'pluginOptions' => [
            'allowClear' => true
        ],
    ]);
3. in /Users/svetlanailina/Sites/boxic/vendor/yiisoft/yii2/base/View.php at line 348 – require('/Users/svetlanailina/Sites/boxic...')
4. in /Users/svetlanailina/Sites/boxic/vendor/yiisoft/yii2/base/View.php at line 257 – yii\base\View::renderPhpFile('/Users/svetlanailina/Sites/boxic...', ['model' => app\models\Categories])
5. in /Users/svetlanailina/Sites/boxic/vendor/yiisoft/yii2/base/View.php at line 156 – yii\base\View::renderFile('/Users/svetlanailina/Sites/boxic...', ['model' => app\models\Categories], null)
6. in /Users/svetlanailina/Sites/boxic/backend/views/categories/create.php at line 24 – yii\base\View::render('_form', ['model' => app\models\Categories])
18192021222324252627?>
<div class="categories-create">
 
    <h1><?= Html::encode($this->title) ?></h1>
 
    <?= $this->render('_form', [
        'model' => $model, //тут красным
    ]) ?>
 
</div>
7. in /Users/svetlanailina/Sites/boxic/vendor/yiisoft/yii2/base/View.php at line 348 – require('/Users/svetlanailina/Sites/boxic...')
8. in /Users/svetlanailina/Sites/boxic/vendor/yiisoft/yii2/base/View.php at line 257 – yii\base\View::renderPhpFile('/Users/svetlanailina/Sites/boxic...', ['model' => app\models\Categories, 'course_id' => '1'])
9. in /Users/svetlanailina/Sites/boxic/vendor/yiisoft/yii2/base/View.php at line 156 – yii\base\View::renderFile('/Users/svetlanailina/Sites/boxic...', ['model' => app\models\Categories, 'course_id' => '1'], backend\controllers\CategoriesController)
10. in /Users/svetlanailina/Sites/boxic/vendor/yiisoft/yii2/base/Controller.php at line 384 – yii\base\View::render('create', ['model' => app\models\Categories, 'course_id' => '1'], backend\controllers\CategoriesController)
11. in /Users/svetlanailina/Sites/boxic/backend/controllers/CategoriesController.php at line 108 – yii\base\Controller::render('create', ['model' => app\models\Categories, 'course_id' => '1'])
102103104105106107108109110111112113114        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        }
 
        return $this->render('create', [
            'model' => $model,
            'course_id' => $course_id //тут красным
        ]);
    }
 
 
    /**
     * Updates an existing Categories model.
12. backend\controllers\CategoriesController::actionCreate('1')
13. in /Users/svetlanailina/Sites/boxic/vendor/yiisoft/yii2/base/InlineAction.php at line 57 – call_user_func_array([backend\controllers\CategoriesController, 'actionCreate'], ['1'])
14. in /Users/svetlanailina/Sites/boxic/vendor/yiisoft/yii2/base/Controller.php at line 157 – yii\base\InlineAction::runWithParams(['course_id' => '1'])
15. in /Users/svetlanailina/Sites/boxic/vendor/yiisoft/yii2/base/Module.php at line 528 – yii\base\Controller::runAction('create', ['course_id' => '1'])
16. in /Users/svetlanailina/Sites/boxic/vendor/yiisoft/yii2/web/Application.php at line 103 – yii\base\Module::runAction('categories/create', ['course_id' => '1'])
17. in /Users/svetlanailina/Sites/boxic/vendor/yiisoft/yii2/base/Application.php at line 386 – yii\web\Application::handleRequest(yii\web\Request)
18. in /Users/svetlanailina/Sites/boxic/backend/web/index.php at line 18 – yii\base\Application::run()
12131415161718    require __DIR__ . '/../../common/config/main.php',
    require __DIR__ . '/../../common/config/main-local.php',
    require __DIR__ . '/../config/main.php',
    require __DIR__ . '/../config/main-local.php'
);
 
(new yii\web\Application($config))->run();
 $_GET = [
    'course_id' => '1',
];

$_COOKIE = [
    '_identity' => 'cdf14508714539d9c7f0bedd4348ccf7b1e9137fbea6e3544c60f34071ee0012a:2:{i:0;s:9:"_identity";i:1;s:49:"[2995,"Q4Z6VBJneUR9l-09rc7tf0rml2VzFpoV",2592000]";}',
    'advanced' => 'aoap21nkq0ethm9pr5nlutggj4',
    '_csrf-backend' => '507a6000eb8f0106225ea3df976dade191865139b57ab92d3c8c952640b0386ea:2:{i:0;s:13:"_csrf-backend";i:1;s:32:"-NWnZ9v1acmAS4i_420Gx3wHS3DV-6ry";}',
];

$_SESSION = [
    '__flash' => [],
    '__id' => 2995,
];
Yii Framework



Модель Courses

Код: Выделить всё

<?php

namespace app\models;

use Yii;

/**
 * This is the model class for table "courses".
 *
 * @property int $id
 * @property string $name Наименование курса
 * @property string $fullname Полное наименование
 * @property string $articul Артикул курса
 * @property int $price Стоимость обучения
 * @property int $hours Кол-во часов курса
 * @property string $prog Наименование утвержденной программы курса для удостоверений
 * @property string $preambula Преамбула для удостоверений
 * @property string $postambula Постамбула для удостоверений
 * @property int $nqforcat Кол-во вопросов, выводимых для категории
 * @property int $basket Флаг удаления
 *
 * @property Answers[] $answers
 * @property Categories[] $categories
 * @property Examstorage[] $examstorages
 * @property Groups[] $groups
 * @property Materials[] $materials
 * @property Questions[] $questions
 */
class Courses extends \yii\db\ActiveRecord
{
    public $categoriesName;
    /**
     * {@inheritdoc}
     */
    public static function tableName()
    {
        return 'courses';
    }

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
          //  [['id'], 'required'],
            [['name' ,'price', 'hours', 'nqforcat','fullname', 'articul', 'prog', 'preambula', 'postambula'], 'required'],
            [['id', 'price', 'hours', 'nqforcat', 'basket'], 'integer'],
            [['name', 'fullname', 'articul', 'prog', 'preambula', 'postambula'], 'string'],
            [['id'], 'unique'],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels()
    {
        return [
          //  'id' => 'ID',
            'name' => 'Наименование курса',
            'fullname' => 'Наименование образовательной программы',
            'articul' => 'Артикул',
            'price' => 'Цена',
            'hours' => 'Рекомендуемое время курса',
            'prog' => 'Наименование утвержденной программы курса для удостоверений',
            'preambula' => 'Преамбула для удостоверений',
            'postambula' => 'Постамбула для удостоверений',
            'nqforcat' => 'Кол-во вопросов, выводимых для категории',
            'basket' => 'Basket',

            'categoriesName' => 'Категории',
            'materialsName' => 'Материалы',
            'questionsName' => 'Вопросы',
        ];
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getAnswers()
    {
        return $this->hasMany(Answers::className(), ['course_id' => 'id']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getCategories()
    {
        return $this->hasMany(Categories::className(), ['course_id' => 'id'])
            ->where(['basket' => '0']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getExamstorages()
    {
        return $this->hasMany(Examstorage::className(), ['course_id' => 'id']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getGroups()
    {
        return $this->hasMany(Groups::className(), ['course_id' => 'id']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getMaterials()
    {
        return $this->hasMany(Materials::className(), ['course_id' => 'id']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getQuestions()
    {
        return $this->hasMany(Questions::className(), ['course_id' => 'id']);
    }
    /* Геттер для полного наименования категории */
    public function getCategoriesName() {
        return $this->Categories->name;
    }
}
Moдель Categories

Код: Выделить всё

<?php

namespace app\models;

use Yii;

/**
 * This is the model class for table "categories".
 *
 * @property int $id
 * @property int $course_id
 * @property int $parent_id
 * @property string $name Наименование
 * @property int $basket Флаг удаления
 *
 * @property Courses $course
 * @property Categories $parent
 * @property Categories[] $categories
 * @property Materials[] $materials
 * @property Questions[] $questions
 */
class Categories extends \yii\db\ActiveRecord
{
    public $courseName;
    /**
     * {@inheritdoc}
     */
    public static function tableName()
    {
        return 'categories';
    }

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['name'], 'required'],
            [['id', 'course_id', 'parent_id', 'basket'], 'integer'],
            [['name'], 'string'],
            [['id'], 'unique'],
            [['course_id'], 'exist', 'skipOnError' => true, 'targetClass' => Courses::className(), 'targetAttribute' => ['course_id' => 'id']],
            [['parent_id'], 'exist', 'skipOnError' => true, 'targetClass' => Categories::className(), 'targetAttribute' => ['parent_id' => 'id']],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'course_id' => 'Курс',
            'parent_id' => 'Родительская категория',
            'name' => 'Наименование',
            'basket' => 'Basket',
            'courseName' => 'Наименование курса',

        ];
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getCourses()
    {
        return $this->hasOne(Courses::className(), ['id' => 'course_id']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getParent()
    {
        return $this->hasOne(Categories::className(), ['id' => 'parent_id']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getCategories()
    {
        return $this->hasMany(Categories::className(), ['parent_id' => 'id']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getMaterials()
    {
        return $this->hasMany(Materials::className(), ['category_id' => 'id']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getQuestions()
    {
        return $this->hasMany(Questions::className(), ['category_id' => 'id']);
    }

    /* Геттер для наименования категории */
    public function getCoursesName() {
        return $this->Courses->name;
    }

}
Контроллер courses

Код: Выделить всё

<?php

namespace backend\controllers;

use Yii;
use app\models\Courses;
use app\models\CoursesSearch;
use app\models\Categories;
use app\models\Materials;
use app\models\Questions;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;
/**
 * CoursesController implements the CRUD actions for Courses model.
 */
class CoursesController extends Controller
{
    /**
     * {@inheritdoc}
     */
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
            'access' => [
                'class' => AccessControl::className(),
                'only' => ['*'],
                'rules' => [
                    [
                        'allow' => true,
                        'roles' => ['admin', 'manager'],
                    ],
                ],
                'denyCallback' => function () {
                    return Yii::$app->response->redirect(['./../../']);
                },
            ],
        ];
    }

    /**
     * Lists all Courses models.
     * @return mixed
     */
    public function actionIndex()
    {
        $item='groups';
        $this->view->params['news'] = $item;

        $searchModel = new CoursesSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        $data_num_cat = Categories::find()->count();
        $data_num_mat = Materials::find()->count();
        $data_num_ques = Questions::find()->count();


        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
            'data_num_cat' => $data_num_cat,
            'data_num_mat' => $data_num_mat,
            'data_num_ques' => $data_num_ques,
        ]);
    }

    /**
     * Displays a single Courses model.
     * @param integer $id
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionView($id)
    {
        $item='groups';
        $this->view->params['news'] = $item;

        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * Creates a new Courses model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $item='groups';
        $this->view->params['news'] = $item;

        $model = new Courses();

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        }

        return $this->render('create', [
            'model' => $model,
        ]);
    }

    /**
     * Updates an existing Courses model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionUpdate($id)
    {
        $item='groups';
        $this->view->params['news'] = $item;

        $model = $this->findModel($id);

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        }

        return $this->render('update', [
            'model' => $model,
        ]);
    }

    /**
     * Deletes an existing Courses model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionDelete($id)
    {
        $item='groups';
        $this->view->params['news'] = $item;

        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }

    /**
     * Finds the Courses model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return Courses the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = Courses::findOne($id)) !== null) {
            return $model;
        }

        throw new NotFoundHttpException('The requested page does not exist.');
    }
}
Контроллер categories

Код: Выделить всё

<?php

namespace backend\controllers;

use Yii;
use app\models\Categories;
use app\models\CategoriesSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;

/**
 * CategoriesController implements the CRUD actions for Categories model.
 */
class CategoriesController extends Controller
{
    /**
     * {@inheritdoc}
     */
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
            'access' => [
                'class' => AccessControl::className(),
                'only' => ['*'],
                'rules' => [
                    [
                        'allow' => true,
                        'roles' => ['admin', 'manager'],
                    ],
                ],
                'denyCallback' => function () {
                    return Yii::$app->response->redirect(['./../../']);
                },
            ],

        ];

    }

    /**
     * Lists all Categories models.
     * @return mixed
     */
    public function actionIndex($course_id)
    {
        $item='file';
        $this->view->params['news'] = $item;

        $id = Yii::$app->request->get('course_id');

        $searchModel = new CategoriesSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);
        $dataProvider->query->where(['course_id'=> $id]);
        $dataProvider->query->andWhere(['basket'=> '0']);


        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,

        ]);
    }



    /**
     * Displays a single Categories model.
     * @param integer $id
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionView($id)
    {
        $item='file';
        $this->view->params['news'] = $item;

        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * Creates a new Categories model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate($course_id)
    {
        $item='file';
        $this->view->params['news'] = $item;

        $model = new Categories();
        $course_id =  Yii::$app->request->get('course_id');
        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        }

        return $this->render('create', [
            'model' => $model,
            'course_id' => $course_id
        ]);
    }


    /**
     * Updates an existing Categories model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionUpdate($id)
    {
        $item='file';
        $this->view->params['news'] = $item;

        $model = $this->findModel($id);

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        }

        return $this->render('update', [
            'model' => $model,
            'course_id' => $model->course_id
        ]);
    }

    /**
     * Deletes an existing Categories model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionDelete($id)
    {
        $item='file';
        $this->view->params['news'] = $item;

        $this->findModel($id)->updateAttributes(['basket'=> '1']);
        return $this->redirect(['courses/index']);

//        $this->findModel($id)->delete();
//        return $this->redirect(['index']);
    }

    /**
     * Finds the Categories model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return Categories the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = Categories::findOne($id)) !== null) {
            return $model;
        }

        throw new NotFoundHttpException('The requested page does not exist.');
    }
}
Форма categories

Код: Выделить всё

<?php
/*Форма для create.php */
use yii\helpers\Html;
use yii\widgets\ActiveForm;
use kartik\select2\Select2;

/* @var $this yii\web\View */
/* @var $model app\models\Categories */
/* @var $form yii\widgets\ActiveForm */
?>

<div class="categories-form">

    <?php $form = ActiveForm::begin(); ?>

    <?= $form->field($model, 'course_id')->widget(Select2::classname(), [
        'data' => $model->courses->name,
        'language' => 'ru',
        'options' => ['placeholder' => 'Выбор курса ...'],
        'pluginOptions' => [
            'allowClear' => true
        ],
    ]);

    ?>
    <?= $form->field($model, 'parent_id')->widget(Select2::classname(), [
        'data' => $model->categories,
        'language' => 'ru',
        'options' => ['placeholder' => 'Выбор родительской категории курса ...'],
        'pluginOptions' => [
            'allowClear' => true
        ],
    ]);

    ?>

    <?= $form->field($model, 'name')->textarea(['rows' => 6]) ?>



    <div class="form-group">
        <?= Html::submitButton('Подтвердить', ['class' => 'btn btn-success']) ?>
    </div>

    <?php ActiveForm::end(); ?>

</div>
Loveorigami
Сообщения: 977
Зарегистрирован: 2014.08.27, 21:54

Re: Как получить в select2 данные из модели

Сообщение Loveorigami »

А почему готовый depdrop не используете для этого?
http://demos.krajee.com/widget-details/depdrop
Аватара пользователя
svil
Сообщения: 563
Зарегистрирован: 2018.02.12, 22:41

Re: Как получить в select2 данные из модели

Сообщение svil »

Пытаюсь использовать
Вот документация на scenario 2, то есть 2 уровня

Код: Выделить всё

use kartik\depdrop\DepDrop;
 
// Parent 
echo $form->field($model, 'cat1')->dropDownList($majorCatList, ['id' => 'cat-id']);
 
// Additional input fields passed as params to the child dropdown's pluginOptions
echo Html::hiddenInput('input-type-1', 'Additional value 1', ['id' => 'input-type-1']);
echo Html::hiddenInput('input-type-2', 'Additional value 2', ['id' => 'input-type-2']);
 
// Child # 1
echo $form->field($model, 'subcat1')->widget(DepDrop::classname(), [
    'type' => DepDrop::TYPE_SELECT2,
    'data' => [2 => 'Tablets'],
    'options' => ['id' => 'subcat1-id', 'placeholder' => 'Select ...'],
    'select2Options' => ['pluginOptions' => ['allowClear' => true]],
    'pluginOptions' => [
        'depends' => ['cat1-id'],
        'url' => Url::to(['/site/subcat1']),
        'params' => ['input-type-1', 'input-type-2']
    ]
]);
 
// THE CONTROLLER
public function actionSubcat1() {
    Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
    $out = [];
    if (isset($_POST['depdrop_parents'])) {
        $parents = $_POST['depdrop_parents'];
        if ($parents != null) {
            $cat_id = $parents[0];
            $param1 = null;
            $param2 = null;
            if (!empty($_POST['depdrop_params'])) {
                $params = $_POST['depdrop_params'];
                $param1 = $params[0]; // get the value of input-type-1
                $param2 = $params[1]; // get the value of input-type-2
            }
 
            $out = self::getSubCatList1($cat_id, $param1, $param2); 
            // the getSubCatList1 function will query the database based on the
            // cat_id, param1, param2 and return an array like below:
            // [
            //    'group1' => [
            //        ['id' => '<sub-cat-id-1>', 'name' => '<sub-cat-name1>'],
            //        ['id' => '<sub-cat_id_2>', 'name' => '<sub-cat-name2>']
            //    ],
            //    'group2' => [
            //        ['id' => '<sub-cat-id-3>', 'name' => '<sub-cat-name3>'], 
            //        ['id' => '<sub-cat-id-4>', 'name' => '<sub-cat-name4>']
            //    ]            
            // ]
            
            
            $selected = self::getDefaultSubCat($cat_id);
            // the getDefaultSubCat function will query the database
            // and return the default sub cat for the cat_id
            
            return ['output' => $out, 'selected' => $selected];
        }
    }
    return ['output' => '', 'selected' => ''];
}
 
Аватара пользователя
svil
Сообщения: 563
Зарегистрирован: 2018.02.12, 22:41

Re: Как получить в select2 данные из модели

Сообщение svil »

В строчке

Код: Выделить всё

echo $form->field($model, 'cat1')->dropDownList($majorCatList, ['id' => 'cat-id']);
что такое $majorCatList?
Аватара пользователя
svil
Сообщения: 563
Зарегистрирован: 2018.02.12, 22:41

Re: Как получить в select2 данные из модели

Сообщение svil »

Код: Выделить всё

echo $form->field($model, 'course_id')->dropDownList($model->courses->name, ['id' => 'course_id']);
?>
Аватара пользователя
svil
Сообщения: 563
Зарегистрирован: 2018.02.12, 22:41

Re: Как получить в select2 данные из модели

Сообщение svil »

Почему выдает ошибку 'data' => $data->courses->name?

Код: Выделить всё

  <?php $form = ActiveForm::begin(); ?>

<?= $form->field($model, 'course_id')->widget(Select2::classname(), [
        'data' => $data->courses->name,
        'language' => 'ru',
        'options' => ['placeholder' => 'Выбор курса ...'],
        'pluginOptions' => [
            'allowClear' => true
        ],
    ]);
//debug($data);
    ?>
Аватара пользователя
svil
Сообщения: 563
Зарегистрирован: 2018.02.12, 22:41

Re: Как получить в select2 данные из модели

Сообщение svil »

Так тоже не работает

Код: Выделить всё

 <?php
    echo Select2::widget([
        'model' => $model,
        'attribute' => 'courseName',
       // 'data' => ArrayHelper::map(\app\models\Courses::findOne(['id'=> $model->course_id]),'name','name'),
       'data' => $model->courses->name,
        'options' => ['placeholder' => 'Select Product'],
        'pluginOptions' => [
            'allowClear' => true
        ],

    ]);
    ?>
Аватара пользователя
svil
Сообщения: 563
Зарегистрирован: 2018.02.12, 22:41

Re: Как получить в select2 данные из модели

Сообщение svil »

Из модели только в index для просмотра, в Форму только через контроллер так:
Контроллер

Код: Выделить всё

   public function actionCreate($course_id)
    {
        $item='file';
        $this->view->params['news'] = $item;

        $model = new Categories();
        $course_id =  Yii::$app->request->get('course_id');
        $data_ = Categories::find()->where(['course_id' => $course_id])->all();
        $data_c = Courses::find()->where(['id' => $course_id])->all();

        foreach ($data_c as $value) {
            $datac[$value->id]=$value->name;
        }
        foreach ($data_ as $value) {
            $data[$value->id]=$value->name;
        }
        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        }

        return $this->render('create', [
            'model' => $model,
            'course_id' => $course_id,
            'data' => $data,
            'datac' => $datac
        ]);
    }
Форма

Код: Выделить всё

<div class="categories-form">
   
    <?php $form = ActiveForm::begin(); ?>

<?= $form->field($model, 'course_id')->widget(Select2::classname(), [
    'data' => [$datac],
        'readonly' => true,
        'language' => 'ru',
        'pluginOptions' => [
            'allowClear' => true
        ],
    ]);
    ?>

    <?= $form->field($model, 'parent_id')->widget(Select2::classname(), [
        'data' => $data,
        'language' => 'ru',
        'options' => ['placeholder' => 'Выбор родительской категории ...'],
        'pluginOptions' => [
            'allowClear' => true
        ],
    ]);

    ?>

    <?= $form->field($model, 'name')->textarea(['rows' => 6]) ?>
CCCZen
Сообщения: 21
Зарегистрирован: 2018.04.01, 15:41

Re: Как получить в select2 данные из модели

Сообщение CCCZen »

Select ест массив, а не значение

Код: Выделить всё

 <?
    $val = [];
    switch ($model->status){
        case 1:
            $val = [0=>'asd',1=>'asd'];
            break;
        case 2:
	        $val = [0=>'2asd',1=>'2asd'];
            break;
    }



    ?>
    <div class="col-md-4">
		<?= $form->field($model, 'responsible')->widget(Select2::classname(), [
			'data' =>$val,
			'options' => ['placeholder' => 'Select a state ...'],
			'pluginOptions' => [
				'allowClear' => true
			],
		]);?>
    </div>

в примере варианты выбора зависят от поля статус модели(если все обернуто в пиджак то работает как вам надо)
Ответить