G
G
Greg Popov2016-05-15 19:49:34
Yii
Greg Popov, 2016-05-15 19:49:34

What is wrong with related insert Yii2?

Using the LAV45 extension , I connected multilingualism for content.
Now I can not understand why it does not add to the database during insert?
I was busy all day, checked everything, and I understand that I'm just green in Yii, as well as in development, and that's the whole trouble. Help, I'm stuck.
e16905ac48ee4c2eb3326ff6d1e20894.png
All fk are the same as pk in type, created using migrations.

<?php

namespace common\models\category;

use lav45\translate\TranslatedTrait;
use lav45\translate\TranslatedBehavior;
use Yii;


class Category extends \yii\db\ActiveRecord
{
    use TranslatedTrait;
    public $notIncludeInResult;
    public static function tableName()
    {
        return 'category';
    }
    public function rules()
    {
        return [
            [['parent_id', 'catalog_type'], 'integer'],
            [['icon_code'], 'string', 'max' => 50],

            [['id'], 'safe'],

            [['parent_id'], 'default', 'value' => null],
            [['catalog_type'], 'default', 'value' => 0],

            [['parent_id'], 'exist', 'skipOnError' => true,
                'targetClass' => Category::className(), 'targetAttribute' => ['parent_id' => 'id']],
        ];
    }

    public function behaviors()
    {
        return [
            [
                'class' => TranslatedBehavior::className(),
                'translateRelation' => 'categoryTranslates',
                'languageAttribute' => 'language_id',
                'translateAttributes' => [
                    'url_type_article',
                    'title',
                    'mkeywords',
                    'mdescription',
                ]
            ]
        ];
    }
    public function getParentTitle()
    {
        $parentId = $this->parent->id;
        return Category::find()->joinWith('category_translate')
            ->where(['category_translate.parent_id' => $parentId])->one();
    }

    public function getParentCategoriesTree()
    {
        $categories = CategoryTranslate::find()
            ->joinWith('category')->all();

        $list = [];

        if (!empty($categories)){
            foreach ($categories as $item){
                $list[$item->id] = [
                    'id'     => $item->id,
                    'title'  => (isset($item->category->parent_id) ?
                        $item->category->parent_id.' - '.$item->title :
                        $item->title
                    ),
                    'parent' => (isset($item->category->parent_id) ?
                        $item->category->parent_id :
                        null
                    ),
                ];
            }
            if ($this->notIncludeInResult !== null){
                unset($list[intval($this->notIncludeInResult)]);
            }

            return $list;

        }else{
            return false;
        }

    }

    
    public function getParent()
    {
        return $this->hasOne(Category::className(), ['id' => 'parent_id']);
    }


    public function getCategories()
    {
        return $this->hasMany(Category::className(), ['parent_id' => 'id']);
    }

    public function getCategoryTranslates()
    {
        return $this->hasMany(CategoryTranslate::className(), ['category_id' => 'id']);
    }

   
    public static function find()
    {
        return new CategoryQuery(get_called_class());
    }

}

<?php

namespace common\models;

use common\models\category\CategoryTranslate;
use Locale;
use Yii;
use yii\db\ActiveRecord;

class Language extends ActiveRecord
{

    const STATUS_DISABLED  = 0;
    const STATUS_ACTIVATED = 1;

    static $current = null;

    public static function tableName()
    {
        return 'language';
    }

    public function behaviors()
    {
        return [
            'timestamp' => [
                'class' => 'yii\behaviors\TimestampBehavior',
                'attributes' => [
                    ActiveRecord::EVENT_BEFORE_INSERT => ['date_create', 'date_update'],
                    ActiveRecord::EVENT_BEFORE_UPDATE => ['date_update'],
                ],
            ],
        ];
    }
    static function getCurrent()
    {
        if( self::$current === null ){
            self::$current = self::getDefaultLang();
        }
        return self::$current;
    }

    public function isSourceLanguage()
    {
        return $this->getOldAttribute('id') == Locale::getPrimaryLanguage(Yii::$app->sourceLanguage);
    }

    static function setCurrent($url = null)
    {
        $language = self::getLangByUrl($url);
        self::$current = ($language === null) ? self::getDefaultLang() : $language;
        Yii::$app->language = self::$current->local;
    }

