Answer the question
In order to leave comments, you need to log in
Yii2 - why are new tags not being created?
There are 2 blog.php codes - none of them can create a new tag on the blog page and save it. Why is that?
<?php
namespace common\models;
use Yii;
use common\models\Blog;
use yii\db\ActiveRecord;
/**
* This is the model class for table "blog".
*
* @property integer $id
* @property string $title
* @property string $text
* @property string $url
* @property integer $status_id
* @property integer $sort
*/
class Blog extends \yii\db\ActiveRecord {
public $tags_array;
/**
* @inheritdoc
*/
public static function tableName()
{
return 'blog';
}
/**
* @inheritdoc
*/
public function rules()
{
return [
[['title', 'url'], 'required'],
[['text'], 'string'],
[['url'], 'unique'],
[['status_id', 'sort'], 'integer'],
[['sort'], 'integer','max'=>99, 'min'=>1],
[['title', 'url'], 'string', 'max' => 150],
[['tags_array'],'safe'],
];
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'id' => 'ID',
'title' => 'Заголовок',
'text' => 'Текст',
'url' => 'ЧПУ',
'status_id' => 'Статус',
'sort' => 'Сортировка',
'tags_array' => 'Тэги',
'tagsAsString' => 'Тэги',
'author.username'=>'Имя Автора',
'author.email'=>'Почта Автора',
];
}
public static function getStatusList() {
return ['off','on'];
}
public function getStatusName(){
$list = self::getStatusList();
return $list[$this->status_id];
}
public function getAuthor () {
return $this->hasOne (User::className(),['id'=>'user_id']);
}
public function getBlogTag () {
return $this->hasMany(BlogTag::className(),['blog_id'=>'id']);
}
public function getTags()
{
return $this->hasMany(Tag::className(),['id'=>'tag_id'])->via('blogTag');
}
public function getTagsAsString()
{
$arr = \yii\helpers\ArrayHelper::map($this->tags,'id','name');
return implode (', ',$arr);
}
public function afterFind()
{
$this->tags_array = $this->tags;
}
public function afterSave ($insert, $changedAttributes)
{
parent::afterSave($insert, $changedAttributes);
$arr = \yii\helpers\ArrayHelper::map($this->tags,'id','id');
foreach ($this->tags_array as $one) {
if(!in_array($one,$arr)){
$model = new BlogTag();
$model->blog_id = $this->id;
$model->tag_id = $one;
$model->save();
}
if(isset($arr[$one])) {
unset ($arr[$one]);
}
}
BlogTag::deleteAll(['tag_id'=>$arr]);
}
}
<?php
namespace common\models;
use Yii;
use common\models\Blog;
use yii\db\ActiveRecord;
/**
* This is the model class for table "blog".
*
* @property integer $id
* @property string $title
* @property string $text
*@property string $body
*@property string $date_publish
* @property string $url
* @property integer $status_id
* @property integer $sort
*/
class Blog extends \yii\db\ActiveRecord {
/* public $tags_array;*/
public $newtags;
/**
* @inheritdoc
*/
public static function tableName()
{
return 'blog';
}
/**
* @inheritdoc
*/
/*public function behaviors() error = Class 'common\models\AltBehavior' not found
{
return [
'alt' => [
'class' => AltBehavior::className(),
'attribute_title' => 'title',
'attribute_alt' =>'title',
],
];
}*/
/* @inheritdoc
*/
public function rules()
{
return [
[[ 'data_publish'], 'safe'],
[['title', 'url'], 'required'],
[['text'], 'string'],
[['url'], 'unique'],
[['status_id', 'sort'], 'integer'],
[['sort'], 'integer','max'=>99, 'min'=>1],
[['title', 'url'], 'string', 'max' => 150],
[['newtags'],'safe'],
[[ 'body'], 'string', 'max' =>10000],
[[ 'social_status_id'], 'default', 'value'=>0],
];
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'id' => 'ID',
'title' => 'Заголовок',
'text' => 'Текст',
'url' => 'ЧПУ',
'body' =>'Body',
'data_publish' => 'Data Publish',
'social_status_id' =>'Соц.сети',
'status_id' => 'Статус',
'sort' => 'Сортировка',
'newtags' => 'Тэги',
/*agsAsString' => 'Тэги',*/
'author.username'=>'Имя Автора',
'author.email'=>'Почта Автора',
];
}
public static function getStatusList() {
return ['пассив','актив', 'не сохранённый'];
}
public function getStatusName(){
$list = self::getStatusList();
return $list[$this->status_id];
}
/* public function getAuthor () {
return $this->hasOne (User::className(),['id'=>'user_id']);
}*/
/* public function getRandomImg () {
preg_match_all ('/<img[^>]+scr="?\'?([^"\']+)"?\'?[^>]*>/i, $this->body, $images, PREG_SET_ORDER);
$abs = Yii::$app->urlManagerFront->createAbsoluteUrl ('/');
$url = $abs.'images/nophoto.jpg;
if (is_array($images)){
$count = count ($images);
if ($count ->0) {
$num =$count - 1;
$rd = $rand($0,$num);
$url = $images [$rd][1];
}
}
return $url;
}*/
/*
public function getShort ($site=30) {
$simb = ($size+8)*6
$text = strip_tags($this->body);
$text = \yii\helpers\StringHelper::truncute ($text,$simb,false);
$text = \yii\helpers\StringHelper::truncuteWords ($text,$size,false);
return $text.'...';
}*/
public function getBlogTag () {
return $this->hasMany(BlogTag::className(),['blog_id'=>'id']);
}
public function getTags()
{
return $this->hasMany(Tag::className(),['id'=>'tag_id'])->via('blogTag');
}
public function beforeDelete()
{
if (parent::beforeDelete()) {
BlogTag::deleteAll (['blog_id'=>$this->id]);
return true;
}else{
return false;
}
}
/* public function getTagsAsString()
{
$arr = \yii\helpers\ArrayHelper::map($this->tags,'id','name');
return implode (', ',$arr);
}*/
public function afterFind()
{
$this->newtags = \yii\helpers\ArrayHelper::map($this->tags,'tag','tag');
}
public function afterSave ($insert, $changedAttributes)
{
parent::afterSave($insert, $changedAttributes);
if (is_array($this->newtags)) {
$old_tags = ArrayHelper::map($this->tags,'tag','id');
foreach ($this->newtags as $one_new_tag) {
if(isset ($old_tags[$one_new_tag])){
unset ($old_tags[$one_new_tag]);
}else{
if ($tag = $this ->createNewTag($one_new_tag)){
Yii::$app ->session ->addFlash('succsess','добавлен тег ' . $one_new_tag);
}else{
Yii::$app ->session ->addFlash('error','тег' .$one_new_tag . ' не добавился');
}
}
}
BlogTag::deleteAll(['and',['blog_id'=>$this->id],['tag_id'=>$old_tags]]);
}else{
BlogTag::deleteAll(['blog_id'=>$this->id]);
}
}
private function createNewTag ($new_tag) {
if ($tag =Tag::find()->andWhere(['tag' =>'new_tag'])->one()) {
$tag = new Tag ();
$tag ->tag = $new_tag;
if (!$tag->save() ) {
$tag = null;
}
}
if ($tag instanceof Tag) {
$blog_tag = new BlogTag();
$blog_tag -> blog_id = $this->id;
$blog_tag -> tag_id =$tag->id;
if ($blog_tag ->save())
return $blog_tag ->id;
}
return false;
}
}
Answer the question
In order to leave comments, you need to log in
Errors are quite clear. What is the problem? Can't read? Don't know English? What exactly can you help with? You threw out a bunch of code torn off from the project for no reason. If you need to solve errors:
Your variables appear out of thin air. Here is an example of a variable $text
. It just came out of thin air and the error clearly indicates this.
Next, you refer to a non-existent property of the object, and the error again unambiguously indicates this.
Read at least a quick tutorial on php.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question