Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

Drupal 8: Forms

1,595 views

Published on

Working with forms in Drupal 8 modules, a presentation at Drupal Meetup Stuttgart, 05/07/2015

Published in: Internet
  • Be the first to comment

Drupal 8: Forms

  1. 1. Drupal 8: FormsDrupal 8: Forms Working with forms in Drupal 8 modulesWorking with forms in Drupal 8 modules Drupal Meetup StuttgartDrupal Meetup Stuttgart 05/07/2015
  2. 2. 1. Creating a form1. Creating a form
  3. 3. <?php /** * @file * Contains DrupalconfigFormConfigExportForm. */ namespace DrupalconfigForm; use DrupalCoreFormFormBase; use DrupalCoreFormFormStateInterface; class ConfigExportForm extends FormBase { public function getFormId() { return 'config_export_form'; } public function buildForm(array $form, FormStateInterface $form_state) { $form['description'] = array( ... ); ... return $form; } public function submitForm(array &$form, FormStateInterface $form_state) { ... } } Example: /modules/config/src/Form/ConfigExportForm.php
  4. 4. FormsForms are classes extending base forms implementing parent methods / properties using the Drupal Form API
  5. 5. Examples for base formsExamples for base forms FormBase (generic) ConfigFormBase (settings forms) ConfirmFormBase (confirmation forms) XYZFormBase (roll your own)
  6. 6. <?php /** * @file * Contains DrupalconfigFormConfigExportForm. */ namespace DrupalconfigForm; use DrupalCoreFormFormBase; use DrupalCoreFormFormStateInterface; class ConfigExportForm extends FormBase { public function getFormId() { return 'config_export_form'; } public function buildForm(array $form, FormStateInterface $form_state) { $form['description'] = array( '#markup' => '<p>' . $this->t('Use the export button below to download your site configuration.') . '</p>', ); $form['submit'] = array( '#type' => 'submit', '#value' => $this->t('Export'), ); return $form; } public function submitForm(array &$form, FormStateInterface $form_state) { $form_state->setRedirect('config.export_download'); } } Complete class: DrupalconfigFormConfigExportForm
  7. 7. 2. Rendering a form2. Rendering a form
  8. 8. ban.delete: path: '/admin/config/people/ban/delete/{ban_id}' defaults: _form: 'DrupalbanFormBanDelete' _title: 'Delete IP address' requirements: _permission: 'ban IP addresses' ban.routing.yml <?php namespace DrupalbanForm; use DrupalCoreFormConfirmFormBase; ... class BanDelete extends ConfirmFormBase { ... } Rendering a standalone form on a page BanDelete.php
  9. 9. ... public function translatePage() { return array( 'filter' => $this->formBuilder()->getForm('DrupallocaleFormTranslateFilterForm'), 'form' => $this->formBuilder()->getForm('DrupallocaleFormTranslateEditForm'), ); } ... DrupallocaleControllerlocaleContoller <?php namespace DrupallocaleForm; use DrupalCoreFormFormStateInterface; class TranslateFilterForm extends TranslateFormBase { ... } Embedding a form in other markup DrupallocaleFormTranslateFilterForm
  10. 10. 3. Validating a form3. Validating a form
  11. 11. Validate =Validate = Checking form values Create error messages Prepare for form submission ...
  12. 12. public function validateForm(array &$form, FormStateInterface $form_state) { $this->file = file_save_upload('file', $form['file']['#upload_validators'], 'translations://', 0); // Ensure we have the file uploaded. if (!$this->file) { $form_state->setErrorByName('file', $this->t('File to import not found.')) } } Example: DrupallocaleFormImportForm
  13. 13. public function validateForm(array &$form, FormStateInterface $form_state) { $name = trim($form_state->getValue('name')); // Try to load by email. $users = $this->userStorage->loadByProperties(array('mail' => $name, 'status' => '1')); if (empty($users)) { // No success, try to load by name. $users = $this->userStorage->loadByProperties(array('name' => $name, 'status' => '1')); } $account = reset($users); if ($account && $account->id()) { $form_state->setValueForElement(array('#parents' => array('account')), $account); } else { $form_state->setErrorByName('name', $this->t('Sorry, %name is not recognized as a username or an email address.', array('%name' => $name))); } } Example: DrupaluserFormUserPasswordForm
  14. 14. 4. Submitting a form4. Submitting a form
  15. 15. Submit =Submit = Storing form values Output messages Write log information Redirect to new URL ...
  16. 16. public function submitForm(array &$form, FormStateInterface $form_state) { if ($form_state->getValue('confirm')) { $this->commentStorage->delete($this->comments); $count = count($form_state->getValue('comments')); $this->logger('content')->notice('Deleted @count comments.', array('@count' => $count)); drupal_set_message($this->formatPlural($count, 'Deleted 1 comment.', 'Deleted @count comments.')); } $form_state->setRedirectUrl($this->getCancelUrl()); } Example: DrupalcommentFormConfirmDeleteMultiple
  17. 17. public function submitForm(array &$form, FormStateInterface $form_state) { $allowed_types = array_filter($form_state->getValue('book_allowed_types')); // We need to save the allowed types in an array ordered by machine_name so // that we can save them in the correct order if node type changes. // @see book_node_type_update(). sort($allowed_types); $this->config('book.settings') // Remove unchecked types. ->set('allowed_types', $allowed_types) ->set('child_type', $form_state->getValue('book_child_type')) ->save(); parent::submitForm($form, $form_state); } Example: DrupalbookFormBookSettingsForm
  18. 18. 5. Reusing existing forms5. Reusing existing forms
  19. 19. Reuse =Reuse = Create a new form based on an existing form
  20. 20. <?php /** * @file * Contains DrupalblockFormBlockDeleteForm. */ namespace DrupalblockForm; use DrupalCoreEntityEntityDeleteForm; use DrupalCoreUrl; /** * Provides a deletion confirmation form for the block instance deletion form. */ class BlockDeleteForm extends EntityDeleteForm { /** * {@inheritdoc} */ public function getCancelUrl() { return new Url('block.admin_display'); } } Example: DrupalblockFormBlockDeleteForm
  21. 21. 6. Modifying forms6. Modifying forms
  22. 22. Some old friends:Some old friends: hook_form_alter() hook_form_FORM_ID_alter() hook_form_BASE_FORM_ID_alter()
  23. 23. ... use DrupalCoreFormFormStateInterface; ... function mymodule_form_node_form_alter(&$form, FormStateInterface $form_state, $form_id) { // Add a checkbox to the node form about agreeing to terms of use. $form['terms_of_use'] = array( '#type' => 'checkbox', '#title' => t("I agree with the website's terms and conditions."), '#required' => TRUE, ); } Example: mymodule.module
  24. 24. Thank You!Thank You! http://slides.com/drubb http://slideshare.net/drubb

×