I have figured out how to create a block from a custom module, by creating a ./src/Plugin/Block folder, then creating a PHP script inside it, with the following code:
<?php
namespace Drupal\MY_MODULE_NAME\Plugin\Block;
use Drupal\Core\Access\AccessResult;
use Drupal\Core\Block\BlockBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Session\AccountInterface;
/**
* Provides a block with a simple text.
*
* @Block(
* id = "BLOCK_MACHINE_NAME",
* admin_label = @Translation("BLOCK_DISPLAY_TITLE"),
* )
*/
class MyBlock extends BlockBase {
/**
* {@inheritdoc}
*/
public function build() {
$html = "MY_BLOCK_CONTENTS_HERE";
return [
'#markup' => $this->t( $html ),
];
}
/**
* {@inheritdoc}
*/
protected function blockAccess(AccountInterface $account) {
return AccessResult::allowedIfHasPermission($account, 'access content');
}
/**
* {@inheritdoc}
*/
public function blockForm($form, FormStateInterface $form_state) {
$config = $this->getConfiguration();
return $form;
}
/**
* {@inheritdoc}
*/
public function blockSubmit($form, FormStateInterface $form_state) {
$this->configuration['my_block_settings'] = $form_state->getValue('my_block_settings');
}
}
My question is, if I want my Custom Module to create a second block, how would I do that?
Do I just create a second script under ./src/Plugin/Block using this same format, and change the BLOCK_MACHINE_NAME and BLOCK_DISPLAY_NAME values?
If I change the line:
class MyBlock extends BlockBase { ... }
to
class MySecondBlock extends BlockBase { ... }
... can I keep all the functions under it the same, eg:
class MySecondBlock extends BlockBase {
public function build() { ... }
protected function blockAccess() { ... }
public function blockForm() { ... }
public function blockSubmit() { ... }
}
Or is it more complicated than that? Do I need to try and build both Blocks from within the same script, and a single set of functions?
Any advice is greatly appreciated, thanks!