/**
  * {@inheritdoc}
  */
 public function elementValidate($element, FormStateInterface $form_state, $form)
 {
     $auto_create = $this->getSelectionHandlerSetting('auto_create');
     // If a value was entered into the autocomplete.
     $value = NULL;
     if (!empty($element['#value'])) {
         // Take "label (entity id)', match the id from parenthesis.
         // @todo: Lookup the entity type's ID data type and use it here.
         // https://drupal.org/node/2107249
         if ($this->isContentReferenced() && preg_match("/.+\\((\\d+)\\)/", $element['#value'], $matches)) {
             $value = $matches[1];
         } elseif (preg_match("/.+\\(([\\w.]+)\\)/", $element['#value'], $matches)) {
             $value = $matches[1];
         }
         if ($value === NULL) {
             // Try to get a match from the input string when the user didn't use the
             // autocomplete but filled in a value manually.
             $handler = \Drupal::service('plugin.manager.entity_reference.selection')->getSelectionHandler($this->fieldDefinition);
             $value = $handler->validateAutocompleteInput($element['#value'], $element, $form_state, $form, !$auto_create);
         }
         if (!$value && $auto_create && count($this->getSelectionHandlerSetting('target_bundles')) == 1) {
             // Auto-create item. See
             // \Drupal\Core\Field\Plugin\Field\FieldType\EntityReferenceItem::presave().
             $value = array('target_id' => NULL, 'entity' => $this->createNewEntity($element['#value'], $element['#autocreate_uid']), '_weight' => $element['#weight']);
             // Change the element['#parents'], so in form_set_value() we
             // populate the correct key.
             array_pop($element['#parents']);
         }
     }
     form_set_value($element, $value, $form_state);
 }
 /**
  * Form element validation handler for 'name' in form_test_validate_form().
  */
 public function validateName(&$element, FormStateInterface $form_state)
 {
     $triggered = FALSE;
     if ($form_state->getValue('name') == 'element_validate') {
         // Alter the form element.
         $element['#value'] = '#value changed by #element_validate';
         // Alter the submitted value in $form_state.
         form_set_value($element, 'value changed by form_set_value() in #element_validate', $form_state);
         $triggered = TRUE;
     }
     if ($form_state->getValue('name') == 'element_validate_access') {
         $form_state->set('form_test_name', $form_state->getValue('name'));
         // Alter the form element.
         $element['#access'] = FALSE;
         $triggered = TRUE;
     } elseif ($form_state->has('form_test_name')) {
         // To simplify this test, just take over the element's value into $form_state.
         form_set_value($element, $form_state->get('form_test_name'), $form_state);
         $triggered = TRUE;
     }
     if ($triggered) {
         // Output the element's value from $form_state.
         drupal_set_message(t('@label value: @value', array('@label' => $element['#title'], '@value' => $form_state->getValue('name'))));
         // Trigger a form validation error to see our changes.
         $form_state->setErrorByName('');
     }
 }
Exemple #3
0
 /**
  * Form element validation handler for 'name' in form_test_validate_form().
  */
 public function validateName(&$element, &$form_state)
 {
     $triggered = FALSE;
     if ($form_state['values']['name'] == 'element_validate') {
         // Alter the form element.
         $element['#value'] = '#value changed by #element_validate';
         // Alter the submitted value in $form_state.
         form_set_value($element, 'value changed by form_set_value() in #element_validate', $form_state);
         $triggered = TRUE;
     }
     if ($form_state['values']['name'] == 'element_validate_access') {
         $form_state['storage']['form_test_name'] = $form_state['values']['name'];
         // Alter the form element.
         $element['#access'] = FALSE;
         $triggered = TRUE;
     } elseif (!empty($form_state['storage']['form_test_name'])) {
         // To simplify this test, just take over the element's value into $form_state.
         form_set_value($element, $form_state['storage']['form_test_name'], $form_state);
         $triggered = TRUE;
     }
     if ($triggered) {
         // Output the element's value from $form_state.
         drupal_set_message(t('@label value: @value', array('@label' => $element['#title'], '@value' => $form_state['values']['name'])));
         // Trigger a form validation error to see our changes.
         form_set_error('', $form_state);
     }
 }
