Variable "pageName" does not exist Symfony 5 EasyAdmin 4 - php

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 !

Related

How display image in edit form Symfony 5

I have form where i upload files - it work so good, i put image name into database, showing it on main page. But if i want to go to edit information about this image e.g name or description form row with image i have empty and once again i need to upload the same photo:
edit form
Project Entity:
/**
* #ORM\Column(type="string", length=255)
*/
private $page_path;
public function getPhotoPath(): ?string
{
return $this->photo_path;
}
public function setPhotoPath(string $photo_path): self
{
$this->photo_path = $photo_path;
return $this;
}
ProjectFormType:
<?php
namespace App\Form;
use App\Entity\Projects;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\Core\Type\FileType;
class ProjectsType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('name', TextType::class, [])
->add('page_path', TextType::class, [])
->add('description', TextType::class, [])
->add('photo_path', FileType::class, [
'data_class' => null,
'label' => 'Zdjęcie',
'constraints' => [
'maxSize' => '5M',
'mimeTypes' => [
'image/*'
],
'mimeTypesMessage' => 'Obsługiwany format pliku musi być obrazem'
]
]);
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'data_class' => Projects::class,
]);
}
}
View:
{% extends 'baseAdmin.html.twig' %}
{% block title %}{{ parent() }}New/Edit
{% endblock %}
{% block body %}
<div class="card-body">
{% form_theme projectsForm 'bootstrap_4_layout.html.twig' %}
{{ form_start(projectsForm) }}
{{ form_row(projectsForm.name) }}
{{ form_row(projectsForm.page_path) }}
{{ form_row(projectsForm.description) }}
{{ form_row(projectsForm.photo_path) }}
<button type="submit" class="btn btn-primary mb-5">Submit</button>
{{ form_end(projectsForm) }}
</div>
{% endblock %}
File input should be empty when edit your entity and this is the default behavior. to make it required false in edit you can use add this simple solution.
'required'=> is_null($builder->getData()->getId())
if you upload a new image, it should replace the old one, otherwise do nothing.
if you want to show the image, you can do it directly in the twig with <img> tag

Correct way to implement a search function in a symfony project?

Im learning Symfony and I'm creating a CRUD app for practicing.
I want to implement a search function in the page where I list my db items. I was wondering what is the correct way to achieve this.
Right now, I have created a searchType and searchController with the next code:
namespace AppBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
class searchController extends Controller
{
public function searchAction(){
$formulario = $this->createForm('AppBundle\Form\SearchType');
return $this->render('searchBar.html.twig', ['form' => $formulario->createView()]);
}
}
class SearchType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('key', ChoiceType::class,
['choices' => [
'Elegir Campo...' => 0,
'Modelo' => 1,
'Marca' => 2,
'Año' => 3,
'Propietario' => 4
]
])
->add('term', TextType::class)
->add('buscar', SubmitType::class)
;
}
}
I have another controller called itemController, where i have the list, add, modify and delete actions. With the twig render() function, I'm rendering the searchBar in the items list page. Which is the correct way to get the values from the 'key' and the 'term' elements and use them to make queries against the db?
I have tried to achieve this without the searchController/searchType and I used a simple <form> in the template and got the key and term values with $request->get() method in the listAction. After I created a switch-case statement to execute queries according to the key value. I could achieve what i wanted like this, but I want to be able to do this the correct way.
Can someone help me/give me some hints on how to continue from this?
Thanks.
Update:
Items Controller:
/**
*#Route("/items", name="items")
*/
public function listAction(Request $request){
$em = $this->getDoctrine()->getManager();
$items = $em->getRepository('AppBundle:Item')->findAll();
return $this->render('items.html.twig', ['items' => $items]);
}
My items.html.twig:
{% extends base.html.twig %}
{% block body %}
{{ render(controller('AppBundle:search:search')) }}
...
{% endblock %}
My searchBar.html.twig:
{{ form_start(form, {'attr': {'class': 'form-inline float-left my-2 my-lg-0'}}) }}
{{ form_widget(form.key) }}
{{ form_widget(form.term, {'attr': {'class': 'ml-1'}}) }}
{{ form_widget(form.buscar, {'attr': {'class': 'btn btn-outline-success ml-1'}}) }}
{{ form_end(form) }}
What i tried with routing and works with the searchController:
/**
* #Route("/search", name="search")
*/
public function searchAction(Request $request){
$em = $this->getDoctrine()->getManager();
$formulario = $this->createForm('AppBundle\Form\SearchType');
$formulario->handleRequest($request);
if($formulario->isSubmitted() && $formulario->isValid()){
$data = $formulario->getData();
$key = $data["key"];
$term = $data["term"];
$items = $em->getRepository('Item::class')->findByTerm($key, $term);
return $this->render('items.html.twig', ['items' => $items]);
}
return $this->render('searchBar.html.twig', ['form' => $formulario->createView()]);
}
If i go to /search and search for an item, it redirects me to my items page with the item i searched. But, If i use the search bar in my items page that i rendered using {{ render(controller('AppBundle:search:search')) }}, it doesn't work.
You are not very far from reaching your goal.
On your Controller, you can update your code to process the incoming request:
public function searchAction(Request $request){
$formulario = $this->createForm('AppBundle\Form\SearchType');
$formulario->handleRequest($request);
if ($formulario->isSubmitted() && $formulario->isValid()) {
$data = $formulario->getData();
// ... perform some action, such as saving the data to the database or search
}
return $this->render('searchBar.html.twig', ['form' => $formulario->createView()]);
}
You can find here more information about Processing Forms
To search into your database, you can process your repositories corresponding to the data. For more information about that, you can go here on Symfony Doctrine documentation
To go further, there is a bundle allowing simplified management of search forms: Lexik Form Filter Bundle

