PHP.SU

Программирование на PHP, MySQL и другие веб-технологии
PHP.SU Портал     На главную страницу форума Главная     Помощь Помощь     Поиск Поиск     Поиск Яндекс Поиск Яндекс     Вакансии  Пользователи Пользователи

Страниц (2): « 1 [2]

> Найдено сообщений: 19
Sandro_s Отправлено: 26 Августа, 2017 - 18:17:02 • Тема: Создание и сохранение новых тэгов в блоге (Yii2) • Форум: CMS и фреймворки

Ответов: 14
Просмотров: 3793
andrewkard пишет:
Вы используете ActiveRecord, соотв. нужно иметь такую колонку в БД


Какую колонку именно? В БД есть таблица Тag. Ошибка указывает на то, что в модели Tag нет атрибута tag. В ней есть id есть name, а tag нету. Но вот тут (в тексте ошибки есть четко файл и номер строки, которая вызвала ошибку):

CODE (htmlphp):
скопировать код в буфер обмена
  1. $this->newtags =\yii\helpers\ArrayHelper::map($this->tags,'tag','tag');


т.е. я пытаюсь обратиться к несуществующему атрибуту. Но как это исправить?
Sandro_s Отправлено: 25 Августа, 2017 - 23:16:08 • Тема: Установка виджетов даты и времени в Yii2 • Форум: CMS и фреймворки

Ответов: 17
Просмотров: 2801
Сайт имеет такую структуру: в site - public (admin, assets, uploads) и yii2 - fronted и backend. В vendor находится блог, как отдельный модуль. Папка ' time', находиться в dir: yii2\ backend\views\time


Но в админ панели слева нет вкладки: 'Time".

Возможно, нужно вставить её в html шаблоне. Но как его создать и где добавить?

yii2\ backend\views\layouts\left.php

PHP:
скопировать код в буфер обмена
  1. <aside class="main-sidebar">
  2.  
  3.     <section class="sidebar">
  4.  
  5.         <!-- Sidebar user panel -->
  6.         <div class="user-panel">
  7.             <div class="pull-left image">
  8.                 <img src="<?= $directoryAsset ?>/img/user2-160x160.jpg" class="img-circle" alt="User Image"/>
  9.             </div>
  10.             <div class="pull-left info">
  11.                 <p>Sandros</p>
  12.  
  13.                 <a href="#"><i class="fa fa-circle text-success"></i> Online</a>
  14.             </div>
  15.         </div>
  16.  
  17.         <!-- search form -->
  18.         <form action="#" method="get" class="sidebar-form">
  19.             <div class="input-group">
  20.                 <input type="text" name="q" class="form-control" placeholder="Поиск..."/>
  21.               <span class="input-group-btn">
  22.                 <button type='submit' name='search' id='search-btn' class="btn btn-flat"><i class="fa fa-search"></i>
  23.                 </button>
  24.               </span>
  25.             </div>
  26.         </form>
  27.         <!-- /.search form -->
  28.  
  29.         <?= dmstr\widgets\Menu::widget(
  30.             [
  31.                 'options' => ['class' => 'sidebar-menu'],
  32.                 'items' => [
  33.                     ['label' => 'Menu Yii2', 'options' => ['class' => 'header']],
  34.                    ['label' => 'страницы', 'url' => ['/article']],
  35.                    ['label' => 'link', 'url' => '#'],
  36.                     ['label' => 'Блог', 'icon' => 'pencil', 'url' => ['/blog']],
  37.                     ['label' => 'Time', 'icon' => 'Time', 'url' => ['/Time']],
  38.                     ['label' => 'Теги', 'icon' => 'tags', 'url' => ['/tag']],
  39.                     ['label' => 'Gii', 'icon' => 'file-code-o', 'url' => ['/gii']],
  40.                     ['label' => 'Debug', 'icon' => 'dashboard', 'url' => ['/debug']],
  41.                     ['label' => 'Login', 'url' => ['site/login'], 'visible' => Yii::$app->user->isGuest],
  42.                     [
  43.                         'label' => 'Same tools',
  44.                         'icon' => 'share',
  45.                         'url' => '#',
  46.                         'items' => [
  47.                             ['label' => 'Генератор кода Gii', 'icon' => 'file-code-o', 'url' => ['/gii'],],
  48.                             ['label' => 'Debug панель', 'icon' => 'dashboard', 'url' => ['/debug'],],
  49.                               ['label' => 'Менеджер настроек', 'icon' => 'cog', 'url' => ['/settings'],],
  50.                             ['label' => 'SEO модуль', 'icon' => 'globe', 'url' => ['/seo'],],
  51.                             [
  52.                                 'label' => 'Level One',
  53.                                 'icon' => 'circle-o',
  54.                                 'url' => '#',
  55.                                 'items' => [
  56.                                     ['label' => 'Level Two', 'icon' => 'circle-o', 'url' => '#',],
  57.                                     [
  58.                                         'label' => 'Level Two',
  59.                                         'icon' => 'circle-o',
  60.                                         'url' => '#',
  61.                                         'items' => [
  62.                                             ['label' => 'Level Three', 'icon' => 'circle-o', 'url' => '#',],
  63.                                             ['label' => 'Level Three', 'icon' => 'circle-o', 'url' => '#',],
  64.                                         ],
  65.                                     ],
  66.                                 ],
  67.                             ],
  68.                         ],
  69.                     ],
  70.                 ],
  71.             ]
  72.         ) ?>
  73.  
  74.     </section>
  75.  
  76. </aside>
  77.  
