PHP . SU
Программирование на PHP, MySQL и другие веб-технологии
Страниц (2): « 1 [2]
Найдено сообщений: 19
Sandro_s
Отправлено: 26 Августа, 2017 - 18:17:02 • Тема: Создание и сохранение новых тэгов в блоге (Yii2) • Форум: CMS и фреймворки
Ответов: 14 Просмотров: 3793
andrewkard пишет: Вы используете ActiveRecord, соотв. нужно иметь такую колонку в БД
Какую колонку именно? В БД есть таблица Тag. Ошибка указывает на то, что в модели Tag нет атрибута tag. В ней есть id есть name, а 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:
скопировать код в буфер обмена
<aside class="main-sidebar">
<section class="sidebar">
<!-- Sidebar user panel -->
<div class="user-panel">
<div class="pull-left image">
<img src="<?= $directoryAsset ?> /img/user2-160x160.jpg" class="img-circle" alt="User Image"/>
</div>
<div class="pull-left info">
<p>Sandros</p>
<a href="#"><i class="fa fa-circle text-success"></i> Online</a>
</div>
</div>
<!-- search form -->
<form action="#" method="get" class="sidebar-form">
<div class="input-group">
<input type="text" name="q" class="form-control" placeholder="Поиск..."/>
<span class="input-group-btn">
<button type='submit' name='search' id='search-btn' class="btn btn-flat"><i class="fa fa-search"></i>
</button>
</span>
</div>
</form>
<!-- /.search form -->
<?= dmstr\widgets\Menu:: widget (
[
'options' => [ 'class' => 'sidebar-menu' ] ,
'items' => [
[ 'label' => 'Menu Yii2' , 'options' => [ 'class' => 'header' ] ] ,
[ 'label' => 'страницы' , 'url' => [ '/article' ] ] ,
[ 'label' => 'link' , 'url' => '#' ] ,
[ 'label' => 'Блог' , 'icon' => 'pencil' , 'url' => [ '/blog' ] ] ,
[ 'label' => 'Time' , 'icon' => 'Time' , 'url' => [ '/Time' ] ] ,
[ 'label' => 'Теги' , 'icon' => 'tags' , 'url' => [ '/tag' ] ] ,
[ 'label' => 'Gii' , 'icon' => 'file-code-o' , 'url' => [ '/gii' ] ] ,
[ 'label' => 'Debug' , 'icon' => 'dashboard' , 'url' => [ '/debug' ] ] ,
[ 'label' => 'Login' , 'url' => [ 'site/login' ] , 'visible' => Yii:: $app -> user -> isGuest ] ,
[
'label' => 'Same tools' ,
'icon' => 'share' ,
'url' => '#' ,
'items' => [
[ 'label' => 'Генератор кода Gii' , 'icon' => 'file-code-o' , 'url' => [ '/gii' ] , ] ,
[ 'label' => 'Debug панель' , 'icon' => 'dashboard' , 'url' => [ '/debug' ] , ] ,
[ 'label' => 'Менеджер настроек' , 'icon' => 'cog' , 'url' => [ '/settings' ] , ] ,
[ 'label' => 'SEO модуль' , 'icon' => 'globe' , 'url' => [ '/seo' ] , ] ,
[
'label' => 'Level One' ,
'icon' => 'circle-o' ,
'url' => '#' ,
'items' => [
[ 'label' => 'Level Two' , 'icon' => 'circle-o' , 'url' => '#' , ] ,
[
'label' => 'Level Two' ,
'icon' => 'circle-o' ,
'url' => '#' ,
'items' => [
[ 'label' => 'Level Three' , 'icon' => 'circle-o' , 'url' => '#' , ] ,
[ 'label' => 'Level Three' , 'icon' => 'circle-o' , 'url' => '#' , ] ,
] ,
] ,
] ,
] ,
] ,
] ,
] ,
]
) ?>
</section>
</aside>
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:
скопировать код в буфер обмена
<?PHP
namespace medeyacom\blog\models;
use Yii;
/**
* This is the model class for table "tag".
*
* @property integer $id
* @property string $name
*/
class Tag extends \yii\db\ActiveRecord
{
/**
* @inheritdoc
*/
public static function tableName( )
{
return 'tag' ;
}
/**
* @inheritdoc
*/
public function rules( )
{
return [
[ [ 'name' ] , 'required' ] ,
[ [ 'name' ] , 'string' , 'max' => 50] ,
] ;
}
/**
* @inheritdoc
*/
public function attributeLabels( )
{
return [
'id' => 'ID' ,
'name' => 'Name' ,
] ;
}
}
Blog.php
PHP:
скопировать код в буфер обмена
<?PHP
namespace medeyacom\blog\models;
use common\components\behaviors\StatusBehavior;
use Yii;
use yii\behaviors\TimestampBehavior;
use yii\db\ActiveRecord;
use yii\db\Expression;
use yii\helpers\ArrayHelper;
use yii\helpers\Url;
use yii\web\UploadedFile;
use common\models\User;
use common\models\ImageManager;
/**
* This is the model class for table "blog".
*
* @property integer $id
* @property string $title
* @property string $text
* @property string $image
* @property string $url
* @property string $date_create
* @property string $date_update
* @property integer $status_id
* @property integer $sort
*/
class Blog extends ActiveRecord
{
const STATUS_LIST = [ 'off' , 'on' ] ;
const IMAGES_SIZE = [
[ '50' , '50' ] ,
[ '800' , null ] ,
] ;
public $tags_array ;
public $file ;
public $newtags ;
/**
* @inheritdoc
*/
public static function tableName( )
{
return 'blog' ;
}
public function behaviors( )
{
return [
'timestampBehavior' => [
'class' => TimestampBehavior:: className ( ) ,
'createdAtAttribute' => 'date_create' ,
'updatedAtAttribute' => 'date_update' ,
'value' => new Expression( 'NOW()' ) ,
] ,
'statusBehavior' => [
'class' => StatusBehavior:: className ( ) ,
'statusList' => self :: STATUS_LIST ,
]
] ;
}
/**
* @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 ] ,
[ [ 'image' ] , 'string' , 'max' => 100 ] ,
[ [ 'file' ] , 'image' ] ,
[ [ 'tags_array' , 'date_create' , 'date_update' ] , 'safe' ] , ] ;
}
/**
* @inheritdoc
*/
public function attributeLabels( )
{
return [
'id' => 'ID' ,
'title' => 'Заголовок' ,
'text' => 'Текст' ,
'url' => 'ЧПУ' ,
'status_id' => 'Статус' ,
'sort' => 'Сортировка' ,
'tags_array' => 'Теги' ,
'image' => 'Картинка' ,
'file' => 'Картинка' ,
'tagsAsString' => 'Теги' ,
'author.username' => 'Имя Автора' ,
'author.email' => 'Почта Автора' ,
'date_update' => 'Обновлено' ,
'date_create' => 'Создано' ,
'smallImage' => 'Картинка' ,
] ;
}
public function getAuthor( ) {
return $this -> hasOne ( User:: className ( ) , [ 'id' => 'user_id' ] ) ;
}
public function getImages( )
{
return $this -> hasMany ( ImageManager:: className ( ) , [ 'item_id' => 'id' ] ) -> andWhere ( [ 'class' => self:: tableName ( ) ] ) -> orderBy ( 'sort' ) ;
}
public function getImagesLinks( )
{
return ArrayHelper:: getColumn ( $this -> images , 'imageUrl' ) ;
}
public function getImagesLinksData( )
{
return ArrayHelper:: toArray ( $this -> images , [
ImageManager:: className ( ) => [
'caption' => 'name' ,
'key' => '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' ) ;
}
public function getSmallImage( )
{
if ( $this -> image ) {
$path = str_replace ( 'admin.' , '' , Url
:: home ( true ) ) . 'uploads/images/blog/50x50/' . $this -> image ; } else {
$path = str_replace ( 'admin.' , '' , Url
:: home ( true ) ) . 'uploads/images/ss.jpg' ; }
return $path ;
}
public function beforeDelete( )
{ if ( parent:: beforeDelete ( ) ) {
$dir = Yii:: getAlias ( '@images' ) . '/blog/' ;
/*if($this->image != '')*/
/* if($this->image && file_exists($dir.$this->image))*/
}
/* if(file_exists($dir.$this->image)){
unlink($dir.$this->image);
}*/
foreach ( self :: IMAGES_SIZE as $size ) {
$size_dir = $size [ 0 ] . 'x' ;
if ( $size [ 1] !== null )
$size_dir .= $size [ 1] ;
/* if(file_exists($dir.$this->image)){
unlink($dir.$size_dir.'/'.$this->image);
}*/
}
BlogTag:: deleteAll ( [ 'blog_id' => $this -> id ] ) ;
return true ;
} else {
return false ;
}
}
public function afterFind( )
{
/* parent::afterFind();
$this->tags_array = $this->tags;*/
$this -> newtags = \yii\helpers\ArrayHelper:: map ( $this -> tags , 'tag' , 'tag' ) ;
}
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]);
}*/
$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 ( $tg = $this -> createNewTag ( $one_new_tag ) ) {
Yii:: $app -> session -> addFlash ( 'success' , 'добавлен тег' . $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 ] ) ;
/* BlogTag::deleteAll(['tag_id'=>$arr]);*/
}
}
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 ;
}
public function beforeSave( $insert )
{
if ( $file = UploadedFile:: getInstance ( $this , 'file' ) ) {
$dir = Yii:: getAlias ( '@images' ) . '/blog/' ;
}
unlink ( $dir . '50x50/' . $this -> image ) ; }
unlink ( $dir . '800x/' . $this -> image ) ; }
$this -> image = strtotime ( 'now' ) . '_' . Yii
:: $app -> getSecurity ( ) -> generateRandomString ( 6 ) . '.' . $file -> extension ; $file -> saveAs ( $dir . $this -> image ) ;
$imag = Yii:: $app -> image -> load ( $dir . $this -> image ) ;
$imag -> background ( '#fff' , 0) ;
$imag -> resize ( '50' , '50' , Yii\image\drivers\Image:: INVERSE ) ;
$imag -> crop ( '50' , '50' ) ;
$imag -> save ( $dir . '50x50/' . $this -> image , 90) ;
$imag = Yii:: $app -> image -> load ( $dir . $this -> image ) ;
$imag -> background ( '#fff' , 0) ;
$imag -> resize ( '800' , null , Yii\image\drivers\Image:: INVERSE ) ;
$imag -> save ( $dir . '800x/' . $this -> image , 90) ;
}
return parent:: beforeSave ( $insert ) ;
}
}
Страниц (2): « 1 [2]
Powered by ExBB FM 1.0 RC1. InvisionExBB