Но хочу разобраться, можно ли обойтись данными из модели.
Один ко многим две модели 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;
}
}
Код: Выделить всё
<?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;
}
}
Код: Выделить всё
<?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.');
}
}
Код: Выделить всё
<?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.');
}
}
Код: Выделить всё
<?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>