Запись в БД не идет, ошибка редактора

Общие вопросы по использованию фреймворка. Если не знаете как что-то сделать и это про Yii, вам сюда.
Ответить
asisdes
Сообщения: 202
Зарегистрирован: 2013.10.03, 15:54

Запись в БД не идет, ошибка редактора

Сообщение asisdes »

Доброго дня!
Затык, друзья на самом простом, ужс.
решил подключить визуальный редактор

подключил аж но 2
ext.imperavi-redactor
и
yii-tinymce.TinyMce от Богдана

Самый прикол, все отображается ровно и даже загрузчики картинок работают, а изменения не пишуться в БД :o
а если все оставить как есть:
echo $form->textArea($model,'content',array('rows'=>5, 'cols'=>50, 'class'=>'input-xxlarge'));
все пишется!
Че за ерунда?!

Заголовок формы такой,

Код: Выделить всё

$form=$this->beginWidget('CActiveForm', array(
    'id'=>'news-form',
    'htmlOptions'=>array('autocomplete'=>'off',
    'enctype'=>'multipart/form-data',
        ),
    // Please note: When you enable ajax validation, make sure the corresponding
    // controller action is handling ajax validation correctly.
    // There is a call to performAjaxValidation() commented in generated controller code.
    // See class documentation of CActiveForm for details on this.
    'enableAjaxValidation'=>false,
));

Код: Выделить всё

<?php echo $form->labelEx($model,'content'); ?>
        <?php //echo $form->textArea($model,'content',array('rows'=>5, 'cols'=>50, 'class'=>'input-xxlarge')); ?>

        <? 
        //Yii::import('ext.imperavi-redactor-widget-master.ImperaviRedactorWidget');
        /*
        $this->widget('ImperaviRedactorWidget', array(
        // You can either use it for model attribute
        'model' => $model,
        'attribute' => 'content',
    
        // or just for input field
        //'name' => 'content',
    
        // Some options, see http://imperavi.com/redactor/docs/
        'options' => array(

        'imageUpload'=>$this->createUrl('imgUpload'),
        'imageUploadErrorCallback'=>'js:function(obj, json){ alert(json.error); }', // function to show upload error to user

        'fileUpload'=>$this->createUrl('fileUpload'),
        'fileUploadErrorCallback'=>'js:function(obj, json){ alert(json.error); }',
        
        // if you are using CSRF protection – add following:
        'uploadFields'=>array(
            Yii::app()->request->csrfTokenName => Yii::app()->request->csrfToken,
        ),
            'lang' => 'ru',
            'toolbar' => true,
            'iframe' => false,
            'css' => 'wym.css',
        ),
        'htmlOptions'=>array(
                'rows'=>25,
                'cols'=>200,
                'style'=>'width:90%;height:500px;'
            ),
        ));
        */
        
        $this->widget('ext.yii-tinymce.TinyMce', array(
            'model' => $model,
            'attribute' => 'content',
            // Optional config
            //'spellcheckerUrl' => array('tinyMce/spellchecker'),
            // or use yandex spell: http://api.yandex.ru/speller/doc/dg/tasks/how-to-spellcheck-tinymce.xml
            'spellcheckerUrl' => 'http://speller.yandex.net/services/tinyspell',
            'fileManager' => array(
                'class' => 'ext.elFinder.TinyMceElFinder',
                'connectorRoute'=>'admin/elfinder/connector',
            ),
            'htmlOptions' => array(
                'rows' => 6,
                'cols' => 60,
            ),
        ));

        ?>
на что стоит обратить внимание?
посмотрел HTML на выходе все ровно кажись

Код: Выделить всё

<div class="row">

        <label for="News_content">Текст</label>                <textarea rows="6" cols="60" id="News_content" name="News[content]">07 января завершился VI Фестиваль итальянской кухни “BUONA ITALIA 2013”. Грандиозное мероприятие проходило в блестящем банкетном зале комплекса Korston Hotels Moscow. В этот вечер рестораны-участники Фестиваля еще раз представили гостям самые необыкновенн</textarea>            </div>
есть код еще Update, может из-за него

Код: Выделить всё

public function actionUpdate($id)
    {
        $model = $this->loadModel($id);
        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);
        if(isset($_POST['News']))
        {
            $model->attributes = $_POST['News'];
        
            $model->uploadImg = CUploadedFile::getInstance($model,'uploadImg');
            $model->uploadPre = CUploadedFile::getInstance($model,'uploadPre');
            
            if ($model->uploadImg) {
                $sourcePathLogo = pathinfo($model->uploadImg->getName());
                $sourcePathExtLogo = $sourcePathLogo['extension'];
                $arrayExtLogo = array('jpg', 'png', 'gif');

                $file_name_logo = self::newFileNameLogo($id, $sourcePathExtLogo);
                $model->logo = $file_name_logo;
                //Генерируем новое имя картинки
            }

            if ($model->uploadPre) {
                $sourcePathPre = pathinfo($model->uploadPre->getName());
                $sourcePathExtPre = $sourcePathPre['extension'];
                $arrayExtPre = array('jpg', 'png', 'gif');

                $file_name_preview = self::newFileNamePre($id, $sourcePathExtPre);
                $model->preview = $file_name_preview;
                //Генерируем новое имя картинки
            }

            $model->lastupdate = time();

            if($model->save())
                Yii::app()->user->setFlash('updateNews','Вы удачно обновили информацию');
                if ($model->uploadImg && (in_array($sourcePathExtLogo, $arrayExtLogo, true))==TRUE) 
                { 
                    $model->uploadImg->saveAs('upload/news/logo/'.$file_name_logo);
                    $image = Yii::app()->image->load('upload/news/logo/'.$file_name_logo);
                    //$image->resize(100, 100);
                    $image->quality(100)->crop(200, 200);
                    $image->save(); 
                }
                
                if ($model->uploadPre && (in_array($sourcePathExtPre, $arrayExtPre, true))==TRUE) 
                { 
                    $model->uploadPre->saveAs('upload/news/preview/'.$file_name_preview); 
                    $image = Yii::app()->image->load('upload/news/preview/'.$file_name_preview);
                    //$image->resize(100, 100);
                    $image->quality(100)->crop(600, 350);
                    $image->save();
                }

                $this->redirect(array('view','id'=>$model->id));
        }

        $this->render('update',array(
            'model'=>$model,
        ));
    }
Изображение
Аватара пользователя
radamir
Сообщения: 142
Зарегистрирован: 2009.08.10, 08:02
Откуда: Новосибирск

Re: Запись в БД не идет, ошибка редактора

Сообщение radamir »

Еще бы код модели News посмотреть.
asisdes
Сообщения: 202
Зарегистрирован: 2013.10.03, 15:54

Re: Запись в БД не идет, ошибка редактора

Сообщение asisdes »

Код: Выделить всё

<?php

/**
 * This is the model class for table "news".
 *
 * The followings are the available columns in table 'news':
 * @property integer $id
 * @property string $title
 * @property string $content
 * @property string $alias
 * @property string $metakey
 * @property string $metadesc
 * @property string $logo
 * @property integer $views
 * @property string $category
 * @property string $tags
 * @property integer $featured
 * @property integer $claim
 * @property string $lastupdate
 * @property string $pubdate
 * @property string $moddate
 * @property string $expdate
 * @property integer $status
 * @property integer $author_id
 * @property integer $gallery_id
 * @property integer $comment_id
 * @property integer $rating_id
 * @property integer $place_id
 * @property integer $label
 * @property integer $like
 * @property string $preview
 */
class News extends CActiveRecord
{
    
    protected $categories_array;
    public $search_category = '';
    
    public $uploadImg; // атрибут для хранения загружаемой картинки статьи
    public $deleteImg; // атрибут для удаления уже загруженной картинки

    public $uploadPre; // атрибут для хранения загружаемой картинки статьи
    public $deletePre; // атрибут для удаления уже загруженной картинки
        
    /**
     * @return string the associated database table name
     */
    public function tableName()
    {
        return 'news';
    }

