Symfony Validator修改表单字段

时间:2017-09-13 20:28:05

标签: symfony validation symfony-forms

我有一个看起来像这样的验证器:

    class ValidUSPSAddressValidator extends ConstraintValidator
    {
        public function validate($protocol, Constraint $constraint)
        {
            $verify = new USPSAddressVerify('*******');
            $uspsAddress = new USPSAddress();
            $apartment = $protocol->getApartment();
            $address = $protocol->getAddress();
            $city = $protocol->getCity();
            $state = $protocol->getState();
            $zip = $protocol->getZip();


            $uspsAddress->setApt($apartment);
            $uspsAddress->setAddress($address);
            $uspsAddress->setCity($city);
            $uspsAddress->setState($state);
            $uspsAddress->setZip5($zip);
            $uspsAddress->setZip4('');
            $verify->addAddress($uspsAddress);

            $verify->verify();
            $response = $verify->getArrayResponse();
            $responseAddress = $response['AddressValidateResponse']['Address'];


            if ($verify->isError()) {
                $this->context->buildViolation($constraint->message)
                    ->addViolation();
            }else{
                $protocol->setAddress($responseAddress['Address2']);
                $protocol->setCity($responseAddress['City']);
                $protocol->setState($responseAddress['State']);
                $protocol->setZip($responseAddress['Zip5']);

                //****** THE BELOW IF ******************
                if($responseAddress['Address2'] != $address || $responseAddress['City'] != $city || $responseAddress['State'] != $state || $responseAddress['Zip5'] != $zip){
                    $this->context->buildViolation($constraint->verify)
                        ->addViolation();
                }

            }
        }
    }

查看最终的IF语句及其中的代码......我正在尝试将字段设置为USPS响应,并且验证器基本上为用户提供了最后一次机会来查看更新的数据修改字段,然后将再次重新验证,只要数据与USPS数据完全匹配,它就会持续存在。问题是protocol-> setXXXXX()设置要保留的对象上的数据,但只是在重新显示表单时不显示字段中的数据...

1 个答案:

答案 0 :(得分:0)

Validator的要点是验证Object,可能尝试使用data transformersform listeners甚至event listeners,并在验证器内跳过这种逻辑。