cakephp: Undefined index in entity properties for new entity

This is a (multiple allowed):

  • bug

  • enhancement

  • feature-discussion (RFC)

  • CakePHP Version: 3.6.4.

  • Platform and Target: Apache / MySQL.

What you did

I wrote the following reusable Trait for Users:

namespace App\Model\Traits;
trait UsersPropertiesTrait
{

    /**
     * Return fullName of contact.
     *
     * @return string
     */
    protected function _getFullName()
    {
        return $this->_properties['first_name'] . '  ' . $this->_properties['last_name'];
    }

    /**
     * Return fullName + email.
     *
     * @return string
     */
    protected function _getFullLabel()
    {
        return $this->_getFullName() . '  (' . $this->_properties['email'] . ')';
    }
}

Entity code for Users, based on CakeDC Users Class:

namespace App\Model\Entity;

use App\Model\Traits\UsersPropertiesTrait;
use CakeDC\Users\Model\Entity\User;

class MyUser extends User
{
    use UsersPropertiesTrait;

    /**
     * Fields that can be mass assigned using newEntity() or patchEntity().
     *
     * Note that when '*' is set to true, this allows all unspecified fields to
     * be mass assigned. For security purposes, it is advised to set '*' to false
     * (or remove it), and explicitly make individual fields accessible as needed.
     *
     * @var array
     */
    protected $_accessible = [
        '*' => true,
        'id' => false
    ];

    /**
     * Fields that are excluded from JSON versions of the entity.
     *
     * @var array
     */
    protected $_hidden = [
        'password',
        'token'
    ];

    protected $_virtual = ['full_label', 'full_name'];
}

The virtual properties are working if the data already exists. But since my upgrade to 3.6.4, it doesn’t work with a new entity.

What happened

Undefined index: first_name in [/var/www/html/charlie/src/Model/Traits/UsersPropertiesTrait.php, line 14]

The new entity hasn’t the expected keys.

What you expected to happen

What can i do to make this work again ?

About this issue

  • Original URL
  • State: closed
  • Created 6 years ago
  • Comments: 15 (11 by maintainers)

Commits related to this issue

Most upvoted comments

It looks like this behavior is something we might have to revisit for 3.7 then. People do expect those to at least return null instead of throwing notices.

Closing as there’s nothing to be done here. Use the get() method or magic properties instead of $_properties and the error is avoided.

I don’t think any extra documentation is required either. It’s basic PHP knowledge that trying to access an nonexistent array index will result in error.

Instead of using $this->_properties, use $this->get('prop_name') and it will return null for non-existent properties.