is there an easy way to allow choice fields in symfony to validate correctly with data that was added via js? So for example you load an empty field then populate it with js/ajax calls then select one of the options an press submit, but the validator always throws this option is not valid errors...
To give some background, Ive got a custom form type that uses the choice type as a parent, and also a custom data transformer that converts the options into entity's (which I can confirm works because if I change the form type to text and manually enter the id corresponding to the choice I would want to select, the form submits fine).
Any idea's? Im happy to provide any files you might want to have a look at?
Edit nullstateType.php
<?php
namespace ISFP\Index\IndexBundle\Form\Type;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use ISFP\Index\IndexBundle\Form\Transformer
ullstateTransformer;
use Doctrine\Common\Persistence\ObjectManager;
class nullstateType extends AbstractType
{
/**
* @var ObjectManager
*/
private $om;
/**
* @param ObjectManager $om
*/
public function __construct(ObjectManager $om)
{
$this->om = $om;
}
public function buildForm(FormBuilderInterface $builder, array $options)
{
$transformer = new nullstateTransformer($this->om);
$builder->prependNormTransformer($transformer);
}
public function setAllowedValues(OptionsResolverInterface $resolver)
{
return array( 'widget' => array('choice'));
}
public function getDefaultOptions(array $options)
{
return array(
'invalid_message' => 'The selected state does not exist',
'property_path' => false
);
}
public function getParent()
{
return 'choice';
}
public function getName()
{
return 'nullstate';
}
}
nullstateTransformer.php
<?php
namespace ISFP\Index\IndexBundle\Form\Transformer;
use Symfony\Component\Form\DataTransformerInterface;
use Symfony\Component\Form\Exception\TransformationFailedException;
use Doctrine\Common\Persistence\ObjectManager;
use ISFP\Index\IndexBundle\Entity\State;
class nullstateTransformer implements DataTransformerInterface
{
/**
* @var ObjectManager
*/
private $om;
/**
* @param ObjectManager $om
*/
public function __construct(ObjectManager $om)
{
$this->om = $om;
}
/**
* Transforms an object (state) to a string (id).
*
* @param Issue|null $state
* @return string
*/
public function transform($state)
{
if (null === $state) {
return "";
}
return $this->om->getRepository('ISFPIndexEntityBundle:State')->getId();
}
/**
* Transforms a string (id) to an object (state).
*
* @param string $id
* @return Issue|null
* @throws TransformationFailedException if object (state) is not found.
*/
public function reverseTransform($id)
{
if (!$id) {
return null;
}
$state = $this->om
->getRepository('ISFPIndexEntityBundle:State')
->findOneById(intval($id))
;
if (null === $state) {
throw new TransformationFailedException(sprintf(
'An state with id "%s" does not exist!',
$id
));
}
return $state;
}
}