I have a form where an XML file is uploaded. After the form is submitted I have to check the content of a pair of tags in the XML file. If the content of the tags is different from some expected, an error should be shown next to the form.
I don't know exactly how to organize this code, any help?
tags: prevalidation, postvalidation
You have several places to perform this check:
I prefer the custom validator because if you have to re-use the form somewhere else you won't have to re-implement the logic of checking the xml.
So in your sfForm class, add a custom validator to your file widget:
class MyForm extends sfForm
{
public function configure()
{
// .. other widget / validator configuration
$this->validatorSchema['file'] = new customXmlFileValidator(array(
'required' => true,
));
And inside your new validator at /lib/validator/customXmlFileValidator.class.php
:
// you extend sfValidatorFile, so you keep the basic file validator
class customXmlFileValidator extends sfValidatorFile
{
protected function configure($options = array(), $messages = array())
{
parent::configure($options, $messages);
// define a custom message for the xml validation
$this->addMessage('xml_invalid', 'The XML is not valid');
}
protected function doClean($value)
{
// it returns a sfValidatedFile object
$value = parent::doClean($value);
// load xml file
$doc = new DOMDocument();
$doc->load($this->getTempName());
// do what ever you want with the dom to validate your xml
$xpath = new DOMXPath($doc);
$xpath->query('/my/xpath');
// if validation failed, throw an error
if (true !== $result)
{
throw new sfValidatorError($this, 'xml_invalid');
}
// otherwise return the sfValidatedFile object from the extended class
return $value;
}
}
Do not forget to clear your cache php symfony cc
and it should be ok.