Есть таблицы Series и Colors, связаны как hasMany через промежуточную таблицу SeriesColor. В форме добавления серий получаю в поле цвета, через
Код: Выделить всё
<?=$form->field($model, 'color')->listBox(ArrayHelper::map(Colors::find()->all(), 'id', 'name'),
[
'multiple' => true,
]);
?>
Модель
Код: Выделить всё
<?php
namespace app\modules\secret\models;
use Yii;
use app\models\CategoriesPrice;
use app\models\Styles;
use app\models\Country;
use app\models\Colors;
use app\models\SeriesColor;
use yii\db\ActiveRecord;
use app\models\Products;
class Series extends ActiveRecord
{
public function behaviors()
{
return [
'image' => [
'class' => 'rico\yii2images\behaviors\ImageBehave',
]
];
}
public $image;
public $gallery;
public $color;
public static function tableName()
{
return 'series';
}
public function rules()
{
return [
[['category_id', 'title', 'keywords', 'description', 'content', 'material', 'thickness'], 'string'],
[['name', 'category_id', 'title', 'keywords', 'description', 'category_price', 'material', 'style', 'countries'], 'required'],
[['category_price', 'style', 'countries'], 'integer'],
[['name'], 'string', 'max' => 80],
[['img'], 'string', 'max' => 200],
[['image'], 'file', 'extensions' => 'jpg, png, gif, tiff'],
[['gallery'], 'file', 'extensions' => 'jpg, png, gif, tiff', 'maxFiles' => 30],
];
}
public function getCategories()
{
return $this->hasOne(Categories::className(), ['id' => 'category_id']);
}
public function getCategoriesPrice()
{
return $this->hasOne(CategoriesPrice::className(), ['id' => 'category_price']);
}
public function getStyles()
{
return $this->hasOne(Styles::className(), ['id' => 'style']);
}
public function getCountry()
{
return $this->hasOne(Country::className(), ['id' => 'countries']);
}
public function getSeriesColor()
{
return $this->hasMany(SeriesColor::className(), ['serie_id' => 'id']);
}
public function getColors()
{
return $this->hasMany(Colors::className(), ['id' => 'color_id'])->via('seriesColor');
}
public function getProducts()
{
return $this->hasMany(Products::className(), ['serie_id' => 'id']);
}
public function attributeLabels()
{
return [
'id' => '№',
'title' => 'Заголовок',
'keywords' => 'Ключевики',
'description' => 'Мета описание',
'content' => 'Описание серии',
'name' => 'Название',
'category_id' => 'Категория',
'color' => 'Цвет',
'category_price' => 'Ценовая категория',
'material' => 'Используемые материалы',
'style' => 'Стиль',
'thickness' => 'Толщина деталей',
'countries' => 'Страна производства',
'image' => 'Картинка',
'gallery' => 'Множественная загрузка изображений (< 30 шт)',
];
}
public function upload(){
if ($this->validate()){
$path = 'upload/store/' . $this->image->baseName . '.' . $this->image->extension;
$this->image->saveAs($path);
$this->attachImage($path, true);
@unlink($path);
return true;
}
else{
return false;
}
}
public function uploadGallery(){
if ($this->validate()){
foreach ($this->gallery as $file){
$path = 'upload/store/' . $file->baseName . '.' . $file->extension;
$file->saveAs($path);
$this->attachImage($path);
@unlink($path);
}
return true;
}
else{
return false;
}
}
}
Код: Выделить всё
<?php
namespace app\modules\secret\controllers;
use Yii;
use app\models\Colors;
use app\modules\secret\models\Series;
use yii\data\ActiveDataProvider;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\web\UploadedFile;
class SeriesController extends Controller
{
public function behaviors()
{
return [
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'delete' => ['POST'],
],
],
];
}
public function actionIndex()
{
$dataProvider = new ActiveDataProvider([
'query' => Series::find()->with('categories', 'colors'),
]);
return $this->render('index', [
'dataProvider' => $dataProvider,
]);
}
public function actionView($id)
{
return $this->render('view', [
'model' => $this->findModel($id),
]);
}
public function actionCreate()
{
$model = new Series();
if ($model->load(Yii::$app->request->post()) && $model->save()) {
$model->image = UploadedFile::getInstance($model, 'image');
if ($model->image){
$model->upload();
}
unset($model->image);
$model->gallery = UploadedFile::getInstances($model, 'gallery');
$model->uploadGallery();
Yii::$app->session->setFlash('info', "Серия {$model->name} создана.");
return $this->redirect(['view', 'id' => $model->id]);
} else {
// Yii::$app->session->setFlash('info', 'Ошибка');
return $this->render('create', [
'model' => $model,
]);
}
}
public function actionUpdate($id)
{
$model = $this->findModel($id);
if ($model->load(Yii::$app->request->post()) && $model->save()) {
$model->image = UploadedFile::getInstance($model, 'image');
if ($model->image){
$model->upload();
}
unset($model->image);
$model->gallery = UploadedFile::getInstances($model, 'gallery');
$model->uploadGallery();
Yii::$app->session->setFlash('info', "Серия {$model->name} обновлена.");
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('update', [
'model' => $model,
]);
}
}
public function actionDelete($id)
{
$model = $this->findModel($id);
$this->findModel($id)->delete();
Yii::$app->session->setFlash('info', "Серия {$model->name} удалена.");
return $this->redirect(['index']);
}
protected function findModel($id)
{
if (($model = Series::findOne($id)) !== null) {
return $model;
} else {
throw new NotFoundHttpException('The requested page does not exist.');
}
}
}
Код: Выделить всё
<?php
use yii\helpers\Html;
use yii\bootstrap\ActiveForm;
use yii\helpers\ArrayHelper;
use app\modules\secret\models\Categories;
use app\models\Colors;
use app\models\CategoriesPrice;
use app\models\Country;
use app\models\Styles;
use mihaildev\ckeditor\CKEditor;
use mihaildev\elfinder\ElFinder;
use app\models\SeriesColor;
use app\models\Series;
mihaildev\elfinder\Assets::noConflict($this);
?>
<div class="series-form">
<?php $form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']]); ?>
<?= $form->field($model, 'name')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'content')->widget(CKEditor::className(),[
'editorOptions' => ElFinder::ckeditorOptions(['elfinder', 'path' => 'some/sub/path'],[/* Some CKEditor Options */]),
]); ?>
<?= $form->field($model, 'title')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'keywords')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'description')->textarea(['rows' => 3]) ?>
<?= $form->field($model, 'category_id')->dropDownList(ArrayHelper::map(Categories::find()->all(), 'id', 'name')) ?>
<?= $form->field($model, 'category_price')->dropDownList(ArrayHelper::map(CategoriesPrice::find()->all(), 'id', 'name')) ?>
<?=$form->field($model, 'color')->listBox(ArrayHelper::map(Colors::find()->all(), 'id', 'name'),
[
'multiple' => true,
// 'prompt' => 'Выберите один или несколько вариантов',
// 'style' => 'background:gray;color:#fff;'
]);
?>
<?= $form->field($model, 'material')->textarea(['rows' => 6]) ?>
<?= $form->field($model, 'thickness')->textarea(['rows' => 6]) ?>
<?= $form->field($model, 'style')->dropDownList(ArrayHelper::map(Styles::find()->all(), 'id', 'name')) ?>
<?= $form->field($model, 'countries')->dropDownList(ArrayHelper::map(Country::find()->all(), 'id', 'name')) ?>
<?= $form->field($model, 'image')->fileInput() ?>
<?= $form->field($model, 'gallery[]')->fileInput(['multiple' => true, 'accept' => 'image/*']) ?>
<div class="form-group">
<?= Html::submitButton($model->isNewRecord ? 'Создать' : 'Обновить', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>