    static function getDefaultLang()
    {
        return Language::find()->where('`default` = :default', [':default' => 1])->one();
    }
    
    static function getLangByUrl($url = null)
    {
        if ($url === null) {
            return null;
        } else {
            $language = Language::find()->where('url_address = :url_address', [':url_address' => $url])->one();
            if ( $language === null ) {
                return null;
            }else{
                return $language;
            }
        }
    }

    
    public static function getList($active = false)
    {
        $query = static::find()
            ->select(['name', 'id'])
            ->orderBy('id')
            ->indexBy('id');
        if ($active == true) {
            $query->active();
        }
        return $query->column();
    }


    
    public function rules()
    {
        return [
            [['url_address', 'local', 'name', 'date_updated', 'date_created'], 'required'],
            [['default', 'date_updated', 'date_created'], 'integer'],
            [['url_address', 'local', 'name'], 'string', 'max' => 255],
        ];
    }

   
    public function getCategoryTranslates()
    {
        return $this->hasMany(CategoryTranslate::className(), ['language_id' => 'id']);
    }

}

<?php

namespace common\models\category;

use common\models\Language;
use Yii;


class CategoryTranslate extends \yii\db\ActiveRecord
{
    
    public static function tableName()
    {
        return 'category_translate';
    }

    
    public function rules()
    {
        return [
            [['category_id', 'language_id'], 'integer'],
            [['mdescription'], 'string'],
            [['url_type_article'], 'trim'],
            [['language_id'], 'default', 'value' => 2],
            [['url_type_article', 'title', 'mkeywords'], 'string', 'max' => 255],
            [['category_id'], 'exist', 'skipOnError' => true, 'targetClass' => Category::className(), 'targetAttribute' => ['category_id' => 'id']],
            [['language_id'], 'exist', 'skipOnError' => true, 'targetClass' => Language::className(), 'targetAttribute' => ['language_id' => 'id']],
        ];
    }

    public function getCategory()
    {
        return $this->hasOne(Category::className(), ['id' => 'category_id']);
    }

   
    public function getLanguage()
    {
        return $this->hasOne(Language::className(), ['id' => 'language_id']);
    }

    
    public static function find()
    {
        return new CategoryTranslateQuery(get_called_class());
    }

    
    public function beforeSave($insert)
    {
        $this->url_type_article = str_replace(' ','_',$this->url_type_article);
        return parent::beforeSave($insert);
    }

}

The CategoryController is the standard CRUD, plus what I've been fiddling with all day:
<?php

    public function actionCreate()
    {
        $category = new Category();
        $category_translate = new CategoryTranslate();

        if ($category->load(Yii::$app->request->post()) && $category_translate->load(Yii::$app->request->post())) {

            $transaction = CategoryTranslate::getDb()->beginTransaction();
            try {

                $category->save();

                $category_translate->category_id = $category->id;
                $category_translate->language_id = $_POST['CategoryTranslate']['language_id'];
                
                $category_translate->save();


                $transaction->commit();
            } catch(\Exception $e) {
                $transaction->rollBack();
                throw $e;
            }

        } else {
            return $this->render('create', [
                'category' => $category,
                'category_translate' => $category_translate,
            ]);
        }
    }

  
}

view:
<?php

use yii\helpers\Html;
use yii\widgets\ActiveForm;
?>

<div class="category-form">

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

    <?= $form->field($category, 'id')->textInput() ?>

    <?= $form->field($category, 'parent_id')->textInput() ?>

    <?= $form->field($category_translate, 'title')->textInput() ?>

    <?= $form->field($category_translate, 'language_id')->textInput(['value'=>2]) ?>

    <?= $form->field($category_translate, 'url_type_article')->textInput() ?>

    <?= $form->field($category_translate, 'mkeywords')->textInput() ?>

    <?= $form->field($category_translate, 'mdescription')->textInput() ?>

    <?= $form->field($category, 'icon_code')->textInput(['maxlength' => true]) ?>

    <?= $form->field($category, 'catalog_type')->textInput() ?>

    <div class="form-group">
        <?= Html::submitButton($category->isNewRecord ? Yii::t('shop', 'Create') : Yii::t('shop', 'Update'), ['class' => $category->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
    </div>

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

</div>

When saving:
8eddb65aa7ca47ddb4c07d46bbf1363f.png

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question