Date is not getting saved to mysql database - symfony

I'm trying to save a date (user's birthday).
$values['name'] = $request->get('name');
$values['fbid'] = $request->get('fbid');
$values['birthdate'] = date("Y-m-d", $request->get('birthdate'));
$em = $this->getDoctrine()->getEntityManager();
$user = new User();
$user->setName($values['name']);
$user->setFbId($values['fbid']);
$user->setBirthdate($values['birthdate']);
$em->persist($user);
$em->flush();
This is however not working. I'm not seeing any errors. What could be wrong? When I delete the setter for the birthday, the user gets inserted into the database perfectly.
Edit:
/**
* #ORM\Column(type="date", nullable=true)
*/
protected $birthdate;
/**
* Set date
*
* #param date $birthdate
*/
public function setBirthdate($birthdate)
{
$this->birthdate = $birthdate;
}

Try setting
$values['birthdate'] = date("Y-m-d", $request->get('birthdate'));
To
$dateTime = new \DateTime();
$values['birthdate'] = $dateTime->setTimestamp($request->get('birthdate'));
Or look into how you can create a DateTime to pass to doctrine

Related

Insert current DateTime manually in phpmyadmin using symfony

So i send the data to the controller using ajax and i want to insert it in the comment table; everything works fine if i delete these two lines about inserting current datetime for the comment and setting my entity nullable
but how can i insert current datetime ;
Controller Code
if($request->get('texte')==NULL)
{
throw new AccessDeniedException('This user does not have access
to this section.');
}
$user = $this->getUser();
if (!is_object($user) || !$user instanceof UserInterface)
{
throw new AccessDeniedException('This user does not have access
to this section.');
}
$comment = new Commentaire();
$em = $this->getDoctrine()->getManager();
$veterinaire=$em->getRepository("MyAppUserBundle:User")->findOneById($request->get('cible'));
$comment->setIdCible($veterinaire);
$comment->setIdClient($user);
$comment->setTexte($request->get('texte'));
$literalTime = \DateTime::createFromFormat("d/m/Y H:i",date_default_timezone_get());
$comment->setDate($literalTime);
$em->persist($comment);
$em->flush();
return new Response("");
}
My Entity :
/**
* #var \DateTime
*
* #ORM\Column(name="date", type="datetime", nullable=false)
*/
private $date;
I even tried to set my AppKernel __construct
public function __construct($environment, $debug)
{
date_default_timezone_set( 'Africa/Tunis' );
parent::__construct($environment, $debug);
}
You just need to pass a DateTime object to setDate:
$comment->setDate(new \DateTime());
or if you want to specify timezone:
$comment->setDate(new \DateTime('now', new \DateTimeZone('Africa/Tunis')));
Of course you can extract creation of DateTime object from the setDate and have additional variable to pass.

Saving information in controller symfony relation ManyToMany HELPPPPP

Hi I need to save information in my db, what I mean is, how to persist when the relationship is manytomany, I am doing like this but it doesn't work!...I will put some code of entity Menu.
/** Agrega nuevo menù
*
* #Route("/save", name="admin_menu_save")
* #Method({"GET", "POST"})
* #param Request $request
* #return Response
*/
public function saveAction(Request $request)
{
$em = $this->getDoctrine()->getManager();
$fecha_menu = $request->get('fecha');
$fecha_comprar = $request->get('fechacomprado');
$fecha_vencimiento = $request->get('fechavencimiento');
$alimentos = $request->get('select_alimentos');
$a = $em->getRepository('AdminBundle:Alimento')->findBy($alimentos);
$menu = new Menu();
$menu->setFecha(new \DateTime($fecha_menu));
$menu->setFechacomprar(new \DateTime($fecha_comprar));
$menu->setFechavence(new \DateTime($fecha_vencimiento));
$menu->setPrecio(6);
$menu->addAlimento($a);
$em->persist($menu);
$em->flush();
return new Response('Guardado OK');
}
//Menu Entity Definition (Just the necessary code):
/**
* #ORM\ManyToMany(targetEntity="Alimento", inversedBy="menu")
* #ORM\JoinTable(name="alimento_menu",
* joinColumns={
* #ORM\JoinColumn(name="menu_id", referencedColumnName="id")
* },
* inverseJoinColumns={
* #ORM\JoinColumn(name="alimento_id", referencedColumnName="id")
* }
* )
*/
private $alimento;
/**
* Constructor
*/
public function __construct()
{
$this->alimento = new ArrayCollection();
}
/**
* Add alimento
*
* #param \AdminBundle\Entity\Alimento $alimento
*
* #return Menu
*/
public function addAlimento(Alimento $alimento)
{
$this->alimento[] = $alimento;
return $this;
}
/**
* Remove alimento
*
* #param \AdminBundle\Entity\Alimento $alimento
*/
public function removeAlimento(Alimento $alimento)
{
$this->alimento->removeElement($alimento);
}
/**
* Get alimento
*
* #return ArrayCollection
*/
public function getAlimento()
{
return $this->alimento;
}
}
I have not experience working with manytomany relations, I hope to solve this problem, that´s show very good, but I don´t know how to save,edit or remove in that manytomany table!....
First, this bit seems weird.
$alimentos = $request->get('select_alimentos');
$a = $em->getRepository('AdminBundle:Alimento')->findBy($alimentos);
Doctrine findBy takes an array with the entity field as a key and the specific entity value as the value. Like this:
$em-getRepository('AdminBundle:Alimento')->findBy(['id' => $id]);
If that's how your $alimentos variable is structured, that's fine. It just looks strange.
If this is a bi-directional relationship, you have to update both entities. So your controller code is like:
$a = $em->getRepository('AdminBundle:Alimento')->findBy($alimentos);
$menu = new Menu();
// -- more code ---//
$menu->addAlimento($a);
$a->addMenu($menu);
$em->persist($menu);
$em->flush();
Check this documentation.
I just realized what was...This was my solution:
foreach ($alimentos as $item) {
$a = $em->getRepository('AdminBundle:Alimento')->find($item);
$menu->addAlimento($a);
}
And of course later I persist menu.

Doctrine #id null when persisted

The following works and a row in inserted into both tables:
$user = new User();
$user->setId(8484);
$user->setData("user test data");
$profile = new Profile();
$profile->setBlah(8484);
$profile->setData("profile test data");
// if I leave this out it works...
$user->setProfile($profile);
$em = $this->getDoctrine()->getEntityManager();
$em->persist($user);
$em->flush();
But if leave out $user->setProfile($profile); I get an error because User's id is null:
An exception occurred while executing 'INSERT INTO User (id, data) VALUES (?, ?)' with params {"1":null,"2":"user test data"}
How can it be?
class User
{
/**
* #ORM\Id
* #ORM\Column(type="integer")
*/
protected $id;
/**
* #ORM\Column(type="string", length=64)
*/
protected $data;
/**
* #ORM\OneToOne(targetEntity="Profile", cascade={"persist", "remove"})
* #ORM\JoinColumn(name="id", referencedColumnName="blah")
*/
protected $profile;
}
class Profile
{
/**
* #ORM\Id
* #ORM\Column(name="blah", type="integer")
*/
protected $blah;
/**
* #ORM\Column(type="string", length=64)
*/
protected $data;
}
Set Profile method:
/**
* Set Profile
*
* #param \Test\AdminBundle\Entity\Profile $profile
* #return User
*/
public function setProfile(\Test\AdminBundle\Entity\Profile $profile = null)
{
$this->profile = $profile;
return $this;
}
EDIT:
If I change the joinColumn name to something random my object looks right using a var_dump but the query fails:
/**
* #ORM\OneToOne(targetEntity="Profile", cascade={"persist"})
* #ORM\JoinColumn(name="random_test", referencedColumnName="blah")
*/
Gives:
An exception occurred while executing 'INSERT INTO User (id, data, random_test) VALUES (?, ?, ?)' with params {"1":8484,"2":"user test data","3":null}:
You need to have your $profile persisted before Doctrine can successfully make a relationship between your user and your profile.
$em = $this->getDoctrine()->getEntityManager();
$user = new User();
$user->setId(8484);
$user->setData("user test data");
$profile = new Profile();
$profile->setBlah(8484);
$profile->setData("profile test data");
$em->persist($profile);
$user->setProfile($profile);
$em->persist($user);
$em->flush();
Think about what you are trying to do in your code in MySQL.
Originally you were saying:
Insert a user who's profile will be (8484)
Which results in (Err: Profile 8484 doesn't exist).
What you want to say is:
Insert a profile (8484).
Insert a user who's profile is (8484).

Creating a new entity, and updating another at once

I've searched a lot about this, and seriously asking is my last resource, doctrine is kicking me hard.
I have an entity named "Contract" and another "Request", a Contract may have several Requests, when adding a new Request I search for an existent contract of that client and associate it if already exists or create it if not.
In RequestRepository.php:
public function findOrCreate($phone)
{
$em = $this->getEntityManager();
$contract = $this->findOneBy(array('phone' => $phone));
if($contract === null)
{
$contract = new Contract();
$contract->setPhone($phone)
->setDesDate(new \DateTime());
# save only if new
$em->persist($contract);
}
return $contract;
}
The thing is, when the contract is new it works ok, but when is "reused" from db I can't modify its attributes. I checked the OneToMany and ManyToOne already.
In Contract.php:
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
* #ORM\OneToMany(targetEntity="Request", mappedBy="contract")
*/
private $id;
In Request.php:
/**
* #var string
*
* #ORM\JoinColumn(nullable=false)
* #ORM\ManyToOne(targetEntity="Cid\FrontBundle\Entity\Contract", inversedBy="id", cascade={"persist"})
*/
protected $contract;
I also have a method which modifies an attribute within Contract.php:
public function addTime($months)
{
$days = $months * 30;
$this->des_date->add(new \DateInterval("P".$days."D"));
return $this;
}
I create the request and "findOrCreate" a contract, but if the later is not "fresh" the addTime does not save to db.
What am I doing wrong?
Edit: The controller is a common CRUD with minor modifications.
Don't worry about "request" name clash, the actual code is in spanish, Request = Solicitud
public function createAction(Request $req)
{
$entity = new Request();
$form = $this->createForm(new RequestType(), $entity);
$form->bind($req);
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$entity->setUser($this->getUser());
$data = $request->request->get('cid_frontbundle_requesttype');
$phone = $data['phone_number'];
$reqRep = $em->getRepository('FrontBundle:Request');
$entity = $reqRep->newRequest($entity, $phone);
return $this->redirect($this->generateUrl('request_show', array('id' => $entity->getId())));
}
return $this->render('FrontBundle:Request:new.html.twig', array(
'entity' => $entity,
'form' => $form->createView(),
));
}
The newRequest:
public function newRequest($request, $phone)
{
$em = $this->getEntityManager();
$contractRep = $em->getRepository('FrontBundle:Contract');
$contract = $contractRep->findOrCreate($phone);
$contract->addTime(123); # this is the problem, I use var_dump and this method works, but doesn't persists
$em->persist($request);
$em->flush();
return $request;
}
Eureka!! The issue was that doctrine seems to check the objects by reference, and all I did with the contract was adding a DateInterval to a DateTime property, so the object was the same for doctrine's matter and there was no saving. This is the code that made it.
public function addTime($months)
{
$days = $months * 30; # I know DateInterval has months but this is company policy ;)
$other = new \DateTime($this->des_date->format('Y-m-d')); # creating a brand new DateTime did the trick
$other->add(new \DateInterval("P".$days."D"));
$this->des_date = $other;
return $this;
}
Thanks for everything #cheesemacfly.

