title: Alter title link in taxonomy view mode

text:
# Question
Title: Alter title link in taxonomy view mode
Under /admin/structure/taxonomy/my\_vocabulary/display/entity I've got a view mode "entity". For this view mode, I would like to alter the way the link in the title field is built (the title is replaced by a real field instance due to title module): the link should be rebuilt into an anchor link like this: `<a href="#term-ID>Title</a>`, where term-ID is replaced with the actul term ID of the term. How can I achieve this by a custom module or by a template function? Are render arrays good for this? Here's a screenhot of the admin page.

# Answer
> 0 votes
I finally altered the title link by using a preprocess hook and a custom field template file (and a custom view mode for my entity, done with `hook_entity_info_alter()`):

```
  function hook_preprocess_taxonomy_term(&$variables) {
  $variables['view_mode'] = $variables['elements']['#view_mode'];
  $variables['term'] = $variables['elements']['#term'];
  $term = $variables['term'];
  $uri = entity_uri('taxonomy_term', $term);
  // Edits are here:
  $variables['term_url'] = url($uri['path'], $uri['options']);
  $variables['term_name'] = check_plain($term->name);
  $variables['page'] = $variables['view_mode'] == 'full' && taxonomy_term_is_page($term);
  $variables['term_id'] = drupal_html_id($term->name);
  // Flatten the term object's member fields.
  $variables = array_merge((array) $term, $variables);
  // Helpful $content variable for templates.
  $variables['content'] = array();
  foreach (element_children($variables['elements']) as $key) {
    $variables['content'][$key] = $variables['elements'][$key];
  }
  field_attach_preprocess('taxonomy_term', $term, $variables['content'], $variables);

  // Gather classes, and clean up name so there are no underscores.
  $vocabulary_name_css = str_replace('_', '-', $term->vocabulary_machine_name);
  $variables['classes_array'][] = 'vocabulary-' . $vocabulary_name_css;

  $variables['theme_hook_suggestions'][] = 'taxonomy_term__' . $term->vocabulary_machine_name;
  $variables['theme_hook_suggestions'][] = 'taxonomy_term__' . $term->tid;
}

```

My taxonomy-term.tpl.php:

```
<div<?php print $attributes; ?>>
  <?php if (!$page && ($view_mode != 'subcategory_anchor')): ?>
    <h2><a href="<?php print $term_url; ?>"><?php print $term_name; ?></a></h2>
  <?php endif; ?>

  <?php if (!$page && ($view_mode == 'subcategory_anchor')): ?>
    <h2 id="<?php print $term_id ?>"><?php print $term_name; ?></h2>
  <?php endif; ?>

  <div<?php print $content_attributes; ?>>
    <?php print render($content); ?>
  </div>
</div>

```

---
Tags: theming, entities
---


title: dynamic flter with views

text:
# Question
Title: dynamic flter with views
Is it possible to display dynamic result based on the URL, with the Views module?

I have a database table with thousand messages, and I would display those containing the words in the URL. For example, with `test.com/variableparent/variableschild`, it should display the text containing the *variables\_child* variable.

I tried with the filter, but I have to put a specific word, not a dynamic one.

# Answer
> 1 votes
You can do this using Views Argument Substitutions and I'm just assuming the Title field here. It should work for any text field.

