Symfony2 -从数据库中提取数据并以表单形式显示

时间:2021-02-03 09:52:20

I want to show the data on my forms but I am not able to do so.

我想在我的表格上显示数据,但是我不能这样做。

Here is my profile.php under userbundle:

这是我的资料。php userbundle下:

 <?php

namespace project\UserBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * Profile
 *
 * @ORM\Table(name="project_profiles")
 * @ORM\Entity
 * @ORM\HasLifecycleCallbacks
 */
class Profile
{
    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var \project\UserBundle\Entity\User
     *
     * @ORM\OneToOne(targetEntity="\project\UserBundle\Entity\User", inversedBy="profile")
     */
    private $user;

    /**
     * @var string
     *
     * @ORM\Column(name="first_name", type="string")
     */
    private $firstName;

    /**
     * @var string
     *
     * @ORM\Column(name="last_name", type="string")
     */
    private $lastName;

    /**
     * @var string
     *
     * @ORM\Column(name="address1", type="string")
     */
    private $address1;

    /**
     * @var string
     *
     * @ORM\Column(name="address2", type="string")
     */
    private $address2;

    /**
     * @var string
     *
     * @ORM\Column(name="city", type="string")
     */
    private $city;

    /**
     * @var string
     *
     * @ORM\Column(name="state", type="string")
     */
    private $state;

    /**
     * @var string
     *
     * @ORM\Column(name="zipcode", type="string")
     */
    private $zipcode;

    /**
     * @var string
     *
     * @ORM\Column(name="country", type="string")
     */
    private $country;

    /**
     * @var integer
     *
     * @ORM\Column(name="client_api_delay", type="integer")
     */
    private $clientApiDelay;

    /**
     * @var \DateTime
     *
     * @ORM\Column(name="created_at", type="datetime")
     */
    private $createdAt;

    /**
     * @var \DateTime
     *
     * @ORM\Column(name="updated_at", type="datetime", nullable=true)
     */
    private $updatedAt;

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set firstName
     *
     * @param string $firstName
     * @return Profile
     */
    public function setFirstName($firstName)
    {
        $this->firstName = $firstName;

        return $this;
    }

    /**
     * Get firstName
     *
     * @return string
     */
    public function getFirstName()
    {
        return $this->firstName;
    }

    /**
     * Set lastName
     *
     * @param string $lastName
     * @return Profile
     */
    public function setLastName($lastName)
    {
        $this->lastName = $lastName;

        return $this;
    }

    /**
     * Get lastName
     *
     * @return string
     */
    public function getLastName()
    {
        return $this->lastName;
    }

    /**
     * Set address1
     *
     * @param string $address1
     * @return Profile
     */
    public function setAddress1($address1)
    {
        $this->address1 = $address1;

        return $this;
    }

    /**
     * Get address1
     *
     * @return string
     */
    public function getAddress1()
    {
        return $this->address1;
    }

    /**
     * Set address2
     *
     * @param string $address2
     * @return Profile
     */
    public function setAddress2($address2)
    {
        $this->address2 = $address2;

        return $this;
    }

    /**
     * Get address2
     *
     * @return string
     */
    public function getAddress2()
    {
        return $this->address2;
    }

    /**
     * Set city
     *
     * @param string $city
     * @return Profile
     */
    public function setCity($city)
    {
        $this->city = $city;

        return $this;
    }

    /**
     * Get city
     *
     * @return string
     */
    public function getCity()
    {
        return $this->city;
    }

    /**
     * Set state
     *
     * @param string $state
     * @return Profile
     */
    public function setState($state)
    {
        $this->state = $state;

        return $this;
    }

    /**
     * Get state
     *
     * @return string
     */
    public function getState()
    {
        return $this->state;
    }

    /**
     * Set zipcode
     *
     * @param string $zipcode
     * @return Profile
     */
    public function setZipcode($zipcode)
    {
        $this->zipcode = $zipcode;

        return $this;
    }

    /**
     * Get zipcode
     *
     * @return string
     */
    public function getZipcode()
    {
        return $this->zipcode;
    }

    /**
     * Set country
     *
     * @param string $country
     * @return Profile
     */
    public function setCountry($country)
    {
        $this->country = $country;

        return $this;
    }

    /**
     * Get country
     *
     * @return string
     */
    public function getCountry()
    {
        return $this->country;
    }

    /**
     * Set clientApiDelay
     *
     * @param integer $clientApiDelay
     * @return Profile
     */
    public function setClientApiDelay($clientApiDelay)
    {
        $this->clientApiDelay = $clientApiDelay;

        return $this;
    }

    /**
     * Get clientApiDelay
     *
     * @return integer
     */
    public function getClientApiDelay()
    {
        return $this->clientApiDelay;
    }

    /**
     * Set createdAt
     *
     * @param \DateTime $createdAt
     * @return Profile
     */
    public function setCreatedAt($createdAt)
    {
        $this->createdAt = $createdAt;

        return $this;
    }

    /**
     * Get createdAt
     *
     * @return \DateTime
     */
    public function getCreatedAt()
    {
        return $this->createdAt;
    }

    /**
     * Set createdAt to NOW
     *
     * @return Profile
     * @ORM\PrePersist
     */
    public function setCreatedAtNow()
    {
        $this->createdAt = new \DateTime();

        return $this;
    }

    /**
     * Set updatedAt
     *
     * @param \DateTime $updatedAt
     * @return Profile
     */
    public function setUpdatedAt($updatedAt)
    {
        $this->updatedAt = $updatedAt;

        return $this;
    }

    /**
     * Get updatedAt
     *
     * @return \DateTime
     */
    public function getUpdatedAt()
    {
        return $this->updatedAt;
    }

    /**
     * Set updatedAt to NOW
     *
     * @return Profile
     * @ORM\PreUpdate
     */
    public function setUpdatedAtNow()
    {
        $this->updatedAt = new \DateTime();

        return $this;
    }

    /**
     * Set user
     *
     * @param \project\UserBundle\Entity\User $user
     * @return Profile
     */
    public function setUser(\project\UserBundle\Entity\User $user = null)
    {
        $this->user = $user;

        return $this;
    }

    /**
     * Get user
     *
     * @return \project\UserBundle\Entity\User
     */
    public function getUser()
    {
        return $this->user;
    }
}

My ProfileController.php file:

我的ProfileController。php文件:

<?php

namespace project\UserBundle\Controller;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use project\UserBundle\Entity\Profile;
use project\UserBundle\Form\ProfileType;

/**
 * Profile controller.
 *
 * @Route("/admin/profile")
 */
class ProfileController extends Controller
{
    /**
     * Lists all Profile entities.
     *
     * @Route("/", name="admin_profile")
     * @Method("GET")
     * @Template()
     */
    public function indexAction()
    {
        $em = $this->getDoctrine()->getManager();

        $entities = $em->getRepository('projectUserBundle:Profile')->findAll();

        return array(
            'entities' => $entities,
        );
    }

    /**
     * Creates a new Profile entity.
     *
     * @Route("/", name="admin_profile_create")
     * @Method("POST")
     * @Template("projectUserBundle:Profile:new.html.twig")
     */
    public function createAction(Request $request)
    {
        $entity  = new Profile();
        $form = $this->createForm(new ProfileType(), $entity);
        $form->bind($request);

        if ($form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $em->persist($entity);
            $em->flush();

            return $this->redirect($this->generateUrl('admin_profile_show', array('id' => $entity->getId())));
        }

        return array(
            'entity' => $entity,
            'form'   => $form->createView(),
        );
    }

    /**
     * Displays a form to create a new Profile entity.
     *
     * @Route("/new", name="admin_profile_new")
     * @Method("GET")
     * @Template()
     */
    public function newAction()
    {
        $entity = new Profile();
        $form   = $this->createForm(new ProfileType(), $entity);

        return array(
            'entity' => $entity,
            'form'   => $form->createView(),
        );
    }

    /**
     * Finds and displays a Profile entity.
     *
     * @Route("/{id}", name="admin_profile_show")
     * @Method("GET")
     * @Template()
     */
    public function showAction($id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('projectUserBundle:Profile')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Profile entity.');
        }

        $deleteForm = $this->createDeleteForm($id);

        return array(
            'entity'      => $entity,
            'delete_form' => $deleteForm->createView(),
        );
    }

    /**
     * Displays a form to edit an existing Profile entity.
     *
     * @Route("/{id}/edit", name="admin_profile_edit")
     * @Method("GET")
     * @Template()
     */
    public function editAction($id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('projectUserBundle:Profile')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Profile entity.');
        }

        $editForm = $this->createForm(new ProfileType(), $entity);
        $deleteForm = $this->createDeleteForm($id);

        return array(
            'entity'      => $entity,
            'edit_form'   => $editForm->createView(),
            'delete_form' => $deleteForm->createView(),
        );
    }

    /**
     * Edits an existing Profile entity.
     *
     * @Route("/{id}", name="admin_profile_update")
     * @Method("PUT")
     * @Template("projectUserBundle:Profile:edit.html.twig")
     */
    public function updateAction(Request $request, $id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('projectUserBundle:Profile')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Profile entity.');
        }

        $deleteForm = $this->createDeleteForm($id);
        $editForm = $this->createForm(new ProfileType(), $entity);
        $editForm->bind($request);

        if ($editForm->isValid()) {
            $em->persist($entity);
            $em->flush();

            return $this->redirect($this->generateUrl('admin_profile_edit', array('id' => $id)));
        }

        return array(
            'entity'      => $entity,
            'edit_form'   => $editForm->createView(),
            'delete_form' => $deleteForm->createView(),
        );
    }

    /**
     * Deletes a Profile entity.
     *
     * @Route("/{id}", name="admin_profile_delete")
     * @Method("DELETE")
     */
    public function deleteAction(Request $request, $id)
    {
        $form = $this->createDeleteForm($id);
        $form->bind($request);

        if ($form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $entity = $em->getRepository('projectUserBundle:Profile')->find($id);

            if (!$entity) {
                throw $this->createNotFoundException('Unable to find Profile entity.');
            }

            $em->remove($entity);
            $em->flush();
        }

        return $this->redirect($this->generateUrl('admin_profile'));
    }

    /**
     * Creates a form to delete a Profile entity by id.
     *
     * @param mixed $id The entity id
     *
     * @return Symfony\Component\Form\Form The form
     */
    private function createDeleteForm($id)
    {
        return $this->createFormBuilder(array('id' => $id))
            ->add('id', 'hidden')
            ->getForm()
        ;
    }
}

I have declared my entities under Resources/Profile/show.html and everything works: For example for address I have:

我已在资源/概要/显示项下声明我的实体。html和一切工作:例如我的地址:

<th>Address2</th>
<td>{{ entity.address2 }}</td>

My problem is I have another bundle called ShowBundle and I want to show those entities on that bunddle. For e.g When I call {{ entity.address2 }} on that bundle to show my address it shows me that: (variable "entity" doesnt exist)

我的问题是我有另一个叫做ShowBundle的bundle我想在这个bunddle上显示这些实体。为e。当我调用{{entity。在那个bundle上address2}显示我的地址它显示:(变量“entity”不存在)

How I can display those profile entities on the twig forms in another bundle, in my case ShowBundle?

如何在另一个bundle中显示这些概要实体?

Thanks a lot

非常感谢

1 个解决方案

#1


3  

Of course you can use {{ app.user.variablename }} which is a global. But for other variable, a view can only display the data the controller send to it. That's the MVC (Model-View-Controller) architecture.

当然,您可以使用{{app.user}。是一个全局变量。但是对于其他变量,视图只能显示控制器发送给它的数据。这就是MVC(模型-视图-控制器)架构。

Variable entity exist in the Twig view only if your controller send it to the view. That's what the lines return array( 'entities' => $entities ); do on your ProfileController.php, and that's why you can use it in Resources/Profile/show.html.

只有当控制器将变量实体发送到视图时,该变量实体才存在于Twig视图中。这就是行返回的数组('entities' => $entities);做你的ProfileController。这就是为什么您可以在参考资料/概要文件/show.html中使用它。

If you want to display an entity in another bundle, just pull it from the database and send it to the view the same way you do in your ProfileController.php. If you wrote yourself the code you posted, that should be an easy task.

如果您想在另一个包中显示实体,只需从数据库中提取实体并将其发送到视图,就像您在ProfileController.php中所做的那样。如果您自己编写了所发布的代码,那么这应该是一项简单的任务。

If you do not understand the code you posted, I suggest you learn to use Symfony. You can read the Book, which is excellent step-by-step documentation.

如果您不理解您所发布的代码,我建议您学习使用Symfony。你可以阅读这本书,它是极好的一步一步的文档。

Tips :

小贴士:

copy-past this code in your other bundle controllers (the methods ending with Action()) :

在其他bundle控制器(以Action()结尾的方法)中复制通过此代码:

$em = $this->getDoctrine()->getManager(); //get the database manager

$profiles = $em->getRepository('projectUserBundle:Profile')->findAll(); // get the profiles

return array(
        'profiles' => $profiles,
    ); // send data to the view

You will access your profiles through {{ profiles }} in your templates.

您将通过模板中的{{{{profiles}访问您的概要文件。

#1


3  

Of course you can use {{ app.user.variablename }} which is a global. But for other variable, a view can only display the data the controller send to it. That's the MVC (Model-View-Controller) architecture.

当然,您可以使用{{app.user}。是一个全局变量。但是对于其他变量,视图只能显示控制器发送给它的数据。这就是MVC(模型-视图-控制器)架构。

Variable entity exist in the Twig view only if your controller send it to the view. That's what the lines return array( 'entities' => $entities ); do on your ProfileController.php, and that's why you can use it in Resources/Profile/show.html.

只有当控制器将变量实体发送到视图时,该变量实体才存在于Twig视图中。这就是行返回的数组('entities' => $entities);做你的ProfileController。这就是为什么您可以在参考资料/概要文件/show.html中使用它。

If you want to display an entity in another bundle, just pull it from the database and send it to the view the same way you do in your ProfileController.php. If you wrote yourself the code you posted, that should be an easy task.

如果您想在另一个包中显示实体,只需从数据库中提取实体并将其发送到视图,就像您在ProfileController.php中所做的那样。如果您自己编写了所发布的代码,那么这应该是一项简单的任务。

If you do not understand the code you posted, I suggest you learn to use Symfony. You can read the Book, which is excellent step-by-step documentation.

如果您不理解您所发布的代码,我建议您学习使用Symfony。你可以阅读这本书,它是极好的一步一步的文档。

Tips :

小贴士:

copy-past this code in your other bundle controllers (the methods ending with Action()) :

在其他bundle控制器(以Action()结尾的方法)中复制通过此代码:

$em = $this->getDoctrine()->getManager(); //get the database manager

$profiles = $em->getRepository('projectUserBundle:Profile')->findAll(); // get the profiles

return array(
        'profiles' => $profiles,
    ); // send data to the view

You will access your profiles through {{ profiles }} in your templates.

您将通过模板中的{{{{profiles}访问您的概要文件。