0

I am trying to add a custom access callback for the node edit page for a particular content type.

I am using alterRoutes function to change the access callback but I am unable to get the node type in this function.

Am I missing something obvious?

0

in RouteSubscriber.php

namespace Drupal\MODULENAME\Routing;

use Drupal\Core\Routing\RouteSubscriberBase;
use Symfony\Component\Routing\RouteCollection;
use Drupal\Core\Routing\RoutingEvents;

/**
 * Class RouteSubscriber.
 *
 * @package Drupal\MODULENAME\Routing
 * Listens to the dynamic route events.
 */
class RouteSubscriber extends RouteSubscriberBase {

    /**
     * {@inheritdoc}
     */
    public static function getSubscribedEvents() {
        $events[RoutingEvents::ALTER] = ['onAlterRoutes',-9999];  // negative Values means "late"
        return $events;
    }
    /**
     * {@inheritdoc}
    */
    protected function alterRoutes(RouteCollection $collection) {
        if ($route = $collection->get('entity.node.edit_form')) {
            $route->setRequirement('_custom_access','\Drupal\MODULENAME\Controller\MYCONTROLLER::access');
        }
    }

}

and in MYCONTROLLER.php

namespace Drupal\MODULENAME\Controller;

use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Session\AccountInterface;

/**
 * Class Inactiveusers
 * @package Drupal\MODULENAME\Controller
 */
class MYCONTROLLER extends ControllerBase {
    function access(AccountInterface $account){
        if($node = \Drupal::routeMatch()->getParameter('node')){
            if ($node->getType() == 'page' && $node->isPublished()) {
                return \Drupal\Core\Access\AccessResult::forbidden();
            }return \Drupal\Core\Access\AccessResult::neutral();
        }
        return \Drupal\Core\Access\AccessResult::neutral();
    }
}
1

There are o node type specific edit routes, only one. You'd have to alter that and then in your access callback, decide if it is your node type or not.

But, why don't you just implement hook_node_access() and check for the update operation? That allows you to control access to that page and also any edit operation elsewhere on th system, on whatever condition that you want.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.