It's as easy as checking for and then setting a cookie in a custom module.
One of the new features in Craft CMS 5 control panel is the collapsable sidebar. It’s a handy feature that allows you to have more horizontal space while publishing content. Craft sets a cookie the first time you collapse the sidebar with a value of collapsed
. After that, it updates the cookie with the value of expanded
or collapsed
depending on the action you take.
However, I wanted a way to make it the sidebar navigation collapsed default, and Craft doesn’t yet allow that as a setting or preference.
Time to call up a custom module and a little bit of PHP to set a cookie.
If your project doesn’t already have a module, you’ll need to create. The easiest way to do that is using Craft Generator.
Once you have your module created, go the module file (mine is called sitemodule.php
and add this code inside of Craft::$app->onInit()
since we don’t need to run this code until Craft is fully initialized:
$cookieName = 'Craft-' . Craft::$app->getSystemUid() . ':sidebar';
if (!Craft::$app->request->getRawCookies()->get($cookieName)) {
$expiryTime = time() + 86400 * 365; // One year from now
setcookie($cookieName, 'collapsed', $expiryTime, '/');
}
First, we set the cookie name we’ll check or create to the same cookie name that Craft 5 will set. After that, we check for the cookie; if it is not set, we set it with the value of collapsed
and a expiration of a year from the time set.
If the cookie does exist, then we don’t set anything because we don’t want to override an expanded sidebar and make it collapsed. We’ll assume it is expanded for a reason and honor that.
To test the code, clear the cookie, if set, from your browser and reload the control panel. Hello, collapsed sidebar!