ninsuo / symfony-collection

[NOT MAINTAINED] A jQuery plugin that manages adding, deleting and moving elements from a Symfony form collection
https://symfony-collection.fuz.org/
MIT License
444 stars 87 forks source link

Form doesn't render #17

Open fcpauldiaz opened 8 years ago

fcpauldiaz commented 8 years ago

The field that is a collection doesn't render at all, it's blank.

The form configuration is:

 ->add('arrayDiagnosticos', 'collection', [
                'type' => new DiagnosticoType(),
                    'allow_add' => true,
                    'allow_delete' => true,
                    'prototype' => true,
                    'attr' => array(
                            'class' => 'my-selector',
                    ),

                ])

The new.html.twig is

{% block body -%}
     {% form_theme form '::jquery.collection.html.twig' %}
     {{ form(form) }}
{% endblock %}

included jquery.collection and jquery

 <script src="{{ asset('js/jquery-1.11.3.min.js')}}"></script>
  <script src="{{asset('js/jquery.collection.js')}}"></script>
  <script type="text/javascript">
        $('.my-selector').collection();
  </script>

I don't know what I'm missing

ninsuo commented 8 years ago

Can you provide the controller that creates that form?

fcpauldiaz commented 8 years ago

This is the whole controller

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 Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use AppBundle\Entity\IngresoPaciente;
use AppBundle\Form\Type\IngresoPacienteType;
use FOS\UserBundle\Model\UserInterface;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security;
use AppBundle\Entity\Diagnostico;

/**
 * IngresoPaciente controller.
 *
 * @Security("has_role('ROLE_USER')")
 * @Route("/datos-clinicos-paciente")
 */
class IngresoPacienteController extends Controller
{
    /**
     * Lists all IngresoPaciente entities.
     *
     * @Route("/", name="ingresopaciente")
     * @Method("GET")
     * @Template()
     */
    public function indexAction()
    {
        $em = $this->getDoctrine()->getManager();

        $entities = $em->getRepository('AppBundle:IngresoPaciente')->findAll();

        return [
            'entities' => $entities,
        ];
    }
    /**
     * Creates a new IngresoPaciente entity.
     *
     * @Route("/", name="ingresopaciente_create")
     * @Method("POST")
     * @Template("AppBundle:IngresoPaciente:new.html.twig")
     */
    public function createAction(Request $request)
    {
        $usuario = $this->get('security.token_storage')->getToken()->getUser();
        if (!is_object($usuario) || !$usuario instanceof UserInterface) {
            throw new AccessDeniedException('El usuario no tiene acceso.');
        }

        $entity = new IngresoPaciente();
        $entity->setUsuario($usuario);
        $diagnostico = new Diagnostico();
        $diagnostico->setDiagnostico('test');
        $entity->getArrayDiagnosticos()->add($diagnostico);
        $form = $this->createCreateForm($entity);
        $form->handleRequest($request);

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

            return $this->redirect($this->generateUrl('ingresopaciente_show', ['slug' => $entity->getSlug()]));
        }

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

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

        $form->add('submit', 'submit', ['label' => 'Guardar', 'attr' => ['class' => 'btn btn-primary btn-block']]);

        return $form;
    }

    /**
     * Displays a form to create a new IngresoPaciente entity.
     *
     * @Route("/nuevo", name="ingresopaciente_new")
     * @Method("GET")
     * @Template()
     */
    public function newAction()
    {
        $entity = new IngresoPaciente();
        $form = $this->createCreateForm($entity);

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

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

        $entity = $em->getRepository('AppBundle:IngresoPaciente')->findOneBy(['slug' => $slug]);

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

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

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

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

        $entity = $em->getRepository('AppBundle:IngresoPaciente')->findOneBy(['slug' => $slug]);

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

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

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

    /**
     * Creates a form to edit a IngresoPaciente entity.
     *
     * @param IngresoPaciente $entity The entity
     *
     * @return \Symfony\Component\Form\Form The form
     */
    private function createEditForm(IngresoPaciente $entity)
    {
        $form = $this->createForm(new IngresoPacienteType(), $entity, [
            'action' => $this->generateUrl('ingresopaciente_update', ['slug' => $entity->getSlug()]),
            'method' => 'PUT',
        ]);

        $form->add('submit', 'submit', ['label' => 'Actualizar',
            'attr' => ['class' => 'btn btn-success'],
            ]);

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

        $entity = $em->getRepository('AppBundle:IngresoPaciente')->findOneBy(['slug' => $slug]);

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

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

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

            return $this->redirect($this->generateUrl('ingresopaciente_edit', ['slug' => $slug]));
        }

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

        if ($form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $entity = $em->getRepository('AppBundle:IngresoPaciente')->findOneBy(['slug' => $slug]);

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

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

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

    /**
     * Creates a form to delete a IngresoPaciente entity by id.
     *
     * @param mixed $id The entity id
     *
     * @return \Symfony\Component\Form\Form The form
     */
    private function createDeleteForm($slug)
    {
        return $this->createFormBuilder()
            ->setAction($this->generateUrl('ingresopaciente_delete', ['slug' => $slug]))
            ->setMethod('DELETE')
            ->add('submit', 'submit', ['label' => 'Eliminar',
                'attr' => ['class' => 'btn btn-danger'],
                ])
            ->getForm()
        ;
    }
}

And the Entity

namespace AppBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Gedmo\Mapping\Annotation as Gedmo;

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

    /**
     * @var \DateTime
     *
     * @ORM\Column(name="fechaIngreso", type="date")
     */
    private $fechaIngreso;

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

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

    /**
     * @var string
     * @ORM\OneToMany(targetEntity="Diagnostico", mappedBy="diagnostico",cascade={"persist"})
     */
    private $arrayDiagnosticos;

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

    /**
     * @ORM\ManyToOne(targetEntity="Paciente",inversedBy="ingreso")
     * @ORM\JoinColumn(name="paciente_id", referencedColumnName="id",onDelete="SET NULL")
     */
    private $paciente;

    /**
     * @Gedmo\Slug(fields={"motivoIngreso"},updatable=true)
     * @ORM\Column(length=128, unique=true)
     */
    private $slug;

    /**
     * @ORM\ManyToOne(targetEntity="UserBundle\Entity\Usuario")
     * @ORM\JoinColumn(name="usuario_id", referencedColumnName="id",onDelete="SET NULL")
     */
    private $usuario;

    /**
     * @var \DateTime
     *
     * @Gedmo\Timestampable(on="create")
     * @ORM\Column(type="datetime",nullable=true)
     */
    private $created;

    /**
     * @var \DateTime
     *
     * @Gedmo\Timestampable(on="update")
     * @ORM\Column(type="datetime",nullable=true)
     */
    private $updated;

    /**
     * @var string
     *
     * @ORM\Column(name="content_changed_by", type="string", nullable=true)
     * @Gedmo\Blameable(on="change", field={"fechaIngreso", "motivoIngreso","procedimientoRealizado","fechaSalida"})
     */
    private $contentChangedBy;

     public function __construct()
    {
        $this->arrayDiagnosticos = new \Doctrine\Common\Collections\ArrayCollection();
    }
pjam commented 6 years ago

@fcpauldiaz I'm having the same problem, have you fixed this? Even before using this plugin.

fcpauldiaz commented 6 years ago

@pjam I stopped using this bundle.

pjam commented 6 years ago

Thanks for your fast reply.

I was having this issue even without using the bundle. Your collection is now working? Did you change anything else besides removing the bundle?

fcpauldiaz commented 6 years ago

I'm currently using this bundle instead to have collections.

pjam commented 6 years ago

Nevermind, I got it to work now. I have my form in an included twig file... it turns out I had to set the form theme in that same file. Including in some parent or config.yml doesn't work, I don't understand why.

Thanks anyway for your help.

fcpauldiaz commented 6 years ago

You should post your code if anyone else has the problem! On Nov 10, 2017, at 6:52 PM, pjam notifications@github.com<mailto:notifications@github.com> wrote:

Nevermind, I got it to work now. I have my form in an included twig file... it turns out I had to set the form theme in that same file. Including in some parent or config.yml doesn't work, I don't understand why.

Thanks anyway for your help.

— You are receiving this because you were mentioned. Reply to this email directly, view it on GitHubhttps://github.com/ninsuo/symfony-collection/issues/17#issuecomment-343625346, or mute the threadhttps://github.com/notifications/unsubscribe-auth/AEUFFHVNTbPZ4MASjw9JLwgZQgQjnoKjks5s1O_jgaJpZM4G8qMO.

ninsuo commented 6 years ago

You may have "nothing" instead of your collection if you initialize it without any element (then nothing is rendered) and the plugin isn't launched (then you don't have the extra add button that allow adding the first element).

My advice: put 1, and up to 3 empty elements inside your collection data during development, at least to test that the plugin is working before working on an empty collection.