Skip to content

Instantly share code, notes, and snippets.

@hudo2007
Last active August 6, 2018 13:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hudo2007/f0d0f4e01dace9c5afbbb13025f28f0e to your computer and use it in GitHub Desktop.
Save hudo2007/f0d0f4e01dace9c5afbbb13025f28f0e to your computer and use it in GitHub Desktop.
// Is the current route/path the front page?
if ($is_front = \Drupal::service('path.matcher')->isFrontPage()) {}
// Need to know what the current page's requested path was, as opposed to the route? You can do this:
$current_uri = \Drupal::request()->getRequestUri();
// Need to redirect to a specific page?
use Drupal\Core\Controller\ControllerBase;
class MyControllerClass extends ControllerBase {
public function foo() {
//...
return $this->redirect('user.page');
}
}
// In Drupal 8, if you need to create links on the fly, utilize the Link class
$link = \Drupal\Core\Link::fromTextAndUrl($text, $url);
// Query for some entities with the entity query service.
$query = \Drupal::entityQuery('node')
->condition('status', 1)
->condition('type', 'article')
->range(0, 10)
->sort('created', 'DESC');
$nids = $query->execute();
// If you need to load the actual entities, you can do so a number of ways:
$node = entity_load_multiple('node', $nids);
$nodes = \Drupal::entityTypeManager()->getStorage('node')->loadMultiple($nids);
$node = \Drupal::entityTypeManager()->getStorage('node')->load($nid);
// Link to an entity using the entity's link method.
$author_link = $user->toLink();
// Do the same thing, but customize the link text.
$author_link = $user->toLink('Some Custom Text');
// Given a node object, here's how to determine its type:
$type = $node->getType();
// To get the full user entity of the node's author:
$author = $node->getOwner();
// To get the raw ID of the author of a node:
$author_id = $node->getOwnerId();
// Create an instance of an image using a specific image style, given a path to a file.
$style = \Drupal\image\Entity\ImageStyle::load('yourStyle_image');
$img_path = $user->field_profile_some_image->entity->getFileUri();
$img_style_url = $style->buildUrl($img_path);
// Get $_POST and $_GET parameters
// Post
$name = \Drupal::request()->request->get('name'); // form param
// Get
$query = \Drupal::request()->query->get('name');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment