Where should I put my entity queries? I would like to create a number of entity query methods/functions that I can have easy access to from my entity handlers and controllers.

With Doctrine 2/Symfony 2 you can just attach such methods to the object/entity repository, and then you can call this repository from elsewhere in your code.  Should I follow this recipe in D8, and if so, how?

I see 4 options for where to put the queries:

Put the methods in my custom entity class.  However, out of the box the entity.query service doesn't seem to be available in Drupal\Core\Entity\ContentEntityBase, nor is the service container.  I can use \Drupal::entityQuery('myentity') in a method, but according to the documentation \Drupal:: should only be used in global functions.  I suppose I can override the constructor and inject this class myself, but I would have thought this kind of functionality would be there already.
Put the methods in my custom entity storage handler.  However, if my understanding is correct, this is the place for special queries that aren't well handled by the entity query services.
Inject the querySelector wherever I need it.  See \Drupal\node\Form\NodeTypeDeleteConfirm in Beta 9 for an example.  This is not an appealing option.
Use global functions in my .module file.  That way I can just use \Drupal::entityQuery and be done with it.  See node.module for many sample implementations.  However, this goes against the D8 documentation and against the goal of putting as much as possible into classes.

Any thoughts or references to emerging best practice would not go amiss :)

4 is definitely worse than 1. While \Drupal should be avoided to make unit testing and other things easier, it's still possible, but with calling functions, it's definitely not.

I fear there's no clear answer to this. There is no common standard for this in Drupal 8. A few modules have repository services, for example block.repository. You still have to manually inject that into your controllers, forms and other places, but you can make interfaces that are much easier to mock/test compared to an entity query.


views pass argument for number of records to display to pager contextual filter? Drupal 7.

Is it possible to pass an argument to the contextual filter to limit number of items to display in a View from the UI?

IOW: can you pass an argument that replicates the Number Of Items portion of the Pager?

I have a node form which uses View Fields to display a view of related items. I want to pass an argument via the Field Display which limits the # of records.

If this must be done programmatically, how do I hook into the view 'contextually'... ie. so that the hook overrides the Number Of Items when the visitor is on a particular page (a Node of a certain Content Type.)

I don't think it's possible through the Views interface. But I think you could probably do it through a small custom module.

function MYMODULE_views_pre_build(&$view) {
  if ($view->name == 'view_name') {
    $limit = $arg(1) //where $arg is the argument from your url
    $view->items_per_page = $limit;
  }
}


Hide the block on the "node/add/my_content_type" page I created a content type. I want to show a block on all nodes of this content type except "node/add/my_content_type". I used the following PHP code:

global $node;
$arg1 = arg(1);
if ( $node->type == 'my_content_type') && arg(0) == 'node' && is_numeric($arg1) ) {
  return TRUE;
}
return FALSE;  //default

Result: the block does show on all nodes of this content type, but also show on "node/add/my_content_type".

What I did wrong? Thanks for any help.

Try this

$node = menu_get_object();
return isset($node) && $node->type == 'your_content_type' && arg(2) == '';

Edit: forgot about the third parameter


Need to migrate large, complex Drupal 6 site to Drupal 8. Suggestions for a good way to tackle this if the core Migrate Upgrade doesn't work for me? I have a lot of experience with Drupal 5, 6 and 7 and am just starting with Drupal 8 and I have a large, complex Drupal 6 site that I need to migrate to D8.

I first tried using D8's Migrate Upgrade but it fails part way through. I didn't have high hopes for this to work but I thought if it could at least get the users and bulk content in then that would be a great starting point. It was unable to accomplish either.

So now I'm going to go the export/import route and try to rebuild the data manually. I've done this a number of times upgrading D6->D7 using XML Views to create the export and Feeds to map and import. It looks like Feeds is nowhere near ready for use yet.

Is using core Migrate module along with other contrib modules to right approach? Is what I'm trying to do even possible?

If so, could anyone point me in the correct direction to get started? I've heard migration plugins mentioned before, I'm assuming that I'll have to create custom migration plugins to make this work, correct?

I guess it depends on what your Drupal 6 does and contains. It's not the same if your complex site has lots of content but little functionality (a large blog, for example), or if it has some or lots of content AND complex functionality (news site publishing workflow with rules, complex permissions, etc). Every case is different.

If what you have is lots of content, this could apply: I recently moved lots of content (around 26k items that became nodes) from a Frankenstein WordPress-based app, and found the following approach useful:

Do exhaustive pre-production:

Make an inventory of everything you have in your old site. Mark what is valuable and what is not.
Based on that inventory, design the entities, fields, taxonomy and relationships that will contain them in your D8 instance.
Make a detailed migration map that makes it explicit how each fragment will map to its new location, and what will be left behind / lost.

Then implement your migration tools:

Export your content (the things you decided are worth migrating) to XML, JSON, or whatever format you feel more comfortable with.
Instead of messing with migration modules, I wrote several drush scripts that read from the old app's db, extract items and save them into entities.
The scripts had reset, migrate_all and type-specific migration routines that helped me test again and again and again, until everything was just right.
Automate everything and make it easy to clear and repeat. There are lots of things that can go wrong, but it's not a problem if you can simply ./reset.drush; ./migrate_all.drush.

Hope this helps.


Using own Bootstrap 3 files I would like to know how I can host my own Bootstrap 3 files (js, css) in the Drupal 7 Bootstrap 3 theme. I know I can deactivate CDN hosting inside the theme settings, but I can't get it to work. Can anyone of you guide me through?

I've had success utilizing the Bootstrap Library module.

  This module loads via libraries the Bootstrap files installed on /sites/all/libraries/bootstrap, regardless of the theme you are using. It does nothing else.

  When using Bootstrap themes is particularly helpful to:

  Correct Browser Support issues, installing respond.js.
  Update your Bootstrap version over your current theme options.
  Just to avoid CDN files loading.


add css if url contains I have one node type and two page types for this node.

http://site.com/themes/*

and

http://site.com/years/*

And i want to hide one of the "view-filed" in all "years" pages using the css.

Found this but it doesn't work

function mythemename_preprocess_page(&$variables,$hook) {
  $alias = explode('/',drupal_get_path_alias(request_uri()));
  if($alias[1]== "years") {
   $vars['theme_hook_suggestions'][] = 'years';
  }
}

https://groups.drupal.org/node/130944#comment-762483

I would be very grateful for any help.

Here's how I would do it (but I'm rather new to this, so maybe your approach is better)...

function mythemename_preprocess_page(&$vars, $hook) {
  if (arg(0) == 'years') {
    drupal_add_css(path_to_theme().'/css/years.css');
  }
}


Using hook_query_TAG_alter to add 'OR' queries to EntityFieldQuery I need to use the OR operator on an EntityFieldQuery which I understand can only be accomplished via addTag and hook_query_TAG_alter.

My query at present:

$query = new EntityFieldQuery();
$query->propertyOrderBy('created', 'DESC');
$query->entityCondition('entity_type', 'node')
    ->entityCondition('bundle', 'news')
    ->propertyCondition('status', 1)
    ->fieldCondition('field_pub_year', 'value', $year, '=');
if(isset($_GET['country_id'])){
    $country = $_GET['country_id'];
    $query->fieldCondition('field_related_country', 'target_id', $country, '=');
}
if(isset($keywords)){
    $query->addTag('search');
}
$result = $query->execute();

Without much more than a rudimentary knowledge of Drupal, I would expect that the following function, inserted into my template, might work:

function hook_query_search_alter(QueryAlterableInterface $query){
    $or = db_or()
      ->fieldCondition('title', 'value','%'. $keywords .'%', 'LIKE')
      ->fieldCondition('body', 'value','%'. $keywords .'%', 'LIKE');
    $query->condition($or);
}

Yet, it seems to do nothing...

I'm having equal luck googling this problem. Appreciate any suggestions.  Thanks.

Update:

I moved the alter function into a module and re-wrote it to look like:

function modulename_query_search_alter(QueryAlterableInterface $query){
    $terms = $query->getMetaData('terms');
    $words = "%".$terms."%";
    $or = db_or()->condition('body', $words, 'LIKE')->condition('title', $words, 'LIKE');
    $query->condition($or);
}

but I now get an unknown column body error.  Removing that condition works correctly and results are filtered by title field. Not sure what the deal is with that...

Solution to using 'OR' queries with EntityFieldQuery:

The query, note the addTag() and addMetaData():

$query = new EntityFieldQuery();
$query->propertyOrderBy('created', 'DESC');
$query->entityCondition('entity_type', 'node')
    ->entityCondition('bundle', 'news')
    ->propertyCondition('status', 1);
if(isset($keywords)){
    $query->addTag('search');
    $query->addMetaData('terms', $keywords);
}
$result = $query->execute();
if(isset($result['node'])){
    $nids = array_keys($result['node']);
} else {
    $nids = array();
}
$news = node_load_multiple($nids);

Then, within a module or something, the hook_query_TAG_alter looks like:

function MODULENAME_query_TAGNAME_alter(QueryAlterableInterface $query){
    $terms = $query->getMetaData('terms');
    $words = "%".$terms."%";
    $query->leftJoin('field_data_field_subtitle', 's', 'node.nid = s.entity_id');
    $or = db_or()->condition('s.field_subtitle_value', $words, 'LIKE')->condition('title', $words, 'LIKE');
    $query->leftJoin('field_data_body', 'b', 'node.nid = b.entity_id');
    $or->condition('b.body_value', $words, 'LIKE');
    $query->condition($or);
}

Above example shows how to join custom field tables and query them using 'OR' along with title and body fields.


What drupal function do I use to rename files when saving nodes programatically? Normally when saving a node with the content type form, uploading a file will automatically rename it if the file name is already in the database.

I am creating nodes programatically. Everything works fine, except if the file name is in the database it fails as this is, of course, a unique field.

What function does Drupal use to check if the name already exists and chanages it accordingly? I could write one, but as drupal already seems to handle this perfectly, I dont see a reason to reinvent the wheel. Here is my code for the file saves.

$file = new stdClass();
$file->filename = basename($local_path);
$file->filepath = $local_path;
$file->uri = $local_path;
$file->filemime = $mime;
$file->filesize = filesize($local_path);

$file->uid = $uid;
$file->status = FILE_STATUS_PERMANENT;
file_save($file);

$images[] = array(
'fid' => $file->fid,
'alt' => $page_data['title'],
'title' => $page_data['title']
);

Drupal uses the file_create_filename() function to do that, you can call it like this:

$basename = drupal_basename($local_path);
$directory = drupal_dirname($local_path);
$local_path = file_create_filename($basename, $directory);

$file = new stdClass();
$file->filename = drupal_basename($local_path);
$file->filepath = $local_path;
// etc...


How do I make the administrative UI feel like Joomla? I am working on a way to make a node/add/article page like joomla but but by now I haven't got any remarkable result.
I've written this code to hide a part and print it in another part:

function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  $form['revision_information']['#type'] = 'hidden';
}

but I need to di it in preprosess time in order to have more performance.
so I use this one:

in .module file:

function template_preprocess_article_node_form(&$variables) {
  if (!module_exists('nodeformcols')) {
      hide($variables['form']['additional_settings']);
   }
}

in article-node-form.tpl.php

    <?php if($sidebar): ?>
      <?php print render($sidebar); print_r($variables['form']['comment_settings']);//['additional_settings'])?>
    <?php endif; ?>

but I don't have access to all field in this way.
any alternative or simpler approach will be appreciated.

You were going in the right direction with:

function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  $form['revision_information']['#type'] = 'hidden';
}

However, you have a bug in that code. The code above will modify every form. Instead, use hook_form_FORM_ID_alter to target the specific form.


Indexing image url in search api drupal 8 How to index the absolute image url instead of image uri in search api drupal 8.

Image field formatter renders the image url but there is no option to index the url part.

It looks like that should be available as a field.

If your field name is "field_image", you would select "field_image:entity:uri".  I think that would give you "public://path-to-file-in-public-directory.jpg"

You could add a custom field to your index in a custom module at src/Plugin/search_api/processor:

In this way, you can add any sort of custom value that's not available by default in the fields provided.


Custom simpltest does not run successfully I have written an automated test to create a node of a specific content type.

Here is the code:

class GlueTestingBuySystemTestCase extends DrupalWebTestCase {

  protected $privileged_user;

  public static function getInfo() {
    return array(
      'name' => 'Buying system',
      'description' => 'Buying system test',
      'group' => 'GLUE',
    );
  }

  public function setUp() {
    $this->profile = 'testing';
    // Enable any modules required for the test. This should be an array of
    // module names.
    parent::setUp(array('glue_testing'));

    // Create and log in our privileged user.
    $this->privileged_user = $this->drupalCreateUser(array(
      'administer nodes',
      ));
    $this->drupalLogin($this->privileged_user);
  }

  public function testBuyingSystem() {
    $edit = array();
    $edit['title'] = $this->randomName(8);
    $this->drupalPost('node/add/test', $edit, t('Save'));
    $this->assertText(t('Test Node Type @title has been created.', array('@title' => $edit['title'])));
  }

}

It does appear in the group "GLUE" but when I run the test it gives me the errors:

Failed to set field title to lLzjWnd0
Found the Save button
Found the requested form fields at node/add/test
"Testing Node Type lLzjWnd0 has been created." found

And does not create any node nor created the user.
Any one who have idea that what is wrong in my code?

afaik there's any content-type in the testing site. You need to create it first. For example date module creates one in DateFieldBasic::setUp (surely there're more examples in core, but I've got that one at hand).


How to set alias url for image address in a content type? I added an image field for a content type and its directory is /content_type_image. it works correctly but when I add a content to this content type the uploaded image url on the website is www.mysite.com/sites/all/ .... I mean it is clear where this image is in the server directory. Is there anyway to set an alias url for files and images in order to hide such urls?

You could set your fields to use the private file system. For more information see Working with files in Drupal 7.

With the private file system, the path to files is of the form

www.example.com/system/files/path/to/file.png

The path /system/files is a drupal url, not an actual directory on your file system.

For your drupal file setting you set the path of the private file system to something like /sites/default/files/private so your images are on the server at sites/default/files/private/content_type_image

So the path to the image will be

www.example.com/system/files/content_type_image/path/to/file.png

then when a user hits that url the drupal callback for the system/files will check access control and then load the image from

/sites/default/files/private/content_type_image/path/to/file.png

Using the private file system also means if someone doesn't have access to the content the image is attached to then they cannot browse directly to that file if they can work out the path (and google can't index it) and it means that if you are using revisioning, users cannot see files attached to old revisions of your content, whcih they can with the public file system.

This is probably the best solution you'll get for stopping users from knowing the location of your files and also from accessing files they shouldn't be allowed to.


Composer cannot delete .editorconfig I'm trying to install a third-party library in Drupal 8 by doing 'composer update'. I get this:

I have made it seemingly impossible for it not to be able to delete .editorconfig:

But I still get the same error. What should I try next?

From https://superuser.com/questions/373115/why-cant-i-delete-a-file-where-i-have-group-write-permissions-on

File deletion is based on directory perms, not file perms (*).

That said, check the directory /var/www/html/drupal_2020 permissions.


Unable to set placeholder on password input function customization_form_user_register_form_alter(&$form, &$form_state, $form_id) {
 $form['account']['pass']['#attributes']['placeholder'] = t('Password');
}

I am trying to set placeholder on password field in registration form.

I seted placeholder on username and email, but on password field won't work...

Any help? Thank you!

Wish I'd seen this sooner. You've probably moved on from this problem, but for the benefit of other people seeking an answer to this question: (obviously replace mymodule with the name of your module)

/**
* Implementation of hook_element_info_alter ()
*/
function mymodule_element_info_alter (& $type)
{
  if (isset($type['password_confirm']['#process'])) {
    $func = '_mymodule_process_password_confirm';

    $type['password_confirm']['#process'][] = $func;
  }

  return $type;
}

/**
 * Do a bit of processing for the password_confirm element.
 * Original processing happens in expand_password_confirm()
 */
function _mymodule_process_password_confirm ($element)
{
  // Use the element's title, or create a custom title with the t() function.
  $element['pass1']['#attributes']['placeholder'] = $element['pass1']['#title'];
  $element['pass2']['#attributes']['placeholder'] = $element['pass2']['#title'];

  // Remove these lines if you want to keep the field labels.
  $element['pass1']['#title_display'] = 'none';
  $element['pass2']['#title_display'] = 'none';

  return $element;
}


Load an entity from a URI I have a URI 'entity:node/27' and I want to load this entity, but I cannot find the correct helper function or class to use.

I do not want to explode the string or regex the string, I am fairly sure there is a function for this.

$params = Url::fromUri("internal:" . $source_uri)->getRouteParameters();
$entity_type = key($params);
$entity = \Drupal::entityTypeManager()->getStorage($entity_type)->load($params[$entity_type]);


Problem creating a node with custom PHP code I wrote the following custom PHP code to create a node

<?php
define('DRUPAL_ROOT', getcwd());
require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

global $user;
$title1=$node->title;
$node = new stdClass;
$node->type = 'Campaign_PlayerList';
$node->title = $title1;
$node->uid = $user->uid;
$node->language='und';
$node->field_cmp_playerid['und'][0]['value']=$user->uid;
$node->field_cmp_userscore['und'][0]['value']=1;
$node->field_cmp_usersupport['und'][0]['value']=1;
node_object_prepare($node);
node_save($node);
?>

The values for field_cmp_playerid and field_cmp_attend_time are not saved.

$node->field_cmp_playerid['und'][0]['value']=$user->uid;

doesnt work and field_cmp_attend_time is the same too.

What could the problem be?

Here is a screenshot of the field management form for the Campaign Playerlist content type:

It looks from your image like field_cmp_playerid is a user reference field, which means the column name won't be value, it will be uid. Try this code:

$node->field_cmp_playerid[LANGUAGE_NONE][0]['uid'] = $user->uid;

The field_cmp_attend_time field probably isn't getting saved because it's missing from your code. It's just a date field so the column name will be value. If the date field you're using is a UNIX timestamp type, for example, the code would look like this:

$node-> field_cmp_playerid[LANGUAGE_NONE][0]['value'] = REQUEST_TIME;

Just in case you want to update your field_cmp_id as well, it's a node reference so the column name becomes nid:

$node->field_cmp_id[LANGUAGE_NONE][0]['nid'] = $nid;


Node count for taxonomy terms How can I display the node count values for taxonomy terms with sorting the result list in descending order of node count?

Create a taxonomy view
Add node group in relationship
Add term name and node nid fields for display
Enable aggregation in "Other" section (Use aggregation: Yes)
Click nid field settings icon, choose group type "count".

Find the export of views that worked for me.

$view = new view;
$view->name = 'term_node_count';
$view->description = 'Displays node count values for terms';
$view->tag = '';
$view->base_table = 'taxonomy_term_data';
$view->human_name = 'term_node_count';
$view->core = 7;
$view->api_version = '3.0-alpha1';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Defaults */
$handler = $view->new_display('default', 'Defaults', 'default');
$handler->display->display_options['use_ajax'] = TRUE;
$handler->display->display_options['group_by'] = TRUE;
$handler->display->display_options['access']['type'] = 'none';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'full';
$handler->display->display_options['pager']['options']['items_per_page'] = '100';
$handler->display->display_options['pager']['options']['offset'] = '0';
$handler->display->display_options['pager']['options']['id'] = '0';
$handler->display->display_options['pager']['options']['expose']['items_per_page_options_all'] = 0;
$handler->display->display_options['style_plugin'] = 'table';
$handler->display->display_options['style_options']['columns'] = array(
  'name' => 'name',
  'nid' => 'nid',
);
$handler->display->display_options['style_options']['default'] = '-1';
$handler->display->display_options['style_options']['info'] = array(
  'name' => array(
    'sortable' => 0,
    'default_sort_order' => 'asc',
    'align' => '',
    'separator' => '',
  ),
  'nid' => array(
    'sortable' => 0,
    'default_sort_order' => 'asc',
    'align' => '',
    'separator' => '',
  ),
);
$handler->display->display_options['style_options']['override'] = 1;
$handler->display->display_options['style_options']['sticky'] = 0;
/* Relationship: Taxonomy: Node */
$handler->display->display_options['relationships']['nid']['id'] = 'nid';
$handler->display->display_options['relationships']['nid']['table'] = 'taxonomy_index';
$handler->display->display_options['relationships']['nid']['field'] = 'nid';
$handler->display->display_options['relationships']['nid']['required'] = 0;
/* Field: Taxonomy: Term */
$handler->display->display_options['fields']['name']['id'] = 'name';
$handler->display->display_options['fields']['name']['table'] = 'taxonomy_term_data';
$handler->display->display_options['fields']['name']['field'] = 'name';
$handler->display->display_options['fields']['name']['alter']['alter_text'] = 0;
$handler->display->display_options['fields']['name']['alter']['make_link'] = 0;
$handler->display->display_options['fields']['name']['alter']['absolute'] = 0;
$handler->display->display_options['fields']['name']['alter']['trim'] = 0;
$handler->display->display_options['fields']['name']['alter']['word_boundary'] = 1;
$handler->display->display_options['fields']['name']['alter']['ellipsis'] = 1;
$handler->display->display_options['fields']['name']['alter']['strip_tags'] = 0;
$handler->display->display_options['fields']['name']['alter']['html'] = 0;
$handler->display->display_options['fields']['name']['element_label_colon'] = 1;
$handler->display->display_options['fields']['name']['element_default_classes'] = 1;
$handler->display->display_options['fields']['name']['hide_empty'] = 0;
$handler->display->display_options['fields']['name']['empty_zero'] = 0;
$handler->display->display_options['fields']['name']['link_to_taxonomy'] = 1;
/* Field: Node: Nid */
$handler->display->display_options['fields']['nid']['id'] = 'nid';
$handler->display->display_options['fields']['nid']['table'] = 'node';
$handler->display->display_options['fields']['nid']['field'] = 'nid';
$handler->display->display_options['fields']['nid']['relationship'] = 'nid';
$handler->display->display_options['fields']['nid']['group_type'] = 'count';
$handler->display->display_options['fields']['nid']['label'] = 'Count';
$handler->display->display_options['fields']['nid']['alter']['alter_text'] = 0;
$handler->display->display_options['fields']['nid']['alter']['make_link'] = 0;
$handler->display->display_options['fields']['nid']['alter']['absolute'] = 0;
$handler->display->display_options['fields']['nid']['alter']['trim'] = 0;
$handler->display->display_options['fields']['nid']['alter']['word_boundary'] = 1;
$handler->display->display_options['fields']['nid']['alter']['ellipsis'] = 1;
$handler->display->display_options['fields']['nid']['alter']['strip_tags'] = 0;
$handler->display->display_options['fields']['nid']['alter']['html'] = 0;
$handler->display->display_options['fields']['nid']['element_label_colon'] = 1;
$handler->display->display_options['fields']['nid']['element_default_classes'] = 1;
$handler->display->display_options['fields']['nid']['hide_empty'] = 0;
$handler->display->display_options['fields']['nid']['empty_zero'] = 0;
$handler->display->display_options['fields']['nid']['link_to_node'] = 1;

/* Display: Block */
$handler = $view->new_display('block', 'Block', 'block_1');
$translatables['term_node_count'] = array(
  t('Defaults'),
  t('more'),
  t('Apply'),
  t('Reset'),
  t('Sort By'),
  t('Asc'),
  t('Desc'),
  t('Items per page'),
  t('- All -'),
  t('Offset'),
  t('node'),
  t('Term'),
  t('Count'),
  t('Block'),
);


Content Type vs. Taxonomy | Example TV Series As this is my first post here I don't know if I do everything right. Please forgive me.

So, my plan is to build a website with many categories and these than contain posts. To explain the stuff in the easiest way I decided to use Series and Episodes.

Serie A:

Episode 1
Episode 2
Episode 3

Serie B:

Episode 1

For my use I also want to be able to decide what exactly an episode is. For example is it an normal one or just a 20 minute special and should be displayed like this:

Serie A:

Author:
Year:
(more stuff here)
Episodes: (Headline)

E1 (Link to this Episode)
E2 (Link to this Episode)

Special Episodes: (Headline)

E1 (Link again)
E2 (Link again)

The problem here is that I don't know if I should create this with Content Types or Taxonomy.

A) So one Content Type for Serie and another one for Episodes. Both with the needed fields. But the problem is here I don't know how to join/connect them properly.

B) Creating a Taxonomy called "Series" and adding all Series into it. Than a Content Type "Episodes" with setting a Tag to connect the Episode to the right Series. The problem I could get here is for example when adding something like genre. A Taxonomy would get a list of Genres like Action, Comedy and so on.

Another point would be accessibility. It should be possible to search for Series include/exclude genres and also searching for fields like year, episode-count of a series.

At last is it possible to create Custom Types where for example a javascript is loaded in the background that parses text from a input text area?

I hope you understand my goal with this example and can tell me the proper way. Thanks for everything.

I would do it the A) way and use Entity reference module to "link" episodes to series. That way you can use watever fields you want in your content types (including taxonomy for genre for example).

  The Entity Reference Module is used to relate entities (nodes, terms,
  users, etc...) to one another.

After that, you can display content types with Views showing Series with list of episodes.


Drush on windows 10 gives an error - Command pm-update needs a higher bootstrap level to run When I try to use drush to work on my local site I get this error:

Command pm-update needs a higher bootstrap level to run - you will need to invoke drush[error]
from a more functional Drupal environment to run this command.
The drush command 'up' could not be executed.                                          [error]
Drush was not able to start (bootstrap) the Drupal database.

I have wamp server installed on windows 10. I also have composer and drush installed on windows 10. I have the user environment path set up correctly. I am in the drupal directory.  I have my local drupal site set up but I cannot get drush to work. I have been crawling the internet and can only find older solutions.

My user environment path for drush is C:\Users\Name\AppData\Roaming\Composer\vendor\drush\drush

My user environment path for composer is
C:\Users\Name\AppData\Roaming\Composer\vendor\bin

When I type drush status I get

$ drush status
 Drupal version         :  8.1.8
 Site URI               :  http://default
 Database driver        :  mysql
 Database hostname      :  localhost
 Database port          :  3306
 Database username      :  root
 Database name          :  tekopolis
 PHP configuration      :  C:\wamp64\bin\php\php7.0.4\php.ini
 PHP OS                 :  WINNT
 Drush script           :  C:\Users\Anthony\AppData\Roaming\Composer\vendor\drush\drush\drush
 Drush version          :  8.1.3
 Drush temp directory   :  C:\Users\Anthony\AppData\Local\Temp
 Drush configuration    :
 Drush alias files      :
 Drupal root            :  C:\wamp64\www\tekopolis
 Drupal Settings File   :  sites/default/settings.php
 Site path              :  sites/default
 Sync config path       :  sites/default/file/config[...]/sync

Does anyone know how to get drush working on windows 10 without acquia dev?

My experience is that these kind of tools are more easier to install on a Linux based system (ports of this programs to Windows are always limited in their capabilities). Luckily, the Windows 10 Anniversary update includes "Ubuntu on Bash on Windows 10", which allows you to natively run terminal-based Linux applications and Bash commands in Windows. Using this feature you can simply follow the native tutorials/install instructions.

To install this Bash shell in Windows 10 (after installing the Anniversary Update), you have to enable the developer mode (go to Settings > Update and Security > For developers). Then in the start menu search for the application: "Turn Windows features on or off" and with this application enable the "Windows Subsystem for Linux (Beta)". A reboot of your computer will follow and after this search in the start menu for "Bash" and follow the instructions. Once completed, you can use the program "Bash on Ubuntu on Windows" to start up your Linux shell.

With apt-get you can install php5 (don't forget to use sudo here), from there you can follow the install instructions of Composer and/or Drush.


Boost not caching non-latin urls I have set clean urls and Boost work great with latin urls like www.mysite.com/yes-this-works.

But when the url have non-latin words like www.mysite.com/μπου-χου this fails.

Any way to solve this?

From my Plesk i see the page name correct but from filezilla the greek characters show ÎµÏÎ¹ÎºÎ¿Î¹Î½ÏÎ½Î¯Î±_.html like this.

Drupal 7

I suspect your host is not using UTF-8 for their filesystem (rather rare these days, for example, in the early 2000, I've seen hosts using ISO-8857-7 or CP-1253 encodings for their files, because that's what Microsoft Windows did). Alternatively, Plesk or FileZilla is not using UTF-8, but that would only be a problem displaying the file names and Boost should work.

If it is because of the filesystem of your host, you could try to forward-port this old patch from 6.x-1.x which would convert with iconv the filename before saving it to disk:
https://www.drupal.org/node/797136

To detect the encoding used on the filesystem, type the command "locale". It should display:

LANG=en_US.utf8

If it display anything else than utf8, such as iso8859-xx or cp-xxxx, that would probably be the source of the problem (and will require patching Boost).

Boost does store on disk the filename unescaped, e.g. it stores it in unicode, not by escaping the characters (ex: %CE%BC%CF%80%CE%BF%CF%85).

Here is a test using Greek, Cyrillic and Latin accents:
https://www.bidon.ca/fr/μπου-χου-добър-ден-éàĉç


Multiple URL aliases for same node I have the following URL aliases for the same node.

/products/single-room/product-listing/wall-mount
/products/multi-room/product-listing/wall-mount

I have two details button Single & Multi-rooms; Single Room button has a link to /products/single-room/product-listing/wall-mount and Multi Room button has a link to /products/multi-room/product-listing/wall-mount. When I click on Single Room or Multi Room Button, both will redirect to /products/multi-room/product-listing/wall-mount; when I delete the multi-room alias the single-room button will go to /products/single-room/product-listing/wall-mount which is correct but multi-room will give the 404 not found error.

What I need is to have two aliases for same node: When users click on single, they are redirect to the same node with /products/single-room/product-listing/wall-mount as URL; when users click on multi-room, they get redirected to the same node with /products/multi-room/product-listing/wall-mount as URL.

Please help me out?

Disable the Global Redirect module.  This module is specifically built to do the behavior you are describing, because search engines like it.

Unless you are using those path segments as contextual filters somewhere, there should be no reason to do this.  If you are using those path segments as contextual filters, there should be a better way to do this.  Either a view page or a panel page would be able to hold that page open, use wildcards for those address segments, and get the functionality that you want without having to upset the search engine bots.


View that uses both taxonomy terms and title(or nid) in contextual filters Is it possible to create a view that uses both taxonomy terms and the node title or nid as contextual filters?

Ideally this would mean that you could have one view that just handled the taxonomy terms eg. the parent-taxonomy-term/child-taxonomy-term view would display all the nodes matching those taxonomy terms and parent-taxonomy-term/child-taxonomy-term/node-title would display a different view with more information on the specific node returned.

Is such a view possible and if so how would i set it up (all my experiments at this have failed)?

The reason I require this is that I wish a view of the same node to be accessible via a number of different taxonomies. I am creating a store where users can see the same gold diamond ring by navigating on the main dropdown menu via 'Jewellery > Rings', 'Gemstones > Diamond' or 'Metal > Gold'. While the user is navigating in this way the breadcrumb trail and url are looking good 'jewellery/rings' etc. But when a product is clicked on and its node is viewed it has its own url that can only fit the pattern of one of the taxonomies. So the breadcrumb trail would suddenly change when getting to the product via another taxonomy.

I wasn't able to find a neat solution to this problem.

What I ended up doing was manually creating a page view from each taxonomy e.g. metals/gold/% and passed it the node title through contextual filters. This meant I was able to create a view of the correct product and the Easy Breadcrumb trail still looked good and a single product may exist in multiple breadcrumb trails. This works but isn't an elegant solution.

It would be great to find a solution to this that didn't need manual creation of page views. So any further thoughts on this are appreciated.


How to create a redirect to point to the user's id? I'd like to create a redirect so when the user hits mydrupal.com/my-account its redirected to mydrupal.com/users/3

I'm using Pathauto and I know I can go to admin/config/search/path/add to add the redirect but I can't get it to point to the user id as variable. For instance, in the existing system path option I thought I could add users/[uid] but that didn't work.

Any suggestions?

Instead of redirecting the mydrupal.com/my-account to particular user ID as mydrupal.com/users/3

You should redirect them to mydrupal.com/user which will lead them to thier profile page if the user is logged in.


drupal_render() and formBuilder's getForm What exactly is the best way to accomplish this? I can pass the $form object returned from getForm to drupal_render() and get the correct themed output fragment but the API docs say this function will be deprecated in D9 and to use the renderer service instead.

When I use:

\Drupal::service('renderer')->render($form)

I get

  You have requested a non-existent service "renderer". Did you mean one of these: "render_html_renderer", "html_fragment_renderer",
  "html_page_renderer"?

When I use:

\Drupal::service('render_html_renderer')->render($form)

I get a valid object with a protected content() method, which contains the string, but I can't seem to find any valid public functions to access this.

I can normally use the route builder to point to a form controller that I've created but, in this instance, I just want to pull an existing form, get the HTML content, and display it - hopefully as a variable in a preprocess function. I don't necessarily want to create a block, since I probably won't be reusing it.

What is the best way to do this? Keep using drupal_render() until D9? Can somebody point me in the right direction?

There are almost no reasons to manually call drupal_render(), you can use/return render arrays almost anywhere, controllers, blocks and also in twig templates.

If you do $variables['form'] = $your_form;in preprocess, then {{ form }} in your template should just work.


Extracting field values (of certain entity type and bundle) from form/form_state I have fields of entity type foo and bundle name bar. These fields get rendered as an HTML input inside a form. There are other fields present on the form, but I'm only interested in foo/bar ones.

The number of foo/bar fields is dynamic (as are the names). I need a way to extract their name/value pairs.

Here's my situation in code:

function submit($form, &$form_state) {
  // Get all the submitted data that is backed by a field of
  // an entity type 'foo' and bundle 'bar'
}

Thanks.

All the field values are in $form_state['values']. See: drupal_form_submit.

You might also be interested in using hook_form_BASE_FORM_ID_alter instead of hook_form_alter to target a particular content type. Your function would look like: 'mymodule_form_' . $form_id . '_alter'.

Or at least an:

if ($form_id == 'your_content_type') { // add new submit handler }

in hook_form_alter.

Also use LANGUAGE_NONE, without quotes, instead of 'und' ie $some->var[LANGUAGE_NONE]['value'];

Also for future reference:
Install the Devel module, use dpm($form_state,'$form_state');

When you use dpm you get nice dumps of variables that look like:
http://goo.gl/qIf6p


Trigger cron internally using PHP The server my site is on cannot use curl, wget or lynx to call the external cron address (eg http://example.com/cron/cron_key)

Is it possible to use php to 'run' the cron from inside the server.

I'm was thinking something like php -f /home/docroot/core/Drupal/Cron.php with a query string for the cron key, but I notice there isn't a query string as in Drupal 7.

I cannot use Drush since it's not installed on the prod servers.

I also cannot use a third party external cron service.

Any ideas?

a way to do that :

create customcron.php in the drupal root with the content :

<?php

use Drupal\Core\DrupalKernel;
use Symfony\Component\HttpFoundation\Request;

$autoloader = require_once 'autoload.php';

$kernel = new DrupalKernel('prod', $autoloader);

$request = Request::createFromGlobals();
$response = $kernel->handle($request);

// Load cron service and run cron.
\Drupal::service('cron')->run();

$kernel->terminate($request, $response);

then run :

php customcron.php

i would not let the file customcron.php in the root because anybody could then execute it from the browser.

A simple way to avoid that is moving the file customcron.php to drupal root only for the time you execute it or maybe have an unguessable file name instead of customcron.php


Disallow access to member files when they are in public file system I have case where I want to make it impossible for the users to access file directly (http://www.mydomain.com/members/file.pdf), but want to allow downloading this file only if link is displayed on Drupal page, that user has privilege to see.

I know it can be easily done if those files are outside webroot and defined as private filesystem.

But is there any alternative solution, Apache way, php/Drupal way to achieve this for files that are not in private filesystem?

Those member files are of various extensions, so I could not just disallow by extension.

I have asked simmilar question before, but as I understood, proposed hook_file_download way works only for private file system setup.

To Apache or any other web server, seeing

<img src="http://www.foo.com/bar.jpg">

in html and a user typing http://www.foo.com/bar.jpg into their browser directly is basically the same thing so the quick answer is "no, not really, at least from a drupal standpoint."  You could obfuscate the path with some javascript trickery but that's about it.

Now, you could look into Apache referrer access, a quick link about allowing access from specific referrers might shed some possibilities on it for you, but now you are certainly outside of drupal :)


Add css style to theme in module I'm writing a module that contains a star field. Now I'm placing the stars using the viewElements function of my field formatter. Everything is working. But I need to place some syling to the field output. Can I send some css styling to the active theme using my module?

My field formatter looks like:

public function viewElements(FieldItemListInterface $items, $langcode) {
    $element = [];

    foreach ($items as $delta => $item) {
    $total = $item->rating/2;

    $stars = '';

    //Place colored stars
    for($i =0; $i < floor($total); $i++)
    {
        $stars .= '';
    }

    //Place half star
    if(floor($total) != $total)
    {
       $stars .= '';
    }

    //Place open stars
    for($i = ceil($total); $i < 5; $i++)
    {
        $stars .= '';
    }

      $element[$delta] = array(
        '#markup' => $stars,
      );
    }
    return $element;
  }

The only thing that I'm missing is the css style that looks like:

.star {
    font-size: x-large;
    width: 50px;
    display: inline-block;
    color: gray;
}
.star:last-child {
    margin-right: 0;
}
.star:before {
    content:'\2605';
}
.star.on {
    color: gold;
}
.star.half:after {
    content:'\2605';
    color: gold;
    position: absolute;
    margin-left: -20px;
    width: 10px;
    overflow: hidden;
}

To do this, you need to create a *.libraries.yml file, with the path to your css file in it:

MODULE.libaries.yml:

star-field:
  version: Version
  css:
    theme:
      path/to/stylesheet.css: {}

Then you can attach that library to your element:

$element['#attached']['library'][] = MODULE/star-field;

This can be overridden in a theme if/when necessary, so this styling should be considered the default styling that the module creates.

More reading: https://www.drupal.org/docs/8/creating-custom-modules/adding-stylesheets-css-and-javascript-js-to-a-drupal-8-module


Exporting nodes except for specific fields I'm wanting to transfer a set of content from one drupal site to another - the field structure etc is the same but there are a couple of requirements:

1) I need to be able export only nodes of a specific content type.
2) I need to be able to exclude certain fields from being exported.

I've had a look at a few modules - Node Export, Backup and Migrate - but these don't appear to handle the exclusion of certain custom fields.

Could anyone point me in the right direction of a module that can do this?

Thanks!

Use feeds -> https://www.drupal.org/project/feeds for custom export / import of nodes, users, taxonomy terms or simple database records


How to show applied filters in a View? I have defined some contextual filters to a View, i need to show a string like "Applied filters: filter_name1:xyz, filter_name2:ykx".
Which is the cleanest way to do it in Views3?

The best way is to implement a template_preprocess_views_view.  The view object is available as $variables['view'].  kpr this to find the property that has the filters in it.  Process them into something readable.  Then set a new entry in $variables.

Then make a new views-view.tpl.php, and name it appropriately for your view (edit the view, click Theme: Information to see the template suggestions), and add the print statements to output the filter info.


nodeaccess configuration problems I created a view that I called gallery (in Drupal 7) which links to a number of sub galleries (http://quaaoutlodge.com/gallery). The sub galleries are of content type gallery.
So, I installed the nodeaccess module because the galleries and the gallery main page should only be accessible by my GalleryViewer  (and GalleryEditor) so I set the Gallery node type up accordingly (no checks for anonymous user). I saved grants and rebuilt permissions. Now, even tho I did the above, any user caan browse my gallery types that are linked from http://quaaoutlodge.com/gallery. Why is this? What am I doing wrong? :o

You have to set the permission inside the Views BLOCK SETTINGS > Access


wishlist and commerce bundle i have commerce_bundle module installed, and we use it to implement (shop the look) concept, the problem is that we already use flags to implement wishlist for separate products and view the items added to wishlist by a view, now we need to allow bundles to be added to wishlist, but we can't view it in the same view that render the products items in wishlist. are there any ideas to solve this problem?

Try this sandbox which reimplements Wishlists as orders. It won't work out of the box since it only hooks into the main add to cart form, so you'd need to add that in... but it's an order so you can theme it like a regular cart/order form.


Convert Media tags to markup I imported the content of a website from Drupal 7 to Drupal 8, but some nodes contain something like this.

[[{"type":"media","view_mode":"media_large","fid":"403","attributes":{"alt":"","class":"media-image","height":"187","style":"display: block; margin-left: auto; margin-right: auto;","typeof":"foaf:Image","width":"480"}}]]

In Drupal 7 this is fixed by setting the filter "Convert Media tags to markup", which does not exist in Drupal 8.

How can I fix this in Drupal 8?

Your media token snippet is from the Drupal 7 Media library and WYSIWYG integration.

I don't know if that integration exists yet in Drupal 8. It would apart of, listed as a project of the Media Entity project for drupal 8.

EDIT

You want to see the Entity Embed module for Drupal 8 which supports WYSIWYG editors. I don't know if they offer a migration of old media content into this new module though.

These modules were found by these blog resources and DrupalCamp sessions which have a Youtube video showing these modules in action:

https://drupalsquad.com/drupal-8-media-handling
https://amsterdam2014.drupal.org/session/drupal-8-media  Media Ecosystem in Drupal8 drupalcamp youtube video can be found at https://www.youtube.com/watch?v=Hd-jPrEcAn8


Document has expired I created my own module and it has a form that is created using the Form API.  The problem is that when a user clicks on a link on the form after hitting the submit button, and goes to the link, and then hits the BACK button on their browser, then the user gets a message of "Document expired.  The document is no longer available".

How can I make it so that the user can hit their BACK button and be taken back to the form?

A better solution might be to add a link on the page that the user sees after the form, that takes them back to the form. You might need to put back in some session values. If the form was already submitted, you'll want to decide whether to load their submission or take them to a blank, new form.


The AMP module requires the PHP AMP library I installed Drupal 8 and amptheme. I downloaded the AMP module and the library files. When I tried to install the module, I got the following message:

  The AMP module requires the PHP AMP library.

The library files are in libraries/amp-library. I think the library location is incorrect.

How do I fix the error?

This module requires the use of Composer to install its libraries. You can learn more about Drupal and Composer on drupal.org's documentation hand book Installing modules' Composer dependencies in Drupal 8. The AMP module project page also has a brief description of how to install on Drupal 8.0.5.


How to convert URL aliases back to node ID I wonder how to convert a URL path back to it's own node (node/nid). I wish to get the original node ID from a given path. e.g.

path = "news/my-news"

..and trace it back to get it's own original URL, e.g. 65. Please advise. Thanks.

You can use drupal_get_normal_path function.

  Return value

  The internal path represented by the alias, or the original alias if
  no internal path was found.


Adding RSS feed view I was trying to add a RSS feed view in Drupal 8. I selected feed row style for Fields, and clicked on Save and edit, but I got this message.

  Row style plugin requires specifying which views fields to use for RSS item.

What does this message mean?

The error just means that the feed row style require fields, but the view being created doesn't have fields.
The error is confusing, since I can create a view like that and add a feed.

There are two ways for not getting that error: The first one is selecting Table as Display format, and Content as Feed row style, in the page to create a new view.

In this way, I got the view without errors.

The second way is creating a view without telling the Views module to include a feed. It will be created after.

On the page shown to create a view, I don't select Include an RSS feed, and I click on Save and edit.

On the next page, I click on +Add and choose Feed on the drop-down list that appears. (I cannot show it on the screenshot, but I can choose between Attachment, Block, Embed, Entity reference, Feed, and Page.)

On the next page, on the bottom, you will get the following error.

  Display "Feed" uses a path but the path is undefined.

Click on No path is set, and enter the path you want for the feed.

This is close to what the Views module gives you, with an exception: The feed is not attached to any page, since it says Attached to: None.

Click on None and select to which pages the feed must be attached.


Reasons for limited login duration? On a site I am working on, I get logged out almost daily. I assume there is a limit on the login duration.

I already set session.gc_maxlifetime to a very high value, using ini_set() in settings.php. This setting is visible in /devel/phpinfo.

Is there anything else that limits the login duration?

EDIT: The original problem occured on a Drupal 7 site. But I imagine that the same problem and solution would apply in Drupal 8. Maybe someone wants to confirm this in the comments.

TLDR

Look for session.gc_maxlifetime and session.cookie_lifetime.

Inspect your session cookies with browser developer tools

To debug this, one can use browser developer tools to inspect cookie expire date.

The cookie that is relevant for login has a key = "SESS...".

An "Expire" of "Session" means that the cookie expires when the browser is closed. Most of the time this is not what you want!

You can open other Drupal sites (e.g. drupal.org) and compare the cookies. It can also be interesting to compare with other Drupal sites installed on the same server (e.g. your localhost), and with different browsers. This can give you clues whether this is a problem with your global server config or with your specific site.

Check current PHP config in Drupal

Open admin/reports/status/php for current phpinfo.
Look for session.cookie_lifetime and session.gc_maxlifetime.

A value of session.cookie_lifetime === 0 causes the Expire === Session for the session cookie. This means that closing the browser causes a logout. Otherwise, the number specifies seconds of login duration.

See http://php.net/manual/en/session.security.ini.php for more information.

Inspect your code and server config

ini_set() statements in your Drupal's sites/*/settings.php
Your .htaccess file.
Your server settings, e.g. in /etc/apache2/apache2.conf, or /etc/apache2/sites-enabled/... grep is your friend.

Also look for modules that modify login duration, such as https://www.drupal.org/project/autologout or https://www.drupal.org/project/autologout.

Fix.

Decide on suitable values for session.gc_maxlifetime and session.cookie_lifetime, and use one of the places mentioned above to set these values.

For the project I am working on, I decided to set both values to 1209600 === two weeks.
(2 * 7 * 24 * 60 * 60 seconds === 1209600 seconds)

About the values

For more information on these values, see

https://blogs.oracle.com/oswald/php:-sessiongcmaxlifetime-vs-sessioncookielifetime (note: the article says 60 = 1h, which afaik is wrong. 60 would be 60 seconds = one minute. For one hour it would have to be 60 * 60 = 3600.
http://www.php.net/manual/en/session.configuration.php#ini.session.gc-maxlifetime
https://stackoverflow.com/questions/5511794/the-question-between-session-gc-maxlifetime-and-session-cookie-lifetime

From the information I found, and my understanding of it:

session.gc_maxlifetime is a server-side limit, but session.cookie_lifetime is a client-side limit.
Even when session.gc_maxlifetime has run out, there is a chance for the session to stay alive for a bit longer, because the garbage collection only happens every once in a while (depending on session.gc_probability and session.gc_divisor).
A browser or other client could ignore or override the cookie lifetime, and keep the session alive longer than intended. I assume the expire date is also stored on server side, so I assume this won't help. See https://superuser.com/questions/442218/automatically-override-cookie-expiration-on-chrome where this is being discussed.


How to replace an unfiltered Search API results view with custom text? Setting: using the search_api_views module, I have created a view with an exposed fulltext search filter. In addition, I have lots of facets for the corresponding search index in a separate block (via the search_api_facetapi module). Searching and filtering works well.

Question: When no facet item is selected and no fulltext search is used, then all indexed nodes are shown in the view as search results. How can I replace this full nodes list with a custom text (e.g., “Enter a search term or select a facet item to filter our products.”)? In other words: how can I hide the results list if and only if no search filter (facet or fulltext) is applied?

Here’s how I solved this:

First I implemented hook_views_post_build. Note, that I could have probably used most other views processing hooks, too, as I’m only adding custom build information.

/**
 * Implements hook_views_post_build().
 */
function MY_MODULE_views_post_build(&$view) {

  // If there is no explicit search being done, then we show a message instead
  // of all search results. We still have to run the search under the hood so
  // that we have correct search facets available. Therefore we could have also
  // used most other views processing hooks here.
  if ($view->name === 'MY_VIEW_NAME' && empty($view->exposed_input['f'])
       && empty($view->exposed_input['search'])) {
    $view->build_info['MY_MODULE_show_message'] = TRUE;
  }
}

Then I added my custom message to an overridden views-view.tpl.php using the previously defined build info variable:

<div class="<?php print $classes; ?>">

  <?php if (isset($view->build_info['MY_MODULE_show_message'])): ?>

My Custom Message

Enter a search term or select a facet item to filter our products.

  <?php else: ?>

  <?php endif; ?>

<?php /* class view */ ?>


Disable (Close) webform form dynamically We would like to be able to put our site into a "read-only" mode prior to doing major releases etc. I was hoping to achieve this for forms on the site by enabling or disabling my custom module, which I could easily do from drush during our release process.

The module would use a hook to disable all forms and show the closed message instead.

This is what I had so far:

<?php

use Drupal\Core\Form\FormStateInterface;

/**
 * Implementation of hook_form_alter().
 *
 * Disables any webforms when this module is active. Include a custom config key
 * called `exempt_from_maintenance_mode` with any value to allow your form to
 * remain open during maintenance.
 *
 * E.g.
 *     exempt_from_maintenance_mode: 1
 *
 * @SuppressWarnings(PHPMD.UnusedFormalParameter)
 */
function yvw_maintenance_form_alter(&$form, FormStateInterface $form_state, $form_id)
{
    // Check for custom config key
    if (array_key_exists('#exempt_from_maintenance_mode', $form)) {
        return;
    }

    // Load the webform entity. This should prevent the module from disabling
    // all forms across the site.
    $webform_id = $form['#webform_id'];
    $webform = \Drupal::entityTypeManager()->getStorage('webform')->load($webform_id);

    // Only disable the webform if its currently enabled
    if ($webform->status() === true) {
        $webform->setStatus('closed');
        // Does not save. Maybe we need a different hook.
    }
}

The problem is I would need to call $webform->save(); which would permanently close the form. I was hoping there was a hook where I could modify the form configuration only at runtime, and not persist any of the changes to the database. But I haven't been able to find any hooks that look like they would do it.

I had a look at Close a webform when total seats reach a maximum which is close to what I want, but it appears that would only run on submission, and also permanently closes the form.

Webforms are config entities and you can use hook_webform_load() to close the webform before it is rendered and then altered. Instead of closing and resaving the webform, you can call $webform->setPropertyOverride('status', FALSE); which will safely close the webform and prevent it from being permanently closed.


Looking for the right modules for user group management I am creating a site that works similarly to Groupon with D7, and I am having trouble finding the right modules to deliver the functionality.

I need to create different user groups: buyer and seller.

For the buyers I need to store their name, geo-location, and email address.

For sellers I need to store the name of their business, email, geo-location, and I want the sellers to be able to create a list of offers(nodes) linked to their business.

My initial thought is to find a module that enables custom field for user profile. I also need a separate registration & login page for each group, and assign new sign-ups to the appropriate group ( buyer vs seller) based on which page they use to register. What modules would you recommend in order to fulfill these requirements?

I would suggest to manage this by using roles.
Create two different roles: Buyer and Seller
As both roles have the same mandatory fields, it wont be an issue for you. Additionally, you can customise additional fields and rights for sellers.


Passing control to another controller In a module I use forms. On special occasions I have to start another form in another module.
In this case I would like to do the following:
1 pass the control from the form to the Controller(1) of the module
2 this Controller(1) should then pass the control to the Controller(2) of the other module
3 this Controller(2) should start the desired form

Step 1 and 3 I can perform

Step 2 is still a problem because I read that a controller always must render output.
I do not want to create a new instance of Controller 2 in Controller 1.

Found out that you can return a redirect to another controller. The parameter handling is not yet clear to me, I cannot find a good tutorial about the usage ofRedirect and passing parameters with it.

My aim is the implementation of a Mediator Pattern. Best practice to do this is using the Event Dispatcher Mechanism.
This is explained here.

A good example of implementing the mechanism, even create your own event type (above the existing types of Drupal) is described here


How to change access callback for content create? I want to allow each user to create a specific node type only once.I know that I must use hook_menu_alter and change access callback to my own callback function.But using this way Drupal's main access callback is overriden and it will skip permissions defined in permissions page.

Is there a way to call my own access callback after main access callback is called?

Absolutely. Just replace original access callback with your own function, and then in your function do both your checks AND call the original callback function.


How do I access a field value for an entity (e.g. node) object? node_load((int) $nid) loads a fully-populated node entity. $node->title->value gets the title, but how do I access field values in Drupal 8?

I guess you do not need to convert $entity into an array,
this would simply work.

$entity->get('field_name')->getValue();

FYI : Using kint() from the devel_kint module will let you know all the available methods that could be used to access the object elements, so comparatively var_dump() is less helpful.


Is there a module that provides payment processing but not a shopping cart? I am building a website that allows users to "upgrade" their content. The user can choose a "premium" listing and once paid for their node will appear higher in a list of nodes.

I'm looking for a module that can do this, or a module that can at least provide the payment page so that I could customise the node editing process and direct them to this page, take their payment then update the node.

I know something like Ubercart can provide the payment processing but it has a very set payment checkout process that is more oriented to a shopping cart checkout process and would take a lot of time to customise for what I want.

Any recommendations on how to do this?

Im running Drupal 7.

Have you tried some of those ?

lm_paypal:

  This module provides an interface to PayPal using Instant Payment
  Notifications (IPN). It currently supports paid memberships
  (subscriptions), donations (tip jar) and paid adverts (classified
  ads).

Payment API: this one need a specific module for the payment platform

  This module can be used by other modules to collect and track payments. Through this API, any module can provide a payment form and payments can be handled and tracked centrally.

How to build a paid membership site with Drupal 7 (paid module)


How can I have multiple content types pick up the same template? I want to override the template for 5 content type that they have all the same attributes, but a different name ,so the suggestion  is :

node--contenttype1.html.twig
node--contenttype2.html.twig
node--contenttype3.html.twig
node--contenttype4.html.twig
node--contenttype5.html.twig

how can i implement a same override for all those 5 content type ?

Normally you'd simply use node.html.twig and then have different node templates for other node types. But I can imagine that it can make sense to bundle certain node types differently instead of providing distinctive templates for all other node types.

So you can implement hook_theme_suggestions_alter or hook_theme_suggestions_HOOK_alter to provide an extra template suggestion. The following snippet lets nodes of a given type pick up a node--foobar.html.twig template if present.

/**
 * Implements hook_theme_suggestions_HOOK_alter().
 */
function MYTHEME_theme_suggestions_node_alter(array &$suggestions, array $variables) {

  $bundles = [
    'contenttype1',
    'contenttype2',
    'contenttype3',
    'contenttype4',
    'contenttype5',
  ];

  /** @var \Drupal\node\Entity\Node $node */
  $node = $variables['elements']['#node'];

  if (in_array($node->bundle(), $bundles)) {
    $suggestions[] = 'node__foobar';
    $suggestions[] = 'node__foobar__' . $variables['elements']['#view_mode'];
  }
}


Calling a field in views-view-fields--view-name.tpl.php ---- Error I am trying to call a field by using the line of code:

<?php print $field->handler->view->field['title_1']; ?>

But i keep getting this error:

I used devel dpm() to look for what was the correct path to call it and it said handler->view->field['title_1']. I am absolutely stumped and I am not sure if I am using the right .tpl.php file or what. Anyone have any ideas?

---EDIT---

<?php foreach ($fields as $id => $field): ?>
  <?php if (!empty($field->separator)): ?>
  <?php print $field->separator; ?>
<?php endif; ?>

<?php print $field->wrapper_prefix; ?>
<?php print $field->label_html; ?>
<?php print $field->content; ?>
<div>
    <?php print $field->handler->view->field['title_1']; ?>
</div>
<?php print $field->wrapper_suffix; ?>

From the commentary, some points are being missed, but this template is used to create the "row" of fields from a View.

Let's create a simple one:

which has three fields, a title, a new field and a custom field, which when run looks likes this:

Now, let's create a views-view-fields--for-da.tpl.php, rescan for templates, and add some debugging information to the top of it:

drupal_set_message('
' . print_r(array_keys($fields), TRUE) . '
');

and running it again, this will give us:

So, now, anyplace we want inside this template, we have access to the individual field's content as:

$fields['title']->content
$fields['field_new_field']->content
$fields['field_my_custom_field']->content

so throwing them in similar drupal_set_message()s produces:

But now, let's say you are exluding one of these fields from display, eg:

then you will get this:

but some more digging into $row via:

drupal_set_message('
' . print_r($row->field_field_my_custom_field, TRUE) . '
');

will give you this:

or access to the content of the excluded field via:

$row->field_field_my_custom_field[0]['rendered']['#markup']

Obviously, the field names are different here than in your specific example, but I hope you can follow the logic.

Also, if you don't want to dig into $row you could always include the field in the display via the Views UI and then exclude it in this template, eg, something like this:

<?php foreach ($fields as $id => $field): ?>
  <?php if ($id != 'field_my_custom_field'): ?>
    <?php if (!empty($field->separator)): ?>
      <?php print $field->separator; ?>
    <?php endif; ?>

    <?php print $field->wrapper_prefix; ?>
      <?php print $field->label_html; ?>
      <?php print $field->content; ?>

        <?php print $fields['field_my_custom_field']->content; ?>

    <?php print $field->wrapper_suffix; ?>
  <?php endif; ?>
<?php endforeach; ?>

which would print all the fields with the exception of the custom one, but would then include its content after the content of each of the other fields.


How to run Drupal console command from code? I have found a lot of documentation on how to run Drush commands from code, but I'm specifically looking on how to run a Drupal Console command from code.

I have some experience in Symfony and I know how to run a Symfony command from code. Since a Drupal console command extends on Symfony command, I thought this should be rather easy. Simply following this tutorial doesn't amount to anything though.

I am trying to run a command in a hook_cron() implementation in a custom module.

Run shell commands via the Process class available in the Symfony framework.

From the Symfony docs:

use Symfony\Component\Process\Process;
use Symfony\Component\Process\Exception\ProcessFailedException;

$process = new Process('ls -lsa');
$process->run();

// executes after the command finishes
if (!$process->isSuccessful()) {
    throw new ProcessFailedException($process);
}

echo $process->getOutput();

  The component takes care of the subtle differences between the
  different platforms when executing the command.

Replace the ls -lsa command in the Process() constructor with your Drupal console command.


mysql populate a field of a content? I have a content type that has the field field_data_latitude.  I see in the database the existence of a table called field_data_field_latitude that contains the values for this content type .  When I populate it via mysql, the value does not show up in the CMS.  Are there other tables I'm supposed to populate?

I also noticed a table called field_data_field_latitude..I popualted that as well but the value is not visible in the CMS.

Clear the cache after adding your custom values to the database.  Might fix the problem as I have seen it work for some in the past.


Commerce add to cart form fails when loaded via Ajax Edit: more details below

I'm setting up a store page as follows, using Views, Commerce, and Drupal AJAX via a custom module:

There is a View that lists product display Nodes (B). Clicking on a Node in the View loads that Node's 'full' view on the page via AJAX (C), which includes the Product reference field / add to cart form (D). There are also AJAX links (A) that will swap the View for another display of the same view (with different criteria for loading the Nodes). The add to cart button works on Nodes included in the View display that loads initially on the page, but not if the View display is switched. When clicked, the form submits, but the product is never added to the cart. No errors or log messages. The exception is that any product Nodes that were loaded in the initial View display will work in subsequent ones.

So if 'new_releases' is the Views display loaded during the initial page load, and it includes 'title 1', then when 'title 1' is loaded, then the 'buy' button works. If 'full_catalog' is then loaded, then 'title 1' is loaded, then the 'buy' button works. But if 'full_catalog' includes 'title X', not included in 'new_releases', then they 'buy' button won't work when 'title X' is loaded.

This makes me think something is going on (perhaps with form_token or form_build_id) that gets initialized properly during the first page load that doesn't happen via subsequent AJAX loads, but I'm not sure what that would be. The form HTML seems to be correct in both cases, both include the product ID and hidden quantity fields. No error messages shown.

Here's my code that loads the node:

function my_module_node_loader($nid = 0) {
 $node = node_load($nid, NULL, false);

 if($node) {
   $nodeview = node_view($node,'full');
   return render($nodeview); //will be returned in my_module_ajax_callback via drupal_json_output
 }

}

The function that retrieves the view:

function my_module_store_contents($display) {

 $view = views_get_view('view_name');
 $view->set_display($display);
 $view->execute();
 $response = $view->result;

 foreach($response as $id=>$row) {
   //do some custom formatting, put the results in $html
 }

  return $html; //returned via my_module_block_view on intial page load, my_module_ajax_callback subsequently

}

I'm already sure the AJAX callbacks are working ok, as the content gets loaded as I'd expect. It's just the issue with the form. Is there an extra step to make sure that a form is initialized properly if loaded via AJAX?

Edit:

Thanks to a tip on drupal commerce's site, I discovered the cause of this was my altering the form's #action, which I had forgotten about. The add-to-cart form seems to take its #action from the path that loads it, so rather my /shop url, it was trying to load the /my-module/ajax callback. Since the add-to-cart form isn't itself ajax-enabled, it was redirecting the page with that url rather than doing it via ajax - I'd get the JSON response - so I was attempting to set the #action back to /shop:

    function my_module_form_commerce_cart_add_to_cart_form_alter(&$form, &$form_state) {

     if(substr($form['#action'],0,15) == '/my-module/ajax') {
       $form['#action'] = '/shop';
       $form_state['rebuild'] = TRUE;
     }
   }

I attempted to use the 'rebuild' directive, with no effect. But if I remove the code altering the #action, then the product is added to the cart, albeit first sending me to /my-module/ajax.

So I need to either alter the add-to-cart form to submit properly via ajax, or figure out how I can alter the #action without breaking the form.

This is an old issue, but it was never answered and ranks high on google. The solution is to rebuild the submit button via javascript after the view has loaded:

$(".view").ajaxComplete(function(event, XMLHttpRequest, ajaxOptions){
          response = XMLHttpRequest.responseText;
          result = response.search(/"status": false/i);
          if(result == -1){
            $("form.commerce-add-to-cart").each(function(){
              $(this).attr("action",window.location.pathname);
            });
          }
          else{
            //console.log("failure binding on ajax complete");
          }
        });

Solution taken from here: https://www.drupal.org/node/1294164#comment-5343066


New node created on one site automatically created on others? Say I have a parent site where all my content is created: nodes and taxonomy terms, but I want that same content to be created - or to appear at least - automatically on multiple child sites. What ways could this functionality be achieved? The solution could be a custom module or a a contrib module, if one exists to perform this task.

Isovera wrote a good article on how to do this "Syndicate content between Drupal"

You'll need Views and Feeds at a minimum to get started.

In views you'd create an RSS feed (there are several views modules available to help with this) for the data you'd like to share between sites. You would then set up Feeds to import your newly created RSS feed. You can map each field from your feed to the content type you'd like to import into. Feeds can be configured to run on cron, allowing content to be imported from one site to another.


How to add a field widget for multiple file upload? Is there a module that provides a multiple file upload (Drag and Drop) widget? If there isn't, how can I build one? Will it require a special setup for the server stack (LAMP)?

Multiupload FileField Widget

This is what you want. It enables the HTML5 standard for uploading multiple files. Use a normal file field but use this widget. Now one can select several files when browsing for files to upload. This works for never web browser but not IE8.


Alter the user registration form I'm trying to change the label and field instructions for the name field on the User Account Creation form. I'm new to coding, and thought this would be an easy task.

My custom module is enabled and I've cleared caches, but none of my changes show up. Here is my code. I've tried a bunch of variations and a bunch of searching, but I never see a single sign of this working.

<?php

/**
 * @file
 * Contains mymodule.module.
 */

use Drupal\Core\Form\FormStateInterface;

/**
 * Implements hook_form_FORM_ID_alter() on behalf of mymodule.module.
 * @see \Array method Array at Array
 */
function mymodule_form_account_alter(&$form, FormStateInterface $form_state, $form_id) {
  // print_r($form); die;
  // ksm($form_id);
  if ($form_id == 'user_register_form') {
    // print_r($form); die;
    // kint($form_id);
    $form['name'] = array(
      '#type' => 'textfield',
      '#title' => $this->t('First and last name'),
      '#maxlength' => USERNAME_MAX_LENGTH,
      '#description' => $this->t("Rewrite this about spaces, periods (.), hyphens (-) and apostrophes (')."),
    );
  }
  drupal_set_message('mymodule_form_account_alter() executed.');
}

Here is the right code:

/**
 * Implements hook_form_FORM_ID_alter().
 */
function <your_module>_form_user_register_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  $form['account']['name']['#title'] = t('First and last name');
  $form['account']['name']['#description'] = t("Rewrite this about spaces, periods (.), hyphens (-) and apostrophes (').");
}

feel free to ask :)
have fun!


How to add image field in a custom module form? In our custom module, mymodule we have a form MyModuleForm where we want to allow for an image to be uploaded or chosen from already uploaded images. Below is the MyModuleForm.php file, but cannot figure out why we are not able to upload the Image and save it. There is a menu link where the module's form is and when we navigate to the page we see a blank page with no field or widget to set the image.

Goal

To be able to make the Image Browser widget display so that we can use an existing image or upload one.
Store the image using MyModuleForm from the custom module.
We should be able to change the image as needed and save the configuration.
Set file status to permanent.
Add to file usage calculation.

How do we add an Image field on our MyModuleForm so that we can either use an existing image or upload a new one?

Here is what we tried but didn't work

MyModuleForm.php

class MyModuleForm extends ConfigFormBase {
  protected function getEditableConfigNames() {
    return [
      'mymodule.settings'
    ];
  }

  public function getFormId() {
    return 'mymodule_form';
  }

  public function buildForm(array $form, FormStateInterface $form_state) {
    $config = $this->config('mymodule.settings');
    $form['my_file'] = [
      '#type' => 'managed_file',
      '#title' => 'my file',
      '#name' => 'my_custom_file',
      '#description' => $this->t('my file description'),
      '#default_value' => $config->get('my_file'),
      '#upload_location' => 'public://'
    ];

    return parent::buildForm($form, $form_state);
  }

  public function validateForm(array &$form, FormStateInterface $form_state) {
    parent::validateForm($form, $form_state);
  }

  public function submitForm(array &$form, FormStateInterface $form_state) {
    // Check if image is uploaded.
    if(isset($form_state['default_press_release_image'])) {
      // Set file status to permanent.
      $image = $form_state->getValue('my_file');
      $file = File::load($image[0]);
      $file->setPermanent();
      $file->save();
      // Add to file usage calculation.
      \Drupal::service('file.usage')->add;
    }

    $this->config('ns_default_images.settings')
      ->set('default_press_release_image', $form_state->getValue('default_press_release_image'))
      ->save();

    parent::submitForm($form, $form_state);
  }
}

The default_value attribute accept an array in case of managed_file:

  $form['my_file'] = [
      '#type' => 'managed_file',
      '#title' => 'my file',
      '#name' => 'my_custom_file',
      '#description' => $this->t('my file description'),
      '#default_value' => [$config->get('my_file')],
      '#upload_location' => 'public://'
    ];

In The submit function you are using a field name different from the declared one in the buildForm().

The value of a managed_file should be an array even when the field is not multiple:

$form_state->getValue('default_press_release_image')[0];


Boost Cache helps some pages, hurts others? I'm working on fixing some performance issues of a Drupal 6 site. Very new to Drupal, been figuring things out as I go, so please bear with me here.

My client has a rather busy site and uses Boost cache. On pages where Boost cache is applicable -- their home page, reviews pages, etc,... -- it works great. Pages are fast, load testing shows that they can take whatever's thrown at them. I just discovered that with Boost enabled, pages that are not eligible for its caching, such as pages with polls that need to pull from the DB each time, they are significantly slower to load then when Boost is disabled entirely.

For instance, here are the Loader.io results of a page in question. The instances where it completed successfully were with Boost disabled, instances where it failed were with Boost enabled. Ignore that 100% error rate test that's second from the top, MySQL actually crashed after the previous test and I forgot to restart it before running again.

All I know for sure is that the errors are caused by MySQL. It appears that Boost adds database overhead, maybe it has to check for information about cached pages and then it has to do a second query to draw the page if it doesn't find the cached information? I'd love any insight anyone can provide!

Edit: Screenshot of Boost expiration settings

There is an option in boost that let you count the number of hits even of cached pages. That version hits your database on each page hit. It's fairly small, but it still loads all the modules as it has to go through the standard Drupal initialization.

Make sure you turn that off if it is on to ease the load on the DB.


Make content be aware of the section I have a site divided by in multiple section which are actually some taxonomy views (taxonomy/term/term_ID).

It works like this:

I have some specific blocks for each section.
Content can be found in multiple sections

The problem is that (because the node is part of multiple section) I don't know how to display the same blocks on the node page as the ones in the section the user just left.

Any ideas? Thanks

You can use context module and create two different contexts by adding conditions as path.

Enable the reactions as blocks and add same blocks in different sections using two context that you created !

  Context allows you to manage contextual conditions and reactions for
  different portions of your site. You can think of each context as
  representing a "section" of your site. For each context, you can
  choose the conditions that trigger this context to be active and
  choose different aspects of Drupal that should react to this active
  context.

Hope it solves the problem :-)


How do I disable user pictures? In Drupal 7, you can disable user pictures just by unchecking the appropriate box on the Config -> People screen.

How can I disable user pictures in Drupal 8?  I see that the default D8 install adds an image field user_picture at /admin/config/people/accounts/fields, but I assume that it would be better to somehow disable this than just to delete it.

For now, I don't want user pictures to be shown or used in any way, unless I decide to re-enable them later.

If you don't want to delete the field, you can exclude the field from input:

/admin/config/people/accounts/form-display

and from output:

/admin/config/people/accounts/display


Inject variables only in teasers (template suggestions) How could I detect if node type is article (in template.php) but process variables only for teaser of article, not article i full mode. (I have template suggestions so i have node--article-teaser.tpl.php). Like:

if ($node->type == 'article' and inject only if article-teaser.tpl.php)

Thanks!

In a preprocess/process function for the node template file, you just need to check the following variables:

$variables['teaser'] must be TRUE
$variables['node']->type must be 'article'

$variables is the parameter passed to preprocess/process functions.


Service to interface with sessions table? In my module, I need greater session control, beyond simple max_lifetime and other parameters taken from PHP config. What I did was to add a column to the sessions table that gives me the effective session expiration, which I can compare against to know if to revoke the session. (I also want to "cache" this in the local session, but this is unrelated to the question).

The question is, what is the best way to retrieve the new data from the sessions table? I can just send a direct DB query, such as:

Database::getConnection()->query('SELECT expires_at FROM {sessions} s WHERE s.uid = :uid', [':uid' => $uid]);

However, is there a built-in service for accessing this table, for greater abstraction?

You can make use of Dynamic Queries
instead of Database::getConnection()->query('SELECT expires_at FROM {sessions} s WHERE s.uid = :uid', [':uid' => $uid]);

You can do:

  // Create an object of type Select.
  $database = \Drupal::database();
  $query = $database->select('sessions', 's');
  // Add extra detail to this query object: a condition, fields and a range.
  $query->condition('s.uid', $uid, '=');
  $query->fields('s', ['expires_at']);
  $result = $query->execute();


How to keep checkbox checked after form submit I am trying to keep checkbox "checked" after form submit and page load. I have following simple code from .module file.

    <?php

function my_module_menu() {
  $items = array();

  $items['examples/my_module'] = array( //this creates a URL that will call this form at "examples/form-example"
    'title' => 'Example Form', //page title
    'description' => 'A form to mess around with.',
    'page callback' => 'drupal_get_form', //this is the function that will be called when the page is accessed.  for a form, use drupal_get_form
    'page arguments' => array('my_module_form'), //put the name of the form here
    'access callback' => TRUE
  );
  return $items;
}

function my_module_form($form, &$form_state) {

$form['terms'] = array(
        '#type' => 'checkbox',
        '#title' => t('Your checkbox'),
    );
  $form['submit_button'] = array(
    '#type' => 'submit',
    '#value' => t('Click Here!'),
  );

  return $form;
}

function my_module_form_submit($form, &$form_state) {
  $form['terms']['#default_value'] = 1;
  }

?>

How can I achieve this?

First you need to specify #default_value to your element, Then if you are going to save your data in some place, then load it and use it as your element default_value, if you are not going to save it then you can use form_state on that but remember to set $form_state['form_rebuild'] as TRUE in submit handler, a sample code will be like this :

function my_module_form($form, &$form_state) {

  $form['terms'] = array(
    '#type' => 'checkbox',
    '#title' => t('Your checkbox'),
    '#default_value' => isset($form_state['values']['terms']) ? $form_state['values']['terms'] : array(),
  );
  $form['submit_button'] = array(
   '#type' => 'submit',
   '#value' => t('Click Here!'),
  );

  return $form;
}
function my_module_form_submit($form, &$form_state) {
  $form['terms']['#default_value'] = 1;
  $form_state['rebuild'] = TRUE;
}


How to display only one Commerce product variation in Views? I have a view which displays the list of all Commerce Products on the site.

The problem is that it displays variations as separate products.

I've tried:

Enabling Views aggregating checkbox
Creating a new view which is based on nodes, instead of Commerce Products
Checking "Distinct" under "Query options"

However, neither of that worked. I'm not sure if I misconfigured these settings.

I suspect that it has to do something with aggregation/grouping but I can't figure it out for a couple of hours already :@

How can I limit the display of products to only one variation?

Thanks!

Just use this in filter.

Content: Product Reference:delta (= 0)

which will show only one variation of your product.


Change date formate in drupal admin tables (log, content listing, edit pages, etc) I've looked everywhere but can't find out how to change the date format in the admin/content/ table and the recent log table.

Current it is displayed as '09/05/2014 - 00:18'' but I just wanted to make it YYYY-mm-dd - hh:mm'

What's the best way to make this happen?

From /admin/config/regional/date-time you can change the way dates are shown. This applies to the whole site though.


Change block titles from h2 to h3 I want that block titles have the h3 tag instead the h2 tag. As I understand I have to change this in the file block.tpl.php.
I found 4 block.tpl.php

root/modules/block/
sites/all/themes/omega/omega/templates
sites/all/themes/omega/starterkits/omega-xhtml/templates
sites/all/themes/omega/alpha/templates/

My question: Which one is the right file to change? I took now the one in the omega folder and it worked (the one in the modules folder did not). But I want to be sure whether this is the correct in order not to have side effects.
And what for is the modules/block directory with files?

thanks for any feedback

As a rule, we should never make changes in core files. If you will read the readme.md file in omega theme, you will see the following,

  Omega 4.x is a base theme and as such should never be used or
  modified directly. Instead, you should use the sub-theming
  functionality provided by Drupal.

  The easiest way to create a new Omega-based sub-theme is by using
  Drush. Omega comes with a very
  easy-to-use Drush command for generating sub-themes through a
  command-line wizard. You can start the sub-theme creation wizard by
  invoking drush omega-wizard in the command-line.

So you should first create omega sub-theme which is quite easy process and then make changes in sub-theme's block.tpl.php file.


Reorganize Language Switcher based on Country/Region I'm working on a site with 34+ languages and will likely be expanding to more. With this many countries, a simple drop-down list can be difficult for usability. I would like to customize the language switcher so that I can categorize a language by region and country. I have seen this before, have created similar on other non-Drupal sites, but haven't seen anything like it for Drupal.

Example:

Europe

Germany

DE

Switzerland

DE
FR

etc.

I'm looking for either a module, or a head start on what I might do short of writing some custom PHP for the project.

You can take a clue from below modules..

Hierarchical Select Module ...

  Hierarchical Select module defines the "hierarchical_select" form
  element, which is a greatly enhanced way for letting the user select
  items in a hierarchy.

Language Switcher Dropdown Module..

  Language Switcher Dropdown is a very simple module that exposes a new
  block, similar to the default Language Switcher block provided by
  Locale module. The new block allows site visitors to switch languages
  using a drop-down select list instead of using hyperlinks.

You need to build a custom module which displays region > countries using hierarchical select module
On Form Submit you need to do below actions which lang drop down does to redirect.

Please find submit handler code below from lang dropdown module..

function lang_dropdown_form_submit($form, &$form_state) {

  $language_code = check_plain($form_state['values']['lang_dropdown_select']);
  $type = $form_state['values']['lang_dropdown_type'];
  $tohome = $form_state['values']['lang_dropdown_tohome'];

  $language_codes = locale_language_list('language');
  if (!in_array($language_code, $language_codes)) return;

  $types = language_types_configurable(FALSE);
  if (!in_array($type, $types)) $type = 'language';

  $path = drupal_is_front_page() ? '<front>' : $_GET['q'];
  $languages = language_negotiation_get_switch_links($type, $path);

  $language = $languages->links[$language_code];

  $newpath = (isset($language['href']) && $tohome == 0) ? $language['href'] : '<front>';

  if (!isset($language['query'])) {
    $language['query'] = drupal_get_query_parameters();
  }

  $form_state['redirect'] = array($newpath, $language);

}


Displaying relative dates in a Views Exposed Filter I have a view displaying a collection of events with a date field the user can set the range of. For a default value, I have +0 days to +90 days, so the user can see all events during the next 90 days. The image below shows all my setting information for the date filter.

Currently, the user sees relative dates when they load the page, as the next image shows:

But I would like this to show dates to the user, instead of these relative values when they load the page. In the picture above, if the date they were viewing the page was 1/11/17, I would like the user to see 1/11/17 to 4/11/17 instead of +0 days to +90 days. What would be the simplest way to make this conversion in Drupal 8?

Edited - You can apply datepicker to the field, as Jquery Ui date picker is available in Drupal8. For reference see to this

Or,

you can programmatically alter the view query in hook_views_query_alter()

function module_name_views_query_alter(ViewExecutable $view, QueryPluginBase $query) {
 // Query alter to provide dynamic date ranges.
 if ($view->id() == 'VIEW ID' && $view->current_display == 'page_1')
 {
    foreach ($query->where[0]['conditions'] as $key) {
      if (array_key_exists(':node__field_start_date_time.field_start_date_time_value[]', $key['value'])) {
        // do anything you want...
        ...
        ...
      }
    }
 }


Add  link around each row in views So basically i want to add a link to original node around each row in views. I have added the following code to the style and row template override in views. Both come up with the same result.

<?php $image = file_create_url($row->field_field_display_image[0]['rendered']['#item']['uri']); ?>

  <div class="block__inner" style="background-image: url('<?php echo $image; ?>');">
    <?php foreach ($fields as $id => $field): ?>
      <?php if (!empty($field->separator)): ?>
      <?php print $field->separator; ?>
    <?php endif; ?>

Now the issue that i am having is that the link is added to each field element that is outputted for some reason, and not just the link around the whole row and each field.

I cannot use custom field as that is making the same issue. It seems views is auto closing the a tag.

Any known workarounds?

I usually remove all default formatting from every field, then hide all of my fields from display apart from the last field in views, and also remove all formatting, making the hidden fields plain text where possible.

Then in that last fields settings, rewrite the results, and input all of the fields as tokens from the replacement patterns.

Then instead of div elements, I use span which plays better inside an anchor, and just add unique classes for each span element.

So an example rewrite results might be...

[title]
[body]

This should not suffer the same issue if you go to each hidden field, and under the style fieldset, make sure than no default wrapper or classes are applied, and also that each field is plain text. This will strip all formatting and place it inside the rewritten span elements. Like @BeeBee says, div and p will break the anchor wrapper.


How to cancel installation of my module if requirements are not met My module depends on a PHP library (sites/all/libraries/xyz/xyz-library.php). I want drupal to continue with installation only if library requirements of my module are met.

I want something of this kind, in my mymodule.install:

function mymodule_install() {
  if( library_exists() )   return; //continue with installation
  else{
    drupal_set_message(t('Installation failed. Please put xyz-library.php in sites/all/libraries/xyz folder.'), 'error');
    return FALSE; // installation failed
  }
}

You can do this in hook_requirements, from the documentation:

  During the 'install' phase, modules can for example assert that
  library or server versions are available or sufficient. Note that the
  installation of a module can happen during installation of Drupal
  itself (by install.php) with an installation profile or later by hand.
  As a consequence, install-time requirements must be checked without
  access to the full Drupal API, because it is not available during
  install.php. For localization you should for example use $t = get_t()
  to retrieve the appropriate localization function name (t() or st()).
  If a requirement has a severity of REQUIREMENT_ERROR, install.php will
  abort or at least the module will not install. Other severity levels
  have no effect on the installation. Module dependencies do not belong
  to these installation requirements, but should be defined in the
  module's .info file.

After your check, you return array (see docs again) with REQUIREMENT_ERROR.

function example_requirements($phase) {
  $requirements = array();
  // Ensure translations do not break at install time
  $t = get_t();

  $requirements['example'] = array(
    'title' => $t('Example Library'),
  );

  $libraries = libraries_get_libraries();
  if (isset($libraries['example'])) {
    $requirements['example']['value'] = $t('Installed');
    $requirements['example']['severity'] = REQUIREMENT_OK;
  }
  else {
    $requirements['example']['value'] = $t('Not Installed');
    $requirements['example']['severity'] = REQUIREMENT_ERROR;
    $requirements['example']['description'] = $t('Please install the example library %url.', array('%url' => 'http://example.com'));
  }

  return $requirements;
}

You can check this code example here.