I
I
Ivan Bogomolov2014-01-21 17:10:50
symfony
Ivan Bogomolov, 2014-01-21 17:10:50

Outputting data to multiple form like form[field][0], form[field][1] in symfony2.2 doctrine?

The type depends on the page, respectively, where the condition is specified, we show the usual form fields there, and in the admin panel I show collections of forms, they have prototypes and using the script, you can add forms of the form Message[name][0],Message[email][0] ,Message[message][0] ... Message[fields][i]

namespace Home\MailBundle\Form\Type;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
use Symfony\Component\Validator\Constraints\NotBlank;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;
use Symfony\Component\HttpFoundation\Request;

class MessageType extends AbstractType
{
  public function buildForm(FormBuilderInterface $builder, array $options)
  {
    $request = Request::createFromGlobals();
    

    $builder->addEventListener(FormEvents::PRE_SET_DATA, function(FormEvent $event) use ($request) {
          $message = $event->getData();
          $form = $event->getForm();  	
         	
          if($request->getPathInfo() == '/' || $request->getPathInfo() == '/subscribes/sendform/public_mail')
          {
          	$form->add('name','text');
        $form->add('email','email');
        $form->add('message','textarea');
          }
          else {
          	$form->add('name',
          	           'collection',
          	           array('allow_add' => true,
          	                 'type' => 'text',
          	                 'label' => array('class' => 'dsdsa'),
          	                  'options' => array(
                   		             'attr' => array(
                   		              'class' => 'form-control',
                   					  'placeholder' => 'Name...',

                   					  )
                   		  			 )
          	                 ));

        $form->add('email',
                   'collection',
                   array('allow_add' => true,
                   		 'type' => 'email',
                   		 'options' => array(
                   		             'attr' => array('class' => 'form-control',
                   					  'placeholder' => 'Email...')
                   		  			 )
                   		));

        $form->add('message',
                   'collection',
                   array('type' => 'textarea',
                  'allow_add' => true,
                  'options' => array(
                   		 			 'attr' => array('class' => 'form-control',
                   						  'placeholder' => 'Message...')
                   					 	)
                ));
          }
          
    	});
    
  }

  public function setDefaultOptions(OptionsResolverInterface $resolver)
  {
    $resolver->setDefaults(array(
      //'data_class' => 'Home\MailBundle\Entity\Message',
    ));
  }

  /**
  *
  * Returns form name lke Message[name]...
  *
  **/
  
  public function getName()
  {
    return 'Message';
  }
}

In the template, the fields are displayed like this {{ form_widget(form.name) }} , additional fields are added to their prototype. In general, one key is equal to one entity, i.e. name[0],email[0],message[0] is one record
In the controller I get
$message = $this->getDoctrine()->getRepository('MailBundle:Message')->findAll();
        
        $form = $this->createForm(new MessageType(), $message);
...
return $this->render('MailBundle:Subscribe:index.html.twig',array(
                             'title' => 'Add email form',
                             'form' => $form->createView()
         ));

The template looks like this (adding and output, I ask for help on the output)
{% block content %}

<div class="contact-form" >
  
  {{ form_errors(form) }}
  <form action="{{ path('mail_send_mail_form_multiple') }}" id="mail_send_mail_form" method="post" {{ form_enctype(form) }} novalidate >
    <h1>{{ title }}</h1>

     
    

      <div class="emailfields">{{ form_widget(form.name) }}
      {{ form_widget(form.email) }}
      {{ form_widget(form.message) }}
      </div>
    
    <div id="insert-blocks" class="row">
              {% for key,field in form %}
                
                {# <b>здесь по идее надо выводить формы</b> {{ form_widget(field) }}  #}
               
            {% endfor %}
        </div>
    <div class="row ">
      <a href="" class="btn" id="add_more">Add mail form...</a>
    </div>
  </br>
    <div class="row">
      <input type="submit"  value="Save all forms" class="btn">
    </div>
  </form>
</div>


<script type="text/javascript">
    // keep track of how many email fields have been rendered
    var formsCount = $('.form-block').size() || 0 ;//'{{ form.name | length }}';

    $(document).ready(function() {
        $('#add_more').click(function() {
            var fieldsList = $('.emailfields div');
            var protoHtml = '';
            fieldsList.each(function(k,v){
            	var newWidget = $(v).attr('data-prototype').replace(/label__/g, "");
            	newWidget = newWidget.replace(/__name__/g, formsCount);
            	protoHtml = protoHtml + newWidget
            });
            // grab the prototype template
            
            // replace the "__name__" used in the id and name of the prototype
            // with a number that's unique to your emails
            // end name attribute looks like name="contact[emails][2]"
           // newWidget = newWidget.replace(/__name__/g, emailCount);
            formsCount++;

            // create a new list element and add it to the list
            var newLi = $('<div class="col-xs-6 col-md-4 form-block "></div>').html(protoHtml);
            newLi.appendTo($('#insert-blocks'));
            $('.form-block div label').replaceWith('<br>');
            return false;
        });
    })
</script>

{% endblock %}

Question: how to convert data into a form in order to sort through and output something like this in a loop (to get fields of the form Message[name][0] ,Message[name][1] ):
{% for key,field in form %}
               
             {{ form_widget(field.name) }}  
               
            {% endfor %}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Ivan Bogomolov, 2014-01-22
@kraso4niy

In general, I left such a code, apparently there is no other way

<form>
 {% for key,field in form.vars.value %}
 <input type="hidden" name="Message[id][{{key}}]" value="{{field.id}}">
<input type="text"name="Message[name][{{key}}]" value="{{ field.name }}" >
<input type="text"name="Message[email][{{key}}]" value="{{ field.email }}" >
<input type="text"name="Message[message][{{key}}]" value="{{ field.message }}" >
{% endfor %}
</form>

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question