Passing POST json object for ArrayCollection data by ajax in Symfony - php

I want to insert Order data in my Symfony 5 application. OrderDetails ArrayCollection data of an Order entity class. Order and OrderDetails ArrayCollection data get by JSON object ajax post. How to passing POST json object for ArrayCollection data by ajax in Symfony.
Entity Code:
class Order
{
public const NUM_ITEMS = 10;
/**
* #ORM\Id()
* #ORM\GeneratedValue()
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\Column(type="string", length=255)
*/
private $orderNo;
/**
* #ORM\Column(type="datetime")
*/
private $orderDate;
/**
* #ORM\Column(type="string", length=255)
*/
private $name;
/**
* #ORM\OneToMany(targetEntity=OrderDetail::class, mappedBy="orders")
*/
private $orderDetails;
public function __construct()
{
$this->orderDetails = new ArrayCollection();
}
public function getId(): ?int
{
return $this->id;
}
public function getOrderNo(): ?string
{
return $this->orderNo;
}
public function setOrderNo(string $orderNo): self
{
$this->orderNo = $orderNo;
return $this;
}
public function getOrderDate(): ?\DateTimeInterface
{
return $this->orderDate;
}
public function setOrderDate(\DateTimeInterface $orderDate): self
{
$this->orderDate = $orderDate;
return $this;
}
public function getName(): ?string
{
return $this->name;
}
public function setName(string $name): self
{
$this->name = $name;
return $this;
}
/**
* #return Collection|OrderDetail[]
*/
public function getOrderDetails(): Collection
{
return $this->orderDetails;
}
public function addOrderDetail(OrderDetail $orderDetail): self
{
if (!$this->orderDetails->contains($orderDetail)) {
$this->orderDetails[] = $orderDetail;
$orderDetail->setOrders($this);
}
return $this;
}
public function removeOrderDetail(OrderDetail $orderDetail): self
{
if ($this->orderDetails->contains($orderDetail)) {
$this->orderDetails->removeElement($orderDetail);
// set the owning side to null (unless already changed)
if ($orderDetail->getOrders() === $this) {
$orderDetail->setOrders(null);
}
}
return $this;
}
}
JS File Code:
// Creating Order Json Object
var orderObj = { "orderNo":"", "orderDate":"", "name":"" };
orderObj.orderNo = $("#text_name").val();
orderObj.orderDate = $("#text_mobileno").val();
orderObj.name = $("#text_email").val();
// Set 2: Ajax Post
// Here i have used ajax post for saving/updating information
$.ajax({
type: 'POST',
contentType: 'application/json;',
url:'/cart/ordersave',
data: JSON.stringify(orderObj),
dataType: 'json',
success: function (response)
{
// alert(response['data']);
//alert(1);
},
error:function(){
alert('ajax failed');
}
});
Controller Code:
/**
* #Route("/cart/ordersave", name="cart_order_save", methods={"POST"})
*
*/
public function ordersave(Request $request, SessionInterface $session)
{
if ($request->isXMLHttpRequest()) {
$content = $request->getContent();
if (!empty($content)) {
$params = json_decode($content, true);
$order = new Order();
$order->setOrderNo('ON-101/20');
$order->setOrderDate(new \DateTime());
$order->setName($params['name']);
$order->setMobileNo($params['mobileno']);
$order->setEmail($params['email']);
$order->setDeliveryAddress($params['address']);
$order->setCity($params['city']);
$order->setState($params['state']);
$order->setZipcode($params['zipcode']);
$order->setPaymentBy(1);
$order->setDeliveryDate(new \DateTime());
$em = $this->getDoctrine()->getManager();
$em->persist($order);
$em->flush();
$lastId = $order->getId();
$session->set('lastOrderIDSession', $lastId);
}
$this->addFlash('notice', 'Order created successfully!');
return new JsonResponse(array('data' => $lastId));
// return new JsonResponse(array('data' => $params));
}
return new Response('Error!', 400);
}
How to get ArrayCollection data in the controller and insert its database table.

I'd advise you using a symfony form, with a form collection, and it will work by itself. You seem to want to use ajax, and even with forms, you can submit the form in javascript without reloading the page.
This will help : https://symfony.com/doc/current/form/form_collections.html
If you really don't want to do that, well you totally can submit an array with the order details data, then iterate on it, create an OrderDetail entity for each, persist them, etc...

