试图调用名为“setName”的未定义方法

时间:2015-12-30 11:51:52

标签: php symfony doctrine

我无法将对象持久保存到数据库中。 这是错误link to error  这是位于AppBundle \ Controller上的DefaultController:

<?php

namespace AppBundle\Controller;

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use AppBundle\Entity\Product;
class DefaultController extends Controller
{
    /**
     * @Route("/", name="homepage")
     */
    public function indexAction(Request $request)
    {
        // replace this example code with whatever you need
        return $this->render('default/index.html.twig', [
            'base_dir' => realpath($this->container->getParameter('kernel.root_dir').'/..'),
        ]);
    }
/**
 * @Route("/content", name="db")
 */
    public function createAction()
    {
        $product = new Product();
        $product->setName('A Foo Bar');
        $product->setPrice('19.99');
        $product->setDescription('Lorem ipsum dolor');
        $em = $this->getDoctrine()->getManager();
        $em->persist($product);
        $em->flush();
        return new Response('Created product id '.$product->getId());
    }
}

这是AppBundle \ Entity上的Product实体,字段名称为:

namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
 * @ORM\Entity
 * @ORM\Table(name="product")
 */
class Product
{
    /**
     * @ORM\Column(type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;
    /**
     * @ORM\Column(type="string", length=100)
     */
    protected $name;
    /**
     * @ORM\Column(type="decimal", scale=2)
     */
    protected $price;
    /**
     * @ORM\Column(type="text")
     */
    protected $description;


    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }
}

2 个答案:

答案 0 :(得分:4)

您遇到此错误的原因是:

  • 产品实体没有setter setName
  • 您正在加载错误的实体类,请检查使用命名空间

答案 1 :(得分:3)

这是一个直接的错误,因为你没有生成你的getter和setter。看一下这个Generating Getters and Setters

这就是你要做的事情:

$ php app/console doctrine:generate:entities AppBundle/Entity/Product