user1077915
user1077915

Reputation: 894

CAKEPHP 3 - Flash component unrecognized after used inside component

I have wrote a component ( isPilotFree ) that makes some checks.

<?php

namespace App\Controller\Component;

use Cake\Controller\Component;
use Cake\Controller\Controller;

class SharedComponent extends Component
{
    public $components = [ 'Flash' ];

    /** check any pilot overlap
    *
    * @param string|null booking record
    * @return true / false
    **/

    public function pilotIsFree( $booking, $who )
    {
        $controller = $this->_registry->getController();

        $Bookings = $controller->Bookings;

        $res = true;

        if( $booking->id == null ) 
            $booking_id = -1;
        else
            $booking_id = $booking->id;

        if( $res )
        {
            $bookings =  $Bookings->find( 'all' )->Where( [ 'provider_pk != ' =>  $booking->provider_pk, 'Bookings.id !=' => $booking_id, $who, 'start = ' => $booking->start ] );

            $res = $bookings->count() == 0;
        }

        // deleted some lines for simplicity
        ... ... ...             

        if( !$res ) 
        {
            $this->Flash->error( __('The pilot is not available.') );
        }

        return( $res );
    }

}
?>

This component is called from inside a controller as :

        if( $this->Shared->pilotIsFree( $booking, [ 'Bookings.requester_pk =' => $booking->requester_pk ] )  )
        {
          ... ... ..
        }

The component is loaded in the controller as :

/**
 * Initialization method
 *
 * @return none
 */
public function initialize()
{
    $this->loadComponent( 'Shared' );
}

The issue that I'm having now is that the Flash call inside the component works fine, but when I try to trigger a flash message from inside the controller I got this error :

Error: Call to a member function success() on boolean File .../src/Controller/BookingsController.php Line: 191

The only way I found to make it work fine is to add at the beginning of the controller this :

public $components = [ 'Flash' ];

It is not supposed the flash component to be loaded in the parent class AppController. Actually if I do not load / use my custom component, I can trigger Flash messages from inside the controller without adding the previous line.

Am I missing something ?

Thanks. Regards. Facundo.

Upvotes: 0

Views: 447

Answers (1)

JazzCat
JazzCat

Reputation: 4573

You need to put this inside your controller.

public function initialize()
{
    parent::initialize();
    $this->loadComponent('Flash');
}

Or inside AppController without parent::initialize();

Upvotes: 1

Related Questions