Yii2:动态模型属性

问题描述 投票:0回答:2

我有桌郎:

  id | lang_name

表2:消息:

  id | message_code

表3:字典

  id | message_id | lang_id | translation

我想将语言引入网格视图。格式:

消息代码 | zh_翻译 | ..._翻译 |..._翻译

由于语言的数量未知,我将数组中的列值传递给gridview。

有一个问题:我需要将语言 id 的值传递给关系模型。我不知道怎么办。

    $searchModel = new langmessages_search();
    $dataProvider = $searchModel->search(Yii::$app->request->queryParams);



    $columns=array();       
    $columns[]=array('label'=>'message_code','attribute'=>'message_code');      
    $languages=Lang::find()->all();
    foreach($languages as $language){       
        $columns[]=array('label'=>$language->name,'attribute'=>'text');
        //'attribute'=>'text' ---> need to dynamically create the attribute or pass lang_id
    }

希望能帮到你。

php gridview model yii2 relation
2个回答
3
投票
public function actionSearch($name, $email)
{
    $model = DynamicModel::validateData(compact('name', 'email'), [
        [['name', 'email'], 'string', 'max' => 128],
        ['email', 'email'],
    ]);
    if ($model->hasErrors()) {
        // validation fails
    } else {
        // validation succeeds
    }
}

上面的例子展示了如何在DynamicModel的帮助下验证$name和$email。 validateData() 方法创建 DynamicModel 的实例,使用给定数据(本例中为姓名和电子邮件)定义属性,然后调用 yii ase\Model::validate()。

您可以通过 hasErrors() 检查验证结果,就像处理普通模型一样。您还可以访问通过模型实例定义的动态属性,例如 $model->name 和 $model->email。

或者,您可以使用以下更“经典”的语法来执行临时数据验证:

$model = new DynamicModel(compact('name', 'email'));
$model->addRule(['name', 'email'], 'string', ['max' => 128])
    ->addRule('email', 'email')
    ->validate();

http://www.yiiframework.com/doc-2.0/yii-base-dynamicmodel.html


0
投票

您的搜索模型可能如下所示:

class LangMessagesSearch extends Model
{

    public $id;
    public $messageCode;

    private $languages = [];


    public function __get($name)
    {
        if (isset($this->languages[$name])) {
            return $this->languages[$name];
        }

        return null;
    }

    public function __set($name, $value)
    {
        return $this->languages[$name] = $value;
    }

    public function getLanguageAttributes()
    {
        $languagesList = Lang::find()->all();

        $attributes = [];
        foreach ($languagesList as $lang) {
            $attributes[] = [
                'attribute' => $lang,
                'format' => 'raw',
                'headerOptions' => [
                    'title' => $lang,
                ],
                'content' => function($model, $key, $index) use ($lang) {
                    // you can do here something with $lang if you need so
                    $content = $model->{$lang};
                    return $content;
                }
            ];
        }

        return $attributes;
    }

    public function search($params)
    {
        // assume that getRecords() implemented here
        $records = $this->getRecords($params);


        $allModels = [];
        foreach ($records as $k => $v) {
            $model = new self;
            $model->id  = $records->id;
            $model->messageCode = $records->messageCode;

            $allModels[] = $model;
        }

        return $this->wrapIntoDataProvider($allModels);
    }

    private function wrapIntoDataProvider($data)
    {
        $provider = new \app\components\ArrayDataProvider(
            [
                'allModels' => $data,
                'pagination' => [
                    'pageSize' => 30,
                ],
            ]
        );

        return $provider;
    }
}

最终在视图中显示网格:

// take just first model in the list
$_model = $dataProvider->allModels[0];

$attributes = array_merge(
    [['class' => 'yii\grid\SerialColumn']],
    [
        'id',
        'messageCode'
    ],
    $_model->getLanguageAttributes()
);

echo \yii\grid\GridView::widget([
    'dataProvider' => $dataProvider,
    'columns' => $attributes
]);
© www.soinside.com 2019 - 2024. All rights reserved.