Sandro_s Отправлено: 25 Августа, 2017 - 22:48:18 • Тема: Создание и сохранение новых тэгов в блоге (Yii2) • Форум: CMS и фреймворки

Ответов: 14
Просмотров: 3793
.
Sandro_s Отправлено: 25 Августа, 2017 - 22:45:49 • Тема: Создание и сохранение новых тэгов в блоге (Yii2) • Форум: CMS и фреймворки

Ответов: 14
Просмотров: 3793
Пробую использовать метод с тэгами, используя модели и события. Что нужно изменить здесь, чтобы можно было добавлять произвольные тэги и как решить ошибку: 'Getting unknown property medeyacom\blog\models\Tag::tag'?

В function afterSave также используется новая переменная $old_tags, но нужно ли её как-то объявлять где-нибудь?

Tag.php
PHP:
скопировать код в буфер обмена
  1. <?PHP
  2.  
  3. namespace medeyacom\blog\models;
  4.  
  5.  
  6. use Yii;
  7.  
  8. /**
  9.  * This is the model class for table "tag".
  10.  *
  11.  * @property integer $id
  12.  * @property string $name
  13.  */
  14. class Tag extends \yii\db\ActiveRecord
  15. {
  16.     /**
  17.      * @inheritdoc
  18.      */
  19.     public static function tableName()
  20.     {
  21.         return 'tag';
  22.     }
  23.  
  24.     /**
  25.      * @inheritdoc
  26.      */
  27.     public function rules()
  28.     {
  29.         return [
  30.             [['name'], 'required'],
  31.             [['name'], 'string', 'max' => 50],
  32.         ];
  33.     }
  34.  
  35.     /**
  36.      * @inheritdoc
  37.      */
  38.     public function attributeLabels()
  39.     {
  40.         return [
  41.             'id' => 'ID',
  42.             'name' => 'Name',
  43.         ];
  44.     }
  45. }
  46.  


Blog.php

