SF2形式:错误属性......也不是其中一种方法"得到

时间:2014-03-23 16:33:58

标签: php symfony

我尝试与Symfony 2.4.1建立联系表单,我有以下错误:

Neither the property "contact" nor one of the methods "getContact()", "isContact()", "hasContact()", "__get()" exist and have public access in class "Open\OpcBundle\Entity\Contact". 

我理解这个错误,但我发现在SF2表单文档或网络上有任何解决方法:

控制器代码为:

[..]

class OpcController extends Controller {
public function contactAction(Request $request) {      
  $contact = new Contact();

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

  $form->handleRequest($request);

  return $this->render("OpenOpcBundle:Opc:contact.html.twig",
        array("formu" => $form->createView(),
        )
  );      
}   
}  

联络实体是:

[...] 
class Contact {
  protected $nom;
  protected $courriel;
  protected $sujet;
  protected $msg;

public function getNom() {
  return $this->nom;
}

public function setNom($nom) {
  $this->nom = $nom;
}

public function getCourriel() {
  return $this->courriel;
}

public function setCourriel($courriel) {
  $this->courriel = $courriel;
}

public function getSujet() {
  return $this->sujet;
}

public function setSujet($sujet) {
  $this->sujet = $sujet;
}

public function getMsg() {
  return $this->msg;
}

public function setMsg($msg) {
   $this->msg = $msg;
}  
} 

Form类代码:

public function buildForm(FormBuilderInterface $builder, array $options) {
  $builder->add('contact');
  ->add('nom', 'text'))
    ->add('courriel', 'email')
    ->add('sujet', 'text')
          ->add('msg', 'textarea')
    ->add('submit', 'submit');
}

public function getName() {
  return "Contact";
}

public function setDefaultOptions(OptionsResolverInterface $resolver) {
  $resolver->setDefaults(array('data_class' => 'Open\OpcBundle\Entity\Contact', ));
}
} 

对这个问题有什么看法?感谢

1 个答案:

答案 0 :(得分:21)

您的错误是正确的,并告诉您实体Contact没有contact属性,也没有相关的getter setter方法,而buildForm()中您使用的联系人属性如$builder->add('contact'); 1}}但实体中不存在相关属性,首先在实体中定义属性

class Contact {
  protected $nom;
  protected $courriel;
  protected $sujet;
  protected $msg;
  protected $contact;

public function getContact() {
  return $this->contact;
}

public function setContact($contact) {
  $this->contact= $contact;
}
/* ...
remaining methods in entity 

*/
}

或者如果它是非映射字段,则必须在构建器中将此字段定义为非映射

$builder->add('contact','text',array('mapped'=>false));

通过上面的定义,您不需要更新您的实体