如何使用selectbox从数据库行symfony2中获取数据

时间:2016-01-25 10:52:50

标签: php mysql symfony doctrine twig

我目前正在使用symfony2中的一个小项目。我用crud命令创建了一个简单的表。我有一个名为“voorraad”(= stock)的实体,它与实体“product”和实体“Locatie”(= Location)有关联。工作原理:我可以在我的库存中添加产品和位置。

所以我的问题是,我无法弄清楚如何使用选择框按位置显示我的库存中的产品。我们的想法是让一个选择框包含来自我的位置实体的位置,如果我选择一个选项,它只会显示我选项的产品。在我的代码下面:

控制器

<?php

 namespace ToolsForEver\VoorraadBundle\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 ToolsForEver\VoorraadBundle\Entity\Voorraad;
 use ToolsForEver\VoorraadBundle\Form\VoorraadType;
 use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security;

/**
 * Voorraad controller.
 *
 * @Route("/voorraad")
 */
class VoorraadController extends Controller
{

/**
 * Lists all Voorraad entities.
 *
 * @Route("/", name="voorraad")
 * @Method("GET")
 * @Template()
 * @Security("has_role('ROLE_USER')")
 */
public function indexAction()
{
    $em = $this->getDoctrine()->getManager();

    $entities = $em->getRepository('ToolsForEverVoorraadBundle:Voorraad')->findBy(array(), array('locatie'=>'asc'));

    return array(
        'entities' => $entities,
    );
}
/**
 * Creates a new Voorraad entity.
 *
 * @Route("/", name="voorraad_create")
 * @Method("POST")
 * @Template("ToolsForEverVoorraadBundle:Voorraad:new.html.twig")
 */
public function createAction(Request $request)
{
    $entity = new Voorraad();
    $form = $this->createCreateForm($entity);
    $form->handleRequest($request);

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

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

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

/**
 * Creates a form to create a Voorraad entity.
 *
 * @param Voorraad $entity The entity
 *
 * @return \Symfony\Component\Form\Form The form
 */
private function createCreateForm(Voorraad $entity)
{
    $form = $this->createForm(new VoorraadType(), $entity, array(
        'action' => $this->generateUrl('voorraad_create'),
        'method' => 'POST',
    ));

    $form->add('submit', 'submit', array('label' => 'Create'));

    return $form;
}

/**
 * Displays a form to create a new Voorraad entity.
 *
 * @Route("/new", name="voorraad_new")
 * @Method("GET")
 * @Template()
 * @Security("has_role('ROLE_USER')")
 */
public function newAction()
{
    $entity = new Voorraad();
    $form   = $this->createCreateForm($entity);

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

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

    $entity = $em->getRepository('ToolsForEverVoorraadBundle:Voorraad')->find($id);

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

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

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

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

    $entity = $em->getRepository('ToolsForEverVoorraadBundle:Voorraad')->find($id);

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

    $editForm = $this->createEditForm($entity);
    $deleteForm = $this->createDeleteForm($id);

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

/**
* Creates a form to edit a Voorraad entity.
*
* @param Voorraad $entity The entity
*
* @return \Symfony\Component\Form\Form The form
*/
private function createEditForm(Voorraad $entity)
{
    $form = $this->createForm(new VoorraadType(), $entity, array(
        'action' => $this->generateUrl('voorraad_update', array('id' => $entity->getId())),
        'method' => 'PUT',
    ));

    $form->add('submit', 'submit', array('label' => 'Update'));

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

    $entity = $em->getRepository('ToolsForEverVoorraadBundle:Voorraad')->find($id);

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

    $deleteForm = $this->createDeleteForm($id);
    $editForm = $this->createEditForm($entity);
    $editForm->handleRequest($request);

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

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

    return array(
        'entity'      => $entity,
        'edit_form'   => $editForm->createView(),
        'delete_form' => $deleteForm->createView(),
    );
}
/**
 * Deletes a Voorraad entity.
 *
 * @Route("/{id}", name="voorraad_delete")
 * @Method("DELETE")
 */
public function deleteAction(Request $request, $id)
{
    $form = $this->createDeleteForm($id);
    $form->handleRequest($request);

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

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

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

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

/**
 * Creates a form to delete a Voorraad entity by id.
 *
 * @param mixed $id The entity id
 *
 * @return \Symfony\Component\Form\Form The form
 */
private function createDeleteForm($id)
{
    return $this->createFormBuilder()
        ->setAction($this->generateUrl('voorraad_delete', array('id' => $id)))
        ->setMethod('DELETE')
        ->add('submit', 'submit', array('label' => 'Verwijder voorraad'))
        ->getForm()
    ;
}
}

VoorraadType.php(表格)

<?php

namespace ToolsForEver\VoorraadBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

class VoorraadType extends AbstractType
{
/**
 * @param FormBuilderInterface $builder
 * @param array $options
 */
public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
        ->add('aantal')
        ->add('locatie', 'entity', array (
        'empty_data' => null,
        'label' => 'Kies locatie',
        'class' => 'ToolsForEver\VoorraadBundle\Entity\Locatie',
        'choice_label' => function ($locatie) {
            return $locatie->getLocatienaam();
        }


        ))
        ->add('product', 'entity', array(
        'empty_data' => null,
        'label' => 'Kies product',
        'class' => 'ToolsForEver\VoorraadBundle\Entity\Product',
        'choice_label' => function ($product) {
            return $product->getNaam();
        }
        ))
    ;
}

/**
 * @param OptionsResolverInterface $resolver
 */
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
    $resolver->setDefaults(array(
        'data_class' => 'ToolsForEver\VoorraadBundle\Entity\Voorraad'
    ));
}

/**
 * @return string
 */
public function getName()
{
    return 'toolsforever_voorraadbundle_voorraad';
}
}

index.html.twig(查看)

{% extends '::base.html.twig' %}

{% block body -%}
<h1 class="hoofdtitel">Voorraad lijst</h1>

<table class="records_list">
    <thead>
        <tr>
            <!-- <th>Id</th> -->
            <th>Product</th>
            <th>Type</th>
            <th>Fabriek</th>
            <th>Aantal</th>
            <th>Inkoopprijs</th>
            <th>Verkoopprijs
            <th>Locatie</th>
            <th>Actions</th>
        </tr>
    </thead>
    <tbody>
    {% for entity in entities %}
        <tr>
    <!--    <td><a href="{{ path('voorraad_show', { 'id': entity.id }) }}">{{ entity.id }}</a></td> -->
            <td>{{ entity.getProduct().getNaam() }}</td>
            <td>{{ entity.getProduct().getType() }}</td>
            <td>{{ entity.getProduct().getFabriek() }}</td>
            <td>{{ entity.aantal }}</td>
            <td>{{ entity.getProduct().getInkoopprijs() }}</td>
            <td>{{ entity.getProduct().getVerkoopprijs() }}</td>
            <td>{{ entity.getLocatie().getLocatienaam() }}</td>
            <td>

                    <a href="{{ path('voorraad_edit', { 'id': entity.id }) }}">Voorraad aanpassen</a>

            </td>
        </tr>
    {% endfor %}
    </tbody>
</table>
        <br>
        <a href="{{ path('voorraad_new') }}">
            Nieuwe voorraad toevoegen   
        </a>

{% endblock %}

因此,在我的控制器中使用简单的代码,我设法按位置订购产品。

因此,对我而言,最后一步是使用选择框按位置显示产品,并使用其他位置从列表中“删除”产品。下面的图片是我到目前为止的结果,我希望此列表上方的选择框。希望有人可以帮助我..

So far..

2 个答案:

答案 0 :(得分:3)

您可以使用调用AJAX来调用其他控制器SF,它使用新的JSON数据过滤您的结果和响应。

如果您的回答AJAX是正确的,您可以移动旧结果并使用JS添加新的HTML代码格式以查看结果选择框。

AJAX +控制器SF =更改结果网页而不重新加载

答案 1 :(得分:2)

Symfony Cookbook提供了一个示例:http://symfony.com/doc/current/cookbook/form/dynamic_form_modification.html#dynamic-generation-for-submitted-forms

基本上,您需要使用“entity”字段的query_builder属性来根据位置限制您的产品。然后,当用户更改Location的值时,创建一个JS脚本,该脚本将在异步侧请求中提交表单,在响应中获取Products的选择框并在页面内替换它。您还需要在表单中使用EventListeners来动态更新字段。

但是,我发现这个解决方案最终非常“沉重”,因为您必须完成整个表单提交过程才能获得产品列表。要改进这一点,您可以创建一个Controller Action,它将根据Location返回Products列表,并在Location更改时调用此路由。

但在这两种情况下,AJAX和Form EventListeners都是必需的。