Why my symfony captcha always return valid?

I followed this tutorial to add a captcha to my form.
First I install it using
composer require captcha-com/symfony-captcha-bundle:"4.*"
After I Install it, I got an error on a file called captcha.html.twig
Error:
captcha Unexpected "spaceless" tag (expecting closing tag for the
"block" tag defined near line 2).
So I changed {% spaceless %} to {% apply spaceless %}
And the error is gone.
But My captcha bot always returns True (even when I don't even fill it.
Here is the ->add() function of my form:
->add('captchaCode', CaptchaType::class, [
'captchaConfig' => 'ExampleCaptchaUserRegistration',
'constraints' => [
new ValidCaptcha([
'message' => 'Invalid captcha, please try again',
]),
],]);
Code of Routes.yaml :
captcha_routing:
resource: "#CaptchaBundle/Resources/config/routing.yml"
Code of captcha.php :
<?php
// app/config/packages/captcha.php
if (!class_exists('CaptchaConfiguration')) { return; }
// BotDetect PHP Captcha configuration options
return [
// Captcha configuration for example form
'ExampleCaptchaUserRegistration' => [
'UserInputID' => 'captchaCode',
'ImageWidth' => 250,
'ImageHeight' => 50,
],
];
Captcha field on the User.php entity:
protected $captchaCode;
public function getCaptchaCode()
{
return $this->captchaCode;
}
public function setCaptchaCode($captchaCode)
{
$this->captchaCode = $captchaCode;
}
Code in the View (twig)
<span class="txt1 p-b-11">
Are You a Robot?
</span>
<div class="wrap-input100 m-b-36">
{{ form_widget(form.captchaCode, {'attr': {'class': 'input100'} }) }}
<span class="focus-input100"></span>
</div>
<div class="error">{{ form_errors(form.captchaCode) }} </div>
Controlleur function:
/**
* #Route("/register", name="user_register", methods={"GET","POST"})
*/
public function register(Request $request,UserPasswordEncoderInterface $encoder): Response
{
$user = new User();
$form = $this->createForm(UserType::class, $user, ['validation_groups' => ['register'], ]);
$form ->remove("description");
$form ->remove("phone");
$form ->remove("website");
$form ->remove("facebook");
$form ->remove("picture");
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$hash = $encoder->encodePassword($user,$user->getPassword());
$user->setPassword($hash);
// defaults values (user can edit them later)
$user->setDescription("Apparently, this User prefers to keep an air of mystery about them.");
$user->setPhone(null);
$user->setPicture("default.png");
$user->setWebsite(null);
$user->setFacebook(null);
$user->setRoles(["ROLE_USER"]);
// end default values
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($user);
$entityManager->flush();
return $this->redirectToRoute('user_login');
}
return $this->render('authentication/register.html.twig', [
'user' => $user,
'form' => $form->createView(),
]);
}

Symfony form inline radios with text fields

In Symfony I have a twig page that displays a form with text fields and check boxes. The form contains data for a question and four possible answers. The user can edit the data and select one answer that is correct.
At the moment I have all the text fields where the user can change the data and four check boxes. Instead of the check boxes I need radio buttons(this is to allow the user to select only one choice). Also I need the check boxes to be on the right hand side of text fields for each possible answer. How can I do this in Symfony. Would much appreciate some help.Thanks.
Using Collection of Forms to build the entire Form
Answer Form:
class AnswerFormType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('answer');
$builder ->add('isCorrect', null , array('label' => false,));
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array('data_class' => 'QuizBundle\Entity\Answer'));
}
public function getName()
{
return 'quiz_bundle_answer_form_type';
}
}
Question Form:
class QuestionFormType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('image');
$builder->add('question');
$builder->add('answers', CollectionType::class, array('entry_type' => AnswerFormType::class));
$builder->add('Submit', SubmitType::class, array('label' => 'Submit'));
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array('data_class' => 'QuizBundle\Entity\Question'));
}
public function getName()
{
return 'quiz_bundle_question_form_type';
}
}
This is my Twig:
{% extends 'base.html.twig' %}
{% block body %}
Edit record page
{{ form_start(form) }}
{{ form_row(form.image) }}
{{ form_row(form.question) }}
{% for answers in form.answers %}
<li>{{ form_row(answers.answer) }}</li>
{% endfor %}
{{ form_end(form) }}
{% endblock %}
You can not mix a radio input with text inputs to let the user edit them.
It is not possible with HTML.
No other choice, you have to :
Recreate the radio behavior with Javascript on the client side
Write some CSS to make your checkboxes looks like radio boxes.
Attach a form constraint which validates only one checkbox is selected after submit.
To put the text inputs at the right side, you have to customize the form widgets. Take a look at the documentation : http://symfony.com/doc/current/cookbook/form/form_customization.html
I understand what you are trying to do because of your previous question. For layout of the form, you can do something like this to make it look better:
{{ form_start(form) }}
{{ form_label(form.image) }}{{ form_widget(form.image) }}
{{ form_label(form.question) }}{{ form_widget(form.question) }}
{% for ans in form.answers %}
<li>{{ form_label(ans.answer) }}{{ form_widget(ans.answer) }}
{{ form_label(ans.isCorrect) }}{{ form_widget(ans.isCorrect) </li>
{{ form_end(form) }}
However, I don't think this is the solution for you. Like Alsatian mentioned, you need to use Javascript to check for "onchange" events for the radio buttons. You are creating a form class, which in my opinion doesn't always work for every design. You might try just a "createFormBuilder" instead and customize exactly as you need.
public function showQuestionFormAction($ansID, Request $request){
// Get Answers...
$em = $this->getDoctrine()->getManager();
$qb->select('a')
->from('AppBundle:Answer', 'a')
->where('a.answer_id = :ansID')
->setParameter('ansID', $ansID);
$ans = $qb->getQuery()->setMaxResults(1)->getOneOrNullResult();
$form = $this->createFormBuilder()
->add('image') // Not sure what type this is???
->add('question', EntityType::class, array(
'class' => 'AppBundle:Question',
'label' => 'Question:',
'choice_label' => 'question', // Label shown.
'choice_value' => 'question_id', // What data you want returned.
'attr' => array('class' => 'question_id'), // For css styling only, you may not need this.
'data' => $ques->getText(), // This is a method (getter) to get question text.
))
->add('ans1', RadioType::class, array(
'label' => '$ans->getAnswer1()',
'required' => false,
'attr' => array(
'onchange' => "check_answer('ans1')", // Javascript function.
'checked' => true,
),
))
->add('ans2', RadioType::class, array(
'label' => '$ans->getAnswer2()',
'required' => false,
'attr' => array(
'onchange' => "check_answer('ans2')", // Javascript function.
'checked' => false,
),
))
...
Then you can use a simple javascript function like so. I made this quickly, so there may be a better/simpler way to design this.
// script/check_answer.js
function check_answer(id){
var ans1 = document.getElementById("form_ans1");
var ans2 = document.getElementById("form_ans2");
var ans3 = document.getElementById("form_ans3");
var ans4 = document.getElementById("form_ans4");
// Check what is changed.
if(id == 'ans1'){
ans2.checked = false;
ans3.checked = false;
ans4.checked = false;
}
if(id == 'ans2'){
ans1.checked = false;
ans3.checked = false;
ans4.checked = false;
}
...
}
Hope that helps.

How to display the current picture above the upload field in SonataAdminBundle?

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')
}

Categories