/** * Implements LinkitSearchPluginInterface::fetchResults(). */ public function fetchResults($search_string) { // If the $search_string is not a string, something is wrong and an empty // array is returned. $matches = array(); // Get the EntityFieldQuery instance. $this->getQueryInstance(); $or = db_or(); $or->condition('n.title', '%' . db_like($search_string) . '%', 'LIKE'); $or->condition('bcd.name', '%' . db_like($search_string) . '%', 'LIKE'); $or->condition('b.biblio_secondary_title', '%' . db_like($search_string) . '%', 'LIKE'); $or->condition('bkd.word', '%' . db_like($search_string) . '%', 'LIKE'); $this->query->condition($or); $this->query->orderBy('b.biblio_year', 'DESC'); //ORDER BY created // Add the search condition to the query object. /*$this->query->propertyCondition($this->entity_field_label, '%' . db_like($search_string) . '%', 'LIKE') ->addTag('linkit_entity_autocomplete') ->addTag('linkit_' . $this->plugin['entity_type'] . '_autocomplete');*/ /* $matches[] = array( 'title' => $this->entity_field_label, 'description' => '', 'path' => '', 'group' => '', 'addClass' => '', ); return $matches; */ /* // Add access tag for the query. // There is also a runtime access check that uses entity_access(). $this->query->addTag($this->plugin['entity_type'] . '_access'); // Bundle check. if (isset($this->entity_key_bundle) && isset($this->conf['bundles']) ) { $bundles = array_filter($this->conf['bundles']); if ($bundles) { $this->query->propertyCondition($this->entity_key_bundle, $bundles, 'IN'); } }*/ // Execute the query. $result = $this->query->execute()->fetchAllAssoc('nid'); /*if (!isset($result[$this->plugin['entity_type']])) { return array(); }*/ $ids = array_keys($result); // Load all the entities with all the ids we got. $entities = entity_load('node', $ids); foreach ($entities as $key => $entity) { // Check the access againt the definded entity access callback. if (entity_access('view', 'node', $entity) === FALSE) { continue; } $matches[] = array('title' => biblio_remove_brace($this->createLabel($entity)), 'description' => $this->createDescription($entity) . ' <span class="name">' . $result[$key]->name . '</span> <span class="year">' . $result[$key]->biblio_year . '</span>', 'path' => $this->createPath($entity), 'group' => $this->createGroup($entity), 'addClass' => $this->createRowClass($entity)); } return $matches; }
/** * Returns the next available member id. */ public function next($membership) { $settings = $this->settings + array('pattern' => '', 'suffix' => 1, 'length' => 5, 'advanced' => array()); $settings['advanced'] += array('separator' => '-', 'maxlength' => '', 'case' => 'none', 'ignore_words' => ''); // Build the member id. $member_id = token_replace($settings['pattern'], array('membership_entity' => $membership), array('sanitize' => TRUE, 'clear' => TRUE, 'callback' => '_membership_entity_token_member_id_token_callback', 'settings' => $settings['advanced'])); // Empty member_ids do not need any cleaning. if ($member_id !== '' && $member_id !== NULL) { $member_id = _membership_entity_token_clean_separator($member_id, $settings['advanced']['separator']); } // Optionally add a unique suffix. if (!empty($settings['suffix'])) { $length = $settings['length']; $suffix = 1; // Find the most recent matching member id. $query = db_select('membership_entity', 'm'); $query->addExpression('MAX(member_id)', 'member_id'); $id = $query->condition('member_id', db_like($member_id) . '%', 'LIKE')->execute()->fetchField(); // If a member id already exists increment suffix by 1. if (!empty($id)) { $id = (int) str_replace($member_id, '', $id); $suffix = $id + 1; } $member_id .= str_pad($suffix, $length, '0', STR_PAD_LEFT); } return $member_id; }
/** * {@inheritdoc} */ public function analyze(TargetInterface $target) { $violations = []; $indexer = $target->getIndexer('function'); if ($indexer->has('hook_form_alter')) { $violations[] = $indexer->get('hook_form_alter'); } $id = $target->id() . '_form_%_alter'; // Until kernel tests are run in PHPUnit, we need to check for // the existence of db_like(). if (function_exists('db_like')) { $id = db_like($id); } $alter_hooks = $target->getIndexer('function')->getQuery()->condition('id', $id, 'LIKE')->execute(); foreach ($alter_hooks as $alter_hook) { $violations[] = $target->open($alter_hook->file)->find(Filter::isFunction($alter_hook->id)); } $issues = []; if ($violations) { $issue = $this->buildIssue($target); array_walk($violations, function (FunctionDeclarationNode $function) use($issue) { $issue->addViolation($function, $this); }); $issues[] = $issue; } return $issues; }
/** * {@inheritdoc} */ public function buildForm(array $form, FormStateInterface $form_state) { $form['customer_type'] = array('#type' => 'radios', '#options' => array('search' => t('Search for an existing customer.'), 'create' => t('Create a new customer account.'), 'none' => t('No customer account required.')), '#required' => TRUE, '#default_value' => 'search', '#ajax' => array('callback' => array($this, 'customerSelect'), 'wrapper' => 'uc-order-customer', 'progress' => array('type' => 'throbber'))); $form['customer'] = array('#prefix' => '<div id="uc-order-customer">', '#suffix' => '</div>', '#tree' => TRUE); // Create form elements needed for customer search. // Shown only when the 'Search for an existing customer.' radio is selected. if (!$form_state->hasValue('customer_type') || $form_state->getValue('customer_type') == 'search') { // Container for customer search fields. $form['customer'] += array('#type' => 'fieldset', '#title' => t('Customer search'), '#description' => t('Enter full or partial information in one or more of the following fields, then press the "Search" button. Search results will match all the provided information.')); // Customer first name. $form['customer']['first_name'] = array('#type' => 'textfield', '#title' => t('First name'), '#size' => 24, '#maxlength' => 32); // Customer last name. $form['customer']['last_name'] = array('#type' => 'textfield', '#title' => t('Last name'), '#size' => 24, '#maxlength' => 32); // Customer e-mail address. $form['customer']['email'] = array('#type' => 'textfield', '#title' => t('E-mail'), '#size' => 24, '#maxlength' => 96); // Customer username. $form['customer']['username'] = array('#type' => 'textfield', '#title' => t('Username'), '#size' => 24, '#maxlength' => 96); $form['customer']['search'] = array('#type' => 'button', '#value' => t('Search'), '#limit_validation_errors' => array(), '#submit' => array(), '#ajax' => array('callback' => array($this, 'customerSearch'), 'wrapper' => 'uc-order-customer-results', 'progress' => array('type' => 'throbber'))); $form['customer']['uid'] = array('#prefix' => '<div id="uc-order-customer-results">', '#suffix' => '</div>'); // Search for existing customer by e-mail address. if ($form_state->getValue('customer')) { $query = db_select('users_field_data', 'u')->distinct(); $query->leftJoin('uc_orders', 'o', 'u.uid = o.uid'); $query->fields('u', array('uid', 'name', 'mail'))->fields('o', array('billing_first_name', 'billing_last_name'))->condition('u.uid', 0, '>')->condition(db_or()->isNull('o.billing_first_name')->condition('o.billing_first_name', db_like(trim($form_state->getValue(['customer', 'first_name']))) . '%', 'LIKE'))->condition(db_or()->isNull('o.billing_last_name')->condition('o.billing_last_name', db_like(trim($form_state->getValue(['customer', 'last_name']))) . '%', 'LIKE'))->condition(db_or()->condition('o.primary_email', db_like(trim($form_state->getValue(['customer', 'email']))) . '%', 'LIKE')->condition('u.mail', db_like(trim($form_state->getValue(['customer', 'email']))) . '%', 'LIKE'))->condition('u.name', db_like(trim($form_state->getValue(['customer', 'username']))) . '%', 'LIKE')->orderBy('o.created', 'DESC')->range(0, $limit = 11); $result = $query->execute(); $options = array(); foreach ($result as $user) { $name = ''; if (!empty($user->billing_first_name) && !empty($user->billing_last_name)) { $name = $user->billing_first_name . ' ' . $user->billing_last_name . ' '; } // Options formatted as "First Last <*****@*****.**> (username)". $options[$user->uid] = $name . '<' . $user->mail . '>' . ' (' . $user->name . ')'; } $max = FALSE; if (count($options) == $limit) { array_pop($options); $max = TRUE; } if (!empty($options)) { // Display search results. $form['customer']['uid'] += array('#type' => 'radios', '#title' => t('Select customer'), '#description' => $max ? t('More than @limit results found. Refine your search to find other customers.', ['@limit' => $limit - 1]) : '', '#options' => $options, '#default_value' => key($options)); } else { // No search results found. $form['customer']['uid'] += array('#markup' => '<p>' . t('Search returned no results.') . '</p>'); } } } elseif ($form_state->getValue('customer_type') == 'create') { // Container for new customer information. $form['customer'] += array('#type' => 'fieldset', '#title' => t('New customer details')); // Customer e-mail address. $form['customer']['email'] = array('#type' => 'email', '#title' => t('Customer e-mail address'), '#size' => 24, '#maxlength' => 96); // Option to notify customer. $form['customer']['sendmail'] = array('#type' => 'checkbox', '#title' => t('E-mail account details to customer.')); } $form['actions'] = array('#type' => 'actions'); $form['actions']['submit'] = array('#type' => 'submit', '#value' => t('Create order')); return $form; }
public function userAutocomplete($query = NULL) { $query = db_select('users_field_data', 'e')->fields('e', array('uid', 'name'))->condition('name', '%' . db_like($query) . '%', 'LIKE')->range(0, 10)->execute(); $result = array(); foreach ($query as $row) { $result[] = array('id' => $row->uid, 'name' => $row->name); } return new JsonResponse($result); }
/** * The autocomplete callback function for the Linkit Entity plugin. */ function autocomplete_callback() { $matches = array(); // Get page urls. $results = db_select('page_manager_pages', 'pmp')->fields('pmp', array('admin_title', 'path'))->condition('pmp.name', '%' . db_like($this->serach_string) . '%', 'LIKE')->execute(); foreach ($results as $page) { $matches[] = array('title' => $this->buildLabel($page->admin_title), 'path' => $this->buildPath($page->path), 'group' => $this->buildGroup('Pages')); } return $matches; }
/** * {@inheritdoc} */ public function validate($items, Constraint $constraint) { if (!isset($items)) { return; } $field_name = $items->getFieldDefinition()->getName(); $value_taken = (bool) \Drupal::entityQuery('user')->condition('uid', (int) $items->getEntity()->id(), '<>')->condition($field_name, db_like($items->first()->value), 'LIKE')->range(0, 1)->count()->execute(); if ($value_taken) { $this->context->addViolation($constraint->message, array("%value" => $items->value)); } }
/** * Tests a LIKE query containing a backslash. */ function testLikeBackslash() { db_insert('test')->fields(array('name'))->values(array('name' => 'abcde\\f'))->values(array('name' => 'abc%\\_'))->execute(); // Match both rows using a LIKE expression with two wildcards and a verbatim // backslash. $num_matches = db_select('test', 't')->condition('name', 'abc%\\\\_', 'LIKE')->countQuery()->execute()->fetchField(); $this->assertIdentical($num_matches, '2', 'Found 2 records.'); // Match only the former using a LIKE expression with no wildcards. $num_matches = db_select('test', 't')->condition('name', db_like('abc%\\_'), 'LIKE')->countQuery()->execute()->fetchField(); $this->assertIdentical($num_matches, '1', 'Found 1 record.'); }
public function autocompLieu(Request $request) { $string = $request->query->get('q'); $matches = array(); if ($string) { $result = db_select('gbb_netab_dafor')->fields('gbb_netab_dafor', array('co_lieu', 'denom_comp', 'sigle'))->condition('denom_comp', '%' . db_like($string) . '%', 'LIKE')->range(0, 10)->execute(); foreach ($result as $res) { $matches[] = array('value' => "{$res->sigle} {$res->denom_comp} ({$res->co_lieu})", 'label' => "{$res->sigle} {$res->denom_comp} ({$res->co_lieu})"); } } return new JsonResponse($matches); }
/** * {@inheritdoc} */ public function submitForm(array &$form, FormStateInterface $form_state) { $match = 'i:' . $this->option->aid . ';s:' . strlen($this->option->oid) . ':"' . $this->option->oid . '";'; db_delete('uc_product_adjustments')->condition('combination', '%' . db_like($match) . '%', 'LIKE')->execute(); $select = db_select('uc_attribute_options', 'ao')->where('{uc_class_attribute_options}.oid = ao.oid')->condition('ao.oid', $this->option->oid); $select->addExpression('1'); db_delete('uc_class_attribute_options')->condition('', $select, 'EXISTS')->execute(); $select = db_select('uc_attribute_options', 'ao')->where('{uc_product_options}.oid = ao.oid')->condition('ao.oid', $this->option->oid); $select->addExpression('1'); db_delete('uc_product_options')->condition('', $select, 'EXISTS')->execute(); db_delete('uc_attribute_options')->condition('oid', $this->option->oid)->execute(); $form_state->setRedirect('uc_attribute.options', ['aid' => $this->option->aid]); }
/** * The autocomplete callback function for the Linkit Entity plugin. */ function autocomplete_callback() { // Create the tmp table. $this->create_tmp_table(); // Populate the tmp table. $this->populate_tmp_table(); $matches = array(); $query = db_select($this->table_name, 'tmp')->fields('tmp', array('path', 'display_title', 'human_name'))->condition('tmp.display_title', '%' . db_like($this->serach_string) . '%', 'LIKE')->addTag('linkit_views_autocomplete')->execute(); foreach ($query as $view) { $matches[] = array('title' => $view->display_title, 'path' => base_path() . $view->path, 'description' => t('View: %view', array('%view' => $view->human_name)), 'group' => t('View pages')); } return $matches; }
/** * Returns autocompletion content for file name textfield. * * @param \Symfony\Component\HttpFoundation\Request $request * The request of the page. * * @return \Symfony\Component\HttpFoundation\JsonResponse * A JSON response. */ public function autocompleteFilename(Request $request) { $matches = array(); // Get the typed string from the URL, if it exists. if ($input = $request->query->get('q')) { $typed_string = Tags::explode($input); $typed_string = Unicode::strtolower(array_pop($typed_string)); $filenames = db_select('uc_files', 'f')->fields('f', ['filename'])->condition('filename', '%' . db_like($typed_string) . '%', 'LIKE')->execute(); while ($name = $filenames->fetchField()) { $matches[] = array('value' => $name); } } return new JsonResponse($matches); }
/** * {@inheritdoc} */ public function submitForm(array &$form, FormStateInterface $form_state) { if ($form_state->getValue(['delete', 'all_aliases'])) { db_delete('url_alias')->execute(); drupal_set_message($this->t('All of your path aliases have been deleted.')); } foreach (array_keys(array_filter($form_state->getValue(['delete', 'plugins']))) as $id) { /** @var \Drupal\pathauto\AliasTypeInterface $alias_type */ $alias_type = $this->aliasTypeManager->createInstance($id); db_delete('url_alias')->condition('source', db_like($alias_type->getSourcePrefix()) . '%', 'LIKE')->execute(); drupal_set_message(t('All of your %label path aliases have been deleted.', array('%label' => $alias_type->getLabel()))); } $form_state->setRedirect('pathauto.bulk.update.form'); }
/** * {@inheritdoc} */ public function find($string, $prefix = true, $limit = 20) { if ($prefix) { $escaped = db_like($string) . '%'; } else { $escaped = '%' . db_like($string) . '%'; } $map = $this->db->select('node', 'n')->fields('n', ['nid', 'title'])->condition('n.type', $this->bundle)->condition('n.title', $escaped, 'LIKE')->orderBy('n.title')->range(0, $limit)->execute()->fetchAllKeyed(); $ret = []; foreach ($map as $id => $title) { $ret[] = new EntityFinderResult('node', $id, $title, $this->getLabel()); } return $ret; }
/** * {@inheritdoc} */ public function convert(TargetInterface $target) { $indexer = $target->getIndexer('function'); // @FIXME This is not working (returns empty result set)...don't know why. $alter_hooks = $indexer->getQuery()->condition(db_or()->condition('id', $target->id() . '_form_alter')->condition('id', db_like($target->id() . '_form_%_alter'), 'LIKE'))->execute(); foreach ($alter_hooks as $alter_hook) { /** @var \Pharborist\Functions\FunctionDeclarationNode $function */ $function = $indexer->get($alter_hook->id); $parameters = $function->getParameters(); if (sizeof($parameters) > 1) { $parameters[1]->setTypeHint('\\Drupal\\Core\\Form\\FormStateInterface'); $target->save($function); } } }
function op_word($fulltext_field) { $where = $this->operator == 'word' ? db_or() : db_and(); // Don't filter on empty strings. if (empty($this->value[0])) { return; } $value = Unicode::strtolower($this->value[0]); $words = preg_split('/ /', $value, -1, PREG_SPLIT_NO_EMPTY); foreach ($words as $word) { $placeholder = $this->placeholder(); $where->where("{$fulltext_field} LIKE {$placeholder}", array($placeholder => '% ' . db_like($word) . '%')); } $this->query->addWhere($this->options['group'], $where); }
/** * {@inheritdoc} */ public function validate($items, Constraint $constraint) { if (!isset($items)) { return; } $field_name = $items->getFieldDefinition()->getName(); /** @var \Drupal\Core\Entity\EntityInterface $entity */ $entity = $items->getEntity(); $entity_type_id = $entity->getEntityTypeId(); $id_key = $entity->getEntityType()->getKey('id'); $value_taken = (bool) \Drupal::entityQuery($entity_type_id)->condition($id_key, (int) $items->getEntity()->id(), '<>')->condition($field_name, db_like($items->first()->value), 'LIKE')->range(0, 1)->count()->execute(); if ($value_taken) { $this->context->addViolation($constraint->message, array("%value" => $items->value)); } }
/** * Find the file for a class that in PSR-0 or PEAR would be in * $psr_0_root . '/' . $path_fragment . $path_suffix * * E.g.: * - The class we look for is Some\Namespace\Some\Class * - The file is actually in "exotic/location.php". This is not following * PSR-0 or PEAR standard, so we need a plugin. * -> The class finder will transform the class name to * "Some/Namespace/Some/Class.php" * - The plugin was registered for the namespace "Some\Namespace". This is * because all those exotic classes all begin with Some\Namespace\ * -> The arguments will be: * ($api = the API object, see below) * $logical_base_path = "Some/Namespace/" * $relative_path = "Some/Class.php" * $api->getClass() gives the original class name, if we still need it. * -> We are supposed to: * if ($api->suggestFile('exotic/location.php')) { * return TRUE; * } * * @param InjectedApiInterface $api * An object with a suggestFile() method. * We are supposed to suggest files until suggestFile() returns TRUE, or we * have no more suggestions. * @param string $logical_base_path_empty * The key that this plugin was registered with. * With trailing '/'. * @param string $relative_path_irrelevant * Second part of the canonical path, ending with '.php'. * * @return bool|null * TRUE, if the file was found. * FALSE or NULL, otherwise. */ function findFile($api, $logical_base_path_empty, $relative_path_irrelevant) { $q = db_select('registry'); // Use LIKE here to make the query case-insensitive. $q->condition('name', db_like($api->getClass()), 'LIKE'); $q->addField('registry', 'filename'); $stmt = $q->execute(); while ($relative_path = $stmt->fetchField()) { $file = $this->baseDir . $relative_path; // Attention: The db_select() above can trigger the class loader for // classes and interfaces of the database layer. This can cause some files // to be included twice, if the file defines more than one class. // So we need to use require_once here, instead of require. That is, use // guessFile() instead of claimFile(). if ($api->guessFile($file)) { return TRUE; } } return FALSE; }
public function photos_access_multiple_users_autocomplete($string = '') { $array = drupal_explode_tags($string); $last_string = trim(array_pop($array)); $matches = []; if ($last_string != '') { $result = db_select('users') ->fields('users', ['name']) ->condition('name', db_like($last_string) . '%', 'LIKE') ->range(0, 10) ->execute(); $prefix = count($array) ? implode(', ', $array) . ', ' : ''; foreach ($result as $user) { $n = $user->name; $matches[$prefix . $n] = $user->name; } } drupal_json_output($matches); }
/** * Builds a SELECT query with multiple conditions and fields. * * The query uses both 'locales_source' and 'locales_target' tables. * Note that by default, as we are selecting both translated and untranslated * strings target field's conditions will be modified to match NULL rows too. * * @param array $conditions * An associative array with field => value conditions that may include * NULL values. If a language condition is included it will be used for * joining the 'locales_target' table. * @param array $options * An associative array of additional options. It may contain any of the * options used by Drupal\locale\StringStorageInterface::getStrings() and * these additional ones: * - 'translation', Whether to include translation fields too. Defaults to * FALSE. * * @return \Drupal\Core\Database\Query\Select * Query object with all the tables, fields and conditions. */ protected function dbStringSelect(array $conditions, array $options = array()) { // Start building the query with source table and check whether we need to // join the target table too. $query = $this->connection->select('locales_source', 's', $this->options)->fields('s'); // Figure out how to join and translate some options into conditions. if (isset($conditions['translated'])) { // This is a meta-condition we need to translate into simple ones. if ($conditions['translated']) { // Select only translated strings. $join = 'innerJoin'; } else { // Select only untranslated strings. $join = 'leftJoin'; $conditions['translation'] = NULL; } unset($conditions['translated']); } else { $join = !empty($options['translation']) ? 'leftJoin' : FALSE; } if ($join) { if (isset($conditions['language'])) { // If we've got a language condition, we use it for the join. $query->{$join}('locales_target', 't', "t.lid = s.lid AND t.language = :langcode", array(':langcode' => $conditions['language'])); unset($conditions['language']); } else { // Since we don't have a language, join with locale id only. $query->{$join}('locales_target', 't', "t.lid = s.lid"); } if (!empty($options['translation'])) { // We cannot just add all fields because 'lid' may get null values. $query->fields('t', array('language', 'translation', 'customized')); } } // If we have conditions for location's type or name, then we need the // location table, for which we add a subquery. We cast any scalar value to // array so we can consistently use IN conditions. if (isset($conditions['type']) || isset($conditions['name'])) { $subquery = $this->connection->select('locales_location', 'l', $this->options)->fields('l', array('sid')); foreach (array('type', 'name') as $field) { if (isset($conditions[$field])) { $subquery->condition('l.' . $field, (array) $conditions[$field], 'IN'); unset($conditions[$field]); } } $query->condition('s.lid', $subquery, 'IN'); } // Add conditions for both tables. foreach ($conditions as $field => $value) { $table_alias = $this->dbFieldTable($field); $field_alias = $table_alias . '.' . $field; if (is_null($value)) { $query->isNull($field_alias); } elseif ($table_alias == 't' && $join === 'leftJoin') { // Conditions for target fields when doing an outer join only make // sense if we add also OR field IS NULL. $query->condition(db_or()->condition($field_alias, (array) $value, 'IN')->isNull($field_alias)); } else { $query->condition($field_alias, (array) $value, 'IN'); } } // Process other options, string filter, query limit, etc. if (!empty($options['filters'])) { if (count($options['filters']) > 1) { $filter = db_or(); $query->condition($filter); } else { // If we have a single filter, just add it to the query. $filter = $query; } foreach ($options['filters'] as $field => $string) { $filter->condition($this->dbFieldTable($field) . '.' . $field, '%' . db_like($string) . '%', 'LIKE'); } } if (!empty($options['pager limit'])) { $query = $query->extend('Drupal\\Core\\Database\\Query\\PagerSelectExtender')->limit($options['pager limit']); } return $query; }
protected function opNotLike($field) { $this->query->addWhere($this->options['group'], $field, '%' . db_like($this->value) . '%', 'NOT LIKE'); }
/** * Implements LinkitSearchPluginInterface::fetchResults(). */ public function fetchResults($search_string) { // If the $search_string is not a string, something is wrong and an empty // array is returned. $matches = array(); // Get the EntityFieldQuery instance. $this->getQueryInstance(); // Add the search condition to the query object. $this->query->propertyCondition($this->entity_field_label, '%' . db_like($search_string) . '%', 'LIKE')->addTag('linkit_entity_autocomplete')->addTag('linkit_' . $this->plugin['entity_type'] . '_autocomplete'); /* * DEBUGGING * to search a biblio node using author name * search must include tables biblio_contributor_data & biblio_contributor & (biblio or node) * EntityFieldQuery cannot support current requirement * implement plain query execution and return results in the format of EntityFieldQuery ($this->query->execute() & $matches) * e.g. (biblio.pages.inc) * $db_result = db_query('SELECT bd.cid, bd.drupal_uid, bd.name, bd.lastname, bd.firstname, bd.prefix, bd.suffix, bd.initials, bd.affiliation, bd.md5, bd.literal, COUNT(*) AS cnt FROM {biblio_contributor} b LEFT JOIN {biblio_contributor_data} bd ON b.cid = bd.cid INNER JOIN {node} n on n.vid = b.vid ' . $where_clause . ' GROUP BY bd.cid, bd.drupal_uid, bd.name, bd.lastname, bd.firstname, bd.prefix, bd.suffix, bd.initials, bd.affiliation, bd.md5, bd.literal ORDER BY lastname ASC, SUBSTRING(firstname,1,1) ASC, initials ASC', array(':filter' => $filter)); * $matches[] = array( 'title' => $this->entity_field_label, 'description' => '', 'path' => '', 'group' => '', 'addClass' => '', ); return $matches; */ // Add access tag for the query. // There is also a runtime access check that uses entity_access(). $this->query->addTag($this->plugin['entity_type'] . '_access'); // Bundle check. if (isset($this->entity_key_bundle) && isset($this->conf['bundles'])) { $bundles = array_filter($this->conf['bundles']); if ($bundles) { $this->query->propertyCondition($this->entity_key_bundle, $bundles, 'IN'); } } // Execute the query. $result = $this->query->execute(); if (!isset($result[$this->plugin['entity_type']])) { return array(); } $ids = array_keys($result[$this->plugin['entity_type']]); // Load all the entities with all the ids we got. $entities = entity_load($this->plugin['entity_type'], $ids); foreach ($entities as $entity) { // Check the access againt the definded entity access callback. if (entity_access('view', $this->plugin['entity_type'], $entity) === FALSE) { continue; } $matches[] = array('title' => $this->createLabel($entity), 'description' => $this->createDescription($entity), 'path' => $this->createPath($entity), 'group' => $this->createGroup($entity), 'addClass' => $this->createRowClass($entity)); } return $matches; }
protected function opNotLike($expression) { $placeholder = $this->placeholder(); $this->query->addWhereExpression($this->options['group'], "{$expression} NOT LIKE {$placeholder}", array($placeholder => '%' . db_like($this->value) . '%')); }
/** * Add or update a db record containing summ of tables data. * * @return TableInterface object (the created or updated record) * * @throws Drupal\Prod\Error\DbAnalyzerException */ public function ManageDbRecord() { $this->logger->log('Adding Database Record For Database ' . $this->getDbName(), NULL, WATCHDOG_DEBUG); $sumTable = TableFactory::get($this->getDbDriver(), $this->getDbIdentifier(), $this->getDbName(), NULL)->setTable($this->getDbName())->flagIsDatabase(TRUE); $query = db_select('prod_db_stats', 's')->condition('pdb_identifier', $this->getDbIdentifier())->condition('pdb_db_name', $this->getDbName())->condition('pdb_is_database', 0); // no filter on enable/disable //->condition('pdb_enable', 1) $prefix = $this->getDbPrefix(); if (!empty($prefix)) { $query->condition('pdb_table', db_like($prefix) . '%', 'LIKE'); } $query->addExpression('SUM(s.' . $prefix . 'pdb_nb_rows)', 'rowsum'); $query->addExpression('COUNT(*)', 'tablecount'); $results = $query->execute(); foreach ($results as $result) { $sumTable->setRows($result->rowsum); $sumTable->setSize($result->tablecount); $sumTable->setIndexSize(0); } /* foreach ($this->getTables() as $table) { $sumTable->addRows($table->getRows()); $sumTable->addSize($table->getSize()); $sumTable->addIndexSize($table->getIndexSize()); } */ //var_dump($sumTable); die('hard'); $sumTable->save(); return $sumTable; }
/** * Deletes custom generated menus */ protected function deleteMenus() { if (\Drupal::moduleHandler()->moduleExists('menu_ui')) { foreach (menu_ui_get_menus(FALSE) as $menu => $menu_title) { if (strpos($menu, 'devel-') === 0) { Menu::load($menu)->delete(); } } } // Delete menu links generated by devel. $result = db_select('menu_links', 'm')->fields('m', array('mlid'))->condition('m.menu_name', 'devel', '<>')->condition('m.options', '%' . db_like('s:5:"devel";b:1') . '%', 'LIKE')->execute(); foreach ($result as $link) { menu_link_delete($link->mlid); } }
/** * {@inheritdoc} */ public function query() { if (!empty($this->view->live_preview)) { return; } // Make sure the id field is included in the results. $id_field = $this->view->storage->get('base_field'); $this->id_field_alias = $this->view->query->addField($this->view->storage->get('base_table'), $id_field); $options = $this->getOption('entity_reference_options'); // Restrict the autocomplete options based on what's been typed already. if (isset($options['match'])) { $style_options = $this->getOption('style'); $value = db_like($options['match']) . '%'; if ($options['match_operator'] != 'STARTS_WITH') { $value = '%' . $value; } // Multiple search fields are OR'd together. $conditions = db_or(); // Build the condition using the selected search fields. foreach ($style_options['options']['search_fields'] as $field_id) { if (!empty($field_id)) { // Get the table and field names for the checked field. $field_handler = $this->view->field[$field_id]; $field_alias = $this->view->query->addField($field_handler->table, $field_handler->realField); $field = $this->view->query->fields[$field_alias]; // Add an OR condition for the field. $conditions->condition($field['table'] . '.' . $field['field'], $value, 'LIKE'); } } $this->view->query->addWhere(0, $conditions); } // Add an IN condition for validation. if (!empty($options['ids'])) { $this->view->query->addWhere(0, $id_field, $options['ids'], 'IN'); } $this->view->setItemsPerPage($options['limit']); }
/** * Implements EntityReferenceHandler::getReferencableEntities(). */ public function getReferencableEntities($match = NULL, $match_operator = 'CONTAINS', $limit = 25) { $options = array(); $target_node_types = $this->field['settings']['handler_settings']['target_bundles']; // No target node types means all issue types may be selected. if (empty($target_node_types)) { $target_node_types = project_issue_issue_node_types(); } global $base_url; // Early return if the short match string would generate too many results. // @todo: Make this configurable? Return even if user has ebereted #nid. // It's unlikely they're trying to reference a two digit nid issue. if (strlen($match) < 4) { return $options; } // If the given string begins with the site domain, try to match it to the // URL of an issue node. if (substr($match, 0, strlen($base_url)) == $base_url) { $matches = array(); // Extract the node ID from the URL, allowing for an anchor tag. preg_match("@^{$base_url}/node/(\\d+)(?:#\\S+)?\$@", $match, $matches); if (isset($matches[1])) { $nid = $matches[1]; $node = node_load($nid); if ($node) { // Only allow the node if it's of the right type and the user has // access to view it. if (in_array($node->type, $target_node_types) && node_access('view', $node)) { $options[$node->type][$nid] = check_plain($this->getLabel($node)); // Don't return yet, as there is a slim chance that the URL is part // of the title of an issue which starts with the domain name or // even the full URL, as in 'http://example.com/node/1 is broken'. } } } } // If the given string is of the form '#1234' then try to match that as a // nid. if (strpos($match, '#') === 0) { if (preg_match("@^#(\\d+)\$@", $match)) { $nid = substr($match, 1); $node = node_load($nid); if ($node) { // Only allow the node if it's of the right type and the user has // access to view it. if (in_array($node->type, $target_node_types) && node_access('view', $node)) { $options[$node->type][$nid] = check_plain($this->getLabel($node)); // Don't return, same reason as above. } } } } // Build a query for the nodes. We can't use buildEntityFieldQuery() because // we have to use a SelectQuery rather than an EntityFieldQuery to have an // OR condition. $query = db_select('node', 'n'); if (isset($match)) { // Try to match on the title or nid. $query->condition(db_or()->condition('n.title', '%' . db_like($match) . '%', 'LIKE')->condition('n.nid', $match)); } // Set the node type. $query->condition('type', $target_node_types); if (!user_access('bypass node access')) { // Restrict the query to published nodes. $query->condition('n.status', NODE_PUBLISHED); } // Restrict the number of returned rows. jQuery UI autocomplete defaults to // showing 10 only. if (!empty($limit)) { $query->range(0, $limit); } // Order the returned nodes by some sort of relevancy. $query->orderBy('n.changed', 'DESC'); $node_data = $query->fields('n', array('nid', 'title', 'type'))->addTag('node_access')->execute()->fetchAll(); foreach ($node_data as $item) { $options[$item->type][$item->nid] = check_plain($item->title); } return $options; }
/** * {@inheritdoc} */ protected function optionRemoved($aid, $oid) { $match = 'i:' . $aid . ';s:' . strlen($oid) . ':"' . $oid . '";'; db_delete('uc_product_adjustments')->condition('nid', $this->idValue)->condition('combination', '%' . db_like($match) . '%', 'LIKE')->execute(); }
/** * The autocomplete callback function for the Linkit Entity plugin. * * @return * An associative array whose values are an * associative array containing: * - title: A string to use as the search result label. * - description: (optional) A string with additional information about the * result item. * - path: The URL to the item. * - group: (optional) A string with the group name for the result item. * Best practice is to use the plugin name as group name. * - addClass: (optional) A string with classes to add to the result row. */ function autocomplete_callback() { $matches = array(); // Get the EntityFieldQuery instance. $this->getQueryInstance(); // Add the search condition to the query object. $this->query->propertyCondition($this->entity_field_label, '%' . db_like($this->search_string) . '%', 'LIKE')->addTag('linkit_entity_autocomplete')->addTag('linkit_' . $this->plugin['entity_type'] . '_autocomplete'); // Add access tag for the query. // There is also a runtime access check that uses entity_access(). $this->query->addTag($this->plugin['entity_type'] . '_access'); // Bundle check. if (isset($this->entity_key_bundle) && isset($this->conf['bundles'])) { if ($bundles = array_filter($this->conf['bundles'])) { $this->query->propertyCondition($this->entity_key_bundle, $bundles, 'IN'); } } // Execute the query. $result = $this->query->execute(); if (!isset($result[$this->plugin['entity_type']])) { return array(); } $ids = array_keys($result[$this->plugin['entity_type']]); // Load all the entities with all the ids we got. $entities = entity_load($this->plugin['entity_type'], $ids); foreach ($entities as $entity) { // Check the access againt the definded entity access callback. if (entity_access('view', $this->plugin['entity_type'], $entity) === FALSE) { continue; } $matches[] = array('title' => $this->buildLabel($entity), 'description' => $this->buildDescription($entity), 'path' => $this->buildPath($entity), 'group' => $this->buildGroup($entity), 'addClass' => $this->buildRowClass($entity)); } return $matches; }
<?php // Using below code you can able to display table with sortable headers & pagination. // Define table headers. $header = array(array('data' => 'ID', 'field' => 'id', 'sort' => 'ASC'), array('data' => 'Name', 'field' => 'name'), array('data' => 'Date of birth', 'field' => 'dob'), array('data' => 'Email', 'field' => 'email')); // Here 'field' values are database field values. (Ex: 'field' => 'name') // If you want to assign sort option to table field like ID, use 'sort' attribute (ex: 'sort' => 'ASC'). // DB query. $select = db_select('my_table', 't')->extend('PagerDefault')->extend('TableSort'); // Example for LIKE condition if (condition) { $select->condition('email', '%' . db_like($qry['email']) . '%', 'LIKE'); } $select->fields('t', array('id', 'name', 'dob', 'email'))->limit(10)->orderByHeader($header)->groupBy('t.email')->orderBy('updated_time', 'DESC')->addExpression('COUNT(*)', 'total'); $results = $select->execute(); // Collect table row values foreach ($results as $row) { $rows[] = array(l($row->id, 'url', array('query' => array('qry' => $row->email), 'attributes' => array('target' => '_blank'))), $row->name, $row->dob, $row->email); } // Putting all together to form a table. $output .= theme('table', array('header' => $header, 'rows' => $rows, "empty" => t("Table has no row!"), "sticky" => true)); $output .= theme('pager'); return $output;