Related

Serialize Entity with ManyToMany relationship in Symfony 5

I have a test app with a manytomany relationship and I can get a JSON correctly:
Job.php:
<?php
namespace App\Entity;
use Symfony\Component\Serializer\Annotation\Groups;
use App\Repository\JobRepository;
use Doctrine\ORM\Mapping as ORM;
use \App\Entity\Category;
/**
* #ORM\Entity(repositoryClass=JobRepository::class)
*/
class Job
{
/**
* #ORM\Id
* #ORM\GeneratedValue
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\Column(type="string", length=255)
*/
private $name;
/**
* #ORM\ManyToMany(targetEntity="App\Entity\Category", inversedBy="jobs")
* #ORM\JoinTable(
* name="jobs_categories",
* joinColumns={#ORM\JoinColumn(name="job_id", referencedColumnName="id")},
* inverseJoinColumns={#ORM\JoinColumn(name="category_id", referencedColumnName="id")}
* )
*/
private $categories;
/**
* Constructor
*/
public function __construct()
{
$this->categories = new \Doctrine\Common\Collections\ArrayCollection();
}
public function getId(): ?int
{
return $this->id;
}
public function getName(): ?string
{
return $this->name;
}
public function setName(string $name): self
{
$this->name = $name;
return $this;
}
public function addCategory($categories): self
{
$this->categories[] = $categories;
return $this;
}
public function removeCategory(Category $categories)
{
$this->categories->removeElement($categories);
}
public function getCategories()
{
return $this->categories;
}
public function __toString () {
return $this->name;
}
}
Category.php
<?php
namespace App\Entity;
use App\Repository\CategoryRepository;
use Doctrine\ORM\Mapping as ORM;
use App\Entity\Job;
/**
* #ORM\Entity(repositoryClass=CategoryRepository::class)
*/
class Category
{
/**
* #ORM\Id
* #ORM\GeneratedValue
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\Column(type="string", length=255)
*/
private $name;
/**
* #ORM\ManyToMany(targetEntity="Job", mappedBy="categories")
*/
protected $jobs;
/**
* Constructor
*/
public function __construct()
{
$this->jobs = new \Doctrine\Common\Collections\ArrayCollection();
}
public function getId(): ?int
{
return $this->id;
}
public function getName(): ?string
{
return $this->name;
}
public function setName(string $name): self
{
$this->name = $name;
return $this;
}
public function addJob(Job $post): self
{
$this->jobs[] = $post;
return $this;
}
public function removeJob(Job $post)
{
$this->jobs->removeElement($post);
}
public function getJob()
{
return $this->jobs;
}
public function __toString () {
return $this->name;
}
}
index.html (JQuery Ajax):
// Añadir tarea
$('#addJob').click(function () {
var name = $('#name').val();
var categories = [];
var categoriesChbx = $(".category");
if (name === "") {
alert("Tienes que agregar una tarea."); // TODO
} else {
categoriesChbx.each(function () {
var item = $(this);
item.is(':checked') ? categories.push(item.attr("name")) : "";
});
var job = {
name: name,
categories: categories
};
var error = false;
$.ajax({
url: "{{ url('ajax_save_job') }}",
type: "POST",
dataType: "json",
data: {
"job": job,
"error": error
},
async: true,
success: function (data, error) {
console.log(data, error);
if (error !== false) {
// TODO
errorDiv = $('.error');
errorDiv.html(error);
errorDiv.show();
}
}
});
}
return false;
});
BackendController.php (ajax method):
public function ajaxSaveJob ()
{
//dump($request->isXMLHttpRequest());
if ($request->isXMLHttpRequest()) {
$jobArray = $request->request->get('job');
$jobInclude = $this->getDoctrine()->getRepository(Job::class)->findOneBy(['name' => $jobArray['name']]);
if (!isset($jobInclude)) {
$job = new Job();
$job->setName($jobArray['name']);
if (isset($jobArray['categories'])) {
foreach ($jobArray['categories'] as $value) {
$category = new Category();
$category = $this->getDoctrine()->getRepository(Category::class)->findOneBy(['name' => $value]);
$job->addCategory($category);
}
}
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($job);
$entityManager->flush();
$encoders = [new JsonEncoder()];
$normalizers = [new ObjectNormalizer()];
$serializer = new Serializer($normalizers, $encoders);
// Serializar objeto a JSON
$jobJson = $serializer->serialize($job, 'json', [
'circular_reference_handler' => function ($object) {
return $object->getName();
}
]);
dump($jobJson);
return new JsonResponse([ 'data' => $jobJson, 'error' => false ]);
}
else {
return new JsonResponse([ 'data' => '', 'error' => 'Ese taréa ya existe' ]);
}
}
else {
return new JsonResponse([ 'data' => '', 'error' => "Error: ..." ]); // TODO
}
}
I want to get somethink like this:
{
"id":137,
"name":"43545",
"categories":["php", "javascript"]
}
But instead I get this:
{
"id":142,
"name":"Diego",
"categories":[{"id":5,"name":"javascript","job":[{"id":103,"name":"5654","categories":[{"id":4,"name":"php","job":["5654",{"id":139,"name":"Mar\u00eda","categories":["php","javascript",{"id":6,"name":"css","job":[{"id":135,"name":"53453453","categories":["javascript","css"]},{"id":138,"name":"Fernando","categories":["javascript","css"]},"Mar\u00eda",{"id":140,"name":"Jose","categories":["css"]}]}]}]},"javascript"]},{"id":135,"name":"53453453","categories":["javascript",{"id":6,"name":"css","job":["53453453",{"id":138,"name":"Fernando","categories":["javascript","css"]},{"id":139,"name":"Mar\u00eda","categories":[{"id":4,"name":"php","job":[{"id":103,"name":"5654","categories":["php","javascript"]},"Mar\u00eda"]},"javascript","css"]},{"id":140,"name":"Jose","categories":["css"]}]}]},{"id":138,"name":"Fernando","categories":["javascript",{"id":6,"name":"css","job":[{"id":135,"name":"53453453","categories":["javascript","css"]},"Fernando",{"id":139,"name":"Mar\u00eda","categories":[{"id":4,"name":"php","job":[{"id":103,"name":"5654","categories":["php","javascript"]},"Mar\u00eda"]},"javascript","css"]},{"id":140,"name":"Jose","categories":["css"]}]}]},{"id":139,"name":"Mar\u00eda","categories":[{"id":4,"name":"php","job":[{"id":103,"name":"5654","categories":["php","javascript"]},"Mar\u00eda"]},"javascript",{"id":6,"name":"css","job":[{"id":135,"name":"53453453","categories":["javascript","css"]},{"id":138,"name":"Fernando","categories":["javascript","css"]},"Mar\u00eda",{"id":140,"name":"Jose","categories":["css"]}]}]},"Diego"]}]
}
¿How could you get only the categories associated with the currently handled job?
PS: Sorry for my bad English.

How to fix error with multiple upload with Symfony 4 NoSuchPropertyException

I want to add a field for upload many attached files in a form with Symfony 4. I've two Entity, Member and Documents with a One-To-Many relation but I've an error who doesn't mean anything for me.
In my Entity Document I've this :
/**
* #ORM\ManyToOne(targetEntity="App\Entity\Member", inversedBy="document")
*/
private $member;
/**
* #return mixed
*/
public function getFile()
{
return $this->file;
}
/**
* #param mixed $file
*/
public function setFile($file): void
{
$this->file = $file;
}
public function getMember(): ?Member
{
return $this->member;
}
public function setMember(?Member $member): self
{
$this->member = $member;
return $this;
}
In my Member Entity :
/**
* #ORM\Entity(repositoryClass="App\Repository\MemberRepository")
*/
class Member
{
/**
* #ORM\OneToMany(targetEntity="App\Entity\Documents", mappedBy="member", cascade={"persist"}, orphanRemoval=true)
*/
private $document;
public function __construct()
{
$this->years = new ArrayCollection();
$this->document = new ArrayCollection();
$this->atelier = new ArrayCollection();
}
/**
* #return Collection|Documents[]
*/
public function getDocument(): Collection
{
return $this->document;
}
public function addDocument(Documents $document): self
{
if (!$this->document->contains($document)) {
$this->document[] = $document;
$document->setMember($this);
}
return $this;
}
public function removeDocument(Documents $document): self
{
if ($this->document->contains($document)) {
$this->document->removeElement($document);
// set the owning side to null (unless already changed)
if ($document->getMember() === $this) {
$document->setMember(null);
}
}
return $this;
}
}
I've try to dump the value of my form but when I try to send my form, I've this error when I don't understand
Could not determine access type for property "document" in class "App\Entity\Member": The property "document" in class "App\Entity\Member" can be defined with the methods "addDocument()", "removeDocument()" but the new value must be an array or an instance of \Traversable, "App\Entity\Documents" given.

insert collection data into database

I have a CollectionType fields in my form, and I made it so I can add as many of these fields as you like, here's a pic (the collectiontype are the fields under Exception)
https://imgur.com/a/xQ7qUNT
Now I'm trying to loop through the data and insert it into an array and finally insert it into my database, but this is what I get in my databse https://imgur.com/a/WyBmmwr
also, tried getting the data that is cough after clicking submit: https://imgur.com/a/pLBKx1y and it's there.
this is my method:
/**
* #Route("/new", name="type_parking_new", methods={"GET","POST"})
*/
public function new(Request $request): Response
{
$typeParking = new TypeParking();
$exception = new Exception();
$form = $this->createForm(TypeParkingType::class, $typeParking);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$lesjours = $typeParking->getJourstravail();
$typeParking->getException()->add($exception);
// Here I try getting the data
$excep = $form->get('Exception');
foreach ($excep as $ExceptionForm) {
$name = $ExceptionForm->get('nom')->getData();
$StartDate = $ExceptionForm->get('datedebut')->getData();
$EndDate = $ExceptionForm->get('datefin')->getData();
$StartTime = $ExceptionForm->get('tempsdebut')->getData();
$EndTime = $ExceptionForm->get('tempsfin')->getData();
$exception->setNom($name);
$exception->setDatedebut($StartDate);
$exception->setDatefin($EndDate);
$exception->setTempsdebut($StartTime);
$exception->setTempsfin($EndTime);
$typeParking->addException($exception);
}
// ends here
// this is unrelated
$jour = $lesjours['jour'];
$debut = $lesjours['debut']->format('H:i:s');
$fin = $lesjours['fin']->format('H:i:s');
$newDate = Array('lesjour' => Array($jour => Array('heuredebut' => $debut, 'heurefin' => $fin)));
$typeParking->setJourstravail($newDate);
//end unrelated
$this->addFlash('success', "type added ");
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($typeParking);
$entityManager->flush();
return $this->redirectToRoute('type_parking_index');
}
return $this->render(
'Admin/type_parking/new.html.twig',
['type_parking' => $typeParking, 'form' => $form->createView()]
);
}
and here's my entity TypeParking
<?php
namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
/**
* #ORM\Entity(repositoryClass="App\Repository\TypeParkingRepository")
*/
class TypeParking
{
/**
* #ORM\Id()
* #ORM\GeneratedValue()
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\Column(type="string", length=55)
*/
private $libelle;
/**
* #ORM\Column(type="time", nullable=true)
*/
private $tempsmax;
/**
* #ORM\Column(type="date", nullable=true)
*/
private $jourdebut;
/**
* #ORM\Column(type="date", nullable=true)
*/
private $jourfin;
/**
* #ORM\Column(type="json_array", nullable=true)
*/
private $jourstravail;
/**
* #ORM\Column(type="json_array", nullable=true)
*/
private $exception;
public function __construct()
{
$this->exception = new ArrayCollection();
}
public function getId(): ?int
{
return $this->id;
}
public function getTempsmax(): ?\DateTimeInterface
{
return $this->tempsmax;
}
public function setTempsmax(\DateTimeInterface $tempsmax): self
{
$this->tempsmax = $tempsmax;
return $this;
}
public function getJourdebut(): ?\DateTimeInterface
{
return $this->jourdebut;
}
public function setJourdebut(\DateTimeInterface $jourdebut): self
{
$this->jourdebut = $jourdebut;
return $this;
}
public function getJourfin(): ?\DateTimeInterface
{
return $this->jourfin;
}
public function setJourfin(\DateTimeInterface $jourfin): self
{
$this->jourfin = $jourfin;
return $this;
}
public function getJourstravail()
{
return array_merge([
'jour' => '',
'debut' => null,
'fin' => null,
// other sub-fields "empty" values
], $this->jourstravail ?? [] // prevent array_merge from failing if exception is empty
); }
public function setJourstravail($jourstravail): self
{
$this->jourstravail = $jourstravail;
return $this;
}
public function getException() {
return $this->exception;
}
public function setException($exception): self
{
$this->exception = $exception;
return $this;
}
public function addException($exception)
{
$this->exception->add($exception);
return $this;
}
public function getLibelle(): ?string
{
return $this->libelle;
}
public function setLibelle(string $libelle): self
{
$this->libelle = $libelle;
return $this;
}
}
btw, I have two entities, TypeParking and Exception, TypeParking has a property named Exception which is a json file type and must contain the data from Exception.

Symfony 4 multiple entities in single form

Been trying for hours and hours to get my multi entity form to work, but it really breaks my head and none of the examples I've found work.
I checked the Collection form type documentation and form collections, as well as the Entity form type.
I have a User entity, UserRole entity and a Role entity.
UserRole contains a userID and a roleID. Just a linking table.
The form shows fields to create a User and I want to be able to as well select a new Role for the new user. So I've tried to use the EntityType, a select dropdown shows with all the roles nicely (only if i add the option mapped => false), but doesn't process after form submit.
It's data is not in the $form->getData(), the user gets created, the user_role entry never created.
If I try it without the mapped => false it throws me:
Could not determine access type for property "user_roles" in class "App\Entity\User": The property "user_roles" in class "App\Entity\User" can be defined with the methods "addUserRole()", "removeUserRole()" but the new value must be an array or an instance of \Traversable, "App\Entity\Role" given..
Code:
$form = $this->createFormBuilder(new User)
... //other add entries
->add('user_roles', EntityType::class, array(
'label' => 'Group (role)',
'class' => Role::class,
'choice_label' => 'name',
// 'mapped' => false, // Form works when false, but doesn't save/create UserRole entry
))
->getForm();
$form->handleRequest($request);
Using the CollectionType it's not showing a select dropdown at all.
Code:
$form = $this->createFormBuilder($user)
.... //other add entries
->add('user_roles', CollectionType::class, array(
'entry_type' => ChoiceType::class,
'entry_options' => array(
'choices' => $roleChoices,
),
))
->getForm();
$form->handleRequest($request);
Am I missing something in my Controller's code or do I misunderstand the use of the Form types? I really have no clue what I'm doing wrong.
User Entity:
<?php
namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Security\Core\User\UserInterface;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use JMS\Serializer\Annotation\Exclude;
/**
* #ORM\Entity(repositoryClass="App\Repository\UserRepository")
* #ORM\HasLifecycleCallbacks()
*/
class User implements UserInterface
{
/**
* #ORM\Column(type="string", length=255, nullable=true)
* #Exclude
*/
private $apiToken;
/**
* #ORM\Id()
* #ORM\GeneratedValue()
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\Column(type="string", length=180, unique=true)
*/
private $email;
/**
* #ORM\Column(type="json_array")
*/
private $roles = [];
/**
* #ORM\Column(type="string", length=255)
*/
private $first_name;
/**
* #ORM\Column(type="string", length=255, nullable=true)
*/
private $middle_name;
/**
* #ORM\Column(type="string", length=255)
*/
private $last_name;
/**
* #ORM\Column(type="boolean")
*/
private $enabled;
/**
* #ORM\Column(type="datetime", nullable=true)
*/
private $blocked_at;
/**
* #ORM\OneToMany(targetEntity="App\Entity\Project", mappedBy="created_by")
*/
private $projects;
/**
* #ORM\OneToMany(targetEntity="App\Entity\UserRole", mappedBy="user", fetch="EAGER")
*/
private $user_roles;
/**
* #ORM\OneToMany(targetEntity="App\Entity\Category", mappedBy="created_by")
*/
private $categories;
/**
* #ORM\OneToMany(targetEntity="App\Entity\ProjectFileIos", mappedBy="created_by")
*/
private $projectFileIos;
/**
* #ORM\OneToMany(targetEntity="App\Entity\ProjectFileAndroid", mappedBy="created_by")
*/
private $projectFileAndroid;
/**
* Generate full name
*/
private $full_name;
/**
* #var string The hashed password
* #ORM\Column(type="string")
* #Exclude
*/
private $password;
/**
* #ORM\OneToMany(targetEntity="App\Entity\ProjectUser", mappedBy="user", fetch="EAGER")
*/
private $projectUsers;
/**
* #ORM\Column(type="datetime")
*/
private $created_at;
/**
* #ORM\Column(type="datetime")
*/
private $updated_at;
/**
* #ORM\ManyToOne(targetEntity="App\Entity\User", inversedBy="project")
*/
private $created_by;
/**
* #ORM\ManyToOne(targetEntity="App\Entity\User", inversedBy="project")
* #ORM\JoinColumn(nullable=true)
*/
private $last_updated_by;
public function __construct()
{
$this->user_roles = new ArrayCollection();
$this->user_role = new ArrayCollection();
$this->categories = new ArrayCollection();
$this->projectFileIos = new ArrayCollection();
$this->projectFileAndroid = new ArrayCollection();
$this->projectUsers = new ArrayCollection();
}
public function getId(): ?int
{
return $this->id;
}
public function getApiToken(): ?string
{
return $this->apiToken;
}
public function setApiToken(string $apiToken): self
{
$this->apiToken = $apiToken;
return $this;
}
public function getEmail(): ?string
{
return $this->email;
}
public function setEmail(string $email): self
{
$this->email = $email;
return $this;
}
/**
* A visual identifier that represents this user.
*
* #see UserInterface
*/
public function getUsername(): string
{
return (string) $this->email;
}
/**
* #see UserInterface
*/
public function getRoles(): array
{
$roles = $this->roles;
// guarantee every user at least has ROLE_USER
$roles[] = 'ROLE_USER';
return array_unique($roles);
}
public function setRoles(array $roles): self
{
$this->roles = $roles;
return $this;
}
/**
* #see UserInterface
*/
public function getPassword(): string
{
return (string) $this->password;
}
public function setPassword(string $password): self
{
$this->password = $password;
return $this;
}
/**
* #see UserInterface
*/
public function getSalt()
{
// not needed when using the "bcrypt" algorithm in security.yaml
}
/**
* #see UserInterface
*/
public function eraseCredentials()
{
// If you store any temporary, sensitive data on the user, clear it here
// $this->plainPassword = null;
}
public function getFirstName(): ?string
{
return $this->first_name;
}
public function setFirstName(string $first_name): self
{
$this->first_name = $first_name;
return $this;
}
public function getMiddleName(): ?string
{
return $this->middle_name;
}
public function setMiddleName(string $middle_name): self
{
$this->middle_name = $middle_name;
return $this;
}
public function getLastName(): ?string
{
return $this->last_name;
}
public function setLastName(string $last_name): self
{
$this->last_name = $last_name;
return $this;
}
public function getEnabled(): ?bool
{
return $this->enabled;
}
public function setEnabled(bool $enabled): self
{
$this->enabled = $enabled;
return $this;
}
public function getBlockedAt(): ?\DateTimeInterface
{
return $this->blocked_at;
}
public function setBlockedAt(?\DateTimeInterface $blocked_at): self
{
$this->blocked_at = $blocked_at;
return $this;
}
/**
* #return Collection|UserRole[]
*/
public function getUserRoles(): ?Collection
{
return $this->user_roles;
}
public function getUserRole(): ?Collection
{
return $this->user_role;
}
public function addUserRole(UserRole $userRole): self
{
if (!$this->user_role->contains($userRole)) {
$this->user_role[] = $userRole;
$user_role->setUserId($this);
}
return $this;
}
public function removeUserRole(UserRole $userRole): self
{
if ($this->user_role->contains($userRole)) {
$this->user_role->removeElement($userRole);
// set the owning side to null (unless already changed)
if ($user_role->getUserId() === $this) {
$user_role->setUserId(null);
}
}
return $this;
}
/**
* #return Collection|Project[]
*/
public function getProjects(): Collection
{
return $this->projects;
}
public function addProject(Project $project): self
{
if (!$this->project->contains($project)) {
$this->project[] = $project;
$project->setUserId($this);
}
return $this;
}
public function removeProject(Project $project): self
{
if ($this->project->contains($project)) {
$this->project->removeElement($project);
// set the owning side to null (unless already changed)
if ($project->getUserId() === $this) {
$project->setUserId(null);
}
}
return $this;
}
/**
* #return Collection|Category[]
*/
public function getCategories(): Collection
{
return $this->categories;
}
public function addCategory(Category $category): self
{
if (!$this->categories->contains($category)) {
$this->categories[] = $category;
$category->setCreatedBy($this);
}
return $this;
}
public function removeCategory(Category $category): self
{
if ($this->categories->contains($category)) {
$this->categories->removeElement($category);
// set the owning side to null (unless already changed)
if ($category->getCreatedBy() === $this) {
$category->setCreatedBy(null);
}
}
return $this;
}
/**
* #return Collection|ProjectFileIos[]
*/
public function getProjectFileIos(): Collection
{
return $this->projectFileIos;
}
public function addProjectFileIo(ProjectFileIos $projectFileIo): self
{
if (!$this->projectFileIos->contains($projectFileIo)) {
$this->projectFileIos[] = $projectFileIo;
$projectFileIo->setCreatedBy($this);
}
return $this;
}
public function removeProjectFileIo(ProjectFileIos $projectFileIo): self
{
if ($this->projectFileIos->contains($projectFileIo)) {
$this->projectFileIos->removeElement($projectFileIo);
// set the owning side to null (unless already changed)
if ($projectFileIo->getCreatedBy() === $this) {
$projectFileIo->setCreatedBy(null);
}
}
return $this;
}
/**
* #return Collection|ProjectFileAndroid[]
*/
public function getProjectFileAndroid(): Collection
{
return $this->projectFileAndroid;
}
public function addProjectFileAndroid(ProjectFileAndroid $projectFileAndroid): self
{
if (!$this->projectFileAndroid->contains($projectFileAndroid)) {
$this->projectFileAndroid[] = $projectFileAndroid;
$projectFileAndroid->setCreatedBy($this);
}
return $this;
}
public function removeProjectFileAndroid(ProjectFileAndroid $projectFileAndroid): self
{
if ($this->projectFileAndroid->contains($projectFileAndroid)) {
$this->projectFileAndroid->removeElement($projectFileAndroid);
// set the owning side to null (unless already changed)
if ($projectFileAndroid->getCreatedBy() === $this) {
$projectFileAndroid->setCreatedBy(null);
}
}
return $this;
}
public function getFullName()
{
$lastName = $this->middle_name ? $this->middle_name . ' ' : '';
$lastName .= $this->last_name;
return $this->first_name . ' ' . $lastName;
}
/**
* Triggered after entity has been loaded into the current EntityManager from de database
* or after refresh operation applied to it
* #ORM\PostLoad
*/
public function postLoad()
{
$this->full_name = $this->getFullName();
}
/**
* #return Collection|ProjectUser[]
*/
public function getProjectUsers(): Collection
{
return $this->projectUsers;
}
public function addProjectUser(ProjectUser $projectUser): self
{
if (!$this->projectUsers->contains($projectUser)) {
$this->projectUsers[] = $projectUser;
$projectUser->setUser($this);
}
return $this;
}
public function removeProjectUser(ProjectUser $projectUser): self
{
if ($this->projectUsers->contains($projectUser)) {
$this->projectUsers->removeElement($projectUser);
// set the owning side to null (unless already changed)
if ($projectUser->getUser() === $this) {
$projectUser->setUser(null);
}
}
return $this;
}
public function getCreatedAt(): ?\DateTimeInterface
{
return $this->created_at;
}
public function setCreatedAt(\DateTimeInterface $created_at): self
{
$this->created_at = $created_at;
return $this;
}
public function getUpdatedAt(): ?\DateTimeInterface
{
return $this->updated_at;
}
public function setUpdatedAt(\DateTimeInterface $updated_at): self
{
$this->updated_at = $updated_at;
return $this;
}
public function getCreatedBy(): ?User
{
return $this->created_by;
}
public function setCreatedBy(?User $created_by): self
{
$this->created_by = $created_by;
return $this;
}
public function getLastUpdatedBy(): ?User
{
return $this->last_updated_by;
}
public function setLastUpdatedBy(?User $last_updated_by): self
{
$this->last_updated_by = $last_updated_by;
return $this;
}
/**
* Triggered on insert
* #ORM\PrePersist
*/
public function onPrePersist()
{
$this->enabled = true;
$this->created_at = new \DateTime("now");
$this->updated_at = new \DateTime();
$this->roles = 'a:1:{i:0;s:9:"ROLE_USER";}';
}
/**
* Triggered on update
* #ORM\PreUpdate
*/
public function onPreUpdate()
{
$this->updated_at = new \DateTime("now");
}
}
In Symfony, to get non-mapped form data, try doing like this.
$data = $form->getData();
$roles = $form->get("user_roles")->getData();
Also, noted one thing. Shouldn't the class be UserRole::class instead of Role::class, in the code block below.
$form = $this->createFormBuilder(new User)
... //other add entries
->add('user_roles', EntityType::class, array(
'label' => 'Group (role)',
'class' => Role::class,
'choice_label' => 'name',
// 'mapped' => false, // Form works when false, but doesn't save/create UserRole entry
))
->getForm();
Hope this helps,
Cheers..
The general way you have chosen is okay. Stick with the EntityType and remove the mapped = false, this would tell Symfony to ignore the field.
I guess the problem is: you have a mixture of $this->user_role and $this->user_roles in your class, probably a renamed variable. Clean this up first in __construct(), addUserRole(), removeUserRole(), getUserRoles(), getUserRole().
Then add a method
public function setUserRoles($userRoles)
{
$this->user_roles = new ArrayCollection();
foreach ($userRoles as $role) {
$this->addUserRole($role);
}
return $this;
}

