javascript - Symfony2 嵌入式表单删除按钮功能

标签 javascript php jquery forms symfony

我在 Symfony2 中创建了一个嵌入式表单,它在一个“部门”中有许多“员工”。现在,添加许多具有“名字”和“姓氏”的员工在“部门”表单上工作正常(我为此使用了 jQuery)。我想要表单上的“删除”按钮功能,我无法弄清楚。谁能帮我实现删除按钮功能?

部门类型.php

<?php

namespace InstituteEvents\FormBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

class DepartmentType extends AbstractType
{
/**
 * @param FormBuilderInterface $builder
 * @param array $options
 */
 public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
        ->add('name')
        ->add('employees','collection', array(
            'type' => new EmployeeType(),
            'prototype' => true,
            'allow_add' => true,
            'by_reference' =>false
         ))    
    ;
}

/**
 * @param OptionsResolverInterface $resolver
 */
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
    $resolver->setDefaults(array(
        'data_class' => 'InstituteEvents\FormBundle\Entity\Department'
    ));
}

/**
 * @return string
 */
public function getName()
{
    return 'department';
}
}

员工类型.php

<?php

namespace InstituteEvents\FormBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

class EmployeeType extends AbstractType
{
/**
 * @param FormBuilderInterface $builder
 * @param array $options
 */
public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
        ->add('firstname')
        ->add('lastname')
    ;
}

/**
 * @param OptionsResolverInterface $resolver
 */
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
    $resolver->setDefaults(array(
        'data_class' => 'InstituteEvents\FormBundle\Entity\Employee'
    ));
}

/**
 * @return string
 */
public function getName()
{
    return 'employee';
}
}

index.html.twig - 此文件包含 jQuery 中的“添加员工”按钮功能。在这里,我想要“删除员工”按钮 + 功能。我不太了解 javascript 或 jQuery,所以我需要帮助来添加“删除员工”按钮及其代码。

<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script>
$(function() {
    var index = 0;
    var prototype = $('ul.form-employees').data('prototype');
    $('#form-employee-btn').on('click', function() { 
        var newForm = prototype.replace(/__name__/g, index++);
        var newLi = $('<li></li>');

        newLi.append(newForm);
        $(this).before(newLi);
    });
});
</script>    
<form method = "post">
{{ form_label(form.name, 'Department Name') }}
{{ form_widget(form.name) }}

<ul class="form-employees" data-prototype = "{{ form_widget(form.employees.vars.prototype)|e }}">
   <input id="form-employee-btn" type="button" value="Add Employees"/>
</ul>

   {{ form_widget(form._token) }}

<input type="submit" value="Submit"/>

</form>

最佳答案

按照说明找到in the docs :

在您的 DepartmentType 表单类中,将 EmployeeType 集合的 allow_delete 属性设置为 true:

    $builder
        ->add('name')
        ->add('employees','collection', array(
            'type' => new EmployeeType(),
            'prototype' => true,
            'allow_add' => true,
            'allow_delete' => true,//add this
            'by_reference' =>false
         )
    );

接下来,添加删除按钮(通过 EmployeeType 表单中的构建器 (->add('delete', 'button')),或手动添加 (在模板中使用 JS)。然后将事件监听器附加到表单。假设您已经像这样添加了删除按钮:

//EmployeeType:
$builder->add('delete', 'button', ['attr' => ['class' => 'delete-employee']]);

如果您在 View 中使用 JS 添加按钮,那么这段代码应该可以解决问题:

$('#department-form-selector').children('employee-form-selector').each(function(i)
{
    $(this).append('<button name="delete' + i + '" class="delete-employee">Delete</button>');
});

添加(或即将添加)按钮后,使用 jQ 附加一个监听器。在这个阶段按钮不需要在 DOM 中,因为我们使用的是事件委托(delegate),而不是直接绑定(bind):

$('#department-form-selector').on('click', '.delete-employee', function()
{
    $(this).closest('form').delete();//remove element
    //optionally submit department form via AJAX call to persist the delete
    return false;//stop event
});

现在,要处理表单(假设实体设置正确):

//in the controller that handles the form:
if ($form->isValid())
{
    //1 => we need to query for the data in the DB, so we know what to delete
    $current = $service->getCurrentDepartmentWithEmployees();
    //get the current employees, that need to be updated
    $oldEmployees = new ArrayCollection();
    foreach ($current->getEmployees() as $employee)
        $oldEmployees->add($employee);
    //2 => get the form data
    $department = $form->getData();
    //3 => check if one or more eployees were deleted
    foreach ($oldEmployees as $employee)
    {
        if (!$department->getEmployees()->contains($employee))
        {//employee was removed, update entity/entities
            $current->getEmployees()->removeElement($employee);
            //depending on the relations you've specified:
            $employee->setDepartment(null);
            $em->persist($employee);
            $em->persist($current);
        }
    }
    $em->flush();
}

请注意,此代码未经测试。最坏情况删除的基本流程(双向,一对多关系倒置,但没有设置ondelete级联限制)。
不过,使用此代码作为引用,您应该能够解决这个问题

关于javascript - Symfony2 嵌入式表单删除按钮功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27858594/

相关文章:

javascript - 使用 vue.js 和 moment.js 创建倒计时

javascript - 如何在where子句中有一个动态查询字段

php - Eloquent 访问器和属性命名

jquery - 谷歌图表 : Data from . json 文件

jquery - MySQL - 3 个不同的表具有相同的列连接在 1 列中

javascript - 使用 jQuery 对表列的值求和

javascript - 字符串化 JSON 内部对象的最佳实践

javascript - 重载属性有什么用?

php - 使用 XDebug 和 Eclipse 逐步执行页面?

php - MYSQL、PHP while循环内的两个连接