No entity manager defined for class DateTime - symfony

I have started using the Sonata Admin bundle and I was following the example on how to map an entity with the bundle to create an administrative interface.
I created an entity called Post and this is the configuration yml file:
Emiliano\PostsBundle\Entity\Post:
type: entity
table: null
repositoryClass: Emiliano\PostsBundle\Entity\PostRepository
id:
id:
type: integer
id: true
generator:
strategy: AUTO
fields:
title:
type: string
column: Title
lenght: 100
published:
type: boolean
column: Published
publishingDate:
type: datetime
column: Publishing_Date
nullable: TRUE
lifecycleCallbacks: { }
Then in my Admin class I have the configureFormFields method:
protected function configureFormFields(FormMapper $formMapper) {
$formMapper->add('title', 'text')
->add('published', 'checkbox', array('required' => false))
->add('publishingDate', 'sonata_type_model_hidden');
}
I found the sonata_type_model_hidden on the sonata admin documentation. What I would like to achieve is to programmatically handle the publishing date (e.g. set the date only if the checkbox published is checked) hiding the implementation to the user.
Everything works fine for create, delete and read, when it comes to modify an entity I get this message in the stacktrace:
No entity manager defined for class DateTime
In sonata-project/doctrine-orm-admin-bundle/Sonata/DoctrineORMAdminBundle/Model/ModelManager.php at line 214
If I show the field everything works fine, I tried also to use:
->add('publishingDate', 'hidden');
without success.
What is exactly the problem here? Is it because Sonata Admin tries to fill a form with the entity values and for publishingDate there's a DateTime while in the form specification I wrote a sonata_type_model_hidden? If so, how can I circumvent this?

sonata_type_model_hidden isn't just hidden field genereator, according to documentation:
sonata_type_model_hidden will use an instance of ModelHiddenType to render hidden field. The value of hidden field is identifier of related entity.
If I understand your problem, You want to set publishing date only when field published == true
You could use entity preSave/preUpdate lifecycle callback for eaxmple
public function preSave()
{
/**
* Check if item is published
*/
if($this->getPublished()) {
$this->setPublishingDate(new \DateTime());
} else {
$this->setPublishingDate(null);
}
}
and remove publishingDate field from SonataAdmin form.

Related

Add empty value to AssociationField in EasyAdminBundle

I want my AssociationField to display a blank value by defaut, in ordre to force the users to select an item.
As I understand, AssociationField is based on EntityType FormType.
My Problem is, if the field of my entity is required, the create form renders the AssociationField without empty value, and thus selects the first value.
I haven't seen any option to add a placeholder to a select for required properties.
Here are some samples:
My Doctrine entity :
//Player.php
#[ORM\ManyToOne(inversedBy: 'players')]
#[ORM\JoinColumn(name:'team_id', referencedColumnName: 'id', nullable: false)]
private Team $team;
... and my CrudController
//PlayerCrudController.php
public function configureFields(string $pageName): iterable
{
return [
//...
AssociationField::new('team'),
//...
]
}
And the create form displays a select with already a value selected.
I've looked into the docs but couldn't find how to achieve this.

PHOTO FIELD IN EASYADMIN IS NOT SHOWING

I am trying to display some images in my bundle (using easyadmin bundle) & symfony 3.4
However, for some reason, the photos aren't showing.
here's my code:
in config.yml:
Employee:
class: BackofficeBundle\Entity\Employee
role_prefix: ROLE_EMPLOYEE_MANAGER
list:
fields:
- id
- Name
- { property: 'photo', label: 'EMPLOYEE AVATAR', type: 'image' , base_path: '/images/' }
in my Employee entity:
/**
* #ORM\Column(name="photo", type="string", length=500)
* #Assert\File(maxSize="500k", mimeTypes={"image/jpeg", "image/jpg", "image/png", "image/GIF"})
*/
private $photo;
in my EmployeeType.php
$builder->add('photo', FileType::class, array('data_class'=>null, 'required'=>false
));
The photo aren't showing in the List page and when i click on the edit i get this error :
The form's view data is expected to be an instance of class Symfony\Component\HttpFoundation\File\File, but is a(n) string. You can avoid this error by setting the "data_class" option to null or by adding a view transformer that transforms a(n) string to an instance of Symfony\Component\HttpFoundation\File\File.
For this case, please consider using VichUploadBundle https://symfony.com/doc/master/bundles/EasyAdminBundle/integration/vichuploaderbundle.html

SonataAdmin create entity with boolean field

I have this entity, if I create a record like this.
$synopsis = new Synopsis();
$synopsis->setPartOne("a");
$synopsis->setPartTwo("b");
$synopsis->setTitle("A");
$synopsis->setSubtitle("B");
$synopsis->setEnabled(false);
$em->persist($synopsis);
$em->flush();
And then I go to my Admin, I see the enabled field to "no" which is expected.
But now, If I use the sonata admin new form field, even if I choose enabled "no", the record is created with enabled = true. And I don't really see why it would be like that.
Here is what I have in my SynopsisAdmin
protected function configureFormFields(FormMapper $formMapper)
{
$formMapper->add('title', TextType::class);
$formMapper->add('subtitle', TextType::class);
$formMapper->add('partOne', TextAreaType::class);
$formMapper->add('partTwo', TextAreaType::class);
$formMapper->add('enabled', BooleanType::class);
}
This is how the enabled field is defined in the entity
/**
* #ORM\Column(type="boolean")
*/
private $enabled;
Thanks for your help.
EDIT: Fun facts too, even if I see no in the sonata view list, when I go to the form view, I see yes instead.
I suspect an error within the sonata core functionnality.
I think you should use the CheckboxType instead of the BooleanType for your Form fields.
Looks like the BooleanType is ment for the list, show and grid actions.
https://symfony.com/doc/master/bundles/SonataAdminBundle/reference/field_types.html
Update
To use the BooleanType you have to set the 'transform' option to true.
This transforms your boolean value to the YES/NO options in the BooleanType:
$formMapper
->add('enabled', BooleanType::class, [
'transform' => true
])

Easyadmin is not recognizing boolean type

I am trying to implement a backend using easyadmin, I think its a great idea and I love the implementation... so far is going well, but I have a little problem, I want to show in the form a boolean field, for ex: 'published', my configuration looks like this:
Blog:
label: 'Posts list'
class: MyCompany\MyBundle\Entity\Post
list:
fields: ['title', 'published']
new:
fields:
- 'title'
- 'summary'
- 'body'
- { property: 'published', type: 'boolean' }
When I run this code, I get the error:
Could not load type "boolean"
This is how I define the field in the Entity:
/**
*
* #ORM\Column(name="published", type="boolean", length=1)
*/
protected $published = 1;
I know it's been a while since this question's posted, but for anyone still getting this error, in easyadmin documentation (https://github.com/javiereguiluz/EasyAdminBundle/blob/master/Resources/doc/book/4-edit-new-configuration.md) it is specified which types we need to use for each scenario (list, edit views).
In your question (edit scenario) so far the only workaround is to use "checkbox"as type in config.yml. Edit view only accepts Symfony Form Types (http://symfony.com/doc/current/reference/forms/types.html).
You don't have to specify type in configuration yml file. It will take automatically from entity.

How to update counter field on the inverse side in many-to-many relation in Symfony?

I have two enteties User and Category, which are connected each other by many-to-many relation.
manyToMany:
categories:
targetEntity: Category
joinTable:
name: users_categories
joinColumns:
user_id:
referencedColumnName: id
inverseJoinColumns:
category_id:
referencedColumnName: id
In my UserAdmin.php (I'm using Sonata Admin and Sonata User bundles) they are handled by this field:
->add('categories', 'sonata_type_model', array('required' => false, 'expanded' => false, 'multiple' => true, 'label' => 'Chose your categories'))
Now I need to add extra field to my Category entity - user_counter, which store number of users, linked with it. It should be updated every time User add, update or delete his relations with Categories.
One idea was to make method in User entity which would get his categories before saving admin form, comparing them to current input and then making decision (categories counter to make +1 or -1). And switch on this method by lifecycleCallbacks (prePersist and preUpdate).
The problem: my code will get all User categories and compare them to current input on each form saving. How I can avoid such overhead? Maybe there is another solution for this task?
Thank you for help.
One way you could keep track is to modify your collection methods in your entity. For instance:
/*
* #ORM\Column(name="user_counter", type="integer")
*/
protected $user_counter;
public function addUser(User $user)
{
$this->users[] = $user;
$this->user_counter++;
}
public function removeUser(User $user)
{
$this->users->remove($user);
$this->user_counter--;
}
Alternatively, if you don't need the counts in the database, just do a $category->getUsers()->count();
Edit:
If you want to use an event listener to track this instead of modifying your entity setters, use a combination of $unitOfWork->getScheduledCollectionUpdates() and getDeleteDiff() and getInsertDiff().

Resources