Description of the feature

The autoActiveLink configuration option allows the navbar helper to deduce the active link automatically and add an active class to the surrounding <li> element.

Enabling the feature

The feature is enabled by default, you can enable or disable it by doing:

$this->Navbar->setConfig('autoActiveLink', false);
$this->Navbar->setConfig('autoActiveLink', true);

When the feature is disable, you can always specify the active option to the NavbarHelper::link() method:

echo $this->Navbar->link('Link', $url, ['active' => true]);

The active option will always override the automatic value, even when autoActiveLink is true:

$this->Navbar->setConfig('autoActiveLink', true);
echo $this->Navbar->link('Link', $url);
// '<li class="active">...</li>
echo $this->Navbar->link('Link', $url, ['active' => false]);
// '<li>...</li>

Explanation of the deduction

The autoActiveLink feature rely on the UrlComparerTrait::compareUrls() method and do not compare URL strictly, it rather check if the first URL is the root path of the second.

Below is a list of combinations to better understand the feature:

Link URL Normalized Current URL Normalized
    ['controller' => 'Pages',
     'action' => 'display', 'faq']
/pages/display/faq /pages/faq /pages/display/faq
/pages/credits /pages/display/credits
    ['controller' => 'Users',
     'action' => 'edit']
/users/edit /users/edit/1 /users/edit/1
/users/edit /users/edit
    ['controller' => 'Users',
     'action' => 'index']
/users/index /users /users/index
/users/edit /users/edit

The query parameters (?) and the anchor (#) are never used for comparison.

Customizing the comparison

When calling the link() method, you can pass an array as the active options to customize the way the comparison is made. This array should contains which part of the URL you want to include in the left part of the comparison. Below is an example that removes the passed parameters and the action:

echo $this->Navbar->link($name, $url, [
    'active' => [
        'action' => false,
        'pass' => false
    ];
]);

Now:

Link URL Normalized Current URL Normalized
    ['controller' => 'Users',
     'action' => 'index']
/users/index /users /users/index
/users/edit /users/edit

Notice that the /users URL now matches the /users/edit URL. The possible keys in the array are defined by the UrlComparerTrait::_parts property:

public $_parts = ['plugin', 'prefix', 'controller', 'action', 'pass'];;