title: Custom view mode issues

text:
# Question
Title: Custom view mode issues
My goal is to switch between different view modes based on the node path (pattern). In my case, the patterns would be:

* dossier/node-alias =\> default template
* dossier/node-alias/cover =\> cover template
* dossier/node-alias/abstract =\> abstract template

I have created the custom view modes with `hook_entity_info_alter` (simplified here to only one custom view mode):

```
/**
 * Implements hook_entity_info_alter
 */
function dossier_config_entity_info_alter(&$entity_info) {

  $entity_info['node']['view modes']['cover'] = array(
    'label' => t('Cover view mode'),
    'custom settings' => TRUE,
  );
}

```

Here is how I declared the path pattern in `hook_menu`:

```
/**
 * Implements hook_menu
 */
function dossier_config_menu() {

  $items = array();

  // Cover entity view mode
  $items['dossier/%/cover'] = array(
    'title' => 'Default title', // overridden in template.php preprocess_node function
    'page callback' => '_dossier_config_switch_viewmodes',
    'page arguments' => array(1, 2), // arguments from uri are 1 => node alias and 2 => cover
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
  );

  return $items;
}

```

And here is my custom callback:

```
function _dossier_config_switch_viewmodes($alias, $view_mode) {

  // Get the node path based on the alias
  $path = drupal_lookup_path('source', 'dossier/' . $alias);

  // Return the node if the path exists
  if ($path !== FALSE) {

    $node = menu_get_object("node", 1, $path);
    $node_view = node_view(node_load($node->nid), $view_mode);

    return array(
      'content' => array(
        'node' => $node_view,
      ),
    );
  }

  return drupal_not_found();
}

```

It works. However, when looking at these nodes in the custom view modes, I lose the node edition tabs (View, Edit, Translate, etc.) and I also seem to lose all the standard classes that are added to the `<body>` such as `node-type-xxx` or `page-node-12345` etc.

I believe that this is a normal behavior with such a custom callback in `hook_menu` (?). So what would be the right way to achieve what I want?

Any help on that will be highly appreciated! Cheers!

**Edit:** I forgot to mention that of course I have 3 different node templates and that I have added the `theme_hook_suggestions` accordingly in my theme `template.php`.

# Answer
> 1 votes
The path for your additional pages should be `node/%node/abstract` and `node/%node/cover` with something like

```
$items['node/%node/abstract'] = array(
  'title callback' => 'node_page_title',
  'title arguments' => array(1),
  'page callback' => 'MODULE_node_view',
  'page arguments' => array('abstract', 1),
  'access callback' => 'MODULE_node_view_access',
  'access arguments' => array('abstract', 1),
  'type' => MENU_LOCAL_TASK,
);

$items['node/%node/cover'] = array(
  'title callback' => 'node_page_title',
  'title arguments' => array(1),
  'page callback' => 'MODULE_node_view',
  'page arguments' => array('cover', 1),
  'access callback' => 'MODULE_node_view_access',
  'access arguments' => array('cover', 1),
  'type' => MENU_LOCAL_TASK,
);

```

If you don't want your additional pages to be available as tabs (like View, Edit and Translate), you can probably use `'type' => MENU_CALLBACK`. By doing so, you ensure Drupal knows these pages are below the normal node view page.

`MODULE_node_view($view_mode, $node)` and `MODULE_node_view_access($view_mode, $node)` are your page and access callbacks. They receive the `$node` already loaded (thanks to the `%node` in the menu item path). If you don't have specific access rules (such as restricting access to only certain content type), you can replace the access callback and arguments by `node_access` and `array('view', 1)`.

Given the question, your likely want to automatically create aliases for your nodes so you can use paths like `dossier/node-alias/cover` instead of things like use `node/1234/cover`. You can implement `hook_path_insert()` and `hook_path_delete()` to automatically create and delete abstract and cover aliases for any aliased node.

```
/**
 * Implements hook_path_insert().
 */
function MODULE_path_insert($path) {
  // If this is an alias to a node view page
  if (preg_match("/^node\/\d+(\/view)?$/", $path['source'], $matches)) {
    // Create aliases for the supported suffixes.
    foreach (array('/abstract', '/cover') as $suffix) {
      $new_path = array_merge($path, array(
        'source' => $matches[0] . $suffix,
        'alias' => $path['alias'] . $suffix
      ));
      unset($new_path['pid']);
      path_save($new_path);
    }
  }
}

/**
 * Implements hook_path_delete().
 */
function MODULE_path_delete($path) {
  // If this is an alias to a node view page
  if (preg_match("/^node\/\d+(\/view)?$/", $path['source'], $matches)) {
    // Delete aliases for the supported suffixes.
    foreach (array('/abstract', '/cover') as $suffix) {
      $new_path = array_merge($path, array(
        'source' => $matches[0] . $suffix,
        'alias' => $path['alias'] . $suffix
      ));
      unset($new_path['pid']);
      path_delete($new_path);
    }
  }
}

```

---
Tags: 7, theming, routes, entities
---


# Question
Title: Drupal 7 module issues using node_ functions
I'm building a basic D7 module that fetches data from an API and then add it as a certain content type. Problem is, every node\_ function is coming back as undefined. node\_object\_prepare, node\_submit, and node\_save with this error message:

```
Call to undefined function node_object_prepare()

```

The module is bare bones... info file:

```
name = Social Fetch
description = Fetches feeds from various social media platforms.
package = public-action
version = 1.0
core = 7.x
files[] = social_fetch.module

```

and the social\_fetch.module...

```
<?php
if(isset($_GET['fetch']))
{
    social_fetch();
}

function social_fetch(){
        $node = new stdClass();
        $node->title = 'test';
        $node->type = "social_boxes";
        node_object_prepare($node); // Sets some defaults. Invokes hook_prepare() and hook_node_prepare().
        $node->language = LANGUAGE_NONE; // Or e.g. 'en' if locale is enabled
        $node->uid = 1;
        $node->status = 0; //(1 or 0): published or not
        $node->promote = 0; //(1 or 0): promoted to front page
        $node->comment = 0; // 0 = comments disabled, 1 = read only, 2 = read/write
        $node = node_submit($node); // Prepare node for saving
        node_save($node);
}

```

So much as I knew, node\_ was part of the core and wouldn't need any dependencies but I may be wrong. I tried adding this:

```
module_load_include('inc', 'node', 'node.module');

```

but that did nothing. also tried loading the bootstrap to see if maybe this was being run before the core loaded, but that did nothing as well.

```
  require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
  drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

```

Am I missing something? should this be run in a hook of some kind and if so, which?

**Side Note**

I am able to achieve what I need by using the db\_ methods below. It just seems like an inferior way to do so since I don't actually know the anatomy of a node to know if these are the only things required to make sure the system remains stable. The kind of things the node API would have handled 100%.

```
      $nid = db_insert('node')
        ->fields(array(
          'title' => 'test',
          'uid' => 1,
          'type' => 'social_boxes',
          'language' => 'und',
          'status' => 0,
          'comment' => 0,
          'promote' => 0,
          'created' => REQUEST_TIME,
          'changed' => REQUEST_TIME,
        ))
        ->execute();

        if($nid)
        {
            db_update('node') //add vid back into the new node
              ->fields(array(
                'vid' => $nid
              ))
              ->condition('nid', $nid, '=')
              ->execute();

            db_insert('node_revision')
            ->fields(array(
              'nid' => $nid,
              'vid' => $nid,
              'uid' => 1,
              'title' => $class->getText(),
              'timestamp' => REQUEST_TIME,
              'log' => '',
              'status' => 0,
              'comment' => 0,
              'promote' => 0,
              'sticky' => 0
            ))
            ->execute();
        }

```

# Answer
Tty the following in your .modulfe file:

```
function social_fetch_menu() {
  $items['social_fetch'] = array(
    'title' => 'Fetch',
    'page callback' => 'social_fetch_fetch',
    'access callback' => true,
  );

  return $items;
}

function social_fetch_fetch() {
  $query = drupal_get_query_parameters(); // $query['fetch'] for your $_GET parameter
  // ... your code to save the node
  return 'done';
}

```

Now clear the caches and go to ../social\_fetch in your browser and see what happens.

To check for your fetch parameter on every page load (of not cached pages) do the following:

```
function social_fetch_init() {
  $query = drupal_get_query_parameters();
  if (isset($query['fetch'])) {
    // add node
  }
}

```
> 2 votes

# Answer
Never ever call functions from the global scope. You are probably running into a situation where other modules (the node module) are not yet loaded.

```
<?php
if(isset($_GET['fetch']))
{
    social_fetch();
}

```

You could try to add your function to hook\_boot(), but even then the node module might not be loaded, so you will have to ensure it is loaded manually. `drupal_load('module', 'node');`

You'll end up with

```
function social_fetch_boot() {
  if(isset($_GET['fetch'])) {
    drupal_load('module', 'node');
    social_fetch();
  }
}

```
> 3 votes

---
Tags: 7, nodes
---


# Question
Title: Cannot redeclare MyClass - but it's only declared once
I'm trying to port an image effect from D7 to D8.

I've got Drupal to list the plugin, but when I try to use it I get a WSOD with "Fatal error: Cannot redeclare class Drupal\image\Plugin\ImageEffect\EffectMagic".

I've checked and there is no other declaration of this class anywhere.

My file is in `mymod/src/Plugin/ImageEffect/EffectMagic.php` and it looks like this (nb. content of functions is removed)

```
/**
 * @file
 * Contains \Drupal\image\Plugin\ImageEffect\EffectMagic.
 */

namespace Drupal\image\Plugin\ImageEffect;

use Drupal\Core\Image\ImageInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\image\ConfigurableImageEffectBase;

/**
 * Scales and crops an image resource.
 *
 * @ImageEffect(
 *   id = "image_effect_magic",
 *   label = @Translation("Effect Magic"),
 *   description = @Translation("Use ImageMagic command line to process images.")
 * )
 */
class EffectMagic extends ConfigurableImageEffectBase {
  public function buildConfigurationForm(array $form, FormStateInterface $form_state)
  public function validateConfigurationForm(array &$form, FormStateInterface $form_state)
  public function submitConfigurationForm(array &$form, FormStateInterface $form_state)
  public function applyEffect(ImageInterface $image)
  public function transformDimensions(array &$dimensions, $uri)
  public function getSummary()
  public function defaultConfiguration()
}

```

# Answer
When you are creating a custom module, you have to make sure your module registers its own namespace. In the current situation your module is attempting to use the namespace of the image module `namespace Drupal\image\Plugin\ImageEffect;`. Where you should actually be using a namespace of your own module `namespace Drupal\mymod\Plugin\ImageEffect;`

Then if you require functions of the image module, you can (as you have done already) load the other classes and functions with `use`. Like `use Drupal\image\ConfigurableImageEffectBase;`.
> 4 votes

---
Tags: 8, media
---


# Question
Title: How can I get the group id of a node using tokens?
I try to use \[node:og\_group\_ref\], but that gives me the group node title and I need the GID, I am sure there should be a way to get it but I haven't found it

# Answer
> 0 votes
In Organic Groups 7.2 the Node idea and Group id are the same. So if you are using views you can do the following:

Add field "Content: Nid" and exclude if from display. Any field arranged below the above can use \[nid\] as a rewrite giving you the Group ID.

Does this help?

# Answer
> 0 votes
You can make the `[node:og_group_ref]` token output the numerical ID instead of the group name by setting up the "Token" display mode for your content type and choosing the "Entity id" formatter for that field:

As shown in this comment in the issue queue:

1. Go to "Structure → Content Types → \[your content type\] → Manage Display".
2. Click "Custom Display Settings" below the field list, enable the "Token" option and save.
3. Go to the new "Token" display mode in the horizontal tabs on the top.
4. For your`og_group_ref` field, set "Format: Entity id" and save.

# Answer
> -1 votes
Like so: \[node:og-group-ref--og-membership--1:0:id\]

---
Tags: organic-groups, tokens
---


title: Rules and Populating Content Fields

text:
# Question
Title: Rules and Populating Content Fields
I have a Temp webform with 2 fields, I have rules set up to, on webform submission, create an entity and then set a data value for the 1 field in my temporary content type.

Here is the rule. I have done this exact same thing on another site. The rule creates the entity successfully and pulls the title from the webform submission value of the title field, then when it moves down to setting the data for the second field in the content type it breaks. I am using \[data:{component}-value\] and replacing {component} with the machine name of the webform field, like I did with the title except it isn't assigning the content field the value I typed and submitted into the webform. Even using the same exact token as i did for the title it does not work. If i used a static just "asdf" to assign to the field of the content type that works, but it will not pull anything from the webform. Any ideas? I'm stuck here.

# Answer
> 0 votes
Well looks like I was using a slightly old version of Webform Rules, updating solved my issue

# Answer
> 1 votes
Add a condition, Entity has field: webform\>field. I have to do that with entityforms.

---
Tags: rules, webforms
---


# Question
Title: How to prevent User Roles from getting reapplied?
For whatever reason when I remove a role from a user's profile, at url `site/user/user-id/edit` it just comes back a few days later. I tried to check **users\_role** table but I do not have that table.

.

We do import every employee every night, based off Active Directory, but I do not touch their roles in the import.

I imagine the best way of solving this is finding the table that has every user's roles, then just removing that entry from the particular user.

# Answer
Try to run this: **`show tables like '%role%';`** MySQL statement. In the results returned you should see a **`users_roles`** table (not **`users_role`**). To that table's columns are stored the `uid` and `rid`, therefore you will be able to find all users that have assigned with a role or more, and possibly an answer to your question.

I would kindly suggest you, since those roles are appeared again and again, to search any by chance or forgotten user\_save implementation within your code.

Hope this help!
> 2 votes

---
Tags: users
---


title: Body Field Trimming

text:
# Question
Title: Body Field Trimming
Does anyone have a solution to the following issue?

I have a body field that I would like to have initially trimmed with a "Read more" link to expand the remainder of the text. This is specifically only on the Node page (so not a views issue) of a custom content type.

I have tried the Smart Trim module, but it doesn't expand the text when click, it just links back to the node page, which is what I'd expect from a views to node link.

Does anyone have any other ideas? I'm stuck currently, either I leave it consistently expanded or just have it trimmed with no "read more" link. Thanks

# Answer
> 1 votes
If I understood your question correctly, you need the Expand Formatter module. From the project page:

> This module provides a formatter for existing text, long text and text with summary widget types. This module allows you to change how the content is being display (formatted) by providing new format types:
> **Trimmed (expandable)**
> **Summary or Trimmed (expandable)**

Granted, this is only for D7, but you didn't tag your question with core version, so I'm guessing that you're using D7.

---
Tags: nodes, entities
---


# Question
Title: How do I filter entity reference fields based on language?
In a Drupal 8 site I have a node content type "page" that references a custom entity type using inline entity form. "Page" also has a paragraphs field usig the Paragraphs module.

The site have multiple languages and therefore the following scenario appears:

1. I have an existing "page" node in both english and german containing entity references and paragraphs.
2. On the english node I add a new paragraph and a new entity reference and save the node.
3. When viewing the node in english I see the added content.
4. When viewing the node in german I also see the new content, which is in english.

I don't want number 4 to happen. That is, I don't want the new untranslated entity and paragraph to be visible on the german translation of the node. The entity reference and paragraph fields are not set as translatable but the target entities are translatable. From what I understand, this means that the newly created entity will be in english, the same is true for the paragraph.

To solve this I'm thinking I should be able to filter out the untranslated entities and paragraph items when viewing the node so that any item that is not in the current language is not shown. The they won't be visible until I go and edit the german node and resave it, which will create translated versions of the entity and paragraph item.

But I am unsure how to go about filtering the fields. Is there any suitable hook that can be used? Or am I going about this in the wrong way?

# Answer
The logic that defines if entities should be shown is in `\Drupal\Core\Field\Plugin\Field\FieldFormatter\EntityReferenceFormatterBase::getEntitiesToView()`

As you can see, translation is checked there, but the API doesn't directly support skipping something, the hooks behind that only allow to control applicable fallback languages and their order.

It's possible that you can use entity access, which is checked after that. Implement `hook_paragraph_access()`, for the view operation, check if the paragraph has a translation in the current content language and if not, forbid access. The same should work for your other entity reference, it's the same could, just implement `hook_ENTITY_TYPE_access()` for that too.

If that doesn't work, you can write your own field formatter plugin and override that method.
> 4 votes

---
Tags: 8, hooks, entities, i18n-l10n
---


# Question
Title: Why is the rate widget (from the Rate module) not showing up?
I'm using the Rate module, together with the entity reference module.

I have a content type let's name it "Gallery". I also created a "Photo" content type, then added a "yes/no" rate widget to this content type. (c)

In "Gallery" I have an entity reference to "Photo".

Now I'm going to make a View like this: Show all of "Photo"s related to this "Gallery" plus rate widget related to every "Photo".

I created a view with nid as argument to get specific node, and two relation, first one is "Entity Reference: Referenced Entity", and second one is "Vote result". then I added first relation as a relation to second relation.

I added "Vote results:value" as field. So far I see the "Photos", but I couldn't get the rate widgets.

What am I missing to also get the rate widgets to show up?

# Answer
> 0 votes
From the screenprint about "**edit widget**" in your question it shows that you've created a "Yes / no" widget using the Rate module.

But nowhere in your question it shows for which "***Node types***" you've enabled your widget. Since you're using the "Yes / no" widget (located at `admin/structure/rate/add?template=yesno` when adding a new widget), you should indicate the desired "Node types" there for which the rating widget is to be enabled. If you didn't specify (select) any of node type, then that would explain ***why the rate widget is not showing up***".

---
Tags: entities, views, rating
---


title: Conditionally unpublish nodes for feeds

text:
# Question
Title: Conditionally unpublish nodes for feeds
We have a content type that up until today was 100% driven by a feeds importer on a D7 site from an XML file (from a third-party system). This importer ran nightly and was set to "Unpublish non-existent nodes" which worked perfectly to remove items not available anymore.

Due to a business needs change we now need to manually create a couple of nodes of this specific content type and we don't want the importer to unpublish these specific nodes. Modifying the third-party system is not an option so the only possibility that we've come up with is to create a local file (CSV/XML/whatever) and create a new importer to run after the original importer to re-publish them.

We could also locally consume the original file and merge it with our custom node list but this seems like more things could break.

Is there another solution to this problem that we're missing?

# Answer
You seem to be using a version of feeds that is fairly recent (perhaps version **7.x-2.0-beta2**). Having said that, the `process` function of the `FeedsProcessor` class is fairly inflexible when it comes to modifying the list of imported nodes that it wants to clean out of Drupal, in that it does not provide a hook to modify that list.

Having said that, your best bet is probably to extend the `FeedsNodeProcessor` class and only override the `initEntitiesToBeRemoved` function to then exclude "potentially unpublished" node ids from `$state->removeList`. You'll need to determine how all of the nodes from `$state->removeList` were created.

How you determine a manually created node from a feeds imported node is up to you but I would recommend querying the `feeds_item` table. If a node's nid is not found in that table then it's safe to assume that the node was manually created.
> 0 votes

---
Tags: feeds
---


# Question
Title: How do I share configuration between custom admin form and node type edit form?
I have a module that requires some settings per content type. The module is to also provide one admin page where all the settings can be applied across content types at once.

Essentially I'm trying to share configuration information between a custom Admin Settings form and the node type edit form. I had this all working with Drupal 8 Beta 10 or something like that, but I'm trying to get it working with the latest stable release (8.0.4).

I originally used the method described here for my custom Admin form using the following code:

```
$config = $this->config('mymodule.settings');
'#default_value' => $config->get('my_setting'),

```

Similarly, for the node edit form alter function, I used:

```
$config =  \Drupal::config('mymodule.settings');
'#default_value' => $config->get('my_setting'),

```

But the above stopped working for the node type settings form at some point, so I started looking at using Third Party Settings:

```
$node_type = $form_state->getFormObject()->getEntity();
'#default_value' => $node_type->getThirdPartySetting('mymodule', 'setting', 'default_value'),

```

This works great for the node type edit form, but I don't know of a way to pull the third-party settings into my custom Admin form partially because getEntity() method isn't available.

So my question is, what is the best practice for sharing configuration settings between a custom admin form and the content type edit form?

# Answer
So the bottom line appears to be that Third Party Settings is a great way to handle content type settings without really caring which content type you're dealing with, but there doesn't seem to be a way to get this working with a custom admin settings form for the reason described in the question.

If I didn't want to have a separate configuration form that handled the content type settings for all content types on one form, I would definitely have used Third Party Settings. However, since I had this extra requirement, I wound up fixing whatever broke along the journey from D8 beta to stable release.

Now the node type gets included with each of the desired settings using the following code:

```
function mymodule_form_node_type_form_builder($entity_type, NodeTypeInterface $type, &$form, FormStateInterface $form_state) {
  $node_type = $type->get('type');
  $config = \Drupal::getContainer()->get('config.factory')->getEditable('mymodule.settings');
  $config->set('my_setting_'.$node_type, $form_state->getValue('my_setting'));
  $config->save();
}

```
> 0 votes

---
Tags: 8
---


