2015-01-28 2 views
1

У меня есть проект в Yii. Сначала это была форма с двумя текстовыми полями: Имя и Тема (тема - список предметов, разделенных запятой). Теперь мне нужно заменить текстовое поле темы списком флажков, которые будут добавлять ту же строку, разделяемую запятой.Yii получение данных из checkboxlist

<!--<?php echo $form->labelEx($model,'Subjects'); ?> 
<?php echo $form->textField($model,'Subjects',array('size'=>60,'maxlength'=>255)); ?> 
<?php echo $form->error($model,'Subjects'); ?>--> 
<?php echo $form->labelEx($model,'Subjects'); ?> 
<?php echo $form->checkBoxList($model,'Subjects',$this->listOfSubjects()); ?> 
<?php echo $form->error($model,'Subjects'); ?> 

Список предметов является метод контроллера, который возвращает массив, необходимый для CheckBoxList в Yii, что-то вроде:

array(
'1'=>'Something', 
'2'=>'Anotherthing' 
); 

Также здесь есть код мои действия создают. Это довольно стандартно:

public function actionCreate() 
{ 
    $model=new CrdTeachers; 
    if(isset($_POST['CrdTeachers'])) 
    { 
     $model->attributes=$_POST['CrdTeachers']; 
     if($model->save()) 
      $this->redirect(array('view','id'=>$model->Teacher_ID));   
    } 
    $this->render('create',array(
     'model'=>$model, 
    )); 
} 

Этот код работал нормально, когда было всего два текстовых поля. Теперь, когда я использую создать действие он говорит, что ошибка:

mb_strlen() expects parameter 1 to be string, array given 

Я не могу найти, где я могу обрабатывать свои данные, чтобы сделать его строку. Любые эксперты Yii здесь? Что я должен искать?
UPDATE: Вот CRDTeachers модель класса

class CrdTeachers extends CActiveRecord 
{ 
    /** 
    * Returns the static model of the specified AR class. 
    * @param string $className active record class name. 
    * @return CrdTeachers the static model class 
    */ 
    public static function model($className=__CLASS__) 
    { 
     return parent::model($className); 
    } 

    /** 
    * @return string the associated database table name 
    */ 
    public function tableName() 
    { 
     return 'crd_teachers'; 
    } 

    /** 
    * @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('Name, Subjects', 'required'), 
      array('Name, Subjects', 'length', 'max'=>255), 
      // The following rule is used by search(). 
      // Please remove those attributes that should not be searched. 
      array('Teacher_ID, Name, Subjects', '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(
      //'rSubjects'=>array(self::HAS_MANY, 'CrdSubjects', 'Subject_ID'), 
      //'categories'=>array(self::MANY_MANY, 'CrdTeachers', '{{CrdSubjects}}(Subject_ID, Subject_Name)'), 
     ); 
    } 

    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; 

     CrdTeachers::model()->deleteAllByAttributes(array('Subject_ID'=>$this->id)); 

     if (is_array($categories)) 
     { 
      foreach ($categories as $id) 
      { 
       if (Category::model()->exists('id=:id', array(':id'=>$id))) 
       { 
        $postCat = new CrdTeachers(); 
        $postCat->post_id = $this->id; 
        $postCat->category_id = $id; 
        $postCat->save(); 
       } 
      } 
     } 
    } 

    /** 
    * @return array customized attribute labels (name=>label) 
    */ 
    public function attributeLabels() 
    { 
     return array(
      'Teacher_ID' => 'Teacher', 
      'Name' => 'Name', 
      'Subjects' => 'Subjects', 
     ); 
    } 

    /** 
    * Retrieves a list of models based on the current search/filter conditions. 
    * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions. 
    */ 
    public function search() 
    { 
     // Warning: Please modify the following code to remove attributes that 
     // should not be searched. 

     $criteria=new CDbCriteria; 

     $criteria->compare('Teacher_ID',$this->Teacher_ID); 
     $criteria->compare('Name',$this->Name,true); 
     $criteria->compare('Subjects',$this->Subjects,true); 

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

    /* 
    * Возвращает список по ID 
    */ 
    public function getParentTypeById($id) { 
     $title = $this->model()->findByPk($id)->Name; 
     return $title; 
    } 
} 
+0

Позвольте мне взглянуть на вашу модель «CrdTeachers». – Roman

+1

Вот моя модель. –

ответ

1

Вы можете использовать этот метод в своей модели.

public function beforeValidate() 
{ 
    if (is_array($this->Subjects)) { 
     $this->Subjects = implode(', ', $this->Subjects); 
    } 

    return parent::beforeValidate(); 
} 
+0

Я отвечу позже. Слишком много другой работы. –

+1

Великий чувак. Это сработало. пользователь3535256 был первый. Но сначала вы написали свой комментарий, и ваш ответ более полный, поэтому я принял ваш. –

1

Вы можете обрабатывать ввод для проверки с помощью функции beforeValidate в модели. Убедитесь, что вы запускаете родительский метод и возвращаете true, если хотите продолжить проверку. Обычно это делается следующим образом:

public function beforeValidate() 
{ 
    // do stuff to transform the array into the string 
    return parent::beforeValidate(); 
} 
Смежные вопросы