Skip to content

Instantly share code, notes, and snippets.

@mortenson
Created August 29, 2019 18:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mortenson/2c600ac96cf90d1bd9728a4abd79d125 to your computer and use it in GitHub Desktop.
Save mortenson/2c600ac96cf90d1bd9728a4abd79d125 to your computer and use it in GitHub Desktop.
Thinking about how Drupal 8 single file components could abstractly provide forms and derive other plugins like blocks
<?php
namespace Drupal\sfc_example\Plugin\SingleFileComponent;
use Drupal\Core\Form\FormStateInterface;
use Drupal\sfc\ComponentBase;
/**
* Contains an example component that provides a block.
*
* @SingleFileComponent(
* id = "dice_roll",
* group = "Example",
* block = {
* "admin_label" = "Dice roll",
* "category" = "Example components",
* }
* )
*/
class DiceRoll extends ComponentBase {
const TEMPLATE = <<<TWIG
<p class="dice-roll">You rolled a {{ roll }}!</p>
{{ cache }}
TWIG;
const CSS = <<<CSS
.dice-roll {
font-size: 20px;
}
CSS;
/**
* {@inheritdoc}
*/
public function buildConfigurationForm(array $form, FormStateInterface $form_state, array $default_values = []){
$form['sides'] = [
'#type' => 'number',
'#title' => $this->t('Sides'),
'#description' => $this->t('The number of sides for the die.'),
'#required' => TRUE,
'#default_value' => isset($default_values['sides']) ? $default_values['sides'] : 2,
'#min' => 2,
];
return $form;
}
/**
* {@inheritdoc}
*/
public function prepareContext(array &$context){
$context['cache'] = ['#cache' => ['max-age' => 0]];
$context['sides'] = isset($context['sides']) ? $context['sides'] : 6;
$context['roll'] = rand(1, $context['sides']);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment