0

在我的表格中,我一次更新了同一模型的更多开始和结束日期。见简化形式:

<?php $form = ActiveForm::begin(); ?>
    <?php foreach($dates as $i=>$date): ?>
        <?= $form->field($date,"[$i]start"); ?>
        <?= $form->field($date,"[$i]end"); ?>
    <?php endforeach; ?>
</table>
<?= Html::submitButton('Save'); ?>
<?php ActiveForm::end(); ?>

在我需要控制的模型中,如果结束日期在开始日期之后:

public function rules() {
    return [
        [['end'], 'compare', 'compareAttribute' =>  'start', 'operator' => '>', 'message' => '{attribute} have to be after {compareValue}.‌'],
    ];
}

我尝试更改选择器,如:Yii2: Validation in form with two instances of same model中所述,但我没有成功。我想我需要在验证 JS 中将 'compareAttribute' 从 'mymodel-start' 更改为 'mymodel- 0 -start':

{yii.validation.compare(value, messages, {"operator":">","type":"string","compareAttribute":"mymodel-start","skipOnEmpty":1,"message":"End have to be after start.‌"});}

所以,我寻找类似的东西:

$form->field($date,"[$i]end", [
    'selectors' => [
        'compareAttribute' => 'mymodel-'.$i.'-start'
    ]
])

解决方案

该解决方案基于lucas的答案。

在模型中,我重写了 formName() 方法,因此对于每个日期,我都有一个唯一的表单名称(基于现有日期的 ID 和基于新日期的随机数):

use ReflectionClass;
...

public $randomNumber;

public function formName()
{
    $this->randomNumber = $this->randomNumber ? $this->randomNumber : rand();
    $number = $this->id ? $this->id : '0' . $this->randomNumber;
    $reflector = new ReflectionClass($this);
    return $reflector->getShortName() . '-' . $number;
}

然后表格如下所示:

<?php $form = ActiveForm::begin(); ?>
    <?php foreach($dates as $date): ?>
        <?= $form->field($date,"start"); ?>
        <?= $form->field($date,"end"); ?>
    <?php endforeach; ?>
</table>
<?= Html::submitButton('Save'); ?>
<?php ActiveForm::end(); ?>
4

1 回答 1

1

覆盖模型类中的 formName() 方法以使其唯一。如果您不想更改模型类,请创建它的子类以用于此控制器操作。完成此操作后,html ID 和名称字段将自动唯一。

于 2016-04-25T16:20:59.733 回答