In my project I have included a third-party bundle via composer containing multiple forms like:
namespace acme\ContactBundle\Form\Type;
class PersonType extends AbstractType {
/**
* @param FormBuilderInterface $builder
* @param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options) {
$builder
->add('firstname', TextType::class, array(
'label' => 'person.firstname'
))
->add('lastname', TextType::class, array(
'label' => 'person.lastname'
));
}
}
Now I would like to add an additional field before firstname
called title
.
Is there a way to do this without touching the original code? Probably, I also need to alter the entity to add the additional database field.
Alternatively: Since I have write access to the third-party bundle, maybe there's a way to allow fields to be injected?
I did the same with FOSUserBundle. |
You need to create a controller which will extends the third party controller. By this, we can overwrite their controller and have an extended functionality.
I imported their controller as follows.
use \FOS\UserBundle\Controller\SecurityController as BaseController;
and extended MyController with the BaseController. You method names should be the same as of third party bundle.
class MyController extends BaseController
{
//extending base loginActionMethod.
public function loginAction(Request $request)
{
//my code
}
}
Similarly in your case.
namespace acme\ContactBundle\Form\Type;
use path_to_your_third_party_formtype as BaseType;
class PersonType extends BaseType
{
/**
* @param FormBuilderInterface $builder
* @param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options) {
$builder
->add('title', TextType::class, array(
'label' => 'person.title'
))
->add('firstname', TextType::class, array(
'label' => 'person.firstname'
))
->add('lastname', TextType::class, array(
'label' => 'person.lastname'
));
}
}
You also need to take care of the entity.
Hope it helps, Cheers.
You can create a form type extension which will add the field that you want to add like this:
// ...
use Symfony\Component\Form\FormTypeExtensionInterface;
class TitleTypeExtension implements FormTypExtensionInterface
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('title', TextType::class);
}
public function getExtendedType()
{
return PersonType::class;
}
}
Make sure that your extension is registered as a service and tagged with the form.type_extension
tag.
However, this will only add the form type after the already existing children. Can you explain why it is important for you to insert it at a particular position?
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.