【问题标题】:how to use a selectbox to fetch data from database row symfony2如何使用选择框从数据库行 symfony2 中获取数据
【发布时间】:2016-05-01 15:45:44
【问题描述】:

我目前正在 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 %}

因此,通过控制器中的一个简单代码,我设法获得了按位置订购的产品。

所以对我来说最后一步是使用选择框按位置显示产品,并从列表中“删除”具有其他位置的产品。下图是我目前的结果,我想要这个列表上方的选择框。希望有人能帮帮我..

【问题讨论】:

    标签: php mysql symfony doctrine twig


    【解决方案1】:

    您可以使用调用 AJAX 来调用另一个控制器 SF,该控制器使用新的 JSON 数据过滤您的结果和响应。

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

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

    【讨论】:

      【解决方案2】:

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

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

      但是,我最终发现这个解决方案相当“繁重”,因为您必须经历整个表单提交过程才能获得产品列表。为了改善这一点,您可以创建一个控制器操作,该操作将根据位置返回产品列表,并在位置更改时调用此路由。

      但在这两种情况下,AJAX 和表单事件监听器都是强制性的。

      【讨论】:

      • 好吧,那么没有其他方法可以做到这一点吗?用树枝还是 PHP?不幸的是,我对 AJAX 没有经验..
      • 对不起,我说过这是强制性的。 Twig 和 PHP 只能对您的后端产生影响,但您希望在客户端的 Web 浏览器中提供一些动态的东西。因此,您需要使用 JavaScript,并且需要 AJAX 从您的服务器获取产品列表。但总是要学习:)
      • 哈哈好吧,这是正确的答案,我还有很多东西要学习.. 无论如何谢谢:)
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多