1. Add some `Global: Null` contextual filters to take each raw component of the url. (Provide default: Raw Value from URL 2 / 3 / 4 etc.
2. In your views filters, add Title: Contains: `***!1***`. Repeat this for however many url components there are. `***!2***` `***!3***` etc. for each Title filter.
3. Use AND / OR in between your Title filters section to control your final result.

---
Tags: 7, views
---


# Question
Title: A view inside another View, updated with AJAX
I have a View of taxonomy terms (categories of books). This View lists all of the categories available to the user. Now I would like that, when the user clicks on the Category, a div will appear with a few books (another View, with contextual filter). By clicking on a link, I can go to the full View or to the details of the book, but if I do not click on any link, and go to another section and click on the title, I would like the earlier section to close the div, and another div with new books will appear in this new section.

The schema would be something like this:

* Category 1
* Category 2
* Category 3

When clicking on Category 1, with AJAX there will appear:

* Category 1 ---\> the next part appears retrieved with AJAX
    + Book 1
    + Book 2
    + Book 3 See more books on Category 1 \<--- END of content thrown by AJAX call.
* Category 2
* Category 3

I have been able to make it work without AJAX, using both modules Views Field View and Views Accordion.

However, I cannot find out how to make it work with AJAX, so no tab content is loaded it will be loaded in AJAX when clicking and opening one tab category, so the browser memory/speed/server requeriment is not impacted if I just want to see books in one category.

# Answer
You can try using Module 'Views Ajax Get'

https://www.drupal.org/project/views\_ajax\_get

Or you can also implement it on your own using below sample code, as Views itself provides callback /views/ajax for getting any view through Ajax -

PHP:

```
$view = views_get_view('taxonomy_term');
$view->set_display('page');
$view->set_use_ajax(TRUE);
$view->set_arguments(array($tid));
$settings = array(
  'views' => array(
    'ajax_path' => url('views/ajax'),
    'ajaxViews' => array(
      array(
        'view_name' => $view->name,
        'view_display_id' => $view->current_display,
        'view_args' => check_plain(implode('/', $view->args)),
        'view_path' => check_plain($_GET['q']),
        'view_base_path' => $view->get_path(),
        'view_dom_id' => 1,
        'pager_element' => $view->pager['element'],
      ),
    ),
  ),
);
drupal_add_js($settings, 'setting');
views_add_js('ajax_view');

```

JavaScript:

```
$.ajax({
  url: Drupal.settings.views.ajax_path,
  type: 'GET',
  data: data,
  success: function(response) {
    var viewDiv = '.view-dom-id-' + data.view_dom_id;
    $('#content > div.limiter').html(response.display);
    // Call all callbacks.
    if (response.__callbacks) {
      $.each(response.__callbacks, function(i, callback) {
        eval(callback)(viewDiv, response);
      });
    }
  },
  error: function(xhr) {
    $('#content > div.limiter').html('<p id="artist-load-error">Error text.</p>');
    $('#block-request-0').hide();
  },
  dataType: 'json'
});

```

Reference: https://stackoverflow.com/questions/4932523/embed-a-view-using-ajax
> 1 votes

# Answer
Views Megarow sounds like it would be ideal for this situation as it opens up a new "accordion" page in the middle of your view like you desire.

You would need to build a new view page / panel page for the parent terms which list the books. This can be done in many ways but I guess a view for /categories/%tid would be the easiest.

The benefit is that you can really do a lot of stuff inside that page.. Blocks / Comments / Multiple Views etc. along with just listing books. If you already have pages for each category, it would be a case of creating a version suitable for loading inside the megarow.

It doesn't close the last category but I guess you could get past that with some basic jQuery.
> 2 votes

---
Tags: 7, views, ajax
---


# Question
Title: Using the modules Rules and Facebook Autopost, the previous post body summary is used instead of the current post
**UPDATED 8/29/2016**

Thank you so much for everyone that responded and special thanks to Pierre.Vriens for the detailed explanation. I am sharing my answer in case anyone finds this useful.

After much research I found that the summary field was not available so I created my own summary (which is not nearly as good as the built in summary from Durpal) but it fits my own needs. It will break in the middle of a word but that is ok for me and also it breaks on 250 characters no matter what but that is ok in my case as well.

In my case I used the following for the facebook-description field (with php wrappers, or course).

`print substr(strip_tags($node->body['und'][0]['value']), 0, 250) . " . . ."` thanks again to everyone!

----- original question -----

When I add a new article my facebook autopost uses the correct image, correct title, and the correct URL but the body summary is from the previous article?

If I rebuild the rules cache it works correctly but only for the next entry then I need to rebuild the rules cache again.

```
{ "rules_fb_new_artice" : {
    "LABEL" : "FB - New Artice",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "TAGS" : [ "facebook" ],
    "REQUIRES" : [ "rules", "php", "fb_autopost_entity" ],
    "ON" : { "node_insert--article" : { "bundle" : "article" } },
    "DO" : [
      { "entity_create" : {
          "USING" : {
          "type" : "facebook_publication",
          "param_type" : "post",
          "param_user" : [ "site:current-user" ]
          },
          "PROVIDE" : { "entity_created" : { "entity_created" : "Created entity" } }
        }
      },
      { "data_set" : {
          "data" : [ "entity-created:field-facebook-name" ],
          "value" : [ "node:title" ]
        }
      },
      { "data_set" : {
          "data" : [ "entity-created:field-facebook-picture" ],
          "value" : "\u003C?php\r\n if($node-\u003Efield_image) {\r\n if(array_key_exists(0, $node-\u003Efield_image[\u0027und\u0027])) {\r\n $fid = $node-\u003Efield_image[\u0027und\u0027][0][\u0027fid\u0027];\r\n\t $result = db_select(\u0027file_managed\u0027, \u0027fm\u0027)\r\n\t\t-\u003Efields(\u0027fm\u0027, array(\u0027uri\u0027))\r\n\t\t-\u003Econdition(\u0027fm.fid\u0027, $fid,\u0027=\u0027)\r\n\t\t-\u003Eexecute()\r\n\t\t-\u003EfetchAssoc();\r\n $path = $result[\u0027uri\u0027];\r\n $style_name = \u0027large\u0027;\r\n print (image_style_url($style_name, $path));\r\n }\r\n }\r\n?\u003E"
        }
      },
      { "data_set" : {
          "data" : [ "entity-created:field-facebook-link" ],
          "value" : [ "node:url" ]
        }
      },
      { "data_set" : {
          "data" : [ "entity-created:field-facebook-description" ],
          "value" : [ "node:body:summary" ]
        }
      },
      { "publish_to_facebook" : {
          "USING" : { "publication" : [ "entity-created" ], "pages" : "140044559353737" },
          "PROVIDE" : { "facebook_publication_id" : { "facebook_publication_id" : "Facebook publication returned ID" } }
        }
      },
      { "entity_save" : { "data" : [ "entity-created" ] } }
    ]
  }
}

```

Here is a screenprint of the above rule with proper formatting.

Some more details: When a new article is submitted a Facebook post is made using the article title, article url, article summary and article image.

# Answer
Your `publish_to_facebook` is NOT your very last Rules action. In fact, as per the `save_entity` which follows it, it appears that you are publishing to Facebook something that hasn't been saved yet. So that at least seems to explain what you see happening.

Any attempt to get it to work should ensure that you only publish something that has been saved. So you may want to try by just swapping the last 2 rules actions.

The above is just a quick and dirty attempt, and I doubt you'll actually get it to work like that. But your question reminds me about issue # 430274, and somehow explains that "after saving something" actually happens "before saving something". This is not a bug, but simply how the Rules module works.

A possible compromise to avoid these kind of issues, is to move your `publish_to_facebook` action into a second Rules or component in order to ensure that the node is definitely saved correctly.

* Method 1: Your original Rule "schedules the execution" (using the Rules Scheduler sub-module) of that Rules component. For example after only a few seconds or minutes if your cron job runs frequent enough (otherwise it'll be next time cron runs). This compromise will ensure that, at the time the Rules component is executed, the entity is for sure saved (so *that* can't be the reason anymore then why things don't work as expected).
* Method 2: Add a Boolean field to the node type and when using Rules to create the node, set it to "off". Then add a redirect to the created node as the last action.
After that, create a second rule for "Content is viewed" which will make the Facebook post.
Condition: "Boolean field == Off".
Action 1: `Post to Facebook` using viewed node's data.
Action 2: `Set a Data Value`: Boolean field == "On".

If none of the above helps, maybe it's worth to do some Rules debugging, as detailed in "How can I display the value of a variable inside a condition?".

**Note**: In 1 of your (moved to chat) comments, you also added this:

> Facebook returns a unique identifier that must be saved as part of the entity so I can further code updates or deletes if necessary.

If I was to make this work, I would first make the original question work, which is about "add a new article" (updates or deletes is an additional challenge). Because as long as you've not succeeded in that, there is nothing to update or delete ...
> 0 votes

---
Tags: rules, social-network
---


# Question
Title: Downloading, and loading Google analytics script locally and daily with Drupal Cron
I'm using Drupal Google Analytics module for some time; It works perfectly and gives me the data I need.

Yet, since instilling it, I get the following notification on Google Pagespeed Insights:

Do you know a way to load the script locally and daily in Drupal so to prevent this notification?

Is there a way to make add a automation to Cron to download the famous ga.js script daily from Google, load it, and then, the next day, delete it, and repeat the process?

# Answer
> 3 votes
This has been built into the Google Analytics module for sometime. In the configuration form, under **Advanced Settings** there's a **Locally cache tracking code file** checkbox. It will persist a local cached version of the JS code for day before a cron run will re-cache it.

---
Tags: 8, performance, cron, google-analytics
---


# Question
Title: How do I get content to display using Views and Panels?
I've created a custom view to display two different content types and now want to override the node display with this new view. I tried using this tutorial to do so with Panels, but I always get no content. Not a completely white screen, just a title and nothing beneath it. I am able to add other content using Panels directly, so I think it must be a problem with the way Views and Panels are interfacing. Any idea what I need to do to fix this?

I have tried: \- changing the output format of the view to 'Panel Fields' (as opposed to 'Content'). \- clearing and re-clearing my browser's cache.

I'm using Drupal 7.12, Chaos Tools 7.x-1.0-rc2, Panels 7.x-3.2 and Views 7.x-3.3

# Answer
For Views to work in panels, you should create a `Content Pane` in your view.

You will likely be using a contextual filter if it's a node / user / taxonomy view so add it, and check `provide default: content id` from url (for a node).

Then in the Pane Settings section, click Argument Input. You will see your contextual filter listed. Choose "From Context", "Content ID".

Your view should now work as expected.
> 1 votes

# Answer
Perhaps your view is applying a filter that is filtering out all the content. Check to make sure that the View you have set up has the right filter criteria.
> 0 votes

# Answer
Create your content type views as block just enabled the block in panels dsiplay wherever you want
> 0 votes

---
Tags: views, panels
---


# Question
Title: I can not change the author of the material, an error occurs. error code inside, along with a screenshot
I want to change the author of the material, but the Ajax work with error

```
Failed to load resource: the server responded with a status of 403 (Forbidden)

```

# Answer
The AJAX path used for autocompleting usernames (**user/autocomplete**) requires a user to have the *access user profiles* permission:

```
  $items['user/autocomplete'] = array(
    'title' => 'User autocomplete',
    'page callback' => 'user_autocomplete',
    'access callback' => 'user_access',
    'access arguments' => array('access user profiles'),
    'type' => MENU_CALLBACK,
    'file' => 'user.pages.inc',
  );

```

Make sure that is true for the user account that's entering the data into the autocomplete field.

If the account does have the permission then the problem is specific to your environment (e.g. a module that alters `access callback` / `access arguments` of router item) and requires further debugging that falls out of the scope here.
> 0 votes

---
Tags: javascript, ajax
---


# Question
Title: AJAX error when using a custom ViewsFilter?
I have created a custom field that is a collection of a couple things, one being a taxonomy entity reference. Now I want to be able to filter a view based on this taxonomy reference. With the code below I see the correct entity reference and can find the correct terms and everything looks good until I click save.

Then it throws this giant AJAX error that i cannot make heads or tails of.

ajax.js?v=8.1.3:965 Uncaught AjaxError:

```
An AJAX HTTP error occurred.
HTTP Result Code: 200
Debugging information follows.
Path: /admin/structure/views/view/category_news_block_6/preview/music
StatusText: OK
ResponseText: 'Technology (25)''Technology (25)'[{"command":"settings","settings":{"ajaxPageState":{"theme":"onsetadmin","libraries":"abheading\/abheading,archived_favorites\/ajax_saving,classy\/base,classy\/messages,classy\/node,contextual\/drupal.contextual-links,contextual\/drupal.contextual-links,contextual\/drupal.contextual-toolbar,core\/drupal.active-link,core\/drupal.autocomplete,core\/drupal.collapse,core\/drupal.collapse,core\/drupal.dialog.ajax,core\/drupal.dialog.ajax,core\/drupal.states,core\/drupal.tabledrag,core\/drupal.tableresponsive,core\/html5shiv,core\/jquery.ui.tabs,core\/normalize,event_calendar\/event_calendar_lib,find\/find_lib,ga_report\/ga_send,import\/ncs,login_mod\/logout,my_podcast\/podcast-js,ncsdev\/ipad_fixes,onsetadmin\/bootstrap,onsetadmin\/global-styling,poll\/drupal.poll-links,scroll_menu\/scroll,seven\/global-styling,shortcut\/drupal.shortcut,social_media\/social_media_style,socialmedianode\/socialmedianode_style,toolbar\/toolbar,toolbar\/toolbar.escapeAdmin,tour\/tour,urltracking\/urltracking_form_style,user\/drupal.user.icons,video\/video_form,views\/views.module,views_ui\/views_ui.admin","theme_token":"gEoIQ537BMQtSpWSiqEYebhCssHSDCwaCPLN1224XqM"},"ajaxTrustedUrl":{"\/admin\/structure\/views\/view\/category_news_block_6\/preview\/music":true},"ajax":{"preview-submit":{"url":"\/admin\/structure\/views\/view\/category_news_block_6\/preview\/music","wrapper":"views-preview-wrapper","event":"click","progress":{"type":"fullscreen"},"method":"replaceWith","disable-refocus":true,"dialogType":"ajax","submit":{"_triggering_element_name":"op","_triggering_element_value":"Update preview"}}},"pluralDelimiter":"\u0003","user":{"uid":"1","permissionsHash":"fd4956e871fce9817761b65924d9442c46e3c597742b03fc3169b17173425acb"}},"merge":true},{"command":"insert","method":null,"selector":null,"data":"\u003Cdiv id=\u0022views-preview-wrapper\u0022 class=\u0022views-preview-wrapper views-admin clearfix\u0022\u003E\u003Cform class=\u0022view-preview-form view-form\u0022 data-drupal-selector=\u0022views-ui-preview-form\u0022 action=\u0022\/admin\/structure\/views\/view\/category_news_block_6\/preview\/music\u0022 method=\u0022post\u0022 id=\u0022views-ui-preview-form\u0022 accept-charset=\u0022UTF-8\u0022\u003E\n  \u003Ch2 class=\u0022view-preview-form__title\u0022\u003EPreview\u003C\/h2\u003E\u003Cdiv class=\u0022js-form-item form-item js-form-type-checkbox form-type-checkbox js-form-item-live-preview form-item-live-preview\u0022\u003E\n        \u003Cinput data-drupal-selector=\u0022edit-displays-live-preview\u0022 type=\u0022checkbox\u0022 id=\u0022edit-displays-live-preview\u0022 name=\u0022live_preview\u0022 value=\u00221\u0022 checked=\u0022checked\u0022 class=\u0022form-checkbox\u0022 \/\u003E\n\n        \u003Clabel for=\u0022edit-displays-live-preview\u0022 class=\u0022option\u0022\u003EAuto preview\u003C\/label\u003E\n      \u003C\/div\u003E\n\u003Cdiv class=\u0022js-form-item form-item js-form-type-textfield form-type-textfield js-form-item-view-args form-item-view-args\u0022\u003E\n      \u003Clabel for=\u0022preview-args\u0022\u003EPreview with contextual filters:\u003C\/label\u003E\n        \u003Csection id=\u0022auth-button\u0022\u003E\u003C\/section\u003E\n\u003Csection id=\u0022view-selector-1\u0022\u003E\u003C\/section\u003E\n\n\n\u003Cinput data-drupal-selector=\u0022preview-args\u0022 aria-describedby=\u0022preview-args--description\u0022 type=\u0022text\u0022 id=\u0022preview-args\u0022 name=\u0022view_args\u0022 value=\u0022\u0022 size=\u002260\u0022 maxlength=\u0022128\u0022 class=\u0022form-text\u0022 \/\u003E\n\n\n            \u003Cdiv id=\u0022preview-args--description\u0022 class=\u0022description\u0022\u003E\n      Separate contextual filter values with a \u0022\/\u0022. For example, \u003Cem class=\u0022placeholder\u0022\u003E40\/12\/10\u003C\/em\u003E.\n    \u003C\/div\u003E\n  \u003C\/div\u003E\n\u003Cinput data-drupal-selector=\u0022form-gdz-2l46lu60yf2rt2cblxxvbeck-cnw41cgteidqo\u0022 type=\u0022hidden\u0022 name=\u0022form_build_id\u0022 value=\u0022form--GDZ_2l46LU60Yf2rT2CblxXvbeCk_cNw41cgtEIdqo\u0022 \/\u003E\n\u003Cinput data-drupal-selector=\u0022edit-view-preview-form-form-token-wquwcx8kkz4\u0022 type=\u0022hidden\u0022 name=\u0022form_token\u0022 value=\u0022nOZgTdYSYFgrtq57O-sekR4qqFbs4c02928-_rVCKrE\u0022 \/\u003E\n\u003Cinput data-drupal-selector=\u0022edit-view-preview-form-rudggtaedzm\u0022 type=\u0022hidden\u0022 name=\u0022form_id\u0022 value=\u0022view_preview_form\u0022 \/\u003E\n\u003Cdiv id=\u0022preview-submit-wrapper\u0022 class=\u0022preview-submit-wrapper form-actions js-form-wrapper form-wrapper\u0022 data-drupal-selector=\u0022edit-actions\u0022\u003E\u003Cinput class=\u0022arguments-preview button js-form-submit form-submit\u0022 data-drupal-selector=\u0022preview-submit\u0022 data-disable-refocus=\u0022true\u0022 type=\u0022submit\u0022 id=\u0022preview-submit\u0022 name=\u0022op\u0022 value=\u0022Update preview\u0022 \/\u003E\n\u003C\/div\u003E\n\u003Cdiv id=\u0022views-live-preview\u0022 class=\u0022views-live-preview js-form-wrapper form-wrapper\u0022 data-drupal-selector=\u0022edit-preview\u0022\u003E\u003Cdiv class=\u0022views-query-info\u0022\u003E\u003Ctable data-drupal-selector=\u0022edit-table\u0022 id=\u0022edit-table--AKkl1_P_Zwc\u0022 data-striping=\u00221\u0022\u003E\n  \n  \n  \n    \u003C\/table\u003E\n\u003C\/div\u003EUnable to preview due to validation errors.\u003C\/div\u003E\n\n\u003C\/form\u003E\n\u003C\/div\u003E","settings":null},{"command":"insert","method":"prepend","selector":null,"data":"\n    \u003Cdiv role=\u0022contentinfo\u0022 aria-label=\u0022Error message\u0022 class=\u0022messages messages--error\u0022\u003E\n          \u003Cdiv role=\u0022alert\u0022\u003E\n                  \u003Ch2 class=\u0022visually-hidden\u0022\u003EError message\u003C\/h2\u003E\n                    The value  is not an array for in on filter: : Category\n                \u003C\/div\u003E\n      \u003C\/div\u003E\n    \n","settings":null}]Drupal.Ajax.error @ ajax.js?v=8.1.3:965complete @ ajax.js?v=8.1.3:510t.complete @ jquery.form.min.js?v=3.51:11j @ jquery.js:3099fireWith @ jquery.js:3211x @ jquery.js:8279(anonymous function) @ jquery.js:8605

```

Here is the code i am using for my filter.

```
<?php

namespace Drupal\my_custom_field\Plugin\views\filter;

use Drupal\Core\Form\FormStateInterface;
use Drupal\user\Entity\User;
use Drupal\views\Plugin\views\filter\InOperator;
use Drupal\Core\Entity\Element\EntityAutocomplete;
use Drupal\views\Views;
use Drupal\views\Plugin\views\display\DisplayPluginBase;
use Drupal\views\ViewExecutable;

/**
 * Filter handler for usernames.
 *
 * @ingroup views_filter_handlers
 *
 * @ViewsFilter("custom_field_category")
 */
class CustomCategoryFilter extends InOperator {

  protected function valueForm(&$form, FormStateInterface $form_state) {
    $form['value'] = array(
        '#title' => $this->t('Category'),
        '#type' => 'entity_autocomplete',
        '#selection_handler' => 'default:taxonomy_term',
        '#target_type' => 'taxonomy_term',
        '#selection_settings'=> [
            'target_bundle'=> array(
                'category',
            ),
        ],
    );
  }

}

```

and my hook

```
<?php

/**
 * implements hook_views_data_alter
 */
function priority_widget_views_data_alter(array &$data){
  $data['node__field_content_category']['priority_widget_category_filter'] = [
      'title' => t('Category'),
      'filter' => array(
          'title' => t('Category'),
          'help' => 'Searches the category field in the Priority Widget',
          'field' => 'field_content_category_target_id',
          'id' => 'priority_widget_category',
      ),

  ];
}

```

What is causing this ajax error? Or is there an easy way to debug this?

# Answer
> 1 votes
The significant line from that error is: `The value is not an array for in on filter: : Category`

If you grep in core for "is not an array for" you'll get `modules/views/src/Plugin/views/filter/InOperator.php`, specifically a line in its validate function that is testing `$this->value` to see if it's an array.

```
$errors[] = $this->t('The value @value is not an array for @operator on filter: @filter', array('@value' => var_export($this->value), '@operator' => $this->operator, '@filter' => $this->adminLabel(TRUE)));

```

Try to debug and find out if there's anywhere in your custom views filter that $this-\>value is equal to a string or something, and convert it to an array.

---
Tags: 8, ajax, views
---


# Question
Title: Can we get full count of results from a query that is extended by PagerDefault
I have a query that is extended by `PagerDefault`. I need to get the total count of results to show something like: "There are a total of 100 results, now showing 21-40". I can't figure out where to get that number without building a separate query to run that doesn't use `PagerDefault`.

First place I looked was `theme_pager()`, which I'm already overriding in template.php. The total result count is not passed there, only the current page (as `$variables['element']`).

I see that within `includes/pager.inc` in `pager_default_initialize()` only the current page number is sent to `theme_pager`, although the total items are passed to that function. (So close!)

Then I thought I could clone the query, but the query must be extended prior to adding conditions, so that wouldn't work. I'll note that this isn't ideal either, because ideally, I would be able to get this total count without two db hits (as it would hit it for the count every time a user navigates the pagination).

So, does anyone know the best way to get the total count?

Thanks!

# Answer
With the existing pager class I don't think you can get that data without running the count query again. The total count is queried directly and saved to a local var before being passed off to `pager_default_initialize()`...it's not saved anywhere.

One option would be to extend the default class and use that for your pager queries. This is un-tested but I think it'll do the trick

```
class MyPager extends PagerDefault {

  /**
   * Overrides PagerDefault::execute().
   */
  public function execute() {
    // Add convenience tag to mark that this is an extended query. We have to
    // do this in the constructor to ensure that it is set before preExecute()
    // gets called.
    if (!$this->preExecute($this)) {
      return NULL;
    }

    // A NULL limit is the "kill switch" for pager queries.
    if (empty($this->limit)) {
      return;
    }
    $this->ensureElement();

    // Get the total items from our new statically cached function.
    $total_items = $this->getTotalItemCount();

    $current_page = pager_default_initialize($total_items, $this->limit, $this->element);
    $this->range($current_page * $this->limit, $this->limit);

    // Now that we've added our pager-based range instructions, run the query normally.
    return $this->query->execute();
  }

  /**
   * Cache the results of PagerDefault::getCountQuery().
   */
  public function getTotalItemCount() {
    static $total_items = NULL;

    if ($total_items === NULL) {
      $total_items = $this->getCountQuery()->execute()->fetchField();
    }

    return $total_items;
  }

}

```

You could then construct a query like the following

```
$query = db_select('table', 't')
  ->fields('t')
  ->condition('foo', 'bar')
  ->extend('MyPager');

$current_items = $query->execute();
$total_items = $query->getTotalItemCount();

```

There might be an easier way, but I just can't see it.
> 6 votes

# Answer
After executing a query extending PagerDefault, you can at any time after that (even between different functions) call a global that stored the total product count.

```
// $results = $paged_query->execute();
// OR
// $results = some_function_that_executes_a_paged_query();
global $pager_total_items;
$count = $pager_total_items[0];

```

This works in Drupal 7 as far as I know, and I have had to use it before when having searches or paginated displays that needed a total count as well. I believe this avoids us having to use a whole second separate query.

This is the most "formal documentation" I could find on it from Drupal. https://api.drupal.org/api/drupal/developer%21globals.php/global/pager\_total\_items/7.x https://api.drupal.org/api/drupal/core!globals.api.php/global/pager\_total\_items/8.2.x
> 2 votes

# Answer
You can get the total count of a query that is extended with PagerDefault with

```
  $num_rows = $query->countQuery()->execute()->fetchField();

```

This query fetches all nodes with pager and counts the total nodes

```
function _test() {
  $query = db_select('node', 'n')
          ->extend('PagerDefault');
  $query->addField('n', 'nid');
  $num_rows = $query->countQuery()->execute()->fetchField();
  $results = $query->execute();
  foreach ($results as $result) {
    drupal_set_message($result->nid); // print each row
    // do fancier stuff here
  }
  drupal_set_message($num_rows); // print total rows
  return 'test';
}

```
> 0 votes

---
Tags: 7, theming, paging
---


# Question
Title: How to change the numbering in duplicate path aliases?
All my node paths have a URL alias, provided by Pathauto. The pattern is `[node:title]`. The generated aliases for nodes with the same title are by default

* **title**,
* **title-0**,
* **title-1**,

etc. I would like to change this numbering into

* **title-1**,
* **title-2**,
* **title-3**,

etc. So, when a node with the title *Test* is submitted, a URL alias **test** should be generated. Once a second node with the same title is published, another alias **test-1** should be created for the first node and a new alias **test-2** should be added for the newly created node.

How can I do that?

# Answer
> 1 votes
`pathauto_alias_uniquify(&$alias, $source, $langcode)` is the function that does the suffixing to generate uniqueness. It has a hard-coded value that starts at 0.

However, Pathauto evokes a hook, `hook_pathauto_is_alias_reserved()` when it checks for uniqueness when generating its path alias. If you have a custom module evoke this hook, you can check reject instances of the -0 suffixing and tell pathauto to move onto the next entry.

```
/**
 * Implements hook_pathauto_is_alias_reserved().
 */
function MYMODULE_pathauto_is_alias_reserved($alias, $source, $langcode) {
  // Return FALSE when the alias ends with '-0'
  $zero_suffix = variable_get('pathauto_separator', '-') . '0';
  return (substr($alias, -strlen($zero_suffix)) == $zero_suffix);
}

```

This might catch entries that legitimately have "-0" in the path, but I'll leave to the reader to devise a workaround for that scenario.

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


# Question
Title: How do I mass flag a node on behalf of users (possibly with VBO)?
I have a view that returns the og members of a group. Users can additionally flag groups. I want all users returned by the view to flag the group. So I tried to do this with Views Bulk Operations (VBO), but the only available operation is "Flag (or unflag) a user". The flag is attached to the group, not the user. How do I do that?

# Answer
> 2 votes
What you could do to get this to work, is to use the integration of VBO with the Rules module, as further detailed below.

# Step 1: Create a Rules Component

Create a (rather basic) Rules component to flag a node by a user. Here is such component in Rules Export format:

```
{ "rules_flag_node_flagged_by_a_user" : {
    "LABEL" : "Flag node flagged by a user",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "flag", "rules" ],
    "USES VARIABLES" : {
      "flagging_user" : { "label" : "Flagging user", "type" : "user" },
      "flagged_node" : { "label" : "Node to be unflagged", "type" : "node" }
    },
    "DO" : [
      { "flag_flagnode" : {
          "flag" : "your_flag",
          "node" : [ "flagged-node" ],
          "flagging_user" : [ "flagging_user" ],
          "permission_check" : "1"
        }
      },
      { "drupal_message" : { "message" : "Node flagged for user  [flagging-user:name] (uid=[flagging-user:uid])" } }
    ]
  }
}

```

This Rules Component uses a flag with machine name `your_flag`. After you edit that machine name to fit the name of your flag, you should be able to import this rule in your own site (using the Rules UI, which needs to be enabled).

BTW: the Rules Action to display a message is just to see it at work while QA-testing this rule, feel free to remove that if you want.

# Step 2: Let VBO do the work

This step is pretty easy ... Just use your VBO view. The clue to what you want VBO to do as an operation is ... **Execute the Rules Component from Step 1**.

If you're not familiar with how to do so, have a look at the video about Using Rules components with VBO". If you want even more, then also watch the subsequent "Using Rules components with more than one parameter" video.

**Attention**: to process like 100.000 records at once is quite a challenge (memory requirements, etc). Therefor you might want to also watch the video about "More details about VBO settings" ... Before you are tempted to use VBO for processing them all at once ...

# Video tutorials

If you're not familiar (enough/yet) with Rules, checkout the 32 (!!!) great, and free, video tutorials Learn the Rules framework.

Happy VBO-ing while Rules-ing!

PS: I'm assuming this question is about D7.

---
Tags: nodes, organic-groups, flags, views
---


title: Unable to enable theme debugging

text:
# Question
Title: Unable to enable theme debugging
I am trying to figure out which template file is used in a page and I stumbled upon this variable to enable in the setting.php

```
$conf['theme_debug'] = TRUE;

```

I did enable the variable in the settings.php and in default.settings.php (what is the difference actually?), but with no luck on seeing the generated output in the markup. And of course cleared the caches several times.

So am I really blind to the generated output? Where does it actually generates?

# Answer
> 1 votes
Permissions issue. That simple. And I wasn't noticing it.

setting.php file has read only permissions (444) by default. So I changed to 644 permissions and that's it.

---
Tags: 7, theming
---


# Question
Title: Why doesn't the AJAX callback call the class contructor?
I've got a Form class, the constructor of which sets a private attribute for the Model. When the form is rendered, everything seems to work as expected. The last form element is a select which, based upon the selected value, adds another textfield to the form if needed. However, the problem is, when the ajax is called for the first time, everything is OK and the additional field is added. When I try to select a different value though, I get this error as if the constructor did not run thus not setting the $model attribute of the class.

> js\_zfg1OcYBPiNuiGY77hX8zdIjztYiO7UAz7wbokItO2I.js:2515 Uncaught AjaxError: An AJAX HTTP error occurred. HTTP Result Code: 200
> Debugging information follows.
> Path: /admin/asphira/contacts/add?ajax\_form=1&\_wrapper\_format=drupal\_ajax
> StatusText: OK
> ResponseText: Error: Call to a member function getKeyedList() on null in
> Drupal\asphira\Form\ContactForm-\>buildForm() (line 112 of C:\xampp\htdocs\reality\modules\asphira\src\Form\ContactForm.php).

Here is the form class.

```
namespace Drupal\asphira\Form;

use Drupal\asphira\Model\ContactTypeModel;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Locale\CountryManager;

class ContactForm extends FormBase {

  private $model;

  public function __construct() {
    $this->model = new ContactTypeModel();
  }

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

  public function buildForm(array $form, FormStateInterface $form_state) {
    $form['name'] = array(
      '#title' => t('Name'),
      '#type' => 'textfield',
      '#required' => TRUE,
    );

    $form['surname'] = array(
      '#title' => t('Surname'),
      '#type' => 'textfield',
      '#required' => TRUE,
    );

    $form['nee_surname'] = array(
      '#title' => t('Née surname'),
      '#type' => 'textfield',
      '#required' => TRUE,
    );

    $form['street'] = array(
      '#title' => t('Street'),
      '#type' => 'textfield',
      '#required' => TRUE,
    );

    $form['street_no'] = array(
      '#title' => t('Street no.'),
      '#type' => 'textfield',
      '#required' => TRUE,
    );

    $form['zip_code'] = array(
      '#title' => t('ZIP code'),
      '#type' => 'textfield',
      '#required' => TRUE,
    );

    $form['city'] = array(
      '#title' => t('City'),
      '#type' => 'textfield',
      '#required' => TRUE,
    );

    $form['country'] = array(
      '#title' => t('Country'),
      '#type' => 'select',
      '#options' => CountryManager::getStandardList(),
      '#required' => TRUE,
    );

    $form['phone'] = array(
      '#title' => t('Telephone'),
      '#type' => 'textfield',
    );

    $form['email'] = array(
      '#title' => t('Email'),
      '#type' => 'email',
      '#required' => TRUE,
    );

    $form['contact_type_container'] = array(
      '#type' => 'container',
      '#attributes' => array(
        'id' => 'contact-type-container',
      ),
    );

    $contact_types = $this->model->getKeyedList('t_contact_type',
      'contact_type_id', 'title');

    $form['contact_type_container']['contact_type'] = array(
      '#title' => t('Contact type'),
      '#type' => 'select',
      '#options' => $contact_types,
      '#required' => TRUE,
      '#ajax' => array(
        'callback' => array($this, 'ajaxSelectContactType'),
        'wrapper' => 'contact-type-container',
        'progress' => array(
          'type' => 'throbber',
          'message' => $this->t('Working...'),
        ),
      )
    );

    $form['actions'] = array('#type' => 'actions');
    $form['actions']['submit'] = array(
      '#type' => 'submit',
      '#value' => t('Save'),
    );

    return $form;
  }

  public function submitForm(array &$form, FormStateInterface $form_state) {
    // TODO: Implement submitForm() method.
  }

  public function ajaxSelectContactType(array &$form, FormStateInterface   $form_state) {
    $contact_type = $form_state->getValue('contact_type');
    $needs_specification = $this->model->needsFurtherSpeification($contact_type);

    if ($needs_specification) {
      $form['contact_type_container']['contact_type_specification'] = array(
        '#title' => t('Specification'),
        '#type' => 'textfield',
        '#description' => '',
        '#required' => TRUE,
      );
    }

    return $form['contact_type_container'];
  }

}

```

Do you have any idea how is it possible that the constructor gets passed by without calling?

# Answer
> 12 votes
Your problem is actually something different entirely.

It is your use of private. Don't use it, use protected. Drupal has a special logic to prevent services from being serialized but it doesn't work properly on private properties, as they are invisible to the trait that is used for that.

Also, like in a similar question recently, sounds like you're re-inventing the wheel a bit. Drupal uses entities for storage of most things, instead of making your own model classes, define it as a content or config entity, which will give you a ton of things, like storage and standard entity form classes that have $this-\>entity. For content entities, you can also easily use base fields and widget/formatter definitions to automatically build the form and output, at least to a certain degree.

The documentation is still very much in progress, but see https://www.drupal.org/developing/api/entity and some of the sub-points, also the examples module. there are also plenty of tutorials.

# Answer
> 1 votes
The code is missing the most important method a class that derives from `FormBase` should implement: `create()`. That is the static method that instantiate any class derived from `FormBase`. Take `ActionAdminManageForm::create()` as example.

```
public static function create(ContainerInterface $container) {
  return new static(
  $container->get('plugin.manager.action')
  );
}

```

Its constructor is then the following one.

```
public function __construct(ActionManager $manager) {
  $this->manager = $manager;
}

```

---
Tags: forms, 8, ajax
---


# Question
Title: Why I'm not able to delete all taxonomy terms tree?
I'm using custom drush command for flushing my custom vocabulary:

```
    function drush_mm_category_delete_all() {
  $vocab = \Drupal\taxonomy\Entity\Vocabulary::load('mm_vocab');

  if (! $vocab) {
    throw new Exception("Missing 'mm_vocab' vocabulary");
  }

  $tree = \Drupal::service('entity_type.manager')
    ->getStorage("taxonomy_term")
    ->loadTree('mm_vocab', 0, NULL, FALSE);

  drush_print('Amount of terms to delete: ' . count($tree));
  $counter = 0;

  foreach($tree as $term) {
    $term_entity = \Drupal\taxonomy\Entity\Term::load($term->tid);
    $term_entity->delete();
    $counter++;
  }

  drush_print('Amount of deleted terms: ' . $counter);

}

```

I'm getting error:

> Error: Call to a member function delete() on null

but WTF? I see that loadTree returns flat array of all vocab term. It seems that all items are object with tid property.

If I add:

```
if ($term_entity) {
  //delete here
}

```

I'm able to run command without error, but only small amount of terms are deleted. Why?

# Answer
> 0 votes
The comment is correct, children are deleted automatically.

So what you can do is set the max\_depth argument to 0, then you should only get the top-level terms and you can delete those.

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


# Question
Title: Looking for a special views exposed filter with pager and select list
i'm looking for an exposed views filter like it is implemented at the linked page. Example here

a) While click on "1.Spieltag" there is a select list.

b) Also there are pager arrows to scroll through 1.Spietag 2.Spieltag ect...

Is there a module or a widget i have missed till now, with which i can achieve the described functionallity? Any other idea how to achieve this?

Thanks Tom

# Answer
> 0 votes
I've updated Ctools, Views and date to the latest version as well. Here the view i recreated from scratch after having updated the modules:

```
$view = new view;
$view->name = 'test';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'node';
$view->human_name = 'test';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'test';
$handler->display->display_options['use_more_text'] = 'plus';
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['query']['options']['query_comment'] = FALSE;
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['exposed_form']['options']['reset_button_label'] = 'Réinitialiser';
$handler->display->display_options['exposed_form']['options']['exposed_sorts_label'] = 'Trier par';
$handler->display->display_options['pager']['type'] = 'full';
$handler->display->display_options['pager']['options']['items_per_page'] = '5';
$handler->display->display_options['pager']['options']['offset'] = '0';
$handler->display->display_options['pager']['options']['id'] = '0';
$handler->display->display_options['pager']['options']['expose']['items_per_page_label'] = 'Éléments par page';
$handler->display->display_options['pager']['options']['expose']['items_per_page_options_all'] = 0;
$handler->display->display_options['pager']['options']['expose']['offset_label'] = 'Décalage';
$handler->display->display_options['style_plugin'] = 'default';
$handler->display->display_options['row_plugin'] = 'node';
/* Champ: Contenu : Titre */
$handler->display->display_options['fields']['title']['id'] = 'title';
$handler->display->display_options['fields']['title']['table'] = 'node';
$handler->display->display_options['fields']['title']['field'] = 'title';
$handler->display->display_options['fields']['title']['label'] = '';
$handler->display->display_options['fields']['title']['alter']['alter_text'] = 0;
$handler->display->display_options['fields']['title']['alter']['make_link'] = 0;
$handler->display->display_options['fields']['title']['alter']['absolute'] = 0;
$handler->display->display_options['fields']['title']['alter']['word_boundary'] = 0;
$handler->display->display_options['fields']['title']['alter']['ellipsis'] = 0;
$handler->display->display_options['fields']['title']['alter']['strip_tags'] = 0;
$handler->display->display_options['fields']['title']['alter']['trim'] = 0;
$handler->display->display_options['fields']['title']['alter']['html'] = 0;
$handler->display->display_options['fields']['title']['hide_empty'] = 0;
$handler->display->display_options['fields']['title']['empty_zero'] = 0;
$handler->display->display_options['fields']['title']['link_to_node'] = 1;
/* Critère de tri: Contenu : Date de publication */
$handler->display->display_options['sorts']['created']['id'] = 'created';
$handler->display->display_options['sorts']['created']['table'] = 'node';
$handler->display->display_options['sorts']['created']['field'] = 'created';
$handler->display->display_options['sorts']['created']['order'] = 'DESC';
/* Filter criterion: Contenu : Publié */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'node';
$handler->display->display_options['filters']['status']['field'] = 'status';
$handler->display->display_options['filters']['status']['value'] = 1;
$handler->display->display_options['filters']['status']['group'] = 0;
$handler->display->display_options['filters']['status']['expose']['operator'] = FALSE;
/* Filter criterion: Contenu : Type */
$handler->display->display_options['filters']['type']['id'] = 'type';
$handler->display->display_options['filters']['type']['table'] = 'node';
$handler->display->display_options['filters']['type']['field'] = 'type';
$handler->display->display_options['filters']['type']['value'] = array(
  'publi' => 'publi',
);
/* Filter criterion: Recherche : Termes de recherche */
$handler->display->display_options['filters']['keys']['id'] = 'keys';
$handler->display->display_options['filters']['keys']['table'] = 'search_index';
$handler->display->display_options['filters']['keys']['field'] = 'keys';
$handler->display->display_options['filters']['keys']['exposed'] = TRUE;
$handler->display->display_options['filters']['keys']['expose']['operator_id'] = 'keys_op';
$handler->display->display_options['filters']['keys']['expose']['label'] = 'Termes de recherche';
$handler->display->display_options['filters']['keys']['expose']['operator'] = 'keys_op';
$handler->display->display_options['filters']['keys']['expose']['identifier'] = 'title';
$handler->display->display_options['filters']['keys']['expose']['multiple'] = FALSE;
/* Filter criterion: Date : Date (node) */
$handler->display->display_options['filters']['date_filter']['id'] = 'date_filter';
$handler->display->display_options['filters']['date_filter']['table'] = 'node';
$handler->display->display_options['filters']['date_filter']['field'] = 'date_filter';
$handler->display->display_options['filters']['date_filter']['operator'] = '<=';
$handler->display->display_options['filters']['date_filter']['exposed'] = TRUE;
$handler->display->display_options['filters']['date_filter']['expose']['operator_id'] = 'date_filter_op';
$handler->display->display_options['filters']['date_filter']['expose']['label'] = 'Par date :';
$handler->display->display_options['filters']['date_filter']['expose']['operator'] = 'date_filter_op';
$handler->display->display_options['filters']['date_filter']['expose']['identifier'] = 'datepicker';
$handler->display->display_options['filters']['date_filter']['expose']['multiple'] = FALSE;
$handler->display->display_options['filters']['date_filter']['form_type'] = 'date_text';
$handler->display->display_options['filters']['date_filter']['date_fields'] = array(
  'node.created' => 'node.created',
);
$handler->display->display_options['filters']['date_filter']['date_method'] = 'AND';

/* Display: Page */
$handler = $view->new_display('page', 'Page', 'page');
$handler->display->display_options['path'] = 'test';
$translatables['test'] = array(
  t('Master'),
  t('test'),
  t('plus'),
  t('Appliquer'),
  t('Réinitialiser'),
  t('Trier par'),
  t('Asc'),
  t('Desc'),
  t('Éléments par page'),
  t('- All -'),
  t('Décalage'),
  t('Termes de recherche'),
  t('Par date :'),
  t('Page'),
);

```

