Answer the question
In order to leave comments, you need to log in
How to pass saved data to a field in Symfony?
I have a POST entity with a cover field that contains an entity - a picture
//src/Entity/Post.php
/**
* @var Image
* @ORM\ManyToOne(targetEntity="Image", cascade={"persist"})
* @ORM\JoinColumn(name="cover_id", referencedColumnName="id")
**/
private $cover;
//src/Controller/PostController.php
/**
* @Route("/{id}/edit", name="post_edit", methods={"GET","POST"})
*/
public function edit(Request $request, Post $post): Response
{
$form = $this->createForm(PostType::class, $post);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$this->getDoctrine()->getManager()->flush();
return $this->redirectToRoute('post_index');
}
return $this->render('post/edit.html.twig', [
'post' => $post,
'form' => $form->createView(),
]);
}
//src/Form/PostType.php
class PostType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('cover', ImageType::class, array(
'label' => 'Cover'
));
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'data_class' => Post::class
]);
}
}
//src/Form/ImagetType.php
class ImageType extends FileType
{
private $imagePath;
/**
* ImageType constructor.
* @param $imagePath
*/
public function __construct($imagePath)
{
$this->imagePath = $imagePath;
}
public function buildForm(FormBuilderInterface $builder, array $options)
{
parent::buildForm($builder, $options);
$builder->addModelTransformer(new CallbackTransformer(
function(Image $image = null) {
if ($image instanceof Image) {
return new File($this->imagePath . '/' . $image->getFile());
}
},
function(UploadedFile $uploadedFile = null) {
if ($uploadedFile instanceof UploadedFile) {
$image = new Image();
$image->setFile($uploadedFile);
return $image;
}
}
));
}
public function getBlockPrefix()
{
return 'image';
}
public function configureOptions(OptionsResolver $resolver)
{
parent::configureOptions($resolver);
$resolver->setDefaults([
'required' => false
]);
}
}
Answer the question
In order to leave comments, you need to log in
You can do "->add('cover', ... " only on the create form, not on the edit form.
You can use $options to do this.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question