# Question
Title: An illegal choice has been detected. Please contact the site administrator.in dynamic select list dependent dropdown
using hook\_form\_alter and custom form elements below

```
$form['get-quotes-shipping']['country'] = array(
      '#type' => 'select',
      '#options' => array('_none' => '- None -') + country_get_list(),
      '#multiple' => FALSE,
      '#weight' => 3,
      '#title'=>t('Country'),
      '#default_value' => (isset($_SESSION['selected_country'])) ? $_SESSION['selected_country'] : '_none',
      '#ajax' => array(
          'event' => 'change',
            'wrapper' => 'squadron-wrapper',
            'callback' => '_get_state_field',
            'method' => 'replace',
       ),
    );

    $form['get-quotes-shipping2']['actions']['get_quotes'] = array(
      '#type' =>'submit',
      '#value' => 'Get Quotes',
       '#submit' => array('custom_changes_get_quotes_submit'),
      '#validate' => array('custom_changes_get_quotes_validate'),
      '#weight' => 1,
    );

  $squadron_options = array();
   if (isset($_SESSION['selected_country'])) {
       module_load_include('inc', 'location');
       $states = location_get_provinces($_SESSION['selected_country']);
       $squadron_options =  $states;
   }
   $form['get-quotes-shipping0']['states']['#type'] = 'select';
     $form['get-quotes-shipping0']['states']['#title'] = t('State/Province');

   $form['get-quotes-shipping0']['states']['#prefix'] = '<div id="squadron-wrapper">';
   $form['get-quotes-shipping0']['states']['#suffix'] = '</div>';
    $form['get-quotes-shipping0']['states']['#options'] = array('_none' => '- None -') + $squadron_options;
    if (isset($squadron_options[0])) {
      $form['get-quotes-shipping0']['states']['#default_value'] =  $squadron_options[0];
    }

```

---

Callback function as given below.

```
function _get_state_field(&$form,&$form_state) {
  module_load_include('inc', 'location');
  if ($form_state['values']['country'] == '_none') {
    unset($form['get-quotes-shipping0']['states']['#options']);
    $form['get-quotes-shipping0']['states']['#default_value'] = '_none';
     return $form['get-quotes-shipping0']['states'];

  }
  else {
      $states = location_get_provinces($form_state['values']['country']);
 $form['get-quotes-shipping0']['states']['#options'] = $states;
     return $form['get-quotes-shipping0']['states'];

  }

}

```

When I select Country and then state at first it gives proper values but when I select country again it gives An illegal choice has been detected

What is the issue with the above code? can anyone point out?

# Answer
i recently made a 3 level dependent dropdown and had the same issue with some of the problems i found on the way. First you need to re-organize your code a little bit more. have in mind that the callback function should normaly look something like this:

```
//callback
    function _get_state_field(&$form,&$form_state) {

     return $form['get-quotes-shipping0']['states'];
}

```

Any code inside the callback has the potential to intervene with the proccess, with some exceptions.

Without taking a longer look to your code i think it should look somethink like this:

```
<?php

 module_load_include('inc', 'location');
  if ($form_state['values']['country'] == '_none') {
    unset($form['get-quotes-shipping0']['states']['#options']);
    $form['get-quotes-shipping0']['states']['#default_value'] = '_none';
     return $form['get-quotes-shipping0']['states'];

  }
  else {
      $states = location_get_provinces($form_state['values']['country']);
 $form['get-quotes-shipping0']['states']['#options'] = $states;
  }

$form['get-quotes-shipping']['country'] = array(
      '#type' => 'select',
      '#options' => array('_none' => '- None -') + country_get_list(),
      '#multiple' => FALSE,
      '#weight' => 3,
      '#title'=>t('Country'),
      '#default_value' => (isset($_SESSION['selected_country'])) ? $_SESSION['selected_country'] : '_none',
      '#ajax' => array(
          'event' => 'change',
            'wrapper' => 'squadron-wrapper',
            'callback' => '_get_state_field',
            'method' => 'replace',
       ),
    );

    $form['get-quotes-shipping2']['actions']['get_quotes'] = array(
      '#type' =>'submit',
      '#value' => 'Get Quotes',
       '#submit' => array('custom_changes_get_quotes_submit'),
      '#validate' => array('custom_changes_get_quotes_validate'),
      '#weight' => 1,
    );

   $form['get-quotes-shipping0']['states']['#type'] = 'select';
     $form['get-quotes-shipping0']['states']['#title'] = t('State/Province');

   $form['get-quotes-shipping0']['states']['#prefix'] = '<div id="squadron-wrapper">';
   $form['get-quotes-shipping0']['states']['#suffix'] = '</div>';
    $form['get-quotes-shipping0']['states']['#options'] = array('_none' => '- None -') + $squadron_options;
    if (isset($squadron_options[0])) {
      $form['get-quotes-shipping0']['states']['#default_value'] =  $squadron_options[0];
    }

    //callback
    function _get_state_field(&$form,&$form_state) {

     return $form['get-quotes-shipping0']['states'];
}
?>

```

This is the code i wrote, try to follow the same structure it's working for me perfectly.

Tell us how it went, have a good coding!
> 1 votes

---
Tags: 7, ajax, forms
---


# Question
Title: Exported menu blocks to a feature module via FE block they are not created - Why?
I am using menu blocks and context to create menus on a site. I have created the menu blocks and added contexts for there use (they are working on my local dev). I have exported the menu blocks to code using fe block and strongarm per the recommendations in Drupal.org I am doing the following after versioning the code to git and pulling it to the new server:

```
drush fr <feature_module>
    "Do you really want to rever variable? (y/n) y
$ Variable reverted
    "Do you really want to revert <feature_module>? (y/n) y
$ <feature_module> revert

```

I clear the cache, go into the new site-\>admin-\>Structure-\>Features-\> and the variables are listed under strongarm and the menu\_blocks are listed on Block settings.

But the menus are not showing on the page. A look in blocks and the menu are not there. It appears they weren't built.

Am I missing a step? Please help.

Thank you in advance

# Answer
> 1 votes
You need to select also, in the feature, under strongarm, the "menu\_block\_ids" variable. Also make sure that the dependency to strongarm is selected. Sometimes it shows the select box but it is left unchecked.

With that the menu block should appear in the blocks page.

It will not appear in the context-\>edit-\>menu block though, and I think that is an issue. I am doing more tests before I really open it though.

----alternatively

Don't do it with fe features or strongarm, instead, just use menu block export module (go there admin/config/user-interface/menu-block/export) and proceed, just put any name and click export.

Copy the resulting code in your feature.module (make sure you put the proper name). Something like this:

```
function feature_name_menu_block_blocks() {
// The array key is the block delta used by menu block.
  return array(
    '23' => array( // feel free to change this to the real id of your menu block
      'parent'      => 'menu-api-menu:0',  //the module might not encapsulate string, be careful
      'title_link'  => 0,
      'admin_title' => 'title',
      'level'       => 1,
      'follow'      => '0',
      'depth'       => 0,
      'expanded'    => 1,
      'sort'        => 0,
    ),
  );
}

```

Just copy the menu block you want to export, you dont have to copy all of them.

---
Tags: features, blocks
---


# Question
Title: Adding Comments to Custom Node Template File
Is there a way to add comments/comment form to a custom template file without having to install the Panels module? I had initially thought I could do it through a php script on the page, but have yet to find an answer.

I'm stuck, but all I need is for it to be at the bottom of my custom template file, which is for a custom content type. Thanks!

# Answer
> 1 votes
You may want to take the sample node template file and update as per your requirement. Here is the code which renders the comments section of the node template file.

```
<?php print render($content['comments']); ?>

```

---
Tags: theming, comments
---


title: Line Item displays sku in title

text:
# Question
Title: Line Item displays sku in title
How do you hide the SKU in the line item display.

It seems to be part of the "Line item label" field on admin/commerce/config/line-items/product/fields

Theres also no option in the view to change it.

# Answer
After further inspection, I found in the view that "Rewrite the output of this field" was on to include the sku.
> 2 votes

# Answer
In my case, it was the 'Commerce Line Item:Label' field that was appending SKU to the end of title. I excluded it from display & SKU disappeared.

Hope this helps someone.

Regards,

Supriya Rajgopal
> 0 votes

---
Tags: commerce
---


# Question
Title: How to insert textfield in the table and submit button under the table
I want to create receive item from my purchase order node. I have to create a table and displayed all data from node. In last column of table I need to add a textfield and a submit button under the table.

I have read a lot of reference, but still getting error. I hope somebody help to solve my problem.

by this code i want to create a form in table

```

function wespi_po_page(){
    $nid =arg(1);
    $form = array();
    $items = db_query('Select
                          Count(field_data_field_item.delta) As items
                        From
                          node Inner Join
                          field_data_field_item On node.nid = field_data_field_item.entity_id
                        Where
                          node.nid = :nid',array(':nid'=>$nid)
                    )->fetchField();
    drupal_set_message('Items counted : ' . $items);

$header = array(
    array('data' => 'Title', 'field' => 'title'),
    array('data' => 'On order', 'field' => 'on_order'),
    array('data' => 'On received', 'field' => 'on_received'),
    array('data' => 'Receive', 'field' => 'receive'),
    );

    $result = db_query ('
                        Select
                          field_data_field_item.field_item_nid As nid,
                          node.title As title,
                          field_data_field_on_order.field_on_order_value As on_order,
                          field_data_field_on_received.field_on_received_value As on_received
                        From
                          field_data_field_item Left Join
                          field_data_field_on_received On field_data_field_item.entity_id =
                            field_data_field_on_received.entity_id And field_data_field_item.delta =
                            field_data_field_on_received.delta Left Join
                          field_data_field_on_order On field_data_field_item.entity_id =
                            field_data_field_on_order.entity_id And field_data_field_item.delta =
                            field_data_field_on_order.delta Inner Join
                          node On field_data_field_item.field_item_nid = node.nid
                        Where
                          field_data_field_item.entity_id = :nid
                        Group By
                          field_data_field_item.field_item_nid', array(':nid' => $nid)
                );
    $rows = array();
    foreach ($result as $data) {
        $rows[] = array(
                    'data' => array(
                          l($data->title, 'node/'. $data->nid),
                          $data->on_order,
                          $data->on_received,
                          //$data->status
                    )
        );
    }
    $output = theme('table',
                            array(
                                'header' => $header,
                                'rows'=>$rows,
                                'sticky' => TRUE,
                            )
        );
    return $output;
}

function wespi_po_theme($existing, $type, $theme, $path) {
  return array(
    'wespi_po_table' => array(
      'render element' => 'element'
    ),
  );
}

function wespi_po_tab_page_form_submit(){
    drupal_set_message($items . ' Items received');
}

```

