Yii, создайте список флажков, и каждый флажок будет изменять данные столбца

я должен сделать список флажков, который будет печатать все столбцы, кроме идентификаторов, таблица в базе данных называется parametros, у которой есть идентификатор и parametro_id, которые не нужно печатать, но будет больше столбцов, которые будут созданы приложение, которое будет иметь данные типа 1-0 или true-false.

я не знаю, как работает список флажков, и я пытался найти какое-то место, которое могло бы объяснить все способы, которые могут быть сгенерированы, я собираюсь показать форму, сгенерированную gii, моделью и контроллером действий.

_form.php

<?php
/* @var $this ParametroController */
/* @var $model Parametro */
/* @var $form CActiveForm */
?>

<div class="form">

<?php $form=$this->beginWidget('CActiveForm', array(
        'id'=>'parametro-form',
        // 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,
)); ?>

        <p class="note">Fields with <span class="required">*</span> are required.</p>

        <?php echo $form->errorSummary($model); ?>

        <div class="row">
                <?php echo $form->labelEx($model,'nombre'); ?>
                <?php echo $form->textField($model,'nombre',array('size'=>60,'maxlength'=>256)); ?>
                <?php echo $form->error($model,'nombre'); ?>
        </div>

        <div class="row buttons">
                <?php echo CHtml::submitButton($model->isNewRecord ? 'Create' : 'Save'); ?>
        </div>

<?php $this->endWidget(); ?>

</div><!-- form -->

Параметро.php (Модель)

<?php

/**
 * This is the model class for table "parametro".
 *
 * The followings are the available columns in table 'parametro':
 * @property integer $id
 * @property string $nombre
 */
class Parametro extends CActiveRecord
{
        /**
         * @return string the associated database table name
         */
        public function tableName()
        {
                return 'parametro';
        }

        /**
         * @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('nombre', 'required'),
//                      array('nombre', 'length', 'max'=>256),
                        // The following rule is used by search().
                        // @todo Please remove those attributes that should not be searched.
                        array('id', 'safe', 'on'=>'search'),
                        array('hplocal', 'safe', 'on'=>'search'),
//                      array('id, nombre', '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(
                'peticion'=>array(self::BELONGS_TO,'Peticion','peticion_id'),
                );
        }

        /**
         * @return array customized attribute labels (name=>label)
         */
        public function attributeLabels()
        {
                return array(
                        'id' => 'ID',
//                      'nombre' => 'Nombre',
                );
        }

        /**
         * 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('nombre',$this->nombre,true);

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

        /**
         * 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 Parametro the static model class
         */
        public static function model($className=__CLASS__)
        {
                return parent::model($className);
        }
}

ParametroController.php (Действие)

public function actionCreate()
{
        $model=new Parametro;

        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);

        if(isset($_POST['Parametro']))
        {
                $model->attributes=$_POST['Parametro'];
                if($model->save())
                        $this->redirect(array('view','id'=>$model->id));
        }

        $this->render('create',array(
                'model'=>$model,
        ));
}

вы можете видеть, что почти ничего не изменилось, но я просто пытаюсь понять, как начать, столбцы, которые будут созданы приложением, будут называться как «ph, h1, ho3 и т. д.». Итак, я хочу сделать список флажков, который будет печатать все эти столбцы, созданные приложением, и когда вы выберете некоторые из них и нажмете «Отправить», отмеченные флажки будут сохранены в определенном столбце как 1 или true.

пожалуйста помоги.


person Oscar Reyes    schedule 20.12.2013    source источник


Ответы (2)


Таким образом, вы можете просто создать список флажков в yii.

<?php echo CHtml::activecheckBoxList($model, 'yourAttribute', array("1" => "Arts", "2" => "Science", "3" => "Culture"), array('separator' => '', 'id' => 'chk_lst_id')); ?>

Это создаст 3 флажка в списке, например:

<input type="checkbox" name="Arts" value="1">Arts<br>
<input type="checkbox" name="Science" value="2">Science<br>
<input type="checkbox" name="Culture" value="3">Culture

Проверьте здесь некоторые другие примеры: http://www.yiiframework.com/wiki/48/by-example-chtml/#hh4

person dev1234    schedule 20.12.2013

Я написал эту вики, может быть, поможет вам

http://www.yiiframework.com/wiki/681/update-related-models-of-a-model-using-listbox-and-checkboxlist-in-the-form/

person kon apaz    schedule 13.05.2014
comment
Простая ссылка на что-то мало помогает, по крайней мере, дает краткое изложение того, что мы там найдем. - person Andrew; 13.05.2014