Yii模型的问题

时间:2013-12-17 03:43:46

标签: php yii

unit_post表。

id : int(11)
name : varchar(50)
description : text
unit_id : int(11)
langitude: float
longitude : float
created : datetime
updated : datetime

UnitPost模型。

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

/**
 * @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('unit_id', 'numerical', 'integerOnly' => true),
        array('name', 'length', 'max' => 255),
        array('description, langitude,longitude, created, updated', 'safe'),
        // The following rule is used by search().
        // @todo Please remove those attributes that should not be searched.
        array('id, name, description, latitude, longitude, unit_id, created, updated', '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(
        'unit' => array(self::BELONGS_TO, 'Unit', 'unit_id'),
    );
}

/**
 * @return array customized attribute labels (name=>label)
 */
public function attributeLabels() {
    return array(
        'id' => 'ID',
        'name' => 'Nama',
        'description' => 'Deskripsi',
        'langitude' => 'Latitude',
        'longitude' => 'Longitude',
        'unit_id' => 'Unit',
        'created' => 'Created',
        'updated' => 'Updated',
    );
}

/**
 * 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('name', $this->name, true);
    $criteria->compare('description', $this->description, true);
    $criteria->compare('langitude', $this->langitude);
    $criteria->compare('longitude', $this->longitude);
    $criteria->compare('unit_id', $this->unit_id);
    $criteria->compare('created', $this->created, true);
    $criteria->compare('updated', $this->updated, 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 UnitPost the static model class
 */
public static function model($className=__CLASS__) {
    return parent::model($className);
}

actionCreate()

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

    $modelDropdown = new UnitDropdownForm('nonPip');

    $upt = Unit::model()->getUptAll();

    $satker = array('' => '');

    if (isset($_POST['UnitPost']) && isset($_POST['UnitDropdownForm'])) {
        $model->attributes = $_POST['UnitPost'];
        if(array_key_exists('satker', $_POST['UnitDropdownForm'])) {
            $model->unit_id = $_POST['UnitDropdownForm']['satker'];
        }else{
            $model->unit_id = $_POST['UnitDropdownForm']['upt'];
        }
        $model->created = date('Y-m-d H:i:s');

        if ($model->save())
            $this->redirect('admin');
    }

    $this->render('create', array(
        'model' => $model,
        'modelDropdown' => $modelDropdown,
        'id' => '',
        'upt' => $upt,
        'satker' => $satker
    ));
}

_form View

<?php $form=$this->beginWidget('bootstrap.widgets.TbActiveForm',array(
'id'=>'user-form',
'enableAjaxValidation'=>false,
'htmlOptions' => array('role'=>'form', 'class'=>'form-horizontal'), )); 
 ?>
<div class="header">
</div>
<?php if($form->errorSummary($model)):?>
    <div class="alert alert-danger">
        <?php echo $form->errorSummary($model); ?>
    </div>
<?php endif; ?>

   <div class="form-group">
        <?php echo $form->label($modelDropdown,'upt',
        array('class'=>'col-lg-2 control-label')); ?>
    <div class="col-lg-5">
            <?php
                $this->widget('bootstrap.widgets.TbSelect2', array(
                    'asDropDownList' => true,
                    'model' => $modelDropdown,
                    'attribute' => 'upt',
                    'options' => array(
                        'width' => '100%',
                    ),
                    'data' => (!empty($upt)) ? $upt : array(''=>''),
                ));
            ?>
    </div>
</div>

<div class="form-group">
    <?php echo $form->label($modelDropdown,'satker',
         array('class'=>'col-lg-2 control-label')); ?>
    <div class="col-lg-5">
            <?php
                $this->widget('bootstrap.widgets.TbSelect2', array(
                    'asDropDownList' => true,
                    'model' => $modelDropdown,
                    'attribute' => 'satker',
                    'options' => array(
                        'width' => '100%',
                    ),
                    'data' => (isset($satker)) ? $satker : array(''=>''),
                ));
            ?>
    </div>
</div>

<div class="form-group">        
    <?php echo $form->label($model, 'name', 
                    array('class'=>'col-lg-2 control-label')); ?>
    <div class="col-lg-5">
        <?php echo $form->textField($model,'name',
                          array('class'=>'form-control','maxlength'=>100)); ?>
    </div>
