【问题标题】:SF2 form : error Neither the property ... nor one of the methods "getSF2 形式:错误既不是属性...也不是方法之一“get
【发布时间】:2014-03-23 16:33:58
【问题描述】:

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

我的错误在哪里?谢谢

【问题讨论】:

  • 这是一个错字问题 contactContact

标签: php symfony


【解决方案1】:

您的错误是正确的,并告诉您实体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->add('contact','text',array('mapped'=>false));

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

【讨论】:

  • 谢谢,它工作正常。我应该再次阅读有关实体的文档。
  • 但现在我的表单中有一个“联系人”表单字段,我不需要它。
  • @user3049922 如果您不需要从表单构建器中删除 add('contact','text',array('mapped'=>false));
  • Thanx, 'mapped' => false 很有帮助。为此+1。 :)
猜你喜欢
  • 2014-04-30
  • 1970-01-01
  • 2014-02-14
  • 1970-01-01
  • 2015-07-10
  • 2013-07-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多