【问题标题】:Adding Attribute Labels to DynamicModel Yii为 DynamicModel Yii 添加属性标签
【发布时间】:2016-07-31 11:20:16
【问题描述】:

我有动态数量的问题和答案。我使用 DynamicModel() 来收集这些数据。

$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",
      .....         
]

我只是无法将 $label 数组设置为我的动态模型的标签属性。 我的 $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

【问题讨论】:

    标签: yii2 yii-extensions yii2-advanced-app yii-components


    【解决方案1】:

    试试这个

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

    【讨论】:

      【解决方案2】:

      您似乎在这里误用了DynamicModel 概念。这应该用于 ad hoc validationnot 来处理表单演示。如果您需要添加标签,请改用常规的Model

      您可以扩展 DynamicModel 并在那里添加 attributeLabels() 并使用您的新方法。但是当您可以创建常规模型并准备好使用时,使用 DynamicModel 有什么意义呢?

      对于自定义属性标签,您可以添加ActiveField 小部件方法label()

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

      或来自HtmlHtml::label()Html::activeLabel() 的静态等效项。

      【讨论】:

        【解决方案3】:

        您可以像这样简单地扩展 DynamicModel :

        class MyDynamicModel extends DynamicModel
        {
            public $attributeLabels = [];
        
            public function attributeLabels(){   
                return $this->attributeLabels;
            }
        }
        

        现在您可以将 $attributeLabels 设置为数组

        【讨论】:

          猜你喜欢
          • 2013-07-04
          • 1970-01-01
          • 2019-12-23
          • 2017-09-17
          • 2014-08-17
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-09-19
          相关资源
          最近更新 更多