zend framework validate data in model instead in the form

試著忘記壹切 提交于 2019-12-13 17:07:32

问题


Using Zend Framework 2. In my application, to edit the data in the database is possible compile an html form or send an http post request(my server is implemented as a web service). In this second case the form is not rendered. Problem: If I put the validations rules in the form when the server recive a post request sent not from the form but from a generic http post request (like an mobile app) the data is not validated/filtered becouse the validations are bind in the form.

Is possible to have an unique centralized validator system ? In my opinion the data must be validate before saving in the db, not in the form!

Ideas?


回答1:


You can find a similar example in the documentation Forms and Actions

In Zend Framework 2 this is done using an input filter, which can either be standalone or defined within any class that implements the InputFilterAwareInterface interface.

So, in this example model entity implements the InputFilterAwareInterface and there are methods setInputFilter and getInputFilter. So later you can call isValid().


I personally put all my filters into src/ModuleName/Filter/ (UserFilter.php). Where implements InputFilterAwareInterface and define getInputFilter() method with all dirty things.

Than in controller, or any other class, just call:

use ModuleName\Filter\UserFilter;

...

$filter = new UserFilter();
$data   = $this->params()->fromPost();

if(!$filter->getInputFilter()->setData($data)->isValid()){
    $data   = $filter->getInputFilter()->getValues();
    $errors = $filter->getInputFilter()->getMessages();
    // Throw an exception
}


来源:https://stackoverflow.com/questions/24570170/zend-framework-validate-data-in-model-instead-in-the-form

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