/**
 * Form submit for da_vinci_form_system_theme_settings_alter().
 */
function da_vinci_form_system_theme_settings_submit($form, &$form_state)
{
    $exclude_css = array_filter(array_map('trim', explode("\n", $form_state['values']['css_exclude'])));
    $exclude_js = array_filter(array_map('trim', explode("\n", $form_state['values']['js_exclude'])));
    form_set_value(array('#parents' => array('css_exclude')), $exclude_css, $form_state);
    form_set_value(array('#parents' => array('js_exclude')), $exclude_js, $form_state);
}
/**
 * Element validate; Set the value of the providers.
 */
function entityreference_prepopulate_providers_validate($element, &$form_state)
{
    $value = $form_state['values']['instance']['settings']['behaviors']['prepopulate']['providers']['enabled'];
    // Sort the value by the weight.
    uasort($value, 'drupal_sort_weight');
    form_set_value($element, $value, $form_state);
}
 /**
  * Element validation helper.
  */
 public static function multipleValidate($element, FormStateInterface $form_state)
 {
     $values = array_map('trim', explode(',', $element['#value']));
     $items = array();
     foreach ($values as $value) {
         $items[] = array('value' => $value);
     }
     form_set_value($element, $items, $form_state);
 }
Exemple #7
0
function drupalexp_form_system_theme_settings_validate(&$form, &$form_state)
{
    $drupalexp_layouts = '';
    $i = 0;
    while (isset($form_state['input']['dexp_layout_' . $i])) {
        $drupalexp_layouts .= $form_state['input']['dexp_layout_' . $i];
        $i++;
    }
    form_set_value($form['layout_settings']['drupalexp_layouts'], $drupalexp_layouts, $form_state);
}
 /**
  * @todo
  */
 function edit_form_validate(&$form, &$form_state)
 {
     parent::edit_form_validate($form, $form_state);
     $values = $form_state['values'];
     if ($values['parent'] == '_none') {
         form_set_value(array('#parents' => array('parent')), '', $form_state);
     } else {
         form_set_value(array('#parents' => array('mode')), DELTA_PRESERVE, $form_state);
     }
 }
 /**
  * {@inheritdoc}
  */
 public function validateForm(array &$form, array &$form_state)
 {
     if ($form_state['values']['name'] == 'validate') {
         // Alter the form element.
         $form['name']['#value'] = '#value changed by #validate';
         // Alter the submitted value in $form_state.
         form_set_value($form['name'], 'value changed by form_set_value() in #validate', $form_state);
         // Output the element's value from $form_state.
         drupal_set_message(t('@label value: @value', array('@label' => $form['name']['#title'], '@value' => $form_state['values']['name'])));
         // Trigger a form validation error to see our changes.
         form_set_error('', $form_state);
     }
 }
Exemple #10
0
/**
 * Form element validation handler for validating the primary region setting for zones.
 */
function alpha_theme_settings_validate_primary(&$element, &$form_state)
{
    if ($element['#value'] != '_none') {
        $values = $form_state['values'];
        if ($values['alpha_region_' . $element['#value'] . '_zone'] != $element['#zone']) {
            form_set_value($element, NULL, $form_state);
        } else {
            $sum = 0;
            foreach ($form_state['regions'] as $region => $item) {
                if ($values['alpha_region_' . $region . '_zone'] == $element['#zone']) {
                    $sum += $values['alpha_region_' . $region . '_columns'];
                    $sum += $values['alpha_region_' . $region . '_prefix'];
                    $sum += $values['alpha_region_' . $region . '_suffix'];
                }
            }
            if ($sum > $values['alpha_zone_' . $element['#zone'] . '_columns']) {
                form_error($element, t('You have specified the %region region as the primary region for the %zone zone but the summed region width is greater than the number of available columns for that zone.', array('%region' => $form_state['regions'][$element['#value']]['name'], '%zone' => $form_state['zones'][$element['#zone']]['name'])));
            }
        }
    }
}
 /**
  * {@inheritdoc}
  */
 public function elementValidate($element, &$form_state, $form)
 {
     $value = array();
     // If a value was entered into the autocomplete.
     $handler = \Drupal::service('plugin.manager.entity_reference.selection')->getSelectionHandler($this->fieldDefinition);
     $bundles = entity_get_bundles($this->getFieldSetting('target_type'));
     $auto_create = $this->getSelectionHandlerSetting('auto_create');
     if (!empty($element['#value'])) {
         $value = array();
         foreach (Tags::explode($element['#value']) as $input) {
             $match = FALSE;
             // Take "label (entity id)', match the ID from parenthesis when it's a
             // number.
             if (preg_match("/.+\\((\\d+)\\)/", $input, $matches)) {
                 $match = $matches[1];
             } elseif (preg_match("/.+\\(([\\w.]+)\\)/", $input, $matches)) {
                 $match = $matches[1];
             } else {
                 // Try to get a match from the input string when the user didn't use
                 // the autocomplete but filled in a value manually.
                 $match = $handler->validateAutocompleteInput($input, $element, $form_state, $form, !$auto_create);
             }
             if ($match) {
                 $value[] = array('target_id' => $match);
             } elseif ($auto_create && (count($this->getSelectionHandlerSetting('target_bundles')) == 1 || count($bundles) == 1)) {
                 // Auto-create item. See
                 // \Drupal\Core\Field\Plugin\Field\FieldType\EntityReferenceItem::presave().
                 $value[] = array('target_id' => NULL, 'entity' => $this->createNewEntity($input, $element['#autocreate_uid']));
             }
         }
     }
     // Change the element['#parents'], so in form_set_value() we
     // populate the correct key.
     array_pop($element['#parents']);
     form_set_value($element, $value, $form_state);
 }
 /**
  * Form validation handler for widget elements.
  *
  * @param array $element
  *   The form element.
  * @param array $form_state
  *   The form state.
  */
 public static function validateElement(array $element, array &$form_state)
 {
     if ($element['#required'] && $element['#value'] == '_none') {
         \Drupal::formBuilder()->setError($element, $form_state, 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_set_value($element, $items, $form_state);
 }
Exemple #13
0
function devis_user_profile_form_validate($form, &$form_state)
{
    // This is a check in case the javascript is disabled for whatever reason.
    if (isset($form['profile_budget_profile']['field_active_regions_belgium'])) {
        $belgium = FALSE;
        $count = 0;
        // Check if Belgium is selected among the choices.
        $lang = $form['profile_budget_profile']['field_active_regions_belgium']['#language'];
        foreach ($form_state['values']['profile_budget_profile']['field_active_regions_belgium'][$lang] as $k => $val) {
            $count++;
            if ($val['value'] == 'BEL') {
                $belgium = TRUE;
            }
        }
        // If Belgium is selected, then asign only Belgium as the value.
        if ($belgium && $count > 1) {
            $new_value = array($lang => array(0 => array('value' => 'BEL')));
            $value['#parents'] = array('profile_budget_profile', 'field_active_regions_belgium');
            form_set_value($value, $new_value, $form_state);
        }
    }
    if (isset($form_state['values']['mail'])) {
        // E-mail check for duplicate user.
        $user_check = user_load_by_mail($form_state['values']['mail']);
        if ($user_check && $form['#user']->uid != $user_check->uid) {
            $site_name = variable_get('site_name', '3devis.be');
            form_set_error('mail', t('The specified email is already registered in !site_name.', array('!site_name' => $site_name)));
        }
        // E-mail check.
        if (!valid_email_address($form_state['values']['mail'])) {
            form_set_error('mail', t('The specified email is not a valid email.'));
        }
    }
    devis_field_phone_belgium_validate($form, $form_state);
    devis_field_tva_validate($form, $form_state);
}
 /**
  * {@inheritdoc}
  */
 public function validate(array $form, FormStateInterface $form_state)
 {
     parent::validate($form, $form_state);
     form_set_value($form['id'], $this->targetEntityTypeId . '.' . $form_state['values']['id'], $form_state);
 }
Exemple #15
0
function _agency_1_theme_settings_map($form, &$form_state)
{
    $validators = array('file_validate_is_image' => array());
    $file = file_save_upload('background_file', $validators);
    $map_file = file_save_upload('footer_contact_us_map_image', $validators);
    //Map image
    if (isset($map_file)) {
        // File upload was attempted.
        if ($map_file) {
            // Move the file, into the Drupal file system
            if ($map_filename = file_unmanaged_copy($map_file->uri, 'public://background_images', FILE_EXISTS_RENAME)) {
                //resize, if necessary
                $map_resized = image_load($map_file->uri);
                list($map_width, $map_height) = getimagesize($map_file->uri);
                if ($map_width > 150 || $map_height > 150) {
                    if ($map_width / $map_height >= 1) {
                        image_scale($map_resized, 150);
                    } else {
                        image_scale($map_resized, null, 150);
                    }
                    image_save($map_resized, $map_filename, FILE_EXISTS_RENAME);
                    $map_resized->status = FILE_STATUS_PERMANENT;
                    drupal_set_message('Uploaded image was greater than 150px.  Image has been resized.');
                }
                //end resize
                unset($form['footer_contact_us']['settings']['footer_contact_us_map_path']);
                $form['footer_contact_us']['settings']['footer_contact_us_map_path']['#value'] = $map_filename;
                $form['footer_contact_us_map_path']['#parents'] = array('footer_contact_us_map_path');
                form_set_value($form['footer_contact_us_map_path'], file_create_url($map_filename), $form_state);
                watchdog('Theme Settings', 'New Footer Map Image uploaded: ' . file_create_url($map_filename));
                drupal_set_message('Map Image uploaded.  URL: ' . file_create_url($map_filename));
            } else {
                form_set_error('file', t('Failed to write the uploaded file the site\'s file folder.'));
            }
        } else {
            // File upload failed.
            form_set_error('background_file', t('The image could not be uploaded.'));
        }
    }
}
Exemple #16
0
 /**
  * Fill value in any field of the form. It first checks if corresponding key
  * exists in the form array. If yes, it finds out its #tree value and that of
  * its parents and sets form_state appropriately. If it doesn't find the key
  * in the form array, then it sets the values in form_state at the top level.
  *
  * @param string|array $field_name
  *   Field name if it is present at top-level form element. If it is not at
  *   the top-level form element, then provide an array.
  * @param string|int|array $values
  *   Value that needs to be filled.
  *
  * @return Response
  *   Response object.
  */
 public function fillValues($field_name, $values)
 {
     if (is_string($field_name)) {
         $field_name = array($field_name);
     }
     $response = $this->getTreeKeys($field_name);
     if (!$response->getSuccess()) {
         $element['#parents'] = $field_name;
     } else {
         $element['#parents'] = $response->getVar();
     }
     form_set_value($element, $values, $this->form_state);
     return new Response(TRUE, $values, "");
 }
 /**
  * {@inheritdoc}
  */
 public function validateForm(array &$form, FormStateInterface $form_state)
 {
     // Check for empty front page path.
     if ($form_state->isValueEmpty('site_frontpage')) {
         // Set to default "user".
         form_set_value($form['front_page']['site_frontpage'], 'user', $form_state);
     } else {
         // Get the normal path of the front page.
         form_set_value($form['front_page']['site_frontpage'], $this->aliasManager->getPathByAlias($form_state->getValue('site_frontpage')), $form_state);
     }
     // Validate front page path.
     if (!$this->pathValidator->isValid($form_state->getValue('site_frontpage'))) {
         $form_state->setErrorByName('site_frontpage', $this->t("The path '%path' is either invalid or you do not have access to it.", array('%path' => $form_state->getValue('site_frontpage'))));
     }
     // Get the normal paths of both error pages.
     if (!$form_state->isValueEmpty('site_403')) {
         form_set_value($form['error_page']['site_403'], $this->aliasManager->getPathByAlias($form_state->getValue('site_403')), $form_state);
     }
     if (!$form_state->isValueEmpty('site_404')) {
         form_set_value($form['error_page']['site_404'], $this->aliasManager->getPathByAlias($form_state->getValue('site_404')), $form_state);
     }
     // Validate 403 error path.
     if (!$form_state->isValueEmpty('site_403') && !$this->pathValidator->isValid($form_state->getValue('site_403'))) {
         $form_state->setErrorByName('site_403', $this->t("The path '%path' is either invalid or you do not have access to it.", array('%path' => $form_state->getValue('site_403'))));
     }
     // Validate 404 error path.
     if (!$form_state->isValueEmpty('site_404') && !$this->pathValidator->isValid($form_state->getValue('site_404'))) {
         $form_state->setErrorByName('site_404', $this->t("The path '%path' is either invalid or you do not have access to it.", array('%path' => $form_state->getValue('site_404'))));
     }
     parent::validateForm($form, $form_state);
 }
 function edit_form_validate(&$form, &$form_state)
 {
     $export_key = $this->plugin['export']['key'];
     // When adding a machine name, the entity/bundle are left off so the user
     // does not have to deal with it. We put it back here behind the scenes.
     $name = $form_state['values'][$export_key];
     form_set_value($form['info'][$export_key], implode(':', array($this->entity_handler->entity_type, $this->entity_bundle, $name)), $form_state);
 }
Exemple #19
0
/**
 * Helper function for install_settings_validate.
 */
function _install_settings_form_validate($database, $settings_file, &$form_state, $form = NULL)
{
    global $databases;
    // Verify the table prefix
    if (!empty($database['prefix']) && is_string($database['prefix']) && !preg_match('/^[A-Za-z0-9_.]+$/', $database['dprefix'])) {
        form_set_error('db_prefix', st('The database table prefix you have entered, %db_prefix, is invalid. The table prefix can only contain alphanumeric characters, periods, or underscores.', array('%db_prefix' => $db_prefix)), 'error');
    }
    if (!empty($database['port']) && !is_numeric($database['port'])) {
        form_set_error('db_port', st('Database port must be a number.'));
    }
    // Check database type
    $database_types = drupal_detect_database_types();
    $driver = $database['driver'];
    if (!isset($database_types[$driver])) {
        form_set_error('driver', st("In your %settings_file file you have configured @drupal to use a %driver server, however your PHP installation currently does not support this database type.", array('%settings_file' => $settings_file, '@drupal' => drupal_install_profile_name(), '%driver' => $database['driver'])));
    } else {
        if (isset($form)) {
            form_set_value($form['_database'], $database, $form_state);
        }
        $class = "DatabaseInstaller_{$driver}";
        $test = new $class();
        $databases = array('default' => array('default' => $database));
        $return = $test->test();
        if (!$return || $test->error) {
            if (!empty($test->success)) {
                form_set_error('db_type', st('In order for Drupal to work, and to continue with the installation process, you must resolve all permission issues reported above. We were able to verify that we have permission for the following commands: %commands. For more help with configuring your database server, see the <a href="http://drupal.org/node/258">Installation and upgrading handbook</a>. If you are unsure what any of this means you should probably contact your hosting provider.', array('%commands' => implode($test->success, ', '))));
            } else {
                form_set_error('driver', '');
            }
        }
    }
}
Exemple #20
0
/**
 * Form API validate for install_settings form.
 */
function install_settings_form_validate($form, &$form_state)
{
    form_set_value($form['_database'], $form_state['values'], $form_state);
    $errors = install_database_errors($form_state['values'], $form_state['values']['settings_file']);
    foreach ($errors as $name => $message) {
        form_set_error($name, $message);
    }
}
 /**
  * Validates the 'add new field' row.
  *
  * @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.
  *
  * @see \Drupal\field_ui\FieldOverview::validateForm()
  */
 protected function validateAddNew(array $form, FormStateInterface $form_state)
 {
     $field = $form_state['values']['fields']['_add_new_field'];
     // Validate if any information was provided in the 'add new field' row.
     if (array_filter(array($field['label'], $field['field_name'], $field['type']))) {
         // Missing label.
         if (!$field['label']) {
             $form_state->setErrorByName('fields][_add_new_field][label', $this->t('Add new field: you need to provide a label.'));
         }
         // Missing field name.
         if (!$field['field_name']) {
             $form_state->setErrorByName('fields][_add_new_field][field_name', $this->t('Add new field: you need to provide a field name.'));
         } else {
             $field_name = $field['field_name'];
             // Add the field prefix.
             $field_name = \Drupal::config('field_ui.settings')->get('field_prefix') . $field_name;
             form_set_value($form['fields']['_add_new_field']['field_name'], $field_name, $form_state);
         }
         // Missing field type.
         if (!$field['type']) {
             $form_state->setErrorByName('fields][_add_new_field][type', $this->t('Add new field: you need to select a field type.'));
         }
     }
 }
/**
 * Calculates the gradient in the top and bottom of all "blocks".
 */
function abessive_calculate_gradient($form, &$form_state)
{
    if (count(form_set_error()) > 0) {
        return;
    }
    $b = _abessive_color_rgb2hsl(_abessive_color_unpack($form_state['values']['abessive_content_background_color'], TRUE));
    // If the background lightness is too dark then we cannot make the gradient tend towards darker - so we make it tend towards lighter instead
    if ($b[2] < 0.5) {
        form_set_value($form['abessive_r5'], _abessive_color_pack(_abessive_color_hsl2rgb(array($b[0], $b[1], $b[2] + 8 / 255)), TRUE), $form_state);
        form_set_value($form['abessive_r4'], _abessive_color_pack(_abessive_color_hsl2rgb(array($b[0], $b[1], $b[2] + 16 / 255)), TRUE), $form_state);
        form_set_value($form['abessive_r3'], _abessive_color_pack(_abessive_color_hsl2rgb(array($b[0], $b[1], $b[2] + 24 / 255)), TRUE), $form_state);
        form_set_value($form['abessive_r2'], _abessive_color_pack(_abessive_color_hsl2rgb(array($b[0], $b[1], $b[2] + 32 / 255)), TRUE), $form_state);
    } else {
        form_set_value($form['abessive_r5'], _abessive_color_pack(_abessive_color_hsl2rgb(array($b[0], $b[1], $b[2] - 8 / 255)), TRUE), $form_state);
        form_set_value($form['abessive_r4'], _abessive_color_pack(_abessive_color_hsl2rgb(array($b[0], $b[1], $b[2] - 16 / 255)), TRUE), $form_state);
        form_set_value($form['abessive_r3'], _abessive_color_pack(_abessive_color_hsl2rgb(array($b[0], $b[1], $b[2] - 24 / 255)), TRUE), $form_state);
        form_set_value($form['abessive_r2'], _abessive_color_pack(_abessive_color_hsl2rgb(array($b[0], $b[1], $b[2] - 32 / 255)), TRUE), $form_state);
    }
}
function entityreference_view_settings_validate($element, &$form_state, $form)
{
    // Split view name and display name from the 'view_and_display' value.
    if (!empty($element['view_and_display']['#value'])) {
        list($view, $display) = explode(':', $element['view_and_display']['#value']);
    } else {
        form_error($element, t('The views entity selection mode requires a view.'));
        return;
    }
    // Explode the 'args' string into an actual array. Beware, explode() turns an
    // empty string into an array with one empty string. We'll need an empty array
    // instead.
    $args_string = trim($element['args']['#value']);
    if ($args_string === '') {
        $args = array();
    } else {
        // array_map is called to trim whitespaces from the arguments.
        $args = array_map('trim', explode(',', $args_string));
    }
    $value = array('view_name' => $view, 'display_name' => $display, 'args' => $args);
    form_set_value($element, $value, $form_state);
}
Exemple #24
0
 /**
  * Special submit handling.
  */
 public function submitOptionsForm(&$form, FormStateInterface $form_state)
 {
     $element = array('#parents' => array('query', 'options', 'query_tags'));
     $value = explode(',', NestedArray::getValue($form_state['values'], $element['#parents']));
     $value = array_filter(array_map('trim', $value));
     form_set_value($element, $value, $form_state);
 }
Exemple #25
0
 /**
  * Form API callback.
  *
  * This function is assigned as an #element_validate callback in
  * instanceSettingsForm().
  *
  * This doubles as a convenience clean-up function and a validation routine.
  * Commas are allowed by the end-user, but ultimately the value will be stored
  * as a space-separated list for compatibility with file_validate_extensions().
  */
 public static function validateExtensions($element, FormStateInterface $form_state)
 {
     if (!empty($element['#value'])) {
         $extensions = preg_replace('/([, ]+\\.?)/', ' ', trim(strtolower($element['#value'])));
         $extensions = array_filter(explode(' ', $extensions));
         $extensions = implode(' ', array_unique($extensions));
         if (!preg_match('/^([a-z0-9]+([.][a-z0-9])* ?)+$/', $extensions)) {
             form_error($element, $form_state, t('The list of allowed extensions is not valid, be sure to exclude leading dots and to separate extensions with a comma or space.'));
         } else {
             form_set_value($element, $extensions, $form_state);
         }
     }
 }
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']));
}
 function edit_form_validate(&$form, &$form_state)
 {
     // Build the actual name of the object for ctools
     $export_key = $this->plugin['export']['key'];
     $name = panelizer_defaults_ui_build_export_name($form_state['values'][$export_key], $this);
     form_set_value($form['info'][$export_key], $name, $form_state);
 }
/** function guifi_mac_validate($mac,&$form_state)
 * 
 * */
function guifi_mac_validate($mac, &$form_state)
{
    if ($form_state['clicked_button']['#value'] == t('Reset')) {
        return;
    }
    $m2 = $mac;
    unset($m2['#post']);
    guifi_log(GUIFILOG_TRACE, 'guifi_mac_validate', $m2['#parents']);
    guifi_log(GUIFILOG_TRACE, 'guifi_mac_validate', $form_state);
    // if empty,
    if (empty($mac['#value'])) {
        $pmac = null;
        // ...and have parents, take parent mac
        if (in_array($mac['#parents'][0], array('vlans', 'aggregations'))) {
            $macs = guifi_get_currentDeviceMacs($mac['#post']);
            $related = $mac['#post'][$mac['#parents'][0]][$mac['#parents'][1]]['related_interfaces'];
            guifi_log(GUIFILOG_TRACE, 'guifi_mac_validate MACS', $macs);
            guifi_log(GUIFILOG_TRACE, 'guifi_mac_validate RELATED', $related);
            if (is_array($related)) {
                $pmac = $macs[$related[0]];
            } else {
                $pmac = $macs[$related];
            }
        }
        // ... or ineterface mac, calculate from base device mac
        if ($mac['#parents'][0] == 'interfaces') {
            $iId = $mac['#post']['interfaces'][$mac['#parents'][1]];
            guifi_log(GUIFILOG_TRACE, 'guifi_mac_validate interface MAC', $iId);
            $pmac = _guifi_mac_sum($mac['#post']['mac'], $iId['etherdev_counter']);
        }
        // if mac set, set value in form
        if (!is_null($pmac)) {
            $mac['#value'] = $pmac;
            form_set_value(array('#parents' => $mac['#parents']), $pmac, $form_state);
            $form_state['rebuild'] = TRUE;
            guifi_log(GUIFILOG_TRACE, 'guifi_mac_validate (null NEW MAC)', $pmac);
        }
        //  if still empty, nothing to validate
        return;
    }
    $pmac = _guifi_validate_mac($mac['#value']);
    if ($pmac == FALSE) {
        form_error($mac, t('Error in MAC address (%mac), use 99:99:99:99:99:99 format.', array('%mac' => $mac['#value'])), 'error');
    } else {
        if ($pmac != $mac['#value']) {
            form_set_value(array('#parents' => $mac['#parents']), $pmac, $form_state);
            $form_state['rebuild'] = TRUE;
        }
    }
    return $mac;
}
Exemple #29
0
/**
 * Helper function for install_settings_validate.
 */
function _install_settings_form_validate($db_prefix, $db_type, $db_user, $db_pass, $db_host, $db_port, $db_path, $settings_file, &$form_state, $form = NULL)
{
    global $db_url;
    // Verify the table prefix
    if (!empty($db_prefix) && is_string($db_prefix) && !preg_match('/^[A-Za-z0-9_.]+$/', $db_prefix)) {
        form_set_error('db_prefix', st('The database table prefix you have entered, %db_prefix, is invalid. The table prefix can only contain alphanumeric characters, periods, or underscores.', array('%db_prefix' => $db_prefix)), 'error');
    }
    if (!empty($db_port) && !is_numeric($db_port)) {
        form_set_error('db_port', st('Database port must be a number.'));
    }
    // Check database type
    if (!isset($form)) {
        $_db_url = is_array($db_url) ? $db_url['default'] : $db_url;
        $db_type = substr($_db_url, 0, strpos($_db_url, '://'));
    }
    $databases = drupal_detect_database_types();
    if (!in_array($db_type, $databases)) {
        form_set_error('db_type', st("In your %settings_file file you have configured @drupal to use a %db_type server, however your PHP installation currently does not support this database type.", array('%settings_file' => $settings_file, '@drupal' => drupal_install_profile_name(), '%db_type' => $db_type)));
    } else {
        // Verify
        $db_url = $db_type . '://' . urlencode($db_user) . ($db_pass ? ':' . urlencode($db_pass) : '') . '@' . ($db_host ? urlencode($db_host) : 'localhost') . ($db_port ? ":{$db_port}" : '') . '/' . urlencode($db_path);
        if (isset($form)) {
            form_set_value($form['_db_url'], $db_url, $form_state);
        }
        $success = array();
        $function = 'drupal_test_' . $db_type;
        if (!$function($db_url, $success)) {
            if (isset($success['CONNECT'])) {
                form_set_error('db_type', st('In order for Drupal to work, and to continue with the installation process, you must resolve all permission issues reported above. We were able to verify that we have permission for the following commands: %commands. For more help with configuring your database server, see the <a href="http://drupal.org/node/258">Installation and upgrading handbook</a>. If you are unsure what any of this means you should probably contact your hosting provider.', array('%commands' => implode($success, ', '))));
            } else {
                form_set_error('db_type', '');
            }
        }
    }
}
/**
 * @todo
 */
function omega_theme_settings_validate_equal_height($element, &$form_state)
{
    $value = isset($element['#zone']) ? $form_state['values']['alpha_zone_' . $element['#zone'] . '_equal_height_container'] : FALSE;
    form_set_value($element, $value, $form_state);
}