Symfony2 2.7
I have looked around, but I do not find a neat, standard way to define:
(*) a form (formType) and whatever controller you need to let a user to create dynamically and at once as many objects as she wishes.
I see here and here, but I am not able to reproduce their solutions.
Question is: is there a standard way to do (*)?
Note: This does not seem to help, in the sense that it creates only a unique Task object, even if it let a user to create (dynamically) several Tag ones.
PARTIAL SOLUTION The following works fine: a user may add as many objects as she wishes.
I need to check whether I may clean the code somehow. If you see a way to improve it, please comment.
Eventually, I wish to have a Job 1:M Tasks 1:M Tags situation, with a form to create at once many Jobs, many Tasks for each Job, many Tags for each Task. I need to check that I may embed forms for the related 1:M entities. Stay tuned!
Controllers
/**
* Creates a new Job entity.
*
* @Route("/", name="Myname_Job_create")
* @Method("POST")
* @Template("MynameBlogBundle:Job:new.html.twig")
*/
public function createAction(Request $request)
{
////var_dump($request); die('here'); // this helped a lot to understand
$postData = $request->request->get('form');
$entity = array();
foreach($postData['jobs'] as $key => $obj){$entity[$key]= new Job();}
$form = $this->createCreateForm($entity);
$form->handleRequest($request);
if ($form->isValid()) {
try {
$em = $this->getDoctrine()->getEntityManager();
foreach($entity as $ent){ $em->persist($ent); }
$em->flush();
} catch (\Doctrine\DBAL\DBALException $e) {
die($e->getMessage());
}
return $this->redirect($this->generateUrl('Myname_Job'));
}
return array(
'info' => $postData,
'entity' => $entity,
'form' => $form->createView(),
);
}
/**
* Creates a form to create a Job entity.
*
* @param Job $entity The entity
*
* @return \Symfony\Component\Form\Form The form
*/
private function createCreateForm(Array $jobs)
{
$form = $this->createFormBuilder(array('jobs'=>$jobs))
->setAction($this->generateUrl('Myname_Job_create'))
->add('jobs','collection',array(
'required' => true,
'allow_add' => true,
'allow_delete' => true,
'type' => new JobType(),
))
->add('submit', 'submit',array('label' => 'Create'))
->getForm()
;
return $form;
}
/**
* Displays a form to create a new Job entity.
*
* @Route("/new", name="Myname_Job_new")
* @Method("GET")
* @Template()
*/
public function newAction()
{
$jobs = array(0 => new Job());
$form = $this->createCreateForm($jobs);
return array(
'entity' => $jobs,
'form' => $form->createView(),
);
}
JobType
class JobType extends AbstractType
{
/**
* @param FormBuilderInterface $builder
* @param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('title', 'text', array(
'label' => 'Write Title ',
'required' => true
))
->add('description','text',array(
'label' => 'Write Descr. ',
))
;
}
....
}
New .twig template
{% extends '::base.html.twig' %}
{% block javascripts %}
{{ parent() }}
<script src="{{ asset('bundles/mynameblog/js/JQuery/jquery-2.1.0.js') }}" type="text/javascript">
</script>
<script>
var $collectionHolder;
// setup an "add aJobs" link
var $addJobLink = $('<a href="#" class="add_Job_link">Add Jobs</a>');
var $newLinkLi = $('<li></li>').append($addJobLink);
function addJobForm($collectionHolder, $newLinkLi) {
// Get the data-prototype explained earlier
var prototype = $collectionHolder.data('prototype');
// get the new index
var index = $collectionHolder.data('index');
// Replace '__name__' in the prototype's HTML to
// instead be a number based on how many items we have
var newForm = prototype.replace(/__name__/g, index);
// increase the index with one for the next item
$collectionHolder.data('index', index + 1);
// Display the form in the page in an li, before the "Add a Jobs" link li
var $newFormLi = $('<li></li>').append(newForm);
$newLinkLi.before($newFormLi);
}
jQuery(document).ready(function() {
// Get the ul that holds the collection of Jobs
$collectionHolder = $('ul.jobs');
// add the "add Jobs" anchor and li to the Jobs ul
$collectionHolder.append($newLinkLi);
// count the current form inputs we have (e.g. 2), use that as the new
// index when inserting a new item (e.g. 2)
$collectionHolder.data('index', $collectionHolder.find(':input').length);
$addJobLink.on('click', function(e) {
// prevent the link from creating a "#" on the URL
e.preventDefault();
// add a newJobs form (see next code block)
addJobForm($collectionHolder, $newLinkLi);
});
});
</script>
{% endblock %}
{% block main -%}
<h1>Job creation</h1>
{{ form_start(form) }}
<ul class="jobs" data-prototype="{{ form_widget(form.jobs.vars.prototype)|e }}">
{# render the job-s only two fields: title description #}
{% for f in form.jobs %}
<li> {{ form_row(f) }} </li>
{% endfor %}
</ul>
{{ form_end(form) }}
{% endblock %}