2016-04-25 118 views
0

在我的表單中,我一次更新來自同一模型的更多開始和結束日期。參見以簡化形式:Yii2:如何驗證具有同一模型的多個實例的表單

<?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,但我沒有成功。我想我需要從 '爲MyModel啓動' 改變 'compareAttribute' 在驗證JS 'mymodel- -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' 
    ] 
]) 

解決方案

該解決方案是基於盧卡斯答案。

在模型中我重寫表格名稱()方法,所以每次約會我有一個獨特的形式的域名(基於對現有的日期編號,並根據新的日期隨機數):

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(); ?> 

回答

1

重寫模型類中的formName()方法以使其唯一。如果您不想更改模型類,請創建它的子類以用於此控制器操作。完成此操作後,html ID和名稱字段將自動保持唯一。

相關問題