2013-08-06 2 views
1

У меня есть проблема с контактной формой в Symfony2 здесь есть код, что я сделал и то, что ошибки я получаюзастрял на Symfony2 для контактной формы

<?php 
// src/Aleksandar/IntelMarketingBundle/Resources/views/ContactType.php 
namespace Aleksandar\IntelMarketingBundle\Resources\views; 

use Symfony\Component\Form\AbstractType; 
use Symfony\Component\Form\FormBuilderInterface; 
use Symfony\Component\OptionsResolver\OptionsResolverInterface; 
use Symfony\Component\Validator\Constraints\Email; 
use Symfony\Component\Validator\Constraints\Length; 
use Symfony\Component\Validator\Constraints\NotBlank; 
use Symfony\Component\Validator\Constraints\Collection; 


class ContactType extends AbstractType 
{ 
    public function buildForm(FormBuilderInterface $builder, array $options) 
    { 
     $builder 
      ->add('name', 'text', array(
       'attr' => array(
        'placeholder' => 'What\'s your name?', 
        'pattern'  => '.{2,}' //minlength 
       ) 
      )) 
      ->add('email', 'email', array(
       'attr' => array(
        'placeholder' => 'So I can get back to you.' 
       ) 
      )) 
      ->add('subject', 'text', array(
       'attr' => array(
        'placeholder' => 'The subject of your message.', 
        'pattern'  => '.{3,}' //minlength 
       ) 
      )) 
      ->add('message', 'textarea', array(
       'attr' => array(
        'cols' => 20, 
        'rows' => 2, 
        'placeholder' => 'And your message to me...' 
       ) 
      )); 
    } 

    public function setDefaultOptions(OptionsResolverInterface $resolver) 
    { 
     $collectionConstraint = new Collection(array(
      'name' => array(
       new NotBlank(array('message' => 'Name should not be blank.')), 
       new Length(array('min' => 2)) 
      ), 
      'email' => array(
       new NotBlank(array('message' => 'Email should not be blank.')), 
       new Email(array('message' => 'Invalid email address.')) 
      ), 
      'subject' => array(
       new NotBlank(array('message' => 'Subject should not be blank.')), 
       new Length(array('min' => 3)) 
      ), 
      'message' => array(
       new NotBlank(array('message' => 'Message should not be blank.')), 
       new Length(array('min' => 5)) 
      ) 
     )); 

     $resolver->setDefaults(array(
      'constraints' => $collectionConstraint 
     )); 
    } 

    public function getName() 
    { 
     return 'contact'; 
    } 
} 
?> 

Это код для формы обратной связи, который будет быть оказаны в представлении нет здесь код из моего контроллера

<?php 

namespace Aleksandar\IntelMarketingBundle\Controller; 

use Symfony\Bundle\FrameworkBundle\Controller\Controller; 

class DefaultController extends Controller 
{ 

/** 
* @Route("/contact", _name="contact") 
* @Template() 
*/  

     public function contactAction() 
    { 

    $form = $this->createForm(new ContactType()); 

    if ($request->isMethod('POST')) { 
     $form->bind($request); 

     if ($form->isValid()) { 
      $message = \Swift_Message::newInstance() 
       ->setSubject($form->get('subject')->getData()) 
       ->setFrom($form->get('email')->getData()) 
       ->setTo('[email protected]') 
       ->setBody(
        $this->renderView(
         'AleksandarIntelMarketingBundle::contact.html.php', 
         array(
          'ip' => $request->getClientIp(), 
          'name' => $form->get('name')->getData(), 
          'message' => $form->get('message')->getData() 
         ) 
        ) 
       ); 

      $this->get('mailer')->send($message); 

      $request->getSession()->getFlashBag()->add('success', 'Your email has been sent! Thanks!'); 

      return $this->redirect($this->generateUrl('contact')); 
     } 
    } 

    return array(
     'form' => $form->createView() 
    ); 

    } 


} 

и здесь укоренение

aleksandar_intel_marketing_contactpage: 
    pattern: /contact 
    defaults: { _controller: AleksandarIntelMarketingBundle:Default:contact } 

теперь, когда я пытаюсь открыть страницу его говорит парование:

"[Semantical Error] The annotation "@Route" in method Aleksandar\IntelMarketingBundle\Controller\DefaultController::contactAction() was never imported. Did you maybe forget to add a "use" statement for this annotation? 500 Internal Server Error - AnnotationException "

Если кто знает, что может быть проблема, пожалуйста, дайте мне знать

ответ

3

Как говорится в сообщении об ошибке, вам не хватает использования в верхней части вашего файла контроллера.

Просто добавьте:

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; 

на вершине своего класса DefaultController.

Вы можете заменить маршрутизацию с:

aleksandar_intel_marketing: 
    resource: "@AleksandarIntelMarketingBundle/Controller/DefaultController.php" 
    type:  annotation 

Таким образом, вы используете @Route аннотацию вместо используемого по умолчанию yml образом объявлять маршруты.

http://symfony.com/doc/current/bundles/SensioFrameworkExtraBundle/annotations/routing.html

+0

Хорошо это исправить эту проблему спасибо вам сейчас что-то еще придумать –

+0

FatalErrorException: Ошибка: Class 'Александар \ IntelMarketingBundle \ Controller \ ContactType' не найден в C: \ WAMP \ WWW \ Symfony \ SRC \ Александар \ IntelMarketingBundle \ Controller \ DefaultController.php строка 38 –

+0

У вас отсутствует оператор использования поверх 'DefaultContro ller.php'. Добавьте его в следующую строку: 'use Aleksandar \ IntelMarketingBundle \ Form \ Type \ ContactType;' – cheesemacfly