Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- * I am working with Symfony 3.1
- * Entities Alpha, Beta, Gamma; Alpha 1:M Beta 1:M Gamma.
- * I need nested forms both to create and to edit/delete nested objects
- * To create nested object, code below works fine.
- * I am not sure how to insert apt JS into the edit form provided by Symfony as to add/delete subobjects
- */
- // Entities defined as by default
- // FORMS
- alphasType.php
- <?php
- namespace Jus\SimpleBundle\Form;
- use Symfony\Component\Form\AbstractType;
- use Symfony\Component\Form\FormBuilderInterface;
- use Symfony\Component\OptionsResolver\OptionsResolver;
- use Symfony\Component\Form\Extension\Core\Type\TextType;
- use Symfony\Component\Form\Extension\Core\Type\CollectionType;
- use Symfony\Component\Form\Extension\Core\Type\SubmitType;
- class AlphasType extends AbstractType
- {
- /**
- * {@inheritdoc}
- */
- public function buildForm(FormBuilderInterface $builder, array $options)
- {
- $builder->add('alphas', CollectionType::class, array(
- 'entry_type'=> AlphaType::class,
- 'allow_add' => true,
- 'allow_delete' => true,
- 'by_reference' => false,
- 'label' => 'Insert one more alpha',
- 'prototype' => true,
- 'prototype_name' => '__alpha_prot__'
- ))
- ->add('Save', SubmitType::class, array('attr' => array('class' => 'save')))
- ;
- }
- /**
- * {@inheritdoc}
- */
- public function configureOptions(OptionsResolver $resolver)
- {
- $resolver->setDefaults(array(
- 'data_class' => null
- ));
- }
- /**
- * {@inheritdoc}
- */
- public function getBlockPrefix()
- {
- return 'jus_simplebundle_alphas';
- }
- }
- alphaType.php
- <?php
- namespace Jus\SimpleBundle\Form;
- use Symfony\Component\Form\AbstractType;
- use Symfony\Component\Form\FormBuilderInterface;
- use Symfony\Component\OptionsResolver\OptionsResolver;
- use Symfony\Component\Form\Extension\Core\Type\TextType;
- use Symfony\Component\Form\Extension\Core\Type\CollectionType;
- class AlphaType extends AbstractType
- {
- /**
- * {@inheritdoc}
- */
- public function buildForm(FormBuilderInterface $builder, array $options)
- {
- $builder->add('title', TextType::class)
- ->add('betas', CollectionType::class, array(
- 'entry_type' => BetaType::class,
- 'allow_add' => true,
- 'allow_delete' => true,
- 'by_reference' => false,
- //'entry_options' => array('entity_manager' => $entityManager),
- 'label' => 'Insert betas for this alpha',
- 'prototype' => true,
- 'prototype_name' => '__beta_prot__'
- )) ;
- }
- /**
- * {@inheritdoc}
- */
- public function configureOptions(OptionsResolver $resolver)
- {
- $resolver->setDefaults(array(
- 'data_class' => 'Jus\SimpleBundle\Entity\Alpha'
- ));
- }
- /**
- * {@inheritdoc}
- */
- public function getBlockPrefix()
- {
- return 'jus_simplebundle_alpha';
- }
- }
- betaType.php
- <?php
- namespace Jus\SimpleBundle\Form;
- use Symfony\Component\Form\AbstractType;
- use Symfony\Component\Form\FormBuilderInterface;
- use Symfony\Component\OptionsResolver\OptionsResolver;
- use Symfony\Component\Form\Extension\Core\Type\TextType;
- use Symfony\Component\Form\Extension\Core\Type\CollectionType;
- class BetaType extends AbstractType
- {
- /**
- * {@inheritdoc}
- */
- public function buildForm(FormBuilderInterface $builder, array $options)
- {
- $builder->add('title')
- //->add('alpha')
- ->add('gammas', CollectionType::class, array(
- 'entry_type' => GammaType::class,
- 'allow_add' => true,
- 'allow_delete' => true,
- 'by_reference' => false,
- //'entry_options' => array('entity_manager' => $entityManager),
- 'label' => 'Insert gammas for this beta',
- 'prototype' => true,
- 'prototype_name' => '__gamma_prot__'
- )) ;
- }
- /**
- * {@inheritdoc}
- */
- public function configureOptions(OptionsResolver $resolver)
- {
- $resolver->setDefaults(array(
- 'data_class' => 'Jus\SimpleBundle\Entity\Beta'
- ));
- }
- /**
- * {@inheritdoc}
- */
- public function getBlockPrefix()
- {
- return 'jus_simplebundle_beta';
- }
- }
- gammaType.php
- <?php
- namespace Jus\SimpleBundle\Form;
- use Symfony\Component\Form\AbstractType;
- use Symfony\Component\Form\FormBuilderInterface;
- use Symfony\Component\OptionsResolver\OptionsResolver;
- class GammaType extends AbstractType
- {
- /**
- * {@inheritdoc}
- */
- public function buildForm(FormBuilderInterface $builder, array $options)
- {
- $builder->add('title')
- //->add('beta')
- ;
- }
- /**
- * {@inheritdoc}
- */
- public function configureOptions(OptionsResolver $resolver)
- {
- $resolver->setDefaults(array(
- 'data_class' => 'Jus\SimpleBundle\Entity\Gamma'
- ));
- }
- /**
- * {@inheritdoc}
- */
- public function getBlockPrefix()
- {
- return 'jus_simplebundle_gamma';
- }
- }
- alphaController.php
- <?php
- namespace Jus\SimpleBundle\Controller;
- use Jus\SimpleBundle\Entity\Alpha;
- use Jus\SimpleBundle\Entity\Beta;
- use Jus\SimpleBundle\Entity\Gamma;
- use Symfony\Bundle\FrameworkBundle\Controller\Controller;
- use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
- use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
- use Symfony\Component\HttpFoundation\Request;
- /**
- * Alpha controller.
- *
- * @Route("Jus/Simple/alpha")
- */
- class AlphaController extends Controller
- {
- /**
- * Lists all alpha entities.
- *
- * @Route("/", name="Jus_Simple_alpha_index")
- * @Method("GET")
- */
- public function indexAction()
- {
- $em = $this->getDoctrine()->getManager();
- $alphas = $em->getRepository('SimpleBundle:Alpha')->findAll();
- return $this->render('alpha/index.html.twig', array(
- 'alphas' => $alphas,
- ));
- }
- /**
- * Creates a new alpha entity.
- *
- * @Route("/new", name="Jus_Simple_alpha_new")
- * @Method({"GET", "POST"})
- */
- public function newAction(Request $request)
- {
- //$alpha = new Alpha();
- $alphas = array(0 => new Alpha());
- //$form = $this->createForm('Jus\SimpleBundle\Form\AlphaType', $alpha);
- $form = $this->createForm('Jus\SimpleBundle\Form\AlphasType', $alphas, array(
- 'action' => $this->generateUrl('Jus_Simple_alpha_new')));
- $form->handleRequest($request);
- /* if ($form->isSubmitted() && $form->isValid()) {
- $em = $this->getDoctrine()->getManager();
- $em->persist($alpha);
- $em->flush($alpha);
- */
- if ($form->isSubmitted() && $form->isValid()) { //echo 'yes';
- try {
- $postData = $request->request->get('jus_simplebundle_alphas');
- //dump($request->request); die();
- $em = $this->getDoctrine()->getEntityManager();
- $alphas = array();
- foreach($postData['alphas'] as $key => $obj){$alphas[$key]= new Alpha();
- $alphas[$key]->setTitle($obj['title']);
- $em->persist($alphas[$key]);
- if(isset($obj['betas'])){
- $betas = array();
- foreach($obj['betas'] as $kkey => $oobj){$betas[$kkey]= new Beta();
- $betas[$kkey]->setAlpha($alphas[$key]);
- $betas[$kkey]->setTitle($oobj['title']);
- $em->persist($betas[$kkey]);
- if(isset($oobj['gammas'])){
- $gammas = array();
- foreach($oobj['gammas'] as $kkkey => $ooobj){$gammas[$kkkey]= new Gamma();
- $gammas[$kkkey]->setBeta($betas[$kkey]);
- $gammas[$kkkey]->setTitle($ooobj['title']);
- $em->persist($gammas[$kkkey]);
- }}
- }}}
- $em->flush();
- } catch (\Doctrine\DBAL\DBALException $e) {
- die($e->getMessage());
- }
- return $this->redirectToRoute('Jus_Simple_alpha_index');
- }
- return $this->render('alpha/new.html.twig', array(
- 'alphas' => $alphas,
- 'form' => $form->createView(),
- ));
- }
- /**
- * Finds and displays a alpha entity.
- *
- * @Route("/{id}", name="Jus_Simple_alpha_show")
- * @Method("GET")
- */
- public function showAction(Alpha $alpha)
- {
- $deleteForm = $this->createDeleteForm($alpha);
- return $this->render('alpha/show.html.twig', array(
- 'alpha' => $alpha,
- 'delete_form' => $deleteForm->createView(),
- ));
- }
- /**
- * Displays a form to edit an existing alpha entity.
- *
- * @Route("/{id}/edit", name="Jus_Simple_alpha_edit")
- * @Method({"GET", "POST"})
- */
- public function editAction(Request $request, Alpha $alpha)
- {
- $deleteForm = $this->createDeleteForm($alpha);
- $editForm = $this->createForm('Jus\SimpleBundle\Form\AlphaType', $alpha);
- $editForm->handleRequest($request);
- if ($editForm->isSubmitted() && $editForm->isValid()) {
- $this->getDoctrine()->getManager()->flush();
- return $this->redirectToRoute('Jus_Simple_alpha_edit', array('id' => $alpha->getId()));
- }
- return $this->render('alpha/edit.html.twig', array(
- 'alpha' => $alpha,
- 'edit_form' => $editForm->createView(),
- 'delete_form' => $deleteForm->createView(),
- ));
- }
- /**
- * Deletes a alpha entity.
- *
- * @Route("/{id}", name="Jus_Simple_alpha_delete")
- * @Method("DELETE")
- */
- public function deleteAction(Request $request, Alpha $alpha)
- {
- $form = $this->createDeleteForm($alpha);
- $form->handleRequest($request);
- if ($form->isSubmitted() && $form->isValid()) {
- $em = $this->getDoctrine()->getManager();
- $em->remove($alpha);
- $em->flush($alpha);
- }
- return $this->redirectToRoute('Jus_Simple_alpha_index');
- }
- /**
- * Creates a form to delete a alpha entity.
- *
- * @param Alpha $alpha The alpha entity
- *
- * @return \Symfony\Component\Form\Form The form
- */
- private function createDeleteForm(Alpha $alpha)
- {
- return $this->createFormBuilder()
- ->setAction($this->generateUrl('Jus_Simple_alpha_delete', array('id' => $alpha->getId())))
- ->setMethod('DELETE')
- ->getForm()
- ;
- }
- }
- // BASE TEMPLATE with JQuery JS
- <!DOCTYPE html>
- <html>
- <head>
- <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
- <script src="{{ asset('bundles/js/simple/jquery-3.1.1.js') }}" type="text/javascript"> </script>
- <script type="text/javascript">
- var $collectionHolder;
- // setup an "add aAlphas" link
- var $addAlphaLink = $('<a href="#" class="add_Alpha_link">Crea un altro Alpha</a>');
- var $newLinkLi = $('<li></li>').append($addAlphaLink);
- jQuery(document).ready(function() {
- // Get the ul that holds the collection of Alphas
- $collectionHolder = $('ul.Alphas');
- // add the "add Alphas" anchor and li to the Alphas ul
- $collectionHolder.append($newLinkLi);
- //window.alert($collectionHolder.append($newLinkLi).html());
- // count the current form inputs we have (e.g. 2), use that as the new
- // index when inserting a new item (e.g. 2)
- var $index = 0;
- var $jndex = 0;
- var $kndex = 0;
- $addAlphaLink.on('click', function(e) {
- // prevent the link from creating a "#" on the URL
- e.preventDefault();
- // add a newAlphas form (see next code block)
- addAlphaForm($collectionHolder, $newLinkLi, $index, $jndex, $kndex); // Ok, it works!
- $index++;
- });
- });
- function addAlphaForm($collectionHolder, $newLinkLi, $index, $jndex, $kndex ) {
- var $addBetaLink = $('<a href="#" class="add_Beta_link_'+$index+'" >Crea un altro Beta</a>');
- var $newLinkLiBis = $('<ul>').append($addBetaLink).append('</ul>');
- // Get the data-prototype
- var prototype = $collectionHolder.data('prototype');
- // get the new index
- var index = $index;
- //window.alert($collectionHolder.data);
- // Replace '__alpha_prot__' in the prototype's HTML to
- // instead be a number based on how many items we have
- var newForm = prototype.replace(/__alpha_prot__/g, index);
- // Display the form in the page in an li, before the "Add a Alphas" link li
- var newForm = $('<li></li>').append(newForm).insertBefore('.add_Alpha_link').append('<a href="#" class="remove-tag">x</a>').append($newLinkLiBis);
- // handle the removal, just for this example
- $('.remove-tag').click(function(e) {
- e.preventDefault();
- $(this).parent().remove();
- return false;
- });
- $addBetaLink.on('click', function(e) {
- e.preventDefault();
- var $collectionHolderBis = $('div#jus_simplebundle_alphas_alphas_'+$index+'_betas');
- addBetaForm($collectionHolderBis, $newLinkLi, $index, $jndex, $kndex); // Ok, it works!
- $jndex++;
- });
- }
- function addBetaForm($collectionHolder, $newLinkLi, $index, $jndex, $kndex) {
- var $addGammaLink = $('<a href="#" class="add_Gamma_link_'+$jndex+'" >Crea un altra Gamma</a>');
- var $newLinkLiTris = $('<ul>').append($addGammaLink).append('</ul>');
- var prototype = $collectionHolder.data('prototype');
- //window.alert(prototype);
- var index = $index;
- var jndex = $jndex;
- var kndex = $kndex;
- var newFormSub = prototype.replace(/__alpha_prot__/g, index).replace(/__beta_prot__/g, jndex).replace(/label__/g, '');
- $('<li></li>').append(newFormSub).append('<a href="#" class="remove-tag">y</a>').insertBefore('.add_Beta_link_'+$index).append($newLinkLiTris)
- $('.remove-tag').click(function(e) {
- e.preventDefault();
- $(this).parent().remove();
- return false;
- });
- $addGammaLink.on('click', function(e) {
- e.preventDefault();
- var $collectionHolderTris = $('div#jus_simplebundle_alphas_alphas_'+$index+'_betas_'+$jndex+'_gammas');
- //window.alert('div#alphas_alphas_'+$index+'_betas_'+$jndex+'_gammas'+$collectionHolderTris.html());
- addGammaForm($collectionHolderTris, $newLinkLi, $index, $jndex, $kndex); // Ok, it works!
- $kndex++;
- });
- }
- function addGammaForm($collectionHolder, $newLinkLi, $index, $jndex, $kndex) {
- var prototype = $collectionHolder.data('prototype');
- var index = $index;
- var jndex = $jndex;
- var kndex = $kndex;
- var newFormSubSub = prototype.replace(/__alpha_prot__/g, index).replace(/__beta_prot__/g, jndex).replace(/__gamma_prot__/g, kndex).replace(/label__/g, '');
- $('<li></li>').append(newFormSubSub).append('<a href="#" class="remove-tag">z</a>').insertBefore('.add_Gamma_link_'+$jndex)
- $('.remove-tag').click(function(e) {
- e.preventDefault();
- $(this).parent().remove();
- return false;
- });
- }
- </script>
- <title>To Learn Symfony2</title>
- </head>
- <body {% block bodyattr -%} {% endblock %} >
- <div id="header">
- {% block header %}Welcome{% endblock %}
- </div>
- <h1 class="title"> {% block title %}TEST NESTED FORMS{% endblock %} </h1>
- {% block body %}{% endblock %}
- <div id="footer">
- {% block footer %}<a href="http://www.symfony.com">developed thanks to SYMFONY</a> {% endblock %}
- </div>
- </body>
- </html>
- // new.twig.html template for alpha entities
- {% extends 'basesimple.html.twig' %}
- {% block body %}
- <h1>Alpha creation</h1>
- {{ form_start(form) }}
- <ul class="Alphas" id="prots" data-prototype="{{ form_widget(form.alphas.vars.prototype) | e }}">
- {# render the alpha's fields#}
- {% for f in form.alphas %}
- <li class="here"> {{ form_row(f) }}
- </li>
- {% endfor %} </ul>
- {{ form_end(form) }}
- <br>
- <hr>
- <a href="{{ path('Jus_Simple_alpha_index') }}">Back to the list</a>
- {% endblock %}
- // edit.twig.html template for alpha entities
- {% extends 'basesimple.html.twig' %}
- {% block body %}
- <h1>Alpha edit</h1>
- {{ form_start(edit_form) }}
- {{ form_widget(edit_form) }}
- <input type="submit" value="Edit" />
- {{ form_end(edit_form) }}
- <ul>
- <li>
- <a href="{{ path('Jus_Simple_alpha_index') }}">Back to the list</a>
- </li>
- <li>
- {{ form_start(delete_form) }}
- <input type="submit" value="Delete">
- {{ form_end(delete_form) }}
- </li>
- </ul>
- {% endblock %}
Advertisement
Add Comment
Please, Sign In to add comment