Validating multiple fields with the same name

ぃ、小莉子 提交于 2019-12-03 23:07:14

问题


I have a view file that looks like this:

<?php
    echo $this->Form->create('ModelName');
        echo $this->Form->input('ModelName.0.firstField');
        echo $this->Form->input('ModelName.0.secondField');
        echo $this->Form->input('ModelName.1.firstField');
        echo $this->Form->input('ModelName.1.secondField');
    echo $this->Form->end();
?>

My question is, how do I validate this data? I'm not saving, so it seems pointless to me to call the save or saveAll methods. I just want to validate the data before I process it and display the results to the user.

What happens currently using:

<?php
    if ($this->request->is('post')) {
        $this->ModelName->set($this->request->data);
        if ($this->ModelName->validates()) {
            echo $this->Session->setFlash('Success');
        } else {
            echo $this->Session->setFlash('Failure');
        }
    }
?>

Is it succeeds all the time even when I'm putting in data that should definitely fail. I have also tried:

<?php
    if ($this->request->is('post')) {
        if ($this->ModelName->validateMany($this->request->data)) {
            echo $this->Session->setFlash('Success');
        } else {
            echo $this->Session->setFlash('Failure');
        }
    }
?>

And that return success all the time as well, but that may be due to the fact that I don't know how to properly use validateMany.


回答1:


Model::set is used for assigning a single set/record of data to the current instance of the Model. So it may be possible that you are only validating the first set of data in your POST data. You would have to iterate through each record in the POST data, Model::set it to the Model data, and then call Model::validates.

Instead of the above method or Model::validateMany, try using Model::saveAll without actually saving.

http://api20.cakephp.org/class/model#method-ModelsaveAll

validate: Set to false to disable validation, true to validate each record before saving, 'first' to validate all records before any are saved (default), or 'only' to only validate the records, but not save them.

<?php
    if ($this->request->is('post')) {
        if ($this->ModelName->saveAll($this->request->data, array('validate' => 'only'))) {
            echo $this->Session->setFlash('Success');
        } else {
            echo $this->Session->setFlash('Failure');
        }
    }
?>


来源:https://stackoverflow.com/questions/12525645/validating-multiple-fields-with-the-same-name

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!