I'm trying to render an image from VichUploader Bundle, and I succeed to do it.
But when I try to include : '#EasyAdmin/crud/detail.html.twig' in my twig file I got an pageName does not exist.
And when I do not set a custom template on my CrudController the pageName exist.
I can't figure out why...
I'm using PHP 8.0, Symfony 5.4.6, EasyAdmin 4.0, and VichUploader 1.19
here is my code:
CrudController:
public function configureFields(string $pageName): iterable
{
$pageName = "detail";
return [
$pageName,
TextField::new('Title'),
TextareaField::new('Description')->hideOnIndex(),
IntegerField::new('Price')->onlyWhenCreating(),
TextField::new('linkToBookingCom', 'Link to booking.com'),
TextField::new('frontImageFile', 'Front image')->setFormType(VichImageType::class)->hideOnIndex(),
CollectionField::new('gallery', 'Gallery of images')
->setEntryType(GalleryType::class)
->hideOnIndex()
->setTemplatePath(
'backoffice/custom-gallery-rendering.html.twig'
)
->setFormTypeOption('by_reference', false)
,
];
// TODO create an assert to validate the link probably with some regex
}
public function configureCrud(Crud $crud): Crud
{
return $crud
->renderContentMaximized()
->setEntityLabelInSingular('Suite')
->setEntityLabelInPlural('Suites')
->setPageTitle(Crud::PAGE_DETAIL, fn(Suite $suite) => $suite->__toString()."details")
;
}
public function configureResponseParameters(KeyValueStore $responseParameters): KeyValueStore
{
if ($responseParameters->has('pageName')) {
if ($responseParameters->get('pageName') === Crud::PAGE_DETAIL) {
$responseParameters->set('suite', $responseParameters->get('entity'));
$responseParameters->set('templateName', 'custom-gallery-rendering.html.twig');
$responseParameters->set('templatePath', 'backoffice/custom-gallery-rendering.html.twig');
// dd($responseParameters);
}
}
return $responseParameters;
}
the GalleryType:
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('imageFile', VichImageType::class,[
'required' => true,
]);
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'data_class' => Image::class,
]);
}
My Twig file:
{% include '#EasyAdmin/crud/detail.html.twig' %}
<div>
{% for image in suite.instance.gallery.images %}
<div id="ea-lightbox-{{ image.id }}">
<img src="{{ vich_uploader_asset(image, 'imageFile') }}" alt="{{ image.imageName }}">
</div>
{% endfor %}
</div>
If you need more information please ask me !
I am building a crud app using symfony 4. Here is the controller code:
<?php
namespace App\Controller;
use App\Entity\Taskslist;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Form\Extension\Core\Type\TextType;
class TodoController extends Controller{
/**
* #Route("/",name="todo_list")
*/
public function listAction(){
$todos=$this->getDoctrine()->getRepository('App:Taskslist')->findAll();
return $this->render('todo/index.html.twig',array('todos' => $todos));
}
/**
* #Route("/todo/create",name="todo_create")
*/
public function createAction(Request $request){
$todo = new Taskslist;
$form = $this->createFormBuilder($todo)
->add('id', TextType::class)
->add('title', TextType::class)
->add('description', TextareaType::class)
// ->add('priority', ChoiceType::class, array('choices' => array('Low' => 'Low', 'Normal' => 'Normal', 'High'=>'High'), 'attr' => array('class' => 'form-control', 'style' => 'margin-bottom:15px')))
// ->add('status', BooleanType::class, array('attr' => array('class' => 'form-control', 'style' => 'margin-bottom:15px')))
->add('Save', SubmitType::class, array('label'=> 'Create Todo'))
->getForm();
$form->handleRequest($request);
if($form->isSubmitted() && $form->isValid()){
$name = $form['id']->getData();
$category = $form['title']->getData();
$description = $form['description']->getData();
//$due_date = $form['status']->getData();
//$name = $form['name']->getData();
//$now = new\DateTime('now');
$todo->setId($name);
$todo->setTitle($category);
$todo->setDescription($description);
$sn = $this->getDoctrine()->getManager();
$sn -> persist($todo);
$sn -> flush();
return $this->redirectToRoute('todo_list');
}
return $this->render('todos/create.html.twig', array(
'form' => $form->createView()
));
}
/**
* #Route("/todo/edit/{id}",name="todo_edit")
*/
public function editAction($id,Request $request){
return $this->render('todo/edit.html.twig');
}
/**
* #Route("/todo/details/{id}",name="todo_details")
*/
public function detailsAction($id){
return $this->render('todo/details.html.twig');
}
}
And here is the edit.html.twig:
{% extends 'base.html.twig' %}
{% if form is defined %}
{% block body %}
{{form_start(form)}}
{{form_widget(form)}}
{{form_end(form)}}
{% endblock %}
{% endif %}
I followed all the tutorials but got this error when i click the edit button :
variable form does not exist.
Although my code steps into the if statement.
Can you please help me?Thanks in advance.i couldn't find any working solution
I think the issue is here:
{% extends 'base.html.twig' %}
{% if form is defined %}
{% block body %}
{{form_start(form)}}
{{form_widget(form)}}
{{form_end(form)}}
{% endblock %}
{% endif %}
use this instead:
{% extends 'base.html.twig' %}
{% block body %}
{{form_start(form)}}
{{form_widget(form)}}
{{form_end(form)}}
{% endblock %}
I have created Custom Form Field Type according to the documentation and it works fine(I mean no errors). I have a class:
<?php
namespace AppBundle\Form\Type;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
class RangeType extends AbstractType
{
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
));
}
public function getParent()
{
return RangeType::class;
}
}
I have a twig template:
{# app/Resources/views/form/fields.html.twig #}
{% block range_widget %}
<div class="cell-md-12 offset-top-45 offset-md-top-0">
<div data-min="" data-max="6000" data-start="[9, 2999]" data-step="10" data-tooltip="false" data-min-diff="10" data-input=".rd-range-input-value-2" data-input-2=".rd-range-input-value-3" class="rd-range"></div>
<hr class="divider divider-offset-lg divider-gray veil reveal-md-block">
</div>
{% endblock %}
I added that to the config:
# app/config/config.yml
twig:
form_themes:
- 'form/fields.html.twig'
and finally I have a code to add the field to the form:
$builder->add('price', RangeType::class, [
'data' => $options['priceRange'] ? $options['priceRange'] : $options['minPrice'].",".$options['maxPrice'],
'attr'=> [
'data-min' => $options['minPrice'],
'data-max' => $options['maxPrice'],
'data-dimension' => $options['dimension']
]
]);
How do I use that "data", "data-min", "data-max", "data-dimension" options from the form builder in the twig template? So far as you can see all of them are static in the template.
You can access you 'attr' option values by using the folowing path:
form.vars.attr
So, to get the 'data-min' parameter value form example, you'll just need to do:
{% set attr = form.vars.attr %}
<div data-min="{{ attr['data-min'] }}" ...
This is form i use:
$form = $this->createForm(new NewsType(), $news)
->add('edit', SubmitType::class, array('label' => 'edit'))
->add('delete', SubmitType::class, array('label' => 'delete'))
->add('comments', CollectionType::class, array('entry_type' => CommentType::class));
CommentType:
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('author', TextType::class)
->add('text', TextType::class)
->add('remove', SubmitType::class);
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'AppBundle\Entity\Comment'));
}
Is it possible to access remove button from CommentType so when its clicked to delete comment entry. Everything is mapped properly, i can see comment objects displayed on my page, but when i use $form->get('remove') i get "Child "remove" does not exist." Is it even possible to do this way?
You need to access a grand grand child doing:
foreach ($form->get('comments') as $entry) {
$toRemove = $entry->get('remove')-isClicked();
// handle it ...
}
But to submit it separately you must ensure that your building the "complete" child form in your view:
{{ form_start(form) }}
{% for child in form %}
{% if 'news_comments' == child.vars['full_name'] %}
{{ form_start(child) }}
{{ form_row(child) }}
{{ form_end(child) }}
{% else %}
{{ form_row(child) }}
{% endif %}
{% endfor %}
{{ form_end(form) %}
Aside note:
be careful, you seem to use symfony 2.8 and to have updated the FQCN for the form types, but it's needed too for creating the form:
$form = $this->createForm(NewsType::class, $news)
I am using SonataAdminBundle (with Doctrine2 ORM) and I have successfully added a file upload feature to my Picture model.
I would like, on the Show and Edit pages, to display a simple <img src="{{ picture.url }} alt="{{ picture.title }} /> tag just above the relevant form field (provided that the Picture being edited is not new, of course), so that the user may see the current photo, and decide whether to change it or not.
After hours of research, I've been unable to figure out how to do it. I suppose I need to override some template, but I'm a bit lost...
Can somebody give me a hint?
Thank you!
Here is the relevant section of my PictureAdmin class.
protected function configureFormFields(FormMapper $formMapper)
{
$formMapper
->add('category', NULL, ['label' => 'Catégorie'])
->add('title', NULL, ['label' => 'Titre'])
->add('file', 'file', ['required' => false, 'label' => 'Fichier']) // Add picture near this field
->add('creation_date', NULL, ['label' => 'Date d\'ajout'])
->add('visible', NULL, ['required' => false, 'label' => 'Visible'])
->add('position', NULL, ['label' => 'Position']);
}
protected function configureShowFields(ShowMapper $showMapper)
{
$showMapper
->add('id', NULL, ['label' => 'ID'])
->add('category', NULL, ['label' => 'Catégorie'])
->add('title', NULL, ['label' => 'Titre'])
->add('slug', NULL, ['label' => 'Titre (URL)'])
->add('creation_date', NULL, ['label' => 'Date d\'ajout'])
->add('visible', NULL, ['label' => 'Visible'])
->add('position', NULL, ['label' => 'Position']);
// Add picture somewhere
}
I have managed to put the image above the field in the edit form. But my solution is a little bit specific, because I use Vich Uploader Bundle to handle uploads, so the generation of the image url was a little bit easier thanks to bundle helpers.
Let's look at my example, a film poster field in a film entity.
This is part of my admin class:
//MyCompany/MyBundle/Admin/FilmAdmin.php
class FilmAdmin extends Admin {
protected function configureFormFields(FormMapper $formMapper)
{
$formMapper
->add('title')
....
->add('poster', 'mybundle_admin_image', array(
'required' => false,
))
}
mybundle_admin_image is handled by a custom field type, that is just a child of file type by setting it's getParent method: (don't forget to register your type class as a service)
//MyCompany/MyBundle/Form/Type/MyBundleAdminImageType.php
public function getParent()
{
return 'file';
}
Then I have a template that extends Sonata's default styling, and I have it included in the admin class:
//MyCompany/MyBundle/Admin/FilmAdmin.php
public function getFormTheme() {
return array('MyCompanyMyBundle:Form:mycompany_admin_fields.html.twig');
}
And finally I have a block for my custom image type that extends the basic file type:
//MyCompany/MyBundle/Resources/views/Form/mycompany_admin_fields.html.twig
{% block mybundle_admin_image_widget %}
{% spaceless %}
{% set subject = form.parent.vars.value %}
{% if subject.id and attribute(subject, name) %}
<a href="{{ asset(vich_uploader_asset(subject, name)) }}" target="_blank">
<img src="{{ asset(vich_uploader_asset(subject, name)) }}" width="200" />
</a><br/>
{% endif %}
{% set type = type|default('file') %}
<input type="{{ type }}" {{ block('widget_attributes') }} {% if value is not empty %}value="{{ value }}" {% endif %}/>
{% endspaceless %}
{% endblock %}
This causes that a 200px wide preview of image (if exists) is shown above the upload field, linked to it's full size version opening in new tab. You can customize it as you want, e.g. adding a lightbox plugin.
you can easily do this on edit page by helpers(FormMapper->setHelps) or option "help" pass on FormMapper
protected function configureFormFields(FormMapper $formMapper) {
$options = array('required' => false);
if (($subject = $this->getSubject()) && $subject->getPhoto()) {
$path = $subject->getPhotoWebPath();
$options['help'] = '<img src="' . $path . '" />';
}
$formMapper
->add('title')
->add('description')
->add('createdAt', null, array('data' => new \DateTime()))
->add('photoFile', 'file', $options)
;
}
You can easily do this on show page
by template attribute pass on $showmapper
->add('picture', NULL, array(
'template' => 'MyProjectBundle:Project:mytemplate.html.twig'
);
and inside your template you get current object so u can call get method and pull image path
<th>{% block name %}{{ admin.trans(field_description.label) }}{% endblock %}</th>
<td>
<img src="{{ object.getFile }}" title="{{ object.getTitle }}" />
</br>
{% block field %}{{ value|nl2br }}{% endblock %}
</td>
To show image in edit mode you have to override fileType or you have to create your own customType on top of fileType
There is also some bundle which is having this kind of functionality
check out this GenemuFormBundle
Solution for Symfony3
The answer from #kkochanski is the cleanest way I found so far. Here a version ported to Symfony3. I also fixed some bugs.
Create a new template image.html.twig for your new form type (full path: src/AppBundle/Resources/views/Form/image.html.twig):
{% block image_widget %}
{% spaceless %}
{% set type = type|default('file') %}
<input type="{{ type }}" {{ block('widget_attributes') }} {% if value is not empty %}value="{{ value }}" {% endif %}/>
{% if image_web_path is not empty %}
<img src="{{ image_web_path }}" alt="image_photo"/>
{% endif %}
{% endspaceless %}
{% endblock %}
Register the new form type template in your config.yml:
twig:
form_themes:
- AppBundle::Form/image.html.twig
Create a new form type and save it as ImageType.php (full path: src/AppBundle/Form/Type/ImageType.php):
<?php
namespace AppBundle\Form\Type;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Form\FormView;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\Form\FormBuilderInterface;
/**
* Class ImageType
*
* #package AppBundle\Form\Type
*/
class ImageType extends AbstractType
{
/**
* #return string
*/
public function getParent()
{
return 'file';
}
/**
* #return string
*/
public function getName()
{
return 'image';
}
/**
* #param OptionsResolver $resolver
*/
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'image_web_path' => ''
));
}
/**
* #param FormView $view
* #param FormInterface $form
* #param array $options
*/
public function buildView(FormView $view, FormInterface $form, array $options)
{
$view->vars['image_web_path'] = $options['image_web_path'];
}
/**
* #param FormBuilderInterface $builder
* #param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->setAttribute('image_web_path', $options['image_web_path'])
;
}
}
If you have done this. You can just import the new ImageType in your entity admin class:
use AppBundle\Form\Type\ImageType
And then, finally use the new form type without any inline-html or boilerplate code in configureFormFields:
$formMapper
->add('imageFile', ImageType::class, ['image_web_path' => $image->getImagePath()])
;
Instead of $image->getImagePath() you have to call your own method that returns the url to your image.
Screenshots
Creating a new image entity using sonata admin:
Editing a image entity using sonata admin:
You can simple do by this way
$image = $this->getSubject();
$imageSmall = '';
if($image){
$container = $this->getConfigurationPool()->getContainer();
$media = $container->get('sonata.media.twig.extension');
$format = 'small';
if($webPath = $image->getImageSmall()){
$imageSmall = '<img src="'.$media->path($image->getImageSmall(), $format).'" class="admin-preview" />';
}
}
$formMapper->add('imageSmall', 'sonata_media_type', array(
'provider' => 'sonata.media.provider.image',
'context' => 'default',
'help' => $imageSmall
));
Teo.sk wrote the method of showing images using VichUploader. I found an option which allow you to show images without this bundle.
First we need to create our form_type. There is tutorial: symfony_tutorial
In main Admin class:
namespace Your\Bundle;
//.....//
class ApplicationsAdmin extends Admin {
//...//
public function getFormTheme() {
return array_merge(
parent::getFormTheme(),
array('YourBundle:Form:image_type.html.twig') //your path to form_type template
);
protected function configureFormFields(FormMapper $formMapper)
{
$formMapper->add('file_photo', 'image', array(
'data_class' => 'Symfony\Component\HttpFoundation\File\File',
'label' => 'Photo',
'image_web_path' => $this->getRequest()->getBasePath().'/'.$subject->getWebPathPhoto()// it's a my name of common getWebPath method
))
//....//
;
}
}
Next part is a code from ImageType class.
namespace Your\Bundle\Form\Type;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
use Symfony\Component\OptionsResolver\Options;
use Symfony\Component\Form\FormView;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\Form\FormBuilder;
use Symfony\Component\Form\FormBuilderInterface;
class ImageType extends AbstractType
{
public function getParent()
{
return 'file';
}
public function getName()
{
return 'image';
}
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'image_web_path' => ''
));
}
public function buildView(FormView $view, FormInterface $form, array $options)
{
$view->vars['image_web_path'] = $options['image_web_path'];
}
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->setAttribute('image_web_path', $options['image_web_path'])
;
}
}
And on the end time for image_type twig template.
{% block image_widget %}
{% spaceless %}
{% set type = type|default('file') %}
<input type="{{ type }}" {{ block('widget_attributes') }} {% if value is not empty %}value="{{ value }}" {% endif %}/>
<img src="{{ image_web_path }}" alt="image_photo"/>
{% endspaceless %}
{% endblock %}
For me it's working! I'm also using avalanche bundle to resize images.
There is an easy way - but you will see the picture below the upload button.
SonataAdmin lets put raw HTML into the ‘help’ option for any given form field. You can use this functionality to embed an image tag:
protected function configureFormFields(FormMapper $formMapper) {
$object = $this->getSubject();
$container = $this->getConfigurationPool()->getContainer();
$fullPath = $container->get('request')->getBasePath().'/'.$object->getWebPath();
$formMapper->add('file', 'file', array('help' => is_file($object->getAbsolutePath() . $object->getPlanPath()) ? '<img src="' . $fullPath . $object->getPlanPath() . '" class="admin-preview" />' : 'Picture is not avialable')
}