# Answer
> 1 votes
implements hook\_form in your module and fetch any data you want from database as well as add textfield. After completion of all form items you can theme it as using

```
$output = theme('table', array( 'header' => $header,  'rows' => $rows));

```

in your page callback function. for more information you can check form api in drupal.org.

# Answer
> 0 votes
I'm not completely sure, but I know you might could check how the https://drupal.org/project/diff module does this when viewing the node/%nid/revisions

It adds a compare button revisions button to the table.

Hope that helps

# Answer
> 0 votes
You can use below link for meeting above Drupal 7 Forms Table

It basically covers theme table & passing form as reference.

# Answer
> 0 votes
You can use Views to display the items corresponding to your node. You may use contextual filter to get the node id from the URL.

Once you have the view appearing in the page, follow the steps provided in this article to create a form and submit data.

https://www.isovera.com/blog/programmatically-creating-forms-views-drupal-7

---
Tags: 7, forms
---


title: Display nodes with the same parent node

text:
# Question
Title: Display nodes with the same parent node
Let's say I have a **Region** content type that have multiple entity reference to a **City** content Type.

When I'm on a **City page**, I would like to display **Cities** of the same **Region** as the **City page**.

How can I achieve this through a view?

Keeping in mind that I also need to display cities of a Region at some point, switching the relation owner (City having the entity reference field to Region) might no be a solution here.

# Answer
If it was me, I'd probably use a Region reference on the City so that you only need a single-value field, but this should be quickly accomplished in Views either way.

Assuming a City reference on the Region:

1. Create a View of Content entities of type City with a Block Display.
2. Add a Node ID Contextual Filter with Default Actions set to Provide Default Value \> Content ID from URL.
3. Add a required Relationship to Region/Content using your reference field.
4. Add your reference Field to the display using the Relationship and uncheck/disable Multiple Field Settings \> Display all values in the same row.
5. Add a Contextual Filter for your reference field using the Relationship with Default Actions set to Provide Default Value \> Content ID from URL. Then check/enable the More \> Exclude option.

Now just place the block in a theme region on your site so that it shows up on the City page. #1-4 should get a View showing all Cities that share a Region with the current one. #5 should remove the current one from the results.
> 0 votes

---
Tags: 8, views
---


# Question
Title: How to simulate radio button functionality within a form
I have a form which has 3 radio buttons, each providing a fieldset.

```
o Choice 1
  Fieldset of options v
o Choice 2
  Fieldset of options v
o Choice 3
  Fieldset of options v

```

In order to achieve this, the three radios are each individual radio buttons, and the fieldset for each is enabled when the radio is checked.

The problem, of course, is that once checked, checking one of the other radios doesn't uncheck the original, because they are different fields. I could use #states to simulate radio behavior, clearing one when another is selected, but I don't believe that will work. If I set Option2 to clear if Option1 is checked: Checking Option2, then checking Option1 will clear Option2, great Trying to check Option2 again will leave it unchecked, because the test of whether Option1 is checked will be true

I tried this setting for two of them:

```
  '#states' => array(
    'unchecked' => array(
      ':input[name="*theOtherOption*"]' => array('checked' => TRUE),
    ),

```

What happens is the behavior works for the first click of each radio button, clicking 1 turns off 2, clicking 2 turns off 1, and then it stops working and I end up with both clicked.

# Answer
you should study the Ajax examples module you can follow the examples estructures to build you own code. After doing that your code should look somethink like this:

```
function test_code_radios_callback($form, $form_state) {
  return $form['radios_fieldset'];
}

function test_code_form($form, &$form_state) {

    $options = array(
        'Name'=>t('Name'),
        'Nickname'=>t('Nickname'),
        'Lastname'=>t('Lastname')
        );

    $form['alias'] = array(
    '#type' => 'radios',
    '#title' => 'Choose your alias',
    '#options' => $options,
    '#default_value' => isset($form_state['values']['alias']) ? $form_state['values']['alias'] : '',
    '#ajax' => array(
      'callback' => 'test_code_autotextfields_callback',
      'wrapper' => 'textfields',
      'effect' => 'fade',
        ),
  );

    $form['textfields'] = array(
    '#title' => t("Your Alias"),
    '#prefix' => '<div id="textfields">',
    '#suffix' => '</div>',
    '#type' => 'fieldset',
    '#description' => t('Write your alias here'),
  );

    if (!empty($form_state['values']['alias']) && $form_state['values']['alias']) {
    $value = array();
    $value = $form_state['values']['alias'];

    foreach($value as $item) {
    $name = $item;
    }

      $form['textfields']['$value'] = array(
      '#type' => 'textfield',
      '#title' => $value,
      );

  }

  return $form;
}
function test_code_autotextfields_callback($form, $form_state) {
  return $form['textfields'];
}

```

I tested and it's working as i understood you need it. Tell us how it went. Have a good coding!.
> 1 votes

# Answer
Try to set the name attribute of your radio buttons to be equal. This is basically just HTML behaviour. All radio buttons with the same name are treated as group and only one can be checked.

```
$form['myradio1'] = array(
  // ..
  '#attributes' => array(
    'name' => 'myradio',
  ),
);

$form['myradio2'] = array(
  // ..
  '#attributes' => array(
    'name' => 'myradio',
  ),
);

```
> 0 votes

---
Tags: javascript
---


# Question
Title: how to reference a field in a field collection in a page.tpl file
I have added a field to the basic page content type (a field collection field, to be exact). I want to be able to pull out the content of each field and display it in different format. How can I do this? Which variable contains this data? I am using an override of page.tpl.php.

EDIT: I did try dpm($node) and I see the field collection field. However this is the structure I see -

```
field_call_to_action['und'][0]['value']
```
which is equal to 231. I still don't see the actual values of the fields in the field collection.

# Answer
> 2 votes
You may use `entity_load`. I have a project in which I use Field Collections as you, and this is a fragment of code in my module. I hope it helps you. The key is the use of **entity\_load**.

```
    foreach($node->field_imagenes["und"] as $value){
                $a = entity_load('field_collection_item',     array($value["value"]));
                $prefered = false;
                if(isset($a[$value["value"]]->field_prefered_image["und"][0]["value"]) ...

```

# Answer
> 0 votes
Few of the tutorials that may be helpful for you:

---
Tags: theming, entities
---


# Question
Title: Deletion of some watchdog messages with subquery
What i want is to delete from watchdog the first 20 messages with type as 'blabla' what i did untill now is:

```
 $query = db_select('watchdog', 'w')
    ->fields('w')
    ->condition('type', 'blabla')
    ->range(0, 250);
  $subquery = $query->execute()->fetchCol('wid');

  if ($subquery != NULL) {

    db_delete('watchdog')
      ->condition('wid', $subquery, 'IN')
      ->execute();
  }

```

it works fine but i want to do it with subquery like:

```
$subquery = db_select('watchdog', 'w')
    ->fields('w', array('wid'))
    ->condition('type', 'blabla')
    ->range(0, 250);

  // Deletes the previous selected values.
  db_delete('watchdog')
    ->condition($subquery, 'wid')
    ->execute();

```

it gives me the error:

```
General error: 1093 You can't specify target table 'watchdog' for update in FROM clause

```

Any ideas how to solve this problem?

# Answer
You were close; this should work for you:

```
$subquery = db_select('watchdog', 'w')
  ->fields('w', array('wid'))
  ->condition('type', 'blabla')
  ->range(0, 250)
  ->execute()
  ->fetchCol('wid');

// Deletes the previous selected values.
db_delete('watchdog')
  ->condition('wid', $subquery, 'IN')
  ->execute();

```

You weren't executing the subquery (meaning there were no results), and you mixed up the order of arguments passed to query condition.
> 0 votes

---
Tags: 7, database, log-messages
---


# Question
Title: Different menu links depending on user account
I need to create menu that has to be diffrent for each user.

```
/user/%username%
/user/%username%/purchases
etc.

```

Is there way to do something like that? Thanks

# Answer
> 1 votes
Yes . You can use Menu Token. (Menu Token module provides tokens, that could be used in title or in path of menu items. For example, if you create a menu item with path: "user/\[current-user:uid\]", the url will be changed "on fly" to: "user/1" )

# Answer
> 0 votes
I found the way that is not really good for me, but it is acceptable. I define items in hook\_menu, and combine my meny with primary\_tabs

---
Tags: users, routes
---


# Question
Title: How to db_select DISTINCT on a particular field in Drupal 7?
I understand that you can specify -\>distinct() on the db\_select statement so that it only returns distinct values when looking at ALL fields. But what I want is to return distinct values by only looking at ONE field. Here's my code:

```
$event_table = db_select('my_table', 'e')
    ->distinct()
    ->orderBy('e.time', 'ASC');//ORDER BY
$event_table->join('node', 'n', 'e.nid = n.nid'); //JOIN node with events
$event_table->groupBy('e.time');//GROUP BY time
$event_table->fields('e')//SELECT the fields from events
    ->fields('n',array('type','status','title'))//SELECT the fields from node
    ->orderBy('e.time', 'ASC');//ORDER BY

$result_event_table = $event_table->execute();
$result_event_table = $result_event_table->fetchAllAssoc('time');

```

Suppose I want the distinct column to be e.nid. You'd think -\>distinct('e.nid') would work but it still returns distinct values based on all fields (i.e. distinct(columns1, column2, column3, etc).

# Answer
> 12 votes
Assuming you're trying to get to roughly this query:

```
SELECT DISTINCT e.nid AS nid, e.time AS time, n.type AS type, n.status AS status, n.title AS title
FROM
{my_table} e
INNER JOIN {node} n ON n.nid = e.nid
GROUP BY e.time
ORDER BY e.time ASC

```

You would use:

```
$query = db_select('my_table', 'e')
  ->distinct()
  ->fields('e', array('nid', 'time', 'foo', 'bar'))
  ->fields('n', array('type', 'status', 'title'))
  ->groupBy('e.time')
  ->orderBy('e.time');

$query->join('node', 'n', 'n.nid = e.nid');

```

# Answer
> 6 votes
DISTINCT is actually a global post-modifier for SELECT, that is, as opposed to SELECT ALL (returning all answers) it is SELECT DISTINCT (returning all unique answers). So a single DISTINCT acts on ALL the columns that you give it.

This makes it real hard to use DISTINCT on a single column, while getting the other columns, without doing major extremely ugly backflips.

The correct answer is to use a GROUP BY on the columns that you want to have unique answers:

# Answer
> 3 votes
Remove `->distinct()` and replace it with `$event_table->AddExpression('distinct e.nid', 'nid');`

Like so:

```
$event_table = db_select('my_table', 'e');
$event_table->AddExpression('distinct e.nid', 'nid')
$event_table->orderBy('e.time', 'ASC');//ORDER BY
$event_table->join('node', 'n', 'e.nid = n.nid'); //JOIN node with events
$event_table->groupBy('e.time');//GROUP BY time

// you need to outline all fields here, can't use e.*
$event_table->fields('e')//SELECT the fields from events

    ->fields('n',array('type','status','title'))//SELECT the fields from node
    ->orderBy('e.time', 'ASC');//ORDER BY

$result_event_table = $event_table->execute();
$result_event_table = $result_event_table->fetchAllAssoc('time');

```

# Answer
> -1 votes
If you use this query then, its provide proper distinct query.

```
<?php

$select = db_select('service_payment_transaction','o');
$select->distinct('o.transaction_id');
$select->innerJoin('users', 'u', 'u.uid = o.user_id');
$select->fields('o');
$select->fields('u');
$select->condition('o.service_gv_code','','!=');
$select->range($start,$page_count);
$select->groupBy('o.service_gv_code');
$select->orderBy('transaction_id', 'DESC');
$result_query = $select->execute();

```

---
Tags: database
---


# Question
Title: How to Display Unique Values from database using db_select in Drupal
i tried with following code but i cant get the attached output

```
$query = db_select('webform_submitted_data', 'u');
$query->fields('u', array('sid','nid','data'));
$query->condition('nid','49','=');
$results =$query->execute();

echo "<table>";
echo "<tr>";
echo "<th>Name <th>";
echo "<th>Post <th>";
echo "</tr>";
while($record = $results->fetchAssoc())
{
 $sid = $record['sid'];
 $nid = $record['nid'];
$submission = webform_get_submission($nid,$sid);
echo "<tr>";
echo $submission->data[1][0];
echo $submission->data[2][0];
echo "</tr>";
}
echo "</table>";
}

```

# Answer
> 1 votes
Try

```
$query = db_select('webform_submitted_data', 'u');
$query->fields('u', array('sid','nid')); $query->condition('nid','49','=');
$results =$query->distinct()->execute();

```

Api info about unique

# Answer
> 0 votes
If you use this query then, its provide proper distinct query.

```
<?php

$select = db_select('service_payment_transaction','o');
$select->distinct('o.transaction_id');
$select->innerJoin('users', 'u', 'u.uid = o.user_id');
$select->fields('o');
$select->fields('u');
$select->condition('o.service_gv_code','','!=');
$select->range($start,$page_count);
$select->groupBy('o.service_gv_code');

```

$select-\>orderBy('transaction\_id', 'DESC'); $result\_query = $select-\>execute();

---
Tags: database
---


# Question
Title: Is there a way to set only the "Full HTML" input format for the administrator role?
A plain Drupal 8 installation set the following input formats for the *administrator* role it creates:

* Basic HTML
* Restricted HTML
* Full HTML

The first one is assigned to authenticated users; so, I guess it would be automatically allowed to the *administrator* role. The second one is assigned to anonymous users too.

Is there a way to assign the *Restricted HTML* input format only to anonymous users? I tried editing it to remove the administrator role from it, but when I edit that input format again, I see it is still assigned to the *administrator* role.

To make the question more understandable, I am referring to the settings in admin/config/content/formats/manage/basic\_html.

>

I can unselect *Administrator* from the *Roles* list, but that change will not be keep after saving. Differently, I can take off the permission to use the *Basic HTML* format from the *Authenticated user* role, select it in admin/config/content/formats/manage/basic\_html, and the selection will be kept.

# Answer
> 2 votes
User #1 is a special user that gets all permissions, always. Its access privileges are not controlled by the administrator rule. You can read more about this on Securing user #1.

I haven't tried this, but the following should work.

You could create a new admin user with the administrator role, and give it access to Full HTML only. If you want you can then disable user #1 completely.
Before you disable user #1, make sure the administrator role really does have all permissions. I don't know about Drupal 8, but in Drupal 7 the administrator does not automatically get all permissions when contributed modules are installed.

---
Tags: 8, input-formats
---


title: Postpone payment to a later stage

text:
# Question
Title: Postpone payment to a later stage
How would it be possible to postpone payment processing (move out of checkout) to a later stage/order status change?

I always thought the payment processing is a rule to be invoked on checkout completion, that I could easily modify, but as it comes out, no such rule can be found.

I'm using Stripe payment gateway with card on file. How I'd like the process to work is that the user puts in the card information in checkout as usual (because of card on file, the information is tokenized and a token stored to my server) But instead of the payment happening right away, I'd like to invoke the payment for the order only after the order has been fully processed and sent on it's way.

Therefore I'd like to ask, what would be the recommended process for achieving such functionality?

My ideal solution would be to somehow skip the payment processing in checkout, and process the payment with a rule on another order status change with the card data stored, but am currently unable to find solutions for this.

Best,

Alari

# Answer
> 0 votes
the payments usually are done in the same session then the checkout and has to be done by the user.

some gateways allow batch processing of payments, maybe try another payment gateway ?

or change your business logic. refunding is easier in most gateways ;) so the user pays, but gets refunded, if the order is not processed after X days.

---
Tags: 7, commerce
---


# Question
Title: Using an address field widget on a custom form and storing data
I have a `Subscription` custom entity and I would like to use the default entity form for administration tasks and a custom multistep form for the subscription process.

I added an address field to my `Subscription` entity and I would like to use the widget in one of the custom form steps.

I was expecting I could use something like `'#type' => 'widget_id'` plus some widget configuration, but it does not seem to be so simple as this answer points out.

> a widget and a form element are two different things that are used in different cases; consider a widget a more specialized type of form element.

What would be the right approach then? In the `field_attach_form` change record a comment suggests

```
$display = EntityFormDisplay::collectRenderDisplay($entity, 'default');
$display->buildForm($entity, $form, $form_state);

```

How do I get just my address field? Form display modes?

And then, how do I deal with validating and storing the data properly?

# Answer
You can limit the $form array's elements by setting their **#access** property to *FALSE*.

The validation and storing should be handled by the form for the corresponding entity by itself.
> 0 votes

---
Tags: 8, entities
---


title: Creating custom CSS for a book

text:
# Question
Title: Creating custom CSS for a book
Using Drupal 7 and creating a number of books with the Books module. They each have their own specific design, so specific CSS needed per book. I know I could create specific content types for each book but I think that would become unmanageable as the number of books grow. We are using the Code Per Node module, we could make use of the Context module to detect which book it is, and then insert a block somewhere on the page with some associated CSS. In theory that would work but is there a better way to do this?

# Answer
In Drupal 7, you can add a CSS class to the `<body>` tag for your book. For nodes, you have the class added by default. For example `page-node-2056`, for the `/node/2056` path.

For Book nodes, you might add the book ID inside your `template.php` theme file, in the `theme_preprocess_html` function:

```
function MYTHEME_preprocess_html(&$vars) {
  // If on an individual node page, add the book ID to body classes.
  if ($node = menu_get_object()) {
    if (isset($node->book['bid'])) {
      $vars['classes_array'][] = drupal_html_class('book-id-' . $node->book['bid']);
    }
  }
}

```

You can then take the ID for each book and add all the style definitions in a single CSS file. Something like the following:

```
.book-id-xxx {
  /* Style for book xxx. */
}
.book-id-yyy {
  /* Syle for book yyy. */
}
... and so on

```

Would it make sense for what you need?
> 1 votes

---
Tags: 7, nodes, theming
---


# Question
Title: How to create a suggested articles block that uses taxonomy?
I've been trying to create a view that uses taxonomy to generate suggested articles to users.

I wanted these articles generated according to their relation with the taxonomy term of the current article the user is reading.

How can I make this work?

# Answer
Have a look at the Similar by Terms module. Here are some more details about it (from its project page):

> This Drupal module attempts to provide context for content items by displaying a view block with links to other similar content. Similarity is based on the taxonomy terms assigned to content. Views are available based on similarity within each of the defined vocabularies for a site as well as similarity within all vocabularies.
>
> What does this really mean? How should you use this module?
>
> 1. Create a freetagging vocabulary called "Tags" assigned to the content types on which you'd like to display the "Similar" view block.
> 2. Enable the view block called "Similar entries from the Tags vocabulary".
> 3. Add keyword tags to the content.
>
> You can also create own views and add similar by term Nid argument, sort handler and similarity as field. Now when you go to the page for a tagged content item, a block will show up displaying other content in descending order of common tags (terms).

**Note**: a stable version of this module is available for both D7 and D8!
> 0 votes

---
Tags: views, 7, blocks
---


# Question
Title: How to unset $page['#attached']['html_head_link'] from head?
Help me with this question please: how to unset `html_head_link` from pages in my Drupal 8.0.3 site.

I mean, delete this META:

```
<link rel="delete-form" href="/node/{id}/delete" />
<link rel="edit-form" href="/node/{id}/edit" />
<link rel="version-history" href="/node/{id}/revisions" />
<link rel="revision" href="/mypage" />

```

I try this in MYTHEME.theme file:

```
function MYTHEME_page_attachments_alter(array &$page) {
  foreach ($page['#attached']['html_head_link'] as $key => $value) {
    unset($page['#attached']['html_head_link'][$key]);
  }
}

```

But this do nothing...

# Answer
> 1 votes
OK. I found fresh module for this trouble. Module's author use `hook_entity_view_alter()` for implements head render. Check out their git respository to download the module and get the full code with comments.

# Answer
> 0 votes
```
function program_html_head_alter(&$head_elements) {
  unset($head_elements['system_meta_generator']);
  foreach ($head_elements as $key => $element) {
    if (isset($element['#attributes']['rel']) && $element['#attributes']['rel'] == 'canonical') {
      unset($head_elements[$key]);
    }
  }
}

```

---
Tags: 8, meta-tags
---


title: Add custom classes to node links

text:
# Question
Title: Add custom classes to node links
How can I add custom classes to node links in Drupal 8?

I want to add some classes to the *Read more* and *Add new comment* links in article teasers.

# Answer
> 6 votes
In your theme open file THEMENAME.theme, example in my case THEMENAME is bartik and file is bartik.theme add code below:

```
/**
 * Implements hook_preprocess_links().
 */
function bartik_preprocess_links(&$variables) {
  if (isset($variables['links']['node-readmore'])) {
    $variables['links']['node-readmore']['link']['#options']['attributes']['class'][] = 'css-readmore';
  }

  if (isset($variables['links']['comment-add'])) {
    $variables['links']['comment-add']['link']['#options']['attributes']['class'][] = 'css-comment';
  }

}

```

**Update:**

Code above will add css class to any readmore link, to add for article only you can add preprocess and check type is article.

```
/**
 * Implements hook_preprocess_HOOK() for node.html.twig.
 */
function bartik_preprocess_node(&$variables) {
  ...

  if ($variables['teaser'] && $variables['node']->getType() == 'article') {
    $node_type_is_article = &drupal_static('node_type_is_article');
    $node_type_is_article = TRUE;
  }
}

/**
 * Implements hook_preprocess_links().
 */
function bartik_preprocess_links(&$variables) {
  if ($node_type_is_article = &drupal_static('node_type_is_article')) {
    if (isset($variables['links']['node-readmore'])) {
      $variables['links']['node-readmore']['link']['#options']['attributes']['class'][] = 'css-readmore';
    }

    if (isset($variables['links']['comment-add'])) {
      $variables['links']['comment-add']['link']['#options']['attributes']['class'][] = 'css-comment';
    }
  }
}

```

Clear all cache and see result. Here is my result:

---
Tags: nodes, 8, theming
---


# Question
Title: Trying to render a custom date format with Twig
I'm in the process of porting one of my contrib themes to Drupal 8. For custom date formats on nodes, I have something like this in a node\_preprocess function in the theme's template.php file in the Drupal 7 version:

```
$vars['thedate'] = format_date($node->created, "custom", "j");
$vars['themonth'] = format_date($node->created, "custom", "M");
$vars['theyear'] = format_date($node->created, "custom", "Y");

```

I render it with the following code.

```
  <?php print $thedate; ?> / <?php print $themonth; ?> / <?php print $theyear; ?>

```

In my Drupal 8 port, I've tried a similar approach in the theme's .theme file and then try to render them in `node.html.twig` as `{{{ thedate }} / {{ themonth }} / {{ theyear }}}`, but I'm getting a nasty error.

> Twig\_Error\_Runtime: An exception has been thrown during the rendering of a template ("The timestamp must be numeric.") in themes/mytheme/templates/page.html.twig at line 210. in Twig\_Template-\>displayWithErrorHandling() (line 279 of /site/core/vendor/twig/twig/lib/Twig/Template.php).

I looked to Twig date formats, and it seems you should simply attach a variable, such as `{{ display_submitted |date("m/d/Y") }}`. I tried that without a preprocess function but what outputs is *12/31/1969*, which is not the date the node was created so I'm a bit lost here.

# Answer
`$node->created` is a FieldItemList object.

You need to use either one of these.

```
$vars['thedate'] = format_date($node->created->value, "custom", "j");
$vars['thedate'] = format_date($node->getCreatedTime(), "custom", "j");

```

All node base fields (and most other entity types, some are still being worked on) have methods now, that are defined in NodeInterface.
> 7 votes

# Answer
Here is an approach that uses just Twig (no preprocess functions needed):

```
<p>{{ node.createdtime | date("d F Y") }}</p>

```
> 14 votes

# Answer
For people who need a little more help understanding this, add the following to YOURTHEMENAME.theme file:

```
/**
 * Implements template_preprocess_comment()
 */
function YOURTHEMENAME_preprocess_comment(&$variables) {
  $comment = $variables['elements']['#comment'];
  $variables['YOUR_DATE_NAME'] = format_date($comment->created->value, "custom", "m / j / y");
}

```

Then in your theme, update the twig template (such as templates/comment.html.twig) to use the variable like so: `{{ YOUR_DATE_NAME }}`
> 1 votes

---
Tags: datetime, 8, theming
---


title: How to add a div class to menu link?

text:
# Question
Title: How to add a div class to menu link?
I would like to add a specific *class* to specific *menu item*, so that the menu item would show an image on **hover**.

Basically I want to implement this in a menu item link:

```
<div class="thumbnails">
<a href="#">Some_name<span><img src="http://www........jpg" alt="image1" height="30%" width="30%" /></span></a>
</div>

```

I have tried Menu Attributes module but I couldn't specified a class I wanted to add. Is there any other way how to do it please?

# Answer
Menu CSS Names

> This is a very simple module that takes the link text of each drupal menu item and adds it as a css class name to the menu's element. Using these class names, each menu item can be styled separately with css. This is also very useful for css sprite techniques.
>
> There are no admin settings for this module, it starts doing its work once the module is enabled. All caches are automatically cleared at this time also. This module works with menus in blocks (including Primary Links) and menus in themes (menus that are enabled from the theme's configuration page).
> 1 votes

# Answer
You could use theme\_menu\_link():

```
function MY_THEME_menu_link(array $variables) {
  $element = $variables['element'];
  $sub_menu = '';

  if ($element['#below']) {
    $sub_menu = drupal_render($element['#below']);
  }
  $output = l($element['#title'], $element['#href'], $element['#localized_options']);

  // Add a div wrapper to my special link.
  $prefix = '';
  $suffix = '';
  if ($element['#href'] == 'foo/bar') {
    $prefix = '<div class="thumbnails">';
    $suffix = '</div>';
  }

  return $prefix . '<li' . drupal_attributes($element['#attributes']) . '>' . $output . $sub_menu . "</li>{$suffix}\n";
}

```
> 0 votes

# Answer
Try to clear your Drupal cache and check once. Further, you can check this link for your purpose.
> 0 votes

---
Tags: 7, routes, media, theming
---


title: Format inline drupal form elements

text:
# Question
Title: Format inline drupal form elements
I got this:

As you see I already aligned label and input field inline with CSS, because they are both inside same container, but the button is outside. I was wondering if I could somehow move the button inside the container? So then I could format all elements into one line.

# Answer
> 0 votes
That's typical in Drupal. In this very moment, This is the CSS styling I use in scenario similar to yours:

```
.some-div-class label,  .some-div-class input[type="text"] {
  display:inline;
  width:auto;
  font-size:0.8em;
}

```

This will work fine on mobile devices as well.

Please do note your own CSS may need a bit more work.

---
Tags: theming, forms
---


title: Add to wishlist with ajax

text:
# Question
Title: Add to wishlist with ajax
How can i make **add to wishlist button** with **ajax** like **add to cart button** using Commerce ajax cart module .

Also in my view how to change the **add to wishlist** button text to **already added** if user has already added the product to wishlist. I am using commerce wishlist module

# Answer
> 1 votes
There is a module called Commerce Wishlist

Alternatively, for ajax functionality, you could use the Flag module to replicate a similar sort of functionality

---
Tags: 7, commerce
---


# Question
Title: Is it important to use base table in query?
Is it important to use base table for entity in query? For example if I want to get all user's id of specific role, should I do:

```
  $query = db_select('users', 'u');
  $query->distinct();
  $query->fields('u', array('uid'));
  $query->innerJoin('users_roles', 'r', 'u.uid = r.uid');
  $query->condition('r.rid', 3);

```

or

```
  $query = db_select('users_roles', 'r');
  $query->fields('r', array('uid'));
  $query->condition('r.rid', 3);

```

# Answer
> 5 votes
No, it's not important, nor necessary.

There's no API method for getting this information, so going directly into the database is fair game. Once you're going directly into the database, you only need to include the tables and fields that your data requires - anything else is a waste of resources.

In this case, you don't need to select or filter anything from the `users` table, so there's no need to join it in (unless you're worried about referential integrity, and want to make sure the user record actually exists).

# Answer
> 3 votes
In your case, the second query is enough, unless you need additional filtering/conditions that depend on the base table (e.g. to select only active users).

Generally speaking, core base tables can have certain tags that give you additional processing/filtering out of the box. The best example is the `node_access` tag, which if you add to a query that runs against `{node}` table, will automatically perform node access checks, and fetch only the nodes currently active user has access to. This might be something to consider if you're querying node-related information.

You can read more about query alteration (tagging) here.

---
Tags: 7, database, entities
---


# Question
Title: entitymetadawrapper with field collection multi value
How can I save multiple values in a *multi-value field collection* using **EntityMetadataWrapper** ?

Here's some of my code

```
$field_collection = entity_create('field_collection_item', array('field_name' => 'MY_FIELD_COLLECTION'));
$field_collection->setHostEntity('commerce_line_item', $line_item);
$wrapper = entity_metadata_wrapper('field_collection_item', $field_collection);

for($delta=0; $delta<$max_delta; $delta++) {
  //MISSING something like $wrapper->setDelta($delta);
  $wrapper->field_example->set($new_value);
  $wrapper->other_field_example->set($new_value);
  $wrapper->save();

}

$field_collection->save();

```

I'm fighting with the field delta : I can't use `$wrapper->field_example[$delta]->set($new_value)` because the wrapper itself is the multi-value field, not its children fields.

So I need to find a way to perform something like

```
$wrapper[$delta]->field_example->set($new_value);

```

But this returns "*Fatal error: Cannot use object of type EntityDrupalWrapper as array*".

**Summary : where can I set the delta of the wrapper in the loop ?**

# Answer
> 5 votes
I've found this example in one of the bug reports on d.o, hopefully it will clear things up a bit:

```
// Load the entity and wrap it.
$entity = entity_load_single('my_entity', $entity_id);
$wrapper = entity_metadata_wrapper('my_entity', $entity);
// Create new field collection items.
$collections = array();
// This is a contrived example so assume $things contains some data that might be set on the collections.
foreach ($things as $thing) {
  $fc = entity_create('field_collection_item', array('field_name' => 'field_example_collections'));
  $fc->setHostEntity('my_entity', $entity, $entity->language, FALSE);
  // Skip saving the host entity since the order in which we are creating the items is not the order we want them saved.
  $fc->save(TRUE);
  $collections[] = $fc;
}
// Set the field collection items via the wrapper.
$wrapper->field_example_collections->set($collections);
// Save the entity.
$wrapper->save();

```

Just as @Clive commented, you need to first load the host entity that this field collection field is attached to (I'm assuming it's a `commerce_line_item`?), then loop through your data and create field collection entities. Then after you've done assigning values, collect them all in an array and set the array as the new value for the host entity's field collection field.

# Answer
> 1 votes
To save multi-value field, you need to wrap the values in `array()`, e.g.

```
$wrapper->field_example->set(array($new_value1, $new_value2, $new_value3));

```

or append as this would be an array:

```
$wrapper->field_example[] = $next_value;

```

Here is some more complete example:

```
try {
  $line_item = entity_metadata_wrapper('commerce_line_item', $entity);
  // Create the collection entity, set field values and set it's "host".
  $field_collection_item = entity_create('field_collection_item', array('field_name' => 'MY_FIELD_COLLECTION'));
  $field_collection_item->setHostEntity('commerce_line_item', $line_item->value());
  $collections[$pname] = entity_metadata_wrapper('field_collection_item', $field_collection_item);
  $collections[$pname]->field_example = array($new_value1, $new_value2);
  $collections[$pname]->other_field_example[] = $new_value;
  $collections[$pname]->other_field_example[] = $other_value;
  $line_item->save();
} catch (Exception $e) {
  drupal_set_message(t('Error message: @error.',
        array('@error' => $e->getMessage())), 'error');
  watchdog_exception('MYMODULE', $e);
}

```

---
Tags: entities
---


# Question
Title: Drupal 8 - how to run multisite using one database
I setup Drupal 8 in my localhost, i want to run multisite using one database and one instance (under one drupal installation) How do i achieve this?

Also, i want the url will work like this : site1 : http://localhost/site1 site2 : http://localhost/site2

Thank you.

# Answer
> 5 votes
First, read this page on Drupal 8 multisite, https://www.drupal.org/node/2297419.

It should give you a good idea of what you have to do in order to get multisite working and also explain some of the things you should consider. Following are generic steps, there are many things you can customize using settings.php.

The documentation inside the settings.php file is also very helpful, read that too by viewing the source of the file here https://api.drupal.org/api/drupal/sites!default!default.settings.php/8.

Briefly, the steps are,

1. Multi-site requires the existence of the sites.php file in the sites directory. This file does not exist by default.
2. Add your sites to a $sites array in this file, instructions are mentioned here https://www.drupal.org/node/2297419
3. Create a site directory inside sites/, the path should be sites/**site1**.
4. Each new site directory must have a settings.php file in order for Drupal to recognize it.
5. Visit the URL of site1, site1.yourdomain.com to install it.

# Answer
> 3 votes
In your settings.php there is the database connection setting. In there, you just need to provide table prefix that will distinguish tables for different sites.

Have a look at the settings.php file, it is well documented in there.

---
Tags: 8, multi-sites
---


title: Revolution Slider stuck at loading

text:
# Question
Title: Revolution Slider stuck at loading
I need your help. I am running a site (D7.43, jQuery 1.10) with the Jollyany theme under the hood. The theme comes packaged with the revolution Slider from ThemePunch. I am trying to include a slider into a page, but am then confronted with the slider being empty and the loading spinner spinning away merrily forever. Navigation bullets and left right arrows are visible but do nothing.

You can see the page here: wixschool.net/test-class.

This page shows the revolution slider in place. The slider shows the last of three images, constant spinner, no transition to next slide. Navigation also doesn't go anywhere, slider completely stuck. Slider scripts are called in the head, html for the slider is put in place and seems OK.

(In fact the sldier does not even show any picture, but I've removed the 'visiblity hidden" from the CSS of the background image so its easier to see the slider.. and it then shows the last of three images, not the first..)

There were suggestions out there that it may be (double call to) script issue, so I have tried switching off all other scripts that are called in the head and below the body to see if that would make a difference, but besides losing functionaltiy that those scripst supply the slider stays stuck..

Any suggestions as to why the slider doesn't work is extremely welcome!

Edit: I just noticed that on the test-class page the TB MegaMenu dropdown in the menu don't work (any other page they do..). Tried removing the entire menu as well as the TB Menu scripts but still no working slider..

# Answer
> 0 votes
Reason for Revolution Slider failure found: the Rev Slider uses the `hammer.js` jQuery plugin. Elsewhere on my site I have installed the jQuery mMenu, which also has `hammer.js` among its scripts. I disabled `hammer.js` in mmenu, and the Rev Slider comes alive immediately. The clash centres around the `event listeners` functions in the hammer script.

Haven't solved all though, mmenu still works fine but I do get a 'where is hammer.js' error thrown at me now of course. Will report when and how I solve that..

---
Tags: media, javascript
---


title: How to: Array of field collection items

text:
# Question
Title: How to: Array of field collection items
Sorry for being a little bit impudent, bit i would need someone to build an array into a code snippet. As I know nearly nothing about php coding, I managed to adept some code I found to get the urls of video files stored in field collection fields (one is for the .mp4 movie, otherone for the .webm version). So far, the code works well, but - here comes the problem - there is only the first value of each field collection field displayed. So, I Think i would need an array to regenerate the div container containing the tag with the source paths for each value of the field collection, not only for the first one. I anybody can help me, I would be very, very thankful.... i am working on this since more than 6 hours now...

here is my code:

```
// get node object
$node = node_load($nid);

// get field collections from node
$field_html_5_video = field_get_items('node', $node, 'field_html_5_video');

// get all fields values if collection exists
if (!empty($field_html_5_video)){
    $field = field_view_value('node',$node, 'field_html_5_video', $field_html_5_video[0]);
    foreach ($field['entity']['field_collection_item'] as $id => $field_collection){

        // load the field collection item entity
        $field_collection_item = field_collection_item_load($id);
        // wrap the entity and make it easier to get the values of fields
        $field_wrapper = entity_metadata_wrapper('field_collection_item', $field_collection_item);

        // all values from the field collection
        $field_video_mp4        = $field_wrapper->field_video_mp4->value();
        $field_video_webm        = $field_wrapper->field_video_webm->value(); // an array of image data
        $field_video_description  = $field_wrapper->field_video_description->value();

        // getting the video urls
        $video_url_mp4          = $field_video_mp4['uri'] ? file_create_url($field_video_mp4['uri']) : '';
        $video_url_webm          = $field_video_webm['uri'] ? file_create_url($field_video_webm['uri']) : '';

        print '<div class="singleswipe">';
        print '<span>';
        print '<span class="inner">';
        print '<video width="100%" controls>';
        print '<source src="' .$video_url_mp4. '" type=\'video/mp4; codecs="avc1.42E01E, mp4a.40.2"\'>';
        print '<source src="' .$video_url_webm. '" type=\'video/webm; codecs="vp8, vorbis"\'>';

        print '</video>';
        print '</span></span>';
        print '<span class="datainfo">' .$field_video_description. '</span>';
        print '</div>';
    }
}

```

# Answer
As per @Andrew comment, instead what you have try printing your HTML start a var outside your foreach and then:

```
$template .= '<html>';

```

adding to it, then print it out after your foreach has finished looping.

In addition make an array outside the foreach, e.g.:

```
$newarray = array();

```

Try not using the `entity_metadata_wrapper`, as it seems like an extra layer of stuff to deal with.
> 0 votes

---
Tags: entities, theming
---


# Question
Title: Looking for solution to have specific terms have automatic tooltips whenever entered into content items
I would like to have specific text automatically (or manually) insert a tooltip.

For example, let's say I want every instance on the website of:

```
CMS

```

And have the tooltip say:

```
"Content Management System"

```

For drupal to automatically add this would be nice...but not asking for that much ;)

Can I add some kind of dynamic token?

The html can be static since the CSS is bootstrap CDN:

```
<p>Drupal is the best <strong><span data-placement="top" data-  toggle="tooltip" title="Content Management System" type="button">CMS</span></strong> in the world.</p>

```

# Answer
> 0 votes
You could write custom javascript that wraps all strings you want to replace with the `<span data-toogle="tooltip"></span>`

here's a tutorial

```
// Pretending we have more than one paragraph to look through
jQuery('p').each(function(){
    traverseChildNodes(this);
});

function traverseChildNodes(node) {

    var next;

    if (node.nodeType === 1) {

        // (Element node)

        if (node = node.firstChild) {
            do {
                // Recursively call traverseChildNodes
                // on each child node
                next = node.nextSibling;
                traverseChildNodes(node);
            } while(node = next);
        }

    } else if (node.nodeType === 3) {

        // (Text node)

        if (/CMS/.test(node.data)) {
            // Do something interesting here
            alert('FOUND A MATCH!');
        }

    }

}

```

# Answer
> 0 votes
In a custom module:

```
function MODULE_filter_info() {
  $filters = array();
  $filters['inline_terms'] = array(
    'title' => t('Term definitions inline'),
    'process callback' => '_MODULE_inline_terms_filter',

  );
  return $filters;
}

function _MODULE_inline_terms_filter($text, $filter, $format, $langcode, $cache, $cache_id) {
  switch ($filter->name) {
    case 'inline_terms':
      $glossary = **... get your glossary array list from somewhere**

      foreach($glossary as $key => $item) {
        $text = str_replace($key, '<span data-placement="top" data-toggle="tooltip" title="' . $item . '" type="button">' . $key . '</span>);
      }
      break;
  }

  return $text;
}

```

If the requirement is **whole word replacements** only, then you can look at preg\_replace, as in this post:

str\_replace: Match whole word only

The benefits of using a text filter is that the content is left untouched in the database. Only when the content is rendered with a cache miss is the filter run over the text.

---
Tags: tooltips
---


# Question
Title: Drupal add google analytics event tracking query strings to url
I have Drupal 7 site for sending the newsletter. I am using simplenews module for sending newsletter. I want to add google analytics tracking query strings to all links in the newsletter so that it is tracked in my google analytics account. How can I achieve this?.

# Answer
Create your links here and add them in your newsletter node content and/or mail template.
> 0 votes

---
Tags: 7, emails, google-analytics
---


# Question
Title: How to add a button :"Get my location" in page views
i have created a gmap views page, and i want add a button "get my location like this :

i want give to visitor a button that can get his location in the map, some one have an idea how to do that ?

# Answer
> 0 votes
You can use the IP Geolocation Views & Maps module for that task. It will provide you with a block that contains a button with the asked functionality. The user location will be determined via several methods:

> Finally IPGV&M provides a set of visitor location retrieval technologies, both IP and HTML5-based, so that you can track where past visits came from and where current visitors are located, superimposing their moving positions as markers on your maps.

Please read carefully about the requirements.

---
Tags: views, location, google-maps
---


title: Drush 8.0.3 cannot update custom module

text:
# Question
Title: Drush 8.0.3 cannot update custom module
I have a few custom modules that updates are being served from a D6 site with the Feature Server (fserver) module. Before updating drush, the drush up command on a site would see there were updates for them just fine. Now I get:

```
$ drush up uni_blocks_antares
Update information last refreshed: Mon, 03/07/2016 - 09:13
Name                Installed Version  Proposed version  Message
uni_blocks_antares  Unknown            Unknown           Specified project not
                                                         found

No code updates available.                                           [ok]

```

But when I check that module's info it exists.

```
$ drush pmi uni_blocks_antares
Extension        :  uni_blocks_antares
Project          :  uni_blocks_antares
Type             :  module
Title            :  UNI Blocks Antares
Description      :  This module pulls in the feed of Toolbar and Footer links
                    from the UNI Features website and creates blocks
                    containing those links.
Version          :  7.x-2.7
Package          :  UNI Custom Modules
Core             :  7.x
PHP              :  5.2.4
Status           :  enabled
Path             :  sites/all/modules/custom/uni_blocks_antares
Schema version   :  module has no schema
Files            :  none
Requires         :  none
Required by      :  none
Permissions      :  none
Configure        :  admin/config/content/uni-blocks

```

I found that updating through the web interface of the site will see an update(version 2.8) and update the module.

How do I get drush up to work again for it?

# Answer
> -1 votes
What I ended up doing was updating drush to 8.0.5 and that solved it.

---
Tags: drush
---


title: How to remove core search index?

text:
# Question
Title: How to remove core search index?
I' switching core search to SOLR. The core search module still needs to be enabled for SOLR to work. How to I remove the (rather large) core search index?

The "search settings / clear index" option says that it won't clear the index and just update new items instead.

I came across search\_reindex(). Do I just run that function?

# Answer
> 8 votes
If I'm reading the function correctly, search\_reindex won't actually empty the search index - it just tells all modules that use search to start re-indexing content.

Uninstalling and re-installing the search module using the "unistall" tab at admin/modules will empty all of the search tables. You will have to temporarily disable all dependent modules to do this.

Alternately, you can empty these tables using the TRUNCATE mysql command. The tables needing to be emptied are search\_dataset, search\_index, search\_total and search\_node\_links. You could also empty the tables using a database management tool - just be sure to leave the table structure intact - you want to empty the tables, not delete them.

You will then need to disable core search indexing to prevent the search index from filling back up. In your sites/default/settings.php file, you can add:

```
$conf['search_cron_limit'] = '0';

```

to prevent Drupal from adding items back into the index on cron runs (while still leaving the search module intact.)

# Answer
> 0 votes
You may also use the Search index wipe contributed module which truncates the search related tables.

> This module clean up search index built by search module. It is helpful while deploying large sites whose search index becomes massive. The reindex button does not clear the search index but rather gradually replaces existing search data with new data as items are reindexed. This module was originated by https://drupal.org/comment/4026188#comment-4026188

---
Tags: 7, search
---


# Question
Title: Which Foundation 6 files need to be uploaded to my host in order to make my Drupal 8 custom theme working with full capabilities
I installed Foundation 6 into my `themes/custom/mytheme` folder using `foundation new`. I get my starter kit, all good and ready to go.

I am not sure which files I need to upload to my host in order for my sites full capabilities.

I track my whole Drupal 8 website using `Git`.

With the installation of Foundation 6 there comes a `.gitignore` file. In this `.gitignore` file it ignores:

```
bower_components
node_modules
npm-debug.log
css

```

But when I want to commit my Foundation 6 custom theme to the server I need files inside `bower_components` folder? Or do I mis something here?

When you look at Foundation 6 example `index.html` they load:

```
bower_components/jquery/dist/jquery.js
bower_components/what-input/what-input.js
bower_components/foundation-sites/dist/foundation.js

```
1. What do I have to do with the Foundation `.gitignore` file exactly?
2. And which javascript files do I have to attach to have a good working Drupal 8 and Foundation 6 theme to start building my theme on?

# Answer
The .gitignore file that is downloaded with Foundation 6 is tied to just the Foundation framework - if you're planning to track the whole Drupal site, you can safely delete it and just use the one that comes at the Drupal root.

In the past I've just tracked everything (and committed everything) in the framework up, including the bower\_components folder.

My \[theme\_name\].libraries.yml file looks like this:

```
global-styling:
  version: 1.x
  css:
    theme:
      stylesheets/fonts/stylesheet.css: {}
      stylesheets/foundation-icons/foundation-icons.css: {}
      stylesheets/app.css: {}
      stylesheets/print.css: { media: print }
  js:
    bower_components/fastclick/lib/fastclick.js: {}
    bower_components/foundation/js/foundation.min.js: {}
    bower_components/foundation/js/foundation/foundation.topbar.js: {}
    js/app.js: {}
  dependencies:
    - core/jquery
    - core/jquery.once

homepage:
  version: 1.x
  js:
    js/jquery-ui-1.11.4.custom/jquery-ui.min.js: {}
    js/wcreek-slider.js: {}

```

The js is my own theme's js folder, and you can see I'm including some bower\_components files. I'm using the default jquery that shipped with Drupal 8, but I'm using Foundation 5. You might want to rather include the version of jquery from the bower\_components.

Also I would recommend that you set your Drupal administration theme to be different from your Foundation theme (I usually set it to Seven) so there's no conflict between Foundation and the Drupal admin tools, like views, etc.

You might be able to use jquery\_update module to specify a lower version of jquery for the admin theme (I haven't tried this in Drupal 8 yet). This might be needed if you are using the overlay module.
> 1 votes

# Answer
I do not recommend tracking bower\_components/node\_modules which is why they are in the gitignore file. They can become quite large (100MB or more) and its so easy to bower install / npm install anyway.

If you are using SCSS to theme, the SCSS file should be importing the bower\_components assets and building from that. They are not necessary to be tracked in that case. If you are using a CI server, it should do bower install etc to get Foundation and compile the CSS.

The 6.x branch of Foundation for Drupal is available, but it is still largely based on 5.x.

https://www.drupal.org/project/zurb\_foundation

You might want to look into starting here, as we have solved some of these issues within Drupal.

In fact, for jQuery, that dependency is ignored per our .bowerrc as Drupal 8 ships with the version of jQuery you would need, so there is no need to load it in the theme.
> 0 votes

---
Tags: theming, 8
---


# Question
Title: How to dynamically set the maximum cardinality for a multi value field?
I am using a multi value image field which is set to hold 5 values. What I need, is to be able to set a lower cardinality for this field on specific nodes of the same content type.

Edit: Below is what I ended up using, it might help someone.

```
/**
 * Implements hook_field_attach_form().
 */
function example_field_attach_form($entity_type, $entity, &$form, &$form_state, $langcode) {
  // Our field name
  $field_name = 'field_listing_images';

  // You may want to add more conditions
  if (isset($form[$field_name][LANGUAGE_NONE])) {

    // Our custom cardinality (hardcoded here)
    $custom_cardinality = 3;

    // Unset all field multi values that are equal or larger than our $custom_cardinality variable
    foreach ($form[$field_name][LANGUAGE_NONE] as $k => $value) {
      if ($k >= $custom_cardinality) {
        unset($form[$field_name][LANGUAGE_NONE][$k]);
      }
    }

    // Our custom form validation
    $form['#validate'][] = 'example_custom_form_validate';
  }
}
/**
 * Our custom form validation callback.
 */
function example_custom_form_validate($form, &$form_state) {
  // Our field name
  $field_name = 'field_listing_images';

  // You may want to add more conditions
  if (isset($form_state['values'][$field_name][LANGUAGE_NONE])) {

    // Our custom cardinality (hardcoded here)
    $custom_cardinality = 3;

    // Unset all field multi values that are equal or larger than our $custom_cardinality variable
    foreach ($form_state['values'][$field_name][LANGUAGE_NONE] as $k => $value) {
      if ($k >= $custom_cardinality) {
        unset($form_state['values'][$field_name][LANGUAGE_NONE][$k]);
      }
    }
  }
}

```

# Answer
After some digging around in the field API, I can only conclude that I cannot find a way to do this properly. If the cardinality is available in a hook prior to rendering, then I cannot find it. If you want to attempt to research more yourself, I recommend the Field Attach API. What I did find, was hook\_field\_attach\_form, in which you can do:

```
function hook_field_attach_form($entity_type, $entity, &$form, &$form_state, $langcode) {
  $form['field_test'][LANGUAGE_NONE][4]['#access'] = FALSE;
}

```

to deny access to the last element. Unfortunately, this has the "nice" effect of leaving an empty drag handle element on the page. In order to get rid of that, you need to

```
function hook_field_attach_form($entity_type, $entity, &$form, &$form_state, $langcode) {
  $form['field_test'][LANGUAGE_NONE][4]['#access'] = FALSE;
  unset($form['field_test'][LANGUAGE_NONE][4]);
}

```

but unset-ting form elements like that is just plain wrong, and can potentially cause issues with form validation.

What you may want to do instead, is move the whole logic in a custom validation form, and simply reject form submission if to many values are entered. See this stackexchange question for custom node validation, it's relevant to D7 as well.
> 0 votes

# Answer
My cardinality was based on the value of another field in a related entity, so I figured out that I could set the number of values to Unlimited in the field settings, then, in hook\_form\_alter, reattach the field to the form with a new cardinality:

```
$field = field_info_field('field_my_field');
$field['cardinality'] = $my_new_cardinality;
$instance = field_info_instance('entity_type', 'field_my_field', 'bundle');

// Depending on the form, the entity may be found in $form['#entity'],
// in $form_state, or elsewhere.
// $langcode is usually LANGUAGE_NONE, but may change in multilingual sites.
$items = isset($entity->field_my_field[$langcode]) ? $entity->field_my_field[$langcode] : array();
$new_field = field_multiple_value_form($field, $instance, $langcode, $items, $form, $form_state);

// This is not needed. It tricks theme_field_multiple_value_form into
// not adding the value reordering widget.
$new_field['#cardinality'] = 0;
foreach (element_children($new_field) as $delta) {
  $new_field[$delta]['_weight']['#access'] = FALSE;
}

$form['field_my_field'][$langcode] = $new_field;

```
> 1 votes

# Answer
The right way to do this is to help get this patch in and use hook\_field\_widget\_properties\_alter() or module "Field instance cardinality".
> 0 votes

# Answer
Currently it's not possible to restrict cardinality in the field instance settings, but you can use the patch from there.

As workaround you may set the the maximum cardinality for a multi value field by modifying `items_count` and its `cardinality` in its `$field_state` (see: `field_form_get_state`), then do extra checking in `hook_form_alter`, e.g.

```
$limit = 3 // Your dynamic limit.
$field_state = field_form_get_state($parents, $field_name, $langcode, $form_state)
$field_state['items_count'] = $limit;
$field_state['field']['cardinality'] = $limit;

```

The above code can be triggered e.g. from rules, see: How to change field cardinality per form either programatically or by rule? for complete example.

Then in hook\_form\_alter() you may check if `items_count` reached its `cardinality`, then disable *Add* and *Remove* buttons. For example:

```
$field = &$form['FIELDNAME'];
$field_state = field_form_get_state($field[$field['#language']]['#field_parents'], $field[$field['#language']]['#field_name'], $langcode, $form_state);
if ($field_state['items_count'] == $field_state['field']['cardinality']) {
  $field[$langcode]['add_more']['#access'] = FALSE;
  foreach (array_column($field[$langcode], 'remove_button') as $key2 => $rm_item) {
    $field[$langcode][$key2]['remove_button']['#access'] = FALSE;
  }
}

```

---

Alternatively try the following module:

which enhances settings for muliple value fields.
> 0 votes

---
Tags: 7, entities
---