如何处理模型中类行为公共属性中的数据? (Yii2)

时间:2014-07-16 07:28:11

标签: php yii yii2

型号代码:

<?php
namespace common\models;

use Yii;
use yii\db\ActiveRecord;
use common\components\behaviors\PageAncestorBehavior;

/**
 * This is the model class for table "page".
 *
 * @property integer $id
 * @property string $title
 * @property string $title_eng
 * @property string $text
 * @property integer $update_ts
 *
 * @property PageTreepath[] $pageTreepaths
 */
class Page extends \yii\db\ActiveRecord
{
    public $ancestor;
    public $descendant;

    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return '{{%page}}';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['title', 'text'], 'required'],
            [['text'], 'string'],
            [['update_ts'], 'integer'],
            [['title', 'title_eng'], 'string', 'max' => 255]
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'title' => Yii::t('app', 'Заголовок'),
            'title_eng' => Yii::t('app', 'Транcлитерация заголовка'),
            'text' => Yii::t('app', 'Текст страницы'),
            'update_ts' => Yii::t('app', 'Дата и время последнего обновления'),
            'ancestor' => Yii::t('app', 'Категория'),
        ];
    }

    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'timestamp' => [
                'class' => 'yii\behaviors\TimestampBehavior',
                'attributes' => [
                    ActiveRecord::EVENT_BEFORE_INSERT => ['update_ts'],
                    ActiveRecord::EVENT_BEFORE_UPDATE => ['update_ts'],
                ],
            ],
            'pageAncestor' => [
                'class' => PageAncestorBehavior::className(),
                'ancestor' => $this->ancestor
            ]
        ];
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getPageTreepaths()
    {
        return $this->hasMany(PageTreepath::className(), ['ancestor' => 'id']);
    }

    /**
     * Get all pages
     * @return array
     */
    public static function getAllPages() {
        $query = new \yii\db\Query;
        $query->select('id, title')
          ->from('{{%page}}')
          ->orderBy('title');

        $command = $query->createCommand();
        return $command->queryAll();
    }

    /**
     * Get list all pages for dropdown list
     * @return array
     */
    public static function getListAllPages() {
        $data = self::getAllPages();
        $result = array(0 => '-');

        if (!empty($data)) {
            foreach ($data as $d) {
                $result[$d['id']] = $d['title'];
            }
        }

        return $result;
    }
}

行为代码:

<?php

namespace common\components\behaviors;

use yii;
use yii\base\Behavior;
use yii\db\ActiveRecord;
use common\models\Page;

class PageAncestorBehavior extends Behavior
{
    public $ancestor;

    public function events()
    {
        return [
            ActiveRecord::EVENT_BEFORE_INSERT => 'beforeInsert',
        ];
    }

    /**
     * @param $event
     */
    public function beforeInsert($event)
    {

        // --- How to get ancestor value?

        //error_log("Ancestor:".$this->ancestor);
    }

    /**
     * @return Page
     */
    private function getOwner() {
        return $this->owner;
    }
}

查看:

<?php $form = ActiveForm::begin([
            'enableClientValidation'=> true,
            'enableAjaxValidation'=> false,
            'validateOnSubmit' => true,
            'validateOnChange' => true,
            'validateOnType' => true,

        ]); ?>

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

    <?= $form->field($model, 'title')->textInput(['maxlength' => 255]) ?>

    <?php
         $redactor = yii\imperavi\Widget::widget(
            [
                'model' => $model,
                'attribute' => 'text',
                'options' => [
                    'minHeight' => 400,
                ],
            ]
        );
        $error = Html::error($model,'text', ['class' => 'help-block']); //error
    ?>

    <?= $form->field($model, 'text', ['template' => "{$error}\n{label}\n{hint}\n{$redactor}"])->textarea();?>
    <br />

    <?php
        // There is select for Page[ancestor]. Inf Behavior i don't recieved this.
       echo $form->field($model, 'ancestor')->dropDownList($allPages);
    ?>

    <div class="form-group">
        <?= Html::submitButton(
            $model->isNewRecord ? Yii::t('app', 'Create') : Yii::t('app', 'Update'),
            ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']
        ) ?>
    </div>

    <?php ActiveForm::end(); ?>

控制器:

public function actionCreate()
    {
        $model = new Page;
        $allPages = Page::getListAllPages();

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('create', [
                'model' => $model,
                'allPages' => $allPages
            ]);
        }
    }

我从表单中获取所有数据,但是我没有收到$ ancestor的值。

我希望从行为中使用它们的形式接收这些祖先。 抱歉我的英文。

2 个答案:

答案 0 :(得分:2)

只需在您的规则中添加ancestor即可!

 [['title','ancestor', 'text'], 'required'],

答案 1 :(得分:1)

变量必须在行为中公开。在您使用此方式访问它的行为$this->ancestor 在您的模型中设置pageAncestor,但行为的名称是PageAncestorBehavior ....为什么?