How to handle Doctrine relationships with Twig - symfony

I have two entities, Customers and Locations. They are in a ManyToOne relationship (one customer can have multiple locations).
This is how I defined the relationship:
class Customers {
/**
* #ORM\Column(type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #ORM\Column(type="string", length=45)
*/
private $name;
}
And the entity Locations:
class Locations {
/**
* #ORM\Column(type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #ORM\ManyToOne(targetEntity="Customers", inversedBy="id")
* #ORM\JoinColumn(name="customers_id", referencedColumnName="id")
*/
private $customers_id;
/**
* #ORM\Column(type="string", length=90)
*/
private $name;
}
I want to be able to click on a User and render in a Twig template all the locations associated to him. This is how I'm doing that now, but I'm not sure it's the proper way.
First the controller:
/**
* #Route("/showLocations/{id}", name = "show_locations")
* #Method("GET")
**/
public function showLocationsAction($id) {
$repository = $this->getDoctrine()->getRepository('AppBundle:Locations');
$locations = $repository->findBy(array('customer_id' => $id ));
$repository = $this->getDoctrine()->getRepository('AppBundle:Customers');
$customer = $repository->findOneById($id);
if(!empty($locations)) {
return $this->render("AppBundle:Default:showLocations.html.twig", array('locations' => $locations, 'customer' => $customer)); }
else return new Response ("There are no locations to show");
}
This is the twig template:
<p>Locations associated with {{customer.name}}</p>
<table id="table_id" class="display">
<thead>
<tr>
<th>Locations</th>
</tr>
</thead>
<tbody>
{% for locations in locations %}
<tr>
<td>{{ locations.name|e }}</td>
</tr>
{% endfor %}
</tbody>
Any suggestion? Thanks!

Looks fine so far. But naming for $customers_id should be $customer only since Doctrine will automatically fetch the related customer and hydrate it into an object.
Then you can fetch and display the customer with {{ location.customer.name }}
$repository = $this->getDoctrine()->getRepository('AtlasBundle:Customers');
$customer = $repository->findOneById($id);
Can be omitted totally then.

Related

I get myself as friend when executing method un repository

