Yii2:动态模型属性 [英] Yii2: dynamic model attributes

查看:901
本文介绍了Yii2:动态模型属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有表朗:

  id | lang_name

表2:消息:

  id | message_code

Table3:Dictionary

Table3: Dictionary

  id | message_id | lang_id | translation

我想用语言带到gridview。格式:

I want to bring to the gridview with languages. Format:

message_code | en_translation | ... _翻译| ... _翻译

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

As the number of languages is not known, i pass value of columns in array to gridview.

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

There is one problem: I need to pass the value of the language id to relation model. I do not know how.

    $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
    }

希望你能帮忙。 / p>

I hope you can help.

推荐答案

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\base\Model :: validate()。

The above example shows how to validate $name and $email with the help of DynamicModel. The validateData() method creates an instance of DynamicModel, defines the attributes using the given data (name and email in this example), and then calls yii\base\Model::validate().

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

You can check the validation result by hasErrors(), like you do with a normal model. You may also access the dynamic attributes defined through the model instance, e.g., $model->name and $model->email.

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

Alternatively, you may use the following more "classic" syntax to perform ad-hoc data validation:

$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

这篇关于Yii2:动态模型属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