richerlariviere
richerlariviere

Reputation: 809

Virtual fields with Cakephp 3

I need to have a virtual property in my user entity. I followed the CakePHP book.

UserEntity.php

namespace App\Model\Entity;

use Cake\ORM\Entity;

class User extends Entity {

    protected $_virtual = ['full_name'];

    protected function _getFullName() {
        return $this->_properties['firstname'] . ' ' . $this->_properties['lastname'];
    }
}

In a controller

$users = TableRegistry::get('Users');
$user = $users->get(29);
$firstname = $user->firstname; // $firstname: "John"
$lastname = $user->lastname; // $lastname: "Doe"
$value = $user->full_name; // $value: null

I followed exactly the book and I only get a null value.

Upvotes: 6

Views: 12875

Answers (3)

Hatem Mahmoud
Hatem Mahmoud

Reputation: 9

namespace App\Model\Entity;

use Cake\ORM\Entity;

class User extends Entity {

protected $_virtual = ['full_name'];

 protected function _getFullName() {
   return $this->firstname . ' ' . $this->lastname ;
 }
} 

you can back to resource here

Upvotes: 0

Ben Mueller
Ben Mueller

Reputation: 9

Why not just go for something like this?

/*
 * Return Fullname
 */
public function getFullname()
{
    $name = $this->firstname . ' ' . $this->lastname;
    return $name;
}

Upvotes: -1

richerlariviere
richerlariviere

Reputation: 809

According to @ndm, the problem was due to a bad file naming. I named the user entity class UserEntity.php. The CakePHP name conventions says that:

The Entity class OptionValue would be found in a file named OptionValue.php.

Thanks.

Upvotes: 7

Related Questions