How to integrate forms of several entities? Symfony 2 - php

I need to merge table 'fos_user' and 'institution'.And I need to display registration form from both entities.
I have a problem with FOSUserBundle.
I created new properties in User class
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
protected $workPhone;
protected $adminPhone;
protected $name;
protected $adress;
public function __construct()
{
parent::__construct();
}
public function setAdress($adress)
{
$this->adress = $adress;
}
public function setName($name)
{
$this->name = $name;
}
public function setWorkPhone($workPhone)
{
$this->workPhone = $workPhone;
}
public function setAdminPhone($adminPhone)
{
$this->adminPhone = $adminPhone;
}
public function getName()
{
return $this->name;
}
public function getAdress()
{
return $this->adress;
}
public function getWorkPhone()
{
return $this->workPhone;
}
public function getAdminPhone()
{
return $this->adminPhone;
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
And I have entity Institution, which I want merge.
/**
* #var integer
*
* #ORM\Column(name="id_institution", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $idInstitution;
/**
* #var string
*
* #ORM\Column(name="name", type="string", length=45, nullable=false)
*/
private $name;
/**
* #var integer
*
* #ORM\Column(name="work_phone", type="integer", nullable=false)
*/
private $workPhone;
/**
* #var integer
*
* #ORM\Column(name="admin_phone", type="integer", nullable=true)
*/
private $adminPhone;
/**
* #var string
*
* #ORM\Column(name="adress", type="string", length=255, nullable=false)
*/
private $adress;
/**
* #var \AppBundle\Entity\FosUser
*
* #ORM\ManyToOne(targetEntity="AppBundle\Entity\FosUser")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="id_fos_user", referencedColumnName="id")
* })
*/
private $idFosUser;
/**
* Get idInstitution
*
* #return integer
*/
public function getIdInstitution()
{
return $this->idInstitution;
}
/**
* Set name
*
* #param string $name
* #return Institution
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* Set workPhone
*
* #param integer $workPhone
* #return Institution
*/
public function setWorkPhone($workPhone)
{
$this->workPhone = $workPhone;
return $this;
}
/**
* Get workPhone
*
* #return integer
*/
public function getWorkPhone()
{
return $this->workPhone;
}
/**
* Set adminPhone
*
* #param integer $adminPhone
* #return Institution
*/
public function setAdminPhone($adminPhone)
{
$this->adminPhone = $adminPhone;
return $this;
}
/**
* Get adminPhone
*
* #return integer
*/
public function getAdminPhone()
{
return $this->adminPhone;
}
/**
* Set adress
*
* #param string $adress
* #return Institution
*/
public function setAdress($adress)
{
$this->adress = $adress;
return $this;
}
/**
* Get adress
*
* #return string
*/
public function getAdress()
{
return $this->adress;
}
/**
* Set idFosUser
*
* #param \AppBundle\Entity\FosUser $idFosUser
* #return Institution
*/
public function setIdFosUser($idFosUser = null)
{
$this->idFosUser = $idFosUser;
return $this;
}
/**
* Get idFosUser
*
* #return \AppBundle\Entity\FosUser
*/
public function getIdFosUser()
{
return $this->idFosUser;
}
This is pert of InstitutionManager where I want save Entity, and this is like service now:
public function createNewEntity($user)
{
$entity = new Institution();
$entity->setName($user->getName());
$entity->setAdminPhone($user->getAdminPhone());
$entity->setWorkPhone($user->getWorkPhone());
$entity->setAdress($user->getAdress());
$entity->setidFosUser($user->getId());
$em = $this->getDoctrine()->getManager();
$em->persist($entity);
$em->flush();
}
And hear override RegistrationController:
public function registerAction()
{
$form = $this->container->get('fos_user.registration.form');
$formHandler = $this->container->get('fos_user.registration.form.handler');
$confirmationEnabled = $this->container->getParameter('fos_user.registration.confirmation.enabled');
$process = $formHandler->process($confirmationEnabled);
if ($process) {
$user = $form->getData();
$authUser = false;
if ($confirmationEnabled) {
$this->container->get('session')->set('fos_user_send_confirmation_email/email', $user->getEmail());
$route = 'fos_user_registration_check_email';
} else {
$authUser = true;
$route = 'fos_user_registration_confirmed';
}
$this->setFlash('fos_user_success', 'registration.flash.user_created');
$institutionManager = $this->container->get('institution_manager');
$institution = $institutionManager->createNewEntity($user);
$url = $this->container->get('router')->generate($route);
$response = new RedirectResponse($url);
if ($authUser) {
$this->authenticateUser($user, $response);
}
return $response;
}
return $this->container->get('templating')->renderResponse('FOSUserBundle:Registration:register.html.'.$this->getEngine(), array(
'form' => $form->createView(),
));
}
services.yml:
services:
institution_manager:
class: AppBundle\Lib\Manager\InstitutionManager
arguments: [ #doctrine.orm.default_entity_manager ]

Your InstitutationController is not being properly initialized. There is a setContainer method which the router calls to, well, set the container. getDoctrine in turn needs the container, hence the null object error.
A simple hack would be to call the setContainer method yourself:
$entity = new InstitutionController();
$entity->setContainer($this->container);
$entity->createNewEntity($user);
But it's a hack you should do some redesigning. What you are calling a controller is not a controller at all. It's a service, maybe a sort of a factory or manager. Sort of like the FOS UserManager.
So read up on how to define a service: http://symfony.com/doc/current/book/service_container.html
It takes a bit of research but once you understand the process then services will become second nature. You will inject the doctrine entity manager directly into your service.
class InstitutionManager
{
protected $entityManager;
public function __construct($entityManager)
{
$this->entityManager = $entityManager;
}
public function createNewEntity($user)
{
$entity = new Institution();
$entity->setName($user->getName());
$entity->setAdminPhone($user->getAdminPhone());
$entity->setWorkPhone($user->getWorkPhone());
$entity->setAdress($user->getAdress());
$entity->setidFosUser($user->getId());
$this->entityManager->persist($entity);
$this->entityManager->flush();
return $entity;
}
I will leave services.yml up to you. The entity manager service id is doctrine.orm.default_entity_manager
Your controller would then look like:
$institutionManager = $this->get('institution_manager');
$institution = $institutionManager->create($user);
You will also want to rethink how you are relating the user object. The userId stuff is a no no. You will want to make a one-to-one relation between $institution and $user. But that is really a different topic.
Enjoy.

Related

Symfony 3 find closest date from now

I have three database tables. user, meeting, group. The meetings and group table are manytomany associations from the user table. So I can do user->getmeetings(), or user->getgroups().
I want to get just the next meeting comping up for the user, and I don't know how to achieve this. Whether by SQL Query or simply in the controller. Here is what I have done so far.
$loggedInUser = $em->getRepository('AppBundle\Entity\User')
->find($id);
foreach ($loggedInUser->getMeetings() as $userMeetings) {
$nextMeeting[$userMeetings->getId()]['id'] = $userMeetings->getId();
$nextMeeting[$userMeetings->getId()]['group'] = $userMeetings->getGroup();
$nextMeeting[$userMeetings->getId()]['name'] = $userMeetings->getName();
$nextMeeting[$userMeetings->getId()]['info'] = $userMeetings->getInfo();
$nextMeeting[$userMeetings->getId()]['bring'] = $userMeetings->getBring();
$nextMeeting[$userMeetings->getId()]['summary'] = $userMeetings->getSummary();
$nextMeeting[$userMeetings->getId()]['files'] = $userMeetings->getFiles();
$nextMeeting[$userMeetings->getId()]['meetingDate'] = $userMeetings->getMeetingDate();
$nextMeeting[$userMeetings->getId()]['meetingAddress'] = $userMeetings->getMeetingAddress();
$nextMeeting[$userMeetings->getId()]['time_diff'] = date_diff($userMeetings->getMeetingDate(), new \DateTime());
}
I have added a time_diff field in the new array to calculate the time from now to the meeting time. All I need to do now is select the smallest one.How can I do this? Thank you.
UPDATE - Below is my User Repository
namespace AppBundle\Repository;
use AppBundle\Entity\User;
use AppBundle\Entity\Meeting;
use Doctrine\ORM\EntityRepository;
use Doctrine\Common\Collections\Criteria;
class UserRepository extends EntityRepository
{
public function getComingMeeting()
{
$criteria = Criteria::create()
->where(Criteria::expr()->gte("meetingDate", new \DateTime('now')))
->orderBy(array("meetingDate" => Criteria::ASC))
->setMaxResults(1);
$this->getMeetings()->matching($criteria);
}
}
Below is my User Entity
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use Doctrine\Common\Collections\ArrayCollection;
/**
* #ORM\Entity(repositoryClass="AppBundle\Repository\UserRepository")
* #ORM\Table(name="user")
*/
class User
{
/**
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\Column(type="string", nullable=false)
*/
private $first_name;
/**
* #ORM\Column(type="string", nullable=false)
*/
private $last_name;
/**
* #ORM\Column(type="string", nullable=false, unique=true)
*/
private $email_address;
/**
* #ORM\Column(type="string", nullable=true)
*/
private $phone_number;
/**
* #ORM\Column(type="string", nullable=false)
*/
private $password;
/**
* #ORM\Column(type="datetime", nullable=true)
*/
private $last_login;
/**
* #ORM\Column(type="string", nullable=true)
*/
private $reset_password;
/**
* #ORM\ManyToMany(targetEntity="Meeting", inversedBy="users")
*/
private $meetings;
/**
* #ORM\ManyToMany(targetEntity="Group", inversedBy="users")
*/
private $groups;
public function __construct()
{
$this->groups = new arrayCollection();
$this->meetings = new arrayCollection();
}
/**
* #return mixed
*/
public function getFirstName()
{
return $this->first_name;
}
/**
* #param mixed $first_name
*/
public function setFirstName($first_name)
{
$this->first_name = $first_name;
}
/**
* #return mixed
*/
public function getLastName()
{
return $this->last_name;
}
/**
* #param mixed $last_name
*/
public function setLastName($last_name)
{
$this->last_name = $last_name;
}
/**
* #return mixed
*/
public function getEmailAddress()
{
return $this->email_address;
}
/**
* #param mixed $email_address
*/
public function setEmailAddress($email_address)
{
$this->email_address = $email_address;
}
/**
* #return mixed
*/
public function getPhoneNumber()
{
return $this->phone_number;
}
/**
* #param mixed $phone_number
*/
public function setPhoneNumber($phone_number)
{
$this->phone_number = $phone_number;
}
/**
* #return mixed
*/
public function getPassword()
{
return $this->password;
}
/**
* #param mixed $password
*/
public function setPassword($password)
{
$this->password = $password;
}
/**
* #return mixed
*/
public function getLastLogin()
{
return $this->last_login;
}
/**
* #param mixed $last_login
*/
public function setLastLogin($last_login)
{
$this->last_login = $last_login;
}
/**
* #return mixed
*/
public function getResetPassword()
{
return $this->reset_password;
}
/**
* #param mixed $reset_password
*/
public function setResetPassword($reset_password)
{
$this->reset_password = $reset_password;
}
/**
* #return arrayCollection|Meeting[]
*/
public function getMeetings()
{
return $this->meetings;
}
/**
* #return ArrayCollection|Group[]
*/
public function getGroups()
{
return $this->groups;
}
/**
* #return mixed
*/
public function getId()
{
return $this->id;
}
}
below is my HomeControlller.php
class HomeController extends Controller
{
/**
* #Route("/home", name="home_show")
*/
public function showAction()
{
$em = $this->getDoctrine()->getManager();
//logged in user
$id = 1;
$loggedInUser = $em->getRepository('AppBundle\Entity\User')
->find($id);
foreach ($loggedInUser->getMeetings() as $userMeetings) {
$nextMeeting[$userMeetings->getId()]['id'] = $userMeetings->getId();
$nextMeeting[$userMeetings->getId()]['group'] = $userMeetings->getGroup();
$nextMeeting[$userMeetings->getId()]['name'] = $userMeetings->getName();
$nextMeeting[$userMeetings->getId()]['info'] = $userMeetings->getInfo();
$nextMeeting[$userMeetings->getId()]['bring'] = $userMeetings->getBring();
$nextMeeting[$userMeetings->getId()]['summary'] = $userMeetings->getSummary();
$nextMeeting[$userMeetings->getId()]['files'] = $userMeetings->getFiles();
$nextMeeting[$userMeetings->getId()]['meetingDate'] = $userMeetings->getMeetingDate();
$nextMeeting[$userMeetings->getId()]['meetingAddress'] = $userMeetings->getMeetingAddress();
$nextMeeting[$userMeetings->getId()]['time_diff'] = date_diff($userMeetings->getMeetingDate(), new \DateTime());
}
$groups = $em->getRepository('AppBundle\Entity\Group')
->findAll();
return $this->render('home/show.html.twig', [
'loggedInUser' => $loggedInUser,
'groups' => $groups,
]);
}
}
You can add a method in your UserEntity with a matching criteria on meeting collection
namespace AppBundle\Entity;
use Doctrine\Common\Collections\Criteria;
....
public function getComingMeeting()
{
$criteria = Criteria::create()
->where(Criteria::expr()->gte("meetingDate", new \DateTime('now')))
->orderBy(array("meetingDate" => Criteria::ASC))
->setMaxResults(1);
return $this->getMeetings()->matching($criteria);
}
see http://doctrine-orm.readthedocs.io/projects/doctrine-orm/en/latest/reference/working-with-associations.html

PHP: Call to a member function .... on a non-object

hello I'm having trouble with:
public function isAdmin()
{
$role = $this->getFirstRole();
if ($role->getRoleId() == "admin")
return true;
return false;
}
it causes: Call to a member function getRoleId() on a non-object
please guys, help. thanks
classes:
class Role implements HierarchicalRoleInterface
{
/**
* Store id.
* #var int
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* Store role kind.
* Possible user kinds: 'guest' (not signed in),
'user' (default for signed in user), 'admin'.
* #var string
* #ORM\Column(type="string", length=255,
unique=true, nullable=true)
*/
protected $roleId;
/**
* Store role parent for inheritance measure.
* #var Role
* #ORM\ManyToOne(targetEntity="User\Entity\Role")
*/
protected $parent;
/**
* Get id.
* #return int
*/
public function getId()
{
return $this->id;
}
/**
* Set id.
* #param int $id
* #return void
*/
public function setId($id)
{
$this->id = (int)$id;
}
/**
* Get role kind.
* #return string
*/
public function getRoleId()
{
return $this->roleId;
}
/**
* Set role kind.
* #param string $roleId
* #return void
*/
public function setRoleId($roleId)
{
$this->roleId = (string) $roleId;
}
/**
* Get parent role
* #return Role
*/
public function getParent()
{
return $this->parent;
}
/**
* Set parent role.
* #param Role $parent
* #return void
*/
public function setParent(Role $parent)
{
$this->parent = $parent;
}
}
class User implements UserInterface, ProviderInterface
{
/**
* Store id.
* #var int
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* Store username.
* #var string
* #ORM\Column(type="string", length=255, unique=true)
*/
protected $username;
/**
* Store email.
* #var string
* #ORM\Column(type="string", unique=true, length=255)
*/
protected $email;
/**
* Store displayName.
* #var string
* #ORM\Column(type="string", length=50, nullable=true)
*/
protected $displayName;
/**
* Store password.
* #var string
* #ORM\Column(type="string", length=128)
*/
protected $password;
/**
* Store state.
* #var int
*/
protected $state;
/**
* Store mark.
* #var float
*/
protected $mark;
/**
* Store roles collection.
* #var \Doctrine\Common\Collections\Collection
* #ORM\ManyToMany(targetEntity="User\Entity\Role")
* #ORM\JoinTable(name="users_roles",
* joinColumns={
#ORM\JoinColumn(
name="user_id",
referencedColumnName="id"
)
},
* inverseJoinColumns={
#ORM\JoinColumn(
name="role_id",
referencedColumnName="id"
)
}
* )
*/
protected $roles;
/**
* Store albums collection
* #var \Doctrine\Common\Collections\Collection
* #ORM\OneToMany(targetEntity="Album\Entity\Album", mappedBy="user",
cascade={"all"})
*/
protected $albums;
/**
* Store comments collection.
* #var \Doctrine\Common\Collections\Collection
* #ORM\OneToMany(targetEntity="Comment\Entity\Comment", mappedBy="user",
cascade={"all"})
*/
protected $comments;
/**
* Store marks collection.
* #var \Doctrine\Common\Collections\Collection
* #ORM\OneToMany(targetEntity="Mark\Entity\Mark", mappedBy="user",
cascade={"all"})
*/
protected $marks;
/**
* Initialies collections.
*/
public function __construct()
{
$this->roles = new ArrayCollection();
$this->albums = new ArrayCollection();
$this->comments = new ArrayCollection();
$this->marks = new ArrayCollection();
}
/**
* Get id.
* #return int
*/
public function getId()
{
return $this->id;
}
/**
* Set id.
* #param int $id
* #return void
*/
public function setId($id)
{
$this->id = (int) $id;
}
/**
* Get username.
* #return string
*/
public function getUsername()
{
return htmlspecialchars($this->username);
}
/**
* Set username.
* #param string $username
* #return void
*/
public function setUsername($username)
{
$this->username = $username;
}
/**
* Get email.
* #return string
*/
public function getEmail()
{
return $this->email;
}
/**
* Set email.
* #param string $email
* #return void
*/
public function setEmail($email)
{
$this->email = $email;
}
/**
* Get displayName.
* #return string
*/
public function getDisplayName()
{
return $this->displayName;
}
/**
* Set displayName.
* #param string $displayName
* #return void
*/
public function setDisplayName($displayName)
{
$this->displayName = $displayName;
}
/**
* Get password.
* #return string
*/
public function getPassword()
{
return $this->password;
}
/**
* Set password.
* #param string $password
* #return void
*/
public function setPassword($password)
{
$this->password = $password;
}
/**
* Get state.
* #return int
*/
public function getState()
{
return $this->state;
}
/**
* Set state.
* #param int $state
* #return void
*/
public function setState($state)
{
$this->state = $state;
}
/**
* Get roles collection.
* #return \Doctrine\Common\Collections\Collection
*/
public function getRoles()
{
return $this->roles;
}
public function getFirstRole() {
$roles = $this->getRoles();
$firstRole = $roles[0];
return $firstRole;
}
/**
* Get comments collection.
* #return \Doctrine\Common\Collections\Collection
*/
public function getComments()
{
return $this->comments;
}
/**
* Get marks collection.
* #return \Doctrine\Common\Collections\Collection
*/
public function getMarks()
{
return $this->marks;
}
/**
* Add a role to user.
* #param Role $role
* #return void
*/
public function addRole($role)
{
$this->roles[] = $role;
}
/**
* Get albums.
* #return \Doctrine\Common\Collections\Collection
*/
public function getAlbums()
{
return $this->albums;
}
public function isAdmin(){
$role = $this->getFirstRole();
if ($role->getRoleId() == "admin")
return true;
return false;
}
/**
* Calculate user mark.
* #return float
*/
public function mark()
{
if (!$this->mark) {
$albums = $this->getAlbums();
$result = 0;
foreach ($albums as &$album) {
$result += $album->mark();
}
$this->mark = $result;
}
return $this->mark;
}
}
anyone?
(writing this becaue it says my post is mostly code)
(writing this becaue it says my post is mostly code)
/**
* Get roles collection.
* #return \Doctrine\Common\Collections\Collection
*/
public function getRoles()
{
return $this->roles;
}
Collections are not accessed by [0], they are Collection objects, use like this:
public function getFirstRole() {
return $this->roles->first();
}
#h2ooooooo gave this helpful link to the docs, containing all methods of the collection: http://www.doctrine-project.org/api/common/2.3/class-Doctrine.Common.Collections.ArrayCollection.html
You can compare ID with an ID (integer), or string by string,
but the best is to compare Entities to keep the whole system integral:
public function isAdmin() {
$role = $this->getFirstRole();
$admin = $entityManager
->getRepository('User\Entity\Role')
->findOneByName('admin');
if ($role === $admin) {
return true;
} else {
return false;
}
}
it seems that $this->getFirstRole() returned user role as string. you just need to compare it as string.
try this:
public function isAdmin()
{
$role = $this->getFirstRole();
return $role == "admin" ? true : false;
}

FatalErrorException: Error: Call to a member function getId() on a non-object in ...PostListener.php line 20

I'm new in Symfony2. I've a task to create blog. One of the necessary is displaying most popular posts. So I think that the best varient is create listener. It will be call, when visiter will read post. And listener will increment onŠµ of the fild in database(MySQL). I create method in repository, which makes selection by this field. And also create Action, which renders posts by this selection. But when I try to read post, a have error:
FatalErrorException: Error: Call to a member function getId() on a non-object in /var/www/blo/src/Blog/Bundle/BlogBundle/EventListener/PostVisitedListener.php line 20.
Please, help me.
This my Entity (Post):
namespace Blog\Bundle\BlogBundle\Entity;
use Doctrine\Common\Collections\ArrayCollection;
use Gedmo\Mapping\Annotation as Gedmo;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
/**
* Post
*
* #ORM\Table(name="post")
* #ORM\Entity(repositoryClass="Blog\Bundle\BlogBundle\Entity\PostRepository")
*/
class Post
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="title", type="string", length=255)
* #Assert\NotBlank
* #Assert\Length(min="13", max="255")
*/
private $title;
/**
* #var string
*
* #ORM\Column(name="author", type="string", length=100)
* #Assert\NotBlank
* #Assert\Length(min="13", max="100")
*/
private $author;
/**
* #var string
*
* #ORM\Column(name="post", type="text")
* #Assert\NotBlank
* #Assert\Length(min="100")
*/
private $post;
/**
* #var string
*
* #ORM\Column(name="image", type="string", length=100)
*/
private $image;
/**
* #Gedmo\Timestampable(on="create")
* #ORM\Column(name="createdAt", type="datetime")
*
*/
private $createdAt;
/**
*
* #ORM\Column(name="tags", type="text")
*/
private $tags;
/**
* #ORM\ManyToOne(targetEntity="Category", inversedBy="posts")
*/
private $category;
/**
* #ORM\OneToMany(targetEntity="Comment", mappedBy="post")
*/
private $comments;
/**
* #var integer
*
* #ORM\Column(name="visitedIncrement", type="integer")
*/
private $visitedIncrement;
public function __construct()
{
$this->comments = new ArrayCollection();
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set title
*
* #param string $title
* #return Post
*/
public function setTitle($title)
{
$this->title = $title;
return $this;
}
/**
* Get title
*
* #return string
*/
public function getTitle()
{
return $this->title;
}
/**
* Set author
*
* #param string $author
* #return Post
*/
public function setAuthor($author)
{
$this->author = $author;
return $this;
}
/**
* Get author
*
* #return string
*/
public function getAuthor()
{
return $this->author;
}
/**
* Set post
*
* #param string $post
* #return Post
*/
public function setPost($post)
{
$this->post = $post;
return $this;
}
/**
* Get post
*
* #return string
*/
public function getPost()
{
return $this->post;
}
/**
* Set image
*
* #param string $image
* #return Post
*/
public function setImage($image)
{
$this->image = $image;
return $this;
}
/**
* Get image
*
* #return string
*/
public function getImage()
{
return $this->image;
}
/**
* Set tags
*
* #param string $tags
* #return Post
*/
public function setTags($tags)
{
$this->tags = $tags;
return $this;
}
/**
* Get tags
*
* #return string
*/
public function getTags()
{
return $this->tags;
}
/**
* Set category
*
* #param $category
* #return $this
*/
public function setCategory($category)
{
$this->category = $category;
return $this;
}
/**
* Get category
*
* #return integer
*/
public function getCategory()
{
return $this->category;
}
/**
* Set comments
*
* #param string $comments
* #return Post
*/
public function setComments($comments)
{
$this->comments = $comments;
return $this;
}
/**
* Get comments
*
* #return string
*/
public function getComments()
{
return $this->comments;
}
/**
* #param \DateTime $createdAt
*/
public function setCreatedAt($createdAt)
{
$this->createdAt = $createdAt;
return $this;
}
/**
* #return \DateTime
*/
public function getCreatedAt()
{
return $this->createdAt;
}
/**
* #param int $visitedIncrement
*/
public function setVisitedIncrement($visitedIncrement)
{
$this->visitedIncrement = $visitedIncrement;
return $this;
}
/**
* #return int
*/
public function getVisitedIncrement()
{
return $this->visitedIncrement;
}
public function __toString()
{
return $this->getTitle();
}
}
This is my PostRepository
public function visitedIncrement($id)
{
$query = $this->getEntityManager()
->createQuery(
'UPDATE BlogBlogBundle:Post p
SET p.visitedIncrement = p.visitedIncrement + 1
WHERE p.id = :post_id')
->setParameter(':post_id', $id);
$query->execute();
This is my PostVisitedEvent
namespace Blog\Bundle\BlogBundle\Event;
use Blog\Bundle\BlogBundle\Entity\Post;
use Symfony\Component\EventDispatcher\Event;
class PostVisitedEvent extends Event
{
protected $post;
/**
* #param Post $post
*/
public function setPost(Post $post)
{
return $this->post;
}
/**
* #return Post
*/
public function getPost()
{
return $this->post;
}
}
This is my PostVisitedListener
namespace Blog\Bundle\BlogBundle\EventListener;
use Blog\Bundle\BlogBundle\Entity\PostRepository;
use Doctrine\ORM\EntityManager;
use Blog\Bundle\BlogBundle\Event\PostVisitedEvent;
class PostVisitedListener
{
protected $repository;
public function __construct(PostRepository $repository)
{
$this->repository = $repository;
}
public function onPostVisited(PostVisitedEvent $event)
{
$this->repository->visitedIncrement($event->getPost()->getId());
}
This is my Action (it opens post and gives a opportunity to create comment):
public function showPostAction($id)
{
$postRepository = $this->container->get('blog_blog_bundle.post.repository');
$post = $postRepository->find($id);
if (!$post) {
throw $this->createNotFoundException('The post is not found!');
}
$commentRepository = $this->container->get('blog_blog_bundle.comment.repository');
$comments = $commentRepository->findCommentForPost($post->getId());
$event = new PostVisitedEvent();
$event->setPost($post);
$eventDispatcher = $this->get('event_dispatcher');
$eventDispatcher->dispatch('blog_blog_bundle.post_visited', $event);
return $this->render('BlogBlogBundle:Default:showPost.html.twig', array(
'post' => $post,
'comments' => $comments,
));
}
Yuo can see, that I also create services for repositories and listener. There are:
service id="blog_blog_bundle.post.repository" class="Blog\Bundle\BlogBundle\Entity\PostRepository" factory-service="doctrine.orm.entity_manager" factory-method="getRepository"
argument>BlogBlogBundle:Post argument
service
service id="blog_blog_bundle.comment.repository" class="Blog\Bundle\BlogBundle\Entity\CommentRepository" factory-service="doctrine.orm.entity_manager" factory-method="getRepository"
argument BlogBlogBundle:Comment argument
service
service id="blog_blog_bundle.post_visited_listener" class="Blog\Bundle\BlogBundle\EventListener\PostVisitedListener"
argument type="service" id="blog_blog_bundle.post.repository"
tag name="kernel.event_listener" event="blog_blog_bundle.post_visited" method="onPostVisited"
service
Please, help me.
public function onPostVisited(PostVisitedEvent $event)
{
if (!($event->getPost() instanceof PostInterface)) return;
$this->repository->visitedIncrement($event->getPost()->getId());
}
PostInterface is not a symfony interface. You have to code it. Asking for interface is better than asking for a concrete instance because symfony sometimes uses proxy classes instead of concrete classes.

php and twig syntax

I have the following code to extract the username of an owner object. The Owner object is essentially the owner of the shop. Here's how it's defined in the Shop class.
/**
* Set owner
*
* #param User $owner
* #return Shop
*/
public function setOwner(User $owner = null)
{
$this->owner = $owner;
return $this;
}
/**
* Get owner
*
* #return User
*/
public function getOwner()
{
return $this->owner;
}
/**
As you can see the owner returns a User object. However when I do .username to the User class I always get undefined. Why is this?
"<%= '/profile/'+item.get('shop').owner.username %>">
When I do the following:
"<%= '/profile/'+item.get('shop').name %>">
it prints out just fine.
Here's some more code on the Shop:
class Shop
{
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #Exclude()
* #ORM\Column(name="isVisible", type="boolean")
*/
private $isVisible = false;
/**
* #ORM\OneToOne(targetEntity="Shopious\MainBundle\Entity\ShopLogo", mappedBy="shop", cascade={"persist","remove"})
*/
protected $shoplogo;
/**
* #Assert\NotBlank(message="Shope name should not be blank")
* #ORM\Column(name="name", type="string", length=100, unique=true)
*/
protected $name;
/**
* Assert\NotBlank(message="Description should not be blank")
* #ORM\Column(name="description", type="string", length=350, nullable=true)
*/
protected $description = "";
/**
* #ORM\Column(name="tags", type="text",nullable=true)
*/
protected $tags = "";
/**
* #ORM\OneToMany(targetEntity="Shopious\MainBundle\Entity\Product", mappedBy="shop", cascade={"remove","persist"})
*/
protected $products;
/**
* #Exclude()
* #ORM\OneToOne(targetEntity="Shopious\UserBundle\Entity\User", inversedBy="shop")
* #ORM\JoinColumn(name="user_id", referencedColumnName="id", onDelete="CASCADE", nullable=true)
*/
protected $owner;
/**
* #Exclude()
* #ORM\OneToOne(targetEntity="Shopious\MainBundle\Entity\PaymentInfo", inversedBy="shop", cascade={"persist","remove"})
* #ORM\JoinColumn(name="paymentInfo_id", referencedColumnName="id" , onDelete="CASCADE")
*/
protected $paymentInfo;
/**
*
* #ORM\OneToMany(targetEntity="Shopious\MainBundle\Entity\ShopTestimonial", mappedBy="shop", cascade={"persist","remove"})
*/
protected $testimonials;
public function __toString()
{
return $this->shopname;
}
/**
* #ORM\PrePersist
*/
public function initialisation()
{
$this->shoplogo = new ShopLogo();
$this->shoplogo->setShop($this);
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set owner
*
* #param User $owner
* #return Shop
*/
public function setOwner(User $owner = null)
{
$this->owner = $owner;
return $this;
}
/**
* Get owner
*
* #return User
*/
public function getOwner()
{
return $this->owner;
}
/**
* Constructor
*/
public function __construct()
{
$this->products = new ArrayCollection();
}
/**
* Set shopname
*
* #param string $shopname
* #return Shop
*/
public function setName($shopname)
{
$this->name = $shopname;
//return $this;
}
/**
* Get shopname
*
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* Set description
*
* #param string $description
* #return Shop
*/
public function setDescription($description)
{
$this->description = $description;
return $this;
}
/**
* Get description
*
* #return string
*/
public function getDescription()
{
return $this->description;
}
/**
* Add products
*
* #param Product $products
* #return Shop
*/
public function addProduct(Product $products)
{
$this->products[] = $products;
return $this;
}
/**
* Remove products
*
* #param Product $products
*/
public function removeProduct(Product $products)
{
$this->products->removeElement($products);
}
/**
* Get products
*
* #return Collection
*/
public function getProducts()
{
return $this->products;
}
public function getPaymentInfo()
{
return $this->paymentInfo;
}
public function setPaymentInfo(\Shopious\MainBundle\Entity\PaymentInfo $paymentInfo)
{
$this->paymentInfo = $paymentInfo;
}
/**
* Set tags
*
* #param string $tags
* #return Shop
*/
public function setTags($tags)
{
$this->tags = $tags;
return $this;
}
/**
* Get tags
*
* #return string
*/
public function getTags()
{
return $this->tags;
}
/**
* Set shoplogo
*
* #param Shopious\MainBundle\Entity\ShopLogo $shoplogo
* #return Shop
*/
public function setShoplogo(\Shopious\MainBundle\Entity\ShopLogo $shoplogo = null)
{
$this->shoplogo = $shoplogo;
return $this;
}
/**
* Get shoplogo
*
* #return Shopious\MainBundle\Entity\ShopLogo
*/
public function getShoplogo()
{
return $this->shoplogo;
}
/**
* Add testimonials
*
* #param \Shopious\MainBundle\Entity\ShopTestimonial $testimonials
* #return Shop
*/
public function addTestimonial(\Shopious\MainBundle\Entity\ShopTestimonial $testimonials)
{
$this->testimonials[] = $testimonials;
return $this;
}
/**
* Remove testimonials
*
* #param \Shopious\MainBundle\Entity\ShopTestimonial $testimonials
*/
public function removeTestimonial(\Shopious\MainBundle\Entity\ShopTestimonial $testimonials)
{
$this->testimonials->removeElement($testimonials);
}
/**
* Get testimonials
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getTestimonials()
{
return $this->testimonials;
}
/**
* Set isVisible
*
* #param boolean $isVisible
* #return Product
*/
public function setIsVisible($isVisible)
{
$this->isVisible = $isVisible;
return $this;
}
/**
* Get isVisible
*
* #return boolean
*/
public function getIsVisible()
{
return $this->isVisible;
}
}
Some code of fetching the data values:
public function getItemsAction()
{
try{
$query = $this->getRequest()->query;
$em = $this->getDoctrine()->getEntityManager();
$items = $em->getRepository('ShopiousMainBundle:Product')->filterBy(
$query->get('category'),
$query->get('tag'),
$query->get('size'),
$query->get('price'),
$query->get('shop'),
$query->get('sort'),
$query->get('page')
);
return $this->Json($items);
}catch(\Exception $ex){
return $this->Json($ex->getMessage(),false);
}
}
I am guessing it is because their is not data for the relationship. It looks like you probably have an item that you are calling a method on to get another object and then calling another method on that object to get yet another object. Since the first call is a proxy object it probably doesn't load the second proxy object data with it. If you look at the data in the data outside the template like in the controller I am guessing it isn't defined there. you might want to make sure that the data is loaded prior to getting to the view. I think that the root of the problem is the initial relationship.
To help you might post some of your controller code where you are getting fetching the data or setting the values.
sounds like class Owner's name is stored into variable "name", not "username"
i think protected $username; doesnot exist only protected $name;
if you want
"<%= '/profile/'+item.get('shop').owner.username %>">
then change
add this to you class first
protected $username[];
public function addUsers(User $user = null)
{
array_push($this->username, $user);
return $this->username;
}
public function getUsers()
{
return $this->username;
}
or a single user
protected $username;
public function addUsers(User $user = null)
{
$this->username= $user;
return $this->username;
}
public function getUsers()
{
return $this->username;
}

Doctrine2: ReflectionException' with message 'Class Comment does not exist in ...' while trying use doctrine models in codeigniter controller

I got "Message: class_parents(): Class Comment does not exist and could not be loaded" while trying to use Doctrine models in CodeIgniter controller.
Here is full stacktrace
Fatal error: Uncaught exception 'ReflectionException' with message 'Class Comment does not exist' in C:\Users\user\Desktop\projects\interview\application\libraries\Doctrine\Common\Persistence\Mapping\RuntimeReflectionService.php:73 Stack trace: #0 C:\Users\user\Desktop\projects\interview\application\libraries\Doctrine\Common\Persistence\Mapping\RuntimeReflectionService.php(73): ReflectionClass->__construct('Comment') #1 C:\Users\user\Desktop\projects\interview\application\libraries\Doctrine\ORM\Mapping\ClassMetadataInfo.php(769): Doctrine\Common\Persistence\Mapping\RuntimeReflectionService->getClass('Comment') #2 C:\Users\user\Desktop\projects\interview\application\libraries\Doctrine\ORM\Mapping\ClassMetadataFactory.php(591): Doctrine\ORM\Mapping\ClassMetadataInfo->initializeReflection(Object(Doctrine\Common\Persistence\Mapping\RuntimeReflectionService)) #3 C:\Users\user\Desktop\projects\interview\application\libraries\Doctrine\ORM\Mapping\ClassMetadataFactory.php(272): Doctrine\ORM\Mapping\ClassMetadataFactory->initializ in C:\Users\user\Desktop\projects\interview\application\libraries\Doctrine\Common\Persistence\Mapping\RuntimeReflectionService.php on line 73
Here is my model in /application/models/Entities/Comment.php
<?php
namespace Entities;
use Doctrine\ORM\Mapping as ORM;
/**
* Entities\Comment
*/
class Comment
{
/**
* #var integer $id
*/
private $id;
/**
* #var integer $parentid
*/
private $parentid;
/**
* #var integer $isactive
*/
private $isactive;
/**
* #var integer $isremoved
*/
private $isremoved;
/**
* #var datetime $removaldate
*/
private $removaldate;
/**
* #var string $user_name
*/
private $user_name;
/**
* #var string $user_email
*/
private $user_email;
/**
* #var string $user_avatar
*/
private $user_avatar;
/**
* #var text $comment
*/
private $comment;
/**
* #var datetime $creationdate
*/
private $creationdate;
/**
* #var integer $rating
*/
private $rating;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set parentid
*
* #param integer $parentid
* #return Comment
*/
public function setParentid($parentid)
{
$this->parentid = $parentid;
return $this;
}
/**
* Get parentid
*
* #return integer
*/
public function getParentid()
{
return $this->parentid;
}
/**
* Set isactive
*
* #param integer $isactive
* #return Comment
*/
public function setIsactive($isactive)
{
$this->isactive = $isactive;
return $this;
}
/**
* Get isactive
*
* #return integer
*/
public function getIsactive()
{
return $this->isactive;
}
/**
* Set isremoved
*
* #param integer $isremoved
* #return Comment
*/
public function setIsremoved($isremoved)
{
$this->isremoved = $isremoved;
return $this;
}
/**
* Get isremoved
*
* #return integer
*/
public function getIsremoved()
{
return $this->isremoved;
}
/**
* Set removaldate
*
* #param datetime $removaldate
* #return Comment
*/
public function setRemovaldate($removaldate)
{
$this->removaldate = $removaldate;
return $this;
}
/**
* Get removaldate
*
* #return datetime
*/
public function getRemovaldate()
{
return $this->removaldate;
}
/**
* Set user_name
*
* #param string $userName
* #return Comment
*/
public function setUserName($userName)
{
$this->user_name = $userName;
return $this;
}
/**
* Get user_name
*
* #return string
*/
public function getUserName()
{
return $this->user_name;
}
/**
* Set user_email
*
* #param string $userEmail
* #return Comment
*/
public function setUserEmail($userEmail)
{
$this->user_email = $userEmail;
return $this;
}
/**
* Get user_email
*
* #return string
*/
public function getUserEmail()
{
return $this->user_email;
}
/**
* Set user_avatar
*
* #param string $userAvatar
* #return Comment
*/
public function setUserAvatar($userAvatar)
{
$this->user_avatar = $userAvatar;
return $this;
}
/**
* Get user_avatar
*
* #return string
*/
public function getUserAvatar()
{
return $this->user_avatar;
}
/**
* Set comment
*
* #param text $comment
* #return Comment
*/
public function setComment($comment)
{
$this->comment = $comment;
return $this;
}
/**
* Get comment
*
* #return text
*/
public function getComment()
{
return $this->comment;
}
/**
* Set creationdate
*
* #param datetime $creationdate
* #return Comment
*/
public function setCreationdate($creationdate)
{
$this->creationdate = $creationdate;
return $this;
}
/**
* Get creationdate
*
* #return datetime
*/
public function getCreationdate()
{
return $this->creationdate;
}
/**
* Set rating
*
* #param integer $rating
* #return Comment
*/
public function setRating($rating)
{
$this->rating = $rating;
return $this;
}
/**
* Get rating
*
* #return integer
*/
public function getRating()
{
return $this->rating;
}
}
And here is controller's code
<?php
require APPPATH . 'models\Entities\Comment.php';
class CommentController extends CI_Controller{
var $em;
function __construct() {
parent::__construct();
$this->em = $this->doctrine->em;
}
public function index()
{
$comment = $this->em->find('Comment', 1);
echo $comment->user_name . '<br/>' . $comment->comment;
}
}
Here is doctrine.php
<?php
class Doctrine
{
// the Doctrine entity manager
public $em = null;
public function __construct()
{
// include our CodeIgniter application's database configuration
require_once APPPATH.'config/database.php';
// include Doctrine's fancy ClassLoader class
require_once APPPATH.'libraries/Doctrine/Common/ClassLoader.php';
// load the Doctrine classes
$doctrineClassLoader = new \Doctrine\Common\ClassLoader('Doctrine', APPPATH.'libraries');
$doctrineClassLoader->register();
// load Symfony2 helpers
// Don't be alarmed, this is necessary for YAML mapping files
$symfonyClassLoader = new \Doctrine\Common\ClassLoader('Symfony', APPPATH.'libraries/Doctrine');
$symfonyClassLoader->register();
// load the entities
$entityClassLoader = new \Doctrine\Common\ClassLoader('Entities', APPPATH.'models');
$entityClassLoader->register();
// load the proxy entities
$proxyClassLoader = new \Doctrine\Common\ClassLoader('Proxies', APPPATH.'models');
$proxyClassLoader->register();
// set up the configuration
$config = new \Doctrine\ORM\Configuration;
if(ENVIRONMENT == 'development')
// set up simple array caching for development mode
$cache = new \Doctrine\Common\Cache\ArrayCache;
else
// set up caching with APC for production mode
$cache = new \Doctrine\Common\Cache\ApcCache;
$config->setMetadataCacheImpl($cache);
$config->setQueryCacheImpl($cache);
// set up proxy configuration
$config->setProxyDir(APPPATH.'models/Proxies');
$config->setProxyNamespace('Proxies');
// auto-generate proxy classes if we are in development mode
$config->setAutoGenerateProxyClasses(ENVIRONMENT == 'development');
// set up annotation driver
$yamlDriver = new \Doctrine\ORM\Mapping\Driver\YamlDriver(APPPATH.'models\Mappings');
$config->setMetadataDriverImpl($yamlDriver);
// Database connection information
$connectionOptions = array(
'driver' => 'pdo_mysql',
'user' => $db['default']['username'],
'password' => $db['default']['password'],
'host' => $db['default']['hostname'],
'dbname' => $db['default']['database']
);
// create the EntityManager
$em = \Doctrine\ORM\EntityManager::create($connectionOptions, $config);
// store it as a member, for use in our CodeIgniter controllers.
$this->em = $em;
}
}
CAN'T FIND OUT WHAT IS GOING WRONG. I'm quite newbie on php and it's technologies. Please help. Any useful ideas will be appreciated
In strings, you always use the fully qualified class name.
This line has to be changed from
$comment = $this->em->find('Comment', 1);
To
$comment = $this->em->find('Entities\Comment', 1);

Categories