I am checking for friends that has accepted my friend request and thus are my real friends. But when displaying my friends I get myself as friend and not the person I have for friend sometimes. This appears when for example my id is second in the table.
I have tried checking if the userid is in either of the columns. Also tried with having two way friendship like A friend with B but B friend with A too. I couldnt get the repository work for the second method so I sticked to this one.
My repository:
public function personalFriends($userId){
$em = $this->getEntityManager();
$result = $em->createQuery('SELECT friends FROM AppBundle\Entity\Friends friends
INNER JOIN AppBundle\Entity\User myuser WHERE (friends.friendsWithMe = :userId OR friends.afriendof = :userId) AND friends.friends = 1');
$result->setParameter('userId', $userId);
return $result->getResult();
}
My controller:
public function indexAction(Request $request)
{
$user = $this->get('security.token_storage')->getToken()->getUser();
$userId = $user->getId();
$posts = $this->getDoctrine()->getRepository(UserPosts::class)->findUserPosts($userId,1);
$friends = $this->getDoctrine()->getRepository(Friends::class)->personalFriends($userId);
return $this->render('default/index.html.twig',
['formed' => null,
'posts' => $posts,
'posted'=>null,
'search' => null,
'friends' => $friends
]);
}
My view :
<div class="card card-body">
{{ app.user.username|capitalize }}'s friends:
{% if friends %}
<div>
{% for friend in friends %}
{{ friend.afriendof.username }}
{% endfor %}
</div>
{% else %}
<div>
You have no friends.
</div>
{% endif %}
</div>
Friends Entity:
class Friends
{
/**
* #ORM\Id()
* #ORM\ManyToOne(targetEntity="AppBundle\Entity\User", inversedBy="myfriends", fetch="EAGER")
* #ORM\JoinColumn(name="user_id", referencedColumnName="id", nullable=false)
*/
private $friendsWithMe;
/**
* #ORM\Id()
* #ORM\ManyToOne(targetEntity="AppBundle\Entity\User", inversedBy="friendof", fetch="EAGER")
* #ORM\JoinColumn(name="friend_id", referencedColumnName="id", nullable=false)
*/
private $afriendof;
/**
* #var integer
*
* #ORM\Column(name="request_sent", type="smallint")
*/
private $requestSent;
/**
* #var integer
*
* #ORM\Column(name="friends", type="smallint")
*/
private $friends;
I want to get only the friends and not myself. I get that I have to change the friend.afriendof.username with friend.friendswithme.username, but how to know when to change between those two.

how to send click a button and submit the students details in the database in symfony

I am doing a symfony final year project at Kyambogo university in Uganda for clearing students within different departments.
I want to be clicking a button and clearing students.
I want this button to submit details of the student which are rendered in the table from entity Student to be
submited to another entity ClearedData
even if you dont do it exactly using my example and you just show me how you could do it using your own example I will be very glad
because all I need to get a way of how I can start on it.
This is my code for the table and the clear button that submits is the one I want to be clicking and sending this data to the database
{% extends 'base.html.twig' %}
{% block body %}
<div class="box table-responsive">
<div class="box-header">
<h1 class="box-title">Student List</h1>
</div>
<!-- box-header -->
<div class="box-body">
<table id="example1" class="table table-striped">
<thead>
<tr>
<th>ID</th>
<th>First Name</th>
<th>Last Name</th>
<th>Registration No.</th>
<th>Gender</th>
<th>Year Of Study</th>
<th>Status</th>
<th>Actions</th>
</tr>
</thead>
{% for student in students %}
<tr>
<td>{{ student.id }}</td>
<td>{{ student.firstName }}</td>
<td>{{ student.lastName }}</td>
<td>{{ student.regNo }}</td>
<td>{{ student.gender }}</td>
<td>{{ student.yearOfStudy }}</td>
<td>Cleared/Not Cleared</td>
<td><input type="submit" value="Clear" class="btn btn-xs btn-facebook"></td>
</tr>
{% endfor %}
<tfoot>
</tfoot>
</table>
</div>
<!-- /.box-body -->
</div>
{% endblock %}
this is the entity class where i want to be submitting the form
<?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* ClearedData
*
* #ORM\Table(name="cleared_data")
* #ORM\Entity(repositoryClass="AppBundle\Repository \ClearedDataRepository")
* #ORM\HasLifecycleCallbacks()
*/
class ClearedData
{
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="regNo", type="string", length=255)
*/
private $regNo;
/**
* #var string
*
* #ORM\Column(name="department", type="string", length=255)
*/
private $department;
/**
* #var string
*
* #ORM\Column(name="status", type="string", length=40)
*/
private $status;
/**
* #var \DateTime
*
* #ORM\Column(name="date", type="date")
*/
private $date;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set regNo
*
* #param string $regNo
* #return ClearedData
*/
public function setRegNo($regNo)
{
$this->regNo = $regNo;
return $this;
}
/**
* Get regNo
*
* #return string
*/
public function getRegNo()
{
return $this->regNo;
}
/**
* Set department
*
* #param string $department
* #return ClearedData
*/
public function setDepartment($department)
{
$this->department = $department;
return $this;
}
/**
* Get department
*
* #return string
*/
public function getDepartment()
{
return $this->department;
}
/**
* Set status
*
* #param string $status
* #return ClearedData
*/
public function setStatus($status)
{
$this->status = $status;
return $this;
}
/**
* Get status
*
* #return string
*/
public function getStatus()
{
return $this->status;
}
/**
* Set date
*#ORM\PrePersist
* #param \DateTime $date
* #return ClearedData
*/
public function setDate($date)
{
$this->date = new \DateTime();
return $this;
}
/**
* Get date
*
* #return \DateTime
*/
public function getDate()
{
return $this->date;
}
}
Change your input submit and make this :
Clear
Create a route for the path 'clear_student :
clear_student:
path: /student/clear/{idstudent}
defaults: {_controller: YourBundle:TheName:clearStudent}
And do your controller :
<?php
namespace YourBundle\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use YourBundle\Entity\ClearedData;
class TheNameController extends Controller
{
public function clearStudentAction(Request $request, $idstudent)
{
$em = $this->getDoctrine()->getManager();
$student = $em->getRepository('YourBundle:Student')->findOneById($idstudent);
(here apply like you want the necessary value of your clearedStudent)
$clearedStudent = new ClearedData();
$clearedStudent->setRegNo($student->getRegNo());
$clearedStudent->setDepartment();
$clearedStudent->setStatus();
$clearedStudent->setDate();
$em->persist(clearedStudent);
$em->flush();
If needed delete the student :
$em->remove($student);
$em->flush();
and return to the URL you want like target :
return $this->render('default/targetPage.html.twig', array(
'example' => $example, //If you have some data to send to the targetPage
));
}
}
I hope it's gonna help you, but i don't understand you haven't form -> so donc need submit button. And you have some needed value in you ClearedStudent that doesn't appears in the student. So i hope it's will help you :) good luck
WARNING : i recommanded you to update your two entity for make them match -> if the goals it's to deplace one to the other you need to have the same needed field.

NestedTree Symfony2 Gedmo annotation show list with Tree

i have a simple probleme but i dont know how to fix it,
Here we go,
I already have a table that contains all menu registred on database, like this
http://snapplr.com/snap/hbch
But, the entity with title A is parent of entity B, so all i want to do now is to tree my list as dependencies with parent and children Tree Gedmo annotation.
this is my index.html.twig page
{% block tbody %}
{% for entity in entities %}
<tr>
<td>{{ entity.title|title }}</td>
<td>{% if entity.type == 'javascript:void(0)' %}
Groupe
{% else %}
{{ entity.type|title }}
{% endif %}</td>
<td>{{ entity.value|title }}</td>
<td>
{% render(controller('MenuBundle:Backend/MenuExtends:createDelete', {'id' : entity.id, 'menu' : id})) %}
</td>
</tr>
{% endfor %}
{% endblock %}
Ok
here my entity
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #ORM\ManyToOne(targetEntity="Menu", inversedBy="extends")
*/
private $menu;
/**
* #var string
* #Gedmo\TreePathSource
* #ORM\Column(name="type", type="string", length=255, nullable=false)
*/
private $type;
/**
* #var string
* #ORM\Column(name="value", type="string", length=255, nullable=false)
*/
private $value;
/**
* #Gedmo\TreeLeft
* #ORM\Column(name="submenu_left", type="integer")
*/
private $lft;
/**
* #Gedmo\TreeRoot
* #ORM\Column(name="submenu_root", type="integer", nullable=true)
*/
private $root;
/**
* #Gedmo\TreeLevel
* #ORM\Column(name="submenu_level", type="integer")
*/
private $lvl;
/**
* #Gedmo\TreeRight
* #ORM\Column(name="submenu_right", type="integer")
*/
private $rgt;
/**
* #Gedmo\TreeParent
* #ORM\ManyToOne(targetEntity="MenuExtends", inversedBy="children")
* #ORM\JoinColumn(name="parent_id", referencedColumnName="id", onDelete="CASCADE")
*/
private $parent;
/**
* #ORM\OneToMany(targetEntity="MenuExtends", mappedBy="parent")
* #ORM\OrderBy({"lft" = "ASC"})
*/
private $children;
what i want to do is :
if an entity have a children, in the same line , open x lines for the x children ...

How to make retrieve data from another controller Symfony2

I'm new with Symfony2 and I have a question that I could not fully solve by myself. I'm programming an application and use the tables client and project. Every project has one client and every client can have multiple projects.
The autonomous display of clients- and projectstables does already work, but I also have to display the projects in the frontend of clients. I already tried multiple ways to do so but I did not have any success so far.
Could you tell me what I have to put in my ClientController-, config.yml and routing.yml-File in order to display the projecttables in the show.html.twig file of client?
I thank you in advance for your answer
Url: http://dev.pingag.ch/Symfony/web/app_dev.php/clients/
ClientController.php
namespace Acme\KeywordBundle\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Acme\KeywordBundle\Entity\Client;
use Acme\KeywordBundle\Entity\Project;
use Acme\KeywordBundle\Form\ClientType;
/**
* Client controller.
*
* #Route("/clients")
*/
class ClientController extends Controller
{
/**
* Lists all Client entities.
*
* #Route("/", name="clients")
* #Method("GET")
* #Template()
*/
public function indexAction()
{
$em = $this->getDoctrine()->getManager();
$entities = $em->getRepository('AcmeKeywordBundle:Client')->findAll();
return array(
'entities' => $entities,
);
}
...
...
...
}
config.yml
imports:
- { resource: parameters.yml }
- { resource: security.yml }
...
...
...
routing.yml
acme_keyword:
resource: "#AcmeKeywordBundle/Controller"
type: annotation
client.php
<?php
namespace Acme\KeywordBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
use Symfony\Component\Validator\Constraints as Assert;
/**
* Client
*
* #ORM\Table()
* #ORM\Entity
*/
class client
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer", nullable=true)
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
// Anfang Kopiert von Anleitung
/**
* #ORM\OneToMany(targetEntity="Project", mappedBy="client")
*/
protected $projects;
/**
* #ORM\OneToMany(targetEntity="File", mappedBy="client")
*/
protected $files;
/**
* #ORM\OneToMany(targetEntity="Contact", mappedBy="client")
*/
protected $contacts;
public function __construct()
{
$this->projects = new ArrayCollection();
$this->files = new ArrayCollection();
$this->contacts = new ArrayCollection();
}
// Ende Kopiert von Anleitung
/**
* #var string
*
* #ORM\Column(name="name", type="string", length=255, nullable=true)
* #Assert\NotBlank()
*/
private $name;
/**
* #var \DateTime
*
* #ORM\Column(name="createdAt", type="datetime", nullable=true)
*/
private $createdAt;
/**
* #var \DateTime
*
* #ORM\Column(name="updatedAt", type="datetime", nullable=true)
*/
private $updatedAt;
/**
* #var string
*
* #ORM\Column(name="logoFileName", type="string", length=255, nullable=true)
*/
private $logoFileName;
/**
* #var string
*
* #ORM\Column(name="logoContentType", type="string", length=255, nullable=true)
*/
private $logoContentType;
/**
* #var integer
*
* #ORM\Column(name="logoFileSize", type="integer", nullable=true)
*/
private $logoFileSize;
/**
* #var \DateTime
*
* #ORM\Column(name="logoUpdatedAt", type="datetime", nullable=true)
*/
private $logoUpdatedAt;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set name
*
* #param string $name
* #return Client
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* Set createtAt
*
* #param \DateTime $createtAt
* #return Client
*/
public function setCreatetAt($createtAt)
{
$this->createtAt = $createtAt;
return $this;
}
/**
* Get createtAt
*
* #return \DateTime
*/
public function getCreatetAt()
{
return $this->createtAt;
}
/**
* Set updatetAt
*
* #param \DateTime $updatetAt
* #return Client
*/
public function setUpdatetAt($updatetAt)
{
$this->updatetAt = $updatetAt;
return $this;
}
/**
* Get updatetAt
*
* #return \DateTime
*/
public function getUpdatetAt()
{
return $this->updatetAt;
}
/**
* Set logoFileName
*
* #param string $logoFileName
* #return Client
*/
public function setLogoFileName($logoFileName)
{
$this->logoFileName = $logoFileName;
return $this;
}
/**
* Get logoFileName
*
* #return string
*/
public function getLogoFileName()
{
return $this->logoFileName;
}
/**
* Set logoContentType
*
* #param string $logoContentType
* #return Client
*/
public function setLogoContentType($logoContentType)
{
$this->logoContentType = $logoContentType;
return $this;
}
/**
* Get logoContentType
*
* #return string
*/
public function getLogoContentType()
{
return $this->logoContentType;
}
/**
* Set logoFileSize
*
* #param integer $logoFileSize
* #return Client
*/
public function setLogoFileSize($logoFileSize)
{
$this->logoFileSize = $logoFileSize;
return $this;
}
/**
* Get logoFileSize
*
* #return integer
*/
public function getLogoFileSize()
{
return $this->logoFileSize;
}
/**
* Set logoUpdatedAt
*
* #param \DateTime $logoUpdatedAt
* #return Client
*/
public function setLogoUpdatedAt($logoUpdatedAt)
{
$this->logoUpdatedAt = $logoUpdatedAt;
return $this;
}
/**
* Get logoUpdatedAt
*
* #return \DateTime
*/
public function getLogoUpdatedAt()
{
return $this->logoUpdatedAt;
}
/**
* Set createdAt
*
* #param \DateTime $createdAt
* #return Client
*/
public function setCreatedAt($createdAt)
{
$this->createdAt = $createdAt;
return $this;
}
/**
* Get createdAt
*
* #return \DateTime
*/
public function getCreatedAt()
{
return $this->createdAt;
}
/**
* Set updatedAt
*
* #param \DateTime $updatedAt
* #return Client
*/
public function setUpdatedAt($updatedAt)
{
$this->updatedAt = $updatedAt;
return $this;
}
/**
* Get updatedAt
*
* #return \DateTime
*/
public function getUpdatedAt()
{
return $this->updatedAt;
}
/**
* Add projects
*
* #param \Acme\KeywordBundle\Entity\Project $projects
* #return Client
*/
public function addProject(\Acme\KeywordBundle\Entity\Project $projects)
{
$this->projects[] = $projects;
return $this;
}
/**
* Remove projects
*
* #param \Acme\KeywordBundle\Entity\Project $projects
*/
public function removeProject(\Acme\KeywordBundle\Entity\Project $projects)
{
$this->projects->removeElement($projects);
}
/**
* Get projects
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getProjects()
{
return $this->projects;
}
/**
* Add files
*
* #param \Acme\KeywordBundle\Entity\File $files
* #return Client
*/
public function addFile(\Acme\KeywordBundle\Entity\File $files)
{
$this->files[] = $files;
return $this;
}
/**
* Remove files
*
* #param \Acme\KeywordBundle\Entity\File $files
*/
public function removeFile(\Acme\KeywordBundle\Entity\File $files)
{
$this->files->removeElement($files);
}
/**
* Get files
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getFiles()
{
return $this->files;
}
/**
* Add contacts
*
* #param \Acme\KeywordBundle\Entity\Contact $contacts
* #return Client
*/
public function addContact(\Acme\KeywordBundle\Entity\Contact $contacts)
{
$this->contacts[] = $contacts;
return $this;
}
/**
* Remove contacts
*
* #param \Acme\KeywordBundle\Entity\Contact $contacts
*/
public function removeContact(\Acme\KeywordBundle\Entity\Contact $contacts)
{
$this->contacts->removeElement($contacts);
}
/**
* Get contacts
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getContacts()
{
return $this->contacts;
}
public function __toString()
{
return $this->name;
}
}
show.html.twig of the cliententity
the project list should schow up under Project list
{% extends '::base.html.twig' %}
{% block body -%}
<h1>Client</h1>
<table class="record_properties">
<tbody>
<!--
<tr>
<th>Id</th>
<td>{{ entity.id }}</td>
</tr>
<tr>
-->
<th>Name</th>
<td>{{ entity.name }}</td>
</tr>
<tr>
<!--
<th>Createdat</th>
<td>{{ entity.createdAt|date('Y-m-d H:i:s') }}</td>
</tr>
<tr>
<th>Updatedat</th>
<td>{{ entity.updatedAt|date('Y-m-d H:i:s') }}</td>
</tr>
<tr>
<th>Logofilename</th>
<td>{{ entity.logoFileName }}</td>
</tr>
<tr>
<th>Logocontenttype</th>
<td>{{ entity.logoContentType }}</td>
</tr>
<tr>
<th>Logofilesize</th>
<td>{{ entity.logoFileSize }}</td>
</tr>
<tr>
<th>Logoupdatedat</th>
<td>{{ entity.logoUpdatedAt|date('Y-m-d H:i:s') }}</td>
</tr>
-->
</tbody>
</table>
<ul class="record_actions">
<li>
<a href="{{ path('clients') }}">
Back to the list
</a>
</li>
<li>
<a href="{{ path('clients_edit', { 'id': entity.id }) }}">
Edit
</a>
</li>
<li>{{ form(delete_form) }}</li>
</ul>
<h1>Project list</h1>
{% endblock %}
If your entity relations are configured correctly (what they seem to be), then you can acces the projects array direclty in twig:
{% for project in entity.projects %}
Name: {{ project.name }}
...
{% endfor %}

Symfony2 Doctrine2 trouble with optional one to many relation

I have a problem with Doctrine2 and two relationed entities.
There is a user-entity that can (not must) have one or a collection of social-entity referenced which contains a social network link.
I do not control Doctrine and I'm still learning relationship.
I want to add a user with/without adding social network link.
After several researches and testing, I am still unable to find a solution.
Here is my user-entity
<?php
//...
/**
* User
*
* #ORM\Table(name="admin_users")
* #ORM\Entity(repositoryClass="UserRepository")
* #ORM\HasLifecycleCallbacks()
*/
class User implements AdvancedUserInterface, \Serializable
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="username", type="string", length=25, unique=true)
*/
private $username;
/**
* #var string
*
* #ORM\Column(name="password", type="string", length=40)
*/
private $password;
/**
*
* #var string
*
* #Assert\NotBlank
*/
private $plainPassword;
//...
/**
* #var ArrayCollection
*
* #ORM\OneToMany(targetEntity="Social", mappedBy="user", cascade={"persist","remove"})
* #ORM\JoinColumn(nullable=true)
*/
private $socials;
public function __construct()
{
$this->socials = new ArrayCollection();
}
//Some getters setters
/**
* Add socials
*
* #param Social $socials
* #return User
*/
public function addSocials(Social $socials)
{
$this->socials[] = $socials;
$socials->setUser($this);
return $this;
}
/**
* Remove socials
*
* #param Social $socials
*/
public function removeSocials(Social $socials)
{
$this->socials->removeElement($socials);
}
/**
* Get socials
*
* #return Collection
*/
public function getSocials()
{
return $this->socials;
}
}
Here is the social-entity
<?php
/**
* Social
*
* #ORM\Table(name="admin_social")
* #ORM\Entity(repositoryClass="SocialRepository")
*/
class Social
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="name", type="string", length=20, nullable=true)
*/
private $name;
/**
* #var string
*
* #ORM\Column(name="url", type="string", length=255, nullable=true)
*/
private $url;
/**
* #ORM\ManyToOne(targetEntity="User", inversedBy="socials", cascade={"persist","remove"})
* #ORM\JoinColumn(name="user_id", referencedColumnName="id", nullable=true)
*/
private $user;
//getters setters
/**
* Set user
*
* #param User $user
* #return Social
*/
public function setUser(User $user)
{
$this->user = $user;
return $this;
}
/**
* Get user
*
* #return User
*/
public function getUser()
{
return $this->user;
}
}
The userType code looks like this:
$builder
->add('username', 'text', array(
'attr'=> array('class' => 'span6',),
'label_attr' => array('class' => 'control-label'),
)
)
// ....
->add('sociaux', 'collection', array('type' => new SocialType(),
'allow_add' => true,
'allow_delete' => true,
'by_reference' => false,))
;
Finally the controller code :
public function addAction()
{
$user = new User;
// Create the form
$form = $this->createForm( new UserType, $user );
// Gets the request
$request = $this->getRequest();
// Checks if the request have type POST
if ( $request->getMethod() == 'POST' ) {
// Links the request and the form
$form->bind( $request );
// Checks if all input values are correct
if ( $form->isValid() ) {
// Save user object in database
$em = $this->getDoctrine()->getManager();
// Persist entity user
$em->persist( $user );
$em->flush();
//...
}
}
//...
}
When I try to add a user without social-entity I have no error, but in the database I have in social table a row with null values. Please help.
UPDATE
In user-entity I added this :
if( !( $socials->getName() === null && $socials->getUrl() === null ) )
{
$this->socials[] = $socials;
$socials->setUser($this);
}
Now there is no row inserted in social table, but when I try editing the user, I have two collection field (duplicated).
See the screenshot
Here my template file (Twig) :
<div class="widget-body">
{{ form_start(form, { 'action': path('acme_admin_edit_user', {'id': userId}), 'attr': {'class': 'form-horizontal'} }) }}
<div class="control-group">
{{ form_errors(form.username) }}
{{ form_label(form.username) }}
<div class="controls">
{{ form_widget(form.username) }}
</div>
</div>
<!-- ... -->
<div id="acme_adminbundle_useredittype_socials" data-prototype="{{ form_row(form.socials.vars.prototype) | escape }}">
{% for social in form.socials %}
<div>
<label class="required text-primary lead">Lien n°{{ loop.index }}</label>
<div id="acme_adminbundle_useredittype_socials_{{ loop.index0 }}">
<div class="control-group">
{{ form_errors(social.name) }}
{{ form_label(social.name) }}
<div class="controls">
{{ form_widget(social.name) }}
</div>
</div>
<div class="control-group">
{{ form_errors(social.url) }}
{{ form_label(social.url) }}
<div class="controls">
{{ form_widget(social.url) }}
</div>
</div>
</div>
</div>
{% endfor %}
</div>
<div class="txt-center well">
<input type="submit" class="auto-margin btn btn-primary btn-large" />
</div>
{{ form_end(form) }}
</div>
Try removing:
#ORM\JoinColumn(nullable=true)
from your User class. #JoinColumn should be defined only on one side of relationship and since Social entity contains name and referencedColumnName it is unnecessary inside the User.

Resources