0

I would like to override the buildForm() method of the Comment module in my custom module.

The method is defined in core/modules/comment/src/Form/CommentAdminOverview.php.

To achieve this, I've created myModuleName/src/Form/MyModuleNameCommentAdminOverview.php, whose first lines are the following.

namespace Drupal\myModuleName\Form; 

use Drupal\comment\CommentInterface;
use Drupal\comment\Form\CommentAdminOverview;
use Drupal\Component\Utility\Unicode;
use Drupal\Core\Datetime\DateFormatterInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Extension\ModuleHandlerInterface;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\user\PrivateTempStoreFactory;
use Symfony\Component\DependencyInjection\ContainerInterface;

class myModuleNameCommentAdminOverview  extends CommentAdminOverview {
  public function buildForm(array $form, FormStateInterface $form_state, $type = 'new') {
    // ...
  }
}

In myModuleName.info.yml I have these lines.

 dependencies:
  - comment:comment

My code is not working. What am I doing wrong?

I have read the following, but I don't understand what I'm doing wrong.

3

These are the two routes for the original form class:

comment.routing.yml:

comment.admin:
  path: '/admin/content/comment'
  defaults:
    _title: 'Comments'
    _form: '\Drupal\comment\Form\CommentAdminOverview'
    type: 'new'
  requirements:
    _permission: 'administer comments'

comment.admin_approval:
  path: '/admin/content/comment/approval'
  defaults:
    _title: 'Unapproved comments'
    _form: '\Drupal\comment\Form\CommentAdminOverview'
    type: 'approval'
  requirements:
    _permission: 'administer comments'

You have to alter both routes like this

  protected function alterRoutes(RouteCollection $collection) {
    if ($route = $collection->get('comment.admin')) {
      $route->setDefault('_form', '\Drupal\mymodule\Form\MyForm');
    }
  }

in a RouteSubscriber.

  • Many thanks by your answer. The problem persists. alterRoute() is called and It's works but my buildform() method hasn't been called. – Agriesean Nov 17 '17 at 11:33
  • What you should check first is the router table, you can use the module Devel (/devel/routes) or Drupal Console: drupal debug:router comment.admin – 4k4 Nov 17 '17 at 14:42
  • 1
    Just run the command myself and found out, that in D8.4 a view has replaced this route. So if you want that your code runs, you have to disable this view, see drupal.org/node/2898013 – 4k4 Nov 17 '17 at 14:53

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.