/** * {@inheritdoc} */ public function submitForm(array &$form, array &$form_state) { $response = new AjaxResponse(); if (form_get_errors($form_state)) { unset($form['#prefix'], $form['#suffix']); $status_messages = array('#theme' => 'status_messages'); $output = drupal_render($form); $output = '<div>' . drupal_render($status_messages) . $output . '</div>'; $response->addCommand(new HtmlCommand('#editor-link-dialog-form', $output)); } else { $response->addCommand(new EditorDialogSave($form_state['values'])); $response->addCommand(new CloseModalDialogCommand()); } return $response; }
/** * Submit the system_config_form ensure the configuration has expected values. */ public function testConfigForm() { // Programmatically submit the given values. foreach ($this->values as $form_key => $data) { $values[$form_key] = $data['#value']; } $form_state = array('values' => $values); drupal_form_submit($this->form, $form_state); // Check that the form returns an error when expected, and vice versa. $errors = form_get_errors($form_state); $valid_form = empty($errors); $args = array('%values' => print_r($values, TRUE), '%errors' => $valid_form ? t('None') : implode(' ', $errors)); $this->assertTrue($valid_form, format_string('Input values: %values<br/>Validation handler errors: %errors', $args)); foreach ($this->values as $data) { $this->assertEqual($data['#value'], \Drupal::config($data['#config_name'])->get($data['#config_key'])); } }
/** * * Do the actual update - passes the update to the plugin's process functions */ function update() { if (function_exists($this->plugin['process'])) { $this->plugin['process']($this); } // Are there any form errors? if ($errors = form_get_errors()) { foreach ($errors as $error) { // Form errors will apply for all entities foreach ($this->entities as $entity) { list($id) = entity_extract_ids($this->entity_type, $entity); $this->set_error($id, $error); } } } return $this->get_result(); }
/** * Helper function used to programmatically submit the form defined in * form_test.module with the given values. * * @param $values * An array of field values to be submitted. * @param $valid_input * A boolean indicating whether or not the form submission is expected to * be valid. */ private function submitForm($values, $valid_input) { // Programmatically submit the given values. $form_state = new FormState(array('values' => $values)); \Drupal::formBuilder()->submitForm('\\Drupal\\form_test\\Form\\FormTestProgrammaticForm', $form_state); // Check that the form returns an error when expected, and vice versa. $errors = form_get_errors($form_state); $valid_form = empty($errors); $args = array('%values' => print_r($values, TRUE), '%errors' => $valid_form ? t('None') : implode(' ', $errors)); $this->assertTrue($valid_input == $valid_form, format_string('Input values: %values<br />Validation handler errors: %errors', $args)); // We check submitted values only if we have a valid input. if ($valid_input) { // By fetching the values from $form_state['storage'] we ensure that the // submission handler was properly executed. $stored_values = $form_state['storage']['programmatic_form_submit']; foreach ($values as $key => $value) { $this->assertEqual($stored_values[$key], $value, format_string('Submission handler correctly executed: %stored_key is %stored_value', array('%stored_key' => $key, '%stored_value' => print_r($value, TRUE)))); } } }
/** * Check if username and email exists in the drupal db * * @params $params array array of name and mail values * @params $errors array array of errors * @params $emailName string field label for the 'email' * * @return void */ static function checkUserNameEmailExists(&$params, &$errors, $emailName = 'email') { $config = CRM_Core_Config::singleton(); $dao = new CRM_Core_DAO(); $name = $dao->escape(CRM_Utils_Array::value('name', $params)); $email = $dao->escape(CRM_Utils_Array::value('mail', $params)); $errors = form_get_errors(); if ($errors) { // unset drupal messages to avoid twice display of errors unset($_SESSION['messages']); } if (!empty($params['name'])) { if ($nameError = user_validate_name($params['name'])) { $errors['cms_name'] = $nameError; } else { $uid = db_query("SELECT uid FROM {users} WHERE name = :name", array(':name' => $params['name']))->fetchField(); if ((bool) $uid) { $errors['cms_name'] = ts('The username %1 is already taken. Please select another username.', array(1 => $params['name'])); } } } if (!empty($params['mail'])) { if ($emailError = user_validate_mail($params['mail'])) { $errors[$emailName] = $emailError; } else { $uid = db_query("SELECT uid FROM {users} WHERE mail = :mail", array(':mail' => $params['mail']))->fetchField(); if ((bool) $uid) { $resetUrl = $config->userFrameworkBaseURL . 'user/password'; $errors[$emailName] = ts('The email address %1 is already registered. <a href="%2">Have you forgotten your password?</a>', array(1 => $params['mail'], 2 => $resetUrl)); } } } }
/** * Validate handler for ctools_export_ui_edit_item_wizard_form. */ function ctools_export_ui_edit_item_wizard_form_validate(&$form, &$form_state) { $method = 'edit_form_' . $form_state['step'] . '_validate'; if (!method_exists($form_state['object'], $method)) { $method = 'edit_form_validate'; } $form_state['object']->{$method}($form, $form_state); // Additionally, if there were no errors from that, and we're finishing, // perform a final validate to make sure everything is ok. if (isset($form_state['clicked_button']['#wizard type']) && $form_state['clicked_button']['#wizard type'] == 'finish' && !form_get_errors()) { $form_state['object']->edit_finish_validate($form, $form_state); } }
/** * {@inheritdoc} */ public function validateForm(array &$form, array &$form_state) { $form_state['handler']->validateOptionsForm($form['options'], $form_state); if (form_get_errors($form_state)) { $form_state['rerender'] = TRUE; } }
function asf_ajax_login_callback($form, &$form_state) { // if errors, return the form if (form_get_errors()) { $msg = 'Sorry, unrecognized username or password.'; for ($i = 0; $i < count($_SESSION['messages']['error']); $i++) { if (strpos($_SESSION['messages']['error'][$i], $msg) !== false) { $_SESSION['messages']['error'][$i] = $msg; break; } } $form_state['rebuild'] = TRUE; return $form; } // this performs the actual login user_login_submit($form, $form_state); // this performs a redirection $path = $form_state["redirect"] . "/subscriptions"; ctools_include('ajax'); ctools_add_js('ajax-responder'); $commands[] = ctools_ajax_command_redirect($path); print ajax_render($commands); exit; }
function tfd_form_get_errors() { $errors = form_get_errors(); if (!empty($errors)) { $newErrors = array(); foreach ($errors as $key => $error) { $newKey = str_replace('submitted][', 'submitted[', $key); if ($newKey !== $key) { $newKey = $newKey . ']'; } $newErrors[$newKey] = $error; } $errors = $newErrors; } return $errors; }
/** * {@inheritdoc} * * Most block plugins should not override this method. To add submission * handling for a specific block type, override BlockBase::blockSubmit(). * * @see \Drupal\block\BlockBase::blockSubmit() */ public function submitConfigurationForm(array &$form, array &$form_state) { // Process the block's submission handling if no errors occurred only. if (!form_get_errors($form_state)) { $this->configuration['label'] = $form_state['values']['label']; $this->configuration['label_display'] = $form_state['values']['label_display']; $this->configuration['provider'] = $form_state['values']['provider']; $this->configuration['cache'] = $form_state['values']['cache']; foreach ($this->getVisibilityConditions() as $condition_id => $condition) { // Allow the condition to submit the form. $condition_values = array('values' => &$form_state['values']['visibility'][$condition_id]); $condition->submitConfigurationForm($form, $condition_values); } $this->blockSubmit($form, $form_state); } }
/** * {@inheritdoc} */ public function submitForm(array &$form, array &$form_state) { $response = new AjaxResponse(); // Convert any uploaded files from the FID values to data-editor-file-uuid // attributes. if (!empty($form_state['values']['fid'][0])) { $file = file_load($form_state['values']['fid'][0]); $file_url = file_create_url($file->getFileUri()); // Transform absolute image URLs to relative image URLs: prevent problems // on multisite set-ups and prevent mixed content errors. $file_url = file_url_transform_relative($file_url); $form_state['values']['attributes']['src'] = $file_url; $form_state['values']['attributes']['data-editor-file-uuid'] = $file->uuid(); } if (form_get_errors($form_state)) { unset($form['#prefix'], $form['#suffix']); $status_messages = array('#theme' => 'status_messages'); $output = drupal_render($form); $output = '<div>' . drupal_render($status_messages) . $output . '</div>'; $response->addCommand(new HtmlCommand('#editor-image-dialog-form', $output)); } else { $response->addCommand(new EditorDialogSave($form_state['values'])); $response->addCommand(new CloseModalDialogCommand()); } return $response; }
/** * Check if username and email exists in the drupal db. * * @param array $params * Array of name and mail values. * @param array $errors * Array of errors. * @param string $emailName * Field label for the 'email'. */ public function checkUserNameEmailExists(&$params, &$errors, $emailName = 'email') { $config = CRM_Core_Config::singleton(); $dao = new CRM_Core_DAO(); $name = $dao->escape(CRM_Utils_Array::value('name', $params)); $email = $dao->escape(CRM_Utils_Array::value('mail', $params)); _user_edit_validate(NULL, $params); $errors = form_get_errors(); if ($errors) { if (!empty($errors['name'])) { $errors['cms_name'] = $errors['name']; } if (!empty($errors['mail'])) { $errors[$emailName] = $errors['mail']; } // also unset drupal messages to avoid twice display of errors unset($_SESSION['messages']); } // Do the name check manually. $nameError = user_validate_name($params['name']); if ($nameError) { $errors['cms_name'] = $nameError; } $sql = "\n SELECT name, mail\n FROM {users}\n WHERE (LOWER(name) = LOWER('{$name}')) OR (LOWER(mail) = LOWER('{$email}'))\n "; $result = db_query($sql); $row = db_fetch_array($result); if (!$row) { return; } $user = NULL; if (!empty($row)) { $dbName = CRM_Utils_Array::value('name', $row); $dbEmail = CRM_Utils_Array::value('mail', $row); if (strtolower($dbName) == strtolower($name)) { $errors['cms_name'] = ts('The username %1 is already taken. Please select another username.', array(1 => $name)); } if (strtolower($dbEmail) == strtolower($email)) { if (empty($email)) { $errors[$emailName] = ts('You cannot create an email account for a contact with no email', array(1 => $email)); } else { $errors[$emailName] = ts('This email %1 is already registered. Please select another email.', array(1 => $email)); } } } }
/** * Simulate action of pressing of an Add More button. This function processes * the form based on the specified inputs and updates the form with the new * values in the cache so that the form's submit button can work correctly. * * @param string $triggering_element_name * Name of the Add More button or value of Op key. * @param array $options * Options array. If key "ajax" is set to TRUE, then * $triggering_element_name is assumed to be name of the Add More button * otherwise it is taken to be the value of Op key. * * @return Response * Response object. */ public function pressButton($triggering_element_name = NULL, $options = array()) { $options += array('ajax' => FALSE); $ajax = $options['ajax']; // Make sure that a button with provided name exists. if ($ajax && !is_null($triggering_element_name) && !$this->buttonExists($triggering_element_name)) { return new Response(FALSE, NULL, "Button {$triggering_element_name} does not exist."); } if (!$ajax) { // If this is not an AJAX request, then the supplied name is the value of // Op parameter. $response = $this->fillOpValues($triggering_element_name); if (!$response->getSuccess()) { return $response; } } $this->clearErrors(); $this->makeUncheckedCheckboxesNull(); $this->removeFileFieldWeights(); $old_form_state_values = !empty($this->form_state['values']) ? $this->form_state['values'] : array(); $this->form_state = form_state_defaults(); $args = func_get_args(); // Remove $triggering_element_name from the arguments. array_shift($args); // Remove $options from the arguments. array_shift($args); $this->form_state['build_info']['args'] = $args; $this->form_state['programmed_bypass_access_check'] = FALSE; //$this->form_state['values']['form_build_id'] = $this->form['#build_id']; // Add more field button sets $form_state['rebuild'] to TRUE because of // which submit handlers are not called. Hence we set it back to FALSE. $this->removeKey('input'); $this->removeKey('triggering_element'); $this->removeKey('validate_handlers'); $this->removeKey('submit_handlers'); $this->removeKey('clicked_button'); $this->form_state['input'] = $old_form_state_values; $this->form_state['input']['form_build_id'] = $this->form['#build_id']; if (!is_null($triggering_element_name) && $ajax) { $this->form_state['input']['_triggering_element_name'] = $triggering_element_name; } $this->form_state['no_redirect'] = TRUE; $this->form_state['method'] = 'post'; //$this->form_state['programmed'] = TRUE; $this->form = drupal_build_form($this->form_id, $this->form_state); if ($ajax && !is_null($triggering_element_name)) { unset($this->form_state['values'][$triggering_element_name]); } // Reset the static cache for validated forms otherwise form won't go // through validation function again. drupal_static_reset('drupal_validate_form'); if ($errors = form_get_errors()) { $this->errors = $errors; return new Response(FALSE, NULL, implode(", ", $this->errors)); } return new Response(TRUE, NULL, ""); }
/** * {@inheritdoc} */ public function validateForm(array &$form, array &$form_state) { $form_state['view']->getExecutable()->displayHandlers->get($form_state['display_id'])->validateOptionsForm($form['options'], $form_state); if (form_get_errors($form_state)) { $form_state['rerender'] = TRUE; } }
<?php $messages = form_get_errors(); if (!empty($messages)) { foreach ($messages as $message) { drupal_set_message($message, 'error'); } print theme('status_messages'); } print drupal_render_children($form);
/** * Form constructor. * * Display a tree of all the terms in a vocabulary, with options to edit * each one. The form is made drag and drop by the theme function. * * @param array $form * An associative array containing the structure of the form. * @param array $form_state * An associative array containing the current state of the form. * @param \Drupal\taxonomy\VocabularyInterface $taxonomy_vocabulary * The vocabulary to display the overview form for. * * @return array * The form structure. */ public function buildForm(array $form, array &$form_state, VocabularyInterface $taxonomy_vocabulary = NULL) { // @todo Remove global variables when http://drupal.org/node/2044435 is in. global $pager_page_array, $pager_total, $pager_total_items; $form_state['taxonomy']['vocabulary'] = $taxonomy_vocabulary; $parent_fields = FALSE; $page = $this->getRequest()->query->get('page') ?: 0; // Number of terms per page. $page_increment = $this->config('taxonomy.settings')->get('terms_per_page_admin'); // Elements shown on this page. $page_entries = 0; // Elements at the root level before this page. $before_entries = 0; // Elements at the root level after this page. $after_entries = 0; // Elements at the root level on this page. $root_entries = 0; // Terms from previous and next pages are shown if the term tree would have // been cut in the middle. Keep track of how many extra terms we show on // each page of terms. $back_step = NULL; $forward_step = 0; // An array of the terms to be displayed on this page. $current_page = array(); $delta = 0; $term_deltas = array(); // @todo taxonomy_get_tree needs to be converted to a service and injected. // Will be fixed in http://drupal.org/node/1976298. $tree = taxonomy_get_tree($taxonomy_vocabulary->id(), 0, NULL, TRUE); $term = current($tree); do { // In case this tree is completely empty. if (empty($term)) { break; } $delta++; // Count entries before the current page. if ($page && $page * $page_increment > $before_entries && !isset($back_step)) { $before_entries++; continue; } elseif ($page_entries > $page_increment && isset($complete_tree)) { $after_entries++; continue; } // Do not let a term start the page that is not at the root. if (isset($term->depth) && $term->depth > 0 && !isset($back_step)) { $back_step = 0; while ($pterm = prev($tree)) { $before_entries--; $back_step++; if ($pterm->depth == 0) { prev($tree); // Jump back to the start of the root level parent. continue 2; } } } $back_step = isset($back_step) ? $back_step : 0; // Continue rendering the tree until we reach the a new root item. if ($page_entries >= $page_increment + $back_step + 1 && $term->depth == 0 && $root_entries > 1) { $complete_tree = TRUE; // This new item at the root level is the first item on the next page. $after_entries++; continue; } if ($page_entries >= $page_increment + $back_step) { $forward_step++; } // Finally, if we've gotten down this far, we're rendering a term on this // page. $page_entries++; $term_deltas[$term->id()] = isset($term_deltas[$term->id()]) ? $term_deltas[$term->id()] + 1 : 0; $key = 'tid:' . $term->id() . ':' . $term_deltas[$term->id()]; // Keep track of the first term displayed on this page. if ($page_entries == 1) { $form['#first_tid'] = $term->id(); } // Keep a variable to make sure at least 2 root elements are displayed. if ($term->parents[0] == 0) { $root_entries++; } $current_page[$key] = $term; } while ($term = next($tree)); // Because we didn't use a pager query, set the necessary pager variables. $total_entries = $before_entries + $page_entries + $after_entries; $pager_total_items[0] = $total_entries; $pager_page_array[0] = $page; $pager_total[0] = ceil($total_entries / $page_increment); // If this form was already submitted once, it's probably hit a validation // error. Ensure the form is rebuilt in the same order as the user // submitted. if (!empty($form_state['input'])) { // Get the POST order. $order = array_flip(array_keys($form_state['input']['terms'])); // Update our form with the new order. $current_page = array_merge($order, $current_page); foreach ($current_page as $key => $term) { // Verify this is a term for the current page and set at the current // depth. if (is_array($form_state['input']['terms'][$key]) && is_numeric($form_state['input']['terms'][$key]['term']['tid'])) { $current_page[$key]->depth = $form_state['input']['terms'][$key]['term']['depth']; } else { unset($current_page[$key]); } } } $errors = form_get_errors($form_state); $destination = drupal_get_destination(); $row_position = 0; // Build the actual form. $form['terms'] = array('#type' => 'table', '#header' => array($this->t('Name'), $this->t('Weight'), $this->t('Operations')), '#empty' => $this->t('No terms available. <a href="@link">Add term</a>.', array('@link' => url('admin/structure/taxonomy/manage/' . $taxonomy_vocabulary->id() . '/add'))), '#attributes' => array('id' => 'taxonomy')); foreach ($current_page as $key => $term) { /** @var $term \Drupal\Core\Entity\EntityInterface */ $form['terms'][$key]['#term'] = $term; $indentation = array(); if (isset($term->depth) && $term->depth > 0) { $indentation = array('#theme' => 'indentation', '#size' => $term->depth); } $form['terms'][$key]['term'] = array('#prefix' => !empty($indentation) ? drupal_render($indentation) : '', '#type' => 'link', '#title' => $term->getName()) + $term->urlInfo()->toRenderArray(); if ($taxonomy_vocabulary->hierarchy != TAXONOMY_HIERARCHY_MULTIPLE && count($tree) > 1) { $parent_fields = TRUE; $form['terms'][$key]['term']['tid'] = array('#type' => 'hidden', '#value' => $term->id(), '#attributes' => array('class' => array('term-id'))); $form['terms'][$key]['term']['parent'] = array('#type' => 'hidden', '#default_value' => $term->parents[0], '#attributes' => array('class' => array('term-parent'))); $form['terms'][$key]['term']['depth'] = array('#type' => 'hidden', '#default_value' => $term->depth, '#attributes' => array('class' => array('term-depth'))); } $form['terms'][$key]['weight'] = array('#type' => 'weight', '#delta' => $delta, '#title' => $this->t('Weight for added term'), '#title_display' => 'invisible', '#default_value' => $term->getWeight(), '#attributes' => array('class' => array('term-weight'))); $operations = array('edit' => array('title' => $this->t('Edit'), 'query' => $destination) + $term->urlInfo('edit-form')->toArray(), 'delete' => array('title' => $this->t('Delete'), 'query' => $destination) + $term->urlInfo('delete-form')->toArray()); if ($this->moduleHandler->moduleExists('content_translation') && content_translation_translate_access($term)) { $operations['translate'] = array('title' => $this->t('Translate'), 'query' => $destination) + $term->urlInfo('drupal:content-translation-overview')->toArray(); } $form['terms'][$key]['operations'] = array('#type' => 'operations', '#links' => $operations); $form['terms'][$key]['#attributes']['class'] = array(); if ($parent_fields) { $form['terms'][$key]['#attributes']['class'][] = 'draggable'; } // Add classes that mark which terms belong to previous and next pages. if ($row_position < $back_step || $row_position >= $page_entries - $forward_step) { $form['terms'][$key]['#attributes']['class'][] = 'taxonomy-term-preview'; } if ($row_position !== 0 && $row_position !== count($tree) - 1) { if ($row_position == $back_step - 1 || $row_position == $page_entries - $forward_step - 1) { $form['terms'][$key]['#attributes']['class'][] = 'taxonomy-term-divider-top'; } elseif ($row_position == $back_step || $row_position == $page_entries - $forward_step) { $form['terms'][$key]['#attributes']['class'][] = 'taxonomy-term-divider-bottom'; } } // Add an error class if this row contains a form error. foreach ($errors as $error_key => $error) { if (strpos($error_key, $key) === 0) { $form['terms'][$key]['#attributes']['class'][] = 'error'; } } $row_position++; } if ($parent_fields) { $form['terms']['#tabledrag'][] = array('action' => 'match', 'relationship' => 'parent', 'group' => 'term-parent', 'subgroup' => 'term-parent', 'source' => 'term-id', 'hidden' => FALSE); $form['terms']['#tabledrag'][] = array('action' => 'depth', 'relationship' => 'group', 'group' => 'term-depth', 'hidden' => FALSE); $form['terms']['#attached']['library'][] = 'taxonomy/drupal.taxonomy'; $form['terms']['#attached']['js'][] = array('data' => array('taxonomy' => array('backStep' => $back_step, 'forwardStep' => $forward_step)), 'type' => 'setting'); } $form['terms']['#tabledrag'][] = array('action' => 'order', 'relationship' => 'sibling', 'group' => 'term-weight'); if ($taxonomy_vocabulary->hierarchy != TAXONOMY_HIERARCHY_MULTIPLE && count($tree) > 1) { $form['actions'] = array('#type' => 'actions', '#tree' => FALSE); $form['actions']['submit'] = array('#type' => 'submit', '#value' => $this->t('Save'), '#button_type' => 'primary'); $form['actions']['reset_alphabetical'] = array('#type' => 'submit', '#submit' => array(array($this, 'submitReset')), '#value' => $this->t('Reset to alphabetical')); $form_state['redirect'] = array(current_path(), $page ? array('query' => array('page' => $page)) : array()); } return $form; }
/** * Verify existing settings.php */ function install_verify_settings() { global $db_prefix, $databases; // Verify existing settings (if any). if (!empty($databases)) { // We need this because we want to run form_get_errors. include_once DRUPAL_ROOT . '/includes/form.inc'; $database = $databases['default']['default']; $settings_file = './' . conf_path(FALSE, TRUE) . '/settings.php'; $form_state = array(); _install_settings_form_validate($database, $settings_file, $form_state); if (!form_get_errors()) { return TRUE; } } return FALSE; }
function guifi_device_form_validate($form, &$form_state) { global $user; guifi_log(GUIFILOG_TRACE, 'function guifi_device_form_validate()', $form_state['values']); guifi_log(GUIFILOG_TRACE, 'function guifi_device_form_validate(vlans)', $form_state['values'][vlans]); guifi_log(GUIFILOG_TRACE, 'function guifi_device_form_validate(aggregations)', $form_state['values'][aggregations]); guifi_log(GUIFILOG_TRACE, 'function guifi_device_form_validate(ipv4)', $form_state['values'][ipv4]); // nick if (isset($form['main']['nick'])) { guifi_validate_nick($form_state['values']['nick']); $query = db_query("\n SELECT nick\n FROM {guifi_devices}\n WHERE lcase(nick)=lcase('%s')\n AND id <> %d", strtolower($form_state['values']['nick']), $form_state['values']['id']); while (db_fetch_object($query)) { form_set_error('nick', t('Nick already in use.')); } } // ssid if (empty($form_state['values']['ssid'])) { $form_state['values']['ssid'] = $form_state['values']['nick']; } // Validate ip address(es) // Finding duplicates $ips = array(); if (!empty($form_state['values']['ipv4'])) { // first checking local IPs foreach ($form_state['values']['ipv4'] as $keyS => $valueS) { if (empty($valueS[ipv4])) { continue; } // duplicate ip? if (in_array($valueS[ipv4], $ips)) { form_set_error("ipv4][{$keyS}][ipv4", t('address %addr is duplicated', array('%addr' => $valueS[ipv4]))); } $ips[] = $valueS[ipv4]; $valueSIPCalc = _ipcalc($valueS[ipv4], $valueS[netmask]); // Now looking into remote IPs foreach ($valueS[subnet] as $keyI => $valueI) { if (empty($valueI[ipv4])) { continue; } guifi_log(GUIFILOG_TRACE, 'function guifi_device_form_validate(ipv4s)', $valueS[ipv4] . ' / ' . $valueI[ipv4] . ' ' . $valueI[did]); // duplicate ip? if (in_array($valueI[ipv4], $ips)) { if ($valueI['new']) { $field = "ipv4][{$keyS}][subnet][{$keyI}][ipv4txt"; } else { $field = "ipv4][{$keyS}][subnet][{$keyI}][ipv4"; } form_set_error($field, t('address %addr is duplicated', array('%addr' => $valueI[ipv4]))); } $ips[] = $valueI[ipv4]; // same subnet as related IP? $valueIIPCalc = _ipcalc($valueI[ipv4], $valueS[netmask]); if ($valueSIPCalc[netid] != $valueIIPCalc[netid] or $valueSIPCalc[maskbits] != $valueIIPCalc[maskbits]) { form_set_error("ipv4][{$keyS}][subnet][{$keyI}][ipv4", t('address %addr1 not at same subnet as %addr2', array('%addr1' => $valueI[ipv4], '%addr2' => $valueS[ipv4]))); } // remote id should be populated if (empty($valueI[did])) { form_set_error("ipv4][{$keyS}][subnet][{$keyI}][did", t('Remote device for address %addr1 not specified', array('%addr1' => $valueI[ipv4]))); } } // for remote IPs } // for local IPs /* if (db_affected_rows(db_query(" SELECT i.id FROM {guifi_interfaces} i,{guifi_ipv4} a WHERE i.id=a.interface_id AND a.ipv4='%s' AND i.device_id != %d", $form_state['values']['ipv4'], $form_state['values']['id']))) { $message = t('IP %ipv4 already taken in the database. Choose another or leave the address blank.', array('%ipv4' => $form_state['values']['ipv4'])); form_set_error('ipv4',$message); } */ } // Validating vlans & aggregations foreach (array('vlans', 'aggregations') as $vtype) { foreach ($form_state['values'][$vtype] as $kvlan => $vlan) { // interface_type (name) should have a value if (empty($vlan['interface_type']) and !form_get_errors()) { $vlan['interface_type'] = substr($vtype, 0, 4) . $kvlan; form_set_value(array('#parents' => array($vtype, $kvlan, 'interface_type')), $vlan['interface_type'], $form_state); $form_state['rebuild'] = TRUE; drupal_set_message(t('Setting interface name to %name', array('%name' => $vlan['interface_type'])), 'warning'); } // parent should exists if (empty($vlan['related_interfaces'])) { form_set_error("{$vtype}][{$kvlan}][related_interfaces", t('%name should have related interface(s)', array('%name' => $vlan[interface_type]))); } } } // foreach vlans, aggregations // No duplicate names on interface names $ifs = guifi_get_currentInterfaces($form_state['values']); $iChecked = array(); foreach ($ifs as $k => $iname) { if (in_array($iname, $iChecked)) { guifi_log(GUIFILOG_TRACE, 'function guifi_device_form_validate()', $iname); foreach (array('interfaces', 'vlans', 'aggregations', 'tunnels') as $iClass) { if (isset($form_state[values][$iClass][$k])) { $f = $iClass . "][{$k}][interface_type"; } form_set_error($f, t('Interface name %name duplicated', array('%name' => $iname))); } } $iChecked[] = $iname; } if (count($form_state['values']['radios'])) { foreach ($form_state['values']['radios'] as $k => $v) { guifi_radios_validate($k, $v, $form_state['values']); } } guifi_maintainers_validate(array2object($form_state['values'])); guifi_funders_validate(array2object($form_state['values'])); }
/** * Check if username and email exists in the drupal db. * * @param array $params * Array of name and mail values. * @param array $errors * Array of errors. * @param string $emailName * Field label for the 'email'. */ public static function checkUserNameEmailExists(&$params, &$errors, $emailName = 'email') { $errors = form_get_errors(); if ($errors) { // unset drupal messages to avoid twice display of errors unset($_SESSION['messages']); } if (!empty($params['name'])) { if ($nameError = user_validate_name($params['name'])) { $errors['cms_name'] = $nameError; } else { $uid = db_query("SELECT uid FROM {users} WHERE name = :name", array(':name' => $params['name']))->fetchField(); if ((bool) $uid) { $errors['cms_name'] = ts('The username %1 is already taken. Please select another username.', array(1 => $params['name'])); } } } if (!empty($params['mail'])) { if (!valid_email_address($params['mail'])) { $errors[$emailName] = ts('The e-mail address %1 is not valid.', array('%1' => $params['mail'])); } else { $uid = db_query("SELECT uid FROM {users} WHERE mail = :mail", array(':mail' => $params['mail']))->fetchField(); if ((bool) $uid) { $resetUrl = url('user/password'); $errors[$emailName] = ts('The email address %1 already has an account associated with it. <a href="%2">Have you forgotten your password?</a>', array(1 => $params['mail'], 2 => $resetUrl)); } } } }
/** * Function to create a user in Drupal. * * @param array $params associated array * @param string $mail email id for cms user * * @return uid if user exists, false otherwise * * @access public * @static */ static function createDrupalUser(&$params, $mail) { $values['values'] = array('name' => $params['cms_name'], 'mail' => $params[$mail], 'op' => 'Create new account'); if (!variable_get('user_email_verification', TRUE)) { $values['values']['pass']['pass1'] = $params['cms_pass']; $values['values']['pass']['pass2'] = $params['cms_pass']; } $config =& CRM_Core_Config::singleton(); // we also need to redirect b $config->inCiviCRM = true; $res = drupal_execute('user_register', $values); $config->inCiviCRM = false; if (form_get_errors()) { return false; } // looks like we created a drupal user, lets make another db call to get the user id! $db_cms = DB::connect($config->userFrameworkDSN); if (DB::isError($db_cms)) { die("Cannot connect to UF db via {$dsn}, " . $db_cms->getMessage()); } //Fetch id of newly added user $id_sql = "SELECT uid FROM {$config->userFrameworkUsersTableName} where name = '{$params['cms_name']}'"; $id_query = $db_cms->query($id_sql); $id_row = $id_query->fetchRow(DB_FETCHMODE_ASSOC); return $id_row['uid']; }
/** * Check several empty values for required forms elements. * * Carriage returns, tabs, spaces, and unchecked checkbox elements are not * valid content for a required field. * * If the form field is found in form_get_errors() then the test pass. */ function testRequiredFields() { // Originates from http://drupal.org/node/117748 // Sets of empty strings and arrays. $empty_strings = array('""' => "", '"\\n"' => "\n", '" "' => " ", '"\\t"' => "\t", '" \\n\\t "' => " \n\t ", '"\\n\\n\\n\\n\\n"' => "\n\n\n\n\n"); $empty_arrays = array('array()' => array()); $empty_checkbox = array(NULL); $elements['textfield']['element'] = array('#title' => $this->randomName(), '#type' => 'textfield'); $elements['textfield']['empty_values'] = $empty_strings; $elements['telephone']['element'] = array('#title' => $this->randomName(), '#type' => 'tel'); $elements['telephone']['empty_values'] = $empty_strings; $elements['url']['element'] = array('#title' => $this->randomName(), '#type' => 'url'); $elements['url']['empty_values'] = $empty_strings; $elements['search']['element'] = array('#title' => $this->randomName(), '#type' => 'search'); $elements['search']['empty_values'] = $empty_strings; $elements['password']['element'] = array('#title' => $this->randomName(), '#type' => 'password'); $elements['password']['empty_values'] = $empty_strings; $elements['password_confirm']['element'] = array('#title' => $this->randomName(), '#type' => 'password_confirm'); // Provide empty values for both password fields. foreach ($empty_strings as $key => $value) { $elements['password_confirm']['empty_values'][$key] = array('pass1' => $value, 'pass2' => $value); } $elements['textarea']['element'] = array('#title' => $this->randomName(), '#type' => 'textarea'); $elements['textarea']['empty_values'] = $empty_strings; $elements['radios']['element'] = array('#title' => $this->randomName(), '#type' => 'radios', '#options' => array('' => t('None'), $this->randomName(), $this->randomName(), $this->randomName())); $elements['radios']['empty_values'] = $empty_arrays; $elements['checkbox']['element'] = array('#title' => $this->randomName(), '#type' => 'checkbox', '#required' => TRUE); $elements['checkbox']['empty_values'] = $empty_checkbox; $elements['checkboxes']['element'] = array('#title' => $this->randomName(), '#type' => 'checkboxes', '#options' => array($this->randomName(), $this->randomName(), $this->randomName())); $elements['checkboxes']['empty_values'] = $empty_arrays; $elements['select']['element'] = array('#title' => $this->randomName(), '#type' => 'select', '#options' => array('' => t('None'), $this->randomName(), $this->randomName(), $this->randomName())); $elements['select']['empty_values'] = $empty_strings; $elements['file']['element'] = array('#title' => $this->randomName(), '#type' => 'file'); $elements['file']['empty_values'] = $empty_strings; // Regular expression to find the expected marker on required elements. $required_marker_preg = '@<.*?class=".*?form-required.*?">@'; // Go through all the elements and all the empty values for them. foreach ($elements as $type => $data) { foreach ($data['empty_values'] as $key => $empty) { foreach (array(TRUE, FALSE) as $required) { $form_id = $this->randomName(); $form = array(); $form_state = \Drupal::formBuilder()->getFormStateDefaults(); $form['op'] = array('#type' => 'submit', '#value' => t('Submit')); $element = $data['element']['#title']; $form[$element] = $data['element']; $form[$element]['#required'] = $required; $form_state['input'][$element] = $empty; $form_state['input']['form_id'] = $form_id; $form_state['build_info']['callback_object'] = new StubForm($form_id, $form); $form_state['method'] = 'post'; // The form token CSRF protection should not interfere with this test, // so we bypass it by setting the token to FALSE. $form['#token'] = FALSE; \Drupal::formBuilder()->prepareForm($form_id, $form, $form_state); drupal_process_form($form_id, $form, $form_state); $errors = form_get_errors($form_state); // Form elements of type 'radios' throw all sorts of PHP notices // when you try to render them like this, so we ignore those for // testing the required marker. // @todo Fix this work-around (http://drupal.org/node/588438). $form_output = $type == 'radios' ? '' : drupal_render($form); if ($required) { // Make sure we have a form error for this element. $this->assertTrue(isset($errors[$element]), "Check empty({$key}) '{$type}' field '{$element}'"); if (!empty($form_output)) { // Make sure the form element is marked as required. $this->assertTrue(preg_match($required_marker_preg, $form_output), "Required '{$type}' field is marked as required"); } } else { if (!empty($form_output)) { // Make sure the form element is *not* marked as required. $this->assertFalse(preg_match($required_marker_preg, $form_output), "Optional '{$type}' field is not marked as required"); } if ($type == 'select') { // Select elements are going to have validation errors with empty // input, since those are illegal choices. Just make sure the // error is not "field is required". $this->assertTrue(empty($errors[$element]) || strpos('field is required', $errors[$element]) === FALSE, "Optional '{$type}' field '{$element}' is not treated as a required element"); } else { // Make sure there is *no* form error for this element. $this->assertTrue(empty($errors[$element]), "Optional '{$type}' field '{$element}' has no errors with empty input"); } } } } } // Clear the expected form error messages so they don't appear as exceptions. drupal_get_messages(); }
/** * Drupal get login example */ public function postPasswordReset() { //var_dump($_POST); $drupal = new \erdiko\drupal\Model(); // Load required include files for requesting user's password \module_load_include('inc', 'user', 'user.pages'); // Fill form_state. $form_state['values']['name'] = $_POST['name']; $form_state['values']['op'] = 'E-mail new password'; // Execute the register form. \drupal_form_submit('user_pass', $form_state); if ($errors = form_get_errors()) { // The supplied name is neither a username nor an email address. return service_error(implode(" ", $errors), 406, array('form_errors' => $errors)); } else { // Requesting new password has been successful. $this->setContent('Email sent'); } }
/** * Verify existing settings.php */ function install_verify_settings() { global $db_prefix, $db_type, $db_url; // Verify existing settings (if any). if ($_SERVER['REQUEST_METHOD'] == 'GET' && $db_url != 'mysql://*****:*****@localhost/databasename') { // We need this because we want to run form_get_errors. include_once './includes/form.inc'; $url = parse_url(is_array($db_url) ? $db_url['default'] : $db_url); $db_user = urldecode($url['user']); $db_pass = urldecode($url['pass']); $db_host = urldecode($url['host']); $db_port = isset($url['port']) ? urldecode($url['port']) : ''; $db_path = ltrim(urldecode($url['path']), '/'); $settings_file = './' . conf_path() . '/settings.php'; _install_settings_form_validate($db_prefix, $db_type, $db_user, $db_pass, $db_host, $db_port, $db_path, $settings_file); if (!form_get_errors()) { return TRUE; } } return FALSE; }
/** * Slightly change the default signature, in order to pragmatically add the * content type name in order to use it as update function. * * Because content types won't have a changing name among sites (on the * opposite as other entities which has incremented identifiers instead * of user set canonical name) we can afford to do an intelligent function * that will guess itself whatever it has to do. * * @see Entity::_save() */ protected function _save($export, $type_name = NULL) { // Basic behavior options. $overwrite = FALSE; switch ($this->getSettings()->getOption('contentBehavior', Yamm_Entity_ContentSettings::MODULE_OVERRIDE)) { case Yamm_Entity_ContentSettings::MODULE_IGNORE: return; case Yamm_Entity_ContentSettings::MODULE_OVERRIDE: // Let the algorigthm do its default job, which is saving the current // content type whatever it exists or not. $overwrite = TRUE; break; case Yamm_Entity_ContentSettings::MODULE_OVERRIDEFALLBACK: // FIXME: Todo. break; case Yamm_Entity_ContentSettings::MODULE_TRYENABLE: default: // FIXME: Todo. break; } // Get back content type name. if (!$type_name) { preg_match('/\'type\'[ ]+=>[ ]+\'([a-zA-Z0-9-_]+)\'/', $export, $matches); $type_name = $matches[1]; } // Check that type already exists on client side, if yes, overwrite it. $type_exists = db_result(db_query("SELECT 1 FROM {node_type} WHERE name = '%s'", $type_name)); $values = array('macro' => $export, 'op' => 'Submit'); $values['type_name'] = $type_exists ? $type_name : '<create>'; // Save the content type using the content_copy module. $form_state['values'] = $values; drupal_execute('content_copy_import_form', $form_state); // Check for errors during creation or update. if ($errors = form_get_errors()) { foreach ($errors as $error) { $msg .= "{$error} "; } watchdog('entity_content', "Error during content import @msg", array("@msg" => $msg), WATCHDOG_ERROR); } // Attempt to clear form cache. cache_clear_all(NULL, 'cache_form'); form_set_error(NULL, '', TRUE); // This will store content type latest definition. cache_set('content_entity_' . $type_name, md5($export), 'yamm_data_store', CACHE_PERMANENT); return $type_name; }
/** * Check if username and email exists in the drupal db * * @params $params array array of name and mail values * @params $errors array array of errors * @params $emailName string field label for the 'email' * * @return void */ function checkUserNameEmailExists(&$params, &$errors, $emailName = 'email') { $config = CRM_Core_Config::singleton(); $dao = new CRM_Core_DAO(); $name = $dao->escape(CRM_Utils_Array::value('name', $params)); $email = $dao->escape(CRM_Utils_Array::value('mail', $params)); _user_edit_validate(NULL, $params); $errors = form_get_errors(); if ($errors) { if (CRM_Utils_Array::value('name', $errors)) { $errors['cms_name'] = $errors['name']; } if (CRM_Utils_Array::value('mail', $errors)) { $errors[$emailName] = $errors['mail']; } // also unset drupal messages to avoid twice display of errors unset($_SESSION['messages']); } // drupal api sucks do the name check manually $nameError = user_validate_name($params['name']); if ($nameError) { $errors['cms_name'] = $nameError; } $sql = "\nSELECT name, mail\n FROM {$config->userFrameworkUsersTableName}\n WHERE (LOWER(name) = LOWER('{$name}')) OR (LOWER(mail) = LOWER('{$email}'))"; $db_cms = DB::connect($config->userFrameworkDSN); if (DB::isError($db_cms)) { die("Cannot connect to UF db via {$dsn}, " . $db_cms->getMessage()); } $query = $db_cms->query($sql); $row = $query->fetchRow(); if (!empty($row)) { $dbName = CRM_Utils_Array::value(0, $row); $dbEmail = CRM_Utils_Array::value(1, $row); if (strtolower($dbName) == strtolower($name)) { $errors['cms_name'] = ts('The username %1 is already taken. Please select another username.', array(1 => $name)); } if (strtolower($dbEmail) == strtolower($email)) { $errors[$emailName] = ts('This email %1 is already registered. Please select another email.', array(1 => $email)); } } }
function opcaim_preprocess_status_messages(&$variables) { $form_errors = form_get_errors(); // on parcours les erreurs du formulaire pour les retirer de la session if (!$form_errors) { return; } foreach ($form_errors as $form_error) { if (isset($_SESSION['messages']['error'])) { $pos = array_search($form_error, $_SESSION['messages']['error']); if ($pos !== FALSE) { unset($_SESSION['messages']['error'][$pos]); } } } // On fait un unset si on a plus d'erreur, sinon on a l'affichage de la div if (empty($_SESSION['messages']['error'])) { unset($_SESSION['messages']['error']); } }
/** * Helper function for outputting the preview above the form * @param $form * @param $form_state */ function snippet_form_build_preview_callback($form, &$form_state) { // Display a preview of the snippet. if (!form_get_errors()) { $variable = array(); $variable['rid'] = $form_state['values']['rid']; $variable['name'] = $form_state['values']['name']; $variable['title'] = check_plain($form_state['values']['title']); $variable['content'] = check_markup($form_state['values']['content']['value'], $form_state['values']['content']['format']); $variable['in_preview'] = 1; return array("#markup" => '<div id="snippet_preview">' . theme('snippet', $variable) . '</div>'); } }
<?php $errors = form_get_errors(); $fields = array('name', 'prenom', 'mail', 'message'); foreach ($fields as $field) { if (isset($errors[$field])) { $form[$field]['#attributes']['aria-describedby'] = "error-{$field}"; } } global $base_url; ?> <div class="container"> <div class='row top-mid-buffer'> <div id="bloc-footer-info" class="col-xs-12 col-sm-4 pull-right"> <?php $block = module_invoke('block', 'block_view', '2'); print render($block['content']); ?> <!-- <div id="social-icon" class="col-xs-12 col-sm-4 col-md-8 ">--> <!-- <img class="vcenter" src="--><?php //print $base_url . '/sites/all/themes/osteopathie/images/viadeo.png'; ?> <!--"/>--> <!-- <img class="vcenter" src="--><?php //print $base_url . '/sites/all/themes/osteopathie/images/facebook.png'; ?> <!--"/>--> <!-- <img class="vcenter" src="--><?php //print $base_url . '/sites/all/themes/osteopathie/images/google.png'; ?>
/** * Verify existing settings.php */ function install_verify_settings() { global $db_prefix, $db_type, $db_url; // Verify existing settings (if any). if (!empty($db_url)) { // We need this because we want to run form_get_errors. include_once './includes/form.inc'; $url = parse_url(is_array($db_url) ? $db_url['default'] : $db_url); $db_user = urldecode($url['user']); $db_pass = isset($url['pass']) ? urldecode($url['pass']) : NULL; $db_host = urldecode($url['host']); $db_port = isset($url['port']) ? urldecode($url['port']) : ''; $db_path = ltrim(urldecode($url['path']), '/'); $settings_file = './' . conf_path(FALSE, TRUE) . '/settings.php'; $form_state = array(); _install_settings_form_validate($db_prefix, $db_type, $db_user, $db_pass, $db_host, $db_port, $db_path, $settings_file, $form_state); if (!form_get_errors()) { return TRUE; } } return FALSE; }
/** * Run an individual installation task. * * @param $task * An array of information about the task to be run. * @param $install_state * An array of information about the current installation state. This is * passed in by reference so that it can be modified by the task. * @return * The output of the task function, if there is any. */ function install_run_task($task, &$install_state) { $function = $task['function']; if ($task['type'] == 'form') { require_once DRUPAL_ROOT . '/includes/form.inc'; if ($install_state['interactive']) { // For interactive forms, build the form and ensure that it will not // redirect, since the installer handles its own redirection only after // marking the form submission task complete. $form_state = array('args' => array(&$install_state), 'no_redirect' => TRUE); $form = drupal_build_form($function, $form_state); // If a successful form submission did not occur, the form needs to be // rendered, which means the task is not complete yet. if (empty($form_state['executed'])) { $install_state['task_not_complete'] = TRUE; return drupal_render($form); } // Otherwise, return nothing so the next task will run in the same // request. return; } else { // For non-interactive forms, submit the form programmatically with the // values taken from the installation state. Throw an exception if any // errors were encountered. $form_state = array('values' => !empty($install_state['forms'][$function]) ? $install_state['forms'][$function] : array()); drupal_form_submit($function, $form_state, $install_state); $errors = form_get_errors(); if (!empty($errors)) { throw new Exception(implode("\n", $errors)); } } } elseif ($task['type'] == 'batch') { // Start a new batch based on the task function, if one is not running // already. $current_batch = variable_get('install_current_batch'); if (!$install_state['interactive'] || !$current_batch) { $batch = $function($install_state); if (empty($batch)) { // If the task did some processing and decided no batch was necessary, // there is nothing more to do here. return; } batch_set($batch); // For interactive batches, we need to store the fact that this batch // task is currently running. Otherwise, we need to make sure the batch // will complete in one page request. if ($install_state['interactive']) { variable_set('install_current_batch', $function); } else { $batch =& batch_get(); $batch['progressive'] = FALSE; } // Process the batch. For progressive batches, this will redirect. // Otherwise, the batch will complete. batch_process(install_redirect_url($install_state), install_full_redirect_url($install_state)); } elseif ($current_batch == $function) { include_once DRUPAL_ROOT . '/includes/batch.inc'; $output = _batch_page(); // The task is complete when we try to access the batch page and receive // FALSE in return, since this means we are at a URL where we are no // longer requesting a batch ID. if ($output === FALSE) { // Return nothing so the next task will run in the same request. variable_del('install_current_batch'); return; } else { // We need to force the page request to end if the task is not // complete, since the batch API sometimes prints JSON output // rather than returning a themed page. $install_state['task_not_complete'] = $install_state['stop_page_request'] = TRUE; return $output; } } } else { // For normal tasks, just return the function result, whatever it is. return $function($install_state); } }