PHP:
скопировать код в буфер обмена
  1.  
  2. <?PHP
  3.  
  4. namespace medeyacom\blog\models;
  5.  
  6. use common\components\behaviors\StatusBehavior;
  7. use Yii;
  8. use yii\behaviors\TimestampBehavior;
  9. use yii\db\ActiveRecord;
  10. use yii\db\Expression;
  11. use yii\helpers\ArrayHelper;
  12. use yii\helpers\Url;
  13. use yii\web\UploadedFile;
  14. use common\models\User;
  15. use common\models\ImageManager;
  16.  
  17. /**
  18.  * This is the model class for table "blog".
  19.  *
  20.  * @property integer $id
  21.  * @property string $title
  22.  * @property string $text
  23.  * @property string $image
  24.  * @property string $url
  25.  * @property string $date_create
  26.  * @property string $date_update
  27.  * @property integer $status_id
  28.  * @property integer $sort
  29.  */
  30. class Blog extends ActiveRecord
  31. {
  32.     const STATUS_LIST = ['off','on'];
  33.     const IMAGES_SIZE = [
  34.         ['50','50'],
  35.         ['800',null],
  36.     ];
  37.     public $tags_array;
  38.     public $file;
  39.     public $newtags;
  40.  
  41.     /**
  42.      * @inheritdoc
  43.      */
  44.     public static function tableName()
  45.     {
  46.         return 'blog';
  47.     }
  48.  
  49.     public function behaviors()
  50.     {
  51.         return [
  52.             'timestampBehavior'=>[
  53.                 'class' => TimestampBehavior::className(),
  54.                 'createdAtAttribute' => 'date_create',
  55.                 'updatedAtAttribute' => 'date_update',
  56.                 'value' => new Expression('NOW()'),
  57.             ],
  58.             'statusBehavior'=>[
  59.                 'class' => StatusBehavior::className(),
  60.                 'statusList' => self::STATUS_LIST,
  61.             ]
  62.         ];
  63.     }
  64.  
  65.     /**
  66.      * @inheritdoc
  67.      */
  68.     public function rules()
  69.     {
  70.         return [
  71.             [['title', 'url'], 'required'],
  72.             [['text'], 'string'],
  73.             [['url'], 'unique'],
  74.             [['status_id', 'sort'], 'integer'],
  75.             [['sort'], 'integer', 'max'=>99, 'min'=>1],
  76.             [['title', 'url'], 'string', 'max' => 150],
  77.             [['image'], 'string', 'max' => 100],
  78.             [['file'], 'image'],
  79.             [['tags_array','date_create','date_update'], 'safe'],];
  80.     }
  81.  
  82.     /**
  83.      * @inheritdoc
  84.      */
  85.     public function attributeLabels()
  86.     {
  87.         return [
  88.             'id' => 'ID',
  89.             'title' => 'Заголовок',
  90.             'text' => 'Текст',
  91.             'url' => 'ЧПУ',
  92.             'status_id' => 'Статус',
  93.             'sort' => 'Сортировка',
  94.             'tags_array' => 'Теги',
  95.             'image' => 'Картинка',
  96.             'file' => 'Картинка',
  97.             'tagsAsString' => 'Теги',
  98.             'author.username' => 'Имя Автора',
  99.             'author.email' => 'Почта Автора',
  100.             'date_update' => 'Обновлено',
  101.             'date_create' => 'Создано',
  102.             'smallImage'=> 'Картинка',
  103.         ];
  104.     }
  105.  
  106.  
  107.     public function getAuthor(){
  108.         return $this->hasOne(User::className(),['id'=>'user_id']);
  109.     }
  110.     public function getImages()
  111.     {
  112.         return $this->hasMany(ImageManager::className(), ['item_id' => 'id'])->andWhere(['class'=>self::tableName()])->orderBy('sort');
  113.     }
  114.     public function getImagesLinks()
  115.     {
  116.         return ArrayHelper::getColumn($this->images,'imageUrl');
  117.     }
  118.     public function getImagesLinksData()
  119.     {
  120.         return ArrayHelper::toArray($this->images,[
  121.                 ImageManager::className() => [
  122.                     'caption'=>'name',
  123.                     'key'=>'id',
  124.                 ]]
  125.         );
  126.     }
  127.     public function getBlogTag(){
  128.         return $this->hasMany(BlogTag::className(),['blog_id'=>'id']);
  129.     }
  130.  
  131.     public function getTags()
  132.     {
  133.         return $this->hasMany(Tag::className(), ['id' => 'tag_id'])->via('blogTag');
  134.     }
  135.  
  136.     public function getTagsAsString()
  137.     {
  138.         $arr = \yii\helpers\ArrayHelper::map($this->tags,'id','name');
  139.         return implode(', ',$arr);
  140.     }
  141.  
  142.     public function getSmallImage()
  143.     {
  144.         if($this->image){
  145.             $path = str_replace('admin.','',Url::home(true)).'uploads/images/blog/50x50/'.$this->image;
  146.         }else{
  147.             $path = str_replace('admin.','',Url::home(true)).'uploads/images/ss.jpg';
  148.         }
  149.         return $path;
  150.     }
  151.  
  152.  
  153.   public function beforeDelete()
  154.      
  155.         {   if (parent::beforeDelete()) {
  156.                 $dir = Yii::getAlias('@images').'/blog/';
  157.              /*if($this->image != '')*/
  158.            if(!empty($this->image))
  159.             /* if($this->image && file_exists($dir.$this->image))*/
  160.         if (isset($this->image) && file_exists($idr.$this->image)){
  161.               unlink($dir.$this->image);
  162.                 }
  163.           /* if(file_exists($dir.$this->image)){
  164.                     unlink($dir.$this->image);
  165.                 }*/
  166.  
  167.  
  168.             foreach (self::IMAGES_SIZE as $size){
  169.                     $size_dir = $size[0].'x';
  170.             if($size[1] !== null)
  171.                         $size_dir .= $size[1];
  172.            /* if(file_exists($dir.$this->image)){
  173.                         unlink($dir.$size_dir.'/'.$this->image);
  174.                     }*/
  175.                 }
  176.        
  177.            BlogTag::deleteAll(['blog_id'=>$this->id]);
  178.            return true;
  179.                  } else {
  180.             return false;
  181.               }
  182.         }
  183.    
  184.  
  185.  
  186.     public function afterFind()
  187.     {
  188.        /* parent::afterFind();
  189.         $this->tags_array = $this->tags;*/
  190.         $this->newtags =\yii\helpers\ArrayHelper::map($this->tags,'tag','tag');
  191.     }
  192.  
  193.  
  194.   public function afterSave($insert, $changedAttributes)
  195.     {
  196.         parent::afterSave($insert, $changedAttributes);
  197.       /*  $arr = \yii\helpers\ArrayHelper::map($this->tags,'id','id');
  198.         foreach ($this->tags_array as $one){
  199.             if(!in_array($one,$arr)){
  200.                 $model = new BlogTag();
  201.                 $model->blog_id = $this->id;
  202.                 $model->tag_id = $one;
  203.                 $model->save();
  204.             }
  205.             if(isset($arr[$one])){
  206.                 unset($arr[$one]);
  207.             }*/
  208.  
  209.              if (is_array($this->newtags)) {
  210.                 $old_tags = ArrayHelper::map($this->tags,'tag','id');
  211.                 foreach ($this ->newtags as $one_new_tag) {
  212.                     if (isset($old_tags[$one_new_tag])) {
  213.                         unset($old_tags[$one_new_tag]);
  214.                    
  215.                     } else{
  216.                        if($tg = $this->createNewTag($one_new_tag)){
  217.                         Yii::$app->session->addFlash('success','добавлен тег' . $one_new_tag);
  218.                     }else{
  219.                         Yii::$app->session->addFlash('error','тег' . $one_new_tag . 'тег не добавился');
  220.                        }
  221.                     }
  222.                 }
  223.                
  224.         BlogTag::deleteAll(['and',['blog_id'=>$this->id],['tag_id'=>$old_tags]]);
  225.     }else{
  226.         BlogTag::deleteAll(['blog_id'=>$this->id]);
  227.        /* BlogTag::deleteAll(['tag_id'=>$arr]);*/
  228.     }
  229. }
  230.  
  231.  
  232.     private function createNewTag ($new_tag) {
  233.         if(!$tag = Tag::find()->andWhere(['tag'=>$new_tag])->one()){
  234.             $tag = new Tag();
  235.             $tag ->tag = $new_tag;
  236.             if(!$tag->save()) {
  237.                 $tag =null;
  238.             }
  239.         }
  240.         if ($tag instanceof Tag) {
  241.             $blog_tag = new BlogTag();
  242.             $blog_tag->blog_id = $this->id;
  243.             $blog_tag->tag_id = $tag->id;
  244.             if($blog_tag->save())
  245.                 return $blog_tag->id;
  246.         }
  247.         return false;
  248.     }
  249.  
  250.  
  251.  
  252.  
  253.     public function beforeSave($insert)
  254.     {
  255.         if($file = UploadedFile::getInstance($this, 'file')){
  256.             $dir = Yii::getAlias('@images').'/blog/';
  257.             if(file_exists($dir.$this->image)){
  258.                 unlink($dir.$this->image);
  259.             }
  260.             if(file_exists($dir.'50x50/'.$this->image)){
  261.                 unlink($dir.'50x50/'.$this->image);
  262.             }
  263.             if(file_exists($dir.'800x/'.$this->image)){
  264.                 unlink($dir.'800x/'.$this->image);
  265.             }
  266.             $this->image = strtotime('now').'_'.Yii::$app->getSecurity()->generateRandomString(6)  . '.' . $file->extension;
  267.             $file->saveAs($dir.$this->image);
  268.             $imag = Yii::$app->image->load($dir.$this->image);
  269.             $imag->background('#fff',0);
  270.             $imag->resize('50','50', Yii\image\drivers\Image::INVERSE);
  271.             $imag->crop('50','50');
  272.             $imag->save($dir.'50x50/'.$this->image, 90);
  273.             $imag = Yii::$app->image->load($dir.$this->image);
  274.             $imag->background('#fff',0);
  275.             $imag->resize('800',null, Yii\image\drivers\Image::INVERSE);
  276.             $imag->save($dir.'800x/'.$this->image, 90);
  277.         }
  278.         return parent::beforeSave($insert);
  279.     }
  280.  
  281.  
  282.  }
  283.  
  284.  
  285.  

Страниц (2): « 1 [2]
Powered by PHP  Powered By MySQL  Powered by Nginx  Valid CSS  RSS

 
Powered by ExBB FM 1.0 RC1. InvisionExBB