我有Symfony表单类型的类,我想单独使用它们,并将它们作为其他表单的一部分
class PracownikType extends AbstractType
{
const DATA_CLASS = 'AppBundle'Entity'Pracownik';
/** @var IPracownikRepository */
private $pracownikRepository;
/** @var User */
private $user;
/**
* PracownikType constructor.
* @param IPracownikRepository $pracownikRepository
* @param TokenStorage $tokenStorage
*/
public function __construct(IPracownikRepository $pracownikRepository, TokenStorage $tokenStorage)
{
$this->pracownikRepository = $pracownikRepository;
$this->user = $tokenStorage->getToken()->getUser();
}
/**
* @param FormBuilderInterface $builder
* @param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('imie', 'text')
->add('nazw', 'text')
->add('email', 'text')
->add('iloscDniWolnych', 'integer')
;
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'class' => self::DATA_CLASS,
'choices' => $this->pracownikRepository->findAllByUser($this->user),
'choice_label' => 'getNazw'
]);
}
public function getParent()
{
return 'entity';
}
public function getName()
{
return 'pracownik';
}
}
我可以使用这个类来创建独立的表单:
$form = $this->createForm('pracownik', $this->dodajPracownikaCommand);
以及其他形式的一部分:
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('pracownik', 'pracownik');
}
我该怎么做?请帮帮我。:)
不要只使用字符串"pracownik",而是创建一个类似new PracownikType()
的实例。
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('pracownik', new PracownikType());
}
如果必须使用字符串,则必须将表单类型声明为服务。请参阅:http://symfony.com/doc/current/book/forms.html#defining-您的表格即服务
然而,我不建议在这个时候这样做,因为我认为Symfony 2.8正在贬低这种行为。