    /**
     * @return array validation rules for model attributes.
     */
    public function rules()
    {
        // NOTE: you should only define rules for those attributes that
        // will receive user inputs.
        return array(
            array('title, alias', 'required'),
            array('views, featured, claim, status, author_id, gallery_id, comment_id, rating_id, place_id, like, label', 'numerical', 'integerOnly'=>true),
            array('title, content, alias, logo, category, tags, lastupdate, pubdate, moddate, expdate', 'length', 'max'=>255),
            array('metakey, metadesc', 'safe'),
 
            //array('categoriesArray', 'safe'),
            array('search_category', 'safe', 'on'=>'search'),


            array('deletePre', 'boolean'),

            array('uploadPre', 'file', 
                'types'=>'jpg, gif, png', // 
                'maxSize'=>1024 * 1024 * 5, // 5 MB
                'allowEmpty'=>true,
                'tooLarge'=>'Файл весит больше 5 MB. Пожалуйста, загрузите файл меньшего размера.',
            ),
            
            array('deleteImg', 'boolean'),
            
            array('logo', 'length', 'max'=>255),
            array('preview', 'length', 'max'=>255),
            
            
            array('uploadImg', 'file', 
                'types'=>'jpg, gif, png', // 
                'maxSize'=>1024 * 1024 * 5, // 5 MB
                'allowEmpty'=>true,
                'tooLarge'=>'Файл весит больше 5 MB. Пожалуйста, загрузите файл меньшего размера.',
            ),
            
            array('alias','ext.LocoTranslitFilter','translitAttribute'=>'title'),
            
            // The following rule is used by search().
            // @todo Please remove those attributes that should not be searched.
            array('id, title, content, alias, metakey, metadesc, logo, views, category, tags, featured, claim, lastupdate, pubdate, moddate, expdate, status, author_id, gallery_id, comment_id, rating_id, place_id', 'safe', 'on'=>'search'),
        );
    }



    
    /**
     * @return array relational rules.
     */
    public function relations()
    {
        // NOTE: you may need to adjust the relation name and the related
        // class name for the relations automatically generated below.
        return array(
            'categories'=>array(self::MANY_MANY, 'Category', 'newscategory(news_id, category_id)'),
            'news_categories'=>array(self::HAS_MANY, 'Newscategory', 'news_id'),

            'news_place'=>array(self::BELONGS_TO, 'Place', 'place_id'),
            'news_author'=>array(self::BELONGS_TO, 'User', 'author_id'),
            
            'labelLink' => array(self::BELONGS_TO, 'Labels', 'label'),
        );
    }

    public function behaviors()
    {
        return array(
            'DMultiplyListBehavior'=>array(
                 'class'=>'DMultiplyListBehavior',
                 'attribute'=>'categoriesArray',
                 'relation'=>'categories',
                 'relationPk'=>'id',
            ),
        );
    }
    
    protected function afterSave()
    {
        $this->refreshCategories();
        parent::afterSave();
    }
 
    protected function refreshCategories()
    {
        $categories = $this->categoriesArray;

        Newscategory::model()->deleteAllByAttributes(array('news_id'=>$this->id));
 
        if (is_array($categories))
        {
            foreach ($categories as $id)
            {
                if (Category::model()->exists('id=:id', array(':id'=>$id)))
                {                
                    $postCat = new Newscategory();
                    $postCat->news_id = $this->id;
                    $postCat->category_id = $id;
                    $postCat->save();
                }
            }
        }
    }
    
    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels()
    {
        return array(
            'id' => 'ID',
            'title' => 'Заголовок',
            'content' => 'Текст',
            'alias' => 'ЧПУ заголовок',
            'metakey' => 'Ключевые слова',
            'metadesc' => 'Описание',
            'logo' => 'Логотип',
            'preview' => 'Превью',
            'views' => 'Просмотров',
            'category' => 'Категория',
            'tags' => 'Тэги',
            'featured' => 'Избранное',
            'claim' => 'Жалоба',
            'lastupdate' => 'Обновлено',
            'pubdate' => 'Опубликовано',
            'moddate' => 'Moddate',
            'expdate' => 'Expdate',
            'status' => 'Статус',
            'author_id' => 'Автор',
            'gallery_id' => 'Галлерея',
            'comment_id' => 'Коментарии',
            'rating_id' => 'Ратинг',
            'like' => 'Симпантия',
            'label' => 'Метка',
            'place_id' => 'Место проведения',
            'uploadImg' => 'Загрузка логотипа',
            'deleteImg' => 'Удалить логотип',
            'uploadPre' => 'Загрузка превью',
            'deletePre' => 'Удалить превью',
        );
    }

