Sonataadminbundle: Unable to use the sonata_type_admin field - Field not linked to an admin

Created on 25 Nov 2014  Â·  40Comments  Â·  Source: sonata-project/SonataAdminBundle

I have an entity "Author" and "Image" with a simple OneToOne relation.
I tried to embed an Admin class in my Author admin class for the "image" field which is linked to the Image entity.

The mapping betweens the two classes is correct.

I created an Admin class for each entity :

  • ImageAdmin works correctly. When I add a new image, the database is updated and the image is uploaded.
  • Then I create the AuthorAdmin thanks to the documentation (http://sonata-project.org/bundles/admin/master/doc/reference/form_types.html#sonata-type-admin). But I always have this message :

The current field image is not linked to an admin. Please create one for the target entity : ``

The admin services are registred in the admin.yml (I used http://sonata-project.org/bundles/admin/master/doc/reference/form_types.html#sonata-type-admin) :

services:
    sonata.admin.author:
        class: Project\BackendBundle\Admin\AuthorAdmin
        tags:
            - { name: sonata.admin, manager_type: orm, group: "Content", label: "Author" }
        arguments:
            - ~
            - Project\BackendBundle\Entity\Author
            - ~

    sonata.admin.image:
        class: Project\BackendBundle\Admin\ImageAdmin
        tags:
            - { name: sonata.admin, manager_type: orm, group: "Content", label: "Image" }
        arguments:
            - ~
            - Project\BackendBundle\Entity\Image
            - 'SonataAdminBundle:CRUD'

I followed all the documentation but now I don't see the problem. I even try to pass the FieldDescription option "admin_code" :

$formMapper
    ->add('name', 'text', array('label' => 'Author name'))
    ->add(
        'image',
        'sonata_type_admin',
        array(),
        array('admin_code' => 'sonata.admin.image')
    )
;

I use the lastest version of sonata admin bundle sonata-project/admin-bundle.

All 40 comments

@ORM\Column overrides @ORM\OneToOne and Doctrine sees this field as simple field - not as association. I just had to remove the line.

Hey guys,

I'd like to reopen this issue as it is happening with the latest stable version of Sonata, without @ORM\Column annotation.
I currently have following version for my project :

  • sonata-project/admin-bundle 3.4.0
  • sonata-project/block-bundle 3.1.1
  • sonata-project/core-bundle 3.0.3
  • doctrine/orm 2.5.4
  • symfony/symfony 3.0.8

I have the same error message when I try to use sonata_type_admin with all my admin forms.

Here is an example : I 'm trying to include a Company admin form in a Contact

Here are my 2 entities relations parts :

/**
 * Contact
 *
 * @ORM\Table(name="contact")
 * @ORM\Entity
 */
class Contact
{
    /**
     * @ORM\ManyToOne(targetEntity="Project\UserBundle\Entity\Company", inversedBy="contacts")
     * @ORM\JoinColumn(name="company_id", referencedColumnName="id")
     * @Assert\NotNull
     */
    protected $company;
}
/**
 * Company
 *
 * @ORM\Table(name="company")
 * @ORM\Entity
 */
class Company
{
    /**
     * @ORM\OneToMany(targetEntity="Project\UserBundle\Entity\Contact", mappedBy="company")
     */
    protected $contacts;
}

Services :

    project_user.admin.company:
        class: Project\UserBundle\Admin\CompanyAdmin
        arguments: [~, Project\UserBundle\Entity\Company, 'SonataAdminBundle:CRUD']
        tags:
            - {name: sonata.admin, manager_type: orm, label: Company}
        calls:
            - [ setTranslationDomain, ['ProjectModelAdmin']]

    project_user.admin.contact:
        class: Project\UserBundle\Admin\ContactAdmin
        arguments: [~, Project\UserBundle\Entity\Contact, ProjectUserBundle:ContactAdmin]
        tags:
            - {name: sonata.admin, manager_type: orm, label: Contact}
        calls:
            - [ setTranslationDomain, ['ProjectModelAdmin']]

In ContactAdmin class :

$formMapper
    ->add('company', 'sonata_type_admin',
        array(
            'required'   => true,
            'btn_add'    => false,
            'btn_delete' => false,
        ),
        array(
            'admin_code' => 'project_user.admin.company',
        )
    )
;

Both admin class works well separately, but with company as a sonata_type_admin (as well as my other admin classes) It shows up the following error message :

The current field company is not linked to an admin. Please create one for the target entity : ``

Please create one for the target entity

Can you give a full stack trace?

Sure here it is (I replaced some namespaces by 'project' in my previous example)

INFO - Matched route "admin_thecamp_user_contact_create". 
DEBUG - Read existing security token from the session. 
DEBUG - SELECT t0.username AS username_1, t0.username_canonical AS username_canonical_2, t0.email AS email_3, t0.email_canonical AS email_canonical_4, t0.enabled AS enabled_5, t0.salt AS salt_6, t0.password AS password_7, t0.last_login AS last_login_8, t0.locked AS locked_9, t0.expired AS expired_10, t0.expires_at AS expires_at_11, t0.confirmation_token AS confirmation_token_12, t0.password_requested_at AS password_requested_at_13, t0.roles AS roles_14, t0.credentials_expired AS credentials_expired_15, t0.credentials_expire_at AS credentials_expire_at_16, t0.id AS id_17, t0.firstname AS firstname_18, t0.lastname AS lastname_19, t0.locale AS locale_20, t0.created_at AS created_at_21, t0.updated_at AS updated_at_22 FROM user t0 WHERE t0.id = ? LIMIT 1 
DEBUG - User was reloaded from a user provider. 
DEBUG - Notified event "kernel.request" to listener "Symfony\Component\HttpKernel\EventListener\DebugHandlersListener::configure". 
DEBUG - Notified event "kernel.request" to listener "Symfony\Component\HttpKernel\EventListener\DumpListener::configure". 
DEBUG - Notified event "kernel.request" to listener "Symfony\Component\HttpKernel\EventListener\ValidateRequestListener::onKernelRequest". 
DEBUG - Notified event "kernel.request" to listener "Symfony\Bundle\FrameworkBundle\EventListener\SessionListener::onKernelRequest". 
DEBUG - Notified event "kernel.request" to listener "Symfony\Component\HttpKernel\EventListener\FragmentListener::onKernelRequest".
DEBUG - Notified event "kernel.request" to listener "Symfony\Component\HttpKernel\EventListener\RouterListener::onKernelRequest". 
DEBUG - Notified event "kernel.request" to listener "Symfony\Component\HttpKernel\EventListener\LocaleListener::onKernelRequest". 
DEBUG - Notified event "kernel.request" to listener "Symfony\Component\HttpKernel\EventListener\TranslatorListener::onKernelRequest". 
DEBUG - Notified event "kernel.request" to listener "Symfony\Component\Security\Http\Firewall::onKernelRequest". 
DEBUG - Notified event "kernel.request" to listener "Knp\Bundle\MenuBundle\EventListener\VoterInitializerListener::onKernelRequest". 
DEBUG - Notified event "kernel.controller" to listener "Symfony\Bundle\FrameworkBundle\DataCollector\RouterDataCollector::onKernelController". 
DEBUG - Notified event "kernel.controller" to listener "Symfony\Component\HttpKernel\DataCollector\RequestDataCollector::onKernelController". 
DEBUG - Notified event "kernel.controller" to listener "Sensio\Bundle\FrameworkExtraBundle\EventListener\ControllerListener::onKernelController". 
DEBUG - Notified event "kernel.controller" to listener "Sensio\Bundle\FrameworkExtraBundle\EventListener\ParamConverterListener::onKernelController". 
DEBUG - Notified event "kernel.controller" to listener "Sensio\Bundle\FrameworkExtraBundle\EventListener\HttpCacheListener::onKernelController". 
DEBUG - Notified event "kernel.controller" to listener "Sensio\Bundle\FrameworkExtraBundle\EventListener\SecurityListener::onKernelController". 
DEBUG - Notified event "kernel.controller" to listener "Sensio\Bundle\FrameworkExtraBundle\EventListener\TemplateListener::onKernelController". 
CRITICAL - Uncaught PHP Exception RuntimeException: "The current field `company` is not linked to an admin. Please create one for the target entity : ``" at /var/www/symfony/vendor/sonata-project/doctrine-orm-admin-bundle/Builder/FormContractor.php line 132 
DEBUG - Notified event "kernel.request" to listener "Symfony\Component\HttpKernel\EventListener\DebugHandlersListener::configure". 
DEBUG - Notified event "kernel.request" to listener "Symfony\Component\HttpKernel\EventListener\DumpListener::configure". 
DEBUG - Notified event "kernel.request" to listener "Symfony\Component\HttpKernel\EventListener\ValidateRequestListener::onKernelRequest". 
DEBUG - Notified event "kernel.request" to listener "Symfony\Bundle\FrameworkBundle\EventListener\SessionListener::onKernelRequest". 
DEBUG - Notified event "kernel.request" to listener "Symfony\Component\HttpKernel\EventListener\FragmentListener::onKernelRequest".
DEBUG - Notified event "kernel.request" to listener "Symfony\Component\HttpKernel\EventListener\RouterListener::onKernelRequest". 
DEBUG - Notified event "kernel.request" to listener "Symfony\Component\HttpKernel\EventListener\LocaleListener::onKernelRequest". 
DEBUG - Notified event "kernel.request" to listener "Symfony\Component\HttpKernel\EventListener\TranslatorListener::onKernelRequest". 
DEBUG - Notified event "kernel.request" to listener "Symfony\Component\Security\Http\Firewall::onKernelRequest". 
DEBUG - Notified event "kernel.request" to listener "Knp\Bundle\MenuBundle\EventListener\VoterInitializerListener::onKernelRequest". 
DEBUG - Notified event "kernel.controller" to listener "Symfony\Bundle\FrameworkBundle\DataCollector\RouterDataCollector::onKernelController". 
DEBUG - Notified event "kernel.controller" to listener "Symfony\Component\HttpKernel\DataCollector\RequestDataCollector::onKernelController". 
DEBUG - Notified event "kernel.controller" to listener "Sensio\Bundle\FrameworkExtraBundle\EventListener\ControllerListener::onKernelController". 
DEBUG - Notified event "kernel.controller" to listener "Sensio\Bundle\FrameworkExtraBundle\EventListener\ParamConverterListener::onKernelController". 
DEBUG - Notified event "kernel.controller" to listener "Sensio\Bundle\FrameworkExtraBundle\EventListener\HttpCacheListener::onKernelController". 
DEBUG - Notified event "kernel.controller" to listener "Sensio\Bundle\FrameworkExtraBundle\EventListener\SecurityListener::onKernelController". 
DEBUG - Notified event "kernel.controller" to listener "Sensio\Bundle\FrameworkExtraBundle\EventListener\TemplateListener::onKernelController". 

Plain text :

[1] RuntimeException: The current field `company` is not linked to an admin. Please create one for the target entity : ``
    at n/a
        in /var/www/symfony/vendor/sonata-project/doctrine-orm-admin-bundle/Builder/FormContractor.php line 132

    at Sonata\DoctrineORMAdminBundle\Builder\FormContractor->getDefaultOptions('sonata_type_admin', object(FieldDescription))
        in /var/www/symfony/var/cache/dev/classes.php line 13178

    at Sonata\AdminBundle\Form\FormMapper->add('company', 'sonata_type_admin', array('required' => true, 'btn_add' => false, 'btn_delete' => false), array('admin_code' => 'thecamp_user.admin.company'))
        in /var/www/symfony/src/Thecamp/UserBundle/Admin/ContactAdmin.php line 213

    at Thecamp\UserBundle\Admin\ContactAdmin->configureFormFields(object(FormMapper))
        in /var/www/symfony/var/cache/dev/classes.php line 9806

    at Sonata\AdminBundle\Admin\AbstractAdmin->defineFormBuilder(object(FormBuilder))
        in /var/www/symfony/var/cache/dev/classes.php line 9800

    at Sonata\AdminBundle\Admin\AbstractAdmin->getFormBuilder()
        in /var/www/symfony/var/cache/dev/classes.php line 10731

    at Sonata\AdminBundle\Admin\AbstractAdmin->buildForm()
        in /var/www/symfony/var/cache/dev/classes.php line 9839

    at Sonata\AdminBundle\Admin\AbstractAdmin->getForm()
        in /var/www/symfony/vendor/sonata-project/admin-bundle/Controller/CRUDController.php line 499

    at Sonata\AdminBundle\Controller\CRUDController->createAction()
        in  line 

    at call_user_func_array(array(object(ContactAdminController), 'createAction'), array())
        in /var/www/symfony/vendor/symfony/symfony/src/Symfony/Component/HttpKernel/HttpKernel.php line 144

    at Symfony\Component\HttpKernel\HttpKernel->handleRaw(object(Request), '1')
        in /var/www/symfony/vendor/symfony/symfony/src/Symfony/Component/HttpKernel/HttpKernel.php line 64

    at Symfony\Component\HttpKernel\HttpKernel->handle(object(Request), '1', true)
        in /var/www/symfony/vendor/symfony/symfony/src/Symfony/Component/HttpKernel/Kernel.php line 177

    at Symfony\Component\HttpKernel\Kernel->handle(object(Request))
        in /var/www/symfony/web/app_dev.php line 30

I think you should debug this method, it is responsible for doing this link I think.

Thanks I'm gonna check it out

It seems that the method attachAdminClass is not called during the process

This sounds oddly familiar… are you using the latest version of the doctrine orm admin bundle ?

Yes I have the latest stable version :
sonata-project/doctrine-orm-admin-bundle 3.0.5

Thanks.
In the case of the company field the method getMappingTypereturns NULL instead of ClassMetadataInfo::MANY_TO_ONE's value

Where/when is the mappingType supposed to be set?

I have no idea, I can't find any calls to the method setMappingType in my bundles

I've switched to sonata-project/doctrine-orm-admin-bundle dev-master 3bc573b, now I have a different error :

You are trying to add sonata_type_admin field company which is not One-To-One or Many-To-One. Maybe you want sonata_model_list instead?

Huh… interesting.

Anyway, dev-master is future Sonata 4, so… don't use it. If you want to try something, try 3.x instead.

Also, the error message makes a lot of sense, doesn't it? or does it? Isn't your relation many to one?

I'm trying 3.x-dev f7e221d, same error message than dev-master.
Well the error message would make sense if I hadn't a @ORM\ManyToOnerelationship to the field company...

Yes I got confused. Can you try the \Exception trick? It should get you a stack trace showing where setMappingType is supposed to be called.

Found it at https://github.com/sonata-project/SonataDoctrineORMAdminBundle/blob/3.x/Model/ModelManager.php#L142
The weird part is that company field is not in Doctrine\ORM\Mapping\ClassMetadata associationMappings array nor in fieldMappings array.
I'm starting to think It might be a Doctrine Issue...

Uuuuh this is setFieldMapping, not setMappingType.

Wooops my bad, I'm getting tired.

Exception in method setMappingType in BaseFieldDescription is never thrown even after I've emptied cache.

Exception in method setMappingType in BaseFieldDescription is never thrown even after I've emptied cache.

Even when going on another form with a relation that works?

Indeed

Currently I'm using SF EntityType field, which is working fine

$formMapper->add('company', 'entity', array(
    'class'        => 'ThecampUserBundle:Company',
    'expanded'     => false,
    'required'     => true,
    'placeholder'  => $container->get('translator')->trans('Choose a company', array(), 'ThecampModelAdmin'),
))

But I'd rather use sonata_type_admin in order to have the add/delete buttons.

I have a project with Sonata 2 and sonata_type_admin. I'm currently migrating it to php7 but I should be done soon. I'll try the exception trick if you haven't found anything until then.

Thanks for your help anyway @greg0ire

For information, the exact same issue occurs with sonata_type_model_autocomplete, sonata_type_collection in a create form. But when editing an existing entity, sonata_type_admin works fine, and the others two (sonata_type_model_autocomplete, sonata_type_collection) give different errors.

Ok so I tried on a form where I have this, and no setMappingType call whatsoever.

But the mapping type is not null in my case…

It is set by calling Sonata\DoctrineORMAdminBundle\Admin\FieldDescription::setAssociationMapping()

Which should happen here in your case. This is what you need to debug.

Weird, cause $metadata->associationMappings is empty in my case...

Can you dump the whole $metadata (remove all fields but company before doing that, it should help your debugging, let's not get confused with other fields)?

Realy weird : when I dump $metadata from a contact create form this is not my Contact entity but my User entity metadata... which is not related to Contact entity at all

Is your ContactAdmin associated with the right class?

Shame on me !!! I forgot an old statement in configureFormFields when I had inheritance from User entity :

if (!$subject->getId()) {
    $user = $userManager->createUser();
    $this->setSubject($user);
}

Of course sonata_type_admin and sonata_type_model seems to work much better now...
Thanks @greg0ire to point me in the right direction. Sorry for wasted your time mate.

Sorry for wasted your time mate.

If you want to repay me, make a PR that checks the type of $subject against $this->class ;) Should be very very easy.

That would have save my day indeed, I'll look into it.

Was this page helpful?
0 / 5 - 0 ratings