0

I would like to access a function from my Form\Form.php in both my Plugin\Block\Block.php and MYMODULE.module.

Related: How to render content generated by controller in custom block? and Inject variables from Controller to Blocks?.

$controller_variable = new ExampleController;, as well as creating a new __contrsuct both give me this error:

ArgumentCountError: Too few arguments to function Drupal\Core\Form\ConfigFormBase::__construct() (I'm always one argument short, 0 of 1, 0r 3 of 4 respectively).

Module Structure:

my_module/
  MYMODULE.module
  routing.yml
  links.menu.yml
  - src/Form/
    - Form_1.php // Module settings form.
    - Form_2.php // Only updates "user.data" through custom submits. values.
 - Plugin/Block/
     - Block.php

(each form has a unique form/settings ID)

MYMODULE.routing.yml:

my_module.settings:
  path: '/path/to/form'
  defaults:
    _form: '\Drupal\my_module\Form\Form_1'
  requirements:
    _permission: 'administer site configuration'
  options:
    _admin_route: TRUE

my_module.form_2:
  defaults:
    _form: '\Drupal\my_module\Form\Form_2'
  requirements:
    _permission: 'access content'

system.admin_group:
  path: '/admin/config/group'
  defaults:
    _controller: '\Drupal\system\Controller\SystemController::systemAdminMenuBlockPage'
    _title: 'Group'
  requirements:
    _permission: 'administer site configuration'

src\Form\Form.php:

class Form extends ConfigFormBase {

  namespace Drupal\my_module\Form;

  public function myCustomFunction() {
    // This uses form/user values to create a new variable.
  }

}

How do you access the above function and its value in:

src\Plugin\Block\Block.php:

class CustomBlock extends BlockBase {

  use Drupal\my_module\Form\Form;

  // This creates an error.
  $controller_variable = new Form();

  public function build() {
    return [
      // Trying to get a conditional for this form so the block gets truly empty when needed.
      \Drupal::formBuilder()->getForm(Form::class),
    ];
  }

}

MYMODULE.module:

use Drupal\my_module\Form\Form;

hook_preprocess_page(&$variables) {
  $variables['form'] = \Drupal::formBuilder()->getForm(Form::class);
}

How can I resolve this error and get the value I need? The routing looks like a culprit, but I do not understand all the intricacies of class injection.

Your Answer

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

Browse other questions tagged or ask your own question.