Call to a member function newEmptyEntity() on null (RESOLVED)

This is making me feel dumb :frowning:

I have a controller for MemberBadges, a MemberBadge can belong to a Member, and can also belong to Form28 (named for old paper based forms used to group MemberBadges)

I have an action in MemberBadgesController “addbymember”, the member_id is based as an argument and this works fine.

However an action in the same controller an action “addbyform28” with the form28_id as an argument gives an error “Call to a member function newEmptyEntity() on null”

Notice (1024) : Undefined property: MemberBadgesController::$MemberBadges in /Applications/MAMP/htdocs/aal-admin2/src/Controller/MemberbadgesController.php on line 181 [in /Applications/MAMP/htdocs/aal-admin2/vendor/cakephp/cakephp/src/Controller/Controller.php, line 337]
Code
Cake\Controller\Controller::__get() /Applications/MAMP/htdocs/aal-admin2/vendor/cakephp/cakephp/src/Controller/Controller.php, line 337
App\Controller\MemberBadgesController::addbyform28() /Applications/MAMP/htdocs/aal-admin2/src/Controller/MemberbadgesController.php, line 181

The offending bit of code is

public function addbyform28($form28Id = null)
{
    $form28sTable = $this->getTableLocator()->get('Form28s');
    $unitsTable = $this->getTableLocator()->get('Units');

    $form28 = $form28sTable->get($form28Id, [
        'contain' => [
            'MemberBadges',
            'Units',
            'Form28Statuses',
        ],
    ]);
    $unit = $unitsTable->get($form28->unit_id);

    $this->Authorization->authorize($unit, 'basicEditor');

    $memberBadge = $this->MemberBadges->newEmptyEntity(); <- THIS LINE

Sure I’m doing something dumb here…

Resolved on slack here

Since not everyone is able to click that slack link (and slack doesn’t save messages indefinitely) lets just document what is happening here:

A controllers model is usually automatically loaded by the used controllers name. So MemberBadgesController should automatically load the MemberBadges model

BUT since you accessed that controller via the URL /memberbadges/ instead of /member-badges/ it tried to load the Memberbadges table instance and set it as $this->Memberbadges instead of $this->MemberBadges

The reason why this happens is the fact, that a OS with a case-insensitive file system is used (usually Windows or MacOS have a default case-insensitive file system).

In the end I would always recommend you look at the generated routes via the debug_kit toolbar, bin/cake routes or simply generate a link via $this->Html->link() to see how to properly access a controller method :wink:

1 Like

Thanks @KevinPfeifer

Slowly migrating big Cake2 app to Cake4, generally baking new files etc. but some cut and pasting of code in views and missed this :frowning:

Handy for next time