我希望你能帮助我解决以下问题。
我想渲染一个嵌入的表单,但没有做到,他们会非常友好地告诉我该怎么做? 感谢您的帮助。
问题:当我保存数据时,会将这些数据插入到数据库中,但是category_id字段中的Product表会插入NULL。
CategoryType
class CategoryType extends AbstractType
{
/**
* @param FormBuilderInterface $builder
* @param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('name')
->add('products', 'collection', array(
'type' => new ProductType(),
'allow_add' => true,
'allow_delete' => true,
'prototype' => true,
'by_reference' => false,
))
;
}
/**
* @param OptionsResolverInterface $resolver
*/
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'DeteccionBundle\Entity\Category'
));
}
/**
* @return string
*/
public function getName()
{
return 'category';
}
}
ProductType
class ProductType extends AbstractType
{
/**
* @param FormBuilderInterface $builder
* @param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('name', 'text')
->add('price')
//->add('category')
;
}
/**
* @param OptionsResolverInterface $resolver
*/
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'DeteccionBundle\Entity\Product'
));
}
/**
* @return string
*/
public function getName()
{
return 'product';
}
}
这是我的模板树枝:
{% block body -%}
{{ form_start(form) }}
{# {{ form(form) }} #}
{{ form_widget(form) }}
{{ form_end(form) }}
<a href="#" id="add-another-email">Añadir otro producto</a>
</ul>
{% endblock %}
{% block javascripts %}
{{ parent() }}
<script>
// keep track of how many email fields have been rendered
var emailCount = '{{ form.products|length }}';
jQuery(document).ready(function() {
jQuery('#add-another-email').click(function(e) {
e.preventDefault();
var productList = jQuery('#category_products');
// grab the prototype template
var newWidget = productList.attr('data-prototype');
// replace the "__name__" used in the id and name of the prototype
// with a number that's unique to your products
// end name attribute looks like name="contact[products][2]"
newWidget = newWidget.replace(/__name__/g, emailCount);
emailCount++;
// create a new list element and add it to the list
var newLi = jQuery('<li></li>').html(newWidget);
newLi.appendTo(productList);
});
})
</script>
{% endblock %}