SF2表单:错误没有一种方法“得到”


SF2 form : error Neither the property ... nor one of the methods "get

我试着用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', ));
}
} 

我错在哪里?由于

您的错误是正确的,并告诉您,您的实体Contact没有contact属性,没有相关的getter setter方法,而在您的buildForm()中,您使用了$builder->add('contact');等接触属性,但实体中没有相关属性存在,首先在您的实体中定义属性

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中定义这个字段为非映射

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

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

相关文章: