Skip to content

Instantly share code, notes, and snippets.

@opi
Last active January 14, 2021 11:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save opi/507ddacb43ab15b496e2ef99258e6b9d to your computer and use it in GitHub Desktop.
Save opi/507ddacb43ab15b496e2ef99258e6b9d to your computer and use it in GitHub Desktop.
Drupal9 - Create field_group from drush command
<?php
namespace Drupal\opitools\Commands;
use Drush\Commands\DrushCommands;
use Drupal\Core\Language\LanguageInterface;
/**
* A Drush commandfile.
*
* In addition to this file, you need a drush.services.yml
* in root of your module, and a composer.json file that provides the name
* of the services file to use.
*/
class OpiToolsCommands extends DrushCommands {
/**
* Create field_group.
*
* @param string $bundle
* Node bundle.
*
* @param string $context
* Context: view / form. Ex: 'form', 'form:default', 'view:full', etc.
*
* @param string $label
* Field group label.
*
* @command opitools:create-field-group
*
* @example opitools:create-field-group mybundle context:mode Label (context is form/view, mode is default or view_mode)
*/
public function createFieldGroup($bundle, $context, $label) {
$mode = 'default';
if (strpos($context, ':')) {
list($context, $mode) = explode(':', $context);
}
$new_group = (object) [
"group_name" => $this->getMachineName("group_" . $label),
"entity_type" => "node",
"bundle" => $bundle,
"mode" => "default",
"context" => $context,
"children" => [],
"parent_name" => "",
"weight" => 20,
"format_type" => "details",
"region" => "hidden",
"format_settings" => [
"id" => "",
"classes" => "",
"description" => "",
"open" => 0,
"required_fields" => 1
],
"label" => $label,
];
field_group_group_save($new_group);
$this->output()->writeln(t('New group @label ( @groupname ) successfully created.', [
'@label' => $new_group->label,
'@groupname' => $new_group->group_name,
]));
\Drupal::cache()->invalidate('field_groups');
}
/**
* Generates a machine name from a string.
*
* This is basically the same as what is done in
* \Drupal\Core\Block\BlockBase::getMachineNameSuggestion() and
* \Drupal\system\MachineNameController::transliterate(), but it seems
* that so far there is no common service for handling this.
*
* @param string $string
*
* @return string
*
* @see \Drupal\Core\Block\BlockBase::getMachineNameSuggestion()
* @see \Drupal\system\MachineNameController::transliterate()
*/
protected function getMachineName($string) {
$transliterated = \Drupal::transliteration()->transliterate($string, LanguageInterface::LANGCODE_DEFAULT, '_');
$transliterated = mb_strtolower($transliterated);
$transliterated = preg_replace('@[^a-z0-9_.]+@', '_', $transliterated);
return $transliterated;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment