json_array不适用于entitytype表单

时间:2016-08-18 15:35:10

标签: php symfony

我使用symfony2。我有一个应该插入json_array的表单,但它不起作用。

My Form Pedido取决于三张桌子,Produto,Subproduto,Comanda。 \

一个Pedido应该是这样的:

id
Quantidade (amount)
Produto_id ( one per data )
Comanda_id ( one per data )
subpedidos ( many Subproduto, json_array, 

{"subprodutoid":1,"subprodutoid":2,"subprodutoid":3}. if do that is good. This is my problem 1.

My problem 2 is how i made generate one field Quantidade for each checkbox generate before. Sample, if the table has 3 item(entitytype subproduto) Coca-Cola, juice, water(checkboxes generate automatic), then i need generate three field quantidade for reach, input#quantidade-coca_cola, input#quantidade-juice, input#quantidade-water. Now the form generate one field quantidade only. If fix my problem i need order the Pedido like 
{"5":2,"3":1,"1":3} mean {"subprodutoid":"quantidade", "subprodutoid":"quantidade"}

我希望这样,以避免仅针对subprodutos的大数据。

关注可能页面:

<?php

namespace AppBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * Pedido
 *
 * @ORM\Table(name="pedido")
 *   @ORM\Entity(repositoryClass="AppBundle\Repository\PedidoRepository")
 */
class Pedido
{
/**
 * @var int
 *
 * @ORM\Column(name="id", type="integer")
 * @ORM\Id
 * @ORM\GeneratedValue(strategy="AUTO")
 */
private $id;

/**
 * @var int
 *
 * @ORM\Column(name="quantidade", type="smallint")
 */
private $quantidade=1;

/**
 * @var int
 *
 * @ORM\Column(name="prioridade", type="smallint")
 */
private $prioridade=0;

/**
 * @var int
 *
 * @ORM\Column(name="confirmacao", type="smallint")
 */
private $confirmacao=0;

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

/**
 * @var string
 *
 * @ORM\Column(name="final", type="string", length=8, nullable=true)
 */
private $final;

/**
 * @ORM\Column(name="subpedidos", type="json_array", length=255, nullable=true)
 */
private $subpedidos;

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

/**
 * @ORM\ManyToOne(targetEntity="Produto", inversedBy="pedidos")
 * @ORM\JoinColumn(name="produto_id", referencedColumnName="id")
 */
protected $produto;

/**
 * @ORM\ManyToOne(targetEntity="Comanda", inversedBy="pedidos")
 * @ORM\JoinColumn(name="comanda_id", referencedColumnName="id")
 */
protected $comanda;

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

/**
 * Set quantidade
 *
 * @param integer $quantidade
 *
 * @return Pedido
 */
public function setQuantidade($quantidade)
{
    $this->quantidade = $quantidade;

    return $this;
}

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

/**
 * Set prioridade
 *
 * @param integer $prioridade
 *
 * @return Pedido
 */
public function setPrioridade($prioridade)
{
    $this->prioridade = $prioridade;

    return $this;
}

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

/**
 * Set confirmacao
 *
 * @param integer $confirmacao
 *
 * @return Pedido
 */
public function setConfirmacao($confirmacao)
{
    $this->confirmacao = $confirmacao;

    return $this;
}

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

/**
 * Set inicio
 *
 * @param string $inicio
 *
 * @return Pedido
 */
public function setInicio($inicio)
{
    $this->inicio = $inicio;

    return $this;
}

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

/**
 * Set final
 *
 * @param string $final
 *
 * @return Pedido
 */
public function setFinal($final)
{
    $this->final = $final;

    return $this;
}

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

/**
 * Set subpedidos
 *
 * @param array $subpedidos
 *
 * @return Pedido
 */
public function setSubpedidos($subpedidos)
{
    $this->subpedidos = $subpedidos;

    return $this;
}

/**
 * Get subpedidos
 *
 * @return array
 */
public function getSubpedidos()
{
    return $this->subpedidos;
}

/**
 * Set levar
 *
 * @param integer $levar
 *
 * @return Pedido
 */
public function setLevar($levar)
{
    $this->levar = $levar;

    return $this;
}

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

/**
 * Set produto
 *
 * @param \AppBundle\Entity\Produto $produto
 *
 * @return Pedido
 */
public function setProduto(\AppBundle\Entity\Produto $produto = null)
{
    $this->produto = $produto;

    return $this;
}

/**
 * Get produto
 *
 * @return \AppBundle\Entity\Produto
 */
public function getProduto()
{
    return $this->produto;
}

/**
 * Set comanda
 *
 * @param \AppBundle\Entity\Comanda $comanda
 *
 * @return Pedido
 */
public function setComanda(\AppBundle\Entity\Comanda $comanda = null)
{
    $this->comanda = $comanda;

    return $this;
}

/**
 * Get comanda
 *
 * @return \AppBundle\Entity\Comanda
 */
public function getComanda()
{
    return $this->comanda;
}

/**
 * @return string
 */
public function __toString()
{
    return $this->subpedidos;
}
}

PedidoType.php

<?php

namespace AppBundle\Form;

use AppBundle\Form\Type\SubpedidoType;
use Doctrine\ORM\EntityRepository;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;

class PedidoType extends AbstractType
{
/**
 * @param FormBuilderInterface $builder
 * @param array $options
 */
public function buildForm(FormBuilderInterface $builder, array $options)
{
    $id = $options['id'];
    $idcategoria = $options['idcategoria'];
    $subcategorias = $options['subcategorias'];

    $builder
        ->add('produto',EntityType::class, array(
            'class'=>'AppBundle:Produto',
            'expanded'=>true,
            'multiple'=>false,
            'label'=>false,
            'choice_label'=> function($produto){
                return $produto->getDescricao(). ' '. $produto->getValor();
            },
            'query_builder' => function(EntityRepository $er) use ( $idcategoria ){
                return $er->createQueryBuilder('u') //set repository categoria
                ->where('u.categoria = ?1') // compara categoria.id = id passado como parametro
                ->setParameter(1, $idcategoria); // identifica a variavel
            }
        ))
        ->add('subpedidos',EntityType::class, array(
            'class'=>'AppBundle:Subproduto',
            'expanded'=>true,
            'multiple'=>true,
            'label'=>false,
            'choice_label'=>function($subproduto){
                return $subproduto->getDescricao(). ' '. $subproduto->getValor();
            },
            'query_builder' => function(EntityRepository $er) use ( $subcategorias ){
                return $this->querySubcategorias($subcategorias, $er);
            }
        ))
        ->add('levar', ChoiceType::class,
            array(
                'choices'=>array(' P/ Viagem'=>0),
                'expanded'=>true,
                'multiple'=>true,
                'label'=>false,
            ))
        ->add('comanda', EntityType::class, array(
            'class'=>'AppBundle:Comanda',
            'label'=>false,
            'choice_label'=>'cliente',
            'query_builder' => function(EntityRepository $er) use ( $id ){
                return $er->createQueryBuilder('u') //set repository categoria
                ->where('u.id = ?1') // compara categoria.id = id passado como parametro
                ->setParameter(1, $id); // identifica a variavel
            }
        ))
    ;
}

/**
 * @param OptionsResolver $resolver
 */
public function configureOptions(OptionsResolver $resolver)
{
    $resolver->setDefaults(array(
        'data_class' => 'AppBundle\Entity\Pedido',
        'id'=>null,
        'idcategoria'=>null,
        'subcategorias'=>null,
    ));
}

/**
 * @param $subcategorias, $er
 * Funcao que monta a query para filtrar as subcategorias existentes na categoria listada no pedido
 */
public function querySubcategorias($subcategorias, $er){
    $query = $er->createQueryBuilder('u'); //set repository categoria
    $count = 1;
    //na primeira montagem eh Where as demais andWhere
    foreach($subcategorias as $subcategoria){
        if($count<2)
            $query->where('u.subcategoria = ?'.$count)->setParameter($count,$subcategoria);
        else
            $query->orWhere('u.subcategoria =?'.$count)->setParameter($count,$subcategoria);
        $count++;
    }

    return $query;
}
}

PedidoController.php

<?php

namespace AppBundle\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 AppBundle\Entity\Pedido;
use AppBundle\Form\PedidoType;

/**
 * Pedido controller.
 *
 * @Route("/pedido")
 */
class PedidoController extends Controller
{
/**
 * Lists all Pedido entities.
 *
 * @Route("/", name="pedido_index")
 * @Method("GET")
 */
public function indexAction()
{
    $em = $this->getDoctrine()->getManager();

    $pedidos = $em->getRepository('AppBundle:Pedido')->findAll();

    return $this->render('pedido/index.html.twig', array(
        'pedidos' => $pedidos,
    ));
}

/**
 * Mostra as opcoes do Menu
 * Id da Comanda eh passado p/ o novo pedido
 * @Route("/menu/{id}", name="pedido_index")
 * @Method({"GET", "POST"})
 */
public function newAction(Request $request, $id)
{
    $em = $this->getDoctrine()->getManager();

    $categoria = $em->getRepository('AppBundle:Categoria')->findByAtivo(1);

    return $this->render('pedido/opcoesMenu.html.twig', array(
        'categorias'=> $categoria,
        'id'=>$id,
    ));
}

/**
 * Creates a new Pedido entity.
 * Id da Comanda eh passado p/ o novo pedido
 * Id da Categoria eh passado p/ o novo pedido
 * @Route("/new/{id}/{idcategoria}", name="pedido_categoria")
 * @Method({"GET", "POST"})
 */
public function byCategoriaAction(Request $request, $id, $idcategoria)
{
    $pedido = new Pedido();
    $em = $this->getDoctrine()->getManager();
    //busca todas as categorias ativas para listar no menu lateral
    $categoria = $em->getRepository('AppBundle:Categoria')->findByAtivo(1);

    //busca todas as subcategorias da categoria escolhida
    $subcategoria = $em->getRepository('AppBundle:Subcategoria')->findBy(
        array('categoria'=>$idcategoria, 'ativo'=>1,));

    $form = $this->createForm('AppBundle\Form\PedidoType', $pedido, array(
        'id'=>$id,
        'idcategoria'=>$idcategoria,
        'subcategorias'=>$subcategoria,
    ));

    dump($form->all());
    exit;
    $form->handleRequest($request);

    if ($form->isSubmitted() && $form->isValid()) {
        $pedido->setInicio(date("H:i:s"));
        $em = $this->getDoctrine()->getManager();
        $em->persist($pedido);
        $em->flush();

        return $this->redirectToRoute('pedido_show', array('id' => $pedido->getId()));
    }

    return $this->render('pedido/new.html.twig', array(
        'form' => $form->createView(),
        'categorias'=> $categoria,
        'idcategoria'=>$idcategoria,
        'id'=>$id,
        'subcategorias'=>$subcategoria,
    ));
}

/**
 * Finds and displays a Pedido entity.
 *
 * @Route("/{id}", name="pedido_show")
 * @Method("GET")
 */
public function showAction(Pedido $pedido)
{
    $deleteForm = $this->createDeleteForm($pedido);

    return $this->render('pedido/show.html.twig', array(
        'pedido' => $pedido,
        'delete_form' => $deleteForm->createView(),
    ));
}

/**
 * Displays a form to edit an existing Pedido entity.
 *
 * @Route("/{id}/edit", name="pedido_edit")
 * @Method({"GET", "POST"})
 */
public function editAction(Request $request, Pedido $pedido)
{
    $deleteForm = $this->createDeleteForm($pedido);
    $editForm = $this->createForm('AppBundle\Form\PedidoType', $pedido);
    $editForm->handleRequest($request);

    if ($editForm->isSubmitted() && $editForm->isValid()) {
        $em = $this->getDoctrine()->getManager();
        $em->persist($pedido);
        $em->flush();

        return $this->redirectToRoute('pedido_edit', array('id' => $pedido->getId()));
    }

    return $this->render('pedido/edit.html.twig', array(
        'pedido' => $pedido,
        'edit_form' => $editForm->createView(),
        'delete_form' => $deleteForm->createView(),
    ));
}

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

    if ($form->isSubmitted() && $form->isValid()) {
        $em = $this->getDoctrine()->getManager();
        $em->remove($pedido);
        $em->flush();
    }

    return $this->redirectToRoute('pedido_index');
}

/**
 * Creates a form to delete a Pedido entity.
 *
 * @param Pedido $pedido The Pedido entity
 *
 * @return \Symfony\Component\Form\Form The form
 */
private function createDeleteForm(Pedido $pedido)
{
    return $this->createFormBuilder()
        ->setAction($this->generateUrl('pedido_delete', array('id' => $pedido->getId())))
        ->setMethod('DELETE')
        ->getForm()
    ;
}
}

