/** * {@inheritdoc} */ public function submitForm(array &$form, FormStateInterface $form_state) { /** @var \Drupal\search_api\ServerInterface $server */ $server = $this->getEntity(); try { $server->deleteAllItems(); drupal_set_message($this->t('All indexed data was successfully deleted from the server.')); } catch (SearchApiException $e) { drupal_set_message($this->t('Indexed data could not be cleared for some indexes. Check the logs for details.'), 'error'); } $failed_reindexing = array(); $properties = array('status' => TRUE, 'read_only' => FALSE); foreach ($server->getIndexes($properties) as $index) { try { $index->reindex(); } catch (SearchApiException $e) { $args = array('%index' => $index->label()); watchdog_exception('search_api', $e, '%type while clearing index %index: @message in %function (line %line of %file).', $args); $failed_reindexing[] = $index->label(); } } if ($failed_reindexing) { $args = array('@indexes' => implode(', ', $failed_reindexing)); drupal_set_message($this->t('Failed to mark the following indexes for reindexing: @indexes. Check the logs for details.', $args), 'warning'); } $form_state->setRedirect('entity.search_api_server.canonical', array('search_api_server' => $server->id())); }
/** * {@inheritdoc} */ public function submit(array $form, FormStateInterface $form_state) { $this->entity->delete(); drupal_set_message($this->t('Responsive image mapping %label has been deleted.', array('%label' => $this->entity->label()))); $this->logger('responsive_image')->notice('Responsive image mapping %label has been deleted.', array('%label' => $this->entity->label())); $form_state->setRedirectUrl($this->getCancelUrl()); }
/** * {@inheritdoc} */ public function submitForm(array &$form, FormStateInterface $form_state) { $settings = array('types' => $form_state->getValue('types')); $this->currentBundle->setAssignmentSettings(self::METHOD_ID, $settings)->save(); $this->setRedirect($form_state); drupal_set_message($this->t('Package assignment configuration saved.')); }
/** * {@inheritdoc} */ public function submitForm(array &$form, FormStateInterface $form_state) { $this->taxonomyTerm->delete(); drupal_set_message($this->t('The forum %label and all sub-forums have been deleted.', array('%label' => $this->taxonomyTerm->label()))); $this->logger('forum')->notice('forum: deleted %label and all its sub-forums.', array('%label' => $this->taxonomyTerm->label())); $form_state->setRedirectUrl($this->getCancelUrl()); }
public function validateExposed(&$form, FormStateInterface $form_state) { if (empty($this->options['exposed'])) { return; } if (empty($this->options['expose']['identifier'])) { return; } $identifier = $this->options['expose']['identifier']; $input = $form_state->getValue($identifier); if ($this->options['is_grouped'] && isset($this->options['group_info']['group_items'][$input])) { $this->operator = $this->options['group_info']['group_items'][$input]['operator']; $input = $this->options['group_info']['group_items'][$input]['value']; } $uids = []; $values = $form_state->getValue($identifier); if ($values && (!$this->options['is_grouped'] || $this->options['is_grouped'] && $input != 'All')) { foreach ($values as $value) { $uids[] = $value['target_id']; } } if ($uids) { $this->validated_exposed_input = $uids; } }
/** * Form validation handler for widget elements. * * @param array $element * The form element. * @param \Drupal\Core\Form\FormStateInterface $form_state * The form state. */ public static function validateElement(array $element, FormStateInterface $form_state) { if ($element['#required'] && $element['#value'] == '_none') { $form_state->setError($element, t('@name field is required.', array('@name' => $element['#title']))); } // Massage submitted form values. // Drupal\Core\Field\WidgetBase::submit() expects values as // an array of values keyed by delta first, then by column, while our // widgets return the opposite. if (is_array($element['#value'])) { $values = array_values($element['#value']); } else { $values = array($element['#value']); } // Filter out the 'none' option. Use a strict comparison, because // 0 == 'any string'. $index = array_search('_none', $values, TRUE); if ($index !== FALSE) { unset($values[$index]); } // Transpose selections from field => delta to delta => field. $items = array(); foreach ($values as $value) { $items[] = array($element['#key_column'] => $value); } $form_state->setValueForElement($element, $items); }
/** * {@inheritdoc} */ public function submit(array &$element, array &$form, FormStateInterface $form_state) { $media_entities = []; $upload = $form_state->getValue('upload'); if (isset($upload['uploaded_files']) && is_array($upload['uploaded_files'])) { $config = $this->getConfiguration(); $user = $this->currentUser; /** @var \Drupal\media_entity\MediaBundleInterface $bundle */ $bundle = $this->entityManager->getStorage('media_bundle')->load($this->configuration['media_entity_bundle']); // First save the file. foreach ($upload['uploaded_files'] as $uploaded_file) { $file = $this->dropzoneJsUploadSave->saveFile($uploaded_file['path'], $config['settings']['upload_location'], $config['settings']['extensions'], $user); if ($file) { $file->setPermanent(); $file->save(); // Now save the media entity. if ($this->moduleHandler->moduleExists('media_entity')) { /** @var \Drupal\media_entity\MediaInterface $media_entity */ $media_entity = $this->entityManager->getStorage('media')->create(['bundle' => $bundle->id(), $bundle->getTypeConfiguration()['source_field'] => $file, 'uid' => $user->id(), 'status' => TRUE, 'type' => $bundle->getType()->getPluginId()]); $event = $this->eventDispatcher->dispatch(Events::MEDIA_ENTITY_CREATE, new DropzoneMediaEntityCreateEvent($media_entity, $file, $form, $form_state, $element)); $media_entity = $event->getMediaEntity(); $media_entity->save(); $media_entities[] = $media_entity; } else { drupal_set_message(t('The media entity was not saved, because the media_entity module is not enabled.')); } } } } if (!empty(array_filter($media_entities))) { $this->selectEntities($media_entities, $form_state); $this->clearFormValues($element, $form_state); } }
/** * {@inheritdoc} */ public function submitForm(array &$form, FormStateInterface $form_state) { /** @var \Drupal\payment\Plugin\Payment\LineItem\PaymentLineItemInterface $line_item */ $line_item = $form_state->get('payment_line_item'); $line_item->submitConfigurationForm($form['line_item'], $form_state); $form_state->setRedirect('user.login'); }
public function submitOptionsForm(&$form, FormStateInterface $form_state) { $exposed_form_options = $form_state->getValue('exposed_form_options'); $form_state->setValue(array('exposed_form_options', 'text_input_required_format'), $exposed_form_options['text_input_required']['format']); $form_state->setValue(array('exposed_form_options', 'text_input_required'), $exposed_form_options['text_input_required']['value']); parent::submitOptionsForm($form, $form_state); }
/** * {@inheritdoc} */ public function buildForm(array $form, FormStateInterface $form_state, LanguageInterface $language = NULL) { if ($language) { $form_state->set('langcode', $language->getId()); } return parent::buildForm($form, $form_state); }
/** * {@inheritdoc} */ public function submitForm(array &$form, FormStateInterface $form_state) { drupal_set_message($this->t('The static context %label has been removed.', ['%label' => $this->page->getStaticContext($this->staticContext)['label']])); $this->page->removeStaticContext($this->staticContext); $this->page->save(); $form_state->setRedirectUrl($this->getCancelUrl()); }
/** * {@inheritdoc} */ public function submit(array $form, FormStateInterface $form_state) { $this->entity->delete(); drupal_set_message($this->t('Custom block %label has been deleted.', array('%label' => $this->entity->label()))); $this->logger('block_content')->notice('Custom block %label has been deleted.', array('%label' => $this->entity->label())); $form_state->setRedirect('block_content.list'); }
/** * {@inheritdoc} */ public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) { /* @var $instance \Drupal\mailchimp_lists\Plugin\Field\FieldType\MailchimpListsSubscription */ $instance = $items[0]; $subscribe_default = $instance->getSubscribe(); $email = NULL; if (!empty($instance->getEntity())) { $email = mailchimp_lists_load_email($instance, $instance->getEntity(), FALSE); if ($email) { $subscribe_default = mailchimp_is_subscribed($instance->getFieldDefinition()->getSetting('mc_list_id'), $email); } } $element += array('#title' => SafeMarkup::checkPlain($element['#title']), '#type' => 'fieldset'); $element['subscribe'] = array('#title' => t('Subscribe'), '#type' => 'checkbox', '#default_value' => $subscribe_default ? TRUE : $this->fieldDefinition->isRequired(), '#required' => $this->fieldDefinition->isRequired(), '#disabled' => $this->fieldDefinition->isRequired()); $form_id = $form_state->getFormObject()->getFormId(); if ($this->fieldDefinition->getSetting('show_interest_groups') || $form_id == 'field_ui_field_edit_form') { $mc_list = mailchimp_get_list($instance->getFieldDefinition()->getSetting('mc_list_id')); $element['interest_groups'] = array('#type' => 'fieldset', '#title' => SafeMarkup::checkPlain($instance->getFieldDefinition()->getSetting('interest_groups_title')), '#weight' => 100, '#states' => array('invisible' => array(':input[name="' . $instance->getFieldDefinition()->getName() . '[0][value][subscribe]"]' => array('checked' => FALSE)))); if ($form_id == 'field_ui_field_edit_form') { $element['interest_groups']['#states']['invisible'] = array(':input[name="field[settings][show_interest_groups]"]' => array('checked' => FALSE)); } $groups_default = $instance->getInterestGroups(); if ($groups_default == NULL) { $groups_default = array(); } if ($mc_list['stats']['group_count']) { $element['interest_groups'] += mailchimp_interest_groups_form_elements($mc_list, $groups_default, $email); } } return array('value' => $element); }
/** * {@inheritdoc} */ public function finish(array &$form, FormStateInterface $form_state) { $cached_values = $form_state->getTemporaryValue('wizard'); drupal_set_message($this->t('Value One: @one', ['@one' => $cached_values['one']])); drupal_set_message($this->t('Value Two: @two', ['@two' => $cached_values['two']])); parent::finish($form, $form_state); }
/** * Form element validation handler for matched_path elements. * * Note that #maxlength is validated by _form_validate() already. * * This checks that the submitted value matches an active route. */ public static function validateMatchedPath(&$element, FormStateInterface $form_state, &$complete_form) { if (!empty($element['#value']) && ($element['#validate_path'] || $element['#convert_path'] != self::CONVERT_NONE)) { /** @var \Drupal\Core\Url $url */ if ($url = \Drupal::service('path.validator')->getUrlIfValid($element['#value'])) { if ($url->isExternal()) { $form_state->setError($element, t('You cannot use an external URL, please enter a relative path.')); return; } if ($element['#convert_path'] == self::CONVERT_NONE) { // Url is valid, no conversion required. return; } // We do the value conversion here whilst the Url object is in scope // after validation has occurred. if ($element['#convert_path'] == self::CONVERT_ROUTE) { $form_state->setValueForElement($element, array('route_name' => $url->getRouteName(), 'route_parameters' => $url->getRouteParameters())); return; } elseif ($element['#convert_path'] == self::CONVERT_URL) { $form_state->setValueForElement($element, $url); return; } } $form_state->setError($element, t('This path does not exist or you do not have permission to link to %path.', array('%path' => $element['#value']))); } }
/** * Form submission handler. * * @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. */ public function submitForm(array &$form, FormStateInterface $form_state) { $author = $form_state->getValue('author'); $body = $form_state->getValue('body'); $title = $form_state->getValue('title'); drupal_set_message('Thanks for submitting the form! you typed in the following as author:' . $author . ' . body:' . $body . '. title:' . $title); }
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'); } }
/** * {@inheritdoc} */ public function submitForm(array &$form, FormStateInterface $form_state) { $values = $form_state->getValues(); $file = File::load($values['file'][0]); // Load File entity. $read_file = new \SplFileObject($file->url()); // Create file handler. $lines = 1; $in_queue = 0; $queue = \Drupal::queue('eventninja'); // Load queue while (!$read_file->eof()) { $data = $read_file->fgetcsv(';'); if ($lines > 1) { // skip headers $user = user_load_by_mail($data[1]); if ($user === false) { // Verify if user with specified email does not exist. $queue->createItem($data); $in_queue++; } else { $this->logger('eventninja')->log(RfcLogLevel::NOTICE, 'User {mail} hasn\'t been created.', ['mail' => $data[1]]); } } $lines++; } if ($lines > 1) { drupal_set_message($this->t('@num records was scheduled for import', array('@num' => $in_queue)), 'success'); } else { drupal_set_message($this->t('File contains only headers'), 'error'); } }
/** * {@inheritdoc} */ public static function value(array &$element, &$input, FormStateInterface $form_state) { if (isset($input['filefield_reference']['autocomplete']) && strlen($input['filefield_reference']['autocomplete']) > 0 && $input['filefield_reference']['autocomplete'] != FILEFIELD_SOURCE_REFERENCE_HINT_TEXT) { $matches = array(); if (preg_match('/\\[fid:(\\d+)\\]/', $input['filefield_reference']['autocomplete'], $matches)) { $fid = $matches[1]; if ($file = file_load($fid)) { // Remove file size restrictions, since the file already exists on // disk. if (isset($element['#upload_validators']['file_validate_size'])) { unset($element['#upload_validators']['file_validate_size']); } // Check that the user has access to this file through // hook_download(). if (!$file->access('download')) { $form_state->setError($element, t('You do not have permission to use the selected file.')); } elseif (filefield_sources_element_validate($element, (object) $file, $form_state)) { if (!in_array($file->id(), $input['fids'])) { $input['fids'][] = $file->id(); } } } else { $form_state->setError($element, t('The referenced file could not be used because the file does not exist in the database.')); } } // No matter what happens, clear the value from the autocomplete. $input['filefield_reference']['autocomplete'] = ''; } }
/** * {@inheritdoc} */ public function save(array $form, FormStateInterface $form_state) { try { $entity = $this->entity; // Save as a new revision if requested to do so. if (!$form_state->isValueEmpty('revision')) { $entity->setNewRevision(); } $is_new = $entity->isNew(); $entity->save(); if ($is_new) { $message = t('%entity_type @id has been created.', array('@id' => $entity->id(), '%entity_type' => $entity->getEntityTypeId())); } else { $message = t('%entity_type @id has been updated.', array('@id' => $entity->id(), '%entity_type' => $entity->getEntityTypeId())); } drupal_set_message($message); if ($entity->id()) { $entity_type = $entity->getEntityTypeId(); $form_state->setRedirect("entity.{$entity_type}.edit_form", array($entity_type => $entity->id())); } else { // Error on save. drupal_set_message(t('The entity could not be saved.'), 'error'); $form_state->setRebuild(); } } catch (\Exception $e) { \Drupal::state()->set('entity_test.form.save.exception', get_class($e) . ': ' . $e->getMessage()); } }
/** * {@inheritdoc} */ public function submit(array $form, FormStateInterface $form_state) { $this->entity->delete(); $this->logger('user')->notice('Role %name has been deleted.', array('%name' => $this->entity->label())); drupal_set_message($this->t('Role %name has been deleted.', array('%name' => $this->entity->label()))); $form_state->setRedirectUrl($this->getCancelUrl()); }
/** * Form element validation handler for #type 'number'. * * Note that #required is validated by _form_validate() already. */ public static function validateNumber(&$element, FormStateInterface $form_state, &$complete_form) { $value = $element['#value']; if ($value === '') { return; } $name = empty($element['#title']) ? $element['#parents'][0] : $element['#title']; // Ensure the input is numeric. if (!is_numeric($value)) { $form_state->setError($element, t('%name must be a number.', array('%name' => $name))); return; } // Ensure that the input is greater than the #min property, if set. if (isset($element['#min']) && $value < $element['#min']) { $form_state->setError($element, t('%name must be higher than or equal to %min.', array('%name' => $name, '%min' => $element['#min']))); } // Ensure that the input is less than the #max property, if set. if (isset($element['#max']) && $value > $element['#max']) { $form_state->setError($element, t('%name must be lower than or equal to %max.', array('%name' => $name, '%max' => $element['#max']))); } if (isset($element['#step']) && strtolower($element['#step']) != 'any') { // Check that the input is an allowed multiple of #step (offset by #min if // #min is set). $offset = isset($element['#min']) ? $element['#min'] : 0.0; if (!NumberUtility::validStep($value, $element['#step'], $offset)) { $form_state->setError($element, t('%name is not a valid number.', array('%name' => $name))); } } }
/** * Submit callback. * * Implements the form logic. */ public function submitForm(array &$form, FormStateInterface $form_state) { $this->config('happy_alexandrie.library_config')->set('opening_hours', $form_state->getValue('opening_hours'))->save(); // Call the parent implementation to inherit from what has been done in it. // In our case, display the confirmation message. parent::submitForm($form, $form_state); }
/** * {@inheritdoc} */ public function submitForm(array &$form, FormStateInterface $form_state) { $this->page->removeVariant($this->displayVariant->id()); $this->page->save(); drupal_set_message($this->t('The display variant %name has been removed.', ['%name' => $this->displayVariant->label()])); $form_state->setRedirectUrl($this->getCancelUrl()); }
/** * {@inheritdoc} */ public function submitForm(array &$form, FormStateInterface $form_state) { $this->page->removeAccessCondition($this->accessCondition->getConfiguration()['uuid']); $this->page->save(); drupal_set_message($this->t('The access condition %name has been removed.', ['%name' => $this->accessCondition->getPluginDefinition()['label']])); $form_state->setRedirectUrl($this->getCancelUrl()); }
/** * {@inheritdoc} */ public function submitForm(array &$form, FormStateInterface $form_state) { //debug($form_state); $zip = $form_state->getValue('zip'); $creditCardNumber = $form_state->getValue('creditCardNumber'); $expDateMonth = $form_state->getValue('expDateMonth'); $expDateYear = $form_state->getValue('expDateYear'); $padDateMonth = str_pad($expDateMonth, 2, '0', STR_PAD_LEFT); $cvv2Number = $form_state->getValue('cvv2Number'); $creditCardType = $form_state->getValue('creditCardType'); $amount = $form_state->getValue('amount'); $currencyCode = "USD"; $paymentAction = "Sale"; $nvpRecurring = ''; $methodToCall = 'doDirectPayment'; $address1 = 'Test'; $firstName = $form_state->getValue('fname'); $lastName = $form_state->getValue('lname'); $city = ''; $state = ''; $nvpstr = '&PAYMENTACTION=' . $paymentAction . '&AMT=' . $amount . '&CREDITCARDTYPE=' . $creditCardType . '&ACCT=' . $creditCardNumber . '&EXPDATE=' . $padDateMonth . $expDateYear . '&CVV2=' . $cvv2Number . '&FIRSTNAME=' . $firstName . '&LASTNAME=' . $lastName . '&STREET=' . $address1 . '&CITY=' . $city . '&STATE=' . $state . '&ZIP=' . $zip . '&COUNTRYCODE=US&CURRENCYCODE=' . $currencyCode . $nvpRecurring; $paypalPro = new PAYPAL_PRO('dcube102_api1.gmail.com', 'A2Z27W9TT38YF99A', 'AhASSJKy6.CmpxA-YrdIVjL0aAmMAsDBSX7w3genQDH3xdQ-ubK-9T5k', '', '', FALSE, FALSE); $resArray = $paypalPro->hash_call($methodToCall, $nvpstr); $ack = strtoupper($resArray["ACK"]); print_r($resArray); if ($resArray["ACK"] == 'Success') { drupal_set_message($this->t('Your Payment is @ack and your Transaction ID is @trans', array('@ack' => $resArray["ACK"], '@trans' => $resArray["TRANSACTIONID"]))); } else { drupal_set_message('Payment Failure:' . $resArray["L_LONGMESSAGE0"], 'error'); } }
/** * {@inheritdoc} */ public function submitForm(array &$form, FormStateInterface $form_state) { batch_test_stack(NULL, TRUE); $function = '_batch_test_' . $form_state->getValue('batch'); batch_set($function()); $form_state->setRedirect('batch_test.redirect'); }
/** * {@inheritdoc} */ public function submitForm(array &$form, FormStateInterface $form_state) { /* @var $entity \Drupal\quiz\Entity\Quiz */ /* @var $question \Drupal\quiz\Entity\Question */ /* @var $answer \Drupal\quiz\Entity\Answer */ /* @var $state \Drupal\quiz\Entity\UserQuizStatus */ $entity = $this->entity; $questions = $entity->getQuestions(); $answerCount = 0; $questionCount = 0; $stateCount = 0; foreach ($questions as $question) { $answers = $question->getAnswers(); foreach ($answers as $answer) { $answerCount++; $answer->delete(); } $questionCount++; $question->delete(); } $states = $entity->getStatuses(); foreach ($states as $state) { $stateCount++; $state->delete(); } $this->entity->delete(); drupal_set_message($this->t('Deleted Quiz @label, @answers answers, @questions questions and @states quiz attempts.', ['@label' => $this->entity->label(), '@answers' => $answerCount, '@questions' => $questionCount, '@states' => $stateCount])); $form_state->setRedirectUrl($this->getCancelUrl()); }
/** * {@inheritdoc} */ public function submitForm(array &$form, FormStateInterface $form_state) { $config = $this->config('configform_example.settings'); $config->set('email_address', $form_state->getValue('email')); $config->save(); return parent::submitForm($form, $form_state); }
/** * {@inheritdoc} */ public function save(array $form, FormStateInterface $form_state) { $this->entity->save(); drupal_set_message($this->t('Saved the %label store type.', [ '%label' => $this->entity->label(), ])); $form_state->setRedirect('entity.commerce_store_type.collection'); }