0
votes

I'm using sonata admin bundle and want to save multiple records against one entity. for example; I have three fields in my Entity (id, project, issues). suppose that a project has number of issues, I'm using multiple selection for the issues field, issues has ManyToOne relation with Issue entity, project has ManyToOne relation with Project entity, i expecting prject_issues table something like this after save,

id | project| issues
--------------------
 1 |    2   |   23
 2 |    2   |   78
 3 |    2   |   45
 4 |    2   |   64

I'm very new to sonata admin and symfony2, how could I achieve this?

2

2 Answers

2
votes

Create three entities: Project, Issue and ProjectIssue. Create three admin classes for each of the entities. Create Doctrine @ORM\OneToMany(targetEntity="ProjectIssue", mappedBy="project", cascade={"persist"}, orphanRemoval=true) relation in Project. Create two ManyToOne relations from ProjectIssue to Project and to Issue. Use app/console doctrine:generate:entities command to generate correct setters and getters for one-to-many relation. Remember to add $projectIssues->setProject($this); in Project::addProjectIssue($projectIssues) method. Finally, do ->add('issues', 'sonata_type_collection', array('by_reference' => null), array('edit' => 'inline','inline' => 'table')) in ProjectAdmin, and ->add('issue') in ProjectIssueAdmin.

This will get you close to solution. Remember to define __toString() methods in your entities.

1
votes

You've to create (at least) two entities, lets name them Project and Issue, Project should be set up to have relationship OneToMany with Issue.
Having done that you should create admin classes for both entities and set them up according to SonataAdmin documentation. If you want only one of them to be directly accessible you might add show_in_dashboard set on false argument in service definition.
Next you'll wish to add this in your ProjectAdmin

protected function configureFormFields(FormMapper $formMapper)
{
   $formMapper
       ->add('issues', 'sonata_type_collection', ['by_reference' => null], 
               ['edit' => 'inline','inline' => 'table']
       )
}

You should be able to find reasons why by_refference and other arguments are set up like this in SonataAdmin docs.
If the above snippet does not work try adding admin_code pointing on the IssueAdmin service in the last argument.