You are here

public function PluginFormFactory::createInstance in Drupal 8

Same name and namespace in other branches
  1. 9 core/lib/Drupal/Core/Plugin/PluginFormFactory.php \Drupal\Core\Plugin\PluginFormFactory::createInstance()

Creates a new form instance.

Parameters

\Drupal\Core\Plugin\PluginWithFormsInterface $plugin: The plugin the form is for.

string $operation: The name of the operation to use, e.g., 'add' or 'edit'.

string $fallback_operation: (optional) The name of the fallback operation to use.

Return value

\Drupal\Core\Plugin\PluginFormInterface A plugin form instance.

Throws

\Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException

Overrides PluginFormFactoryInterface::createInstance

File

core/lib/Drupal/Core/Plugin/PluginFormFactory.php, line 34

Class

PluginFormFactory
Provides form discovery capabilities for plugins.

Namespace

Drupal\Core\Plugin

Code

public function createInstance(PluginWithFormsInterface $plugin, $operation, $fallback_operation = NULL) {
  if (!$plugin
    ->hasFormClass($operation)) {

    // Use the default form class if no form is specified for this operation.
    if ($fallback_operation && $plugin
      ->hasFormClass($fallback_operation)) {
      $operation = $fallback_operation;
    }
    else {
      throw new InvalidPluginDefinitionException($plugin
        ->getPluginId(), sprintf('The "%s" plugin did not specify a "%s" form class', $plugin
        ->getPluginId(), $operation));
    }
  }
  $form_class = $plugin
    ->getFormClass($operation);

  // If the form specified is the plugin itself, use it directly.
  if (ltrim(get_class($plugin), '\\') === ltrim($form_class, '\\')) {
    $form_object = $plugin;
  }
  else {
    $form_object = $this->classResolver
      ->getInstanceFromDefinition($form_class);
  }

  // Ensure the resulting object is a plugin form.
  if (!$form_object instanceof PluginFormInterface) {
    throw new InvalidPluginDefinitionException($plugin
      ->getPluginId(), sprintf('The "%s" plugin did not specify a valid "%s" form class, must implement \\Drupal\\Core\\Plugin\\PluginFormInterface', $plugin
      ->getPluginId(), $operation));
  }
  if ($form_object instanceof PluginAwareInterface) {
    $form_object
      ->setPlugin($plugin);
  }
  return $form_object;
}