新数据页面

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

{% block title %}
    Comanda Aberta
{% endblock %}

{% block body %}
 <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<link rel="stylesheet" href="{{ asset('bundles/app/css/style.css') }}" />
<script src="{{ asset('bundles/app/js/jquery.min.js') }}" type="application/javascript"></script>
<script src="{{ asset('bundles/app/js/style.js') }}" type="application/javascript"></script>

<header>
    <span class="menu-anchor"></span>
    <h1><- Novo Pedido</h1>
</header>
<menu>
    <ul>
        {% set descricao = 'Categoria' %}
        {% for categoria in categorias %}
        <li><a href=" {{ path('pedido_categoria', { id: id, idcategoria: categoria.id }) }}">{{ categoria.descricao }}</a></li>
            {% if idcategoria == categoria.id %}
                {% set descricao = categoria.descricao %}
            {% endif %}
        {% endfor %}
    </ul>
</menu>
<section class="main">
    <fieldset id="listaOpcoes">
        {{ form_start(form) }}
        {{ form_row(form.comanda) }}
        <fieldset>
            <legend>{{ descricao }}</legend>
            {{ form_row(form.produto) }}

            {% for subcategoria in subcategorias %}
                <fieldset id="{{ subcategoria }}">
                    <legend>{{ subcategoria }}</legend>
                    <div id="pedido_subpedidos">
                    {% for key, subpedidos in form.subpedidos.vars.choices %}

                        {% if form.subpedidos.vars.choices[key].data.subcategoria.id == subcategoria.id %}
                            {{ form_row( form.subpedidos[ key ],  {'attr': {'class': 'css-checkbox'},'label_attr':{'class':'css-label'}}) }}
                        {% endif %}

                    {% endfor %}
                    </div>
                </fieldset>
                {% endfor %}

            {{ form_row(form.levar) }}
            <input type="submit" value="Gerar Pedido" />
        </fieldset>
        {{ form_end(form) }}
    </fieldset>