</div>  

<div class="form-group">
    <?php echo $form->label($model, 'description', 
                  array('class' => 'col-lg-2 control-label')); ?>
    <div class="col-lg-5">
        <?php echo $form->textField($model,'description',
                      array('class'=>'form-control','maxlength'=>100)); ?>
    </div>
</div>

    <div class="form-group">
    <?php echo $form->label($model, 'map', 
                         array('class' => 'col-lg-2 control-label')); ?>
    <div class="col-lg-5">
        <div id="gmap" class="gmap3 top" 
                          style="width:600px; height:350px"></div>
        zoom level: <span id="zoom_level"></span><br>
                    <?php echo $form->label($model, 'langitude', 
                           array('class' => 'control-label')); ?>
                    <input type="text" id="lang" 
                     class="form-control" maxlength="100" name="UnitPost[langitude]" />
                    <?php echo $form->label($model, 'longitude', 
                                  array('class' => 'control-label')); ?>
                    <input type="text"  id="long" class="form-control"
                                       maxlength="100" name="UnitPost[longitude]" />
        <a href="#" id="coordinate" class="btn btn-primary">set map</a>
    </div>
</div>

<div class="form-actions">
    <?php $this->widget('bootstrap.widgets.TbButton', array(
        'buttonType'=>'submit',
        'type'=>'primary',
        'label'=>$model->isNewRecord ? 'Create' : 'Save',
    )); ?>
    <?php $this->widget('bootstrap.widgets.TbButton', array(
        'type'=>'link',
        'label'=>'Cancel',
        'url'=>'#cancel'
    )); ?>

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

我的Yii模型有些问题。

1。我的模型属性有“未定义”错误。

在表格中插入新字段,我在规则,attributesLabel和搜索功能中对其进行了详细说明。但它仍然没有“定义”。当我在另一个模型中插入新字段时,我使用此方法,但它工作,但不在此模型中。

实际上,此错误已得到修复。但问题是,是正确的解决方案吗?。因为我不必在另一个模型中这样做。

我在定义模型类之后定义了属性..

class UnitPost extends CActiveRecord {

public $langitude;
public $longitude;

...

2。我无法将数据插入这些新字段。

我无法将数据插入字段'纬度'和'经度'。为什么?我定义了我的规则中提到的那些。

public function rules() {
    // NOTE: you should only define rules for those attributes that
    // will receive user inputs.
    return array(
        array('unit_id', 'numerical', 'integerOnly' => true),
        array('name', 'length', 'max' => 255),
        array('description, langitude,longitude, created, updated', 'safe'),
        // The following rule is used by search().
        // @todo Please remove those attributes that should not be searched.
        array('id, name, description, langitude, longitude, unit_id, created, updated', 'safe', 'on' => 'search'),
    );
}

但是当我在Insert动作中print_r($ model-&gt;属性)时,纬度和经度不存在。

Array ( [name] => Name [description] => Description [id] => [unit_id] => [created] => [updated] => )

很抱歉,如果我的帖子太长而且看起来很复杂。如果你帮助我,我将非常感激。

感谢的。

3 个答案:

答案 0 :(得分:1)

我认为问题在于你的规则,即

 array('description, langitude,longitude created, updated', 'safe'),

正如您所看到的,经度已创建之间没有逗号 ,,这是两个不同的属性。插入一个逗号然后再试一次。我希望它能奏效 第二件事你不需要声明任何像这样的变量

public $latitude;
    public $longitude;

如果它们已存在于您的表格中。If your table has these fields then there is no need of defining them.The data will be inserted to these fields like the other fields.

答案 1 :(得分:0)

在您的模型规则中,

     array('description, langitude,longitude created, updated', 'safe'),

这里你错过了经度和创造之间的逗号。它应该是。

     array('description, langitude,longitude,created, updated', 'safe'),

答案 2 :(得分:0)

你应该在

之后使用$ model-&gt; validate()函数
if(isset($_POST['UnitPost']) && isset($_POST['UnitDropdownForm'])) {
    $model->attributes = $_POST['UnitPost'];
if($model->validate())
{
   //save data
}
}