简体   繁体   中英

How to properly set referring entity property when creating sub entity in Sonata Admin Bundle using sonata_type_model field

I feel like I'm missing something simple here...TLDR: using sonata_type_model field, which uses modal when adding new sub entities to a parent, how do I pass the parent to the sub entity to add it to the sub entity's reference field?

#

I have two entities at play, "User" and "Role" entities.

User -> OneToMany -> Role.

I'm trying to figure out how to create, edit, and delete roles from a user's Sonata Admin Bundle page.

In my UserAdmin class, I've configured the form fields like so:

$formmapper->add('roles', 'sonata_type_model', array(
                'required' => false,
                'btn_delete' => true,
                'btn_list' => true,
                'multiple' => true,
                'btn_add' => true,
            ))

Existing roles show up fine. If I click the "add" button under the field of roles the Modal window appears with the fields from my "role" admin form. My problem is that when I save the new Role it does not properly reference the User on which it was created. I don't know how to pass the parent USER entity to the child ROLE entity! This should be simple but. I cannot find this answer anywhere

If you want one User can have many roles ('multiple => true' option in your class), and role can be used by many users, you should prefer a ManyToMany relationship.

Use something like this for replace your actual OneToMany :

//Entity\User   

/**
* @ORM\ManyToMany(targetEntity="Role", mappedBy="users", cascade={"persist"})
*/
protected $roles;

And in your child entity :

//Entity\Role

/**
* @ORM\ManyToMany(targetEntity="User", inversedBy="roles", cascade={"persist", "remove"})
* @ORM\JoinTable(name="users_roles",
*     joinColumns={@ORM\JoinColumn(name="role_id", referencedColumnName="id")},
*     inverseJoinColumns={@ORM\JoinColumn(name="user_id", referencedColumnName="id")}
* )     *
* @var ArrayCollection $users
*/
protected $users;

Your parent entity (User) should have methods addRole(), removeRole() and getRole(). Else, you should do php app/console doctrine:generate:entities

If it's good, you have to edit your addRole() and removeRole() methods.

She must be like this :

public function addRole(\Namespace\Bundle\Entity\Role $roles)
{
     $this->roles[] = $roles;
     $roles->addUser($this);

     return $this;
}

public function removeRole(\Namespace\Bundle\Entity\Role $roles)
{
    $this->roles->removeElement($roles);
    $roles->removeUser($this);
}

Then, your addRole should work in Sonata

I don't think this is the intended way to solve this problem, but needing to set the "user" entity on the "role" entity form that opens in an modal window when editing the User entity was achieved by using the jQuery ajaxComplete() function to listen for ajax windows opening, checking to see if it was the right one, grabbing the User ID from the page URL, and setting that ID in the hidden form element

jQuery(document).ready(function() {
    $(document).ajaxComplete(function (event, request, settings) {
        if (settings.url.indexOf('/your-entity-admin-path-') >= 0){
            var pathArray = window.location.pathname.split( '/' );
            $('.modal-body .box-body input[type=hidden]').val(pathArray[3]);
        }
    });
});

A nasty solution but sometimes we just need things to work...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM