4

只想在 Symfony 2.1 中创建一个简单的联系表格。如何?

联系表格.php:

namespace frontend\mainBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilder;

class ContactForm extends AbstractType
{
    public function buildForm(FormBuilder $builder, array $options)
    {
        $builder->add('subject', 'textarea');
        $builder->add('email', 'email');
        $builder->add('message', 'textarea');
    }
    public function getName()
    {
        return 'contact';
    }

}

DefaultController.php

namespace frontend\mainBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use mylib\DataFormatChecker;
use frontend\mainBundle\Form\ContactForm;
use Symfony\Component\HttpFoundation\Request;

class DefaultController extends Controller
{

        public function contactAction(Request $request)
    {

        $task = array();
        $form = $this->createFormBuilder(new ContactForm(), $task);  
        if ($request->getMethod() == 'POST') {
        $form->bindRequest($request);

        if ($form->isValid()) {
            // perform some action, such as saving the task to the database

            //return $this->redirect($this->generateUrl('task_success'));
        }
    }
    return $this->render('frontendmainBundle:Default:contact.html.php', array(
        'form' => $form->createView()
    ));
    }
}

错误:在 ContactForm 的第 8 行声明 frontend\mainBundle\Form\ContactForm::buildForm() 必须与 Symfony\Component\Form\FormTypeInterface::buildForm(Symfony\Component\Form\FormBuilderInterface $builder, array $options) 兼容.php。

怎么了?

不好意思,用过symfony 1.4

4

1 回答 1

4

实际上,该错误与 symfony 无关。这是因为buildForm函数的声明与基类(AbstractType)的声明不匹配。的第一个参数buildForm必须是的实例,FormBuilderInterface而您的第一个参数是的实例FormBuilder

// ...
use Symfony\Component\Form\FormBuilderInterface;

class ContactForm extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    // ...
于 2012-12-23T17:00:21.957 回答