---
Tags: 7, views, paging
---


# Question
Title: Products are stored without title and product variations. Can't display them
Such a weird thing has happened in my commerce kickstart 2 store. Somehow some products are in database but have not product variations and have not Title, so I can't display them in backend to remove them.

Is there a way to display those products in backoffice or I will have to delete directly in database? If so, is safe to remove them only in products table?

**UPDATE:**

I went inside database. I figured out that products that are not displayed in back-end search have not product variations anymore. Most of these products had Title Field and I could delete them by searching in front-end, clicking in Title *link* \- this took me to node page's product. But now there are a few ones that have not Title. In front-end searching display them, but there is not a *link* to view node's product. So I think what I have are nodes without product variations. And the question What I do to deleted them remains.

# Answer
> 0 votes
I'm not working on Kickstart as I prefer to have a custom install of Drupal Commerce.

Commerce concept is that each product you create is a variation and you can use those variations in a display (content type)

If you can't see and delete products in the products list, you can create a view (page) displaying commerce products in admin mode (page url : admin/my-view). Then add fields like : product id, sku, title and commerce product delete link.

But it's really strange to have products without title in yourdatabase... because you can't create product without title.

---
Tags: commerce
---


title: Flag Module: "Never Flagged" Status

text:
# Question
Title: Flag Module: "Never Flagged" Status
Flag Module is a very effective module for tagging entities which - apparently - only handles two status: "flagged" and "unflagged", while I need now to know if an entity was even been flagged before. So, 3 status:

* "never flagged"
* "flagged"
* "unflagged"

Which solution have we today in order to see if an entity has ever been flagged?

# Answer
IMO there ***is*** a solution without custom coding ... Below is a synopsis (to avoid writing a manual ...) of how to get this to work ...

# Step 1:

Create an additional flag, let's label it like "Ever flagged with `FlagX`" (whereas '`FlagX`' reflects the flag for which you want to know if the entity was ever flagged).

# Step 2:

Use the Rules module to create a rule like so:

* Rules Event: After entity (=node or user) is flagged with `FlagX`
* Rules Action: Flag an entity (= node or user), with parameter the flag "Ever flagged with `FlagX`"

Here is a sample of such rule (in Rules export format, adapt the machine name of both flags to fit your needs prior to importing it in your own site), for a flag used for flagging an entity of type "user":

```
{ "rules_set_the_ever_flagged_with_flagx_flag" : {
    "LABEL" : "Set the ever flagged with FlagX flag",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "flag" ],
    "ON" : { "flag_flagged_flagx" : [] },
    "DO" : [
      { "flag_flaguser" : {
          "flag" : "ever_flagged_with_flagx ",
          "user" : [ "flagged-user" ],
          "flagging_user" : [ "flagging-user" ],
          "permission_check" : "1"
        }
      }
    ]
  }
}

```

# Step 3:

"*To know if an entity was ever been flagged before*" (as in your question), all you need to do now is to check for the entities that have been flagged with the "Ever flagged with `FlagX`" flag. Obviously, it should be straight forward to use the Views module to create an appropriate list of those entities (like users) for which the "Ever flagged with `FlagX`" flag is ***not yet*** set ... which would then be the actual answer to your question, i.e. the entities (like users) which were "**N**ever flagged with `FlagX`".
> 2 votes

# Answer
Add a term reference field to a taxonomy vocabulary that lists the three options.

By default, the field saves as "not flagged", on flag, rules changes it to "flagged" and on unflag, rules changes it to "unflagged".

Add some conditions so the field isn't changed unnecessarily. I never feel bad about adding fields for site features.
> 1 votes

---
Tags: 7, flags
---


# Question
Title: Display Count of associated nodes as "more" in Calendar View?
I'm using the Drupal Calendar module to create a monthly calendar view. As is default behavior the monthly calendar shows a list of the days events on each day. I have the Format Settings set to only display one event and then a "more" link. I would like to have the total number of events for that day next to the "more" link.

I attempted to add a "nid:count" aggregated field but it only counted for each node (so it was always "1") not per day.

How can I show the total number of events per day?

# Answer
> 1 votes
In your calendar view you can select format\>Settings: Too many items to "Hide all add link to day" and it will show the totals for that day.

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


title: Drupal 7 Can't add date sort criteria

text:
# Question
Title: Drupal 7 Can't add date sort criteria
I have a view that display a list of nodes of a content type that has a date field. I'm trying to add a sort criteria based on this data field, I can select it but hust after that I get returned to the main views screen, without the data sort.

I know that data fields are sortable so where can I have more informations about "why" this field is not added to sort criteria?

# Answer
It will avialable in Format -\> Settings -\> Check 'Stortable' Check box
> 1 votes

# Answer
I solved my problem: drupal views module can't handle fields with a machine name longer or equal to 24 chars, so I used this module https://www.drupal.org/project/field\_rename to change the custom date field name and now everything is ok!
> 1 votes

---
Tags: views
---


title: D7 indexing page

text:
# Question
Title: D7 indexing page
I am looking to create a dropdown menu that will display all the tags but in a indexing manner. See example at http://www.healthinfonet.ecu.edu.au for the A-Z topic menu.

Anyway we can do that in D7 ?

# Answer
Yes, create a view which is displaying the list and connect that to the menu with the help of module. https://www.drupal.org/project/menu\_views
> 0 votes

---
Tags: taxonomy-terms, navigation
---


# Question
Title: Environment dependend workflow with configuration management
When using Drupal 7 with larger projects, we used a Custom module together with Features, Environment and Environment Indicator modules to keep special environment settings apart. We had at least one feature module for each environment containing something like this:

**Production**

* no dblog module active
* no devel modules
* all sorts of caching enabled
* red coloring on Environment Indicator

**Staging / Testing**

* dblog module active
* no devel modules
* some caching disabled
* yellow coloring on Environment Indicator

**Staging / Testing**

* dblog module active
* all sorts of devel modules active
* caching disabled
* green coloring on Environment Indicator

When developing we used to push new code to production when it was finished and tested. After successful deployment, we cloned the database down to staging and development environments to be sync with the state of production in terms of new content. After that we would run commands like `drush env-switch staging` to tell Drupal to set environment to Staging and run some custom hooks that would enable the Staging feature module and its settings and dependencies. This way Production, Staging and Develop had different sets of modules and configuration but the same state of content.

After reading and testing into Configuration Management, i fail to see how i could accomplish such a workflow. When using `drush config-export staging` it exports all current settings into staging directory, which i can check into git and deploy it on my server. Features for D8 lacks of some things that have been in D7. I miss a settings we had in D7 and i am not able to add a dependency without additional settings. I don't depend on Features if there is another way of doing things like this in D8.

What am i missing in D8? What would be the current workflow to get such environment dependent settings and modules active and different environments in Drupal 8?

Thanks for you help!

# Answer
> 1 votes
### Drupal 7

Have you considered adding some intelligence to *settings.php*? You could test `$_SERVER['HTTP_HOST']` there, and set `$conf['some_variable']` accordingly. Below are some examples from Pantheon. They use their own environment variables to test which environment is running, but you can achieve the same by testing `$_SERVER['HTTP_HOST']` or maybe testing `file_exists('some_file_which_identifies_environment')` \- whatever is convenient.

```
// All Pantheon Environments.
if (defined('PANTHEON_ENVIRONMENT')) {
  // Drupal caching in test and live environments.
  if (in_array(PANTHEON_ENVIRONMENT, array('test', 'live'))) {
    // Anonymous caching - enabled.
    $conf['cache'] = 1;
    // Block caching - enabled.
    $conf['block_cache'] = 1;
    // Expiration of cached pages - 15 minutes.
    $conf['page_cache_maximum_age'] = 900;
    // Aggregate and compress CSS files in Drupal - on.
    $conf['preprocess_css'] = 1;
    // Aggregate JavaScript files in Drupal - on.
    $conf['preprocess_js'] = 1;
  }
  // Drupal caching on dev environment, and all multidevs
  else {
    // Anonymous caching.
    $conf['cache'] = 0;
    // Block caching - disabled.
    $conf['block_cache'] = 0;
    // Expiration of cached pages - none.
    $conf['page_cache_maximum_age'] = 0;
    // Aggregate and compress CSS files in Drupal - off.
    $conf['preprocess_css'] = 0;
    // Aggregate JavaScript files in Drupal - off.
    $conf['preprocess_js'] = 0;
  }

  // Minimum cache lifetime - always none.
  $conf['cache_lifetime'] = 0;
  // Cached page compression - always off.
  $conf['page_compression'] = 0;

  if (PANTHEON_ENVIRONMENT == 'dev') {
    // Google Analytics.
    $conf['googleanalytics_account'] = 'UA-XXXXXXXX-X';
  }
  else if (PANTHEON_ENVIRONMENT == 'test') {
    // Google Analytics.
    $conf['googleanalytics_account'] = 'UA-XXXXXXXX-Y';
  }
  else if (PANTHEON_ENVIRONMENT == 'live') {
    // Google Analytics.
    $conf['googleanalytics_account'] = 'UA-XXXXXXXX-Z';
  }
}

```

---

### Drupal 8

The same approach can work in Drupal 8, except that the global configuration variable is named `$config`. This is documented here: Configuration override system and that page shows the example:

`$config['system.maintenance']['message'] = 'Sorry, our site is down now.';`

---
Tags: 8, configuration, deployment
---


# Question
Title: How to add a functionality to views bulk operations?
I want to use Views bulk operations to be able to change all my products' taxonomy terms at once.

I have my product managing view with views bulk operations set up and working but there is no operation for editing taxonomy terms under "Modify entity values".

I assume it is possible to add this functionality, but I'm not sure how, any suggestions?

# Answer
VBO comes, out of the box, with some predefined (hardcoded) operations that can be applied to each row selected in the view. The available operations are shown within "Selected bulk operations" when configuring the VBO field. Obviously, something like `Edit taxonomy terms` isn't one of them.

However using Rules (Conditions and/or Actions) you can execute a VBO operation which you define using a Rules Component. To get the idea, have a look at the video about Using Rules components with VBO" uses a Rules Component with (only) 1 parameter. If you want even more, then also watch the subsequent "Using Rules components with more than one parameter" video. This video actually shows how to (also) add a term to a node, so it should be pretty forward to use a similar technique.

For an example in which this technique is used, refer to the answer to "How to implement the mass operations on the Group's members page using Views?".

Note: to process thousands of nodes at once is quite a challenge (memory requirements, etc). Therefor you might want to also watch the video about "More details about VBO settings" ... Before you are tempted to use VBO for processing them all at once ...

Happy VBO-ing while Rules-ing!
> 2 votes

# Answer
You will find an operation called "Modify entity values" in VBO settings. You need to select the field in the Operation settings.
> 0 votes

# Answer
If the functionality you are looking for is not in there already, you can either write it yourself (as some modules do) following this guide in the handbook.

Or you could use the rules module to add this as a component, following this screencast here.
> 0 votes

---
Tags: taxonomy-terms, ubercart, views
---


# Question
Title: Up-to-date solution for cloning commerce product-variation types and their product displays
I am using Drupal 7 with commerce module. There are a lot of product-types with a plethora of fields – but in general, only a few fields differ, the vocabularies attached to the product for example. So I would like to stubbornly clone the product-variants and their product-display and make some minor changes manually afterwards. It's important, that the display settings are cloned, too. While researching, I found a confusing amount of modules that seem to offer that kind of functionality:

I would be glad to hear advices from savvy people for modules and appropriate workflows.

# Answer
After trying out all above modules, I can clearly say for my usecase the winner is: bundle\_copy for cloning product displays in combination with bundle\_copy\_commerce for the product variations. Cave: I didn't use the clone/copy feature of both moduls because of errors and poor cloning (fieldgroups weren't copied) – instead I used the export/import feature:

1. Export the entity
2. Replace in the code from step 1 all occurences of the bundle name with a new name
3. Import the code from step 2 again.
4. When using fieldgroups you have to make sure, you rename the fieldgroups in step 4 with a unique name (add the bundle name as a suffix, for example).
> 1 votes

---
Tags: commerce
---


# Question
Title: Is there a way to add a persistent querystring across multiple pages?
I want to add a persistent query string to pages once it is introduced (for the context module to maintain a page layout inside an iframe). At the moment, I'm checking the http referer for the string and redirecting to the current url + query string.
This works fine, except:

1. It's an extra page load. Not a big issue as it's an admin page inside an iframe that's not used much.
2. It breaks batch pages. I think I can get around this by checking if arg(0) is "batch" and then add the referer to $\_session and then check for it.

This seems really convoluted, hacky and prone to breaking the site for a user if I don't get the session variable deleted straight away.

`hook_url_outbound_alter()` doesn't work for forms unfortunately so is there a better way?

# Answer
The way I would go about this would be to dedicate an alias subdomain and perform the redirect before hitting the application.

For example, Apache can be configured via mod\_rewrite to add any query parameter to the requested URL:

```
  # Add iframe=1 to query parameter if requested from iframe domain.
  RewriteCond %{HTTP_HOST} ^if.example.com [NC]
  RewriteCond %{QUERY_STRING} !iframe=1 [NC]
  RewriteRule ^(.*)$  http://if.example.com/$1?iframe=1 [L,R=301]

```

The only problem this causes is that D7.5 now forcing iframes to only originate from the same domain so you'll have to explicitly allow iframing from this different domain in your settings.php:

```
# Allow iframing on host requests to the iframe domain
if ($_SERVER['HTTP_HOST'] == 'if.example.com') {
  $conf['x_frame_options'] = '';
}

```
> 0 votes

# Answer
I believe this is something the PURL module was designed to do (persistent query string):

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

---
Tags: redirection
---


# Question
Title: Running tests on fresh 8.2.x install throws "Permission Denied" for Kernel tests
Under a fresh install of 8.2.x, when I run tests, only Kernel tests seem to fail with this message from the testing UI:

```
(path/to/test/Kernel/test.php) ... Permission denied

```

Pretty much any Kernel test I select exits immediately with that error. Other tests, like Unit tests, work fine. Is this a file permission issue or something I missed in config?

# Answer
Looks like some tests can only be ran with the command line and will not work with the test runner UI.
> 0 votes

---
Tags: 8, testing
---


title: Correct way to customize modules?

text:
# Question
Title: Correct way to customize modules?
When making changes to files in sites/all/modules/moduleidownloaded where should the changes be stored? I know you shouldn't edit the core module files for risk of updates etc. So where should I put customized module files such as templates and styles?

# Answer
> 1 votes
You can create two folder `contrib` and `custom` inside `sites/all/modules`. Drupal is able to look up any folders inside `sites/all/modules` to discover the modules.

If it is multiple site structure, you can do the same in `sites/[site_name]/modules`

For the custom templates and styles, if you means the theme one, you can place the theme in `sites/all/themes/custom`, otherwise, templates and styles can be placed inside custom module.

# Answer
> 0 votes
The best way for the Drupal community would be to share back your changes as a patch on an issue you would open in the given project's issue queue. That way we all benefit.

Alternatively, well-written modules are overrideable and you could customize just those things in your custom module. Overriding templates is an example of just such a thing.

---
Tags: 7
---


# Question
Title: Drupal 8 programmatical block can't be place in "Block Place UI"
I have been using drupal examples https://www.drupal.org/project/examples and developing my own examples for practice. But I have come against an issue I can't workout. Below is my link to the block code I have been developing.

d8 module block example on github

I can get the block to display under admin/structure/block, but when I press the "Display Block" button in the overlay I get no response can someone tell me why? See image

The error I am getting from the ajax call is

```
ajax.js?v=8.1.8:965 Uncaught AjaxError:
An AJAX HTTP error occurred.
HTTP Result Code: 200
Debugging information follows.
Path: /d8/admin/structure/block/add/pnc_block_test/pnc?region=-1
StatusText: OK
ResponseText:
Fatal error:  Class 'Drupal\Core\block\BlockBase' not found in /vagrant/src/d8/modules/custom/pnc/pnc_block_test/src/Plugin/Block/PncBlockTest.php on line 23

```

What I have trying to achieve is the following

# Answer
Message have say

> Fatal error: Class 'Drupal\Core\block\BlockBase' not found in /vagrant/src/d8/modules/custom/pnc/pnc\_block\_test/src/Plugin/Block/PncBlockTest.php on line 23

problem here is wrong typo **block** not **Block**

replace

```
// Module block exit. But this class not exit
use Drupal\Core\block\BlockBase;

```

with

```
//path folder core/lib/Drupal/Core/Block
use Drupal\Core\Block\BlockBase;

```
> 3 votes

---
Tags: 8, blocks
---


# Question
Title: How to insert value to taxonomy on custom form submission
I have a page where admin can add a new hospital name to the site, search for the hosiptals and view all the hospitals in a tabular format. This is done by writing custom module and form.

What I now need is to add the value of the newly created hospital to a taxonomy term "hospital". So that I can use this taxonomy term reference in multiple content types.

If admin adds hospital-1 and hospital-2 to the site using custom form, on form submission these should automatically get added to the taxonomy term.

# Answer
Inside the form submit handler I do the following operations. First I fetch the vocabulary. Then I search for the new hospital name in that vocabulary. If that name doesn't exists I will save the new term.

$vocabulary = taxonomy\_vocabulary\_machine\_name\_load('hospital\_names');

$existing\_term = taxonomy\_get\_term\_by\_name($hospital\_name, $vocabulary);

if (empty($existing\_term)) { $term1 = (object) array( 'name' =\> $hospital\_name, 'vid' =\> $vocab-\>vid, ); taxonomy\_term\_save($term1); }
> 0 votes

# Answer
To add taxonomy term in form submission, get all inputted term values and those to Vocabulary you need.

```
use Drupal\taxonomy\Entity\Term;
$categories_vocabulary = 'EXAMPLE'; // Vocabulary machine name
$categories = ['test 1', 'test 2', 'test 3', 'test 4']; // List of test terms
foreach ($categories as $category) {
  $term = Term::create(array(
    'parent' => array(),
    'name' => $category,
    'vid' => $categories_vocabulary,
))->save();

```
> 0 votes

---
Tags: forms, taxonomy-terms
---


# Question
Title: Programmatically get all names of an entity reference field
Example: I want to get **all tag names** that are inside **field\_tags** of node 5.

I can get the target\_id with $node-\>field\_tags-\>getValue();

But the problem is, I don't know what entity the target\_id value belongs to. Could be a node id, term id, user id. Without that info, I am not able to use the target\_id to get the name of the tag.

How can I get all the names of an entity reference field?

# Answer
> 21 votes
The easiest way to get what you want is something like this:

```
$names = [];
foreach ($node->field_tags as $item) {
  if ($item->entity) {
    $names[$item->entity->id()] = $item->entity->label();
  }
}

```

`->entity` is a so called computed property, it doesn't show up in `getValues()`. All reference fields have it.

And yes, forget about `print_r()` on entity or other complex objects. They contain objects that reference each other, and `print_r()` can't handle that. If you have an entity, always use `print_r($entity->toArray())`, then you get the field values only. You could install devel module or use a debugger, but that will give you the internal structure of an entity, which is not really want you want to see.

# Answer
> 8 votes
An entity reference field, by definition, can only target one entity type so you can know what your target type is by calling up `getSetting()` on the field definition.

```
// Print the targeted entity type field.
$field = \Drupal\field\Entity\FieldStorageConfig::loadByName('node','field_tags');
echo $field->getSetting('target_type');

```

Or better yet, use `EntityReferenceFieldItemList::referencedEntities()` to pull up the node's referenced entities and the associated data you need.

```
// Return an array of Entity objects referenced in the field.
$node->field_tags->referencedEntities();

```

---
Tags: 8, entities
---


# Question
Title: Secure Pages Module or force HTTPS Across Whole Site?
I understand that the Secure Pages module allows you to let some pages use http and force others to use https. Assuming that is correct, **is there any reason for me to use Secure Pages if I'm already forcing all requests to my domain to use https?**

*More info below if you need it, some of which is platform specific for my host:*

I'm getting ready to launch a production ubercart ecommerce site using the Pantheon hosting platform. I want to make sure to be secure and fully PCI compliant, so I was following these guidelines which state that I need to use secure pages.

However, before that, I followed these guidelines to force https across my entire site, for all environments including dev/test. I don't mind a slight performance hit because I would rather be as secure as possible.

To force https I have added some code to my settings.php file and I have also created a page rule on Cloudflare to force requests to my domain to use https.

It's overkill but I also used the recommended code in the Pantheon documentation link above in my settings.php file to redirect all traffic to https.

The documentation for installing secure pages also raises several red flags for me.

* It involves applying core patches that have failed tests and suggests that you can do them by hand, which seems unreliable to me.
* Some of the instructions lack explanation and seem somewhat unreliable. Not trying to be mean, but where this concerns security, it makes me worry. For example, they mention that you need to change the $base\_url parameter in settings.php file, but then go on to say "This option may or may not be necessary. Some have reported that they need it, others have reported it breaks caching of their site." Similarly, after telling you to add the Cookie Domain they say: "Some have made comments that this is not necessary, or causes issues with their site. It's a recommended setting, but not explicitly required." Another unclear sentence in the documentation is that after applying the core patches: "If everything worked, you should see some output like "hunk succeeded" or something like that and you're good to go." The idea of changing core and then not explicitly knowing if I've done it correctly or not seems very worrying to me.
* One of the instructions is "Adding the Cookie Domain" but Pantheon documentation cited above also says that it "already handles the necessary environment settings to ensure that Drupal is aware the site is running under HTTPS and that user session cookies should be secured." So, there's no reason to worry about that step in the Secure Pages instructions, I believe.
* Other instructions from Secure Pages involve changing .htaccess to force www or the bare domain, but I have already taken care of that by following the Pantheon documentation above and modifying my settings.php file. This seemed the more reliable way to go since Pantheon documentation says .htaccess is ignored by NGINX servers.

So since I am already forcing https across my entire site, and I correctly enabled credit card encryption by creating a folder outside of my document root, is that enough to be PCI compliant using the Ubercart Credit Card module without Secure Pages?

# Answer
Frankly, I bypassed Secure Pages and just forced all traffic to be HTTPS via htaccess. I prefer all traffic to be forced HTTPS.

SecurePages *generally* works up front, but I have seen a lot of wacky behavior with it that I just don't bother anymore.
> 1 votes

# Answer
> ... is there any reason for me to use Secure Pages ...?

No, in general, but here's one possible reason: to avoid needing your own SSL certificate and its associated cost and administration hassle. I'm currently working on a project, also hosted on Pantheon, where we do just this. We used *Secure Pages* to redirect the user to https for sensitive pages... user login, contact form, other forms.

So, as an example, when a user goes to https://example.com/user they get redirected to https://live-example.pantheonsite.io/user \- registered users on this site are all organisation staff, or similar - it's no big deal for them to see the pantheonsite.io address.

The full implementation uses a combination of *Secure Pages* and some custom logic in *settings.php*. The latter primarily deals with overriding the configuration values for *Secure Pages* depending on the environment (local, dev, test, live). For example, when running on a local development machine it sets `$conf['securepages_enable'] = 0;`.
> 0 votes

---
Tags: ubercart, security, configuration
---


# Question
Title: How to add my own images to the views slide show?
I am new to Drupal. I have been trying to make a slide show on the front page but I am facing an issue on how to upload images of my choice in the slide show. I.e. the images that I have in my computers folder.

I have created a view and placed an image field in it, everything is set. I have also added the block to the main page content. All I can see on the front page is the slider title obviously since i have not been able to add any images.

Can any body tell me how to set my own images to the slider?

I don't want to use fixer slider.

I have used views slide show and some other js files for cycle.

**Edit**: Here is a screenprint of the view I defiined so far:

# Answer
> 3 votes
First you need create a content type for your slider (`admin/structure/types/add`), let alias it `slider`, then add your desire fields to it ( maybe a image field and title as a slider slogan ), then create a image style for your slider in `admin/config/media/image-styles/add` ( create a image style according to your slider image in your design), then in views change filter to show only images form slider content type.

For more details do "How to Build Drupal 8 Slideshows" step by step.

# Answer
> 1 votes
Lets say you have now created a view for your slider , what it does is that when a new article is posted in your site this view fetches article's image out of it and shows it on your slideshow , so an answer for your question is : "create some articles and views will use their images for your slider"

Now the problem is whenever a new article is posted to your site slider image changes , I mean this content type is not exclusive for slider (or it can be if you don't use it for posting articles), to overcome this problem you can follow Zhilevan's instruction to create an exclusive content type for your slider.

you also can use Nivo Slider if you want a fast solution for that. (off course it's not as dynamic and configurable as views slideshow)

# Answer
> 1 votes
> I have created a view and placed an image field in it...

Suitably configured, *Views Slideshow* will display images selected by the related *View*. Depending on how that View is configured, you may need to create some content of a particular *content-type*, or content which meets some other criteria which you defined in the View.

For example: maybe you set the View to filter content on *promoted to front page*. In that case, you will need to make sure that the nodes which you create to hold related images all have the *promoted to front page* option switched on.

Suggestion: Make a copy of the View, or add a *display* to it. There, set the *Format* to some simple option such as *Unformatted list*. Then check that the View displays the expected content. This will help to isolate where the problem is by removing *Views Slideshow* from the equation.

---
Tags: views
---


# Question
Title: Configuring/using Drupal Pathauto module
I am new to Drupal. I just installed Drupal 8 and pathauto module.

Now I need to configure `path patterns` or whatever they are called.

On page https://www.drupal.org/documentation/modules/pathauto they give the path for configuring as:

For 7.x, 8.x: **Administer** \> **Configuration** \> **Search and Metadata** \> **URL aliases**, in the "**Patterns**" tab.

But can't see "Patterns" tab. When I click http://localhost/admin/config/search/path/add I get to a page with a form and 2 fields: 1. Existing system path 2. Path alias

I also tried http://localhost/admin/config/search/path/pathauto and http://localhost/admin/config/search/pathauto but they both give me 'Page not found'.

How do I configure `Pathauto`?

# Answer
A module must be enabled and configured after installing its files.
> 1 votes

---
Tags: 8, path-aliases
---


title: Get user ID from CSRF token

text:
# Question
Title: Get user ID from CSRF token
Is there any way how can I programmatically get user ID from CSRF token? I'm using web service and need to update user data according to user token.

# Answer
> 0 votes
1. Create a view with contextual filter CSRF and field UID.
2. Get the view programmatically

$view\_object = views\_get\_view("view\_name");

Then we set the view display that we want to process.

```
$view_object->set_display("my_display");

```

Other methods can be used to customize the we way the view will be processed like set\_items\_per\_page or set\_arguments... A full reference of these methods can be found here: https://api.drupal.org/api/views/includes!view.inc/class/view/7. You have to use the set\_arguments to add the CRSF key as a contextual reference to the view

Before processing the view using the execute method, it's recommended to run the pre\_execute method.

```
$view_object->pre_execute();
$view_object->execute();

```

The results of the processed view are stored in the result property

```
$results = $view_object->result;

```

If you need the rendered results, you can go further and render the view.

```
$output = $view_object->render();
print $output;

```

Thxs to reference: https://blog.cloudtroopers.com/programmatically-fetch-results-view-drupal-7

# Answer
> 0 votes
I figured it out by using `global $user;` and then I don't need to use access token from session, just `$user->uid;`

Thanks anyway

---
Tags: 7, users, csrf
---


# Question
Title: How to get the correct reference to this item?
I'm writing a hook for a form but do not get the correct reference. What do I wrong?

```
  if($form_id == "entityqueue_subqueue_edit_form") {
    foreach ($form[eq_taxonomy_term][und][items] as $row => $rowinfo) {

      dpm($rowinfo[target_id]);
      if ($rowinfo[target_id][value] == 94){

        unset ($form[eq_taxonomy_term][und][items][$row]);
      }
    }
  }

```

# Answer
The correct reference is:

```
  if ($rowinfo['target_id']['#value'] == 94)

```
> 1 votes

---
Tags: nodes
---


# Question
Title: How to hide custom fields on the registration form?
I have added a lot of fields in the user profile, and sorted them using Gield Groups module tabs. Аnd now when registering the user, on the register form appears all fields and field groups tabs.

How can I hide all custom field and tabs on registration form and leave only email and one of custom field? Or can I create custom registration module with custom module?

# Answer
You can configure the registration form in "Manage form display" of the "Account settings":

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

Go to the bottom of this page and in "Custom Display Settings" enable the use of custom display settings for the "Register" form.

Then you get a tab "Register" at the top of the page. Here you can configure which fields are displayed.
> 7 votes

---
Tags: users, 8
---


# Question
Title: Why am I getting undefined is not a function when using jquery?
HTML

more code here...

```
<script type="text/javascript" src="//code.jquery.com/jquery-1.10.2.min.js"></script>
<script type="text/javascript" src="https://example.com/sites/all/modules/ac_modules/ac_exercise/ac_exercise.js?nkuo2r"></script>

```

more code here...

```
<div class="form-item form-type-textfield form-item-time-start">
  <label for="edit-time-start">Time Start </label>
 <input type="text" id="edit-time-start" name="time_start" value="11:28:12" size="4" maxlength="8" class="form-text" />
</div>

```

more code here...

Javascript - ac\_exercise.js

```
$(document).ready(function(){
  $("#edit-time-start").on("change paste keyup", function() {
     alert($(this).val());
  });
});

```

In Chrome's console I get the following error: **Uncaught TypeError: undefined is not a function - ac\_exercise.js?nkuo2r:1** which is this line of code:

```
$(document).ready(function(){

```

# Answer
```
(function ($) {
  $(document).ready(function(){

  your code here

  });
})(jQuery);

```
> 3 votes

# Answer
jQuery needs to be wrapped and passed in an anonymous closure like this in Drupal 7.

If you are writing code that needs to fire the document is ready, you could evaluate if you should make it a Drupal behavior or not.

```
(function ($) {
  $(document).ready(function(){

    $("#edit-time-start").on("change paste keyup", function() {
      alert($(this).val());
    });

  });
})(jQuery);

```
> 3 votes

# Answer
Please check your current JQuery library may not have any conflicts.

However, you can use the JQUERY at the bottom. Please refer this article
> -1 votes

---
Tags: javascript
---


title: No URLs in dashboard

text:
# Question
Title: No URLs in dashboard
After installing Drupal I cannot use the dashboard menu because none of the URLs are found. I cannot google my way to find a solution to this so.

# Answer
> 0 votes
Check that the .htaccess file exists in the Drupal root. Sometimes people unzip/untar or copy paste Drupal directories and this file is excluded by some operating systems and file transfer programs.

Drupal 7 .htaccess: http://cgit.drupalcode.org/drupal/tree/.htaccess?h=7.x

Drupal 8.2.x .htaccess: http://cgit.drupalcode.org/drupal/tree/.htaccess

This is usually the cause of what you report.

Otherwise, this could be an issue with how Apache or IIS is setup to serve your Drupal site. Since you can really get in the weeds with server configurations such as Apache, it is recommended you use something like Acquia Dev Desktop or DrupalVM to install and run a Drupal site locally, so you can sidestep issues and run a local site under generally accepted best practices for a LAMP stack tuned for Drupal.

---
Tags: installation, dashboard
---


# Question
Title: Add additional information to a field of a content type
Let's say I have a content type Order. It has two fields:

Product1 with values 1-10 and Product2 with values 1-10. I am looking for a way to assign prices to the fields.

For example:

Product1\*1 = 10

Product1\*2 = 20

...

Product2\*1 = 20

Product2\*2 = 40

So if someone chooses value 2 of Product1 and value 2 of Product2 the system should calculate 40. I will do the calculation with a custom module, I am just looking for a easy way to define these prices.

# Answer
> 2 votes
Some solutions you have:

1) create field Product with multi values to content type Order bases on a table field. Module : https://www.drupal.org/project/tablefield

In this table you can attached the prices and with a custom module do the counting.

2) Create content type Order, create content type Product. In content type Product add a field price. Make a relation to entity from Order to Product.

