Answer the question
In order to leave comments, you need to log in
How to create custom forms with nested fields in Symfony 4?
The question stems from this post Do I need to use Symfony forms? A similar situation occurs. Before creating an object (that is, not editing a saved entity), I will not find how to process the form. There is a User object, it has nested dependencies.
$user = $this->getUser();
// Какое то значение
$client = $user->getClient()->getClientSomeData();
// Допустим теги, описания, которое являются ArrayCollection вообще тьма
$clientTags = $user->getClient()->getTags()->getTag()->getName();
Answer the question
In order to leave comments, you need to log in
The solution is, as often, simple. Do not create internal fields for your type
namespace App\Form\Type;
use ...
class UserSelectType extends AbstractType
{
private $userRepository;
public function __construct(UserRepository $repository)
{
$this->userRepository = $repository;
}
public function buildForm(FormBuilderInterface $builder, array $options)
{
// Это фрагмент удаляем и вставляется обычное поле, а не форма
$builder->add(
'user',
AutocompleteType::class,
[
'label' => false,
'class' => User::class,
'attr' => [
'placeholder' => 'Клиент',
'class' => 'user-autocomplete-property',
],
]
);
//dd($builder);
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(
[
'label' => false,
'class' => User::class,
'attr' => [
'placeholder' => 'Клиент',
'class' => 'user-autocomplete-property',
],
]
);
}
public function getParent()
{
return AutocompleteType::class;
}
}
namespace App\Form;
use ...
class VehicleFormType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
/**
* @var Vehicle $vehicle
*/
$vehicle = $options['data'] ?? null;
$isEdit = $vehicle && $vehicle->getId();
$builder
->add(
'user',
UserSelectType::class,
[
'empty_data' => new ClientData(),
'property_path' => 'clientData',
]
)
->add(
'brand',
TextType::class,
[
'attr' => [
'placeholder' => 'Бренд',
],
'label' => false,
]
)
->add(
'button',
SubmitType::class,
[
'attr' => [
'class' => 'btn btn-primary',
],
'label' => $isEdit ? 'Изменить' : 'Сохранить',
]
)
->add(
'resetButton',
ResetType::class,
[
'attr' => [
'class' => 'btn btn-secondary',
],
'label' => 'Сбросить',
]
);
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(
[
'data_class' => Vehicle::class,
]
);
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question