Save Object in table related to another

How can I create a new object when a cell is related to another table? In my case there exist a table with states, like id=1,state=active;id=2,state=inactive.
My Entity/States.php
class States
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer", nullable=false)
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;
....
Entity/User.php
....
/**
* Set state
*
* #param \Frontend\AccountBundle\Entity\States $state
* #return User
*/
public function setState(\Frontend\AccountBundle\Entity\States $state = null)
{
$this->state = $state;
return $this;
}
My AccountController:
....
$user = new User();
$em = $this->get('doctrine')->getEntityManager();
$state = $this->getDoctrine()->getRepository('FrontendAccountBundle:States')->find(1);
$user->setEmail($formData->getEmail());
$user->setStateId(1);
$em->persist($user);
$em->flush();
This is not working and way to complicated: http://symfony.com/doc/current/book/doctrine.html#relationship-mapping-metadata. It was so freaking easy in symfony1.4.
Your User entity has a method setState(), which takes a single parameter of $state. That parameter must be of type \Frontend\AccountBundle\Entity\States.
In your controller, you obtain that object through this call:
$state = $this->getDoctrine()->getRepository('FrontendAccountBundle:States')->find(1);
So when you go to set the State of the User, you don't need to bother with IDs. Rather, just set the State directly, and Doctrine will take care of the rest:
$user->setState($state);
This solution works for me:
https://stackoverflow.com/a/14131067/2400373
But in Symfony 4 change the line of getRepository:
$role = $this->getDoctrine()
->getRepository(Role::class)
->find(1);
$usuario->setRole($role);

Resources