Example #1
1
 /**
  * {@inheritdoc}
  */
 public function form(array $form, FormStateInterface $form_state)
 {
     $view = $this->entity;
     $form['#prefix'] = '<div id="views-preview-wrapper" class="views-admin clearfix">';
     $form['#suffix'] = '</div>';
     $form['#id'] = 'views-ui-preview-form';
     $form_state->disableCache();
     $form['controls']['#attributes'] = array('class' => array('clearfix'));
     $form['controls']['title'] = array('#prefix' => '<h2 class="view-preview-form__title">', '#markup' => $this->t('Preview'), '#suffix' => '</h2>');
     // Add a checkbox controlling whether or not this display auto-previews.
     $form['controls']['live_preview'] = array('#type' => 'checkbox', '#id' => 'edit-displays-live-preview', '#title' => $this->t('Auto preview'), '#default_value' => \Drupal::config('views.settings')->get('ui.always_live_preview'));
     // Add the arguments textfield
     $form['controls']['view_args'] = array('#type' => 'textfield', '#title' => $this->t('Preview with contextual filters:'), '#description' => $this->t('Separate contextual filter values with a "/". For example, %example.', array('%example' => '40/12/10')), '#id' => 'preview-args');
     $args = array();
     if (!$form_state->isValueEmpty('view_args')) {
         $args = explode('/', $form_state->getValue('view_args'));
     }
     $user_input = $form_state->getUserInput();
     if ($form_state->get('show_preview') || !empty($user_input['js'])) {
         $form['preview'] = array('#weight' => 110, '#theme_wrappers' => array('container'), '#attributes' => array('id' => 'views-live-preview'), 'preview' => $view->renderPreview($this->displayID, $args));
     }
     $uri = $view->urlInfo('preview-form');
     $uri->setRouteParameter('display_id', $this->displayID);
     $form['#action'] = $uri->toString();
     return $form;
 }
Example #2
0
 /**
  * {@inheritdoc}
  */
 public function buildForm(array $form, FormStateInterface $form_state)
 {
     if ($form_state->isRebuilding()) {
         $form_state->setUserInput(array());
     }
     // Initialize
     $storage = $form_state->getStorage();
     if (empty($storage)) {
         $user_input = $form_state->getUserInput();
         if (empty($user_input)) {
             $_SESSION['constructions'] = 0;
         }
         // Put the initial thing into the storage
         $storage = ['thing' => ['title' => 'none', 'value' => '']];
         $form_state->setStorage($storage);
     }
     // Count how often the form is constructed.
     $_SESSION['constructions']++;
     drupal_set_message("Form constructions: " . $_SESSION['constructions']);
     $form['title'] = array('#type' => 'textfield', '#title' => 'Title', '#default_value' => $storage['thing']['title'], '#required' => TRUE);
     $form['value'] = array('#type' => 'textfield', '#title' => 'Value', '#default_value' => $storage['thing']['value'], '#element_validate' => array('::elementValidateValueCached'));
     $form['continue_button'] = array('#type' => 'button', '#value' => 'Reset');
     $form['continue_submit'] = array('#type' => 'submit', '#value' => 'Continue submit', '#submit' => array('::continueSubmitForm'));
     $form['submit'] = array('#type' => 'submit', '#value' => 'Save');
     if (\Drupal::request()->get('cache')) {
         // Manually activate caching, so we can test that the storage keeps working
         // when it's enabled.
         $form_state->setCached();
     }
     if ($this->getRequest()->get('immutable')) {
         $form_state->addBuildInfo('immutable', TRUE);
     }
     return $form;
 }
Example #3
0
 /**
  * {@inheritdoc}
  */
 public function submitForm(array &$form, FormStateInterface $form_state)
 {
     global $base_url;
     // Test discovery does not run upon form submission.
     simpletest_classloader_register();
     // This form accepts arbitrary user input for 'tests'.
     // An invalid value will cause the $class_name lookup below to die with a
     // fatal error. Regular user access mechanisms to this form are intact.
     // The only validation effectively being skipped is the validation of
     // available checkboxes vs. submitted checkboxes.
     // @todo Refactor Form API to allow to POST values without constructing the
     //   entire form more easily, BUT retaining routing access security and
     //   retaining Form API CSRF #token security validation, and without having
     //   to rely on form caching.
     $user_input = $form_state->getUserInput();
     if ($form_state->isValueEmpty('tests') && !empty($user_input['tests'])) {
         $form_state->setValue('tests', $user_input['tests']);
     }
     $tests_list = array();
     foreach ($form_state->getValue('tests') as $class_name => $value) {
         if ($value === $class_name) {
             if (is_subclass_of($class_name, 'PHPUnit_Framework_TestCase')) {
                 $test_type = 'phpunit';
             } else {
                 $test_type = 'simpletest';
             }
             $tests_list[$test_type][] = $class_name;
         }
     }
     if (!empty($tests_list)) {
         putenv('SIMPLETEST_BASE_URL=' . $base_url);
         $test_id = simpletest_run_tests($tests_list, 'drupal');
         $form_state->setRedirect('simpletest.result_form', array('test_id' => $test_id));
     }
 }
Example #4
0
 /**
  * {@inheritdoc}
  */
 public static function valueCallback(&$element, $input, FormStateInterface $form_state)
 {
     if ($input !== FALSE) {
         if (!empty($input)) {
             // If we're dealing with Mozilla or Opera, we're lucky. It will
             // return a proper value, and we can get on with things.
             return $element['#return_value'];
         } else {
             // Unfortunately, in IE we never get back a proper value for THIS
             // form element. Instead, we get back two split values: one for the
             // X and one for the Y coordinates on which the user clicked the
             // button. We'll find this element in the #post data, and search
             // in the same spot for its name, with '_x'.
             $input = $form_state->getUserInput();
             foreach (explode('[', $element['#name']) as $element_name) {
                 // chop off the ] that may exist.
                 if (substr($element_name, -1) == ']') {
                     $element_name = substr($element_name, 0, -1);
                 }
                 if (!isset($input[$element_name])) {
                     if (isset($input[$element_name . '_x'])) {
                         return $element['#return_value'];
                     }
                     return NULL;
                 }
                 $input = $input[$element_name];
             }
             return $element['#return_value'];
         }
     }
 }
 public function submitForm(array &$form, \Drupal\Core\Form\FormStateInterface $form_state)
 {
     // Check to make sure that the file was uploaded to the server properly
     $userInputValues = $form_state->getUserInput();
     $uri = db_select('file_managed', 'f')->condition('f.fid', $userInputValues['import']['fids'], '=')->fields('f', array('uri'))->execute()->fetchField();
     if (!empty($uri)) {
         if (file_exists(\Drupal::service("file_system")->realpath($uri))) {
             // Open the csv
             $handle = fopen(\Drupal::service("file_system")->realpath($uri), "r");
             // Go through each row in the csv and run a function on it. In this case we are parsing by '|' (pipe) characters.
             // If you want commas are any other character, replace the pipe with it.
             while (($data = fgetcsv($handle, 0, ',', '"')) !== FALSE) {
                 $operations[] = ['csvimport_import_batch_processing', [$data]];
             }
             // Once everything is gathered and ready to be processed... well... process it!
             $batch = ['title' => t('Importing CSV...'), 'operations' => $operations, 'finished' => $this->csvimport_import_finished(), 'error_message' => t('The installation has encountered an error.'), 'progress_message' => t('Imported @current of @total products.')];
             batch_set($batch);
             fclose($handle);
         } else {
             drupal_set_message(t('Not able to find file path.'), 'error');
         }
     } else {
         drupal_set_message(t('There was an error uploading your file. Please contact a System administator.'), 'error');
     }
 }
Example #6
0
 /**
  * Clear values from upload form element.
  *
  * @param array $element
  *   Upload form element.
  * @param \Drupal\Core\Form\FormStateInterface $form_state
  *   Form state object.
  */
 protected function clearFormValues(array &$element, FormStateInterface $form_state)
 {
     // We propagated entities to the other parts of the system. We can now remove
     // them from our values.
     $form_state->setValueForElement($element['upload']['fids'], '');
     NestedArray::setValue($form_state->getUserInput(), $element['upload']['fids']['#parents'], '');
 }
 public function ajaxSubmit(array &$form, FormStateInterface $form_state)
 {
     //---------------------------------------------------------------
     //            get the own attributes values of the swap
     //---------------------------------------------------------------
     //get all the swaps plugins
     $manager = \Drupal::service('plugin.manager.swaps');
     $swaps = $manager->getDefinitions();
     $swap = $swaps['column'];
     $input = $form_state->getUserInput();
     $settings = array();
     $settings['size'] = $input['swaps_column_size'];
     $settings['number'] = $input['swaps_column_number'];
     //---------------------------------------------------------------
     // get the default attributes values of the swap (required for visual help)
     //---------------------------------------------------------------
     $settings['swapId'] = $swap['id'];
     $settings['swapName'] = $swap['name'];
     $settings['container'] = $swap['container'];
     SwapDefaultAttributes::getDefaultFormElementsValues($settings, $input);
     //---------------------------------------------------------------
     //            create the ajax response
     //---------------------------------------------------------------
     $visualSettings = array('visualContentLayout' => array('attributes' => $settings));
     $response = new AjaxResponse();
     $response->addCommand(new CloseModalDialogCommand());
     $response->addCommand(new SettingsCommand($visualSettings, FALSE));
     return $response;
 }
 /**
  * {@inheritdoc}
  */
 public function buildForm(array $form, FormStateInterface $form_state)
 {
     $form['one'] = array('#type' => 'textfield', '#title' => 'One', '#required' => TRUE);
     $form['two'] = array('#type' => 'textfield', '#title' => 'Two', '#required' => TRUE);
     $form['actions'] = array('#type' => 'actions');
     $user_input = $form_state->getUserInput();
     $form['actions']['submit'] = array('#type' => 'submit', '#value' => 'Save', '#limit_validation_errors' => array(array($user_input['section'])), '#submit' => array(array($this, 'submitForm')));
     return $form;
 }
Example #9
0
 protected function valueForm(&$form, FormStateInterface $form_state)
 {
     $users = $this->value ? User::loadMultiple($this->value) : array();
     $default_value = EntityAutocomplete::getEntityLabels($users);
     $form['value'] = array('#type' => 'entity_autocomplete', '#title' => $this->t('Usernames'), '#description' => $this->t('Enter a comma separated list of user names.'), '#target_type' => 'user', '#tags' => TRUE, '#default_value' => $default_value, '#process_default_value' => FALSE);
     $user_input = $form_state->getUserInput();
     if ($form_state->get('exposed') && !isset($user_input[$this->options['expose']['identifier']])) {
         $user_input[$this->options['expose']['identifier']] = $default_value;
         $form_state->setUserInput($user_input);
     }
 }
 /**
  * {@inheritdoc}
  */
 public function buildForm(array $form, FormStateInterface $form_state)
 {
     $conf_path = './' . conf_path(FALSE);
     $settings_file = $conf_path . '/settings.php';
     $form['#title'] = $this->t('Database configuration');
     $drivers = drupal_get_database_types();
     $drivers_keys = array_keys($drivers);
     // Unless there is input for this form (for a non-interactive installation,
     // input originates from the $settings array passed into install_drupal()),
     // check whether database connection settings have been prepared in
     // settings.php already.
     // Note: The installer even executes this form if there is a valid database
     // connection already, since the submit handler of this form is responsible
     // for writing all $settings to settings.php (not limited to $databases).
     $input =& $form_state->getUserInput();
     if (!isset($input['driver']) && ($database = Database::getConnectionInfo())) {
         $input['driver'] = $database['default']['driver'];
         $input[$database['default']['driver']] = $database['default'];
     }
     if (isset($input['driver'])) {
         $default_driver = $input['driver'];
         // In case of database connection info from settings.php, as well as for a
         // programmed form submission (non-interactive installer), the table prefix
         // information is usually normalized into an array already, but the form
         // element only allows to configure one default prefix for all tables.
         $prefix =& $input[$default_driver]['prefix'];
         if (isset($prefix) && is_array($prefix)) {
             $prefix = $prefix['default'];
         }
         $default_options = $input[$default_driver];
     } else {
         $default_driver = current($drivers_keys);
         $default_options = array();
     }
     $form['driver'] = array('#type' => 'radios', '#title' => $this->t('Database type'), '#required' => TRUE, '#default_value' => $default_driver);
     if (count($drivers) == 1) {
         $form['driver']['#disabled'] = TRUE;
     }
     // Add driver specific configuration options.
     foreach ($drivers as $key => $driver) {
         $form['driver']['#options'][$key] = $driver->name();
         $form['settings'][$key] = $driver->getFormOptions($default_options);
         $form['settings'][$key]['#prefix'] = '<h2 class="js-hide">' . $this->t('@driver_name settings', array('@driver_name' => $driver->name())) . '</h2>';
         $form['settings'][$key]['#type'] = 'container';
         $form['settings'][$key]['#tree'] = TRUE;
         $form['settings'][$key]['advanced_options']['#parents'] = array($key);
         $form['settings'][$key]['#states'] = array('visible' => array(':input[name=driver]' => array('value' => $key)));
     }
     $form['actions'] = array('#type' => 'actions');
     $form['actions']['save'] = array('#type' => 'submit', '#value' => $this->t('Save and continue'), '#button_type' => 'primary', '#limit_validation_errors' => array(array('driver'), array($default_driver)), '#submit' => array('::submitForm'));
     $form['errors'] = array();
     $form['settings_file'] = array('#type' => 'value', '#value' => $settings_file);
     return $form;
 }
Example #11
0
 /**
  * {@inheritdoc}
  *
  * @param \Drupal\filter\Entity\FilterFormat $filter_format
  *   The filter format for which this dialog corresponds.
  */
 public function buildForm(array $form, FormStateInterface $form_state, FilterFormat $filter_format = NULL)
 {
     // This form is special, in that the default values do not come from the
     // server side, but from the client side, from a text editor. We must cache
     // this data in form state, because when the form is rebuilt, we will be
     // receiving values from the form, instead of the values from the text
     // editor. If we don't cache it, this data will be lost.
     if (isset($form_state->getUserInput()['editor_object'])) {
         // By convention, the data that the text editor sends to any dialog is in
         // the 'editor_object' key. And the image dialog for text editors expects
         // that data to be the attributes for an <img> element.
         $file_element = $form_state->getUserInput()['editor_object'];
         $form_state->set('file_element', $file_element);
         $form_state->setCached(TRUE);
     } else {
         // Retrieve the image element's attributes from form state.
         $file_element = $form_state->get('file_element') ?: [];
     }
     $form['#tree'] = TRUE;
     $form['#attached']['library'][] = 'editor/drupal.editor.dialog';
     $form['#prefix'] = '<div id="editor-file-dialog-form">';
     $form['#suffix'] = '</div>';
     // Load dialog settings.
     $editor = editor_load($filter_format->id());
     $file_upload = $editor->getThirdPartySettings('editor_file');
     $max_filesize = min(Bytes::toInt($file_upload['max_size']), file_upload_max_size());
     $existing_file = isset($file_element['data-entity-uuid']) ? \Drupal::entityManager()->loadEntityByUuid('file', $file_element['data-entity-uuid']) : NULL;
     $fid = $existing_file ? $existing_file->id() : NULL;
     $form['fid'] = array('#title' => $this->t('File'), '#type' => 'managed_file', '#upload_location' => $file_upload['scheme'] . '://' . $file_upload['directory'], '#default_value' => $fid ? array($fid) : NULL, '#upload_validators' => array('file_validate_extensions' => !empty($file_upload['extensions']) ? array($file_upload['extensions']) : array('txt'), 'file_validate_size' => array($max_filesize)), '#required' => TRUE);
     $form['attributes']['href'] = array('#title' => $this->t('URL'), '#type' => 'textfield', '#default_value' => isset($file_element['href']) ? $file_element['href'] : '', '#maxlength' => 2048, '#required' => TRUE);
     if ($file_upload['status']) {
         $form['attributes']['href']['#access'] = FALSE;
         $form['attributes']['href']['#required'] = FALSE;
     } else {
         $form['fid']['#access'] = FALSE;
         $form['fid']['#required'] = FALSE;
     }
     $form['actions'] = array('#type' => 'actions');
     $form['actions']['save_modal'] = array('#type' => 'submit', '#value' => $this->t('Save'), '#submit' => array(), '#ajax' => array('callback' => '::submitForm', 'event' => 'click'));
     return $form;
 }
Example #12
0
 /**
  * Provide a simple textfield for equality
  */
 protected function valueForm(&$form, FormStateInterface $form_state)
 {
     $form['value'] = array('#type' => 'textfield', '#title' => $this->t('Value'), '#size' => 30, '#default_value' => $this->value);
     if ($exposed = $form_state->get('exposed')) {
         $identifier = $this->options['expose']['identifier'];
         $user_input = $form_state->getUserInput();
         if (!isset($user_input[$identifier])) {
             $user_input[$identifier] = $this->value;
             $form_state->setUserInput($user_input);
         }
     }
 }
 /**
  * {@inheritdoc}
  */
 public function view(OrderInterface $order, array $form, FormStateInterface $form_state)
 {
     $contents['#attached']['library'][] = 'uc_payment/uc_payment.styles';
     if ($this->configuration['show_preview']) {
         $contents['line_items'] = array('#theme' => 'uc_payment_totals', '#order' => $order, '#weight' => -20);
     }
     // Ensure that the form builder uses #default_value to determine which
     // button should be selected after an ajax submission. This is
     // necessary because the previously selected value may have become
     // unavailable, which would result in an invalid selection.
     $input = $form_state->getUserInput();
     unset($input['panes']['payment']['payment_method']);
     $form_state->setUserInput($input);
     $options = array();
     $methods = PaymentMethod::loadMultiple();
     uasort($methods, 'Drupal\\uc_payment\\Entity\\PaymentMethod::sort');
     foreach ($methods as $method) {
         // $set = rules_config_load('uc_payment_method_' . $method['id']);
         // if ($set && !$set->execute($order)) {
         //   continue;
         // }
         if ($method->status()) {
             $options[$method->id()] = $method->getDisplayLabel();
         }
     }
     \Drupal::moduleHandler()->alter('uc_payment_method_checkout', $options, $order);
     if (!$options) {
         $contents['#description'] = $this->t('Checkout cannot be completed without any payment methods enabled. Please contact an administrator to resolve the issue.');
         $options[''] = $this->t('No payment methods available');
     } elseif (count($options) > 1) {
         $contents['#description'] = $this->t('Select a payment method from the following options.');
     }
     if (!$order->getPaymentMethodId() || !isset($options[$order->getPaymentMethodId()])) {
         $order->setPaymentMethodId(key($options));
     }
     $contents['payment_method'] = array('#type' => 'radios', '#title' => $this->t('Payment method'), '#title_display' => 'invisible', '#options' => $options, '#default_value' => $order->getPaymentMethodId(), '#disabled' => count($options) == 1, '#required' => TRUE, '#ajax' => array('callback' => array($this, 'ajaxRender'), 'wrapper' => 'payment-details', 'progress' => array('type' => 'throbber')));
     // If there are no payment methods available, this will be ''.
     if ($order->getPaymentMethodId()) {
         $plugin = $this->paymentMethodManager->createFromOrder($order);
         $definition = $plugin->getPluginDefinition();
         $contents['details'] = array('#prefix' => '<div id="payment-details" class="clearfix ' . Html::cleanCssIdentifier('payment-details-' . $definition['id']) . '">', '#markup' => $this->t('Continue with checkout to complete payment.'), '#suffix' => '</div>');
         try {
             $details = $plugin->cartDetails($order, $form, $form_state);
             if ($details) {
                 unset($contents['details']['#markup']);
                 $contents['details'] += $details;
             }
         } catch (PluginException $e) {
         }
     }
     return $contents;
 }
