# Question
Title: In Drupal 7, how do you git clone a module project quickly?
There doesnt seem to be any good documentation on a quick way to git clone a module project. I have already read this: https://drupal.org/project/examples/git-instructions

The following format does not work for me:

> git clone --branch 7.x-1.x http://git.drupal.org/project/examples.git

I am getting this error:

Is there a way to do a git clone quickly by copying a url without having to put in --branch 7.x-1.x versions... or better yet is there a drush command to do a git clone? All i want to do right now is do a git clone of a project and provide a patch to the maintainer, but im hitting resistance setting this up.

# Answer
> 7 votes
Just use the format you say doesn't work. This is the correct format. The URL does matter. (Do *not* use the format that produces the error.)

I.e. to clone branch 7.x-1.x of `tb_megamenu`, you should use:

```
git clone --branch 7.x-1.x http://git.drupal.org/project/tb_megamenu.git

```

You may skip the `--branch` option and branch identifier when cloning. This will clone the current `HEAD`, which may (or may not) be the head of the branch you want.

# Answer
> 1 votes
An easier option I find is to use the Drush command `drush pm-download` with the `--package-handler=git_drupalorg` option. For the examples module given in your question you would run this command in a terminal:

```
drush pm-download --package-handler=git_drupalorg examples-7.x

```

Specifying the Drupal version in the argument above ensures the correct branch is checked-out after the project is cloned.

Here's the relevant documentation for the Drush command and options:

```
drush help pm-download

```

Download Drupal core or projects from drupal.org (Drupal core, modules, themes or profiles) and other sources. It will automatically figure out which project version you want based on its recommended release, or you may specify a particular version.

If no `--destination` is provided, then destination depends on the project type:

* Profiles will be downloaded to `profiles/` in your Drupal root.
* Modules and themes will be downloaded to the site specific directory (`sites/example.com/modules|themes`) if available, or to the site wide directory otherwise.
* If you're downloading drupal core or you are not running the command within a bootstrapped drupal site, the default location is the current directory.
* Drush commands will be relocated to `/usr/share/drush/commands` (if available) or `~/.drush`. Relocation is determined once the project is downloaded by examining its content.

**Examples:**

* `drush dl --package-handler=git_drupalorg examples` Use git.drupal.org to checkout and update the Examples project.

**Arguments:**

1. `projects` \- A comma delimited list of drupal.org project names, with optional version. Defaults to 'drupal'

**Options:**

* `--package-handler=git_drupalorg` Use git.drupal.org to checkout and update projects.
* `--gitusername` Your git username as shown on user/\[uid\]/edit/git. Typically, this is set this in drushrc.php. Omitting this prevents users from pushing changes back to git.drupal.org.
* `--gitsubmodule` Use git submodules for checking out new projects. Existing git checkouts are unaffected, and will continue to (not) use submodules regardless of this setting.
    + `--gitsubmoduleaddparams` Add options to the `git submodule add` command.
* `--gitcheckoutparams` Add options to the `git checkout` command.
* `--gitcloneparams` Add options to the `git clone` command.
* `--gitfetchparams` Add options to the `git fetch` command.
* `--gitpullparams` Add options to the `git pull` command.
* `--gitinfofile` Inject version info into each .info file.

---
Tags: 7, version-control
---


# Question
Title: How do I interpret the line of codes ( \ No newline at end of file) and (+ - core/jquery.once)
In the Drupal8 zircon/includes/monokai/monokai.min/css patch how do I manually apply the last two lines of code; ( \ No newline at end of file) and (+ - core/jquery.once).
Thank you

```
diff --git a/zircon.libraries.yml b/zircon.libraries.yml
index bd6a231..3358a49 100644
--- a/zircon.libraries.yml
+++ b/zircon.libraries.yml
@@ -8,7 +8,7 @@ global-styling:
       includes/fontawesome/css/font-awesome.min.css: {}
       includes/slick/slick/slick.css: {}
       includes/slick/css/style.css: {}
-      includes/monokai/monokai.min/css: {}
+      includes/monokai/monokai.min.css: {}
       includes/flexslider/flexslider.css: {}
       css/html.css: {}
       css/page.css: {}
@@ -38,4 +38,5 @@ global-styling:
     - core/drupal.ajax
     - core/drupal
     - core/drupalSettings
-    - core/jquery.once
\ No newline at end of file
+    - core/jquery.once

```

# Answer
> 2 votes
The message "No newline at end of file" is a warning GIT throws up when there is not a newline as the last line in a file. You can solve this by adding a newline at the very end of the file.

---
Tags: rules
---


# Question
Title: How to copy data from one node reference to another node reference in same content type
I have already saved a lot of data in a content type 'Events' in the node reference field `field_organization`. However, I need the data to be moved to the field `field_affiliation` also within the same content type.

Is there a way to do this with VBO and PHP command or another simpler way without code?

# Answer
As far as I know VBO is rather not for this kind of job, I also don't know any other module to help you with this except the migrate module but I also think that it won't be of any help for you. What you are describing is called "migration", transferring and storing data from one place to an other, even if it is just one field or an entire website. Most migration tasks require at some point, if not at all points, code writing, code to manage the data during the migration. Fortunately, to your case is just a field, so you'll need to write a small script by taking advantage of the Drupal's node API, to transfer the data from one field to another, and that's it.

Rough idea on how to do it:

```
$query = new EntityFieldQuery();

$query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'events')
  ->propertyCondition('status', NODE_PUBLISHED)
  ->addMetaData('account', user_load(1)); // Run the query as user 1.

$result = $query->execute();

if (isset($result['node'])) {
  $nids = array_keys($result['node']);
  $nodes = entity_load('node', $nids);
}

foreach ($nodes as $node) {
  $value = $node->field_organization[LANGUAGE_NONE][0]['value'];
  $node->field_affiliation[LANGUAGE_NONE][0]['value'] = $value;
  field_attach_update('node' ,$node);
}

```

Use drush to run your script by using this command :

`drush php-script site/all/scripts/script_name` I know, this is too much for someone who has not much experience with Drupal yet but if you are really serious in getting involved with it you should start learning and use those things as much as possible.

Lastly, if you still insist to do it without writing a single line of code, do it manually, but you will soon discover that that way has a major disadvantage if your nodes are more than one or two hundred.
> 0 votes

# Answer
If you have access to PHPMyAdmin or any other database viewing program, all you have to do is export the `field_data_organization` table and import it into `field_data_affiliation`.

Clear flush/cache in Drupal to see changes.
> 0 votes

---
Tags: 7, entities
---


# Question
Title: How can I add a Twig template to a programatically created custom content type?
I created a module implementing a content type. How can I set a custom template file for that content type and for the teaser and full view modes? I need to use the template files in the folder of my module, not the theme the site is currently using.

These are some details about my module.

* Module name: My Module
* Content type name: My Content
* Teaser template name: node--my-content--teaser.html.twig
* Full template name: node--my-content--full.html.twig
* Field template name: field--node--field-my-field--my-content.html

# Answer
> 1 votes
> **Nodes**
>
> Pattern: *node--\[type|nodeid\]--\[viewmode\].html.twig*
>
> Base template: *node.html.twig* (base location: core/modules/node/templates/node.html.twig)
>
> Theme hook suggestions are made based on these factors, listed from the most specific template to the least. Drupal will use the most specific template it finds:
>
> 1. node--nodeid--viewmode.html.twig
> 2. node--nodeid.html.twig
> 3. node--type--viewmode.html.twig
> 4. node--type.html.twig
> 5. node--viewmode.html.twig
> 6. node.html.twig
>
> Note that underscores in a content type's machine name are replaced by hyphens.

Source: Twig Template naming conventions

In your case this is number 3.

Example:

**node--article--teaser.html.twig**

If you want to place the template inside the module see: Template for custom content type

In your case this would look like this:

```
/**
 * Implements hook_theme().
 */
function my_module_theme() {
  return [
    'node__my_content__teaser' => [
      'base hook' => 'node',
    ],
    'node__my_content__full' => [
      'base hook' => 'node',
    ],
  ];

```

In my experience you only need `base hook`. Drupal will discover the correct template name and path on its own. You have to be careful with the underscores (\_) in the theme hook, they should match exactly the hyphens (-) of the template name.

# Answer
> 0 votes
You don't need to do anything, except creating the necessary template files for the theme you are using, with the correct names. The Node module already suggests the following template files, for a node, in `node_theme_suggestions_node()`.

```
  $suggestions[] = 'node__' . $sanitized_view_mode;
  $suggestions[] = 'node__' . $node->bundle();
  $suggestions[] = 'node__' . $node->bundle() . '__' . $sanitized_view_mode;
  $suggestions[] = 'node__' . $node->id();
  $suggestions[] = 'node__' . $node->id() . '__' . $sanitized_view_mode;

```

Supposing that custom\_type is the content type (i.e. bundle) created from the module, you could use node--custom-type--teaser.html.twig as template file for the teaser of that content type, and node--custom-type--full.html.twig for the full display mode of the same content type.

Keep in mind that template files are searched following a specific order; the first existing template file is then used. So, if you are viewing the teaser of a node whose ID is equal to 2, the following template files will be used, if they exist.

* node--2--teaser.html.twig
* node--2.html.twig

In this case, you could have a node--custom-type--teaser.html.twig file, but it will never be used.

---
Tags: theming, 8, entities
---


title: URL alias to call function

text:
# Question
Title: URL alias to call function
in short I want the same functionality as the taxonomy module where you can have an URL like "localhost/drupal/admin/structure/taxonomy/occupational\_fields/edit" where occupational\_fields was the aliased part.

The menu entry in taxonomy for the page callback looks like this:

```
$items['admin/structure/taxonomy/%taxonomy_vocabulary_machine_name/edit'] = array(
  'title' => 'Edit',
  'page callback' => 'drupal_get_form',
  'page arguments' => array('taxonomy_form_vocabulary', 3),
  'access arguments' => array('administer taxonomy'),
  'type' => MENU_LOCAL_TASK,
  'weight' => -10,
  'file' => 'taxonomy.admin.inc',
);

```

The function declaration looks like this:

```
function taxonomy_form_vocabulary($form, &$form_state, $edit = array())

```

Now my implementation looks like this:

```
$items['admin/config/mapper/%tid/edit'] = array(
  'title'            => 'Mapper edit mapping',
  'description'      => 'Add or edit a mapping',
  'page callback'    => 'drupal_get_form',
  'page arguments'   => array('mapper_form_mappings', 3),
  'access arguments' => array('administer site configuration'),
  'type'             => MENU_LOCAL_TASK,
  'file'             => 'mapper.admin.inc',
);

```

And respectively:

```
function mapper_form_mappings($form, &$form_state, $edit = array())

```

But when an URL like "localhost/drupal/admin/config/mapper/11/edit" is opened the function above is not called.

I tried googling a good URL alias tutorial for module programming, but couldn't find one. Maybe I searched for the wrong thing?

edit: I can imagine that I need some type of handler, but I couldn't find one in the taxonomy files and the tutorials didn't mention them either.

# Answer
Okay, here is a proper answer to a tricky question.

## Documentation

First of all, you should read the following two documents, if you haven't already:

## Simple Wildcards

By using % as a path wildcard you are instructing the menu\_router matching algorithm to use the path argument as it is (used mostly for numerical arguments). So, following from your comment, yes, it does have a significance. If you write your code like this:

```
$items['admin/config/mapper/%/edit'] = array(
  'title'            => 'Mapper edit mapping',
  'description'      => 'Add or edit a mapping',
  'page callback'    => 'drupal_get_form',
  'page arguments'   => array('mapper_form_mappings', 3),
  'access arguments' => array('administer site configuration'),
  'type'             => MENU_LOCAL_TASK,
  'file'             => 'mapper.admin.inc',
);

```

you are going to get the 3rd part of your path as an argument to your mapper\_form\_mappings function. Exactly as it occurs in the path.

## Auto-Loader Wildcards

Now, if you would use a `%NAME` type of wildcard, like taxonomy does, you would be triggering the 'Autoloader Wildcards' (a.k.a. 'Wildcard Loader Arguments') functionality. Drupal will try to load an object through a function called `NAME_load`. In the case of the `%taxonomy_vocabulary_machine_name` Drupal will try to load a vocabulary using the specified machine name as an argument to the `taxonomy_vocabulary_machine_name_load` function. The loaded object will then be passed as an argument to `drupal_get_form` (or any other function defined in your path definition).

## Current problem

In your case, your original code:

```
$items['admin/config/mapper/%tid/edit'] = array(
  'title'            => 'Mapper edit mapping',
  'description'      => 'Add or edit a mapping',
  'page callback'    => 'drupal_get_form',
  'page arguments'   => array('mapper_form_mappings', 3),
  'access arguments' => array('administer site configuration'),
  'type'             => MENU_LOCAL_TASK,
  'file'             => 'mapper.admin.inc',
);

```

implies there is a `tid_load` function that will receive the `%tid` argument from the URL and should return some object to `drupal_get_form`. This is however not working, since such a function does not exist.

## Alternatives using wildcard loaders

If you want to use the 'Auto-Loader Wildcards' functionality, you should do one of the following:

* Use an existing \_load function, e.g. `taxonomy_term_load`. Your wildcard should be called `%taxonomy_term` in this case and the final argument passed to drupal\_get\_form would be an taxonomy term object.
* Use a custom \_load function, e.g. `mapper_load`. Your wildcard should be called `%mapper` in this case and the final argument passed to `drupal_get_form` would be whatever your `mapper_load` function returns.

Best of luck!
> 0 votes

---
Tags: uri, path-aliases
---


# Question
Title: Field filter in Views, filter by TID, not name
I have a content type, books, with a field Category, based on a taxonomy. I have a View of books, and can filter by author, date, and also by field category. Everything works right, but when I try to add several subcategories (nested taxonomy), I have the problem that I cannot let the filter exactly as it is, as I can have two family names exactly equal, namely "offers". For example:

```
 http://www.example.com/books/science/offers
 http://www.example.com/books/sports/offers

```

As I am using arg(3) for retrieving "offers", I have the same name for two different taxonomies with different tid's.

How can I alter the SQL in ´MYMODULE\_views\_pre\_view´ so I can filter by tid instead of name? I can programmaticaly get the tid from the URL and inject it directly into the SQL, but don't know how to alter this SQL accordingly.

# Answer
@no-sssweat' answer is what you want as long as views can figure out the right tid from the url. In cases where it can't but you know how to, you can do an argument replacement in a custom module. Here is some code I have that is doing that:

```
/**
 * Implements hook_views_pre_view().
 */
function MYMODULE_views_pre_view(&$view, &$display_id, &$args) {
    $views_to_process = array(
        'view_name1' => array(
            'display_name1',
            'display_name2',
            'display_name3',
        ),
        'view_name2' => array(
            'display_name1',
        )
    );
    if (!in_array($view->name, array_keys($views_to_process))) { return; }
    if (!in_array($view->current_display, $views_to_process[$view->name])) { return; }
    if (!empty($args[0]) && !_MYMODULE_isInteger($args[0])) {
        $tid = _MYMODULE_get_tid_for_top_level_term($args[0], 'area');
        if ($tid) {
            $args[0] = $tid;
        }
    }

}

/**
 * Helper function to determine whether a value is an integer or not.
 *
 * Sourced from http://php.net/manual/en/function.is-int.php#82857
 */
function _MYMODULE_isInteger($input){
    return(ctype_digit(strval($input)));
}

```

The \`$views\_to\_process is a tree of views and displays that this should be applied to and the first two ifs just ignore this hook if the display isn't in $views\_to\_process. I then check to make sure there is an argument of some kind in place and that it isn't already an integer (helper function included for that), and then it loads a tid based on the current argument. It then replaces that argument with the tid. If you replaced \_MYMODULE\_get\_tid\_for\_top\_level\_term with your helper function for loading up the tid, you can then use the tid as a contextual filter value. I hope that helps!

*note:* I currently have a question open on that very view, and while I don't think this solution has anything to do with the issue I'm having, there is a chance.
> 1 votes

---
Tags: 7, views, taxonomy-terms
---


# Question
Title: How to change menu links items title programitically?
I have created a menu name `My Menu` (machine name: my\_menu ) with menu item `My Nodes` and `My messages`. Now I want alter `My nodes` and `My messages` link title. So the menu items should look like `Nodes` and `Messages` instead of `My nodes` and `My Messages`.

So I don't understand and also didn't find how can I alter the menu link title programmatically. i am trying to use `hook_menu_alter(&$items)` and `hook_menu_link_alter(&$item)`, but it doesn't give any result.

So can anyone please tell me how can I alter the menu link items title?

Thanks in advance

# Answer
> 1 votes
Use theme\_link function for altering your link markup. I have recently come across a scenario where I needed to change my account name to user name I did with the following code.

```
function THEMENAME_link($variables) {
  if ($variables['text'] == "My account") {
    $variables['text'] = $GLOBALS['user']->name;
  }

return '<a href="' . check_plain(url($variables['path'], $variables['options'])) . '"' . drupal_attributes($variables['options']['attributes']) . '>' . ($variables['options']['html'] ? $variables['text'] : check_plain($variables['text'])) . '</a>';
}

```

---
Tags: theming, hooks, navigation
---


title: Custom Region Empty

text:
# Question
Title: Custom Region Empty
I have created a custom region in my bootstrap sub-theme. The line in my .info file is:

```
regions[conent_bottom]  = 'Content bottom'

```

I have then added that to my page.tpl.php file using:

```
<?php print render($page['content_bottom']); ?>

```

I have flushed all caches and the new region is showing correctly on the blocks admin page. However, any blocks I allocate to the new region are not showing up on the page.

I have checked the variable for the page using:

```
<?php dpm($page); ?>

```

and the $content\_bottom variable is there but is coming up as empty.

Can anyone suggest anything that might be causing this? I'm using Bootstrap 7.x-3.5 with Drupal 7.43.

# Answer
Check your spelling: regions\[conent\_bottom\]
> 1 votes

---
Tags: 7, blocks, theming
---


# Question
Title: Pathauto and Token to get the first child term
I am trying to create URL path aliases patterns with Tokens and Pathauto.

My main issue is how to I get the child of a parent of a taxonomy term? So my url is something like this.

\[child-term:name\]/\[node:name\]

In tokens help page I can see a lot \[term:parent\] references but not child ones. I am sure is something simple but in the vast amount of tokens I cannot seem to find it.

# Answer
Thanks to @zhilevan and the link provided in his comment I got some hints.

In any case what actually worked is this:

\[node:field-region-city-location:1:name\]/\[node:title\]

So now I get correctly \[child-term:name\]/\[node:name\]

Thanks for the guidance everybody.
> 0 votes

# Answer
You can do quite advanced things with `hook_pathauto_alias_alter` to replace complex aliases patterns with just PHP code.

Here's how to use it:

```
/**
 * Implements hook_pathauto_alias_alter().
 */
function MYMODULE_pathauto_alias_alter(&$alias, array &$context) {
  // Make sure we're dealing with nodes
  if (isset($context['module']) && $context['module'] == 'node') {
    // If this is a "my_content_type" content type
    if ($context['type'] == 'my_content_type') {
      $node = $context['data']['node'];

      // do stuff with $node, such as getting the taxonomy term
      // and loading the term.. then getting the children terms etc..

      // then assign a string value to $alias
      $alias = pathauto_cleanstring($child_term->name) . '/' . pathauto_cleanstring($node->title); // for example...

      // Clean the alias
      $function = 'pathauto_clean_alias';
      if (function_exists($function)) {
        $alias = $function($alias);
      }

      // Now just make sure the alias generated is unique to this node.
      $function = 'pathauto_alias_uniquify';
      if (function_exists($function)) {
        $source = 'node/'.$node->nid;
        $lang = $node->language;

        $function($alias, $source, $lang);
      }
    }
  }
}

```
> 0 votes

---
Tags: 7, path-aliases
---


title: Where is the node_type variable set?

text:
# Question
Title: Where is the node_type variable set?
Looking at the documentation for the Drupal 8 html.html.twig template file, I notice node\_type is listed between the available variables for that template file.
Contrary to the other variables available to that template file, thought, node\_type is not set from `template_preprocess_html()` nor `_template_preprocess_default_variables()`, which are the functions I expect to set the documented variables for that template file.

What function or method initializes node\_type to the bundle of the currently viewed node for html.html.twig?

# Answer
node\_type is set in `node_preprocess_html()` from the Node module.

```
/**
 * Implements hook_preprocess_HOOK() for HTML document templates.
 */
function node_preprocess_html(&$variables) {
  // If on an individual node page, add the node type to body classes.
  if (($node = \Drupal::routeMatch()->getParameter('node')) && $node instanceof NodeInterface) {
    $variables['node_type'] = $node->getType();
  }
}

