我有一个实体“票证”,我想创建一个包含许多此实体的表单。
所以我创建了一个这样的FormType:
class TicketType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('quantity');
}
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => null,
));
}
public function getName()
{
return 'event';
}
}
这是我的控制器:
$clientTickets = array();
for ($i = 0; $i < 5; $i++) {
clientTickets[] = new Ticket();
}
$formTickets = $this->createForm(new TicketType(), array('tickets' => $clientTickets));
if ($request->getMethod() == 'POST') {
$formTickets->handleRequest($request);
for ($i=0; $i < $formTickets.size(); $i++) {
$em->persist($ticket[$i]);
}
}
最后我的树枝:
{{ form_start(form, {'attr': {'class': 'form-horizontal', 'id': 'msform', 'name': 'myform', 'method': 'POST' }}) }}
{% for clientTicket in form.tickets %}
{{ form_widget(form.quantity) }}
{% endfor %}
{{ form_rest(form) }}
{{ form_end(form) }}
当我进入页面时,我收到此错误:
对象“Symfony \ Component \ Form \ FormView”的方法“票证”没有 存在于YourBundle:文件夹:view.html.twi at line
为什么我做错了?你有解决方案吗?
答案 0 :(得分:2)
你可能需要这样做:
我们有这种表格类型:
class TicketType extends AbstractType {
public function buildForm(FormBuilderInterface $builder, array $options) {
$builder - > add('field1', 'text');
$builder - > add('field2', 'text');
$builder - > add('field3', 'text');
}
public function setDefaultOptions(OptionsResolverInterface $resolver) {
$resolver - > setDefaults(array(
'data_class' = > null,
));
}
public function getName() {
return 'event';
}
}
然后在你的控制器中你需要有这样的东西:
public function testAction( )
{
$clientTickets = array(
'tickets' => array(
array(
'field1' => 'aaa',
'field2' => 'aaa',
'field3' => 'aaa'
),
array(
'field1' => 'bbb',
'field2' => 'bbb',
'field3' => 'bbb'
),
array(
'field1' => 'ccc',
'field2' => 'ccc',
'field3' => 'ccc'
)
)
);
$formTickets = $this->createFormBuilder( $clientTickets )
->add( 'tickets', 'collection', array( 'type' => new TicketType() ) )
->getForm();
if ($formTickets->handleRequest( $this->getRequest() )->isValid()) {
$data = $formTickets->getData();
var_dump( $data );
}
return array(
'form' => $formTickets->createView()
);
}
你的树枝看起来像这样:
{{ form_start(form) }}
<ul>
{% for clientTicket in form.tickets %}
<li>{{ form_row(clientTicket.field1) }} {{ form_row(clientTicket.field2) }} {{ form_row(clientTicket.field3) }}</li>
{% endfor %}
</ul>
{{ form_rest(form) }}
{{ form_end(form) }}
我认为这段代码是自我解释的。希望它有所帮助
答案 1 :(得分:0)
更新: 我想你需要做这样的事情:
{% for i in 0..form|length %}
{{ form[i].method }}
{% endfor %}