</section>
{% block stylesheets %}
    <style>
        input[type=checkbox]{
        }

        input[type=checkbox]+label{
            display:block;
            margin:-2px;
            padding: 4px 12px;
            margin-bottom: 0;
            margin:5px 5px 5px 5px;
            font-size: 20px;
            line-height: 20px;
            color: #333;
            text-align: center;
            text-shadow: 0 1px 1px rgba(255,255,255,0.75);
            vertical-align: middle;
            cursor: pointer;
            background-color: #f5f5f5;
            background-image: -moz-linear-gradient(top,#fff,#e6e6e6);
            background-image: -webkit-gradient(linear,0 0,0 100%,from(#fff),to(#e6e6e6));
            background-image: -webkit-linear-gradient(top,#fff,#e6e6e6);
            background-image: -o-linear-gradient(top,#fff,#e6e6e6);
            background-image: linear-gradient(to bottom,#fff,#e6e6e6);
            background-repeat: repeat-x;
            border: 1px solid #ccc;
            border-color: #e6e6e6 #e6e6e6 #bfbfbf;
            border-color: rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);
            border-bottom-color: #b3b3b3;
            filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffffff',endColorstr='#ffe6e6e6',GradientType=0);
            filter: progid:DXImageTransform.Microsoft.gradient(enabled=false);
            -webkit-box-shadow: inset 0 1px 0 rgba(255,255,255,0.2),0 1px 2px rgba(0,0,0,0.05);
            -moz-box-shadow: inset 0 1px 0 rgba(255,255,255,0.2),0 1px 2px rgba(0,0,0,0.05);
            box-shadow: inset 0 1px 0 rgba(255,255,255,0.2),0 1px 2px rgba(0,0,0,0.05);
        }
        input[type=checkbox]+label{
            display:block;
            margin:-2px;
            padding: 4px 12px;
            margin-bottom: 0;
            margin:5px 5px 5px 5px;
            font-size: 20px;
            line-height: 20px;
            color: #333;
            text-align: center;
            text-shadow: 0 1px 1px rgba(255,255,255,0.75);
            vertical-align: middle;
            cursor: pointer;
            background-color: #f5f5f5;
            background-image: -moz-linear-gradient(top,#fff,#e6e6e6);
            background-image: -webkit-gradient(linear,0 0,0 100%,from(#fff),to(#e6e6e6));
            background-image: -webkit-linear-gradient(top,#fff,#e6e6e6);
            background-image: -o-linear-gradient(top,#fff,#e6e6e6);
            background-image: linear-gradient(to bottom,#fff,#e6e6e6);
            background-repeat: repeat-x;
            border: 1px solid #ccc;
            border-color: #e6e6e6 #e6e6e6 #bfbfbf;
            border-color: rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);
            border-bottom-color: #b3b3b3;
            filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffffff',endColorstr='#ffe6e6e6',GradientType=0);
            filter: progid:DXImageTransform.Microsoft.gradient(enabled=false);
            -webkit-box-shadow: inset 0 1px 0 rgba(255,255,255,0.2),0 1px 2px rgba(0,0,0,0.05);
            -moz-box-shadow: inset 0 1px 0 rgba(255,255,255,0.2),0 1px 2px rgba(0,0,0,0.05);
            box-shadow: inset 0 1px 0 rgba(255,255,255,0.2),0 1px 2px rgba(0,0,0,0.05);
        }
        fieldset{
            background-color: #f6a553;
            outline-color: #222222;
            width:300px;
            height: auto;
            padding-left: 10px;
            padding-right: 10px;
            padding-bottom: 20px;
        }
        fieldset legend{
            margin: 15px 15px 15px 15px;
            padding: 10px 10px 10px 10px;
            background-color: #f6f6f6;
            color: #313131;
            font-weight: bold;
            border-radius: 10px;
            width:120px;
        }

        input[type=text]{
            height: 50px;
            width:280px;
            font-size: 18px;
            margin-bottom: 10px;
        }
        input[type=submit]{
            margin-top: 10px;
            display:inline-block;
            width: 95%;
            height: 50px;
            font-size: 25px;
            text-transform: uppercase;
            font-weight: bolder;
            background-color: #880000;
            color: #ffffff;
        }
        input[type=submit]:hover{
            background-color: rgba(255, 200, 73, 0.99);
            color:#222222;
        }

        /*
     Hide radio button (the round disc)
     we will use just the label to create pushbutton effect
     */
        input[type=radio] {
            display:none;
        }

        /*
         Change the look'n'feel of labels (which are adjacent to radiobuttons).
         Add some margin, padding to label
         */
        input[type=radio] + label {
            display:block;
            margin:-2px;
            padding: 4px 12px;
            margin-bottom: 0;
            margin:5px 5px 5px 5px;
            font-size: 14px;
            line-height: 20px;
            color: #333;
            text-align: center;
            text-shadow: 0 1px 1px rgba(255,255,255,0.75);

            cursor: pointer;
            background-color: #f5f5f5;
            background-image: -moz-linear-gradient(top,#fff,#e6e6e6);
            background-image: -webkit-gradient(linear,0 0,0 100%,from(#fff),to(#e6e6e6));
            background-image: -webkit-linear-gradient(top,#fff,#e6e6e6);
            background-image: -o-linear-gradient(top,#fff,#e6e6e6);
            background-image: linear-gradient(to bottom,#fff,#e6e6e6);
            background-repeat: repeat-x;
            border: 1px solid #ccc;
            border-color: #e6e6e6 #e6e6e6 #bfbfbf;
            border-color: rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);
            border-bottom-color: #b3b3b3;
            filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffffff',endColorstr='#ffe6e6e6',GradientType=0);
            filter: progid:DXImageTransform.Microsoft.gradient(enabled=false);
            -webkit-box-shadow: inset 0 1px 0 rgba(255,255,255,0.2),0 1px 2px rgba(0,0,0,0.05);
            -moz-box-shadow: inset 0 1px 0 rgba(255,255,255,0.2),0 1px 2px rgba(0,0,0,0.05);
            box-shadow: inset 0 1px 0 rgba(255,255,255,0.2),0 1px 2px rgba(0,0,0,0.05);
        }
        /*
         Change background color for label next to checked radio button
         to make it look like highlighted button
         */
        input[type=radio]:checked + label {
            background-image: none;
            outline: 0;
            -webkit-box-shadow: inset 0 2px 4px rgba(136, 210, 251, 0.91),0 1px 2px rgba(0,0,0,0.05);
            -moz-box-shadow: inset 0 2px 4px rgba(115, 171, 197, 0.91),0 1px 2px rgba(0,0,0,0.05);
            box-shadow: inset 0 2px 4px rgba(46, 91, 98, 0.73),0 1px 2px rgba(0,0,0,0.05);
            background-color:darkkhaki;
            font-weight: bold;
        }
    </style>
{% endblock %}

{% endblock %}

0 个答案:

没有答案