```
> 3 votes

---
Tags: nodes
---


title: drupal hook_update_N()

text:
# Question
Title: drupal hook_update_N()
1. If I install all updates from site\_name/update.php, and after change the system.schema\_version from 7005 to 7003 using (to reinstall updates 7004 and 7005)

UPDATE system SET schema\_version = 7003 WHERE name = 'test';
2. I then try to run site\_name/update.php but it not run because the fields that `hook_update_N()` adds already exists. And I see when access update.php after error that 2 updates exists.
3. After I restore system.schema\_version to its initially value (7005)

Are the updates 7004 and 7005 now installed or not?

# Answer
> 2 votes
> Are the updates 7004 and 7005 now installed or not?

Were they both installed prior to your intentionally trying to break it?

If so, then yes.

If not, then no.

# Answer
> 2 votes
What are you trying to do, and why are you trying to do this? To be honest, it makes no sense. First off, schema numbers should start at 7000 (in Drupal 7), and you should never be resetting them, particularly within hook\_update\_N(), as you're just going to cause the same code to be run every time the update process is run.

---
Tags: 7
---


# Question
Title: How to add an specific action button in views?
Is there any way to add a specific action button in view module for an entity I've created programmatically.

More specifically, I want to make a search of my entity in view, and having beside each result of the entity an action button . Currently, we can configure 'delete/edit' button. I want to add a specific one.

PS: I'm using Drupal 8 and i created my module an entity with drupal console.

# Answer
Here is the solution I found for my problem: Let say that my entity is named **Entity**. I created a new operation in my controller implementing my business logic , say we'll call it **operation\_name**. Then, in my **EntityListBuilder.php** , I surcharged the operation getDefaultOperations, specifying the name of my operation, the url and title : `public function getDefaultOperations(EntityInterface $entity) {
 $operations = parent::getDefaultOperations($entity);
 $operations['operation_name'] = array(
 'title' => $this->t('operation_title'),
 'weight' => 30,
 'url' => new Url('url',array(
 'medecin' => $entity->id(),
 )
 )
 );
 return $operations;
 }`

Back to my view configuration: In adding fields section I will add "Action link" , we will notice that the operation "operation\_name" was add to the others (edit and delete).
> 2 votes

---
Tags: views, entities, console
---


# Question
Title: How do I use block_view_alter for the template file?
I want to alter a view block. I used `hook_block_view_alter()`, but this is not working in a template theme Drupal 8.

How do I use `hook_block_view_alter()` in template theme?

# Answer
> 1 votes
I think from the \*.theme file you should use `hook_preprocess_HOOK`

---
Tags: 8, blocks
---


title: How do I get all ContentEntities?

text:
# Question
Title: How do I get all ContentEntities?
What I'm trying to do is

```
$entities = EntityInterface::loadMultiple();

```

That should give me all entities.

But when I call it, it gives me this

> Fatal error: Cannot call abstract method Drupal\Core\Entity\EntityInterface::loadMultiple()

What I need is the type and the bundles of the entities.

I don't want to get specific entities like Node, Comment, Block etc. I want to get them all.

```
$fields['node']['article'] =  <<<< I want that dynamic.

```

Something like that

```
foreach($entities as $entity) {
  $fields[$entity->getType()][$entity->bundle()] = ....
}

```

# Answer
> 4 votes
You can get around the error about the abstract method by using `entity::loadMultiple`, but you'll get a new error, because this only works from an entity subclass.

Instead of using the static method, you would have to do this dynamically:

First get all content entity types:

```
  $entity_types = \Drupal::entityTypeManager()->getDefinitions();
  $content_entity_types = array_filter($entity_types, function ($entity_type) {
    return $entity_type instanceof \Drupal\Core\Entity\ContentEntityTypeInterface;
  });
  $content_entity_type_ids = array_keys($content_entity_types);

```

Then load all entities for each type:

```
  $entities = [];
  foreach ($content_entity_type_ids as $type) {
    $entities[$type] = \Drupal::entityTypeManager()->getStorage($type)->loadMultiple();
  }

```

---
Tags: 8, entities
---


# Question
Title: How to display current user name in webform field?
I have created one webform with Name,Email id, Address fields. if user is login in name field already fill with 'login user name' and no one login then its fill with 'Anonymous'.

my issue is if user login its fill with login user name but not login then filed should be blank not fill with 'anonymous'.

Please help...

# Answer
You can alter the webform and put some and achieve this.

```
<?php
    function module_name_form_alter(&$form, &$form_state, $form_id) {
   // module_name = your custom module name.
       if($form_id =='webform_name')
        // webform_name = your webform id
           //check condition for non login user
           if(!user_is_logged_in()){
            {
             $form['submitted']['field_name']['#default_value']= 'anynomous';
             // field_name = Field name
            }
         }
    }

    ?>

```

You also need to debug using dpm. Which helps you solve you problem easily.

I believe that you can also do this using Rules module. You also need to try for this.
> 1 votes

---
Tags: 7, webforms
---


# Question
Title: How to allow users programatically to post and view posts regardless of they are trusted contact or not in drupal commons
All is in the title, actually users can only posts privately to theirs trusted contacts and sees posts of trusted contacts. I don't need such restriction in my project and want to bypassing this restriction so all users except anonymous can posts and see posts.

That beeing said, I don't wanna change they way groups works, so if group is private all posts in the group should stay private.

I've searched in commons\_trusted\_contacts module and I can't figure out where this is been handle. I've tried to set group\_content\_access value to 1 in database (1|Public - accessible to all site users) but this doesn't seems to be the way.

# Answer
I found out that commons\_trusted\_contacts module is setting content access as private while posting for trusted contacts, which add post to user group so that only user's trusted contacts sees posts.

In order to post regardless of users are trusted contact or not, I've changed value of group\_content\_access to public. This way posts are not assigned to any group so it's visible for all users. In database, gid is then set to 0 instead of uid representing user group.

Bellow the line I've changed

```
$wrapper->group_content_access->set(OG_CONTENT_ACCESS_PRIVATE);

```

to

```
$wrapper->group_content_access->set(OG_CONTENT_ACCESS_PUBLIC);

```
> 0 votes

---
Tags: organic-groups, 7
---


# Question
Title: Alternative themed forms for a single custom content type
On a site I would like a "quick entry" form for a custom content type on the front page, while also keeping the "normal" non-customized "node/add/mycontenttype" form. I'm able to customize the "normal" form by using the theme\_hook function returning the proper array which points to my function that renders the form ('template' =\> 'some-node-form').

But ideally I would like to keep both versions of the form, rendering my customized form on the frontpage in a block, and with the normal form at the normal place "node/add/mycontenttype". I figured I could try to detect at runtime in the 'some-node-form' function if for instance it was invoked through a special path "node/add/mycontenttype/frontpage", by passing a variable or similar. I haven't quite managed to do this yet, but at least in theory it should be doable.

But do any experienced Drupal developers have better ways of accomplishing what I'm doing, things like having multiple paths pointing to different template rendering functions or similar?

# Answer
My first thought (in Drupal 6) would be to use hook\_form\_alter to set a different #theme value in the form depending on the path.

eg

```
mymodule_form_alter(&$form, &$form_state, $form_id) {
 if ($form_id = 'my_form_id') {
  if ($_GET['q'] == 'somepath') {
   $form['#theme'] = 'function_one';
  } elseif ($_GET['q'] == 'someotherpath') {
    $form['#theme'] = 'function_two';
  }
 }
}

```
> 0 votes

# Answer
cam8001 clued me in regarding the '#theme' setting. In my template.php I have:

```
<?php

function groc_theme($existing, $type, $theme, $path) {
  return array(
    'purchase_node_form_fp' => array(
      'render element' => 'form',
      'template' => 'groc-purchase-node-form'
    )
   );
}

function groc_form_alter(&$form, &$form_state, $form_id) {
  if (arg(3) == 'fp') {
    $form['#theme'] = 'purchase_node_form_fp';
  }
 }
?>

```

and in my groc-purchase-node-form.tpl.php I then render the special form. In the groc\_form\_alter above I have hardcoded a path element instead of using a request parameter, but it's similar to the accepted solution. The way the code above works is that if I want the "special" form, I just add on a "/fp" to the normal add node link.
> 0 votes

# Answer
What I ended up doing in my implementation was using entityform (D7) and using rules to map and create the appropriate node when the entity form saves.
> 0 votes

---
Tags: 7, forms, theming
---


# Question
Title: CSS defined in library is not included, but theme works
themes/custom/teleci/teleci.info.yml:

```
base theme: bartik
core: 8.x
name: Teleci
package: Custom
type: theme
version: "1.1"
libraries:
  - teleci/global-styling

```

themes/custom/teleci/teleci.libraries.yml:

```
global-styling:
  version: "1.1"
  css:
    theme:
      css/override.css: {}
      css/style.css: {}

```

I also have custom template in `themes\custom\teleci\templates\block--teleci-branding.html.twig` that is loading correctly - that means the theme works. But the CSS files are not included (they are not in the generated HTML).

I tried

* `php drupal.phar cr all`
* setting bartik as default and then set my theme back
* clear browser cache
* open in private window
* disable JS/CSS minification in settings
* check both yml files in yamllint.com
* disable base theme (bartik)

I'm out of ideas and would appreciate any help :(

**Update:** I created minimal theme (that does not work as well) for you to test. Could you please test it and let me know if it works for you? https://github.com/tomasfejfar/drupal-simple-theme/ (i have it in `/themes/custom`)

**Update 2:** the mini-theme works when I fixed a small bug that is not present in my theme. So there is something about my theme that makes it break.

# Answer
> 0 votes
Finally it seems to have been fixed. **I re-created the same template again under a new name.** Checked the diff of `theme.info.yml` and `theme.libraries.yml` files - only difference is the name. The new template has all the same functionality the previous had and is 1-to-1 copy except for the name. So only thing I can think of is that while playing with the template something has broken and left some residue in the database that prevented the theme from functioning properly ever again.

Thanks everyone who tried to help!

---
Tags: 8, theming
---


title: Trying to add CSS styles to a theme

text:
# Question
Title: Trying to add CSS styles to a theme
This is the content of the .info.yml file.

```
name: Endymion
description: Drupal 8 starter theme
type: theme
core: 8.x

libraries:
    - endymion/global-css

regions:
  header: Header
  primary_menu: 'Primary menu'
  breadcrumb: Breadcrumb
  content: Content
  sidebar_first: 'Sidebar first'
  footer_first: 'Footer first'

```

This is the content of the .libraries.yml file.

```
global-css:
    css:
        theme:
            css/css1.css: {}

```

I keep getting this error message:

> The website encountered an unexpected error. Please try again later.

How do I fix this error?

Additional point:

Get the same error message whether I'm running locally or on a remote server (siteground)

# Answer
AFAIK you should use 2 spaces to indent your YAML. It seems you either use 4 spaces or a tab.

That is the case for the libraries files as well as the libraries key in info file.
> 2 votes

---
Tags: theming, 8
---


title: How to create product template?

text:
# Question
Title: How to create product template?
Please see the red box. In Magento there is a feature where i can create Product Templates - templates can be created for products with different fields.

I know i can create Content Types for this, but i felt that will make too many Content Types. Is there another work around this so that it's like Magento? Is there a module for it.

Thanks!

# Answer
> 0 votes
In Drupal Commerce you can just make product types and it will generate product displays (content types) meant for building the presentation. The product type holds all the meta data about the product itself.

# Answer
> -1 votes
With different fields for each template you have two ways:

1. different content types
2. one (maybe extreme large) content type with all fields, and then hide unused fields, depends on template choosen (template options in taxonomy list). You can use conditional fields module: https://www.drupal.org/project/conditional\_fields still not ready for drupal 8, but as you can see issue, will be ported soon. If not, you can write own module or use some ugly javascript to hide fields.

---
Tags: theming, commerce
---


# Question
Title: Add 2 flag fields of 2 types of flag to views field
I have two kinds of flags. Each flag has a field that gets a value. I want to add these field in one field of views. Any user can flag a content by two kinds of flags.

Should I use "views field view"? What is the instruction?

# Answer
> 2 votes
You may be able to do this with native views.

Using field rewriting in views you can insert values into field display originating from other fields in the same row if they are ordered to appear above it. You can also use a "Global: Custom Text" field and add values and HTML to construct complex output.

Add the fields you want to be displayed as part of the rewritten/global field should be ordered to appear above it by clicking the reorder button and using the handle bars to drag fields up and down.

Those fields you want to merge should be set to exclude from display.

Those hidden fields will be available as a token value you will be able to use elsewhere in the view row in the global custom text field, or combined field.

---
Tags: 7, views, flags
---


# Question
Title: How to create a rule that unpublishes comments that contain links?
I'm trying to create a rule that does the following.

* **Event**: After saving new content type Forum Topic
* **Conditions**:

+ User has role 'authenticated', and
    + Content body contains link (*this is the part I can't figure out*)
* **Actions**:

+ Unpublish Content
    + Show a message on the site:

    > "Your user permissions currently do not allow for you to post a forum topic that contains a link. Please remove all links from your post and re-submit by clicking the following edit link: \[node:edit-url\]
    >
    > This precaution helps us keep our forum and comments spam free. If you would like the ability to post links, please e-mail the site admin: \[site:mail\]"

The general idea is that I want users to register to the forum and be able to create new forum topics but not be allowed to post links since this is the whole purpose behind spam. Once they make a few quality posts, I'll move them to a trusted user group that this rule doesn't apply to, allowing them to post links.

The reason why I don't want to use Text Formats to strip out tags is because the spam post will still be published, minus the links. This will lead to offensive, spammy posts still showing up in the forum index.

# Answer
> 0 votes
Enable the module **PHP Filter** that comes in core. This adds a new condition named `Execute custom PHP code`, which must return TRUE or FALSE.

Then write a PHP snippet in that condition that uses PHP's `preg_match` on the $node-\>body field. You can find regex patterns to check for valid URLs in many places, for example here.

# Answer
> 1 votes
Look at honeypot and hidden capchta before getting too many rules involved.

# Answer
> 0 votes
I trust the solution in argiepiano's answer works, but for all sorts of reasons mentioned in the answer to "What are the downsides of using PHP Filter code in blocks, nodes, views-args, etc?" you should try to avoid using the PHP filter whenever possible.

Here is a prototype of a rule, in Rules export format, that should also answer your question:

```
{ "rules_find_links_in_body" : {
    "LABEL" : "Find links in body",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "node_insert--article" : { "bundle" : "article" } },
    "IF" : [
      { "user_has_role" : {
          "account" : [ "site:current-user" ],
          "roles" : { "value" : { "2" : "2" } }
        }
      },
      { "OR" : [
          { "text_matches" : {
              "text" : [ "node:body:value" ],
              "match" : "http(|s):\/\/+",
              "operation" : "regex"
            }
          },
          { "text_matches" : {
              "text" : [ "node:body:value" ],
              "match" : "ANotAllowedTextStringInBody",
              "operation" : "regex"
            }
          }
        ]
      }
    ],
    "DO" : [
      { "drupal_message" : { "message" : "Node body contains an URL ..." } }
    ]
  }
}

```

Some more details about the above prototype rule:

* **Rules Event** = After saving new content of type "Article" (adapt the type to fit your needs).
* **Rules Conditions**:
    + Check if the current user is an authenticated user.
    + Perform a text comparison, using a **Regular Expression** as the **Comparison operation** (which you can perfectly do in Rules, without using the PHP filter for it. For the actual regular expression, this rule uses `http(|s)://+`, which will discover strings that start with either `http://` or `https://`, and which should be pretty close to the "*contains a link*" as in your question. Should you have additional / similar requirements to discover variations of this (say some other string like `ANotAllowedTextStringInBody`), another Rules Condition (with an *OR*) will take care of that also.
* **Rules Action** = Show a message on the site (adapt the message to fit your needs), and add other relevant Rules Actions.

**Voilà**, no PHP filter needed.

---
Tags: 7, rules, advertising
---


# Question
Title: Drupal as an interface for users to Add/Edit/Search a database
I have a friend who wants to set up a site for an NPO that basically **allows users to search and edit a data table** with about 100 fields. My solution (being from the MS world) would be to set up a simple MVC.Net site which pretty much auto-generates pages and forms for searching and editing rows. The technology the NPO has set up however, is Drupal 7 running on Apache with a MySQL instance floating around in there.

I've searched Drupal modules and poked around with things like Data which seemed fit for constructing a UI that searches and modifies DB tables, but didn't see any way to make it work. This seems like it would be a pretty common problem people want to solve though. **Can anyone propose some appropriate tools/modules for setting up such a site?**

---

That's my question, but if you are looking for some additional information about what they're trying to accomplish, here's some relevant details:

* The data we want to kick off the site with is about 300 rows in an excel spreadsheet. Something supporting a bulk data import would be preferable, but isn't required. I've already converted the data into an SQL db, so if we can simply point a module to the database, that would be great too.
* Most of these are plain text fields, some are numeric, some are paragraph format (with line breaks). Rather than just text boxes for everything though, while editing and searching on certain fields, they want to present the user with a drop-down list of available values.
* On the same vein as having drop-down lists for certain fields, forms that supports some customization (such as custom data validation routines) would probably be handy.
* I have a grand total of about 10 hours of experience working with Drupal, but I'm comfortable with installing and configuring modules, and have ssh access to the server.

# Answer
Start off with something like this:

If you need to manipulate the data tables directly, that's not exactly what Drupal is built for. It's more than a Front End. It's a full CMF.
> 4 votes

# Answer
Well, yes.

Technically you can probably do this. If the database is on the same DB platform (Mysql, MariaDB, Postgres, etc) there are a few things you can do.

You can connect Drupal to more than one database at once.

You can visualize data in an external database/tables using views

So, that solves the read part. However, writing to that DB would require some custom PHP work to create a custom module that will generate a Drupal form and write the data to the DB. This is very possible, and requires a bit of PHP knowledge.

You will probably also need to expose this to a menu item and made available at a URL on your Drupal site, so you'll need to also know about menu routing, so this is a really nice holistic guide to that.
> 0 votes

---
Tags: 7, database
---


# Question
Title: I cannot add a new CSS class to the classes_array array
I'm using Drupal 7, and a Bootstrap sub-theme. I am using the following code to add a new CSS class (taxonomy-\[vocabulary-name\]) to the classes\_array array.

### template.php

```
function bootstrap_gstt_preprocess_html(&$variables) {
  if (arg(0) == 'node' && is_numeric(arg(1))) {
    $node = node_load(arg(1));
    $results = _bootstrap_gstt_taxonomy_node_get_terms($node);
    $taxonomy_vocab = $results->name;
    if (is_array($results)) {
      foreach ($results as $item) {
        $taxonomy_vocab = "taxonomy-".strtolower(drupal_clean_css_identifier($item->name));
        $variables['classes_array'][] = $taxonomy_vocab;

        $variables['classes'] = implode(' ', $variables['classes_array']);
        dpm($variables['classes_array']);
      }
    }
  }
}

function _bootstrap_gstt_taxonomy_node_get_terms($node, $key = 'tid') {
  static $terms;
  if (!isset($terms[$node->vid][$key])) {
    $query = db_select('taxonomy_index', 'r');
    $t_alias = $query->join('taxonomy_term_data', 't', 'r.tid = t.tid');
    $v_alias = $query->join('taxonomy_vocabulary', 'v', 't.vid = v.vid');
    $query->fields( $t_alias );
    $query->condition("r.nid", $node->nid);
    $result = $query->execute();
    $terms[$node->vid][$key] = array();
    foreach ($result as $term) {
      $terms[$node->vid][$key][$term->$key] = $term;
    }
  }
  return $terms[$node->vid][$key];
}

```

### html.tpl.php

```
<!DOCTYPE html>
<html<?php print $html_attributes;?><?php print $rdf_namespaces;?>>
<head>
  <link rel="profile" href="<?php print $grddl_profile; ?>" />
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <?php print $head; ?>
  <title><?php print $head_title; ?></title>
  <?php print $styles; ?>
  <!-- HTML5 element support for IE6-8 -->
  <!--[if lt IE 9]>
    <script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script>
  <![endif]-->
  <?php print $scripts; ?>
</head>
<body<?php print $body_attributes; ?>>
  <div id="skip-link">
    <a href="#main-content" class="element-invisible element-focusable"><?php print t('Skip to main content'); ?></a>
  </div>
  <?php print $page_top; ?>
  <?php print $page; ?>
  <?php print $page_bottom; ?>
</body>
</html>

```

With `dpm($variables['classes_array']);`, the new CSS classes I added appear in the array, but they aren't output as body CSS classes.

Is there anything I need to change in my code?

# Answer
You simply do as Drupal does in its html.tpl.php file. Instead of using `<body<?php print $body_attributes; ?>>`, you use the following code.

```
<body class="<?php print $classes; ?>" <?php print $attributes;?>>

```

`$attributes` is set from `template_preprocess()` with the following code.

```
  // Flatten out attributes, title_attributes, and content_attributes.
  // Because this function can be called very often, and often with empty
  // attributes, optimize performance by only calling drupal_attributes() if
  // necessary.
  $variables['attributes'] = $variables['attributes_array'] ? drupal_attributes($variables['attributes_array']) : '';
  $variables['title_attributes'] = $variables['title_attributes_array'] ? drupal_attributes($variables['title_attributes_array']) : '';
  $variables['content_attributes'] = $variables['content_attributes_array'] ? drupal_attributes($variables['content_attributes_array']) : '';

```

Also, you don't need the following line in `bootstrap_gstt_preprocess_html()`.

```
$variables['classes'] = implode(' ', $variables['classes_array']);

```

`template_process()`, which is executed after `bootstrap_gstt_preprocess_html()`, contains the following code.

```
  // Flatten out classes.
  $variables['classes'] = implode(' ', $variables['classes_array']);

```

So, what your code is doing is already done from Drupal.

As side note, this what I would change in the code you shown.

```
$results = _bootstrap_gstt_taxonomy_node_get_terms($node);
$taxonomy_vocab = $results->name;
if (is_array($results)) {
  // Omissis.
}

```

Since `_bootstrap_gstt_taxonomy_node_get_terms()` is surely returning an array, you cannot access an object property as you do with `$results->name`.

```
$t_alias = $query->join('taxonomy_term_data', 't', 'r.tid = t.tid');
$v_alias = $query->join('taxonomy_vocabulary', 'v', 't.vid = v.vid');

```

If you are going to use the value returned from `$query->join()`, then you should use the following code.

```
$t_alias = $query->join('taxonomy_term_data', 't', 'r.tid = %alias.tid');
$query->join('taxonomy_vocabulary', 'v', "$t_alias.vid = %alias.vid");

```

Also, since you are using `$key` (whose default value is `'tid'`) in the rest of the code, you should probably use the following code.

```
$t_alias = $query->join('taxonomy_term_data', 't', "r.$key = %alias.$key");
$query->join('taxonomy_vocabulary', 'v', "$t_alias.vid = %alias.vid");

```

To understand what %alias means, see `SelectQuery::join()`.

> **$condition**: The condition on which to join this table. If the join requires values, this clause should use a named placeholder and the value or values to insert should be passed in the 4th parameter. For the first table joined on a query, this value is ignored as the first table is taken as the base table. The token %alias can be used in this string to be replaced with the actual alias. This is useful when $alias is modified by the database system, for example, when joining the same table more than once.

If you are sure the same table is not joined more than once, you can simply ignore the value returned from `$query->join()` and use the following code.

```
$query->join('taxonomy_term_data', 't', "r.$key = t.$key");
$query->join('taxonomy_vocabulary', 'v', 't.vid = v.vid');

```
> 1 votes

---
Tags: 7, theming
---


# Question
Title: How do I add a column to the table shown in the vocabulary listing page?
I need to add a column to the table shown in the page listing the vocabularies defined for a site. How can I achieve this?

>

# Answer
You would need to override the class generating the list builder output on this page, then fill in the methods with what you want:

```
  /**
   * {@inheritdoc}
   */
  public function buildHeader() {
    $header['label'] = t('Vocabulary name');
    $header['foo'] = t('Custom Header');
    return $header + parent::buildHeader();
  }

  /**
   * {@inheritdoc}
   */
  public function buildRow(EntityInterface $entity) {
    $row['label'] = $entity->label();
    $row['foo'] = 'custom_value';
    return $row + parent::buildRow($entity);
  }

```

See this related question: Can you change the list builder class used by an entity?

So, in essence:

```
function mymodule_entity_type_alter(array &$entity_types) {
  /** @var $entity_types \Drupal\Core\Entity\EntityTypeInterface[] */
  $entity_types['taxonomy_vocabulary']->setListBuilderClass('Drupal\mymodule\VocabularyListBuilder');
}

```

Then, in your mymodule/src folder, create a VocabularyListBuilder.php, and copy in from the core/modules/taxonomy/src/VocabularyListBuilder.php and modify the two methods above for your output (since they'll be basically identical).

You could also do this with a View page as well, but for archival purposes wanted to explain how this works in general for Drupal core. List builder classes are such a cool and useful new D8 thing.
> 10 votes

---
Tags: 8, taxonomy-terms
---


title: Views - Filter Dates/Years

text:
# Question
Title: Views - Filter Dates/Years
I'm stuck on a necessary component for a website I'm working on.

I've got a content type called "Photograph" which has a variety of fields including one for "Date", which includes a variety of entries including just the year, or the year and month, or the full date.

My problem is that I cannot select a date earlier than 2013, which is a problem because some of these photographs date from 1848 on up. That leaves me with the option of a calendar selection, or by entering the date itself, which doesn't work for ease to visitors. So I'd like to use the selection option (with a focus mainly on years), but how do I edit the select options to include the years that I need included?

# Answer
> 2 votes
By default, the Date field's Views integration sets a +/- 3 year range for date filters. If you want to expand this beyond this range, set the **Starting year** & **Ending year** settings to *Other*.

This option will let you enter an arbitrary year from which your select box will start and end.

---
Tags: 7, views, datetime
---


# Question
Title: How to sort taxonomy terms on a term reference field?
I have a taxonomy term reference field on a node. On the "node/add" page I would like to sort the terms by "due date" (a field added to that vocabulary).

# Answer
If you're stuck using a term reference field, here are some widget options:
> 5 votes

# Answer
I had succsefull manage this by this module, Views Term Hierarchy Weight Field, just add (hidden) Hierarchical weight field, then, on sort settings, sort by this new field.
> 0 votes

---
Tags: 7, taxonomy-terms
---


# Question
Title: How do I delete all menu links from a menu using the menu machine name in Drupal 8
I trying to get the existing menu items and then delete them in bulk but I'm getting an error trying to load them.

```
$query = \Drupal::entityQuery('menu_link')
->condition('menu_name', 'mycustommenu')
// Order by weight so as to be helpful for menus that are only one level deep.
->sort('weight');
$result = $query->execute();

Drupal\Component\Plugin\Exception\PluginNotFoundException: The "menu_link" entity type does not exist. in Drupal\Core\Entity\EntityTypeManager->getDefinition() (line 125 of core/lib/Drupal/Core/Entity/EntityTypeManager.php).

```

Can someone suggest how I might do this better thanks.

# Answer
```
$mids = \Drupal::entityQuery('menu_link_content')
  ->condition('menu_name', 'browse')
  ->sort('weight')
  ->execute();

$controller = \Drupal::entityTypeManager()->getStorage('menu_link_content');
$entities = $controller->loadMultiple($mids);
$controller->delete($entities);

```
> 2 votes

---
Tags: navigation
---


# Question
Title: How do I display serialized 'REST Export' with date format rather than timestamp?
I am using csv\_serialization contrib module to add csv encoding to the core Serialization output formats.

I have a view with a REST export display to allow the download of contact form 'message' entities, and as each contact form might have different fields I must return a (serialized) *Entity* rather than *Fields* (with the option to configure each field's display).

The resulting csv download lists created date as a unix timestamp and I need to format it as a human readable time and date, but as far as I can see the 'REST export' does not go through rendering so I cannot preprocess it in the same way I might with a different type of Views display.

# Answer
> 2 votes
Even with the rows being displayed as entities, you can have a `hook_views_pre_render(&$views)` invocation alter the entity field properties before they are used they are rendered out.

```
function MYMODULE_views_pre_render($view) {

  // Only alter my_view_machine_id view, rest_export display
  if ($view->id() == 'my_view_machine_id' &&
      $view->getDisplay()->definition['id'] == 'rest_export') {
    foreach ($view->result as $row) {
      if (isset($row->_entity->created)) {
        // Alter the entity created property to a readable ISO8601 date
        $row->_entity->created->setValue(date('c', $row->_entity->created->value));
      }
    }
  }
}

```

There might be a better part of Views rendering pipeline (e.g. REST views export has some templating system) to place this in, but it still renders out the altered serialized property.

---
Tags: importing-exporting, 8
---


title: CSS Junk files in the css folder

text:
# Question
Title: CSS Junk files in the css folder
What are all those junk CSS files in site/files/css with names like css\_ZFCUUB6IIfaVQ-erWDr0M0Na1JbxEsU-8zjQrWAtrbU.css? There are hundreds of them.

How do these get generated over time? What do they do?

# Answer
> 5 votes
They aren't junk files, they are aggregated files are generated when you have CSS aggregation turned on. They make your page load times faster, as multiple files are aggregated into a single file, meaning less files have to be downloaded to the browser.

# Answer
> 3 votes
Yes @Jaypan is right. You need to check on admin/config/development/performance. In the *Bandwidth optimization* section there is an option for *Aggregate and compress CSS files*. Deselect that option and save, if you want to remove them.

Clear the cache and check.

---
Tags: theming
---


# Question
Title: When and where should I replace tokens on a custom path for metatag context?
I have custom tokens defined in `hook_token_info()` and `hook_tokens()`. I need these tokens to populate metatag data for the **metagag** module on a custom path. I have the **context** module installed as well.

The path routes to a callback that loads the object I need to pass to `token_replace().`

My question is when and where do I call `token_replace()` so the tokens are available to **metatag context** on page load?

# Answer
> 0 votes
The correct place to specify the replace data was in `hook_tokens()`. I did not follow the original tutorial correctly and thought since my tokens were not available I was in the wrong place.

I ended up specifying my tokens as the **current-page** type. After I did that, they displayed and I can now use them for my metatags.

As a side note, I did discover you need to run cron after you make changes to `hook_token_info()`.

---
Tags: 7, tokens, meta-tags
---


title: Install New Module Link Not There

text:
# Question
Title: Install New Module Link Not There
I've seen this question posted elsewhere here but I haven't seen an answer for it. I am new to Drupal and I'm interested in installing some modules via the Drupal interface, but I don't see the "Install New Module" link on the modules page. (Yes, update manager is already enabled, and going to admin/modules/install doesn't get me anywhere).

# Answer
There are 2 components to the *Install New Module* UI access callback:

* It requires the *Administer software updates* permission for the user to be enabled. It can be enabled for any user role underneath the **People \> Roles** administration section for the relevant user role.
* It requires `update_manager_access` variable to be set to TRUE. By default, this should be `TRUE`, but it can be overridden in **settings.php** or manually set (e.g. `drush vset update_manager_access 0`). In which case, it needs to be adjusted in settings.php or by updating the variable in the database (`drush vset update_manager_access 1`).
> 0 votes

# Answer
If every thing is fine @Lisa and still you didn't find "Install new module" under Modules than may be there is a problem with the installation of your drupal version. May be its not installed properly.
> 0 votes

---
Tags: installation
---


# Question
Title: How can I implement a flag module with caches but won't affect cache the flagging nodes?
According to a post here, I have installed flag module to implement product comparison. However I found that the CPU usage is very high 80-90%, then I tried to install boost and Views content cache to improve the performance. The result is good, CPU usage drop to around 10%, but when I flag(add) or unflag(remove) the node from the views, it not work.

# Answer
Views Content Cache has a patch for flags support, although I don't know how well it will work with Boost.

Try using the Views Flag Refresh module, it's supposed to tell the view when to refresh, don't know if it will play nice with the other modules though.
> 0 votes

---
Tags: 6, performance, flags
---


# Question
Title: Cached rendering depending on a parameter
I'm trying to render a template given a request parameter but I get the same result once the cache is set.

Let's say I have this template :

```
-- {{ step }} -- {{ xxx }} --
{% if not step %}not step{% endif %}
{% if step == 1 %}step 1{% endif %}
{% if step == 2 %}step 2{% endif %}

```

And this preprocessor

```
function themename_preprocess_page(&$variables) {
    $request = \Drupal::request();
    $variables['step'] = null;
    $variables['xxx'] = rand ();

    if ($request->query->has('step')) {
        $variables['step'] = $request->query->get('step');
    }
}

```

When I work with the cache template disabled, I get the expected resut, e.g when requesting `page?step=1`, I get `step 1`, `page?step=2`, I get `step 2` and so on. However, when the cache is enabled, the first page load is correct and the subsequent loads take the same markup (if I first load `page?step=1`, I get `step 1` whatever parameter I use after that).

How can I tell Drupal to process my variable even if the cache is enabled?

# Answer
Add the cache context `url.query_args` in preprocess:

```
function themename_preprocess_page(&$variables) {
  $variables['#cache']['contexts'][] = 'url.query_args';

```

Or more specific:

```
  $variables['#cache']['contexts'][] = 'url.query_args:step';

```
> 8 votes

---
Tags: 8, caching
---


# Question
Title: How to get child terms based on parent terms between two different taxonomies
I have created two vocabulary

1. Program
2. Topics

I want to load the topics based on the program selection.

It looks like category and subcategory.

I created some program like java, .net, PHP and I created some topics like session (php), inheritance(java), cookie(php).

So now I want to list all the topics which are coming under a particular program.

Can you tell me which drupal function used to get all the terms under parent terms.?

Note: `taxonomy_get_children` not working because I am using two vocabularies

# Answer
You'll need to load your content's term references and then load those term entities so you can follow your chain of taxonomy terms. There's many ways to do that; `taxonomy_term_load_multiple()` is one such function.

```
$tids = array();

// @TODO: Use the $nid that corresponds with your node
// @TODO: Replace field_program & field_topic with your taxonomy ref field name
$node = node_load($nid);
foreach ($node->field_programs[LANGUAGE_NONE] as $term) {
  $tids[] = $term['tid'];
}
$programs = taxonomy_term_load_multiple($tids);

// @TODO: Iterate over $programs and retrieve
// topic tid references from $program->field_topic[LANGUAGE_NONE]

```
> 0 votes

# Answer
You can add code in template.php as theme\_preprocess\_page()
`if(arg(0) == 'taxonomy' && arg(1) == 'term')
 {
 $tid = (int)arg(2);
 $term = taxonomy_term_load($tid);
 $arrTermId = taxonomy_get_children($tid);
 $arrData = taxonomy_select_nodes(array_keys($arrTermId), $pager = TRUE, $limit = FALSE, $order = array('t.sticky' => 'DESC', 't.created' => 'DESC'));
 $arrContent = node_load_multiple($arrData, $conditions = array(), $reset = FALSE);
print_r($arrContent);
 }`

In $arrContent you will get values of all the nodes.
> 0 votes

---
Tags: 7, taxonomy-terms
---


# Question
Title: Error - Sharing the Same URL for two different views in exposed filter
My goal is to prepare glossary based on contents

I have used two views, one is alphabetical search and another one is keyword search filter.

In alphabetical search, I grouped the alphabets and setted in the block and then clicking the letters, It will take to the page which contains the particular content. And here, I have used the URL is local host/glossary.

In Keyword search, Here also used the same URL (localhost/glossary), I setted the search functionality in the block and when searching the content using keywords of contents.

Its not filtering for keyword search, does only for alphabetical search.

I want to filter the both in same URL.

Please help me to sort out this issue.

# Answer
You can use Views Glossary to create a glossary that is grouped alphabetically, and then add an exposed filter to search by Keyword.

Enabling the module provides you with an example view that you can clone and modify to get the functionality you need.

1. Clone the view "Views Glossary Example" to create your `/glossary` view
2. Add your exposed filter for your keyword search.
3. Open contextual filters and change the Title filter to "Display all results for the specified field" when the filter value is not in the URL. If you don't do this, the view will only display results for 'A' when no letter is selected.

This will allow users to simultaneously search the glossary using keywords and/or filter the glossary alphabetically.
> 0 votes

---
Tags: 7, views
---


# Question
Title: Drupal gives error while add content or edit node
Hi all i am facing this error when try to edit node or add content

Additional uncaught exception thrown while handling exception.

Original

```
PDOException: SQLSTATE[HY000]: General error: 2006 MySQL server has gone away: INSERT INTO {watchdog} (uid, type, message, variables, severity, link, location, referer, hostname, timestamp) VALUES (:db_insert_placeholder_0, :db_insert_placeholder_1, :db_insert_placeholder_2, :db_insert_placeholder_3, :db_insert_placeholder_4, :db_insert_placeholder_5, :db_insert_placeholder_6, :db_insert_placeholder_7, :db_insert_placeholder_8, :db_insert_placeholder_9); Array ( [:db_insert_placeholder_0] => 1 [:db_insert_placeholder_1] => node [:db_insert_placeholder_2] => %type: !message in %function (line %line of %file). [:db_insert_placeholder_3] => a:6:{s:5:"%type";s:12:"PDOException";s:8:"!message";s:238:"SQLSTATE[HY000]: General error: 2006 MySQL server has gone away: SELECT 1 AS expression FROM {variable} variable WHERE ( (name = :db_condition_placeholder_0) ); Array ( [:db_condition_placeholder_0] =&gt; drupal_http_request_fails ) ";s:9:"%function";s:14:"variable_set()";s:5:"%file";s:74:"/home/apetrdo6/public_html/Development/InfinityPups/includes/bootstrap.inc";s:5:"%line";i:991;s:14:"severity_level";i:3;} [:db_insert_placeholder_4] => 3 [:db_insert_placeholder_5] => [:db_insert_placeholder_6] => http://apetrailportfolio.com/Development/InfinityPups/node/add/dogs [:db_insert_placeholder_7] => http://apetrailportfolio.com/Development/InfinityPups/node/add/dogs [:db_insert_placeholder_8] => 103.63.25.150 [:db_insert_placeholder_9] => 1473159652 ) in dblog_watchdog() (line 160 of /home/apetrdo6/public_html/Development/InfinityPups/modules/dblog/dblog.module).

Additional

PDOException: SQLSTATE[HY000]: General error: 2006 MySQL server has gone away: SELECT 1 AS expression FROM {variable} variable WHERE ( (name = :db_condition_placeholder_0) ); Array ( [:db_condition_placeholder_0] => drupal_css_cache_files ) in variable_set() (line 991 of /home/apetrdo6/public_html/Development/InfinityPups/includes/bootstrap.inc).

Uncaught exception thrown in session handler.

PDOException: SQLSTATE[HY000]: General error: 2006 MySQL server has gone away: UPDATE {users} SET access=:db_update_placeholder_0 WHERE (uid = :db_condition_placeholder_0) ; Array ( [:db_update_placeholder_0] => 1473159609 [:db_condition_placeholder_0] => 1 ) in _drupal_session_write() (line 219 of /home/apetrdo6/public_html/Development/InfinityPups/includes/session.inc).

Uncaught exception thrown in shutdown function.

PDOException: SQLSTATE[HY000]: General error: 2006 MySQL server has gone away: DELETE FROM {semaphore} WHERE (value = :db_condition_placeholder_0) ; Array ( [:db_condition_placeholder_0] => 80080962057cea1b962fce6.76953018 ) in lock_release_all() (line 269 of /home/apetrdo6/public_html/Development/InfinityPups/includes/lock.inc).

```

# Answer
One possibility to solve is to increase "max\_allowed\_packet" .

> ```
>     Go to xampp\mysql\bin
>     Open my.ini
>     Change "max_allowed_packet" from "1m" to "16m"
>     Save my.ini
>     Now restart MySql through the XAMPP control panel.
>
> ```

Or

settings.php

```
ini_set('max_allowed_packet', '1024M');

```
> 0 votes

---
Tags: 7, theming
---


# Question
Title: Why isn't media respecting my allowed file type settings
In my field settings for a media based image field, I have this:

When I upload an image and click next I get the following:

both of those types allow image files, but this particular field should only allow items to be classified as images. Why is the setting not being respected?

# Answer
My guess based on my own experience is that the uploaded file shares the same mime type as the publication files configuration, and the system is asking the user which file type to designate. Example, if both types allow for PNGs, it won't be able to determine the file type for you. Try uploading a file who's mimetype isn't shared by others; you won't get that dialog.
> 1 votes

---
Tags: 7, entities, media
---


# Question
Title: Redirect to home page without using deprecated methods
I am attempting to add some code to a `hook_entity_view_alter()` function to redirect the user to the homepage under a rare condition with `RedirectResponse`.

I understand the method to accomplish this is along these lines (taken from here):

```
$response = new Symfony\Component\HttpFoundation\RedirectResponse($url);
$response->send(); // don't send the response yourself inside controller and form.
return;

```

My issue is that I am not sure how to format `$url`. Most articles on the topic, such as this one, suggest using `\Drupal::url()`, but this is deprecated in favour of `Drupal\Core\Url`. I would like to avoid using deprecated methods as much as possible, but am stuck at trying to figure out what the `Drupal\Core\Url` equivalent is to `\Drupal::url('<front>')`. I am not sure which methods to be using, and nothing I've tried with `Url::fromUri()` has worked.

# Answer
Try using Url::fromInternalUri then instead of fromUri():

https://api.drupal.org/api/drupal/core!lib!Drupal!Core!Url.php/function/Url%3A%3AfromInternalUri/8.2.x

It specifically notes the use of `front` and `none`. But you can't pass the URL object or path tokens to RedirectResponse, as this is a Drupal construct. That class expects the following arguments:

http://api.symfony.com/2.3/Symfony/Component/HttpFoundation/RedirectResponse.html

```
string  $url        The URL to redirect to
integer $status     The response status code
array   $headers    An array of response headers

```

`$url` needs to be a string, so on your URL object, call -\>toString() to get the URL.

https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Url.php/function/Url%3A%3AtoString/8.2.x
> 2 votes

---
Tags: 8, uri, redirection
---


# Question
Title: Establish whether a node is NEW in a custom #submit function
I need to test whether a user is creating a new node as opposed to editing an existing node in a custom #submit function added to a node edit/creation form.

I can access the node via

```
$node = $form_state->getFormObject()->getEntity();

```

$node-\>id() - gives the new node ID so cant be used.

$node-\>get('nid') - also gives an gives the new node ID so cant be used.

$node-\>isNew() - This is actually FALSE in this hook despite it being new content.

# Answer
You could try this method:

```
if ($form_state->getFormObject()->getOperation() == 'edit') {
  // existing node
}

```

These are the operations defined for node:

```
 "form" = {
   "default" = "Drupal\node\NodeForm",
   "delete" = "Drupal\node\Form\NodeDeleteForm",
   "edit" = "Drupal\node\NodeForm"
 },

```
> 4 votes

# Answer
You can implement hook\_entity\_presave to look at an entity on create/update:

https://api.drupal.org/api/drupal/core!lib!Drupal!Core!Entity!entity.api.php/function/hook\_entity\_presave/8.2.x

Just implement some logic to check that the entity is a Node, and that it is either isNew() or has no id(), then put your logic inside of that.
> 0 votes

---
Tags: nodes, 8
---


title: Where is the Boost cached files?

text:
# Question
Title: Where is the Boost cached files?
I use Drupal 7.9 and Boost 7.x-1.x-dev

Last month i disabled Boost. I used only core caching with the all options are enabled. And min cache 6 hours, max cache 1 day.

Then without chancing core cache settings i enabled Boost module. I didn't change any setting. \- Cache specific pages: All pages \- Cache HTML output, usually a webpage of type text/html: Enabled, 6 hours, 1 day \- Root cache directory: cache \- Normal cache directory: normal

But the "html" files aren't saved to my public html folder. I have this folder: "/public\_html/cache/normal/www.example.com"

But this folder only has a ".htaccess" file.

I get 25 hits in one hour, but there is no html file inside these folders.

What would be the problem. Thank you for help.

# Answer
cache/normal/www.example.com is indeed where Boost would store your cached files.

Have you added the proper Boost directives to your public\_html/.htaccess? It sometimes takes a bit of fiddling to get them right - you need to experiment by accessing the site as an anonymous user and viewing source on the returned page to see if the Boost signature is in there.
> 4 votes

# Answer
Boost saves cache files in a subdir to the public files dir (`cache/normal`). That can be virtually any place on your server, default is `/sites/default/files` relative to your drupal install.

**Note**: Boost allow you to setup where different things is stored, so this could be an entirely different place.
> 1 votes

# Answer
Watch out on Centos for SELinux blocking write access.

In your logs you will see:

```
SELinux is preventing /usr/sbin/httpd from write access on the directory normal

```

Try setting the boolean.

```
# setsebool -P httpd_unified 1

```
> 0 votes

---
Tags: caching
---


# Question
Title: Changing "Product [product:title] added to your cart." message in Drupal Commerce
I'm trying to change/customize this message and have found that it is generated by "Display an Add to Cart message" rule from Drupal Rules. Everything would be fine but I can't find this text and I also don't know what to alter (and how) to change this message. Does anyone tried to do this?

# Answer
> 3 votes
There are several Options,

1. got to rules and disable the add to cart rule, then create your own.
2. Use this module https://drupal.org/project/stringoverrides to override the string. The string to override is this "%title added to your cart."

I wouldn't edit the module file commerce\_cart.rules.inc -\> function commerce\_cart\_rules\_add\_to\_cart\_message($product) as when you update it will just overwrite what you have done

# Answer
> 2 votes
The best way to do this is with: `hook_rules_action_info_alter()`

```
function HOOK_rules_action_info_alter(&$actions) {
    $actions['commerce_cart_add_to_cart_message']['callbacks']['execute'] = 'MODULE_custom_cart_callback';
}

function MODULE_custom_cart_callback($product) {
    drupal_set_message(t('%title added to <a href="!cart-url">your cart</a>.', array('%title' => $product->title, '!cart-url' => url('cart'))));
}

```

Basic steps:

1. Create a new module.
2. Add the `hook_rules_action_info_alter()` hook replacing "HOOK" with your module name.
3. Define `MODULE_custom_cart_callback($product)` replacing "MODULE" with your module name.
4. Enable the module and clear the cache.

# Answer
> 0 votes
I am using this to replace an existing drupal message to my custom message.

```
function _exclude_message($mymessage, $mytype="status"){    $flag = false if ($messageArr = drupal_set_message()) {  foreach($messageArr as $type=>$messages) {
  if ($mytype==$type) {
    foreach($messages as $key=>$message) {
      if ($mymessage==$message) {
    unset($_SESSION['messages'][$type][intval($key)]);
       $flag = true;
      }
   }
  }

  if (count($_SESSION['messages'][$type])==0) unset($_SESSION['messages'][$type]);}} return $flag;}
function my_theme_status_messages($display = NULL) {
  if (_exclude_message('Sorry, unrecognized username or password. <a href="/user/password">Have you forgotten your password?</a>',"error")) drupal_set_message("Sorry, unrecognized username or password.","error");
 return theme_status_messages($display);
}

```

under template.php

this code will replace existing "Sorry, unrecognized username or password.Have you forgotten your password?" with my custom message "Sorry, unrecognized username or password.".

Hope this will help you.

# Answer
> 0 votes
I'm using String Overrides module and there was no need to delete the message rule. I found the message rule defined in the commerce cart module code

**%title added to your cart.** so just changed it, for example, to **%title added to your basket.**

...where as the other message was configured **%title removed from your cart.** and needed changing to, for example **%title removed from your basket.**

Hope that would be helpful :)

---
Tags: commerce, rules
---


# Question
Title: How to hide a field in a views row if the row is about content type article?
I have a view that is showing all my content types. What I want is to hide a certain field in its row if the content type on this particular views row has a content type of Article.

How can I do that?

# Answer
> 0 votes
One of solutions is using Views Conditional module

> Views Conditional is a simple module that allows you to define conditionals (if xxx then yyy) with fields in views. Conditions include:
>
> ```
> Equal To
> Not Equal To
> Greater Than
> Less Than
> Empty
> Not Empty
>
> ```
>
> Views conditional allows you to output text based on the result of the condition.
>
> ---
>
> How to use Views Conditional in your Views: 1. Create a view. Add some fields under "FIELDS". 2. Click on "ADD" next to fields. Scroll down to "Views: Views Conditional", probably found near the bottom of the list. 3. Add and configure fields... 4. Choose a field to run a condition against, and provide values accordingly. 5. Save, views conditional handles the logic and returns as specified.

For findout how it work at Views Conditional Module (Drupal 7 Tutorial) - YouTube

# Answer
> 0 votes
Add content type as a hidden field above the field you wish to hide. For the field you wish to hide rewrite the field so as to add a class, using the token for the hidden field (ie \[hidden-\[type\] ), then target that via CSS (ie target hidden-article)

---
Tags: 7, views
---


# Question
Title: Give a specific user role the ability to give a user a role but not the 'administrator' role
I have a set up using drupal 7 where, as a super administrator, I can add a user with a role of 'manager' (who can also add users to his shop) but I want to also give 'manager' the ability to specify if the user he wants to add will have either of the two simple roles (one to create/add data and one to view reports on sales only) say, 'sales-agent', 'sales-report'. Currently, in my setup, the manager can specify all roles including the 'administrator' role which I should have access only as a developer/super admin.

I have been looking around for modules to fit this but my time is running out.

Thanks for all your help. Drupal is great!

# Answer
There is a perfect module for you - Role Delegation \- and there is a stable 7.x release as well. Here is an excerpt about it from the module's project page:

> ... allows site administrators to grant some roles the authority to assign selected roles to users, without them needing the administer permissions permission.
>
> For each role, Role Delegation provides a new assign ROLE role permission to allow the assignment of that role.
> 1 votes

# Answer
Use the Flag module to create 2 (not global) flags, with these details:

* These flags will be used to flag *users* (not nodes or something).
* Say you label those flags ***Create/add data*** and ***View reports***.
* Only users who have role ***manager*** are allowed to use these flags (something you can specify when configuring these flags).

Create a 1st rule (using the Rules module) like so:

* Rules Event: User gets flagged by the ***View reports*** flag.
* Rules Action: Grant Access to your role to ***View reports***.

Create a 2nd rule that is similar to the 1st rule, but now for the ***Create/add data*** (flag and role).

### Possible improvements

You could take this even a step further, also using Rules: Create a 3rd (and 4th) rule with Rules Event "User is unflagged", and trigger a Rules Action "Remove access to the role corresponding to the flag".

If you want, you can even consolidate these 4 rules in a single rule, using the Conditional Rules module.

### Avoid modulitis

With the above approach, you reduce the risk your site starts to suffer modulitis (= way too much contributed modules that only do 1 specific thing). Because chances are that you already use Rules in your site, maybe also Flag already. And if you're not using these modules yet, you'll find dozens of other use-cases for those 2 modules ... and possibly get rid of even more contributed modules that only do 1 thing (what else can you use the Role delegation module for?).
> 0 votes

---
Tags: 7, users
---


# Question
Title: Retrieve a field value without loading the entire node?
I have a large number of NIDs and I need one field value from each node. Is there any way to avoid the overhead of loading the entire node to get one field value?

# Answer
I don't think there's anything built in to the API but in a pinch you could just query the database directly:

```
$entity_type = 'node';
$bundle = 'page';
$nids = array(1, 2, 3);

$field_values = db_select('field_revision_FIELD_NAME', 'f')
  ->fields('f', array('entity_id', 'FIELD_NAME_value'))
  ->condition('entity_type', $entity_type)
  ->condition('bundle', $bundle)
  ->condition('entity_id', $nids, 'IN')
  ->condition('deleted', 0)
  ->execute()
  ->fetchAllKeyed();

```

After running that you should have an array of field values, keyed by their respective node's nid.

It's worth remembering the column name won't necessarily be `FIELD_NAME_value`; for example a node reference field would have a column name of `FIELD_NAME_nid`. Which one you use will depend on your field type.

**UPDATE**

It seems there is a way to do it with the API, but it's not pretty and still involves a manual query:

```
// Get the field meta data for the field_id.
$field_name = 'field_something';
$field_info = field_info_field($field_name);
$field_id = $field_info['id'];

// Load up the properties from the node table.
$nids = array(1, 2, 3);
$sql = 'SELECT * FROM {node} WHERE nid IN (:nids)';
$nodes = db_query($sql, array(':nids' => $nids))->fetchAllAssoc('nid');

// Attach the single field to all nodes.
field_attach_load('node', $nodes, FIELD_LOAD_CURRENT, array('field_id' => $field_id));

```

That method takes advantage of the `$options` parameter in `field_attach_load()` by specifying a field ID to load data for. It's worth noting, per the docs:

> Note that returned entities may contain data for other fields, for example if they are read from a cache.

So the code might have appeared to load extra field data, but anything other than the field you've specified will come from cache.
> 19 votes

# Answer
I find a bit cleaner way using an entityCondition and field attach load.

```
$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'story')
  ->propertyCondition('status', 1)
  ->fieldCondition('field_story_image', 'fid', 'NULL', '!=');
$result = $query->execute();

if (isset($result['node'])) {
  $stories = $result['node'];

  // At first we need to get field's id. If you already know field id, you can ommit this step
  // Get all fields attached to a given node type
  $fields = field_info_instances('node', 'story');

  // Get id of body field
  $field_id = $fields['field_story_image']['field_id'];

  // Attach a field of selected id only to get value for it
  field_attach_load('node', $stories, FIELD_LOAD_CURRENT, array('field_id' => $field_id));

  // Get values of our node field
  $output = field_get_items('node', $stories, 'field_story_image');
}

```

From the blog post http://timonweb.com/loading-only-one-field-from-an-entity-or-node
> 3 votes

# Answer
To avoid loading node one by one having large number of NIDs, you can use `node_load_multiple()` which will load multiple nodes at one go:

> `node_load_multiple($nids = array(), $conditions = array(), $reset = FALSE)`

Normally loading the nodes are cached and it's fast if you're using memory caching (like memcached), but could be slow if you've too many modules installed (like Pathauto, etc)..

Other way is to reuse the existing object, so check whether you can load it directly from cache (e.g. via `form_get_cache` if it's part of the form) or from `$_POST` request.

Another way is to use `EntityFieldQuery` with multiple NIDs, e.g.

```
$query->entityCondition('entity_id', array(17, 21, 422), 'IN')

```

which will fetch the values directly from the database.
> 0 votes

---
Tags: 7, entities
---


# Question
Title: import multi-value from csv into entity reference field from a field collection
I posted this question at https://stackoverflow.com/questions/39234531/import-multi-value-from-csv-into-field-collections but I have not got any replies yet. Below is the summary:

I have a simple csv file with 3 columns: NID|Key|List; where NID is the node id and Key was the unique value used to add field collections to the respective node. "List" is a multi-value field separated by ";".

```
Example (csv file):
NID,Key,List
1,2,text1;text2;text3
1,3,text4;text4
2,123,text1
...

```

**Field collection** has an **entity reference** field to a taxonomy plus other fields.

```
Field Collections:
Field1: text;
Field2: Term Reference;
Field3: Entity Reference; <-- importer/tamper not working!
...

```

The field collection fields were mapped correctly, except for the field that was an **entity reference** to a taxonomy. I configured Feeds Tamper with the Field Collection Feeds module but the entity reference list was not imported.

*Does anyone has experience (suggestions) importing a multi-value field from a csv file into an entity reference field within a field collection?*

# Answer
> 0 votes
Solution: using the same feeds importer's configuration but instead of importing with the standalone form, it worked once it was moved to a content type form. If a content type is selected a source is imported by creating a node of that content type.

---
Tags: hooks, importing-exporting, entities
---


title: Content acces basing on a field value

text:
# Question
Title: Content acces basing on a field value
In Drupal 8, how do I give access to some nodes to users with specific roles, depending on a field value or a taxonomy value?

# Answer
> 1 votes
this is how i did it ( simplified for demo purpose )

```
function my_module_node_access(NodeInterface $node, $op, AccountInterface $account) {

global $user;
$user = \Drupal\user\Entity\User::load($account->id());

  if ($node->bundle() == 'my_content_type') {
    if ($op == 'view') {
        $visibility=$node->field_visibilite->getString();
        $target=$node->field_target->getString();

        if ($visibility ==='all')
            return \Drupal\Core\Access\AccessResult::allowed();

        if ($visibility ==='restricted')
            if (($target === 'group1') && ($user->hasRole('group1')))
                return \Drupal\Core\Access\AccessResult::allowed();

}

 return \Drupal\Core\Access\AccessResult::forbidden();

}

```

---
Tags: nodes, users, 8, taxonomy-terms
---


# Question
Title: Is there anyway to upload a picture to a user image field via services without an FID?
So I want to update a user image field (let's say field\_picture for the sake of convenience).

Preferably I only want to make one AJAX call rather than two, so I'd prefer to not have to create the file, get the fid back and pass that to the user.

Is there anyway to just pass in a local URI or anything like that, or do I need to essentially do two calls?

# Answer
Ok I am going to post what I did to make this work with services. I'll also include a bit of information about my specific use-case because I don't see any list of steps anywhere else on the internet to make this happen, so maybe it'll make it easier for someone along the line.

**Here's the optional part of the answer:**

I was doing this in PhoneGap. To pass the image data from a mobile device via PhoneGap to a user, I did the following:

```
navigator.camera.getPicture(saveProfile,
                            function(message) { alert('get picture failed'); },
                            { quality: 50,
                            destinationType: navigator.camera.DestinationType.DATA_URL,
                            sourceType: navigator.camera.PictureSourceType.PHOTOLIBRARY }
                            );

function saveProfile(image) {
json.image = image;
}

                $.ajax({
                    url: "http://drupal/services_endpoint" + uid,
                    type: 'PUT',
                    contentType: 'application/json',
                    data: JSON.stringify(json)
                }
                );

```

**And now the actual answer:**

After finding this link here: Create file through services

I released I could do something similar:

```
function MY_MODULE_services_request_preprocess_alter($controller, &$args, $options) {
  switch ($controller['callback']) {
    case '_user_resource_update':
      if (isset($args[1]['image'])) {
        $data = base64_decode(trim($args[1]['image']));
        $finfo = finfo_open();
        $mime_type = finfo_buffer($finfo, $data, FILEINFO_MIME_TYPE);
        finfo_close($finfo);
        $ext = $mime_type ? str_replace('image/', '', $mime_type) : 'png';
        $file_name = uniqid();
        $file = file_save_data($data, 'public://users/' . $file_name . '.' . $ext, FILE_EXISTS_REPLACE);
        file_usage_add($file, "user", "user", $args[0]);
        $args[1]['field_picture'] = array(
          'und' => array(
            0 => array(
              'fid' => $file->fid,
            ),
          ),
        );
      }
  }
}

```

This will generate a random file name. I'm not sure if that'll work perfectly for everyone, but it worked for my use-case.

Anyway, that is a basic way to get image data from a mobile device (iPhone in this case) into a Drupal user in one RESTful call.
> 0 votes

---
Tags: 7, services
---


# Question
Title: Creating SearchAPI searches without using Views
I am using SearchAPI on a website with 20,000 entities indexed. Searching through them with SearchAPI is pretty simple. Its fast. I want to keep it as fast as possible with very low overhead, without using Views.

I've created the appropriate code needed to create a form, blocks, and a page callback via a custom module. What I would like to do is have someone use a custom search form, hit submit, and be sent to the search results page callback.

What is the best way to store and read from form values in a page callback? Is there any way to have values persist outside of $\_SESSION? Or is that the best method? If I wrote a method in my search class that inspected $\_POST and did proper validation on it, would it be better to use that to keep executing a search based on that?

I already have paging methods worked out in the code, but kind of scratched my head on how to execute a form, then when using a pager, keep those values for querying the next set. I think I am close, but wanted some input if there is a way I am not seeing.

# Answer
> 0 votes
Realized I never added a follow up. Search API Page does not solve all the cases, and this is possible in Drupal 8 as well.

A query string was added on form submission, redirecting to my url + query string args. These prefill form values (sanitized of course) and modify the initial Search API query. Extra work was done to store some data in session, so that the query could be repeated on detail pages for sidebar results (prev/next navigation in the same result set).

Using the normal Drupal pager worked fine as well.

As part of this work, a module was born: https://www.drupal.org/project/search\_api\_view\_modes

Here is an example of doing it in Drupal 8: https://gist.github.com/kevinquillen/cad07541347385744b161a26690ab75d

Taking this route allows you to create and provide a very tailored, controlled experience.

---
Tags: 8, forms, search
---


title: Drupal.behaviors Once() won't execute

text:
# Question
Title: Drupal.behaviors Once() won't execute
I have created a custom block that shows some parking information for the user (using json) and this worked fine for most pages, but when I visit any created nodes (pages like /node/1,/node/2) the jquery get executed twice (so the information is added twice to the parkings-div in the block). After some searching, I thought using "once" would solve my problem but after adding this it doesn't execute at all.

```
(function ($) {
    "use strict";

Drupal.behaviors.Parkings = {
    attach: function (context, settings) {
        $('#parkings',context).once('parkingsbehavior', function () {
            getAndShowResults();
        });

        function getAndShowResults() {
            var root_url = getRootUrl();
            $.get(root_url + "parkings", {})
                    .done(function (data) {
                        var i;
                        for (i = 0; i < data.length; i++) {
                            var p = $(document.createElement("p"));
                            var p_text = data[i].description + ', free: ' + data[i].parkingStatus.availableCapacity;
                            p.append(p_text);
                            p.appendTo("#parkings");
                        }
                    });
        }

        function getRootUrl() {
            return window.location.origin ? window.location.origin + '/' : window.location.protocol + '/' + window.location.host + '/';
        }
}};

}(jQuery));

```

This is my routing file:

```
parkings.content:
      path: '/parkings'
      defaults:
        _controller: '\Drupal\parkings\Controller\ParkingsController::content'
        _title: 'Parkings Gent'
      requirements:
       _permission: 'access content'

```

and I've added these dependencies:

```
    - core/jquery
    - core/drupal.ajax
    - core/drupal
    - core/drupalSettings
    - core/jquery.once

```

Am I misunderstanding how once() works or am I just using it wrong?

(I'm using Drupal 8 v1.8)

# Answer
> 12 votes
jQuery Once has changed with jQuery 2.x, see the Drupal changelog for info.

I ran into the same issue and that fixed it for me:

Essentially now you are going to want to do:

`...once('mybehavior').each(function()...`

---
Tags: theming, 8, javascript, blocks
---


# Question
Title: How to show custom error messages below text field?
I want to display custom error messages below that text field in `comments form`. Currently it displays all error messages above the page which is not acceptable.

I'm using this theme for my blog. I also used this but it's not working. As I'm new in drupal I'm struggling with this, please suggest any solution.

# Answer
You need go to your theme's template folder and edit **page.tpl.php**'

Look for `<?php print $messages; ?>` and move it below `<?php print render($page['content']); ?>`

Thanks for the note @Kevin. If you wish, you can add if statements around the `<?php print $messages; ?>` that check the page url and/or content type if you need to have them appear below only for certain pages.
> 0 votes

---
Tags: 7, forms, comments, paging, nodes
---


# Question
Title: New Account, change Duplicate E-mail error
I run a drupal / civicrm build for a non-profit. We are very careful with our members information, and want to make sure that no one trying to, would be able to figure out if someone they knew was a registered user.

The problem we have is when someone goes to create a new user account, if they use an e-mail that is already on our site, they get an error message saying that they can't use that e-mail because it's already registered on the site.

There are plenty of people - bosses, spouses, etc who could be testing an e-mail address to see if someone they know is on our site, and this error message pretty much confirms it.

Is it possible to change the error message to something else? We have the e-mail confirmation enabled, why can't it say, "An e-mail has been sent to abc@xyz.com with your login information?"

# Answer
You can do a couple of things. One, I would advise installing the Username Enumeration Prevention module:

https://www.drupal.org/project/username\_enumeration\_prevention

This will stop forgot password form abuse.

Secondly, hiding this fact on the registration side is hard. You can't have duplicate email or usernames in Drupal (not easily), and if you get an error on that then it is pretty apparent it is already in use. Giving a vague error here could also confuse actual users who are trying to register.
> 0 votes

---
Tags: users, debugging
---


title: Drush over local network share?

text:
# Question
Title: Drush over local network share?
Can drush be run on a site when I have the server connected to my machine as a network share? I am running Win10 and the server is Windows based with IIS. The website folder mounted as a drive, so the path to it is something like Z:\website.

I noticed that I can switch between Acquia DevDesktop sites by changing the cmd line path (ie. from c:\devdesktop\site1 to c:\devdesktop\site2)

Can I essentially do the same by changing over to z:\website?

My thinking is that getting everything setup as if the webserver were remote (what most install tutorials asume) seems overkill. But, I am not really sure what DevDesktop is doing to get drush running on it's sites.

Is anyone doing anything similar?

# Answer
In theory yes. Windows is a bit more difficult because, windows.

But if you have Drush installed locally, and it's the same PHP version as you have on the server machine it should work. You will need to modify your DB credentials to reference your database by network accessible hostname or IP so that your machine can connect to the database on the server remotely.

Disclaimer: I've never tried this, but it should work. YMMV etc.

The more "right" way to do this would be to set up an ssh server on the windows box server, and set up Drush aliases to act against the remote server with Drush installed locally on the server and client.

I don't know how well that works on Windows but quick reading suggests it should be possible.
> 0 votes

---
Tags: drush
---