I'm trying to add a User to the Item as it's owner
-
manually in the Controller by
$item->setOwner($this->getUser());
- in a ManyToOne-relation.
Everything defined in the FormType gets saved as it should but the owner_id
is NULL
. I don't get any error-message.
Any ideas? Code below.
Thanks in advance!
# src/myBundle/Controller/myController.php
class myController extends Controller {
public function myAction(Request $request) {
$item = new Item();
$item->setOwner($this->getUser());
// print_r($this->getUser()); <- prints a valid user
$form = $this->createForm(new ItemFormType(), $item);
if ($request->isMethod('POST')) {
$form->handleRequest($request);
if ($form->isValid()) {
$em = $this->get('doctrine.orm.default_entity_manager');
$em->persist($item); // saves everything but the owner
$em->flush();
}
}
return $this->render('myBundle:path/to:template.html.twig', array(
'form' => $form
)
}
}
-
# src/myBundle/Form/ItemFormType.php
class ItemFormType extends AbstractType {
public function buildForm(FormBuilderInterface $builder, array $options) {
$builder->add(...);
// ...
}
}
public function configureOptions(OptionsResolver $resolver) {
$resolver->setDefaults(array(
'data_class' => 'myBundle\Entity\Item'
));
}
public function getName() {
return 'myItemForm';
}
-
# src/myBundle/Entity/Item.php
class Item {
// ...
/**
* @ORM\ManyToOne(targetEntity="myBundle\Entity\User")
* @ORM\JoinColumn(name="owner_id", referencedColumnName="id")
*/
protected $owner;
// ...
// Getter & Setter
// ...
}
-
# src/myBundle/Entity/User.php
use FOS\UserBundle\Model\User as BaseUser;
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity
* @ORM\Table(name="fos_user")
*/
class User extends BaseUser {
/**
* @ORM\Id
* @ORM\Column(type="integer")
* @ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
public function __construct()
{
parent::__construct();
}
/**
* @return mixed
*/
public function getId()
{
return $this->id;
}
}