起初我认为这是不可能的,因为我之前在这个问题上做过一些研究。我决定试一试,我让它工作了。基本上我创建了一个自定义表单类型,它有两个字段问题和选项。然后我设法在数据转换类中获得了这两个值,它们可以用于转换。这是文件。
Note that the 'option' field is not used, but I did verify
it was accessible from the data transformer.
Also, I could not manage to render the validation messages declared
on the data transform class when transformation fails. I stopped
there, but if you manage to do it let me know.
第一个表单类型
class IssueSelectorType extends AbstractType
{
/**
* @var ObjectManager
*/
private $om;
/**
* @param ObjectManager $om
*/
public function __construct(ObjectManager $om)
{
$this->om = $om;
}
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('number', 'text', array(
// 'mapped' => false
));
$builder->add('option', 'choice', array(
// 'mapped' => false
));
$transformer = new IssueToNumberTransformer($this->om);
$builder->addViewTransformer($transformer);
}
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'invalid_message' => 'The selected issue does not exist',
));
}
public function getName()
{
return 'issue_selector';
}
public function getParent()
{
return 'field';
}
}
数据转换器类:
class IssueToNumberTransformer implements DataTransformerInterface
{
/**
* @var ObjectManager
*/
private $om;
/**
* @param ObjectManager $om
*/
public function __construct(ObjectManager $om)
{
$this->om = $om;
}
/**
* Transforms an object (issue) to a array .
*
* @param Issue|null $issue
* @return array
*/
public function transform($issue)
{
if (null === $issue)
{
return array(
'number' => 0,
'option' => 0
);
}
return array(
'number' => $issue->id,
'option' => 0
);
}
/**
* Transforms a array to an object (issue).
*
* @param array $value
* @return Issue|null
* @throws TransformationFailedException if object (issue) is not found.
*/
public function reverseTransform($value)
{
if (null === $value)
{
return null;
}
if (!is_array($value))
{
throw new UnexpectedTypeException($value, 'array');
}
$number = $value['number'] ;
$option = $value['option'] ;
$issue = $this->om
->getRepository('AcmeTransformerBundle:Issue')
->findOneBy(array('id' => $number))
;
if (null === $issue)
{
throw new TransformationFailedException(sprintf(
'An issue with number "%s" does not exist!', $number
));
}
return $issue;
}
}