3) Make use of ubercard. This will define products, cards and as far I can remember the recalculation of the card can be refreshed easily

4) Make use of Drupal Commerce, I know it is possible in there but never used it.

Let me know if you need more details.

# Answer
> 0 votes
I think I understand what you are trying to do - if you are not using Drupal Commerce, you should be. It will do a lot of this for you, including calculating complex products made of compound attributes. I really would not try to do this with a few content types and fields, something is bound to get missed or you will run into edge cases that Commerce has likely already solved.

You can set up a Commerce site even if users are not doing any on-site checkout just to handle product, pricing, and calculating within its commerce engine, Views, and Rules.

There are lots of contributed price and discount style modules for Commerce, give them a look through and see what could suit you:

https://drupalcommerce.org/taxonomy/term/2564

---
Tags: 7, entities
---


title: How get access special field value?

text:
# Question
Title: How get access special field value?
I want to get access to a special field value, do some processing or manipulating on it and then place it back in theme. For example, I've created a custom content type that name is "News" and has a field with below properties:

* **label:** News Number
* **machine name:** news\_num
* **value:** Number (float)

I did content-type node theming with name **node--news.html.twig**, Now I want to understand Is there any preproccessing hook to modify or altering the field value and in addition I want to learn right way for manipulate the field value, I wrote something like below code:

**ThemeName.theme:**

```
function ThemeName_preprocess_node(&$variables) {
// Get access to field value:
  $value = $variables['node']->news_num();
/**
* Makeing some manipulation on $value here.
*/
  $variables['value'] = $value;
}

```
1. The type of operation is not really important; I'm most looking for a solution to learn standard method and general format to access and modify the field value.
2. I just want to overview the field value (alter the field value before rendering) and not doing any override or change the field value in the database.

Any suggestions?

# Answer
I suggest you two solution one based on what you tried to did

## First solution

in `yourthemename.theme`

```
if ($variables['node']->getType() == 'YOUR_CONTENT_TYPE') {
    $variables['My_Field'] = $variables['node']->get('YOUR_FIELD')->value;
  }

```

and in your custom node template

```
   {{ My_Field }}

```

> Tips: Those of **"YOUR\_CONTENT\_TYPE"** and **"YOUR\_FIELD"** are machine names for your content type and your content field.

## **Second solution**

in your **content type node template file** ( I mean if your content type name is News in `node--news.html.twig`) try to add your custom value to it with:

```
  {% set My_Field = node.YOUR_FIELD.value
      {# Make your manipulation here #}
   %}
   {# And then print it back wherever you like with below code: #}
  {{ My_Field }}

```
> 3 votes

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


# Question
Title: How to add a sub-theme for mobile version?
I finished my drupal site, and now I should create the mobile version.First I'm using Bootstrap 3.3.5 with a sub-theme, and drupal 7. I'm sorry I don't know how to explain it but I want like, add a another sub-theme like my existing sub-theme and change on it for mobile with saving all my node and views, thank you.

# Answer
> 1 votes
Create another subtheme (lets call it `mobiletheme` ) and with mobile theme module set your mobile version of site use `mobiletheme`.

> Adds the ability to choose a mobile theme in admin/build/themes/settings which is used for serving users on mobile devices.

another solution is detect and set theme for mobile with themekey module (Check tutorial here: http://mustardseedmedia.com/podcast/episode52 )

> ThemeKey allows you to define simple or sophisticated theme-switching rules which allow automatic selection of a theme depending on current path, taxonomy terms, language, node-type, and many, many other properties. It can also be easily extended to support additional properties exposed by other modules. In combination with Drupal's theme inheritance you can easily achieve features like:
>
> ```
> individually-styled channels
> a front-page / "splash" screen
> a date/time-selected Christmas theme
> mobile themes for different auto-detected mobile devices
> special themes for "limited" or "old" browsers
> content, user, or role -specific themes
> indicating your environment (production, staging, testing, sandbox, … )
> testing your redesign safely on a live server
> ...
>
> ```
>
> And unlike other theme switching modules, ThemeKey should play well with internal and external page caches, like Boost or Varnish, even for anonymous users.

**but really it is heavy module and if you want only want switch to another theme when user surf site with mobile I strongly recommend you to use mobile theme module.**

# Answer
> 0 votes
Just add another theme to your site and setup the mobile devices indicator in the themekey\] module. Themekeys supports:

* mobile themes for different auto-detected mobile devices

---
Tags: 7, theming
---


title: Show current week items is views

text:
# Question
Title: Show current week items is views
I want to create a view which shows all items of the current week based on the publication date. The week starts on Sunday and ends on Saturday. I tried the relative date filter in the Views module with 'between last Sunday and this Saturday' This works. But on Sunday, it shows all the items of the past week, so, on Sunday, the view is not correct. Could anyone help me with an solution?

# Answer
> 2 votes
The key is using **-1 second** So

1. first solution: Use this values

**next sunday - 1 week**

and

**next sunday - 1 second**
2. Second solution based on you told on question :

**last sunday**
and
**this sunday - 1 second**

---
Tags: views
---


# Question
Title: How customize update interval of aggregator module
By default **update inteval** of RSS aggregator in Core aggregator module start form 15 min, I mean 15 min is minimum value,

But I need update RSS aggregator shorter than 15 min,and update my feed each 2,5,10 minute too,

How can I set Update interval to what I required?

one solution is using alternative module like feeds module but it is not stable yet.

# Answer
The update interval values for an Aggregator Feed is hardcoded into the Entity definition for the refresh field. You'll need to alter the definition to allow different values.

In a custom module, you can evoke `hook_entity_base_field_info_alter()` to alter the Feed definition to accept shorter intervals:

```
function MYMODULE_entity_base_field_info_alter(&$fields, $entity_type) {
  if ($entity_type->get('id') == 'aggregator_feed') {
    $definition = $fields['refresh']->getItemDefinition();
    $intervals = $definition->getSetting('allowed_values');
    $intervals = array(
      120 => '2 min',
      300 => '5 min',
      600 => '10 min',
    ) + $intervals;
    $intervals = $definition->setSetting('allowed_values', $intervals);
    $fields['refresh']->setItemDefinition($definition);
  }
}

```
> 1 votes

---
Tags: 8, feeds
---


# Question
Title: How to create a Bean type programmatically?
I'm building a module that creates set of blocks using Bean module. How do I can create a `Bean Type` programmatically in order to be able to create the blocks?

# Answer
> 4 votes
Bean uses ctools plugins for its types. Per the docs:

```
/**
 * Implements hook_bean_types().
 *
 * Beans uses ctools plugins to define the block types.
 * All plugin files must be registered in the .info file.
 */
function hook_bean_types() {
  $plugins = array();
  $plugins['plugin_key'] = array(
    'label' => t('Title'),
    'description' => t('Description'),
    // This is optional. Set it to TRUE if you do not want the plugin to be
    // displayed in the UI.
    'abstract' => FALSE,
    'handler' => array(
      'class' => 'ClassName',
      'parent' => 'bean',
      // This should be pointing to the path of your custom bean plugin module.
      'path' => drupal_get_path('module', 'example_bean') . '/plugins',
      // Class files should be named accordingly in order to support ctools
      // autoloading procedures.
      'file' => 'ClassName.class.php',
    ),
  );
  return $plugins;
}

```

# Answer
> 1 votes
It is pretty simple.

---

```
<?php
$bean = bean_create(array('type' => 'my_bean_type'));
$bean->label = 'Administrative Label';
$bean->title = 'Bean Title';
$bean->delta = 'bean-machine-name';
$bean->field_block_content = array(
'en' => array(array(
  'value' => '<p>Text</p>',
  'format' => 'wysiwyg_editor',
)),
);
$bean->save();
?>

```

# Answer
> 1 votes
From looking at the code in `bean_admin_ui_type_form_submit()` I've put together the following function:

```
/**
 * @param $machine_name
 * @param $label
 * @param string $desc
 */
function create_bean_type($machine_name, $label, $desc = '') {
  $plugin_info = array(
    'name' => '',
    'label' => '',
    'description' => '',
    'type' => '',
    'editable' => TRUE,
    'handler' => array(
      'info_file' => TRUE,
      'class' => 'BeanCustom',
      'parent' => 'bean',
      'file' => 'BeanCustom.class.php',
      'path' => drupal_get_path('module', 'bean_admin_ui') . '/plugins',
    ),
  );
  $bean_type = new BeanCustom($plugin_info);
  $bean_type->type = $machine_name;
  $bean_type->setLabel($label);
  $bean_type->setDescription($desc);
  $bean_type->save(TRUE);
  drupal_flush_all_caches();
}

```

I've not used the `_bean_admin_default_plugin()` function in case this code is running with the bean\_admin\_ui module disabled.

You can use this function like this:

```
create_bean_type('baked_bean', 'Baked Bean', 'A baked bean is a bundle attached to the bean entity type. Also if you eat too many you may fart.');

```

---
Tags: 7, blocks
---