symfony の選択フィールドを、js 経由で追加されたデータで正しく検証できるようにする簡単な方法はありますか? したがって、たとえば、空のフィールドをロードし、それに js/ajax 呼び出しを入力してから、プレス送信のオプションの 1 つを選択しますが、バリデーターは常にこのオプションをスローし、有効なエラーではありません...
背景を説明するために、選択タイプを親として使用するカスタムフォームタイプと、オプションをエンティティに変換するカスタムデータトランスフォーマーを取得しました(フォームタイプをテキストに変更して手動で入力すると、動作することを確認できます選択したい選択肢に対応するID、フォームは正常に送信されます)。
何か案は?ご覧になりたいファイルがありましたら、喜んで提供させていただきます。
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\nullstateTransformer;
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;
}
}