PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, December 31, 2021

[FIXED] Cakephp3 : using another model in a controller

 December 31, 2021     cakephp, cakephp-3.0     No comments   

Issue

I started an app with CakePHP3 and i need to record some users's actions. So, I have migrated my log structure, I have baked my controller & model and now, I try to get a log when a user log in.

I updated my UsersController like this:

namespace App\Controller;

use App\Controller\AppController;
use App\Model\Table\LogsTable;
use App\Model\Entity\User;
use App\Model\Entity\Log;

class UsersController extends AppController {

    public function login(){
      $this->viewBuilder()->layout('external');
      $user = $this->Users->newEntity();
      if($this->request->is('post')){
        $user = $this->Auth->identify();
        if($user){
          //DOING : enregistrement valide$log = new Log();
            $log->user_id = 1;
            $log->action = 'lorem ipsum';
            $log->target_user = 0;
            $log->target_object = 0;
            $log->comment = 'test';
            $logs = new LogsTable();
            $logs->save($log);

          $this->Auth->setUser($user);
          if($this->Auth->user('security') == 'admin'){
            return $this->redirect(['action' => 'admin_index']);
          }else{
            return $this->redirect($this->Auth->redirectUrl());
          }
        }
        //TODO : enregistrement faux
        $this->Flash->error(__('Email or password are wrong.'));
      }
      $this->set(compact('user'));
      $this->set('_serialize', ['user']);
    }

}

But it doesn't work, I have the error message for the save() :

Error: Call to a member function transactional() on a non-object

Any ideas?


Solution

This way

use Cake\ORM\TableRegistry;

$logs = TableRegistry::get('LogsTable');
$logs->save($log);

more info

EDIT since 3.6 you should use

use Cake\ORM\TableLocator

$articles = TableRegistry::getTableLocator()->get('Articles', [
    'className' => 'App\Custom\ArticlesTable',
    'table' => 'my_articles',
    'connection' => $connectionObject,
    'schema' => $schemaObject,
    'entityClass' => 'Custom\EntityClass',
    'eventManager' => $eventManager,
    'behaviors' => $behaviorRegistry
]);

more info here



Answered By - Sam Vimes
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing