# Question
Title: Automake forum on node creation with rules
I'm desperately trying to programmatically add a new forum (in the 194 tid specific container) on node creation with rules.

I run php script when adding new node with rules, but I'm really newbee with php. I'm trying to use form\_forum\_form and form\_forum\_submit putting this variables :

```
require_once 'modules/forum/forum.admin.inc';

$autoform = array(
     'name' => '[node:title]',
    'description' => 'Forum du projet [node:title]',
    'tid' => 194,
    'weight' => 0,
);

$form = forum_form_forum($form, &$form_state, $edit = $autoform);
forum_form_submit($form, &$form_state);
print_r(drupal_get_messages());

```

This link doesn't helped me and there is nowhere on the web where the answer is explicitely given. How to programmatically create forums and containers (not forum topics)?

Thanks for helping

# Answer
> 2 votes
There is no need for any custom php here. Just the below steps.

In Rules actions,

1. Action 1: "Create a new entity \> Taxonomy term"
2. Enter your title based on the created node and put it in the forum taxonomy
3. Action 2: "Set a data value \> \[entity-created:parent\], Value: 194"

---
Tags: rules, nodes
---


title: .attr('target','_blank'); does not work

text:
# Question
Title: .attr('target','_blank'); does not work
I have a custom module with differents forms and on one of these forms i want to submit and open the result on a new tab. I found a way to do this on this link : custom form submit in a new browser tab

it works great but instead i need to make a js file to do the same thing.

If it works with the target attributes (link above) directly put in my form why make the same thing in a js file ? i suppose that i will have to use a js file, because with the target attributes it does not work, a new tab does not open when i clicked on a modal button (using ctools modal form).

So my problem is the following: when i make a js file and put this code

```
(function ($) {
Drupal.behaviors.multi_example = {
  attach: function(context, settings) {
      $('#pv-button').attr('target', '_blank');
  }
};

})(jQuery);

```

It does anything ! On my js file, my id button works properly, i have tested it with a simple alert:

```
.click(function(){
            alert("Hello World");
}

```

and it works. I've also tested with `window.open('','_blank')` and a new tab open. So i think there is a problem with the .attr() function. I've passed a long time to search a solution on "google" but nothing... i need some help please.

PS: I want to precise that i have used all these codes (code above) on a normal node, not on a modal.

I'm using Drupal 7.50, jQuery 1.10.2, PHP 5.6.19

# Answer
> 1 votes
This questions seems unrelated to Drupal, and is probably more appropriate on a different forum.

I'm no expert on HTML, but you should make sure that:

(a) you are applying the `target` attribute to html tags that **accept it** (basically `<a>` and `<form>` only). Notice that submit `<button>` or `<input type='submit'>` has a different attribute called `formtarget` (rather than `target`)

And (b) if you are applying this to an `<a>` tag, it has to also have an `href` attribute. See MDN reference

The link you posted for a "custom submit in a new browser tab" answer probably adds the `target` attribute to the `<form>` tag, not to the input.

---
Tags: forms, javascript, chaos-tool-suite
---


# Question
Title: How to invoke autodialog module close method in autodialog.js file using ajax_command_invoke
I have form that loads in modal using autodialog module and I have two buttons inside the form the `close` and `save` button. What I am trying to achieve is to just close the modal when the close button is clicked. I can do this using jQuery but what I wanted to do is use `ajax_command_invoke` to invoke autodialog close to close the modal. so far this what I have done, but I can't make it work maybe I am doing it wrong.

```
function example_autodialog_close_form_submit($form, &$form_state) {
  switch($form_state['clicked_button']['#value']) {
    case 'Closed':
      $commands[] = ajax_command_invoke('.autodialog-content', 'dialog', array('close'));
      break;
    case 'Save':
      // Insert data in database.
      break;
  }
  return array('#type' => 'ajax', '#commands' => $commands);
}

```

> Using jQuery, this one work but what I wanted is use ajax\_command\_invoke to invoke auto dialog close.

```
$('#autodialog-close').click(function() {
  $('.autodialog-content').dialog('close');
});

```

Some code snippet in `autodialog` module `autodialog.js` file.

```
  Drupal.ajax.prototype.commands.autodialog = function (ajax, response, status) {
    var options = {
      title: response.title,
      width: 500,
      modal: true,
      closeText: Drupal.t('Close'),
      close: function () {
        $(this).dialog('destroy').remove();
      }
    };
    $.extend(options, response.options);

    // Close previous dialog
    if (options.closeprev) {
      $('.autodialog-content').dialog('close');
    }

    // Create dialog content
    var $dialogContent = $('' + response.content + '').appendTo('body');

    // Open dialog. Not $dialog.dialog() because it causes problems with inline scripts for jQuery 1.4.
    $('#' + response.dialog_id).dialog(options);

    // Remove focus from first tabbable element
    $dialogContent.closest('.ui-dialog').focus();

    // Close dialog when clicked outside
    $('.ui-widget-overlay:last').click(function (event) {
      if ($(event.target).hasClass('ui-widget-overlay')) {
        $dialogContent.dialog('close');
      }
    });

    Drupal.attachBehaviors($dialogContent);
  }

```

# Answer
Finally I made it work.

Instead of using asaf module (This module is used to AJAX-ify form submissions) - not aware of this one, just notice it appending its own ajax class. thought that `autodialog` already made the submit button ajaxified. In combo with autodialog I make my form api submit button ajaxified.

here's my working code

Form submit buttons.

```
  $form['closed'] = array(
    '#type' => 'submit',
    '#value' => 'Closed',
    '#attributes' => array('class' => array('btn btn-block btn-default btn-sm')),
    '#ajax' => array(
      'callback' => 'ajax_example_submit',
    ),
  );

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => 'Save Changes',
    '#ajax' => array(
      'callback' => 'ajax_example_submit',
    ),
  );

```

Ajax callback

```
function ajax_example_submit($form, &$form_state) {
  $commands = array();
  switch($form_state['clicked_button']['#value']) {
    case 'Closed':
      $commands[] = ajax_command_invoke('.autodialog-content', 'dialog', array('close'));
      break;
    case 'Save Changes':
      drupal_set_message('Saved Changes');
      $commands[] = ajax_command_invoke('.autodialog-content', 'dialog', array('close'));
      break;
  }
  return array('#type' => 'ajax', '#commands' => $commands);
}

```
> 1 votes

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


# Question
Title: Image Captcha Refresh not displaying refresh link
I want to add button/link for refreshing Image Captcha, therefore I've installed and enabled Image Captcha Refresh module. But this module is doing nothing, no refresh button is added, no options are added to Image Captcha settings page, no javascript is loaded from this module.

My captcha is in custom form:

```
$form['captcha'] = array(
    '#title' => 'Code',
    '#type' => 'captcha',
    '#captcha_type' => 'image_captcha/Image',

```

What could be wrong?

# Answer
> 2 votes
I have tried recreating your problem and i saw that after you enable the refresh module for the image recaptcha, a link is added below the image in all the forms where captcha is enabled.

But there is no configuration page specific to this refresh module. The link works fine in reloading the image.

I suggest that you add your form via configuration page of the captcha module instead of adding it in the code.

just include your form machine name and captcha in the captcha module configuration page.

---
Tags: forms, captcha
---


# Question
Title: How to change content url content/title to text/title?
I created some content and changed the URL `content/title` to `text/title`. My issue is why my changes didn't apply on some content.

# Answer
> 3 votes
You probably have to delete and then bulk create them from the `admin/config/search/path/delete_bulk` and `admin/config/search/path/update_bulk` pages.

Be careful though if there are links pointing towards pages.

---
Tags: path-aliases
---


# Question
Title: REST API POST returning 400 Syntax error
I wrote a REST plugin for posting data to my Drupal site, When I send JSON data from browser it is returning the error `{readyState: 4, responseText: "{"error":"Syntax error"}", responseJSON: Object, status: 400, statusText: "Bad Request"}` but it is working fine in Postman. What might be the issue?

The data I am send is `{"name" : "user", "pass" : "userpass"}`

I am also adding the following headers in request.

```
"Content-Type", 'application/json'
"Accept", 'application/json'

```

# Answer
You can use Postman to generate your code

Click here to change code language
> 1 votes

---
Tags: 8
---


title: Admin user can't administer the site

text:
# Question
Title: Admin user can't administer the site
When I sign with admin user (or any other user), I can edit the contents, I can edit user, I can´t create user, I can\`t Edit nodes, I can´t install upgrades, I can´t install modules, I can´t save anything.

Thanks.

# Answer
If you can't do all that with the superuser (typically admin, user ID 1), checking permissions won't help, since that account has a "pass all permissions" check on nodes, modules, users, etc.

To figure this out, you can try a few things:

* Go into the database and check if your admin user really has uid 1 (in the users table)
* Check modules (custom modules, specifically) to see if any of them deny access to any admin pages
> 0 votes

---
Tags: debugging
---


# Question
Title: Adding a class to a <div> in .theme file
Using Drupal 8 and Bootstrap sub-theme.

I see that classes are being added to my divs in the page template file using the following:

```
<section{{ content_attributes.addClass(content_classes) }}>

```

That's great. But what if I wanted to add additional classes to these div tags. How would I do that...in my .theme file somehow?

# Answer
> 3 votes
### OPTION 1

In your template file, you could find the `set content_classes` and add another class name to the list.

```
{%
  set content_classes = [
    'class-name',
    'class-name-other',
  ]
%}
<section{{ content_attributes.addClass(content_classes) }}>

```

### OPTION 2

In your **.theme** file

```
function themename_preprocess_html(&$variables) {
  $variables['content_attributes']['class'][] = 'class-name-other';
}

```

**Note:** This preprocess is for the **html.html.twig** file, you need to use the correct preprocess depending on your template file name.

If it's the **node.html.twig** then use function `themename_preprocess_node(&$variables)`

If it's the **page.html.twig** then use function `themename_preprocess_page(&$variables)`

---
Tags: theming, 8
---


# Question
Title: How to add comment to a node with ajax (ctools modal)?
I' trying to create custom module that should add comment to a content type in a modal window, with ajax. I wrote following code, but when I click on the 'Add review' link, browser loads new page when I can add 'reviews about shop' content type. I want to do this in a modal window, without reloading

```
function current_posts_menu() {
 $items['add/%ctools_js/review'] = array(
   'page callback'    => 'current_posts_ctools_modal_review',
   'page arguments'   => array(1),
   'access arguments' => array('create review content'),
 );
 return $items;
}

function current_posts_popup_style() {

  static $added = FALSE;
  if ($added == FALSE) {
    $added = TRUE;

    // Include the CTools tools that we need.
    ctools_include('modal');
    ctools_include('ajax');
    ctools_modal_add_js();

    $popup_style = array(
      'first-popup-style' => array(
        'modalSize' => array(
          'type' => 'fixed',
          'width' => 420,
          'height' => 'auto',
        ),
        'modalOptions' => array(
          'opacity' => (float) 0.3, .
          'background-color' => '#000000',
        ),
        'closeText' => '',
        'loadingText' => '', .
        'animation' => 'fadeIn',
        'animationSpeed' => 'fast',
      ),
    );

    drupal_add_js($popup_style, 'setting');

  }
}
function current_posts_block_info(){
 $blocks['add_review'] = array(
   'info' => t('Add review'),
 );
 return $blocks;
}

/**
* Implements hook_block_view().
*/
function current_posts_block_view($delta = '') {
    $block = array();
 switch ($delta) {
   case 'add_review':
     ctools_include('ajax');
     ctools_include('modal');
     ctools_modal_add_js();
     current_posts_popup_style();
     $comment_site_id = arg(1);
      $block['content'] = l(t('Add a review'), "add/nojs/review/{$comment_site_id }", array('html' => TRUE, 'attributes' => array('class' => "ctools-use-modal ctools-modal-first-popup-style")));
/*ctools-modal-first-popup-style */
     break;
 }
 return $block;
}

function current_posts_form_alter(&$form, &$form_state, $form_id) {
 switch ($form_id) {
   case 'comment_site':
     $comment_site_id = arg(3);
     if (is_numeric(arg(3))) {
       $lang = field_language('node', $form['#node'], 'field_news');
       // Declaration the default value for field on the comment creating form.
       $form['field_news'][$lang][0]['nid']['#default_value'] = $comment_site_id;

     }

 }
}

function current_posts_ctools_modal_review($js = FALSE) {
 // loading libraries ctools'a
 ctools_include('node.pages', 'node', '');
 ctools_include('modal');
 ctools_include('ajax');

 $type = 'reviews_about_shop';
 $node = (object) array(
   'uid' => $user->uid,
   'name' => (isset($user->name) ? $user->name : ''),
   'type' => $type,
   'language' => LANGUAGE_NONE
   );
  // Loading node form with disabled scripts.
 if (!$js) {
   return drupal_get_form($type . '_node_form', $node);
}
 // Create array $form_state.
 $form_state = array(
   'title' => t('Add Review'),
   'ajax'  => TRUE,
 );

    $form_state['build_info']['args'] = array($node);
    $output = ctools_modal_form_wrapper($type . '_node_form', $form_state);
    // Actions after form submit.
    if (!empty($form_state['executed'])) {
    $output = array();
    // Close pop up.
    $output[] = ctools_modal_command_dismiss();
    $comment_site_id = arg(3);
    // Insert  updated  view into a  page.
    if (is_numeric(arg(3))) {
     $output[] = ajax_command_html('.latest-reviews-full-style', views_embed_view('reviews_on_main_page', 'block', arg(3)));
    }
 }
    print ajax_render($output);
}

```

**Note**: I need like adding content type in a modal window. In my module reviews\_about\_shop is a content type that linked to a content type comment\_site.

# Answer
You need to add ajax library to that

```
drupal_add_library('system', 'drupal.ajax');

```

Or you can use the below function to render the ajax link

```
$block['content'] = l(t('Add a review'), "add/nojs/review/{$comment_site_id }", array('html' => TRUE, 'attributes' => array('class' => "ctools-use-modal ctools-modal-first-popup-style")));

```

Replace the above line to below.

```
$block['content'] = ctools_modal_text_button(t('Newsletter datacapture modal'), "add/nojs/review/{$comment_site_id }", t('Add a review'), "ctools-modal-first-popup-style");

```

Modify the argument

```
function current_posts_menu() {
 $items['add/%ctools_js/review/%'] = array(
   'page callback'    => 'current_posts_ctools_modal_review',
   'page arguments'   => array(1,3),
   'access arguments' => array('create review content'),
 );
 return $items;
}

```

and not to mention "Clear Cache"
> 1 votes

# Answer
Assuming you're on Drupal 7. Alternatively, you could do it with the Modal Forms (with ctools) module

> Modal forms make use of the modal feature in the ctools module to open some common forms in a modal window.
> 0 votes

---
Tags: ajax, chaos-tool-suite
---


# Question
Title: How can I set a separator for a taxonomy field?
Within my nodes I'm want to display my taxonomy field references with a separator, like this:

```
term1 - term2 - term3

```

what I get as a standard is:

```
term1
term2
term3

```

with display suite I can get:

```
term1 term2 term3

```

I know that I can do this with CSS styling, but is there another solution to add a separator?

# Answer
> 3 votes
You can do this in Twig.

Place this file in the `templates` folder of your theme (`field-tags` is the field name):

**field--field-tags.html.twig**

```
 <div{{ attributes }}>
    {% for item in items %}
      {% if not loop.last %}
        <span{{ item.attributes }}>{{ item.content }} - </span>
      {% else %}
        <span{{ item.attributes }}>{{ item.content }}</span>
      {% endif %}
    {% endfor %}
  </div>

```

To add classes use `{{ attributes.addClass() }}` or `{{ item.attributes.addClass() }}`, see https://drupal.stackexchange.com/a/212307/47547

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


# Question
Title: How to add auto generate password link for admin?
I am using Drupal 7 for my website. I have two roles **administrator** and **IT**. I want to add auto generate password link at the time change the password by superadmin or IT role and also send the mail to respective user.

Please help how to add this functionality in my site.

# Answer
> 1 votes
I have implemented this functionality using Password Quick Set module and doing a little bit of custom code.

# Answer
> 2 votes
You can used `hook_user_presave()` to get the changed password in your module:

```
function mymodule_user_presave(&$edit, $account, $category){
 echo $_REQUEST['pass']['pass1'];
}

```

and use the functions `hook_mail()` & `drupal_mail()` to send the email in `hook_user_presave()` with the changed password in `$_REQUEST['pass']['pass1']`.

---
Tags: 7, users
---


# Question
Title: How can I recreate a previously deleted Content Type?
I have deleted a Content Type called **news** some months ago using Drupal’s Field UI. Now I would like to recreate a new Content Type **with the exact same machine name** **news**. However no Content Type shows up. When I take a look at the database a new entry has been created in the node\_type table.

Somehow Drupal doesn’t remove the Content Type in the database. What’s the recommended way to cleanup orphaned Content Types? Why does Drupal keep these leftovers? I don’t want to mess around in database.

# Answer
You should delete the actual content first before deleting the content type. And nodes are going to be orphaned too and provably they will not display same as the content type news. can you try to search the existing news node in `admin/content` and check if you can still see the existing node type news that you created before. and try to delete them all before deleting the news content type and try to re-create the news content type.
> 1 votes

---
Tags: 7, entities
---


# Question
Title: Override default language via URL parameter
With the Internationalization module, is there any way to override the default language selection?

We have a site with two languages, EN and FR, and we'd like to send out an email newsletter that has various links to the secondary (non-default) language content. The Language Negotiation is set to "Path prefix with language fallback", and directs them to the default language, even if we use the full language prefixed URL, ie:

```
www.example.com/fr/content
--gets sent to--
www.example.com/en/content

```

What would be ideal is if we could pass an argument like this:

```
www.example.com/fr/content?force_language=FR

```

Any solutions out there?

# Answer
It's been more than a few years since I've done this in Drupal 6, so things may be a bit vague and hazy. I do remember there being an order menu for this, where you could say that language gets selected first by cookie, then browser language, then user preference, then path prefix, or change the order entirely.
> 0 votes

---
Tags: 6, i18n-l10n
---


# Question
Title: Unable to set drupal_set_message() after logout redirect
I want to show a message via `drupal_set_message()` after logout and redirects to page.

Code:

```
/*
 * Implements hook_user_logout().
 */
function example_user_logout($account){
  $login_message = 'You have been redirected';
  drupal_set_message(t($login_message));
  $login_redirect = '/mypage';
  example_redirect($login_redirect);
}

/**
 * Redirect path for logout.
 */
function example_redirect($path) {
  $response = new RedirectResponse($path);
  $response->send();
  exit;
}

```

Tried commenting exit also, but still no luck. Any help would be appreciable.

# Answer
> 4 votes
`drupal_set_message()` sets the message in `$_SESSION`. By logging out, you destroy the current session and thus wipe the message you just set.

---
Tags: 8, redirection, status-messages
---


title: Field value as Views 3 block title

text:
# Question
Title: Field value as Views 3 block title
I have a Views 3 block whose block title I would like to set using PHP in the header section. This would enable me to use tokens from the views results, which is *not* possible from the UI.

In the case of a views *page* I was able to set the page title via the following PHP command in the header section:

```
$view = views_get_current_view();
$view->build_info['title'] = 'My Page Title';

```

However, I was *not* able to do the same thing for block titles via

```
$view = views_get_current_view();
$view->build_info['title'] = 'My Block Title';

```

This is probably because the `build_info['title']` command only edits the page (or node) title. Does anyone know of an analogous command to set *block* titles?

# Answer
> 1 votes
Sorry, I made a huge mistake. When I tried to achieve the same thing for the block title, I copied the code from the page header but didn't *remove* it from the page header. In other words, I used the PHP commands - *exactly* as described in the question - in the headers of two subviews of the *same* view *simultaneously*. To be more precise, the variable `$view` was used in two places, which caused an error.

When I replace

```
$view = views_get_current_view();
$view->build_info['title'] = 'My Block Title';
```
with
```
$view_block = views_get_current_view();
$view_block->build_info['title'] = 'My Block Title';
```
things work as desired!

# Answer
> 1 votes
In the current version of Views (3.14), you can write tokens in the view title.

It doesn't say so in any help messages, but I have tested it on https://simplytest.me and it worked.

You can see the available token names by selecting the last field and activating `Rewrite the output of this field` and folding out `Replacement patterns`.

---
Tags: views, blocks
---


# Question
Title: How to merge results from two different views?
I need to write an impossible view and I achieve to retrieve the correct list of nodes in two different views and now I need to merge the results in one single table.

How can I merge it?

If the `views_1` give me nodes: `[2, 52, 68, 41]` and the `views_2` give me nodes: `[2, 66, 88]`
I want **ONE** table with the nodes: `[2, 52, 68, 41, 66, 88]`

I can't just merge filter's views because they are based on two relationships so **I can't say to require one relationship OR the other one**, but only to require one or both relationship.

# Answer
Output one view as you normally would.

1. Implement `views_pre_render`.
2. Call `view::preview` on the second view.
3. Manually merge the results from 2 into 1.
> 3 votes

# Answer
To expand on @Letharion's Answer here's an example:

```
function HOOK_views_pre_render(&$view) {

  if($view->name == 'views_1' && $view->current_display == 'default') {

    //Load views_2
    $view2 = views_get_view('views_2'); //View Name
    $view2->preview('default'); //View Display

    //Check for empty results
    if(empty($view2->result)){
      return;
    }

    $view->result = array_merge($view->result, $view2->result);
  }
}

```
> 2 votes

# Answer
Here is alternative way of merging results from two impossible views by using `hook_views_post_render`:

```
/**
 * Implements hook_views_post_render().
 */
function foo_views_post_render(&$view, &$output, &$cache) {
  if ($view->name == 'my_view_1') {

    // API: http://api.drupal.org/api/views/includes!view.inc/class/view/7
    $view2 = views_get_view('my_view_2');
    $view2->preview('page');
    if (empty($view2->result)) {
      return; // Return on empty results.
    }

    $dom = new DOMdocument();
    $dom->loadHTML($output); // Load HTML from a string into DOM object.

    foreach ($view2->result as $item) {

      // Create field values.
      $row1 = clone $row2 = clone $row3 = clone $row4 = clone $row5 = $dom->createDocumentFragment();
      // TODO: Here, get the values assigned from $item ($view2->result).
      $row2_title = 'same value from view2';
      $url = 'some/url';
      $row1->appendXML('<div>foo</div>');
      $row2->appendXML(l($row2_title, $url)); // Link example.
      $row3->appendXML('<div>foo</div>');
      $row4->appendXML('<div>foo</div>');
      $row5->appendXML('<div>foo</div>');

      // Create columns and append content.
      $td1 = $dom->createElement('td'); // row1
      $td1->appendChild($row1);
      $td2 = $dom->createElement('td'); // row2
      $td2->appendChild($row2);
      $td3 = $dom->createElement('td'); // row3
      $td3->appendChild($row3);
      $td4 = $dom->createElement('td'); // row4
      $td4->appendChild($row4);
      $td5 = $dom->createElement('td'); // row5
      $td5->appendChild($row5);

      // Create row and append columns.
      $tr = $dom->createElement('tr');
      $tr->appendChild($td1)->setAttribute('class', 'views-field views-field-row1');
      $tr->appendChild($td2)->setAttribute('class', 'views-field views-field-row2');
      $tr->appendChild($td3)->setAttribute('class', 'views-field views-field-row3');
      $tr->appendChild($td4)->setAttribute('class', 'views-field views-field-row4');
      $tr->appendChild($td5)->setAttribute('class', 'views-field views-field-row5');

      // Apply changes to table and document.
      $table = $dom->getElementsByTagName('table')->item(0)->getElementsByTagName('tbody')->item(0);
      $table->appendChild($tr);
    }

    $output = $dom->saveHTML();
  }
}

```

This solution is for table display only and it's adding new items of *view2* into *view1* results by parsing directly html output.

It has advantage of merging different type of views which doesn't share the same data, not using SQL or proper node objects or using different hooks (e.g. Search API, or YQL View).
> 0 votes

# Answer
The below code combines two views based on `message` table which have different relationships. Same should apply on `node` table.

```
/**
 * Implements hook_views_pre_execute().
 */
function MY_MODULE_views_pre_execute(&$view) {
  if ($view->name == 'VIEW_1' && $view->current_display == 'DISPLAY_OF_VIEW_1') {

    $view2 = views_get_view('VIEW_2');
    $view2->build('DISPLAY_OF_VIEW_2');

    $view->build_info['query'] = db_select( //this is for cardinality errrors
      $view->build_info['query']
        ->fields('table_alias', array('timestamp'))
        ->range() //unset offset and limit to set them after the union
        ->union(
          $view2->build_info['query']
            ->fields('table_alias', array('timestamp'))
            ->range()
      ), 'table_alias'
    )
      ->fields('table_alias', array('mid', 'timestamp'))
      ->orderBy('timestamp', 'DESC') //you should order manually
      ->range(
        $view->query->pager->current_page * $view->query->limit,
        $view->query->limit);

    $view->build_info['count_query'] = $view->build_info['query'];
  };
}

```

The evolution of above code has been like this:

```
/**
 * Implements hook_views_pre_execute().
 */
function MY_MODULE_views_pre_execute(&$view) {
  if ($view->name == 'VIEW_1' && $view->current_display == 'DISPLAY_OF_VIEW_1') {

    $view2 = views_get_view('VIEW_2');
    $view2->build('DISPLAY_OF_VIEW_2');

    $view->build_info['query']
      ->fields('table_alias', array('timestamp'))
      ->union(
          $view2->build_info['query']
            ->range()
            ->fields('table_alias', array('timestamp'))
            ->orderBy('timestamp', 'DESC')
      );

    $view->build_info['count_query']
      ->union(
          $view2->build_info['count_query']
          ->range()
      );
  };
}

```
> 0 votes

# Answer
From what I understood you have two different content types, you want to select the content of both of them but the result should be distinct values. Create a view of both content types and set `Use aggregation:Yes` to create distinct values.
> 0 votes

---
Tags: 7, views, theming
---


# Question
Title: How do I display fields from a Commerce Cheque transaction using Views?
We have been processing payments in Drupal Commerce using the Commerce Cheque module. For accounting purposes, we would like a view showing all checks received with check numbers, etc..

How do I configure a view to display fields from Commerce Cheque, specifically check number?

# Answer
You can create a view of of Payment Transactions and filter by Payment Method = check.

The check reference number is stored in the field called Remote ID. Just add that field to the view.
> 0 votes

---
Tags: commerce
---


title: Using panels and panelizer with i18n

text:
# Question
Title: Using panels and panelizer with i18n
I'm building a multilingual site with 4 different languages, using panels and panelizer, but am struggling to see how to have different panels for different languages.

The site has to be content-manageable by the client, so I need to provide panels that can be translated by them.

I've tried 2 routes - first of all using the i18n\_panels submodule in panels. The readme.txt file suggests that I can create a custom pane which can be translated, which would be great, but it isn't very clear how to do this. The example doesn't work.

I've also tried adding a pane for each language and using visibility rules based on the node language. This doesn't work either.

Does anyone have an example of a custom pane that is multilingual using i18n\_panels, or another way of achieving the same effect?

# Answer
I couldn't get the i18n\_panels module to work, but the Multilingual panels module works a treat.

https://www.drupal.org/project/mlpanels
> 0 votes

---
Tags: i18n-l10n, panels
---


title: Display an image search api page result

text:
# Question
Title: Display an image search api page result
I'm trying to display an image on the search api page result. I tried the following way: Displaying Images in Search Results, but I'm getting a "Notice: Undefined index: node...template.php" error. Off course after changing the preprocess function to `theme_preprocess_search_api_page_result`. Am I getting this error because the following preprocessor works only for the search module? Is there another way to add an image to the search api result?

I'm using the following modules version:

* Search API 7.x-1.17
* Solr search 7.x-1.10
* Search Api Page 7.x-1.2

# Answer
> 0 votes
Found my mistake, such a newbie. Instead of 'node' index in the `$variables['result']['node'];` replace it with 'entity'.

But I ended up using a different approach by getting the image URL to be able to style the image as desired.

`<img class="img-responsive" src="<?php print file_create_url($entity->field_image['und']['0']['uri']); ?>" />`

And changed the function template file to:

```
$node = node_load($variables['result']['entity']->nid);
$node && ($variables['entity'] = $node);

```

# Answer
> 1 votes
You first have to add the image to the index. Then preferably reindex. Usually for some reason the image fields are hidden on the page, where you add the fields to the index. The page in Drupal 7 would be under Search and metadata \> Search API \> Your index, edit \> Fields /admin/config/search/search\_api/index/NAME\_OF\_INDEX/fields

And your image field you may add from the bottom - the section is called "Add related fields" and then you should choose your field and click "Add field". Afterwards you may click the checkbox to the field - in order to add it to the index.

The approach with node\_load is a very bad one because that would load stuff from the database, where the idea of Search Api and in this case the connection with Apache Solr - is to get everything directly from the Solr.

---
Tags: 7, search
---


title: Fetch data from database in cron_hook

text:
# Question
Title: Fetch data from database in cron_hook
I made a custom module which runs during cron via de cron\_hook. On installation of the module a database table is installed:

```
  $schema['license_expire'] = array(
    'description' => 'The base table for license_expire.',
    'fields' => array(
      'uid' => array(
        'description' => 'The primary identifier for a user.',
        'type' => 'int',
        'unsigned' => TRUE,
        'not null' => TRUE,
        'default' => 0),
      'warned_user' => array(
        'description' => 'User warning',
        'type' => 'int',
        'unsigned' => TRUE,
        'not null' => TRUE,
        'default' => 0),
    ),
    'primary key' => array('uid'),
  );
  return $schema;

```

When the cron runs content is added to the database. Say uid = 1 and warned\_user = 1.

But when I try to fetch this warned\_user data in de cron\_hook it doesn't return any.

```
function hook_cron() {
//EXPIRE VARIABLES
$expiresMonth = strtotime('+1 month');
$expiresWeek = strtotime('+1 week');
$expired = strtotime('today');

//ALL USERS EXPIRING WITHIN ONE MONTH
$query = new EntityFieldQuery();
$query
->entityCondition('entity_type', 'commerce_license')
->propertyCondition('status', COMMERCE_LICENSE_ACTIVE)
->propertyCondition('expires', 0, '<>')
->propertyCondition('expires', $expiresMonth, '<');
$results = $query->execute();

//SEND EMAIL TO USERS
if (!empty($results['commerce_license'])) {
    $license_ids = array_keys($results['commerce_license']);

    //all licenses
    foreach($license_ids as $license_id) {

       //get Uid
       $myUid = db_select('commerce_license','cl')
         ->fields('cl', array('uid'))
         ->condition('license_id', $license_id)
         ->execute()->fetchField();

       //for testing it only works for de admin account
       if($myUid == 1){
           //get user
           $to = user_load($myUid);

           //get expiring timestamp
           $myExpire = db_select('commerce_license','cl')
             ->fields('cl', array('expires'))
             ->condition('license_id', $license_id)
             ->execute()->fetchField();

           $myDate = date("d-m-Y", $myExpire);

           //get times user is noticed
            $myMessages = db_select('license_expire','le')
            ->fields('le', array('warned_user'))
            ->condition('uid', $myUid)
            ->execute()->fetchField();

           //for some reason the $myMessages value is nothing so watchdog is "myMails = = 1"
           watchdog('license expire', 'myMails = '.$myMessages.' = '.$myUid);

           if($myMessages){do something, but it never does because it can't pull $myMessages value from the db, and it sure is there}

```

The above code does work when I use it in a page.tpl.php file.

I found something about, cron being a Anonymous user and this could be the problem but the solution offered didn't work for me. What dit I forget/overlook/do wrong?

# Answer
I found the problem, I was using the same variable names (for example $query) in different custom modules I build. Changing these variable names to unique names made it work perfectly.
> 0 votes

---
Tags: cron
---


# Question
Title: Re-enable System theme file within a child theme
I have the bootstrap theme installed.

I have a custom theme installed.

The bootstrap.info.yml file has the lines:

```
libraries-override:

# Remove individual stylesheets.
  system/base:
    css:
      component:
        css/components/ajax-progress.module.css: false
        css/components/autocomplete-loading.module.css: false
        css/components/tabledrag.module.css: false

```

In my custom\_theme.info.yml file, how can I re-enable the ajax-progress.module.css file?

I've tried adding the following, thinking it would override it, but it doesn't seem to work.

```
libraries-override:

# Re-enable individual stylesheets.
  system/base:
    css:
      component:
        css/components/ajax-progress.module.css: true

```

# Answer
> 0 votes
One way of getting this to work is to add the CSS file as a part of your global-styling in `custom_theme.libraries.yml`

```
global-styling:
  css:
    theme:
      /core/modules/system/css/components/ajax-progress.module.css: {}

```

Hope this helps anyone who has come across this problem.

---
Tags: theming, 8
---


# Question
Title: How to convert text area data into select list in forms?
I want to create a configurable select list in forms.To achieve this what I did is I have created a text area, in that I will enter values like:

```
HI|Hi
BYE|Bye

```

So, in form select options I have to use these values in a dropdown list. How can I achieve that. I am getting this text area data in form like below.Here I am getting data, but not displaying in the options.

```
$entityoptions = variable_get('entitydropdown');

```

I am getting the values as it is, but am not getting how can I assign these values to `#options`. I did like below but its not displaying the values.

```
'#options' => $entityoptions,

```

Please help me to identify, where I am doing wrong. Thanks in advance.

# Answer
As requested in the comments, in answer format:

1. Use the explode() function on your string
2. Loop through the results and split each entry
3. Add the result to the options array you feed to the select box

Eg.

```
$options = array();
$lines = explode(PHP_EOL, $entityoptions);
foreach($lines as $line) {
  $line = explode('|', $line);
  $options[$line[0]] = $line[1];
}

```
> 0 votes

---
Tags: 7, forms
---


# Question
Title: Attaching 'active' class to faqfield expanded question
I am using the FAQ Field module my project which utilizes the jQuery Accordion UI and HTML definition lists, and I am wondering how I can attach an 'active' field to the expanded question. I would like to know so I can show/hide an up/down caret next to each of the questions based on it's active (expanded) state. I am using Drupal 7. Thank you.

# Answer
> 0 votes
This functionality is provided by FAQ Field using the jQuery Accordion UI.

In Structure \> Content Types \> Your Content type \> manage display (admin/structure/types/manage/\[your\_content\_type\]/display), if you change your FAQ field display settings from Definition List to Accordion, an up/down caret is shown next to each question.

If you click on the gear icon corresponding to your FAQ Field you can configure which question is active by default, as well as whether the questions are collapsible.

Result:

The Accordion setting also adds the class `ui-state-active` to the active question element (an h3) and the class `ui-accordion-content-active` to the active answer element (a div).

---
Tags: 7, navigation
---


# Question
Title: Prompt to translate a content after creating a new content
In my drupal site, I want to add a prompt informing editors that they must add a french version of an article (or any content type). I tried doing this using Rules but there is no way to check if a content type has been translated to French.. CAn anyone shed some light? Thanks!

# Answer
> 0 votes
So I ended up creating a custom module instead and checking if `$node->tnid == 0` then run `drupal_set_message('Add FR article.. blah blah');`

# Answer
> 1 votes
In the answer to "How to implement side-by-side translation?", I describe how to do side my side translation by adding an entity reference field and linking back to the original English article.

For your case, you could use rules to create a French node when an English node is created, save the entity reference and redirect to node/\*/translate where the French node would be displayed next to the English one.

If you want to take this approach, I can add more details. I think it would give a very nice workflow.

# Answer
> 0 votes
Even though I have seen people using Rules for translation but still I am not sure whether Rules has got this check(translation) as condition or not.

But even if it doesn't, you can create your own condition by hook\_rules\_condition\_info & then use existing Rules action to show message to any user type when he visit node.

I have done similar kind of thing using hook\_node\_view, where I checked available translation & if it's not available, I did set message using drupal\_set\_message.

Something like (not tested)-

```
// Replace your own module name to HOOK
function HOOK_node_view($node, $view_mode, $langcode) {
  // If content type is article & node is being viewed in full mode.
  if ($node->type == 'article' && $view_mode == 'full') {
    global $user;
    //If French translation isn't available & User is of type moderator.
    if (!isset($node->translations->data['fr']) && $user->type == 'moderator') {
      drupal_set_message(t('Please add French translation for the node'), 'status', FALSE);
    }
  }
}

```

---
Tags: rules, i18n-l10n
---


title: Admin approved file uploads

text:
# Question
Title: Admin approved file uploads
I want to allow all authenticated users to upload files, but I want them to be approved first before they're publically viewable. I'm currently using a single image field for the uploads, that can have unlimited values.

I'm not sure what is a good way of going about this. Let's say, the user uploads 4 images, which are all shortly after approved. Then, later, they upload one more image... I still want the first four to be publically viewable, but I don't want the fifth one to be until it's approved.

Also, I am kind of concerned about the fact that the files would be downloadable immediately, as soon as they are uploaded via sites/default/files. Is this a big deal? Concerned about copyright violations and such.

# Answer
I believe what you wanted is similar to commerce file module where users can upload file and have configurable settings, where you can limit access duration, number of downloads etc. and about this one `downloadable immediately, as soon as they uploaded via sites/default/files. Is this a big deal?` yes it is big deal once you uploaded it in `sites/default/files` everyone can access it and download anytime without restriction you may violate some regulation. you should upload it outside Drupal where users can't access it via url. Where in `commerce file` already have this settings where you could place your file folder outside Drupal. I am not sure if this is already available in Drupal 8.
> 0 votes

---
Tags: 8
---


title: How do I combine two blocks?

text:
# Question
Title: How do I combine two blocks?
I have a view of taxonomy categories. I'm also using the built in search block, and the Bootstrap theme.

Is it possible to combine those blocks into one block? I've tried creating a search view, but failed miserable.

# Answer
> 0 votes
You are looking into this on the wrong way. You need a module to do this. It cannot be done by putting block in search.

You need to use one of these modules.

---
Tags: 8, blocks
---


# Question
Title: db_select returns empty array, BUT the raw query returns records...?
I've written a query to get records that `start` column is later than a given time. Take the following:

```
$q = db_select('timetable_slot', 's')
    ->fields('s')
    ->where('str_to_date(s.start, \'%H:%i\') >= \'15:24\' ');

    print_r($q->__toString());
    /* SELECT s.* FROM timetable_slot s WHERE (str_to_date(s.start, '%H:%i') >= '15:24' ) */

$result = $q->execute()
    ->fetchAll();

print_r($result); /* [] */

```

`$result` comes back as an empty array. If I run the generated SQL manually I get the results I expect, any reason why drupal is returning an empty set?

I've also tried:

```
db_query("SELECT s.* FROM {timetable_slot} s WHERE (str_to_date(s.start, '%H:%i') > '15:24')")->fetchAll();

```

This also returns empty, even though the query works in a db client.

Thanks

# Answer
> 1 votes
It's impossible to troubleshoot such a query without access to your environment.

The Devel module has a query inspection tool (**Display query log** in the Devel settings). that can assist you in determining what query was sent to your database. Use that to determine the exact query sent to your DB and how it differs from the query you're sending to your SQL client.

---
Tags: 7
---


# Question
Title: Alter validation when using inline entity form
Is it possible to alter the validation function when using inline\_entity\_form ?

Here is an example module that I'm using where I use devel to validate if I can hook into drupals and IEF validate functions (as pointed out by Shawn Conn).

```
function mymodule_inline_entity_form_entity_form_alter(&$entity_form, &$form_state)
{
  $entity_form['#element_validate'] = array('mymodule_inline_entity_form_entity_form_validate');
}

function mymodule_inline_entity_form_entity_form_validate(&$entity_form, &$form_state)
{
  // No effect
  form_set_error('field_price', '!Validate');
  form_set_error('field_bucket_list', '!Validate');
}

```

I have one content type which has a title and a decimal field called field\_price and a second type which has the IEF field (called field\_bucket\_list).

# Answer
> 0 votes
Yes, IEF calls `drupal_alter()` after upon building a form. This enables any custom module to invoke `hook_inline_entity_form_entity_form_alter()` to alter it.

```
/**
 * Implements hook_inline_entity_form_entity_form_alter().
 */
function MYMODULE_inline_entity_form_entity_form_alter(&$entity_form, &$form_state) {
  // Replace validation callback.
  $entity_form['#element_validate'] = array(
    'MYMODULE_inline_entity_form_entity_form_validate'
  );
}

function MYMODULE_inline_entity_form_entity_form_validate(&$entity_form, &$form_state) {
  // @TODO: Add extra validation in front of IEF validation handler.
  inline_entity_form_entity_form_validate($entity_form, $form_state);
}

```

# Answer
> 1 votes
At last I got it to work. Here is the final code where the error was that I did not fully understand how to use form\_set\_error to point at the field I wanted to validate.

```
function mymodule_inline_entity_form_entity_form_alter(&$entity_form, &$form_state)
{
  $entity_form['#element_validate'] = array('mymodule_inline_entity_form_entity_form_validate');
}

function mymodule_inline_entity_form_entity_form_validate(&$entity_form, &$form_state)
{
  form_set_error('field_bucket_list][und][form][field_price', '!Validate');
  inline_entity_form_entity_form_validate($entity_form, $form_state);
}

```

The field I wanted to validate is field\_price and is located as values-\>field\_bucket\_list-\>und-\>form-\>field\_price in $form\_state, which I got from using Devel.

---
Tags: 7, entities
---


# Question
Title: Very slow cache processing: Is there any alternative?
I have some Drupal sites and the one common problem on them: very large cache with very slow processing and therefore the sites work very slow. I have enabled all caches and set them to long lifetime. But the sites are still slow. My server has 4GHz frequency and 4G RAM. DB queries log shows me that all queries takes 100-300ms summary.

When I perform profiling with xhprof I see that the largest part of wall time is used by serialize, unserialize and array\_map functions. So i suppose it is because of large amount of serialized data stored in cache. So the data can be get from DB quickly but is processed by CPU very slowly.

So what should I do with the issue? How can I reduce cached data amout or store not serialized data in cache?

# Answer
> 1 votes
If a large part of your time is spent with serialize then that might point to some broken code; as in things keep getting serialized to be stored in the cache/db but it keeps on having a cache miss, otherwise you should only see unserialize with heavy cache usage.

The pattern you're pointing to sounds like you have some code that is abusing the variables table. Inside variable\_initialize() it runs array\_map with serialize, and variable\_set() calls serialize. I would check the max\_allowed\_packet value inside of MySQL; my preference is to set it to 32M.

If you can provide more details, I can give you a better answer. I will say that using PHP7 should give you a big speedup if you haven't done so.

---
Tags: caching, performance
---


title: Address field "Same as above"

text:
# Question
Title: Address field "Same as above"
I have 2 address fields : **Res. addr** and **Permanant addr.** On clicking another field : **same as above**

I want to copy all the values entered in Res. addr to Permanant addr.

Please let me know how to do it?

Thanks, ronforever

# Answer
> 2 votes
There is no simple solution, and therefore I'm not sure this question is good for the Drupal Stack Exchange. It's going to be a matter of custom JavaScript or AJAX Form API code, and it will be dependent on how you're using Address Field and what sort of form you're integrating it into.

Based on the comments below, though, I'd add that there's nothing particularly challenging about this. If both sets of form elements are on the same page, it's a simple matter to use JavaScript (especially with jQuery) to copy the data from one form field to the next. There just isn't a simple property to toggle within the form API code itself.

# Answer
> 0 votes
I had the same problem and my solution was to use RULES. I have to address fields on my node, one is the registration address of a particular company a the other address field is the standard shipping address.

So in my case I have made the shipping address field not mandatory and if its empty a RULE i triggered which copies the address from the other field.

---
Tags: entities
---


title: Attach dynamic inline css to <head>

text:
# Question
Title: Attach dynamic inline css to <head>
Is it possible to add inline CSS to into the `<head>` section of a Drupal 8 page? My expected result should look like this:

```
<head>
<style>
.my-custom-class {
  background-color: red;
}
</style>
</head>

```

I've tried to add it to `hook_preprocess_HOOK()` but it will not show up.

```
function my_module_preprocess_html(&$variables) {
  $variables['html']['#attached']['css'][] = array(
    'type' => 'inline',
    'every_page' => TRUE,
    'data' => '.my-custom-class { background: ' . $dynamic_color . '; }',
  );
}

```

I've tried a few other things but it did not work either. Whats the right way to do this?

# Answer
> 8 votes
After doing some more research i've found an answer to my problem. The main reason for not finding a solution was, they don't want you to do this in Drupal 8.

From their documentation:

https://www.drupal.org/developing/api/8/assets#dynamic-css-js

> If the dynamic CSS/JS is built for each request, then you enter the truly advanced territory. This is hard, and for a good reason: per-request dynamic assets have to be built on every single request and therefore slow Drupal down. We want to make it hard to make Drupal slow down, so this is why we don't offer a nice API for this — since we don't want you to do it.

This makes sense and there is a short description how to get it to work anyway but its lacking of an example. This is what i've done to get it to work:

```
function my_module_page_attachments_alter(array &$page) {
  $background_color = '#000';
  $page['#attached']['html_head'][] = [
    [
      '#tag' => 'style',
      '#value' => '.my-custom-class { background: ' . $background_color . '; }',
    ],
    'my-custom-module'
  ];
}

```

---
Tags: theming, 8
---


title: Check if a user has a role

text:
# Question
Title: Check if a user has a role
How can I check if a user has a certain role?

# Answer
Checking for a permission is recommended over checking for a role. When you use permissions, you can assign that permission to multiple roles, which makes your system more flexible. Also, remember that roles can be renamed, which would break your code.

That said, if you want to check for a role, you can do this:

```
// The currently logged-in user is stored in a global variable.
global $user;

// Check if the user has the 'editor' role.
if (in_array('editor', $user->roles)) {
  // do fancy stuff
}

```
> 93 votes

# Answer
To check if the current user has a single role or any of multiple roles, a great way is to do:

```
//can be used in access callback too
function user_has_role($roles) {
    //checks if user has role/roles
    return !!count(array_intersect(is_array($roles)? $roles : array($roles), array_values($GLOBALS['user']->roles)));
};

if (user_has_role(array('moderator', 'administrator'))) {
  // $user is admin or moderator
} else if(user_has_role('tester')){
  // $user is tester
} else{
  // $user is not admin and not moderator
}

```
> 12 votes

# Answer
Update for Drupal version \>= 7.36

You can use function user\_has\_role from Drupal API https://api.drupal.org/api/drupal/modules%21user%21user.module/function/user\_has\_role/7.

Try this example:

```
<?php
function MYMODULE_foo() {
  $role = user_role_load_by_name('Author');
  if (user_has_role($role->rid)) {
    // Code if user has 'Author' role...
  }
  else {
    // Code if user doesn't have 'Author' role...
  }

  $user = user_load(123);

  if(user_has_role($role->rid, $user)) {
    // Code if user has 'Author' role...
  }
  else {
    // Code if user doesn't have 'Author' role...
  }
}
?>

```
> 10 votes

# Answer
Here's the actual code from the comment that is referred to in the accepted answer as the best practice

```
<?php
  function mymodule_perm() {
    return array('access something special');
  }

  function dosomethingspecial() {
    // For current user
    if (user_access('access something special')) {
      // Doing something special!
    }

    // For a specific user
    if (user_access('access something special', $theuser)) {
      // Doing something special!
    }
  }
?>

```
> 2 votes

# Answer
To be futureproof in case the role name changes it's best to check for the role id (rid) which can be found in the role table in the database.

If you want to check for a role with rid 16, do:

```
// Load the currently logged in user.
global $user;

// Check if the user has the 'editor' role, when 'editor' has role id 16
if (array_key_exists(16, $user->roles)) {
  // do fancy stuff
}

```
> 1 votes

# Answer
There's `user_has_role()` which accepts a role ID. So you could first get a role ID from a role name and then pass that to `user_has_role()`.

```
$role = user_role_load_by_name('My Role');
$role_id = $role ? $role->rid : NULL;
global $user;
if ($role_id && user_has_role($role_id, $user)) {
  // Yes, this user has this role.
}

```
> 1 votes

# Answer
The other answers didn't work; I am not sure why. I used the following code.

```
global $user;

// Check to see if $user has the administrator role.
if (in_array('administrator', array_values($user->roles))) {
  // Do something.
}

```

A helper function could look like this.

```
/**
 * Check to see if a user has been assigned a certain role.
 *
 * @param $role
 *   The name of the role you're trying to find.
 * @param $account
 *   The account to check; if not given, use the currently logged-in user.
 *
 * @return
 *   TRUE if the user object has the role.
 */
function _user_has_role($role, $account = NULL) {
  global $user;
  if (!isset($account)) {
    $account = $user;
  }

  return (is_array($account->roles) && in_array($role, array_values($account->roles));
}

```
> 1 votes

# Answer
to check if a user has a certain role:

```
function test_role(){
   global $user;
   if(isset($user->roles['my_role'])){
     return true;
   }
   else {
    return false;
 }
}

```
> 0 votes

---
Tags: 7, users
---


# Question
Title: Ubercart override default flat rate quote
Drupal 7. Using Ubercart 7.x-3.10. I created a shipping default flat rate quote of $7. I created a product and gave it a flat shipping rate of $3.00. When I check out, the shipping quote is $10 (default + product). I don't understand how I get the product flat rate quote to override the default flat rate quote. Could someone please point me in the right direction? Thanks!

# Answer
> 0 votes
What I discovered is that in order for the default shipping flat rate quote to be overridden by product flat rate quote:

In Configuration-\>shipping quotes: **Base price** must be set to 0.00 **Default product shipping rate** set to whatever the flat rate is. In my example, it was $7.00.

In product -\>shipping settings-\>flat shipping rates: **Flat rate quotes** should be set to the overriding amount. In my example, it was $3.00.

So, in the test product example, the flat quote shipping rate would be $3.00. If no rate is set in the product, then the rate will be the default shipping quote of $7.00.

A bit confusing at first, but logical, I guess.

---
Tags: ubercart
---


title: How to add cache contexts to a region

text:
# Question
Title: How to add cache contexts to a region
How can I add cache contexts to a region. I have been able to do this to my blocks but have noticed that parts of the region remain cached.

# Answer
> 2 votes
You can add a cache context to a region the same way as to any other page element:

```
function mytheme_preprocess_region(&$variables) {
  if ($variables['region'] == 'myregion') {
    $variables['#cache']['contexts'][] = 'user';
  }
}

```

But this is probably not what you want, because regions are not cached. Usually the blocks inside a region are cached and the complete page which contains the regions. The cache context of the region will only have an effect on higher level elements, not downwards.

---
Tags: 8, caching, theming
---


# Question
Title: How to sort view search results by giving custom relevance weights?
I am using Drupal 7.43 and core search module.

I use "Search: Search Terms" for filter criteria and "Search:Score" Sorting criteria in my view to sort my results according to relevance.

But, for example if I search for text "drupal view search" it prioritize some node containing word "drupal" 5 times over a node containing all the text I entered, "drupal view search".

I want to sort my results such that, prioritize nodes that have title as the text I entered,then nodes that have any of the words in title, then nodes that have that text in the body.

How can I customize and add more functionality to the content ranking part in this page /admin/config/search/settings?

# Answer
> 2 votes
Drupal core's search can't really do this. You'll need to use something like the Search API contrib module (https://www.drupal.org/project/search\_api).

Search API allows you to plug in different backends ("servers") for the search database. I have the most experience with Solr, rather than the "database" backend. Solr, for sure, lets you not only choose which fields get indexed, but also how much relevance each field is awarded when a search matches. That is, you can say to index the title of the node as a Fulltext, with a score (weight) of 5, but index the body as Fulltext with a weight of 4.

---
Tags: views, search, 7
---


# Question
Title: How do I get a form field value out of a config entity data blob?
I am trying to add a form field in a existing config entity form. The value of the field is stored in the data blob of the correct config entity but I am not able to get it out of it.

```
/**
* Implements hook_form_FORM_ID_alter().
*/
function my_module_form_field_config_edit_form_alter(&$form, FormStateInterface $form_state) {
 $someEntity = \Drupal::entityTypeManager()->getStorage('some entity');
 $form['my-field'] = [
  '#type' => 'number',
  '#title' => 'some title',
  '#weight' => 1,
  '#min' => '0',
  '#max' => '50',
  '#default-value' => $someEntity->getValue('my-field'), // Here I would like to get the Value that is stored in the db
 ];
 $form['#validate'][] = 'my_module_field_config_edit_form_validate';
}

```

@Berdir

I tried your answer but the value still won't be set as default\_value

```
    /**
     * Implements hook_form_FORM_ID_alter().
     */
function comment_limit_form_field_config_edit_form_alter(&$form, FormStateInterface $form_state) {
  $comment = $form_state->getFormObject()->getEntity();
  $form['edit-limit-per-user'] = [
    '#type' => 'number',
    '#title' => 'Comment limit per user',
    '#weight' => 1,
    '#min' => '0',
    '#max' => '50',
    '#default_value' => $comment->getThirdPartySetting('comment_limit', 'edit-limit-per-user', FALSE),
  ];
  $form['#validate'][] = 'comment_limit_field_config_edit_form_validate';
  $form['#entity_builders'][] = 'comment_limit_form_field_edit_form_add_form_builder';
}

/**
 *
 */
function comment_limit_form_field_edit_form_add_form_builder($entity_type, FieldConfig $comment , &$form, FormStateInterface $form_state) {
  $comment->setThirdPartySetting('comment_limit', 'edit-limit-per-user', $form_state->getValue('edit-limit-per-user'));
}

comment.type.comment.third_party.comment_limit:
  type: mapping
  label: 'Comment limit per user'
  mapping:
    edit_limit_per_user:
      type: number
      label: 'Comment limit per user'

```

Did I miss something?

This works for me:)

# Answer
The entity is already available with `$form_state->getFormObject()->getEntity()`. That basically answers your question.

Note that stuffing arbitrary keys into a config entity is not supported, you should use the third party settings API instead. See http://larowlan.github.io/meet-third-party-settings-interface/#/12 for a simple example (but make sure you also check the slides before about config schema). The initial part is not necessary anymore as all config entities support third party settings out of the box now.
> 1 votes

---
Tags: 8, forms
---


# Question
Title: Cloning the Base theme bartik, seven, and stark in Drupal 8
I tried copying the seven theme from /core/theme into my own /theme folder. I renamed all the files that starts with seven to sevenx and also renamed the seven\_ functions to sevenx\_ and it still not showing up on the theme pages.

* What else do I need to change to make drupal 8 see this new cloned theme?
* Is there a quick tool to get this done without having me to rename everything?

# Answer
> 1 votes
A few things that could have been missed -

Cache clear, Changing the name of the theme in .info.yml of the new theme, Not putting the base theme in the .info.yml.

If none of those work, this is a pretty good guide. https://www.drupal.org/theme-guide/8/creating-a-sub-theme

---
Tags: theming, 8
---


# Question
Title: Trying to programmatically alter the id of an exposed filter in views
This is for Drupal 7.

I am trying to modify an exposed filter's id in views. Basically we've noticed a use-case with multiple simple hierarchical selects on a given page, in separate exposed filter forms will conflict because they're using the same id attribute in the HTML.

The solution we've come up to to solve this is to append a short hash to the end of this id, making it unique across the page.

The problem is that I'm having trouble figuring out exactly where to do this, and the views objects' immense size doesn't help me in tracking down exactly where I have to make this change.

I'm trying things like this (this is in hook\_views\_pre\_view):

```
$view->display['DISPLAY_NAME']->handler->options['filters']['field_FIELD_NAME_HASH-HERE'] = $view->display['DISPLAY_NAME']->handler->options['filters']['FIELD_NAME'];

$view->display['DISPLAY_NAME']->handler->options['filters']['field_FIELD_NAME_HASH-HERE']['expose']['identifier'] = 'field_FIELD_NAME_HASH-HERE';

$view->display['DISPLAY_NAME']->handler->options['filters']['field_FIELD_NAME']['expose']['operator_id'] = 'field_FIELD_NAME_HASH-HERE_op';

```

However this only seems to throw an error.

So how do I change the id on a given exposed filter for a view/display?

EDIT - this is the markup I am trying to affect:

```
<div class="form-item form-type-select form-item-field-FIELD_NAME shs-wrapper-processed">
 <select class="element-invisible shs-enabled form-select shs-processed" id="edit-field-FIELD_NAME" name="field_FIELD_NAME" style="display: none;"><option value="All" selected="selected"><option></option></select>
<select id="edit-field-FIELD_NAME-select-1" class="shs-select form-select shs-select-level-1 chosen-disable" style="display: inline-block;"><option></option></select></div>

```

Everywhere that has FIELD\_NAME either has the default field name, or if I change it in Views, the changed identifier, however I can't seem to change any of these names programmatically - even with the answer below, which is what I really need to do.

How do I affect this markup?

Here is my current hook\_preprocess\_views\_exposed\_form:

```
if($vars['form']['#id'] == 'views-exposed-form-reference-views-block-1') {
    $number = <NUMBERHERE>;
    $vars['form']['#info']['filter-field_FIELD_NAME']['value'] = 'field_FIELD_NAME_' . $number;
    $vars['form']['field_FIELD_NAME_' . $number] = $vars['form']['field_FIELD_NAME'];
    $vars['form']['field_FIELD_NAME_' . $number]['#id'] = 'edit-FIELD-NAME-' . $number;
    $vars['form']['field_FIELD_NAME_' . $number]['#parents'] = array('field_FIELD_NAME_' . $number);
    $vars['form']['field_FIELD_NAME_' . $number]['#array_parents'] = array('field_FIELD_NAME_' . $number);
    $vars['form']['field_FIELD_NAME_' . $number]['#name'] = 'field_FIELD_NAME_' . $number;
    $vars['widgets']['filter-field_FIELD_NAME']->id = 'edit_field_FIELD-NAME-' . $number;
    unset($vars['form']['field_FIELD_NAME']);
  }

```

# Answer
> 0 votes
I think you might be using the wrong tool for the job. It sounds like this is a theming problem, not a views data structure problem (which would use something like `hook_views_pre_view()`.

You can override the template **views-exposed-form.tpl.php** to override the markup of the exposed form & the preprocess function `template_preprocess_views_exposed_form()` to override the markup form widgets:

```
function MYTHEME_preprocess_views_exposed_form(&$vars, $hook) {
  // @TODO: alter markup of $vars['widgets']['filter-MYFILTER']->widget.
}

```

Alternatively, the views UI provides a means to change the id element by changing the **Filter identifier** underneath the **More** fieldset which also changes the URL query parameter used as well.

---
Tags: 7, views
---


# Question
Title: Allow FAPI checkboxes to specify some options as disabled
I want to disable a single checkbox in a `checkboxes` FAPI element.

```
<?php

namespace Drupal\fapi_example\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;

class SimpleForm extends FormBase {

  /**
   * Build the simple form.
   */
  public function buildForm(array $form, FormStateInterface $form_state) {

    $form['checboxes'] = [
      '#type' => 'checkboxes',
      '#options' => [
        'A' => $this->t('A'),
        'B' => $this->t('B'),
        //I want C allway check and disable.
        'C' => $this->t('C'),
        'D' => $this->t('D'),
      ],
      '#default_value' => array('C'),
      //Follow topic https://www.drupal.org/node/284917. But don't work
      //'#disabled_values' => array('C'),
      '#title' => $this->t('Title Checkboxes'),
    ];

    return $form;
  }

  /**
   * Getter method for Form ID.
   */
  public function getFormId() {
    return 'form_checkboxes';
  }

  /**
   * Implements a form submit handler.
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {

  }

}

```

I try to follow this topic but its not working (8.1.x), and tried to search in google but it just solve in Drupal 7. So How can I disable a single checkbox in a 'checkboxes' FAPI element?

# Answer
> 1 votes
I find a way. Add option process in define form type.

```
<?php

namespace Drupal\fapi_example\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;

class SimpleForm extends FormBase {

  /**
   * Build the simple form.
   */
  public function buildForm(array $form, FormStateInterface $form_state) {

    $form['checboxes'] = [
      '#type' => 'checkboxes',
      '#options' => [
        'A' => $this->t('A'),
        'B' => $this->t('B'),
        //I want C allways check and disable.
        'C' => $this->t('C'),
        'D' => $this->t('D'),
      ],
      //Add options process
      '#process' => [
        array($this, 'processCheckboxes'),
      ],
      '#default_value' => array('C'),
      //Follow topic https://www.drupal.org/node/284917. But don't work
      //'#disabled_values' => array('C'),
      '#title' => $this->t('Title Checkboxes'),
    ];

    return $form;
  }

  /**
   * Process checkboxes
   */
  public static function processCheckboxes(&$element, FormStateInterface $form_state, &$complete_form) {
    $value = is_array($element['#value']) ? $element['#value'] : array();
    $element['#tree'] = TRUE;
    if (count($element['#options']) > 0) {
      if (!isset($element['#default_value']) || $element['#default_value'] == 0) {
        $element['#default_value'] = array();
      }
      $weight = 0;
      foreach ($element['#options'] as $key => $choice) {
        if ($key === 0) {
          $key = '0';
        }
        $weight += 0.001;

        $element += array($key => array());
        $element[$key] += array(
          '#type' => 'checkbox',
          '#title' => $choice,
          '#return_value' => $key,
          '#default_value' => isset($value[$key]) ? $key : NULL,
          '#attributes' => $element['#attributes'],
          '#ajax' => isset($element['#ajax']) ? $element['#ajax'] : NULL,
          '#error_no_message' => TRUE,
          '#weight' => $weight,
        );

        if ($key == 'C') {
          $element[$key]['#disabled'] = TRUE;
          $element[$key]['#default_value'] = $key;
        }
      }
    }
    return $element;
  }

  /**
   * Getter method for Form ID.
   */
  public function getFormId() {
    return 'form_checkboxes';
  }

  /**
   * Implements a form submit handler.
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {

  }

}

```

It's working but i think FAPI allow options disable some value is better.

---
Tags: forms, 8
---


# Question
Title: View calc and multiple field collection lines
I came here because I have a problem with view calc module and several lines in my field collection. So first the result of my view look like this :

All this fields are in the same content type, and I put `sum calculation` on each fields. But it's seems the value of the field is multiplied by the count of lines in my field collections. So for the first sum(Montant HT) the calcul done is :

8600 + 51600 + (3101.26 * 5) + 2962.99 + (42000 * 3)

For the column `paid sum` I don't know how the sum is calculated I doesn't understand.

I tried to use distinct but it didn't work, so how can I found the right sum for all my column ??

Thanks

# Answer
Finally, I found a way to make it work. Although, maybe it's not a good solution but it worked. Here is steps:

1. Find file views\_calc\_table.inc in views\_calc module directory.
2. Change `if ($query_alias == 'unknown') {` to `if ($query_alias ==
'unknown' || $field->field_info['type'] == 'field_collection') {` in line 238 under `function add_aggregation_fields(&$view)`

**Remind，never hack core!**
> -1 votes

---
Tags: views, entities
---


# Question
Title: How to pass a variable about sufficient User Points to a Rules condition in another rule?
I used this link to set up a UserPoints Store: Drupal 7 - How to Set up a Simple UserPoints Store.

For some reason when I buy (flag) a node (store item) and for quantity I put more UserPoints, than the transaction is not blocked, which results in a negative user points balance.

**Problem:**

1. Either this issue is addressed and I set some wrong settings(I double checked everything so I don't think so)
2. I need to make my own custom setting for the UserPoints not to enter negatives.

**Is there a way I can set and pass a variable (`enough_points=true`) from (1st) rule "Check User Points" and then use it as a condition in (2nd) rule "Flag item"?**

# Answer
There is no Rules Condition related to the current total user points for a user. Except by using custom PHP code as in this example (which you could use in a Rules Conditionn *Execute custom PHP code* condition, e.g. to do some type of comparison):

```
global $user;
$current_points = userpoints_get_current_points($user->uid, 'all');
if ($current_points < 0) {return TRUE;}

```

However, there is a Rules Action "***Load user points of a user***", whereas you can ask for either a specific category, or for all categories together. This Rules Action provides a Rules variable (for which you can specify its name and description) which contains the amount of user points for the requested category. You can then use this variable in subsequent Rules Actions.

If you then want to use that variable within a Rules Condition, you have 2 ways of doing so:

* Include the condition in a Rules Component, whereas you trigger the execution of that Rules Component via a Rules Action following the "Load user points of a user" (and passing the variable containing the amount of user points as a variable for the Rules Component).
* Use the Conditional Rules module, so that you can specify Rules Conditions within Rules Actions.

Here is a basic example that displays a message about the current total user points for a user, after the user performed an update of some node (= the Rules Event, which you can change to any Rules event that you want):

```
{ "rules_display_userpoints_after_updating_content" : {
    "LABEL" : "Display userpoints after updating content",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "userpoints_rules", "rules" ],
    "ON" : { "node_update" : [] },
    "DO" : [
      { "userpoints_rules_get_current_points" : {
          "USING" : { "user" : [ "site:current-user" ], "tid" : "all" },
          "PROVIDE" : { "loaded_points" : { "total_points" : "Number of points in all categories together" } }
        }
      },
      { "drupal_message" : { "message" : "You now have [total-points:value] points" } }
    ]
  }
}

```

Use the Rules UI to import the above rule in your own site if you want.
> 2 votes

---
Tags: 7, rules, userpoints
---


# Question
Title: Programatically change the base theme of the current theme
I have a theme that is a child theme of 'stable'.

Currently the base theme is defined in the info.yml file, however i don't want its parent theme to be so permanent.

I am looking for a way to be able to programatically change the base theme in code so that the theme could switch its parent on demand.

# Answer
So as it turns out an info.yml file can be altered inside HOOK\_system\_info\_alter

To change the base theme definition of an existing theme you can use the following

```
function HOOK_system_info_alter(&$info, $file, $type) {
  if ($type == 'theme') {
    if ($info['name'] == 'YOUR THEME NAME') {
      $info['base theme'] = 'NEW_BASE_THEME_NAME';
    }
  }
}

```

As this hook is only fired when caches are flushed there is no need for a separate cache flush after the change is made.
> 0 votes

---
Tags: 8
---


# Question
Title: Saving 1 vocabulary deletes all terms of all vocabualries in the site | Data mining
Since I migrated D7 to D8 I **suffer** from the following problem and need help regarding mining the data that could be useful to make a fine report to the Drupal community.

## The story:

When you visit nodes created before migration, you can see their taxonomy terms.

If I save a node with taxonomy data that was created before migration - All its taxonomy data is vanished if its from selection box or radio buttons (if its from autocomplete, the node saves just fine, as weird as it sounds)... It happens in all nodes, and in all content types, (even new ones I create after migration whether from migrated or new content types).

A **milestone** in my efforts to understand why it happens is this:

When I save any taxonomy vocabulary like in the following image, all of its terms, including the terms of all other vocabularies are just suddenly deleted... Insane as it sounds --- Right after I hit "Save", all of the terms in all vocabularies in the site, just vanish.

But this deletion is only in the UI level; that is, If I go to the table containing taxonomy terms, that is *taxonomy\_term\_field\_data* I can see all 30 terms that appear in all nodes.

I have consulted a Drupal programmer on this and he told me this is most certainly a migration bug, given it happens on an all-core site and there are no errors in `drush ws --full`.

## Note:

I **don't** ask anyone to debug this for me; Since I learn basic programming and haven't yet learned to debug, all I am asking is what PDO data should I monitor and present in my report to the Drupal community.

I would thank you dearly for giving me any direction because I suffer from this problem very much.

# Answer
You should look into the database if the taxonomy terms are deleted indeed or just have changed the tid, the language or anything else.

The most probable is the terms are not deleted but when you try to load them by some parameters the parameters has changed and the result is no terms.
> 0 votes

---
Tags: 8, database, debugging
---


# Question
Title: May I use width and height CSS properties on images?
CSS architecture (for Drupal 8) says:

> Never apply widths or heights except to elements that natively have these properties (e.g. images).

I use CSS properties like `width:100%` often with images. It seems much easier to get to than the markup most of the time. Does this guideline mean I should not being doing this? If so, is the only solution overriding a template file to get at the HTML element properties?

# Answer
> 5 votes
What I understand is, it is suggesting opposite to what you are interpreting.

Lets take a look again.

> *Never apply widths or heights except to elements that natively have these properties (e.g. images).*

So, it is saying that, you can apply the height and width to image freely as the `Height` and `Width` are the default property of images. This you can understand as all images has some width and some height. So they are intrinsic property of image.

Now, lets take **other proof**, why you can apply Height and Width to image. If you see the Drupal's core feature, **Image Style** at `Admin/Config/Media/Image style`, there you can specifiy as many image style as you want with different `Width` and `Height`.

>

Hence this feature allowing the facility to change the dimensions of same image with different Image styles - AND how this is happening, simply by changing the height and width, So this is the core feature.

Hence, `image` comes in the category of ***except*** in your highlighter following statement.

> *Never apply widths or heights except to elements that natively have these properties (e.g. images).*

**So, you can freely use width and height to Images.**

# Answer
> 5 votes
Do note that those guidelines apply to

> Drupal core and contributed **modules**

(emphasis mine).

They don't apply to themes.

The point of the document is to make sure that CSS implemented by **module** developers isn't awkward for themes to override.

The decisions you make in your own theme are your call. So if you want to apply widths to images, apply away.

Incidentally, the CSS formatting guidelines *are* intended for themers, so they're worth a read. Even those examples use `width`s in selectors that are unlikely to refer to images, so you can safely assume the other guidelines don't apply here.

Heck, if they did, we wouldn't be able to create responsive themes.

# Answer
> 0 votes
You must use width and height proterties.

The main reason is than after load the html, your browser will render the page but the images are not there.

If you use size properties, the page will use the right layout because the browser knows how big are the images before they are loaded. If you don't use size properties, your page will look like a mess until images are loaded.

---
Tags: theming, 8
---


# Question
Title: How can I get a list of the patches I submitted for issues on drupal.org?
How can I get a list of the patches I submitted for issues on drupal.org?

I can see the list of my posts, but I need only those with a patch.

# Answer
> 0 votes
If you contributed patches, they will be credited to you. In that case, on your profile, you will see the ones credited to you in the past 3 months. In my case, I see the following.

>

Keep in mind that sometimes you participate in an issue without contributing patches, and you get credited for participating.

Unfortunately, there isn't a page with all the credited issues for all the projects, but if you have a list of the projects to which you contributed patches, you can get the list of the credited issues for that project by looking at `https://www.drupal.org/u/<username>/issue-credits/<project-id>`, where `<username>` is the username on drupal.org (in my case, kiamlaluno) and `<project-id>` is the ID for the project (for example, 3060 for Drupal core). So, if I would want to look to all the patched I submitted for Drupal core, I would look at https://www.drupal.org/u/kiamlaluno/issue-credits/3060.

It seems that the list of credited patches has been created on 2015, so you would not get any credited patch before that year.

---
Tags: community-official-site
---


# Question
Title: Advanced forum: How to modify template of forum list page?
Here's the normal template for Advanced Forum:

I'd like to modify the template of advanced forum so that I can

1. Remove the elements in red
2. Rearrange the elements in blue
3. Edit the elements in green
4. Display the topic starter's profile2 picture

so that I can achieve the result below:

So far, I've tried editing advanced-forum.naked.topic-list.tpl.php but it doesn't change anything. I've managed to remove some of the content with Panels but I cannot modify what's left over here.

# Answer
> 1 votes
I achieved what I wanted (rearrange, add and remove fields, and set the display format for the time format) just by using views here : admin/structure/views/view/advanced\_forum\_topic\_list

# Answer
> 1 votes
When I had to do this I found there are lots of template files and it's not obvious what controls what. I ended up putting die() in each one to find out which template file was used for each view, and then a case of trial and error to make the changes I wanted.

When you have worked out which files need editing then you should copy them from:

```
/sites/all/modules/advanced_forum/styles/naked/advanced-forum.naked.TEMPLATE_NAME.tpl.php

```

to your theme at:

```
/sites/all/themes/YOUR_THEME/templates/advanced-forum.naked.TEMPLATE_NAME.tpl.php

```

Any files here will override the ones in the advanced forum themes folder.

# Answer
> 1 votes
Just to update the answer from @Felix Eve - if doing it in your own theme in Drupal 7 (which is recommended) then save the "naked" file here, ie with a hyphen and no "naked":

```
/sites/all/themes/YOUR_THEME/templates/advanced-forum-TEMPLATE_NAME.tpl.php

```

---
Tags: nodes
---


title: how to use drupal theme

text:
# Question
Title: how to use drupal theme
I try to use theme()

```
function test_theme() {
  return array(
    'my_custom_gallery' => array(
      'variables' => array(
        'image_urls' => null,
      ),
      'template' => 'my-custom-gallery',
      'path' => drupal_get_path('module', 'test') . '/templates',
    ),
  );
}

function test_form($form, &$form_state) {
  $array = array('images' => array('test0' => 'test0', 'test1' => 'test1'));
  $output = theme('my_custom_gallery', $array);
  return $output;
}

```

And my-custom-gallery.tpl.php

```
<div style="background-color:red; width:300px;heoght:300px;">
<?php
  print_r($images);
?>
</div>

```

But I not see the html from template

# Answer
> 1 votes
In your `test_theme()` function you set `image_urls` as the variable to the template. So print `$image_url` instead of `$images` in your template.

Try

```
<div style="background-color:red; width:300px;heoght:300px;">
<?php
  print_r($image_urls);
?>
</div>

```

in my-custom-gallery.tpl.php

# Answer
> 1 votes
You need to clear caches, so hook\_theme() gets recognized.

---
Tags: 7
---


# Question
Title: Behavior being fired on backend causes AJAX error
I am using jQuery Update to bump up the jQuery version on the front end, and keep the default 1.4 on the backend.

On a custom filter form on the home page, i use jQuery on, and wrap it in a behavior so it still works after an ajax event on that page.

The problem is that for some reason, when editing the page, and adding a new field collection row when Ajax is fired, the jQuery is being called, and an error happens because jQuery on did not exist in 1.4.

> VM787:31 Uncaught TypeError: $(...).on is not a function

Steps to fix...

1. I am using drupal\_add\_js but I check that if `(!path_is_admin(current_path())) {//jQuery}` to make sure it isnt called on the admin pages
2. I am certain the JS is not on the admin pages, but after ajax, it is called because its in a behavior.

Is there a way to say which behaviors should run on the admin side, and which shouldnt?

# Answer
> 0 votes
Funny how sometimes you write out the question, and it makes you think about it in a different way!

The issue is that the behavior is obviously saved somewhere and called on an ajax event, EVEN if the js is not being called on that page! This was funny behavior to me, but the quick fix (maybe not the right fix) was to check the current path, and not run the JS inside that behavior if the path had "edit" in it.

```
Drupal.behaviors.myBehavior = {
  attach: function (context, settings) {
    (function($) {

        jQuery(document).ready(function() {

        var pathname = window.location.pathname;
            // If the page does NOT contain edit
            if (! (pathname.indexOf('edit') > -1) ) {

               // All of the JS stuff....

            }
        });

    }(jQuery));
  }
};

```

I will leave this question open for a few days as I would be interested to see if there's a better way of doing this. Ideally some way to control which behaviors are called on which pages?

---
Tags: 7, javascript, ajax
---


# Question
Title: How to show fontawesome icons in admin page inside Ckeditor?
I managed to insert fontawesome iconS using Ckeditor with the Font Awesome Icons v1 module.

I just put this code in the HTML view of Ckeditor.

```
<i class="fa fa-camera-retro fa-lg"> </i>

```

The icon is shown correctly in frontend but in CKEditor it is not shown at all.

I guess I need to load all fontawesome files inside Ckeditor. How can I do this? I need to see the icon in ckeditor in the same way as I see it in frontend.

Fontawesome is located at: **sites/all/libraries/fontawesome**

# Answer
A CKEditor plugin for fontawesome exists. If you're using the WYSIWYG module there are a number of hooks that allows you to modify your WYSIWYG editor. In fact, someone has done a write up on how to manually add CKEditor plugins using Drupal.
> 4 votes

# Answer
I use the add-on CKEditor Font Awesome by DOKSoft. This plugin will attach Font Awesome CSS automatically. See demo.
> 2 votes

# Answer
You can have the Font-Awesome icons in the Drupal wysiwyg area as well. Add the following line in the wysiwyg advanced options \> Custom JavaScript config. (admin/config/content/ckeditor/edit/xxx):

```
config.contentsCss = ['//cdn.jsdelivr.net/fontawesome/4.5.0/css/font-awesome.min.css','//cdn.jsdelivr.net/bootswatch/3.3.6/readable/bootstrap.css'];

```

ps: you may like to add this second line to allow empty tag (then you can avoid the useless` ` in the tag)

```
CKEDITOR.dtd.$removeEmpty.i = 0;

```

At the end you should have something similar to:

```
config.allowedContent = true;
CKEDITOR.dtd.$removeEmpty['i'] = false
CKEDITOR.dtd.$removeEmpty.i = 0;
CKEDITOR.dtd.$removeEmpty['span'] = false;
config.contentsCss = ['//cdn.jsdelivr.net/fontawesome/4.5.0/css/font-awesome.min.css','//cdn.jsdelivr.net/bootswatch/3.3.6/readable/bootstrap.css'];

```
> 1 votes

---
Tags: wysiwyg
---


title: Search for page title

text:
# Question
Title: Search for page title
I want to search for page name.

I have a title of page news and events. if i search event. i want news and event page will come on search results. when i click on that news-events page will open.

Any idea how to do this?

# Answer
Take a look at this one: https://www.drupal.org/project/search\_by\_page

Hope this is what you require.
> 0 votes

---
Tags: 7, views, search
---


title: #states hide by radio won't work

text:
# Question
Title: #states hide by radio won't work
The problem is all in the title. So here is my code (i cut some part to make it more visible) :

Constructor :

```
public function __construct() {
  $user = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id());
  $this->sub_forms['user'] = \Drupal::service('entity.form_builder')->getForm($user);
}

```

buildForm :

```
public function buildForm(array $form, FormStateInterface $form_state) {
  $sub_forms_keys = array_keys($this->sub_forms);
  // INC ALL SUBFORM INTO THE MAIN FORM
  foreach ($this->sub_forms as $key => $sub_form) {
    // REMOVE THE PROCESS CALLBACK
    if (!empty($sub_form['#process'])) {
      unset($sub_form['#process']);
    }

    // ALTER THE SUBFORM
    if ($key == $sub_forms_keys[0]) {
      // user Alter
      foreach ($sub_form as $field_key => $sub_form_field) {
        // Pour tous les champs
        if (substr($field_key, 0, 10) != 'field_user') {
          // Si ce n'est pas un champ personnalisé friterie
          unset($sub_form[$field_key]); // Cacher le champ
        }
        else if (array_key_exists('widget', $sub_form[$field_key]))
          // Si c'est un champ friterie et qu'il dispose d'un widget
          $sub_form_field_widget = $sub_form[$field_key]['widget'][0];
          $sub_form_field_widget['#states'] = array(
            'visible' => array(
              ':input[#edit-proprietaire-0]' => array('checked' => true),
            )
          );
          dsm($sub_form_field_widget);
        }
      }
    }

    // ADD THE SUBFORM INTO THE MAIN FORM
    $form[$key] = [
      '#type' => 'container',
      'form' => $sub_form
    ];
  }
  return $form;
}

```

Here is a pastern link of a dsm() of a field to show you the structure and that the #states is include : http://pastebin.com/1a8AqVzm

Then here is the HTML code of the entity i want to focus (it's a radio button) :

```
<input class="clear-panel-field panel-field-inline container-inline form-radio" data-drupal-selector="edit-proprietaire-0" type="radio" id="edit-proprietaire-0" name="proprietaire" value="0">

```

# Answer
> 1 votes
```
'#states' => array(
  'visible' => array(
    ':input[name="your checkbox"]' => array('checked' => TRUE),
  ),
)

```

add this to the element you want to hide.this will be visible only when the checkbox is checked.

# Answer
> 0 votes
```
'#states' => array(
  'visible' => array(
    ':input[name="check box name"]' => array('value' => 'value'),
  ),
),

```

This will hide dependency field based on input checked, even if it true.

---
Tags: 8, javascript
---


# Question
Title: Selected Checkboxes (taxonomy) populate a new select list with values of selected boxes
---

*** question answered: Help needed with hook\_node\_submit in custom module to save data ***

---

In Drupal 7, I have a custom content type. In this, there is a multi select term reference to select categories for that content.

I now need to be able to select one from the previously selected category and mark it somehow as the 'main' category.

Lets say I have a multiple select term reference field with the following options:

```
Apples
Bananas
Pears
Oranges
Grapes
Pineapples

```

The user selects Apples, Pears and Grapes. Now I either need to:

1. Programmatically create another field for each of these selected—maybe with an ajax callback—and have radio buttons so I can only select one of the selected terms which one is my main category.
2. Create a radio field next to the ticked items—maybe also with ajax—where I can select the main one out of the selected.

Does anyone have any ideas regarding this?

To be clearer, I have a lot of these lists on one content type. Repeating each list as a single value list is not an option.

I guess my best bet is to use the `hook_form_alter()` with some sort of AJAX callback to create either a single radio button next to the tick box the user has just ticked, or programmically create a new radio field list for each item checked in the specified list.

**Update:** Ok, I have decided that the best way to do it would be to create a custom module that uses ajax to create a radio button for each checked checkbox, allowing to select the element that should be used as the main element.

So I have used `hook_form_alter()` to add an `#after_build` function as we need to wait for the form to be rendered before we can access the tax term values.

Here is my module so far. I use a lot of comments so it should be clear what I am trying to do:

### MYMODULE.module

```
/**
 * Implementation of HOOK_form_alter()
 * Do the ajax form alteration
 */
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {

  // 1.CONTENT FORM
  // I created a custom content type 'content' and added a term
  // reference to it
  if($form_id == 'content_node_form') {

    // tax term ref is the main part, so let us
    // remove title and body fields
    unset($form['body']);
    unset($form['title']);

    // do our stuff after the form has been rendered ...
    $form['#after_build'][] = 'MYMODULE_after_build';

  }
}

/**
 * after_build function for content_node_form
 */
function MYMODULE_after_build(&$form, &$form_state) {

    dsm($form);

    // In the after_build call we can now actually use the
    // element_children function to grab the values of the fields that
    // don't start with a hash tag #
    // in this test case 1,2,3,4 and 5

    // wrap each of the elements rendered ...
    foreach(element_children($form['field_taxonomy']['und']) as $key) {

      $form['field_taxonomy']['und'][$key] += array(

        // this is added before the element and then replaced by our callback ..
        // we use the $key value in the id so that we know which div to replace
        // depending on which checkbox is checked ...
        '#prefix' => '<div class="taxonomy_term_wrapper">
                        <div id="callback_replace_'.$key.'">Replace Me ' . $key . '</div>',

        // this is added after the element so we basically wrap around it ..
        '#suffix' => '</div>',

        // add some ajax stuff here ...
        '#ajax' => array(
          // name of the callback function to call upon change
          'callback' => 'MYMODULE_callback',
          // the id of the element that will be replaced
          'wrapper' => 'callback_replace_'.$key,
          // replace the wrapper
          'method' => 'replace',
          // what kind of effect do we want ...
          'effect' => 'fade',
          // show progress on callback
          'progress' => array('type' => 'throbber'),
        ),
      );

      if (!empty($form_state['values']['field_taxonomy']['und'][$key])) {
        // the form to show upon change ...
        $form['field_taxonomy']['und']['main_cat'] = array(
          // we want a radio button
          '#type' => 'radio',
          '#title' => t('Test Title'),
          '#description' => t('Test Description ...'),
          '#default_value' => empty($form_state['values']['field_taxonomy']['und'][$key]) ?
                              $form_state['values']['field_taxonomy']['und'][$key] :
                              $form_state['values']['field_taxonomy']['und'][$key],
        );
      }

    }

  return $form;
}

function MYMODULE_callback($form, $form_state) {
 return $form['field_taxonomy']['und']['main_cat'];
}

```

This is what it currently looks like prior to checking a box:

The HTML of the rendered form is the following one:

# Answer
> 1 votes
create the items as check boxes. after they are selected, show a drop down list with these items or another radio button to select the primary category. you can hide the second drop down using the following code until the first check boxes are selected.

```
'#states' => array(
'visible' => array(
':input[name="your checkbox"]' => array('checked' => TRUE),
 ),
)

```

add this to the element you want to hide.this will be visible only when the checkbox is checked.

# Answer
> 0 votes
How about two lists, one titled primary that takes one selection, the other multiple. You will still need to address the second list or selection to eliminate duplications.

---
Tags: 7, taxonomy-terms, entities, ajax
---


# Question
Title: How to have nodes online but not as a separate node number?
I have several content types let say : fooCT1,fooCT2, fooCT3 ... fooCT20. fooCT1 has several entities to the other content types.

If I publish fooCT1 I run a rule which also publish all relevant nodes (fooCT2.. fooCt20) in order to see this information in a panel page for a anonymous user.

But using this means also that the different nodes are available under there separate names url aliases like:

/node/xx

where xx is the node nummer

How to disable this easily?

# Answer
> 2 votes
You can't disable the node entity's canonical path easily, but you can serve a 403/4 for requests to the pages instead.

The simplest method for that is probably the Rabbit Hole module

> Rabbit Hole is a module that adds the ability to control what should happen when an entity is being viewed at its own page.
>
> Perhaps you have a content type that never should be displayed on its own page, like an image content type that's displayed in a carousel. Rabbit Hole can prevent this node from being accessible on its own page, through node/xxx.

---
Tags: nodes
---