Skip to main content

Posts

Showing posts from 2017

Database queries in Drupal 8

Select Get single value: $query = \Drupal::database()->select('node_field_data', 'nfd'); $query->addField('nfd', 'nid'); $query->condition('nfd.title', 'Potato'); $query->range(0, 1); $nid = $query->execute()->fetchField(); Get single row: $query = \Drupal::database()->select('node_field_data', 'nfd'); $query->fields('nfd', ['nid', 'title']); $query->condition('nfd.type', 'vegetable'); $query->range(0, 1); $vegetable = $query->execute()->fetchAssoc(); Using db like: $query = \Drupal::database()->select('node_field_data', 'nfd'); $query->fields('nfd', ['nid', 'title']); $query->condition('nfd.type', 'vegetable'); $query->condition('nfd.title', $query->escapeLike('ca') . '%', 'LIKE'); $vegetable = $query->execute()->f...

How to make a page redirection on Drupal 8 (like drupal_goto() on Drupal 7)?

Example 1. Redirect to the front page:     return new \Symfony\Component\HttpFoundation\RedirectResponse(\Drupal::url('<front>')); Example 2. Redirect to a route path (user page):     return new \Symfony\Component\HttpFoundation\RedirectResponse(\Drupal::url('user.page')); Example 3. To a internal path    return new \Symfony\Component\HttpFoundation\RedirectResponse('/node/17/edit');    OR    return new \Symfony\Component\HttpFoundation\RedirectResponse(\Drupal\Core\Url::fromUserInput('/node/17/edit')->toString()); Example 4. Redirect to Access Denied (403) or Not Found (404) page. 403: throw new \Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException(); 404: throw new \Symfony\Component\HttpKernel\Exception\NotFoundHttpException();

Delete array from value not key.

if(($key = array_search($del_val, $messages)) !== false) {     unset($messages[$key]); } array_search() returns the key of the element it finds, which can be used to remove that element from the original array using unset(). It will return FALSE on failure, however it can return a false-y value on success (your key may be 0 for example), which is why the strict comparison !== operator is used. The if() statement will check whether array_search() returned a value, and will only perform an action if it did.