Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
576 views
in Technique[技术] by (71.8m points)

symfony - Symfony2 Doctrine2 Many To Many Form not Saving Entities

I am having some trouble with a many to many relationship. I have Users and Assets. I would like to be able to assign users to an asset on the asset page.

The code below displays a list of users when creating/editing an asset, however changes made to the user checkboxes do not save, while the rest of the data is persisted.

If I add an entry to users_assets through the mysql client, these changes are shown in the asset list.

User

class User extends BaseUser
{
    /**
     * @ORMManyToMany(targetEntity="Asset", inversedBy="users")
     */
    private $assets;
}

Asset

class Asset
{
    /**
     * @ORMManyToMany(targetEntity="User", mappedBy="assets")
     */
    private $users;
}

AssetType

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $form = $builder
        ->add('users', null, array(
            'expanded' => true,
            'multiple' => true
        ))
        ->getForm();

    return $form;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

For some reason I had to switch the doctrine mappings to get this to work:

Asset:
 /**
 * @ORMManyToMany(targetEntity="AdaptiveUserBundleEntityUser", inversedBy="assets")
 * @ORMJoinTable(name="user_assets")
 */
private $users;

User:
 /**
 * @ORMManyToMany(targetEntity="SplashSiteBundleEntityAsset", mappedBy="users")
 */
private $assets;

Now when I save the asset it saves the users associated. I did not need to define builder->add as an entity or collection. I simply pass it null and it uses the mapping info to fill in the entity info:

AssetType:
->add('users', null, array('expanded' => "true", "multiple" => "true"))

Not exactly sure why I needed to have the inversedBy and JoinTable info on the Asset vs The User but it seems to be working now!

Thanks For The Suggestions!!!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...