Question

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?

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top