    /**
     * Retrieves a list of models based on the current search/filter conditions.
     *
     * Typical usecase:
     * - Initialize the model fields with values from filter form.
     * - Execute this method to get CActiveDataProvider instance which will filter
     * models according to data in model fields.
     * - Pass data provider to CGridView, CListView or any similar widget.
     *
     * @return CActiveDataProvider the data provider that can return the models
     * based on the search/filter conditions.
     */
    public function search()
    {
        // @todo Please modify the following code to remove attributes that should not be searched.
        $criteria=new CDbCriteria;
        $criteria->compare('id',$this->id);
        $criteria->compare('title',$this->title,true);
        $criteria->compare('content',$this->content,true);
        $criteria->compare('alias',$this->alias,true);
        $criteria->compare('metakey',$this->metakey,true);
        $criteria->compare('metadesc',$this->metadesc,true);
        $criteria->compare('logo',$this->logo,true);
        $criteria->compare('views',$this->views);
        $criteria->compare('category',$this->category,true);
        $criteria->compare('tags',$this->tags,true);
        $criteria->compare('featured',$this->featured);
        $criteria->compare('claim',$this->claim);
        $criteria->compare('lastupdate',$this->lastupdate,true);
        $criteria->compare('pubdate',$this->pubdate,true);
        $criteria->compare('oddate',$this->moddate,true);
        $criteria->compare('expdate',$this->expdate,true);
        $criteria->compare('status',$this->status,true);
        $criteria->compare('author_id',$this->author_id,true);
        $criteria->compare('gallery_id',$this->gallery_id,true);
        $criteria->compare('comment_id',$this->comment_id,true);
        $criteria->compare('rating_id',$this->rating_id,true);
        $criteria->compare('like',$this->like,true);
        $criteria->compare('label',$this->label,true);
        $criteria->compare('place_id',$this->place_id,true);

        $criteria->compare('news_categories.category_id',$this->search_category);
        $criteria->with = array('news_categories'); 
        $criteria->together = true;

        $criteria->order = 'if(featured=1,0,1)'; // 'if(featured=1,0,1), if(featured=0,RAND(),title)'; //

        return new CActiveDataProvider($this, array(
            'criteria'=>$criteria,
            'pagination' => array('pageSize' => 20),
        ));
    }

    /**
     * Returns the static model of the specified AR class.
     * Please note that you should have this exact method in all your CActiveRecord descendants!
     * @param string $className active record class name.
     * @return News the static model class
     */
    public static function model($className=__CLASS__)
    {
        return parent::model($className);
    }
    
    public function beforeSave()
    {
        //$this->lastupdate = time();
       
        if ($this->isNewRecord) { 
            $this->pubdate = time();
            $this->views = 0;
            $this->featured = 0;
            $this->claim = 0;
            $this->status = 0;
            $this->author_id = Yii::app()->user->id;
        }
        return parent::beforeSave();
    }
    

    protected function afterFind() {

       parent::afterFind();
    }

    public static function All($place_id)
    {
       
           $criteria=new CDbCriteria;
        
        $criteria->compare('place_id', $place_id);
        $criteria->compare('status', 0);
        /*
        $criteria->compare('id',$this->id);

        $criteria->compare('name',$this->name,true);
        $criteria->compare('user_id',$this->user_id);
        $criteria->compare('email',$this->email,true);
        $criteria->compare('created',$this->created,true);

        $criteria->compare('text',$this->text,true);
        $criteria->compare('hash',$this->hash,true);
        $criteria->compare('staff',$this->staff);
        $criteria->compare('interior',$this->interior);
        $criteria->compare('kitchen',$this->kitchen);
        $criteria->compare('totalrating',$this->totalrating);
        $criteria->compare('claim',$this->claim);
        */
        
        $criteria->order = 'pubdate ASC';
        $criteria->limit = '36';
        
        return new CActiveDataProvider('News', array(
                'criteria'=>$criteria,
                'pagination' => array('pageSize' => 6),
            ));    
    }
    /*
findByAttributes(array('place_id'=>$model->id),
                                                    array(
                                                        'condition'=>'status=:status', 
                                                        'params'=>array(':status'=>0)
                                                    )
                                                ), */
                                                        
}

 
Изображение
asisdes
Сообщения: 202
Зарегистрирован: 2013.10.03, 15:54

Re: Запись в БД не идет, ошибка редактора

Сообщение asisdes »

Тему удалите пожайлуста. чтоб не засорять форум.
я сам тупиканул!
В модели неправильно указал правила.
Изображение
Ответить