Reputation: 23
I am calling entity to provide drop down options. I set a place holder value. I tried setting the data value, but regardless placeholder value is alway tag with selected.
My PostFormType:
public function buildForm(FormBuilderInterface $builder, array $options) {
$builder
->add('title', TextType::class, array( 'attr' => array(
'class' => 'form-control'
)))
->add('price', TextType::class, array( 'attr' => array(
'class' => 'form-control'
)))
->add('artist', EntityType::class, [
'data'=>2,
'placeholder'=>'Choose Artist',
'class'=>Artist::class,
'choice_label'=>'artist',
'query_builder'=> function (EntityRepository $er) {
return $er->createQueryBuilder('artist')
->orderBy('artist.artist', 'ASC');
},
'empty_data' => null,
'attr' => array(
'class' => 'form-control'
)
])
->add('userId', HiddenType::class )
->add('description', TextareaType::class, array( 'attr' => array(
'class' => 'form-control'
)))
->add('purchaseDate','date')
->add('id',HiddenType::class)
;
}
Upvotes: 1
Views: 1440
Reputation: 2267
I had the same issue using symfony 6.3, and could solve it with the following modifications:
First: while adding artist to form:
mapped: true
value: 2
, as this will reset your artist field value to 2 each time is form is rendered, regardless of your submitted value previously'choice_value' => fn($c) => $c,
to tell use the entity artist as the choice valueSecond: to convert the entity artist to a scalar value, implement __toString()
in your artist model
Third: add a view transformer to transform the ID of artist to artist entity once form is submitted:
$builder->get('artist')
->addViewTransformer(
new CallbackTransformer(
function (?string $modelData): ?Artist {
if ($modelData === null) {
return null;
}
return $this->artistRepository->find((int)$modelData);
},
function ($formData) {
return $formData;
},
)
);
Forth:: While creating the form in your controller, pass in the submitted value, suppose you form's method is GET
:
$queryParameters = $request->query->all();
$searchForm = $this->createForm(ArtistType::class, $queryParameters);
$searchForm->handleRequest($request);
Upvotes: 0
Reputation: 1587
You shouldn't configure data
for property artist
if it has to be modified by user in the form.
In case you want to set the default value of a new Entity. Even if you do, the change from UI form will not affect as the data
attribute will reset the value to 2
as provided after submit.
You can always use Constructor
of the relevant Entity
to set any default value.
But, as artist
is a referenced property. You should do it in Controller
before you build the form.
$artist = $em->getRepository("AppBundle:Artist")->find(2);
$entity->setArtist($artist)
// Load the form here. The default value automatically set in the form
Hope this helps!
Upvotes: 0