Symfony4 setter where getter match id route?

I'm kindly new on Symfony
I'm doing a vote system but i guess this should work for like,
At the moment my controller function is this, this only create a new row with 1vote, but not update any $id created before.
/**
* #Route("/public/{id}/vote", name="poll_vote", methods="GET|POST")
*/
public function vote(Request $request, Poll $poll): Response
{
$inc = 1;
$em = $this->getDoctrine()->getManager();
$entity = new Poll();
$entity->setVotes($inc++);
$em->persist($entity);
$em->flush();
}
return $this->redirectToRoute('poll_public');
}
This is my button from twig template
<a href="{{ path('poll_vote', {'id': poll.id}) }}">
An this is my entity
class Poll
{
/**
* #ORM\Id()
* #ORM\GeneratedValue()
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\Column(type="string", length=255)
*/
private $name;
/**
* #ORM\Column(type="integer", nullable=true)
*/
private $votes;
public function getId(): ?int
{
return $this->id;
}
public function getName(): ?string
{
return $this->name;
}
public function setName(string $name): self
{
$this->name = $name;
return $this;
}
public function getVotes(): ?int
{
return $this->votes;
}
public function setVotes(?int $votes): self
{
$this->votes = $votes;
return $this;
}
}
I have no idea about how can match my getID from my entity and match for the $id from the #Route.
Any guide or suggestion would be really appreciate.
Thanks
EDIT:
Updated with the correct function after Arne answer:
/**
* #Route("/public/{id}", name="poll_vote", methods="GET|POST")
*/
public function vote($id)
{
$entityManager = $this->getDoctrine()->getManager();
$poll = $entityManager->getRepository(Poll::class)->find($id);
if (!$poll) {
throw $this->createNotFoundException(
'No polls found for id '.$id
);
}
$poll->setVotes($poll->getVotes()+1);
$entityManager->flush();
return $this->redirectToRoute('poll_public', [
'id' => $poll->getId()
]);
}
basically you have to get the ID from your request, query the Entitty Repository for your Poll Entity, update the votes and persist it back to your database.
Get the ID from your request
$id = $request->query->get('id');
Query the repository:
$entityManager = $this->getDoctrine()->getManager();
$poll= $entityManager->getRepository(Poll::class)->find($id);
Update the votes:
$poll->setVotes($poll->getVotes()+1);
Persist to the DB:
$entityManager->persist($poll);
$entityManager->flush();
Alternatively you could also use the ParamConverter to let Symfony get the Poll object for you. More information about updating objects can be found in the Doctrine Guide.
Note that yor route will only match existing polls, since id is a required parameter in the URL. You might add another route without an ID which is being used for creating new Poll entities.

Categories