class ComponentGenerateForm in Module Builder 8.3
Form showing generated component code.
Hierarchy
- class \Drupal\Core\Form\FormBase implements ContainerInjectionInterface, FormInterface uses DependencySerializationTrait, LoggerChannelTrait, MessengerTrait, LinkGeneratorTrait, RedirectDestinationTrait, UrlGeneratorTrait, StringTranslationTrait
- class \Drupal\Core\Entity\EntityForm implements EntityFormInterface
- class \Drupal\module_builder\Form\ComponentFormBase
- class \Drupal\module_builder\Form\ComponentGenerateForm uses MessengerTrait
- class \Drupal\module_builder\Form\ComponentFormBase
- class \Drupal\Core\Entity\EntityForm implements EntityFormInterface
Expanded class hierarchy of ComponentGenerateForm
File
- src/
Form/ ComponentGenerateForm.php, line 14
Namespace
Drupal\module_builder\FormView source
class ComponentGenerateForm extends ComponentFormBase {
use MessengerTrait;
/**
* {@inheritdoc}
*/
public function form(array $form, FormStateInterface $form_state) {
$form = parent::form($form, $form_state);
$component_data = $this
->getComponentDataObject();
// Get the generation config.
$config = \Drupal::config('module_builder.settings');
$module_config = $config
->get('generator_settings.module');
$config_data = \Drupal::service('module_builder.drupal_code_builder')
->getTask('Configuration')
->getConfigurationData('module');
$config_data
->import($module_config ?? []);
// Get the files.
try {
$files = $this->codeBuilderTaskHandlerGenerate
->generateComponent($component_data, [], $config_data);
} catch (InvalidInputException $e) {
$this
->messenger()
->addError(t("Invalid input for code generator: @message", [
'@message' => $e
->getMessage(),
]));
return $form;
}
// Get the path to the module if it's previously been written.
$existing_module_path = $this
->getExistingModule();
if ($existing_module_path) {
$this
->messenger()
->addWarning(t("This module already exists at @path. It is recommended you use version control to prevent losing any existing code.", [
'@path' => $existing_module_path,
]));
}
$module_name = $this->entity
->id();
if (\Drupal::moduleHandler()
->moduleExists($module_name)) {
$this
->messenger()
->addWarning(t("This module is currently ENABLED on this site. Writing files MAY CAUSE YOUR SITE TO CRASH."));
}
ksort($files);
$statuses = [];
foreach ($files as $filename => $code) {
// We don't actually use the value from the form, as the POST process
// seems to be turning unix line endings into Windows line endings! Store
// it in the form state instead.
$form_state
->set([
'files',
$filename,
], $code);
// Warn the user if the file already exists, and is not committed to git.
$filepath = $existing_module_path . '/' . $filename;
if (file_exists($filepath)) {
// TODO: if the file is clean in git, we can maybe skip this, or say
// it's ok to overwrite?
// Perform the 'git status' command in the module folder, to allow for
// the case where the module has its own git repository.
$git_status = shell_exec("cd {$existing_module_path} && git status {$filename} --porcelain");
if (!empty($git_status)) {
$git_status_code = substr($git_status, 0, 2);
// TODO: These don't take into account that changes might be staged.
switch ($git_status_code) {
case '??':
$statuses[$filename] = t("WARNING: file already exists and is not under git version control! Writing this will lose the existing version.");
break;
case ' M':
$statuses[$filename] = t("WARNING: file already exists and has uncommitted changes! Writing this will lose these.");
break;
}
}
else {
$statuses[$filename] = t("(File already exists)");
}
}
else {
$statuses[$filename] = '';
}
}
$form['files'] = [
'#type' => 'module_builder_generated_files',
'#files' => $files,
'#statuses' => $statuses,
];
return $form;
}
/**
* {@inheritdoc}
*/
public function validateForm(array &$form, FormStateInterface $form_state) {
parent::validateForm($form, $form_state);
// The 'write selected' button needs at least one file to be selected.
if ($form_state
->getTriggeringElement()['#name'] == 'write_selected') {
$values = $form_state
->getValue('filename_list');
$files_to_write = array_filter($values);
if (empty($files_to_write)) {
$form_state
->setError($form['files']['filename_list'], $this
->t("At least one file must be selected to write."));
}
}
}
/**
* {@inheritdoc}
*/
protected function actions(array $form, FormStateInterface $form_state) {
$actions = [];
$actions['write_selected'] = [
'#type' => 'submit',
'#name' => 'write_selected',
'#value' => $this
->t('Write selected files'),
'#submit' => array(
'::writeSelected',
),
'#dropbutton' => 'generate',
];
$actions['write_new'] = [
'#type' => 'submit',
'#name' => 'write_new',
'#value' => $this
->t('Write new files'),
'#submit' => array(
'::writeNew',
),
'#dropbutton' => 'generate',
];
$actions['write_all'] = [
'#type' => 'submit',
'#name' => 'write_all',
'#value' => $this
->t('Write all files'),
'#submit' => array(
'::writeAll',
),
'#dropbutton' => 'generate',
];
return $actions;
}
/**
* Returns the path to the module if it has previously been written.
*
* @return
* A Drupal-relative path to the module folder, or NULL if the module
* does not already exist.
*/
protected function getExistingModule() {
$module_name = $this->entity
->id();
$exists = \Drupal::service('extension.list.module')
->exists($module_name);
if ($exists) {
$module = \Drupal::service('extension.list.module')
->get($module_name);
return $module
->getPath();
}
}
/**
* Submit callback to write all the module files.
*/
public function writeAll(array $form, FormStateInterface $form_state) {
$values = $form_state
->getValues();
$drupal_relative_module_dir = \Drupal::service('module_builder.module_file_writer')
->getRelativeModuleFolder($this->entity
->id());
\Drupal::service('file_system')
->prepareDirectory($path, FileSystemInterface::CREATE_DIRECTORY);
$count_written = 0;
foreach (array_keys($values['file_code']) as $module_relative_filepath) {
$file_contents = $form_state
->get([
'files',
$module_relative_filepath,
]);
$result = \Drupal::service('module_builder.module_file_writer')
->writeSingleFile($drupal_relative_module_dir, $module_relative_filepath, $file_contents);
if ($result) {
$count_written++;
}
else {
$this
->messenger()
->addError(t("Problem writing file @file", [
'@file' => $module_relative_filepath,
]));
}
}
if ($count_written) {
$this
->messenger()
->addStatus(t("Written @count files to folder @folder.", [
'@count' => $count_written,
'@folder' => $drupal_relative_module_dir,
]));
}
}
/**
* Submit callback to write only the selected files.
*/
public function writeSelected(array $form, FormStateInterface $form_state) {
$values = $form_state
->getValue('filename_list');
$files_to_write = array_filter($values);
$drupal_relative_module_dir = \Drupal::service('module_builder.module_file_writer')
->getRelativeModuleFolder($this->entity
->id());
\Drupal::service('file_system')
->prepareDirectory($path, FileSystemInterface::CREATE_DIRECTORY);
$count_written = 0;
foreach (array_keys($files_to_write) as $module_relative_filepath) {
$file_contents = $form_state
->get([
'files',
$module_relative_filepath,
]);
$result = \Drupal::service('module_builder.module_file_writer')
->writeSingleFile($drupal_relative_module_dir, $module_relative_filepath, $file_contents);
if ($result) {
$count_written++;
}
else {
$this
->messenger()
->addError(t("Problem writing file @file", [
'@file' => $module_relative_filepath,
]));
}
}
if ($count_written) {
$this
->messenger()
->addStatus(t("Written @count files to folder @folder.", [
'@count' => $count_written,
'@folder' => $drupal_relative_module_dir,
]));
}
}
/**
* Submit callback to write only new module files.
*/
public function writeNew(array $form, FormStateInterface $form_state) {
$values = $form_state
->getValues();
$drupal_relative_module_dir = \Drupal::service('module_builder.module_file_writer')
->getRelativeModuleFolder($this->entity
->id());
\Drupal::service('file_system')
->prepareDirectory($path, FileSystemInterface::CREATE_DIRECTORY);
$count_written = 0;
foreach (array_keys($values['file_code']) as $module_relative_filepath) {
if (file_exists($drupal_relative_module_dir . '/' . $module_relative_filepath)) {
continue;
}
$file_contents = $form_state
->get([
'files',
$module_relative_filepath,
]);
$result = \Drupal::service('module_builder.module_file_writer')
->writeSingleFile($drupal_relative_module_dir, $module_relative_filepath, $file_contents);
if ($result) {
$count_written++;
}
else {
$this
->messenger()
->addError(t("Problem writing file @file", [
'@file' => $module_relative_filepath,
]));
}
}
if ($count_written) {
$this
->messenger()
->addStatus(t("Written @count files to folder @folder.", [
'@count' => $count_written,
'@folder' => $drupal_relative_module_dir,
]));
}
}
/**
* Submit handler to write a single file.
*/
public function submitWriteSingle(array $form, FormStateInterface $form_state) {
$button = $form_state
->getTriggeringElement();
$button_array_parents = $button['#array_parents'];
$file_key = $button_array_parents[1];
$file_contents = $form_state
->get([
'files',
$file_key,
]);
$drupal_relative_module_dir = \Drupal::service('module_builder.module_file_writer')
->getRelativeModuleFolder($this->entity
->id());
$result = \Drupal::service('module_builder.module_file_writer')
->writeSingleFile($drupal_relative_module_dir, $file_key, $file_contents);
if ($result) {
$this
->messenger()
->addStatus(t("Written file @file to folder @folder.", [
'@file' => $file_key,
'@folder' => $drupal_relative_module_dir,
]));
}
else {
$this
->messenger()
->addError(t("Problem writing file @file", [
'@file' => $file_key,
]));
}
}
}
Members
Name![]() |
Modifiers | Type | Description | Overrides |
---|---|---|---|---|
ComponentFormBase:: |
protected | property | The Drupal Code Builder wrapping service. | |
ComponentFormBase:: |
protected | property | The DCB Generate Task handler. | |
ComponentFormBase:: |
protected | property | The exception thrown by DCB when initialized, if any. | |
ComponentFormBase:: |
public | function |
Form constructor. Overrides EntityForm:: |
|
ComponentFormBase:: |
public static | function |
Instantiates a new instance of this class. Overrides FormBase:: |
|
ComponentFormBase:: |
protected | function | Gets the data object for the entity in the form. | |
ComponentFormBase:: |
public | function |
Sets the form entity. Overrides EntityForm:: |
|
ComponentFormBase:: |
public | function | Sets the generate task. | |
ComponentFormBase:: |
function | Construct a new form object | ||
ComponentGenerateForm:: |
protected | function |
Returns an array of supported actions for the current entity form. Overrides EntityForm:: |
|
ComponentGenerateForm:: |
public | function |
Gets the actual form array to be built. Overrides EntityForm:: |
|
ComponentGenerateForm:: |
protected | function | Returns the path to the module if it has previously been written. | |
ComponentGenerateForm:: |
public | function | Submit handler to write a single file. | |
ComponentGenerateForm:: |
public | function |
Form validation handler. Overrides FormBase:: |
|
ComponentGenerateForm:: |
public | function | Submit callback to write all the module files. | |
ComponentGenerateForm:: |
public | function | Submit callback to write only new module files. | |
ComponentGenerateForm:: |
public | function | Submit callback to write only the selected files. | |
DependencySerializationTrait:: |
protected | property | An array of entity type IDs keyed by the property name of their storages. | |
DependencySerializationTrait:: |
protected | property | An array of service IDs keyed by property name used for serialization. | |
DependencySerializationTrait:: |
public | function | 1 | |
DependencySerializationTrait:: |
public | function | 2 | |
EntityForm:: |
protected | property | The entity being used by this form. | 7 |
EntityForm:: |
protected | property | The entity type manager. | 3 |
EntityForm:: |
protected | property | The module handler service. | |
EntityForm:: |
protected | property | The name of the current operation. | |
EntityForm:: |
private | property | The entity manager. | |
EntityForm:: |
protected | function | Returns the action form element for the current entity form. | |
EntityForm:: |
public | function | Form element #after_build callback: Updates the entity with submitted data. | |
EntityForm:: |
public | function |
Builds an updated entity object based upon the submitted form values. Overrides EntityFormInterface:: |
2 |
EntityForm:: |
protected | function | Copies top-level form values to entity properties | 7 |
EntityForm:: |
public | function |
Returns a string identifying the base form. Overrides BaseFormIdInterface:: |
5 |
EntityForm:: |
public | function |
Gets the form entity. Overrides EntityFormInterface:: |
|
EntityForm:: |
public | function |
Determines which entity will be used by this form from a RouteMatch object. Overrides EntityFormInterface:: |
1 |
EntityForm:: |
public | function |
Returns a unique string identifying the form. Overrides FormInterface:: |
10 |
EntityForm:: |
public | function |
Gets the operation identifying the form. Overrides EntityFormInterface:: |
|
EntityForm:: |
protected | function | Initialize the form state and the entity before the first form build. | 3 |
EntityForm:: |
protected | function | Prepares the entity object before the form is built first. | 3 |
EntityForm:: |
protected | function | Invokes the specified prepare hook variant. | |
EntityForm:: |
public | function | Process callback: assigns weights and hides extra fields. | |
EntityForm:: |
public | function |
Form submission handler for the 'save' action. Overrides EntityFormInterface:: |
41 |
EntityForm:: |
public | function |
Sets the entity manager for this form. Overrides EntityFormInterface:: |
|
EntityForm:: |
public | function |
Sets the entity type manager for this form. Overrides EntityFormInterface:: |
|
EntityForm:: |
public | function |
Sets the module handler for this form. Overrides EntityFormInterface:: |
|
EntityForm:: |
public | function |
Sets the operation for this form. Overrides EntityFormInterface:: |
|
EntityForm:: |
public | function |
This is the default entity object builder function. It is called before any
other submit handler to build the new entity object to be used by the
following submit handlers. At this point of the form workflow the entity is
validated and the form state… Overrides FormInterface:: |
17 |
EntityForm:: |
public | function | ||
EntityForm:: |
public | function | ||
FormBase:: |
protected | property | The config factory. | 1 |
FormBase:: |
protected | property | The request stack. | 1 |
FormBase:: |
protected | property | The route match. | |
FormBase:: |
protected | function | Retrieves a configuration object. | |
FormBase:: |
protected | function | Gets the config factory for this form. | 1 |
FormBase:: |
private | function | Returns the service container. | |
FormBase:: |
protected | function | Gets the current user. | |
FormBase:: |
protected | function | Gets the request object. | |
FormBase:: |
protected | function | Gets the route match. | |
FormBase:: |
protected | function | Gets the logger for a specific channel. | |
FormBase:: |
protected | function |
Returns a redirect response object for the specified route. Overrides UrlGeneratorTrait:: |
|
FormBase:: |
public | function | Resets the configuration factory. | |
FormBase:: |
public | function | Sets the config factory for this form. | |
FormBase:: |
public | function | Sets the request stack object to use. | |
LinkGeneratorTrait:: |
protected | property | The link generator. | 1 |
LinkGeneratorTrait:: |
protected | function | Returns the link generator. | |
LinkGeneratorTrait:: |
protected | function | Renders a link to a route given a route name and its parameters. | |
LinkGeneratorTrait:: |
public | function | Sets the link generator service. | |
LoggerChannelTrait:: |
protected | property | The logger channel factory service. | |
LoggerChannelTrait:: |
protected | function | Gets the logger for a specific channel. | |
LoggerChannelTrait:: |
public | function | Injects the logger channel factory. | |
MessengerTrait:: |
protected | property | The messenger. | 29 |
MessengerTrait:: |
public | function | Gets the messenger. | 29 |
MessengerTrait:: |
public | function | Sets the messenger. | |
RedirectDestinationTrait:: |
protected | property | The redirect destination service. | 1 |
RedirectDestinationTrait:: |
protected | function | Prepares a 'destination' URL query parameter for use with \Drupal\Core\Url. | |
RedirectDestinationTrait:: |
protected | function | Returns the redirect destination service. | |
RedirectDestinationTrait:: |
public | function | Sets the redirect destination service. | |
StringTranslationTrait:: |
protected | property | The string translation service. | 1 |
StringTranslationTrait:: |
protected | function | Formats a string containing a count of items. | |
StringTranslationTrait:: |
protected | function | Returns the number of plurals supported by a given language. | |
StringTranslationTrait:: |
protected | function | Gets the string translation service. | |
StringTranslationTrait:: |
public | function | Sets the string translation service to use. | 2 |
StringTranslationTrait:: |
protected | function | Translates a string to the current language or to a given language. | |
UrlGeneratorTrait:: |
protected | property | The url generator. | |
UrlGeneratorTrait:: |
protected | function | Returns the URL generator service. | |
UrlGeneratorTrait:: |
public | function | Sets the URL generator service. | |
UrlGeneratorTrait:: |
protected | function | Generates a URL or path for a specific route based on the given parameters. |