/**
  * Build an EntityFieldQuery to get referencable entities.
  * Almost the same as EntityReference_SelectionHandler_Generic::buildEntityFieldQuery,
  * but the bundles are dynamic.
  */
 protected function buildEntityFieldQuery($match = NULL, $match_operator = 'CONTAINS')
 {
     $query = new EntityFieldQuery();
     $query->entityCondition('entity_type', $this->field['settings']['target_type']);
     $node_types = project_node_types_by_behavior($this->field['settings']['handler_settings']['behavior']);
     if (!empty($node_types)) {
         $query->entityCondition('bundle', $node_types, 'IN');
     }
     if (isset($match)) {
         $entity_info = entity_get_info($this->field['settings']['target_type']);
         if (isset($entity_info['entity keys']['label'])) {
             $query->propertyCondition($entity_info['entity keys']['label'], $match, $match_operator);
         }
     }
     // Add a generic entity access tag to the query.
     $query->addTag($this->field['settings']['target_type'] . '_access');
     $query->addTag('entityreference');
     $query->addMetaData('field', $this->field);
     $query->addMetaData('entityreference_selection_handler', $this);
     // Add the sort option.
     if (!empty($this->field['settings']['handler_settings']['sort'])) {
         $sort_settings = $this->field['settings']['handler_settings']['sort'];
         if ($sort_settings['type'] == 'property') {
             $query->propertyOrderBy($sort_settings['property'], $sort_settings['direction']);
         } elseif ($sort_settings['type'] == 'field') {
             list($field, $column) = explode(':', $sort_settings['field'], 2);
             $query->fieldOrderBy($field, $column, $sort_settings['direction']);
         }
     }
     return $query;
 }
 protected function _getEntities()
 {
     $options = $this->getOptions();
     $query = new EntityFieldQuery();
     $query->entityCondition('entity_type', $options['entity-type']);
     if (!empty($options['sort-field'])) {
         if (strpos($options['sort-field'], ':') === FALSE) {
             $query->propertyOrderBy($options['sort-field'], strtoupper($options['sort-order']));
         } else {
             $sort_field = explode(':', $options['sort-field']);
             $query->fieldOrderBy($sort_field[0], $sort_field[1], strtoupper($options['sort-order']));
         }
     }
     if (!empty($options['bundle'])) {
         $query->propertyCondition('type', $options['bundle']);
     }
     $query->range(0, $options['limit']);
     $results = $query->execute();
     if (empty($results[$options['entity-type']])) {
         return array();
     }
     return entity_load($options['entity-type'], array_keys($results[$options['entity-type']]));
 }
 /**
  * Build an EntityFieldQuery to get referencable entities.
  */
 public function buildEntityFieldQuery($match = NULL, $match_operator = 'CONTAINS')
 {
     $query = new EntityFieldQuery();
     $query->entityCondition('entity_type', $this->field['settings']['target_type']);
     if (!empty($this->field['settings']['handler_settings']['target_bundles'])) {
         $query->entityCondition('bundle', $this->field['settings']['handler_settings']['target_bundles'], 'IN');
     }
     if (isset($match)) {
         $query->propertyCondition('title', $match, $match_operator);
     }
     // Add an access tag to the query.
     $query->addTag('harmony_access');
     $query->addTag('entityreference');
     $query->addMetaData('field', $this->field);
     $query->addMetaData('entityreference_selection_handler', $this);
     // Adding the 'harmony_thread_access' tag is sadly insufficient for threads: core
     // requires us to also know about the concept of 'published' and
     // 'unpublished'. We need to do that as long as there are no access control
     // modules in use on the site. As long as one access control module is there,
     // it is supposed to handle this check.
     if ((!user_access('bypass harmony forum access control') || !user_access('administer forum content')) && !count(module_implements('harmony_thread_grants'))) {
         $query->propertyCondition('status', HARMONY_PUBLISHED);
         $query->propertyCondition('locked', HARMONY_NOT_LOCKED);
     }
     // Add the sort option.
     if (!empty($this->field['settings']['handler_settings']['sort'])) {
         $sort_settings = $this->field['settings']['handler_settings']['sort'];
         if ($sort_settings['type'] == 'property') {
             $query->propertyOrderBy($sort_settings['property'], $sort_settings['direction']);
         } elseif ($sort_settings['type'] == 'field') {
             list($field, $column) = explode(':', $sort_settings['field'], 2);
             $query->fieldOrderBy($field, $column, $sort_settings['direction']);
         }
     }
     return $query;
 }
 /**
  * Sort the query for list.
  *
  * @param \EntityFieldQuery $query
  *   The query object.
  *
  * @throws \Drupal\restful\Exception\BadRequestException
  * @throws \EntityFieldQueryException
  *
  * @see \RestfulEntityBase::getQueryForList
  */
 protected function queryForListSort(\EntityFieldQuery $query)
 {
     $resource_fields = $this->fieldDefinitions;
     // Get the sorting options from the request object.
     $sorts = $this->parseRequestForListSort();
     $sorts = $sorts ? $sorts : $this->defaultSortInfo();
     foreach ($sorts as $public_field_name => $direction) {
         // Determine if sorting is by field or property.
         /* @var \Drupal\restful\Plugin\resource\Field\ResourceFieldEntityInterface $resource_field */
         if (!($resource_field = $resource_fields->get($public_field_name))) {
             return;
         }
         if (!($property_name = $resource_field->getProperty())) {
             throw new BadRequestException('The current sort selection does not map to any entity property or Field API field.');
         }
         if (ResourceFieldEntity::propertyIsField($property_name)) {
             $query->fieldOrderBy($property_name, $resource_field->getColumn(), $direction);
         } else {
             $column = $this->getColumnFromProperty($property_name);
             $query->propertyOrderBy($column, $direction);
         }
     }
 }
  /**
   * Sort the query for list.
   *
   * @param \EntityFieldQuery $query
   *   The query object.
   *
   * @throws \RestfulBadRequestException
   *
   * @see \RestfulEntityBase::getQueryForList
   */
  protected function queryForListSort(\EntityFieldQuery $query) {
    $public_fields = $this->getPublicFields();

    // Get the sorting options from the request object.
    $sorts = $this->parseRequestForListSort();

    $sorts = $sorts ? $sorts : $this->defaultSortInfo();

    foreach ($sorts as $public_field_name => $direction) {
      // Determine if sorting is by field or property.
      if (!$property_name = $public_fields[$public_field_name]['property']) {
        throw new \RestfulBadRequestException('The current sort selection does not map to any entity property or Field API field.');
      }
      if (field_info_field($property_name)) {
        $query->fieldOrderBy($public_fields[$public_field_name]['property'], $public_fields[$public_field_name]['column'], $direction);
      }
      else {
        $column = $this->getColumnFromProperty($property_name);
        $query->propertyOrderBy($column, $direction);
      }
    }
  }
 /**
  * Entity field query for entities of the defined bundle.
  */
 private function getAggregate($bean)
 {
     $type = $bean->settings['entity_type'];
     foreach ($bean->settings['bundle_types'] as $bundle) {
         $query = new EntityFieldQuery();
         $query->entityCondition('entity_type', $type);
         $query->entityCondition('bundle', $bundle);
         $query->propertyOrderBy('created', 'DESC');
         if ($type == 'node') {
             $query->propertyCondition('status', 1);
         }
         // Additional conditions for node based translations.
         global $language;
         if ($language->language != NULL && $type == 'node') {
             $query->propertyCondition('language', $language->language);
             $query->propertyCondition('tnid', 0, "<>");
         }
         $results[$bundle] = $query->execute();
         // For nodes using field based translation.
         if ($language->language != NULL && $type == 'node') {
             $query = new EntityFieldQuery();
             $query->entityCondition('entity_type', $type);
             $query->entityCondition('bundle', $bundle);
             $query->propertyOrderBy('created', 'DESC');
             $query->propertyCondition('tnid', 0);
             $query->propertyCondition('status', 1);
             $field_translated = $query->execute();
             // Reassign the result array or merge arrays if necessary
             if (empty($results[$bundle][$type]) && !empty($field_translated)) {
                 $results[$bundle][$type] = $field_translated[$type];
             } elseif (!empty($results[$bundle][$type]) && !empty($field_translated[$type])) {
                 $combined = $results[$bundle][$type] + $field_translated[$type];
                 ksort($combined);
                 $results[$bundle][$type] = $combined;
             }
         }
     }
     // Store the results in an aggregated array of entities.
     $aggregate = array();
     if (isset($results[$bundle][$bean->settings['entity_type']])) {
         foreach ($results[$bundle][$bean->settings['entity_type']] as $id => $result) {
             $aggregate[$bean->settings['entity_type']][$id] = $result;
         }
     }
     return $aggregate;
 }
Ejemplo n.º 7
0
 /**
  * Displays the bean.
  */
 public function view($bean, $content, $view_mode = 'default', $langcode = NULL)
 {
     // We need to make sure that the bean is configured correctly.
     if (!empty($bean->filters['vocabulary']) && !empty($bean->settings['bundle_types'])) {
         // Define an array of all taxonomy terms in the defined vocabularies.
         $possible_tid = array();
         foreach ($bean->filters['vocabulary'] as $vm) {
             $query = new EntityFieldQuery();
             $result = $query->entityCondition('entity_type', 'taxonomy_vocabulary')->propertyCondition('machine_name', $vm)->execute();
             foreach ($result['taxonomy_vocabulary'] as $vocabulary) {
                 $vid = $vocabulary->vid;
             }
             $tree = taxonomy_get_tree($vid);
             foreach ($tree as $term) {
                 $possible_tid[$term->tid] = $term->tid;
             }
         }
         // Compare possible terms to those attached to the menu object or current
         // user depending on 'related' settings.
         $active_entity = bean_tax_active_entity_array($bean->settings['related']);
         if (isset($active_entity['terms'])) {
             $valid_tid = array();
             foreach ($active_entity['terms'] as $term) {
                 if (isset($possible_tid[$term->tid])) {
                     $valid_tid[$term->tid] = $term->tid;
                 }
             }
             // Store Entity type.
             $type = $bean->settings['entity_type'];
             // Entity field query for entities of the defined bundle.
             $aggregate = array();
             foreach ($bean->settings['bundle_types'] as $bundle) {
                 $query = new EntityFieldQuery();
                 $query->entityCondition('entity_type', $type);
                 $query->entityCondition('bundle', $bundle);
                 $query->propertyOrderBy('created', 'DESC');
                 if ($type == 'node') {
                     $query->propertyCondition('status', 1);
                 }
                 // Additional conditions for node based translations.
                 global $language;
                 if ($language->language != NULL && $type == 'node') {
                     $query->propertyCondition('language', $language->language);
                     $query->propertyCondition('tnid', 0, "<>");
                 }
                 $results[$bundle] = $query->execute();
                 // For nodes using field based translation.
                 if ($language->language != NULL && $type == 'node') {
                     $query = new EntityFieldQuery();
                     $query->entityCondition('entity_type', $type);
                     $query->entityCondition('bundle', $bundle);
                     $query->propertyOrderBy('created', 'DESC');
                     $query->propertyCondition('tnid', 0);
                     $query->propertyCondition('status', 1);
                     $field_translated = $query->execute();
                     // Reassign the result array or merge arrays if necessary
                     if (empty($results[$bundle][$type]) && !empty($field_translated[$type])) {
                         $results[$bundle][$type] = $field_translated[$type];
                     } elseif (!empty($results[$bundle][$type]) && !empty($field_translated[$type])) {
                         $combined = $results[$bundle][$type] + $field_translated[$type];
                         ksort($combined);
                         $results[$bundle][$type] = $combined;
                     }
                 }
                 // Store the results in an aggregated array of entities.
                 if (isset($results[$bundle][$bean->settings['entity_type']])) {
                     foreach ($results[$bundle][$bean->settings['entity_type']] as $id => $result) {
                         $aggregate[$bean->settings['entity_type']][$id] = $result;
                     }
                 }
             }
             // Create a taxonomy related "score" for each result's matching terms.
             $result = array();
             $unmatching = array();
             if (isset($aggregate[$bean->settings['entity_type']])) {
                 foreach ($aggregate[$bean->settings['entity_type']] as $key => $value) {
                     $entity_terms = bean_tax_get_entity_terms($bean->settings['entity_type'], $key);
                     $score = 0;
                     // The actual scoring to determine valid taxonomy term matching.
                     foreach ($entity_terms as $term) {
                         if (isset($valid_tid[$term->tid])) {
                             $score++;
                         }
                     }
                     $item['id'] = $key;
                     $item['score'] = $score;
                     // A score of 1 or greater adds to the array of matching entities.
                     if ($score != 0) {
                         $result[] = $item;
                     } elseif ($score == 0 && $bean->settings['unmatch_add']) {
                         $result[] = $item;
                     }
                 }
             }
             // Calculate an overall score.
             $all = 0;
             foreach ($result as $item) {
                 $all = $item['score'] + $all;
             }
             // If overall score is none, do sort.
             if ($all != 0) {
                 // Invoke comparison function to determine highest ranked results.
                 usort($result, "bean_tax_cmp");
             }
         }
         // Remove active page from results.
         if (!empty($result)) {
             foreach ($result as $key => $entity) {
                 $active_page = bean_tax_active_entity_array('page');
                 if (isset($active_page['ids']) && $active_page['ids'][0] == $entity['id'] && $active_page['type'] == $bean->settings['entity_type']) {
                     unset($result[$key]);
                 }
             }
         }
         // Related entities initially set to none.
         if (empty($result)) {
             // Hide block when result is empty and 'hide_empty' option is checked.
             if ($bean->settings['hide_empty'] || !$active_entity['object']) {
                 return;
             }
             // There are no related nodes. Set Empty array for theme output.
             $content['#markup'] = t('No Results');
         } elseif (isset($active_entity['type']) && $active_entity['type'] == 'bean' && $bean->bid === $active_entity['object']->bid) {
             $content['#markup'] = '';
         } else {
             // Start counting results at index of 0.
             $i = 0;
             // Set and index for actual results shown.
             $shown = 0;
             // Set markup index as empty.
             $content['#markup'] = '';
             // Load and render the related entities.
             foreach ($result as $entity) {
                 if (isset($entity['id']) && $shown < $bean->filters['records_shown'] && $i >= $bean->filters['offset_results']) {
                     $entity = entity_load_single($bean->settings['entity_type'], $entity['id']);
                     $entity_view = entity_view($bean->settings['entity_type'], array($entity), $bean->settings['entity_view_mode']);
                     $content['#markup'] .= drupal_render($entity_view);
                     $shown++;
                 }
                 // Count continues along...
                 $i++;
             }
         }
     }
     if (!empty($bean->more_link['text']) && !empty($bean->more_link['path'])) {
         // Invoke the theme function to show the additional information "more link"
         $content['#markup'] .= theme('bean_tax_more_link', array('text' => $bean->more_link['text'], 'path' => $bean->more_link['path']));
     }
     return $content;
 }
Ejemplo n.º 8
0
 /**
  * As seen in commerce_services: sorting.
  *
  * Adds property and field order by directions to an index EntityFieldQuery.
  *
  * @param \EntityFieldQuery $query
  *   The EntityFieldQuery object being built for the index query.
  * @param string $entity_type
  *   Machine-name of the entity type of the index query.
  * @param array $sort_by
  *   An array of database fields to sort the query by, with sort fields being
  *   valid properties, single column field names, or multi-column field column
  *   names for the matching entity type.
  * @param array $sort_order
  *   The corresponding sort orders for the fields specified in the $sort_by
  *   array; one of either 'DESC' or 'ASC'.
  */
 public static function indexQuerySort(\EntityFieldQuery $query, $entity_type, array $sort_by, array $sort_order)
 {
     // Loop over each sort field to add them as property or field order by
     // directions on the query object. This function assumes the $sort_by and
     // $sort_order arrays contain an equal number of elements with keys matching
     // the sort field to the appropriate sort order.
     foreach ($sort_by as $sort_key => $sort_field) {
         // Determine the corresponding sort direction for this sort field,
         // defaulting to DESC in case of an erroneous request.
         $direction = 'DESC';
         if (!empty($sort_order[$sort_key])) {
             $direction = strtoupper($sort_order[$sort_key]);
         }
         // If the current sort field is a property, use a property condition.
         $properties = self::entityTypeProperties($entity_type);
         if (in_array($sort_field, array_keys($properties), TRUE)) {
             $query->propertyOrderBy($properties[$sort_field], $direction);
         } else {
             // Look for the field name among the entity type's field list.
             foreach (self::entityTypeFields($entity_type) as $field_name => $field_type) {
                 // If the sort field begins with a field name, then either the sort
                 // field is the field name or is a column of the field.
                 if (strpos($sort_field, $field_name) === 0) {
                     $field_info = field_info_field($field_name);
                     // If it is the field name and the field type has a single column
                     // schema, add the field condition to the index query.
                     if ($field_name == $sort_field && count($field_info['columns']) == 1) {
                         $column = key($field_info['columns']);
                         $query->fieldOrderBy($field_name, $column, $direction);
                         break;
                     } else {
                         // Otherwise if the sort field contains a valid column
                         // specification for the field type, add the field condition to
                         // the index query.
                         $column = substr($sort_field, strlen($field_name) + 1);
                         if (in_array($column, array_keys($field_info['columns']))) {
                             $query->fieldOrderBy($field_name, $column, $direction);
                             break;
                         }
                     }
                 }
             }
         }
     }
 }