4
votes

Just want to create a simple contact form in Symfony 2.1. How?

ContactForm.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()
    ));
    }
}

Error: Declaration of frontend\mainBundle\Form\ContactForm::buildForm() must be compatible with Symfony\Component\Form\FormTypeInterface::buildForm(Symfony\Component\Form\FormBuilderInterface $builder, array $options) in line 8 in ContactForm.php.

What is wrong?

Sorry, used to symfony 1.4

1

1 Answers

4
votes

The error has nothing to do with symfony, actually. It occurs because declaration of buildForm function does not match with that of base class (AbstractType). The first parameter of buildForm must be an instance of FormBuilderInterface whereas your first parameter is instance of FormBuilder

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

class ContactForm extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    // ...