Example #14
0
  /**
   * {@inheritdoc}
   *
   * @param \Drupal\filter\Entity\FilterFormat $filter_format
   *   The filter format for which this dialog corresponds.
   */
  public function buildForm(array $form, FormStateInterface $form_state, FilterFormat $filter_format = NULL) {
    // The default values are set directly from \Drupal::request()->request,
    // provided by the editor plugin opening the dialog.
    $user_input = $form_state->getUserInput();
    $input = isset($user_input['editor_object']) ? $user_input['editor_object'] : [];

    /** @var \Drupal\editor\EditorInterface $editor */
    $editor = $this->editorStorage->load($filter_format->id());
    $linkit_profile_id = $editor->getSettings()['plugins']['linkit']['linkit_profile'];
    $this->linkitProfile = $this->linkitProfileStorage->load($linkit_profile_id);

    $form['#tree'] = TRUE;
    $form['#attached']['library'][] = 'editor/drupal.editor.dialog';
    $form['#prefix'] = '<div id="linkit-editor-dialog-form">';
    $form['#suffix'] = '</div>';

    // Everything under the "attributes" key is merged directly into the
    // generated link tag's attributes.
    $form['attributes']['href'] = [
      '#title' => $this->t('Link'),
      '#type' => 'linkit',
      '#default_value' => isset($input['href']) ? $input['href'] : '',
      '#description' => $this->t('Start typing to find content or paste a URL.'),
      '#autocomplete_route_name' => 'linkit.autocomplete',
      '#autocomplete_route_parameters' => [
        'linkit_profile_id' => $linkit_profile_id
      ],
      '#weight' => 0,
    ];

    $this->addAttributes($form, $form_state, $this->linkitProfile->getAttributes());

    $form['actions'] = [
      '#type' => 'actions',
    ];

    $form['actions']['save_modal'] = [
      '#type' => 'submit',
      '#value' => $this->t('Save'),
      '#submit' => [],
      '#ajax' => [
        'callback' => '::submitForm',
        'event' => 'click',
      ],
    ];

    return $form;
  }
Example #15
0
 /**
  * {@inheritdoc}
  */
 public function buildForm(array $form, FormStateInterface $form_state)
 {
     $form['textfield'] = array('#title' => 'Textfield', '#type' => 'textfield');
     $form['checkboxes'] = array('#title' => t('Checkboxes'), '#type' => 'checkboxes', '#options' => array(1 => 'First checkbox', 2 => 'Second checkbox'), '#default_value' => array(1, 2));
     $form['field_to_validate'] = array('#type' => 'radios', '#title' => 'Field to validate (in the case of limited validation)', '#description' => 'If the form is submitted by clicking the "Submit with limited validation" button, then validation can be limited based on the value of this radio button.', '#options' => array('all' => 'Validate all fields', 'textfield' => 'Validate the "Textfield" field', 'field_to_validate' => 'Validate the "Field to validate" field'), '#default_value' => 'all');
     $form['field_restricted'] = array('#type' => 'textfield', '#title' => 'Textfield (no access)', '#access' => FALSE);
     // The main submit button for the form.
     $form['submit'] = array('#type' => 'submit', '#value' => 'Submit');
     // A secondary submit button that allows validation to be limited based on
     // the value of the above radio selector.
     $form['submit_limit_validation'] = array('#type' => 'submit', '#value' => 'Submit with limited validation', '#submit' => array('::submitForm'));
     $user_input = $form_state->getUserInput();
     if (!empty($user_input['field_to_validate']) && $user_input['field_to_validate'] != 'all') {
         $form['submit_limit_validation']['#limit_validation_errors'] = array(array($user_input['field_to_validate']));
     }
     return $form;
 }
Example #16
0
 /**
  * {@inheritdoc}
  */
 public function buildForm(array $form, FormStateInterface $form_state)
 {
     if ($form_state->hasValue('date')) {
         $userInput = $form_state->getUserInput();
         $userInput['result'] = 'Date Set';
         $form_state->setUserInput($userInput);
     } else {
         $form_state->setValue('date', date('Y-m-d', REQUEST_TIME));
         $form_state->setValue('result', 'date not set');
         $result = 'Date Not Set';
     }
     $form['ajax_wrapper'] = ['#type' => 'container', '#attributes' => ['id' => 'ajax_wrapper']];
     $form['ajax_wrapper']['date'] = ['#type' => 'date', '#title' => $this->t('Date')];
     $form['ajax_wrapper']['submit_button'] = ['#type' => 'submit', '#value' => 'Load', '#ajax' => ['callback' => [$this, 'ajaxFormCallback']]];
     $form['ajax_wrapper']['result'] = ['#type' => 'textfield', '#title' => $this->t('Result'), '#default_value' => $result];
     return $form;
 }
Example #17
0
 /**
  * {@inheritdoc}
  *
  * @param \Drupal\filter\Entity\FilterFormat $filter_format
  *   The filter format for which this dialog corresponds.
  */
 public function buildForm(array $form, FormStateInterface $form_state, FilterFormat $filter_format = NULL)
 {
     // The default values are set directly from \Drupal::request()->request,
     // provided by the editor plugin opening the dialog.
     $user_input = $form_state->getUserInput();
     $input = isset($user_input['editor_object']) ? $user_input['editor_object'] : array();
     $form['#tree'] = TRUE;
     $form['#attached']['library'][] = 'editor/drupal.editor.dialog';
     $form['#prefix'] = '<div id="editor-link-dialog-form">';
     $form['#suffix'] = '</div>';
     // Everything under the "attributes" key is merged directly into the
     // generated link tag's attributes.
     $form['attributes']['href'] = array('#title' => $this->t('URL'), '#type' => 'textfield', '#default_value' => isset($input['href']) ? $input['href'] : '', '#maxlength' => 2048);
     $form['actions'] = array('#type' => 'actions');
     $form['actions']['save_modal'] = array('#type' => 'submit', '#value' => $this->t('Save'), '#submit' => array(), '#ajax' => array('callback' => '::submitForm', 'event' => 'click'));
     return $form;
 }
Example #18
0
 /**
  * {@inheritdoc}
  */
 public function form(array $form, FormStateInterface $form_state)
 {
     $user_input = $form_state->getUserInput();
     $form['#title'] = $this->t('Edit style %name', array('%name' => $this->entity->label()));
     $form['#tree'] = TRUE;
     $form['#attached']['library'][] = 'image/admin';
     // Show the thumbnail preview.
     $preview_arguments = array('#theme' => 'image_style_preview', '#style' => $this->entity);
     $form['preview'] = array('#type' => 'item', '#title' => $this->t('Preview'), '#markup' => drupal_render($preview_arguments), '#weight' => -5);
     // Build the list of existing image effects for this image style.
     $form['effects'] = array('#type' => 'table', '#header' => array($this->t('Effect'), $this->t('Weight'), $this->t('Operations')), '#tabledrag' => array(array('action' => 'order', 'relationship' => 'sibling', 'group' => 'image-effect-order-weight')), '#attributes' => array('id' => 'image-style-effects'), '#empty' => t('There are currently no effects in this style. Add one by selecting an option below.'), '#weight' => 5);
     foreach ($this->entity->getEffects() as $effect) {
         $key = $effect->getUuid();
         $form['effects'][$key]['#attributes']['class'][] = 'draggable';
         $form['effects'][$key]['#weight'] = isset($user_input['effects']) ? $user_input['effects'][$key]['weight'] : NULL;
         $form['effects'][$key]['effect'] = array('#tree' => FALSE, 'data' => array('label' => array('#plain_text' => $effect->label())));
         $summary = $effect->getSummary();
         if (!empty($summary)) {
             $summary['#prefix'] = ' ';
             $form['effects'][$key]['effect']['data']['summary'] = $summary;
         }
         $form['effects'][$key]['weight'] = array('#type' => 'weight', '#title' => $this->t('Weight for @title', array('@title' => $effect->label())), '#title_display' => 'invisible', '#default_value' => $effect->getWeight(), '#attributes' => array('class' => array('image-effect-order-weight')));
         $links = array();
         $is_configurable = $effect instanceof ConfigurableImageEffectInterface;
         if ($is_configurable) {
             $links['edit'] = array('title' => $this->t('Edit'), 'url' => Url::fromRoute('image.effect_edit_form', ['image_style' => $this->entity->id(), 'image_effect' => $key]));
         }
         $links['delete'] = array('title' => $this->t('Delete'), 'url' => Url::fromRoute('image.effect_delete', ['image_style' => $this->entity->id(), 'image_effect' => $key]));
         $form['effects'][$key]['operations'] = array('#type' => 'operations', '#links' => $links);
     }
     // Build the new image effect addition form and add it to the effect list.
     $new_effect_options = array();
     $effects = $this->imageEffectManager->getDefinitions();
     uasort($effects, function ($a, $b) {
         return strcasecmp($a['id'], $b['id']);
     });
     foreach ($effects as $effect => $definition) {
         $new_effect_options[$effect] = $definition['label'];
     }
     $form['effects']['new'] = array('#tree' => FALSE, '#weight' => isset($user_input['weight']) ? $user_input['weight'] : NULL, '#attributes' => array('class' => array('draggable')));
     $form['effects']['new']['effect'] = array('data' => array('new' => array('#type' => 'select', '#title' => $this->t('Effect'), '#title_display' => 'invisible', '#options' => $new_effect_options, '#empty_option' => $this->t('Select a new effect')), array('add' => array('#type' => 'submit', '#value' => $this->t('Add'), '#validate' => array('::effectValidate'), '#submit' => array('::submitForm', '::effectSave')))), '#prefix' => '<div class="image-style-new">', '#suffix' => '</div>');
     $form['effects']['new']['weight'] = array('#type' => 'weight', '#title' => $this->t('Weight for new effect'), '#title_display' => 'invisible', '#default_value' => count($this->entity->getEffects()) + 1, '#attributes' => array('class' => array('image-effect-order-weight')));
     $form['effects']['new']['operations'] = array('data' => array());
     return parent::form($form, $form_state);
 }
 /**
  * Validates a password_confirm element.
  */
 public static function validatePasswordConfirm(&$element, FormStateInterface $form_state, &$complete_form)
 {
     $pass1 = trim($element['pass1']['#value']);
     $pass2 = trim($element['pass2']['#value']);
     if (strlen($pass1) > 0 || strlen($pass2) > 0) {
         if (strcmp($pass1, $pass2)) {
             $form_state->setError($element, t('The specified passwords do not match.'));
         }
     } elseif ($element['#required'] && $form_state->getUserInput()) {
         $form_state->setError($element, t('Password field is required.'));
     }
     // Password field must be converted from a two-element array into a single
     // string regardless of validation results.
     $form_state->setValueForElement($element['pass1'], NULL);
     $form_state->setValueForElement($element['pass2'], NULL);
     $form_state->setValueForElement($element, $pass1);
     return $element;
 }
 /**
  * {@inheritdoc}
  */
 public function buildForm(array $form, FormStateInterface $form_state)
 {
     // Get sensible default values for the form elements in this form.
     $default['states'] = isset($_GET['states']) ? $_GET['states'] : array('active' => 'active');
     $default['subscribed'] = isset($_GET['subscribed']) ? $_GET['subscribed'] : array('subscribed' => 'subscribed');
     $default['newsletters'] = isset($_GET['newsletters']) ? $_GET['newsletters'] : array();
     $form['states'] = array('#type' => 'checkboxes', '#title' => t('Status'), '#options' => array('active' => t('Active users'), 'inactive' => t('Inactive users')), '#default_value' => $default['states'], '#description' => t('Subscriptions matching the selected states will be exported.'), '#required' => TRUE);
     $form['subscribed'] = array('#type' => 'checkboxes', '#title' => t('Subscribed'), '#options' => array('subscribed' => t('Subscribed to the newsletter'), 'unconfirmed' => t('Unconfirmed to the newsletter'), 'unsubscribed' => t('Unsubscribed from the newsletter')), '#default_value' => $default['subscribed'], '#description' => t('Subscriptions matching the selected subscription states will be exported.'), '#required' => TRUE);
     $options = simplenews_newsletter_list();
     $form['newsletters'] = array('#type' => 'checkboxes', '#title' => t('Newsletter'), '#options' => $options, '#default_value' => $default['newsletters'], '#description' => t('Subscriptions matching the selected newsletters will be exported.'), '#required' => TRUE);
     // Get export results and display them in a text area. Only get the results
     // if the form is build after redirect, not after submit.
     $input = $form_state->getUserInput();
     if (isset($_GET['states']) && empty($input)) {
         $form['emails'] = array('#type' => 'textarea', '#title' => t('Export results'), '#cols' => 60, '#rows' => 5, '#value' => $this->getEmails($_GET['states'], $_GET['subscribed'], $_GET['newsletters']));
     }
     $form['submit'] = array('#type' => 'submit', '#value' => t('Export'));
     return $form;
 }
 /**
  * {@inheritdoc}
  */
 public function buildForm(array $form, FormStateInterface $form_state)
 {
     $edit = $form_state->getUserInput();
     $form['comments'] = array('#prefix' => '<ul>', '#suffix' => '</ul>', '#tree' => TRUE);
     // array_filter() returns only elements with actual values.
     $comment_counter = 0;
     $this->comments = $this->commentStorage->loadMultiple(array_keys(array_filter($edit['comments'])));
     foreach ($this->comments as $comment) {
         $cid = $comment->id();
         $form['comments'][$cid] = array('#type' => 'hidden', '#value' => $cid, '#prefix' => '<li>', '#suffix' => String::checkPlain($comment->label()) . '</li>');
         $comment_counter++;
     }
     $form['operation'] = array('#type' => 'hidden', '#value' => 'delete');
     if (!$comment_counter) {
         drupal_set_message($this->t('There do not appear to be any comments to delete, or your selected comment was deleted by another administrator.'));
         $form_state->setRedirect('comment.admin');
     }
     return parent::buildForm($form, $form_state);
 }
Example #22
0
 /**
  * {@inheritdoc}
  */
 public function view(OrderInterface $order, array $form, FormStateInterface $form_state)
 {
     $user = \Drupal::currentUser();
     $pane = $this->pluginDefinition['id'];
     $source = $this->sourcePaneId();
     $contents['#description'] = $this->getDescription();
     if ($source != $pane) {
         $contents['copy_address'] = array('#type' => 'checkbox', '#title' => $this->getCopyAddressText(), '#default_value' => $this->configuration['default_same_address'], '#ajax' => array('callback' => array($this, 'ajaxRender'), 'wrapper' => $pane . '-address-pane', 'progress' => array('type' => 'throbber')));
     }
     if ($user->isAuthenticated() && ($addresses = uc_select_addresses($user->id(), $pane))) {
         $contents['select_address'] = array('#type' => 'select', '#title' => t('Saved addresses'), '#options' => $addresses['#options'], '#ajax' => array('callback' => array($this, 'ajaxRender'), 'wrapper' => $pane . '-address-pane', 'progress' => array('type' => 'throbber')), '#states' => array('invisible' => array('input[name="panes[' . $pane . '][copy_address]"]' => array('checked' => TRUE))));
     }
     $contents['address'] = array('#type' => 'uc_address', '#default_value' => $order->getAddress($pane), '#prefix' => '<div id="' . $pane . '-address-pane">', '#suffix' => '</div>');
     if ($form_state->hasValue(['panes', $pane, 'copy_address'])) {
         $contents['address']['#hidden'] = !$form_state->isValueEmpty(['panes', $pane, 'copy_address']);
     } elseif (isset($contents['copy_address'])) {
         $contents['address']['#hidden'] = $this->configuration['default_same_address'];
     }
     if ($element = $form_state->getTriggeringElement()) {
         $input = $form_state->getUserInput();
         if ($element['#name'] == "panes[{$pane}][copy_address]") {
             $address =& $form_state->getValue(['panes', $source]);
             foreach ($address as $field => $value) {
                 if (substr($field, 0, strlen($source)) == $source) {
                     $field = str_replace($source, $pane, $field);
                     $input['panes'][$pane][$field] = $value;
                     $order->{$field} = $value;
                 }
             }
         }
         if ($element['#name'] == "panes[{$pane}][select_address]") {
             $address = $addresses[$element['#value']];
             foreach ($address as $field => $value) {
                 $input['panes'][$pane][$pane . '_' . $field] = $value;
                 $order->{$pane . '_' . $field} = $value;
             }
         }
         $form_state->setUserInput($input);
         // Forget any previous Ajax submissions, as we send new default values.
         $form_state->unsetValue('uc_address');
     }
     return $contents;
 }
Example #23
0
 /**
  * {@inheritdoc}
  */
 public function submitForm(array &$form, FormStateInterface $form_state)
 {
     /** @var $view \Drupal\views_ui\ViewUI */
     $view = $form_state->get('view');
     $order = array();
     $user_input = $form_state->getUserInput();
     foreach ($user_input['displays'] as $display => $info) {
         // Add each value that is a field with a weight to our list, but only if
         // it has had its 'removed' checkbox checked.
         if (is_array($info) && isset($info['weight']) && empty($info['removed']['checkbox'])) {
             $order[$display] = $info['weight'];
         }
     }
     // Sort the order array.
     asort($order);
     // Remove the default display from ordering.
     unset($order['default']);
     // Increment up positions.
     $position = 1;
     foreach (array_keys($order) as $display) {
         $order[$display] = $position++;
     }
     // Setting up position and removing deleted displays.
     $displays = $view->get('display');
     foreach ($displays as $display_id => &$display) {
         // Don't touch the default.
         if ($display_id === 'default') {
             $display['position'] = 0;
             continue;
         }
         if (isset($order[$display_id])) {
             $display['position'] = $order[$display_id];
         } else {
             $display['deleted'] = TRUE;
         }
     }
     $view->set('display', $displays);
     // Store in cache.
     $view->cacheSet();
     $url = $view->urlInfo('edit-form')->setOption('fragment', 'views-tab-default');
     $form_state->setRedirectUrl($url);
 }
 /**
  * Form element submit handler for mollom_test_form().
  */
 function fieldSubmitForm(array &$form, FormStateInterface $form_state)
 {
     // Remove all empty values of the multiple value field.
     $form_state->setValue('field', array_filter($form_state->getValue('field')));
     // Update the storage with submitted values.
     $storage_record = $form_state->getValues();
     // Store the new value and clear out the 'new' field.
     $new_field = $form_state->getValue(array('field', 'new'), '');
     if (!empty($new_field)) {
         $storage_record['field'][] = $form_state->getValue(array('field', 'new'));
         $form_state->setValue(array('field', 'new'), '');
         $storage_record['field']['new'] = '';
         unset($storage_record['field']['add']);
         $input = $form_state->getUserInput();
         $input['field']['new'] = '';
         $form_state->setUserInput($input);
     }
     $form_state->set('mollom_test', $storage_record);
     $form_state->setRebuild(TRUE);
 }
Example #25
0
 /**
  * {@inheritdoc}
  */
 public function buildForm(array $form, FormStateInterface $form_state)
 {
     if ($form_state->isRebuilding()) {
         $form_state->setUserInput(array());
     }
     // Initialize
     $storage = $form_state->getStorage();
     if (empty($storage)) {
         $user_input = $form_state->getUserInput();
         if (empty($user_input)) {
             $_SESSION['constructions'] = 0;
         }
         // Put the initial thing into the storage
         $storage = ['thing' => ['title' => 'none', 'value' => '']];
         $form_state->setStorage($storage);
     }
     // Count how often the form is constructed.
     $_SESSION['constructions']++;
     drupal_set_message("Form constructions: " . $_SESSION['constructions']);
     $form['title'] = array('#type' => 'textfield', '#title' => 'Title', '#default_value' => $storage['thing']['title'], '#required' => TRUE);
     $form['value'] = array('#type' => 'textfield', '#title' => 'Value', '#default_value' => $storage['thing']['value'], '#element_validate' => array('::elementValidateValueCached'));
     $form['continue_button'] = array('#type' => 'button', '#value' => 'Reset');
     $form['continue_submit'] = array('#type' => 'submit', '#value' => 'Continue submit', '#submit' => array('::continueSubmitForm'));
     $form['submit'] = array('#type' => 'submit', '#value' => 'Save');
     // @todo Remove this in https://www.drupal.org/node/2524408, because form
     //   cache immutability is no longer necessary, because we no longer cache
     //   forms during safe HTTP methods. In the meantime, because
     //   Drupal\system\Tests\Form still has test coverage for a poisoned form
     //   cache following a GET request, trick $form_state into caching the form
     //   to keep that test working until we either remove it or change it in
     //   that issue.
     if ($this->getRequest()->get('immutable')) {
         $form_state->addBuildInfo('immutable', TRUE);
         if ($this->getRequest()->get('cache') && $this->getRequest()->isMethodSafe()) {
             $form_state->setRequestMethod('FAKE');
             $form_state->setCached();
         }
     }
     return $form;
 }
Example #26
0
 /**
  * {@inheritdoc}
  */
 public function prepare(OrderInterface $order, array $form, FormStateInterface $form_state)
 {
     // If a quote was explicitly selected, add it to the order.
     if (isset($form['panes']['quotes']['quotes']['quote_option']['#value']) && isset($form['panes']['quotes']['quotes']['quote_option']['#default_value']) && $form['panes']['quotes']['quotes']['quote_option']['#value'] !== $form['panes']['quotes']['quotes']['quote_option']['#default_value']) {
         $quote_option = explode('---', $form_state->getValue(['panes', 'quotes', 'quotes', 'quote_option']));
         $order->quote['method'] = $quote_option[0];
         $order->quote['accessorials'] = $quote_option[1];
         $order->data->uc_quote_selected = TRUE;
     }
     // If the current quote was never explicitly selected, discard it and
     // use the default.
     if (empty($order->data->uc_quote_selected)) {
         unset($order->quote);
     }
     // Ensure that the form builder uses the default value to decide which
     // radio button should be selected.
     $input = $form_state->getUserInput();
     unset($input['panes']['quotes']['quotes']['quote_option']);
     $form_state->setUserInput($input);
     $order->quote_form = uc_quote_build_quote_form($order, !$form_state->get('quote_requested'));
     $default_option = _uc_quote_extract_default_option($order->quote_form);
     if ($default_option) {
         $order->quote['rate'] = $order->quote_form[$default_option]['rate']['#value'];
         $quote_option = explode('---', $default_option);
         $order->quote['method'] = $quote_option[0];
         $order->quote['accessorials'] = $quote_option[1];
         $methods = uc_quote_methods();
         $method = $methods[$quote_option[0]];
         $label = $method['quote']['accessorials'][$quote_option[1]];
         $result = db_query("SELECT line_item_id FROM {uc_order_line_items} WHERE order_id = :id AND type = :type", [':id' => $order->id(), ':type' => 'shipping']);
         if ($lid = $result->fetchField()) {
             uc_order_update_line_item($lid, $label, $order->quote['rate']);
         } else {
             uc_order_line_item_add($order->id(), 'shipping', $label, $order->quote['rate']);
         }
     } else {
         unset($order->quote);
     }
 }
Example #27
0
 protected function valueForm(&$form, FormStateInterface $form_state)
 {
     $values = array();
     if ($this->value) {
         $result = entity_load_multiple_by_properties('user', array('uid' => $this->value));
         foreach ($result as $account) {
             if ($account->id()) {
                 $values[] = $account->getUsername();
             } else {
                 $values[] = 'Anonymous';
                 // Intentionally NOT translated.
             }
         }
     }
     sort($values);
     $default_value = implode(', ', $values);
     $form['value'] = array('#type' => 'textfield', '#title' => $this->t('Usernames'), '#description' => $this->t('Enter a comma separated list of user names.'), '#default_value' => $default_value, '#autocomplete_route_name' => 'user.autocomplete_anonymous');
     $user_input = $form_state->getUserInput();
     if ($form_state->get('exposed') && !isset($user_input[$this->options['expose']['identifier']])) {
         $user_input[$this->options['expose']['identifier']] = $default_value;
         $form_state->setUserInput($user_input);
     }
 }
Example #28
0
 /**
  * Render API callback: builds the formatter settings elements.
  */
 public function formatterSettingsProcessCallback(array &$element, FormStateInterface $form_state, array &$complete_form)
 {
     $config = $this->getConfiguration();
     $parents_base = $element['#parents'];
     $formatter_parent = array_merge($parents_base, ['formatter_type']);
     $formatter_settings_parent = array_merge($parents_base, ['formatter_settings']);
     $settings_element =& $element['formatter_settings_wrapper']['formatter_settings'];
     // Set the #parents on the formatter_settings so they end up as a peer to
     // formatter_type.
     $settings_element['#parents'] = $formatter_settings_parent;
     // Get the formatter name in a way that works regardless of whether we're
     // getting the value via AJAX or not.
     $formatter_name = NestedArray::getValue($form_state->getUserInput(), $formatter_parent) ?: $element['formatter_type']['#default_value'];
     // Place the formatter settings on the form if a formatter is selected.
     $formatter = $this->getFormatter($formatter_name, $form_state->getValue('formatter_label'), $form_state->getValue($formatter_settings_parent, $config['formatter']['settings']), $config['formatter']['third_party_settings']);
     $settings_element = array_merge($formatter->settingsForm($settings_element, $form_state), $settings_element);
     // Store the array parents for our element so that we can use it to pull out
     // the formatter settings in our AJAX callback.
     $complete_form['#formatter_array_parents'] = $element['#array_parents'];
     return $element;
 }
Example #29
0
 /**
  * AJAX handler for by_user_state.
  *
  * @param array $form
  *   An associative array containing the structure of the form.
  * @param \Drupal\Core\Form\FormStateInterface $form_state
  *   The current state of the form.
  *
  * @return array
  */
 public function toggleByUserMode($form, FormStateInterface $form_state)
 {
     $by_user_mode = $form_state->getUserInput();
     $by_user_mode = !empty($by_user_mode['by_user_mode']);
     \Drupal::configFactory()->getEditable('devel_node_access.settings')->set('by_user_mode', $by_user_mode)->save(TRUE);
     $form['user_content'][0] = $by_user_mode ? DnaBlock::buildByUserInfo() : [];
     return $form['user_content'];
 }
Example #30
0
 protected function valueForm(&$form, FormStateInterface $form_state)
 {
     $vocabulary = $this->vocabularyStorage->load($this->options['vid']);
     if (empty($vocabulary) && $this->options['limit']) {
         $form['markup'] = array('#markup' => '<div class="form-item">' . $this->t('An invalid vocabulary is selected. Please change it in the options.') . '</div>');
         return;
     }
     if ($this->options['type'] == 'textfield') {
         $terms = $this->value ? Term::loadMultiple($this->value) : array();
         $form['value'] = array('#title' => $this->options['limit'] ? $this->t('Select terms from vocabulary @voc', array('@voc' => $vocabulary->label())) : $this->t('Select terms'), '#type' => 'textfield', '#default_value' => EntityAutocomplete::getEntityLabels($terms));
         if ($this->options['limit']) {
             $form['value']['#type'] = 'entity_autocomplete';
             $form['value']['#target_type'] = 'taxonomy_term';
             $form['value']['#selection_settings']['target_bundles'] = array($vocabulary->id());
             $form['value']['#tags'] = TRUE;
             $form['value']['#process_default_value'] = FALSE;
         }
     } else {
         if (!empty($this->options['hierarchy']) && $this->options['limit']) {
             $tree = $this->termStorage->loadTree($vocabulary->id(), 0, NULL, TRUE);
             $options = array();
             if ($tree) {
                 foreach ($tree as $term) {
                     $choice = new \stdClass();
                     $choice->option = array($term->id() => str_repeat('-', $term->depth) . SafeMarkup::checkPlain(\Drupal::entityManager()->getTranslationFromContext($term)->label()));
                     $options[] = $choice;
                 }
             }
         } else {
             $options = array();
             $query = \Drupal::entityQuery('taxonomy_term')->sort('weight')->sort('name')->addTag('term_access');
             if ($this->options['limit']) {
                 $query->condition('vid', $vocabulary->id());
             }
             $terms = Term::loadMultiple($query->execute());
             foreach ($terms as $term) {
                 $options[$term->id()] = SafeMarkup::checkPlain(\Drupal::entityManager()->getTranslationFromContext($term)->label());
             }
         }
         $default_value = (array) $this->value;
         if ($exposed = $form_state->get('exposed')) {
             $identifier = $this->options['expose']['identifier'];
             if (!empty($this->options['expose']['reduce'])) {
                 $options = $this->reduceValueOptions($options);
                 if (!empty($this->options['expose']['multiple']) && empty($this->options['expose']['required'])) {
                     $default_value = array();
                 }
             }
             if (empty($this->options['expose']['multiple'])) {
                 if (empty($this->options['expose']['required']) && (empty($default_value) || !empty($this->options['expose']['reduce']))) {
                     $default_value = 'All';
                 } elseif (empty($default_value)) {
                     $keys = array_keys($options);
                     $default_value = array_shift($keys);
                 } elseif ($default_value == array('')) {
                     $default_value = 'All';
                 } else {
                     $copy = $default_value;
                     $default_value = array_shift($copy);
                 }
             }
         }
         $form['value'] = array('#type' => 'select', '#title' => $this->options['limit'] ? $this->t('Select terms from vocabulary @voc', array('@voc' => $vocabulary->label())) : $this->t('Select terms'), '#multiple' => TRUE, '#options' => $options, '#size' => min(9, count($options)), '#default_value' => $default_value);
         $user_input = $form_state->getUserInput();
         if ($exposed && isset($identifier) && !isset($user_input[$identifier])) {
             $user_input[$identifier] = $default_value;
             $form_state->setUserInput($user_input);
         }
     }
     if (!$form_state->get('exposed')) {
         // Retain the helper option
         $this->helper->buildOptionsForm($form, $form_state);
     }
 }