2016-07-31 80 views
0

我有動態數量的問題和答案。我使用DynamicModel()來收集這些數據。將屬性標籤添加到DynamicModel Yii

$attributes = [ 
     "answer_1" => "Some Value 1", 
     "answer_2" => "Some Value 2", 
     "answer_3" => "Some Value 3", 
     ..... 
] 

$customFormModel = new DynamicModel($attributes); 

我也有

$labels = [ 
     "answer_1" => "Label 1", 
     "answer_2" => "Label 2", 
     "answer_3" => "Label 3", 
     .....   
] 

我只是不能得到$標籤陣列被設置爲標籤屬性爲我的動態模型。 我的$ customFormModel-> attributeLabels()總是空的。

這些結果包含以下問題。 我得到這樣的

Answer 1 can not be blank 
Answer 2 can not be blank 
Answer 3 can not be blank 

錯誤消息我想,而不是

Label 1 can not be blank 
Label 2 can not be blank 
Label 3 can not be blank 

回答

0

像你在這裏妄稱DynamicModel概念試試這個

$customFormAttributes = array_map(function ($key) use ($attributes) { 
    return $attributes[$key]; 
}, array_flip($labels)); 

$customFormModel = new DynamicModel($customFormAttributes); 
0

它看起來什麼。這應該用於ad hoc validation而不是以處理表單顯示。如果您需要添加標籤,請改用常規Model

您可以擴展DynamicModel並在其中添加attributeLabels(),然後使用您的新方法。但是,當您可以創建一切準備好使用的常規模型時,使用DynamicModel有什麼意義?

對於自定義屬性標籤,你可以從Html::label()Html類,Html::activeLabel()添加ActiveField部件方法label()

<?= $form->field($customFormModel, 'attribute')->label('...') ?> 

或靜態等效。

0

,你可以簡單地擴展DynamicModel這樣的:

class MyDynamicModel extends DynamicModel 
{ 
    public $attributeLabels = []; 

    public function attributeLabels(){ 
     return $this->attributeLabels; 
    } 
} 

現在你可以設置$ attributeLabels爲陣列