0

Try and data to database and get an error.:

Uncaught Error: Call to a member function persist() on null in

  public function addNewPostAction()
    {
        // Create new Post entity..
     //   $entityManager =  $container->get('doctrine.entitymanager.orm_default');
        $post = new Post();
        $post->setTitle('Top 10+ Books about Zend Framework 3');
        $post->setContent('Post body goes here');
        $post->setStatus(Post::STATUS_PUBLISHED);
        $currentDate = date('Y-m-d H:i:s');
        $post->setDateCreated($currentDate);
        $this->entityManager->persist($post);
        $this->entityManager->flush();

    }

UPDATE: Error: Zend\Mvc\Controller\PluginManager::get was unable to fetch or create an instance for get

public function addNewPostAction()
{
    // Create new Post entity..
    //   $entityManager = $container->get('doctrine.entitymanager.orm_default');
    $post = new Post();
    $post->setTitle('Top 10+ Books about Zend Framework 3');
    $post->setContent('Post body goes here');
    $post->setStatus(Post::STATUS_PUBLISHED);
    $currentDate = date('Y-m-d H:i:s');
    $dm = $this->get('doctrine.odm.mongodb.document_manager');
    $dm->persist($post);
    $dm->flush();
}
randomUser
  • 91
  • 2
  • 11
  • https://stackoverflow.com/questions/12769982/reference-what-does-this-error-mean-in-php/12769983#12769983 – Sammitch Dec 15 '17 at 21:27

1 Answers1

2

From the 2 samples above, it is obvious you are trying to get doctrine `s entity manager.

1st sample:

$this->entityManager

probably the property $entityManager of the controller is not set, also from the commented code

$entityManager = $container->get('doctrine.entitymanager.orm_default');

it is obvious you are trying to get entity manager.

2nd sample:

$this->get('doctrine.odm.mongodb.document_manager');

I assume this is from a symfony example.

Anyway to get the doctrine manager in your controller, you have to inject it, change your controller constructor to accept it as an argument:

class IndexController extends AbstractActionController
{
    private $doctrineManager;

    public function __construct($doctrineManager)
    {
        $this->doctrineManager = $doctrineManager;
    }

and then inject the doctrine manager to your controller factory in your module.config.php:

'controllers' => [
    'factories' => [
        Controller\IndexController::class => function ($container) {

            return new Controller\IndexController(
                $container->get('doctrine.odm.mongodb.document_manager')
            );
        },
        // ...
    ],
],

Side note: the error "Zend\Mvc\Controller\PluginManager::get was unable to fetch or create an instance for get" is thrown because zend tries any undefined methods to resolve them to a plugin, eg. if you define a plugin with name myAwesomePlugin, you can access it in your action as:

$this->myAwesomePlugin();
Jannes Botis
  • 11,154
  • 3
  • 21
  • 39