Ejemplo n.º 1
0
 /**
  * {@inheritdoc}
  */
 public static function generateSampleValue(FieldDefinitionInterface $field_definition)
 {
     $settings = $field_definition->getSettings();
     $precision = rand(10, 32);
     $scale = rand(0, 2);
     $max = is_numeric($settings['max']) ?: pow(10, $precision - $scale) - 1;
     $min = is_numeric($settings['min']) ?: -pow(10, $precision - $scale) + 1;
     // @see "Example #1 Calculate a random floating-point number" in
     // http://php.net/manual/function.mt-getrandmax.php
     $random_decimal = $min + mt_rand() / mt_getrandmax() * ($max - $min);
     $values['value'] = self::truncateDecimal($random_decimal, $scale);
     return $values;
 }
Ejemplo n.º 2
0
 /**
  * {@inheritdoc}
  */
 public static function generateSampleValue(FieldDefinitionInterface $field_definition)
 {
     $random = new Random();
     $settings = $field_definition->getSettings();
     if (empty($settings['max_length'])) {
         // Textarea handling
         $value = $random->paragraphs();
     } else {
         // Textfield handling.
         $value = substr($random->sentences(mt_rand(1, $settings['max_length'] / 3), FALSE), 0, $settings['max_length']);
     }
     $values = array('value' => $value, 'summary' => $value, 'format' => filter_fallback_format());
     return $values;
 }
Ejemplo n.º 3
0
 /**
  * {@inheritdoc}
  */
 public static function generateSampleValue(FieldDefinitionInterface $field_definition)
 {
     $settings = $field_definition->getSettings();
     $precision = $settings['precision'] ?: 10;
     $scale = $settings['scale'] ?: 2;
     // $precision - $scale is the number of digits on the left of the decimal
     // point.
     // The maximum number you can get with 3 digits is 10^3 - 1 --> 999.
     // The minimum number you can get with 3 digits is -1 * (10^3 - 1).
     $max = is_numeric($settings['max']) ?: pow(10, $precision - $scale) - 1;
     $min = is_numeric($settings['min']) ?: -pow(10, $precision - $scale) + 1;
     // Get the number of decimal digits for the $max
     $decimal_digits = self::getDecimalDigits($max);
     // Do the same for the min and keep the higher number of decimal digits.
     $decimal_digits = max(self::getDecimalDigits($min), $decimal_digits);
     // If $min = 1.234 and $max = 1.33 then $decimal_digits = 3
     $scale = rand($decimal_digits, $scale);
     // @see "Example #1 Calculate a random floating-point number" in
     // http://php.net/manual/en/function.mt-getrandmax.php
     $random_decimal = $min + mt_rand() / mt_getrandmax() * ($max - $min);
     $values['value'] = self::truncateDecimal($random_decimal, $scale);
     return $values;
 }
Ejemplo n.º 4
0
 /**
  * {@inheritdoc}
  */
 public static function generateSampleValue(FieldDefinitionInterface $field_definition)
 {
     $random = new Random();
     $settings = $field_definition->getSettings();
     static $images = array();
     $min_resolution = empty($settings['min_resolution']) ? '100x100' : $settings['min_resolution'];
     $max_resolution = empty($settings['max_resolution']) ? '600x600' : $settings['max_resolution'];
     $extensions = array_intersect(explode(' ', $settings['file_extensions']), array('png', 'gif', 'jpg', 'jpeg'));
     $extension = array_rand(array_combine($extensions, $extensions));
     // Generate a max of 5 different images.
     if (!isset($images[$extension][$min_resolution][$max_resolution]) || count($images[$extension][$min_resolution][$max_resolution]) <= 5) {
         $tmp_file = drupal_tempnam('temporary://', 'generateImage_');
         $destination = $tmp_file . '.' . $extension;
         file_unmanaged_move($tmp_file, $destination, FILE_CREATE_DIRECTORY);
         if ($path = $random->image(drupal_realpath($destination), $min_resolution, $max_resolution)) {
             $image = File::create();
             $image->setFileUri($path);
             $image->setOwnerId(\Drupal::currentUser()->id());
             $image->setMimeType(\Drupal::service('file.mime_type.guesser')->guess($path));
             $image->setFileName(drupal_basename($path));
             $destination_dir = static::doGetUploadLocation($settings);
             file_prepare_directory($destination_dir, FILE_CREATE_DIRECTORY);
             $destination = $destination_dir . '/' . basename($path);
             $file = file_move($image, $destination, FILE_CREATE_DIRECTORY);
             $images[$extension][$min_resolution][$max_resolution][$file->id()] = $file;
         } else {
             return array();
         }
     } else {
         // Select one of the images we've already generated for this field.
         $image_index = array_rand($images[$extension][$min_resolution][$max_resolution]);
         $file = $images[$extension][$min_resolution][$max_resolution][$image_index];
     }
     list($width, $height) = getimagesize($file->getFileUri());
     $values = array('target_id' => $file->id(), 'alt' => $random->sentences(4), 'title' => $random->sentences(4), 'width' => $width, 'height' => $height);
     return $values;
 }
 /**
  * {@inheritdoc}
  */
 public static function generateSampleValue(FieldDefinitionInterface $field_definition)
 {
     $random = new Random();
     $settings = $field_definition->getSettings();
     // Prepare destination.
     $dirname = static::doGetUploadLocation($settings);
     file_prepare_directory($dirname, FILE_CREATE_DIRECTORY);
     // Generate a file entity.
     $destination = $dirname . '/' . $random->name(10, TRUE) . '.txt';
     $data = $random->paragraphs(3);
     $file = file_save_data($data, $destination, FILE_EXISTS_ERROR);
     $values = array('target_id' => $file->id(), 'display' => (int) $settings['display_default'], 'description' => $random->sentences(10));
     return $values;
 }
 /**
  * {@inheritdoc}
  */
 public static function isApplicable(FieldDefinitionInterface $field_definition)
 {
     if (!$field_definition->isRequired()) {
         return FALSE;
     }
     $handler_settings = $field_definition->getSettings()['handler_settings'];
     // Entity types without bundles will throw notices on next condition so let's
     // stop before they do. We should support this kind of entities too. See
     // https://www.drupal.org/node/2569193 and remove this check once that issue
     // lands.
     if (empty($handler_settings['target_bundles'])) {
         return FALSE;
     }
     if (count($handler_settings['target_bundles']) != 1) {
         return FALSE;
     }
     return TRUE;
 }
Ejemplo n.º 7
0
 /**
  * Returns the array of field settings.
  *
  * @return array
  *   The array of settings.
  */
 protected function getFieldSettings()
 {
     return $this->fieldDefinition->getSettings();
 }
Ejemplo n.º 8
0
 /**
  * {@inheritdoc}
  */
 public function buildForm(array $form, FormStateInterface $form_state, FieldDefinitionInterface $field_config = NULL, $delta = 0)
 {
     $input = $form_state->getUserInput();
     // Store field information in $form_state.
     if (!static::getModalState($form_state)) {
         $field_state = array('page' => 1);
         static::setModalState($form_state, $field_state);
     }
     // Store for ajax commands.
     $form['delta'] = ['#type' => 'value', '#value' => $delta];
     // Get the field settings for filtering and validating files.
     if ($field_config) {
         $form['field_name'] = ['#type' => 'value', '#value' => $field_config->getName()];
         $field_settings = $field_config->getSettings();
         $extensions = $field_settings['file_extensions'];
         $catalog_id = $field_settings['catalog_id'];
     } else {
         // If we are coming from the ckeditor image dialog, we don't have field
         // config, look for extensions in the query string instead.
         // TODO: Think of a better way to do this.
         $query = \Drupal::request()->query->all();
         $extensions = $query['extensions'];
         $catalog_id = $query['catalog_id'];
     }
     $operation_options = ['startswith' => $this->t('Starts with'), 'matches' => $this->t('Matches')];
     $form['filters'] = ['#type' => 'container', '#attributes' => ['class' => ['search-form']], 'title' => ['#markup' => '<span class="search-title">' . $this->t('Search by filename') . '</span>']];
     $form['filters']['filename_op'] = array('#type' => 'select', '#title' => $this->t('Operation'), '#options' => $operation_options, '#default_value' => !empty($input['filename_op']) ? $input['filename_op'] : '');
     $form['filters']['filename'] = array('#type' => 'textfield', '#title' => $this->t('Search by filename'), '#size' => 20, '#default_value' => !empty($input['filename']) ? $input['filename'] : '');
     $ajax_settings = ['callback' => [$this, 'searchAjax'], 'wrapper' => self::AJAX_WRAPPER_ID, 'effect' => 'fade', 'progress' => ['type' => 'throbber']];
     $form['filters']['search'] = ['#type' => 'submit', '#submit' => [[$this, 'searchSubmit']], '#ajax' => $ajax_settings, '#value' => $this->t('Search'), '#attributes' => array('class' => array('embridge-ajax-search-submit'))];
     $filters = [];
     $filters[] = ['field' => 'fileformat', 'operator' => 'matches', 'value' => $this->massageExtensionSetting($extensions)];
     // Static list of known search filters from EMDB.
     // TODO: Make this configurable.
     $known_search_filters = ['libraries', 'assettype', 'fileformat'];
     // Add filename filter as this always exists.
     if (!empty($input['filename_op'])) {
         $filters[] = ['field' => 'name', 'operator' => $input['filename_op'], 'value' => $input['filename']];
     }
     // Add user chosen filters.
     foreach ($known_search_filters as $filter_id) {
         if (empty($input[$filter_id])) {
             continue;
         }
         $filters[] = ['field' => $filter_id, 'operator' => 'matches', 'value' => $input[$filter_id]];
     }
     // Execute a search.
     $modal_state = static::getModalState($form_state);
     $page = $modal_state['page'];
     $search_response = $this->getSearchResults($page, $filters);
     $title = $this->t('More search options');
     $form['filters']['extra_filters'] = ['#markup' => '<div class="moreOptions"><a href="#options" data-toggle="collapse">' . $title . '</a><div id="options" class="collapse">'];
     // Add filters from search response.
     if (!empty($search_response['filteroptions'])) {
         foreach ($search_response['filteroptions'] as $filter) {
             if (!in_array($filter['id'], $known_search_filters)) {
                 continue;
             }
             // "Empty" option.
             $filter_options = [$this->t('-- Select --')];
             // Add each option to the list.
             foreach ($filter['children'] as $option) {
                 $filter_options[$option['id']] = $this->t('@name (@count)', ['@name' => $option['name'], '@count' => $option['count']]);
             }
             $form['filters']['extra_filters'][$filter['id']] = ['#type' => 'select', '#title' => $this->t('@name', ['@name' => $filter['name']]), '#options' => $filter_options, '#default_value' => !empty($input[$filter['id']]) ? $input[$filter['id']] : ''];
         }
     }
     $form['filters']['close_extra_filters'] = ['#markup' => '</div></div>'];
     if (!empty($search_response['results'])) {
         $form['search_results'] = ['#theme' => 'embridge_search_results', '#results' => $this->formatSearchResults($search_response, $this->assetHelper, $catalog_id)];
     } else {
         $form['search_results'] = ['#type' => 'markup', '#markup' => $this->t('<p>No files found, please adjust your filters and try again.</p>')];
     }
     // Add "previous page" pager.
     $form['pagination'] = ['#type' => 'container', '#attributes' => ['class' => ['pagination']]];
     $form['pagination']['page_previous'] = ['#type' => 'submit', '#value' => $this->t('Previous page'), '#submit' => [[$this, 'previousPageSubmit']], '#ajax' => array('callback' => [$this, 'searchAjax'], 'wrapper' => self::AJAX_WRAPPER_ID, 'effect' => 'fade'), '#disabled' => !($page > 1)];
     // Add "next page" pager.
     $form['pagination']['page_next'] = ['#type' => 'submit', '#value' => $this->t('Next page'), '#submit' => [[$this, 'nextPageSubmit']], '#ajax' => array('callback' => [$this, 'searchAjax'], 'wrapper' => self::AJAX_WRAPPER_ID, 'effect' => 'fade'), '#disabled' => !($search_response['response']['pages'] > $search_response['response']['page'])];
     $form['result_chosen'] = ['#type' => 'hidden', '#value' => !empty($input['result_chosen']) ? $input['result_chosen'] : ''];
     $form['actions'] = ['#type' => 'actions'];
     $form['actions']['submit'] = ['#type' => 'submit', '#value' => $this->t('Select'), '#submit' => array(), '#ajax' => array('callback' => [$this, 'selectItemAjax'], 'event' => 'click'), '#attributes' => array('class' => array('embridge-ajax-select-file', 'hidden-button'))];
     $form['#attached']['library'][] = 'embridge/embridge.lib';
     $form['#prefix'] = '<div id="' . self::AJAX_WRAPPER_ID . '"><div id="' . self::MESSAGE_WRAPPER_ID . '"></div>';
     $form['#sufix'] = '</div>';
     return $form;
 }
 /**
  * Returns the form element for caption settings.
  *
  * @param \Drupal\Core\Field\FormatterBase $formatter
  * @param \Drupal\Core\Field\FieldDefinitionInterface $field_definition
  *
  * @return array
  */
 protected function captionSettings(FormatterBase $formatter, FieldDefinitionInterface $field_definition)
 {
     $field_settings = $field_definition->getSettings();
     // Set the caption options.
     $caption_options = array(0 => $formatter->t('None'), 1 => $formatter->t('Image title'), 'alt' => $formatter->t('Image ALT attribute'));
     // Remove the options that are not available.
     $action_fields = array();
     if ($field_settings['title_field'] == FALSE) {
         unset($caption_options[1]);
         // User action required on the image title.
         $action_fields[] = 'title';
     }
     if ($field_settings['alt_field'] == FALSE) {
         unset($caption_options['alt']);
         // User action required on the image alt.
         $action_fields[] = 'alt';
     }
     // Create the caption element.
     $element['caption'] = array('#title' => $formatter->t('Choose a caption source'), '#type' => 'select', '#options' => $caption_options);
     // If the image field doesn't have all of the suitable caption sources, tell the user.
     if ($action_fields) {
         $action_text = $formatter->t('enable the @action_field field', array('@action_field' => join(' and/or ', $action_fields)));
         /* This may be a base field definition (e.g. in Views UI) which means it
          * is not associated with a bundle and will not have the toUrl() method.
          * So we need to check for the existence of the method before we can
          * build a link to the image field edit form.
          */
         if (method_exists($field_definition, 'toUrl')) {
             // Build the link to the image field edit form for this bundle.
             $rel = "{$field_definition->getTargetEntityTypeId()}-field-edit-form";
             $action = $field_definition->toLink($action_text, $rel, array('fragment' => 'edit-settings-alt-field', 'query' => \Drupal::destination()->getAsArray()))->toRenderable();
         } else {
             // Just use plain text if we can't build the field edit link.
             $action = ['#markup' => $action_text];
         }
         $element['caption']['#description'] = $formatter->t('You need to @action for this image field to be able to use it as a caption.', array('@action' => render($action)));
         // If there are no suitable caption sources, disable the caption element.
         if (count($action_fields) >= 2) {
             $element['caption']['#disabled'] = TRUE;
         }
     } else {
         $element['caption']['#default_value'] = $formatter->getSetting('caption');
     }
     return $element;
 }
Ejemplo n.º 10
0
 /**
  * {@inheritdoc}
  */
 public static function generateSampleValue(FieldDefinitionInterface $field_definition)
 {
     $random = new Random();
     $settings = $field_definition->getSettings();
     // Generate a file entity.
     $destination = $settings['uri_scheme'] . '://' . $settings['file_directory'] . $random->name(10, TRUE) . '.txt';
     $data = $random->paragraphs(3);
     $file = file_save_data($data, $destination, FILE_EXISTS_ERROR);
     $values = array('target_id' => $file->id(), 'display' => (int) $settings['display_default'], 'description' => $random->sentences(10));
     return $values;
 }