# Question
Title: drupal_goto is not refreshing the webform on submit
I have a webform node. I need the users to fill it and on submit, the user will be redirected to some link.

```
if ($form_id == 'webform_client_form_970') {
    $form['#submit'][] = 'dl_pdf';
}

function dl_pdf(){
        drupal_goto("http://dev.site.com/ar/printpdf/9", $options);
    }

```

When the form is submitted, **drupal\_goto** works ( it actually just downloads a PDF file automatically ) but the form does not get refreshed.

What i have been doing wrong. Any clue?

**Solution:**

```
if ($form_id == 'webform_client_form_970') {
        //$form['#submit'][] = 'dl_pdf';
        drupal_add_js(
            'jQuery(document).ready(function () {
                jQuery(".webform-submit").on("click", function(){
                    var win = window.open("'.dl_pdf().'", "_blank");
                    win.focus();
                });
            });',
        array(
            'type' => 'inline',
            'scope' => 'footer',
            'weight' => 5
            )
        );
    }

function dl_pdf(){
        return "http://dev.site.com/ar/printpdf/9?name=".$userinfo->title."&date=".$course_date."&course_type=off-non-reg&course_name_ar=".$courseinfo->title."";
}

```

# Answer
> 1 votes
If you redirect to a URL that does not return a page but instead returns some other type of resource (such as a PDF in this case), then the current page will not be refreshed, as you have observed, because the response to the form request is returning the PDF, not HTML.

If you want the page to be refreshed as well then a common technique is to return the HTML for the new page from the form, and then redirect again to return the PDF. Because you need the new page to load fully (so the browser renders it), you'll need to use JavaScript to provide the redirect to the PDF. You can have a link in the page as well, to say something like "If the file does not download automatically, click here".

# Answer
> 0 votes
For redirect form after submit you have to implement

```
$form_state['redirect'] = "Your URL"

```

For more information visit here

---
Tags: redirection
---


# Question
Title: How to display multiple blocks using a custom calendar module?
I have created a calendar module in Drupal 7. In addition to the default calendar on the website, my client can create a new calendar for events specific to a particular page.

Say that they want to add "Youth" and "College and Career" calendars; the db table looks like this:

table: churchcal\_calendars

------id------|------name-----|------set\_default------

------1-------------Main---------------1--------

------2-------------Youth--------------0---------

------3-------College and Career---------0-----------

In my churchcal.module file, I have set hook\_block\_info and hook\_block\_view:

```
function churchcal_block_info() {
    $blocks = array();
    $blocks['monthly_calendar'] = array(
        'info' => t('Display the monthly calendar.'),
        'cache' => DRUPAL_NO_CACHE,
    );

    //get calendars
    include('db.php');
    $result = mysql_query("SELECT * FROM churchcal_calendars WHERE set_default != '1'");
        while($row = mysql_fetch_array($result)) {
            $cal_name = $row['name'];
            $sys_cal_name = strtolower(str_replace(' ', '_', $cal_name));
            $blocks['churchcal_' . $sys_cal_name] = array(
                'info' => t('Display calendar for ' . $cal_name . '.'),
                'cache' => DRUPAL_NO_CACHE,
            );
        }

    return $blocks;
}

function churchcal_block_view($block_name = '') {
    if ($block_name == 'monthly_calendar') {
        $content = monthlyCalendar();
        $block = array (
            'subject' => t(''),
            'content' => $content,
        );
    }

        //get calendars
        include('db.php');
        $result = mysql_query("SELECT * FROM churchcal_calendars WHERE set_default != '1'");
            while($row = mysql_fetch_array($result)) {
                $cal_name = $row['name'];
                $sys_cal_name = strtolower(str_replace(' ', '_', $cal_name));
                $cal_id = $row['id'];

                if($block_name == 'churchcal_' . $sys_cal_name) {
                    $content .= churchCal($cal_id);
                    $block = array(
                        'subject' => t('Upcoming Events'),
                        'content' => $content,
                    );
            }

        return $block;
    }
}

```

The "monthly\_calendar" is the main calendar, and there is no problem with that block.

Beneath the monthly calendar is the code for the additional calendars. I can see each calendar in admin/structure/block page (for the example "Display calendar for Youth", "Display calendar for College and Career"). That part works great. However, **I can only see one calendar**, and that is whichever is first in the db with default != 1. In this example, the Youth calendar would display, but not the College and Career. So, it tells me that hook\_block\_info is correct and there is a problem with hook\_block\_view.

How can I display a calendar for each calendar in the db?

# Answer
It looks like you should review that "`return $block;`" that you inserted in the `while()` statement.

PS: not sure why you didn't (couldn't) post your own answer, which is why I do so now anyway ...
> 1 votes

---
Tags: 7, blocks
---


title: Node ID is not appearing

text:
# Question
Title: Node ID is not appearing
I am working on creating a view based on nid in Drupal 8. I cannot find node id or nid listed - I see Entity id. I am trying to set up a contextual filter so only certain node fields (node type B) will show up when node type B's relationship field matches the node alias of node type A. (I am looking at https://www.drupal.org/node/1841004, but the terminology is different for Drupal 8.)

# Answer
> 1 votes
Turns out nid in Drupal 8 is now listed as ID - and it is listed liked this: Title - ID and Category - content. It appears on the view as Content: ID. I put this in Fields and made it hidden. I added a relationship to my other content type. Then for contextual filter I used the Content:ID with the relationship. Under When filter is not available, I picked Provide default value: Content ID from URL. And then the view worked.

---
Tags: views, nodes, 8
---


title: How to invoke AJAX on Vertical Tabs?

text:
# Question
Title: How to invoke AJAX on Vertical Tabs?
My case is simple: When user switches tabs, I want to dynamically fill empty fields in the tab he entered, calculating them from the tab he went from. Like suggesting city by zip code, or address by company name if I have it in database.

Problem is - I can do it on button click or on field's blur, but I'd prefer it to happen on vertical tab switch. Items with `vertical_tabs` type simply does not have `#ajax` property. Is there any neat way around it?

`#states` seemed a solution, but it seems they only support static value set, like:

```
':input[name="foo"]' => array('value' => 'bar'),

```

# Answer
`#states` attributes cannot use to invoke AJAX. See drupal\_process\_states

With your question, i think the solution is write an javascript file and `#attached` it to the form you need.

You can bind a click event to `.vertical-tab-button` element (better) or orverride `Drupal.verticalTab.prototype.focus` function (not recommend).
> 1 votes

# Answer
I would recommend to override `Drupal.verticalTab.prototype.focus` though @Sang Le Thanh said not to do so.

You can apply the default behaviour with your custom logic which will not break any Drupal core function.

```
var defaultFocus = Drupal.verticalTab.prototype.focus;
Drupal.verticalTab.prototype.focus = function() {
    // enter your code
    defaultFocus.apply(this);
}

```
> 0 votes

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


# Question
Title: Custom libraries and dependency injection
I have been using D7 for a while, new to D8; also have a fair amount of experience with Laravel/Lumen and dependancy injection (DI). One of the big sell's of D8 is the new OO structure, and specifically the Symphony DI system.

So to test this out, I want to develop (port some of my old D7 code) to a D8 custom library, that will 'inject' when needed, and I do not want to do this as a module (I got that right; the objective is to have a PHP library class).

Given some of the documentation I read, I created a folder called `/libraries/my_library`, and for the hell of it I added a PSR4 mapping to /composer.json like so:

`"Drupal\\CustomLib\\": "libraries"`

For the record, I tried it without `Drupal\\` as well - makes no difference.

In `/libraries/my_library/scr/myClass.php` I have a single class `myClass`. I also added a my\_library.services.yml

services:

```
  myClass:
    class:   CustomLib\mylibrary\myClass

```

And in my custom theme file I simply tried

```
use CustomLib\mylibrary;

function quirk_preprocess_html(&$vars) {
  $tools = Drupal::service('myClass');
}

```

which results in

`Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException: You have requested a non-existent service`

Can someone point me in the right direction please. What am I missing. I am assuming Drupal is not scanning the /libraries/my\_library folder for the services definition - but how do I get it to do so?

# Answer
> 2 votes
OK people, I played around with a couple of options, but the bottom line is, if you want to create your own 'services' class, specifically for dependancy injection, it has to be tied to a module.

So - I created a custom module. The actual module file is empty

```
<?php

```

Also created the services definition / config file `my_module.services.yml` and then critically, your services class files should go in a sub-folder /src. Since it is a service, you will need an interface and implementation class.

---
Tags: 8, theming
---


title: Add class to field collection wrapper

text:
# Question
Title: Add class to field collection wrapper
I've got a field collection with has a div wrapper with the classes "field-collection-container clearfix" I'd like to add an additional class to this div. How would I go about this?

I've tried this:

```
MYTHEME_preprocess_field(&$variables, $hook){
    if($element['#field_name'] == "FIELD_COLLECTION_NAME"){
        $variables["element"]["#prefix"] = '<div class="field-collection-container clearfix MY_CLASS">'
    }
}

```

But this doesn't seem to have any affect. I'm not sure what else to try, I also found an answer here https://drupal.stackexchange.com/a/142389/39899 but that doesn't seem to do anything either. The code I put above actually runs as I did a var\_dump() and saw the results but when I tried that with the answer I linked to I got nothing.

\[UPDATE\]

Just to clarify, I'm looking specifically to amend the div with the class "field-collection-container" not add another wrapper. The reason being that I think it's just tidier to make use of the markup Drupal already outputs rather than just adding more do it.

# Answer
> 4 votes
The wrapper containing the 'field-collection-container' class is added in field\_collection\_field\_formatter\_view() and because of this it seems that the usual theme functions (e.g theme\_field, templatee\_preprocess\_field and template\_process\_field) are not able to alter the #prefix.

I've found that it is possible to alter the #prefix by altering the field collection field at the point it is attached the the parent entity by implementing hook\_field\_attach\_view\_alter() in our theme (in template.php):

```
/**
 * Implements hook_field_attach_view_alter()
 */
function MYTHEME_field_attach_view_alter(&$output, $context) {

  // First check we're dealing with a field collection field.
  if(!empty($output['field_link_collection'])) {

    // Now check for our specific field collection field.
    if ($output['field_link_collection']['#field_name'] === 'field_link_collection' ) {

      // Alter the prefix.
      $output['field_link_collection']['#prefix'] = '<div class="field-collection-container clearfix MYCLASS">';
    }
  }

}

```

Make sure you replace 'field\_link\_collection' with the machine name of your field collection field.

Field collections are entities themselves (containing fields) as well being fields attached to other entities which is incredibly powerful but I've found to be confusing when trying to alter specific things.

I think that in this case accessing theme\_preprocess\_field doesn't change anything as it's the wrong point in the render chain and the field is instead being rendered through field\_formatter\_view (I'm not certain that this is the case though, it may be more complex).

It might also be useful to look at the Display Suite module as it gives you much more control over the markup Drupal generates.

If you wanted to make this easier in the future, submitting a patch to the field collection module to declare a template in field\_collection\_theme() would help, this issue looks related.

UPDATE

Another method is to change the field display settings (in 'manage display' of the node) of the field collection field from 'field collection items' to 'fields only'. There should still be a wrapper div which you can amend the classes of by doing something like:

```
function MYTHEME_preprocess_field(&$variables) {
  if($element['#field_name'] == "FIELD_COLLECTION_NAME"){
    $variables['classes_array'][] = 'MYCLASS';
  }
}

```

# Answer
> 0 votes
1. Your function missing parameters $variables
2. theme\_field use file template to show html. You can see source . In source don't use variable $element only use $items. So your html don't change anythink.
3. You can add wrapper with overwrite file tpl with suggestions. So easy with file name field--FIELD\_COLLECTION\_NAME.tpl.php and overwrite to html you want.Or can overwrite function theme\_field() (copy to file template.php and clear cache.)

> ```
> function YourTheme_field($variables) {
>   $output = '';
>
>   // Render the label, if it's not hidden.
>   if (!$variables ['label_hidden']) {
>     $output .= '<div class="field-label"' . $variables ['title_attributes'] . '>' . $variables ['label'] . ': </div>';
>   }
>
>   // Render the items.
>   $output .= '<div class="field-items"' . $variables ['content_attributes'] . '>';
>   foreach ($variables ['items'] as $delta => $item) {
>     $classes = 'field-item ' . ($delta % 2 ? 'odd' : 'even');
>     $output .= '<div class="' . $classes . '"' . $variables ['item_attributes'][$delta] . '>' . drupal_render($item) . '</div>';
>   }
>   $output .= '</div>';
>
>   // Render the top-level DIV.
>   $output = '<div class="' . $variables ['classes'] . '"' . $variables ['attributes'] . '>' . $output . '</div>';
>
>   return $output;
> }
>
> ```

# Answer
> 0 votes
I didn't ever want extraneous prefix and suffix HTML around my fields (I'd rather know exactly what's there by writing a template file), so I modified the answer here to scrub them all -- obviously, some people may want their prefixes and suffixes, but if not, this is a way to wipe them out generally without having to specify field-by-field:

```
/**
 * Scrub prefixes and suffixes from fields in output.
 *
 * Implements hook_field_attach_view_alter()
 */
function bartik_field_attach_view_alter(&$output) {
  if (is_array($output)) {
    foreach ($output as &$field) {
      if (isset($field['#prefix'])) {
        $field['#prefix'] = '';
      }
      if (isset($field['#suffix'])) {
        $field['#suffix'] = '';
      }
    }
  }
}

```

---
Tags: 7, entities
---


# Question
Title: content access does not work after changing domain
after designing and developing a website I changed its domain. Now any of the permissions are not working. every thing is OK appearently but the functionality is not OK at all.(I mean all the checkboxes and settings are correct but anonymous users have access to all contents!!)

I am using content access module and check the `Enable per content node access control settings` option in content type setting.

# Answer
> 0 votes
Rebuild the permissions table.

* Go to /admin/reports/status/rebuild
* Or find the link on the status report: Reports -\> Status report and the link is under the Node Access Permissions row.

---
Tags: 7, rules, users, domain-access
---


# Question
Title: How to add a cache context from an existing menu?
I want to update my breadcrumb when the menu structure changes. This did not work:

```
$breadcrumb->addCacheContexts(['route']);

```

Whats the correct way?

Edit: some more context (pun actually intended):

> I have a breadcrumb which adds the menu structure of the current node's menu parents as links. Obviously, when the structure somehow changes, the breadcrumb has to get updated also.

# Answer
Apparently it's:

```
$breadcrumb->addCacheContexts(['route.menu_active_trails:main']);

```

and

```
$breadcrumb->addCacheTags(['config:system.menu.main']);

```
> 0 votes

---
Tags: 8, caching, breadcrumbs
---


title: views information in exposed form hook

text:
# Question
Title: views information in exposed form hook
I am trying to compare views in exposed form but so far there is no way I am getting views information in exposed form. Is there any way to do so? I need to compare view id for theme suggestion.

# Answer
> 2 votes
The view and display of an exposed form are stored in `$form_state`.

```
function mymodule_form_views_exposed_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state) {
  $view = $form_state->get('view');
  $display = $form_state->get('display');
}

```

---
Tags: views, 8, hooks
---


# Question
Title: pm-update fails "sh: --backend=2: command not found"
The pm-download command is working so I can update modules individually, but I can't do it in bulk. Both drush 6.2.0 and 6.1.0 give an error.

The output of `drush up --debug` is the following.

> Bootstrap to phase 0. \[0.01 sec, 2.24 MB\]
> \[bootstrap\] Drush bootstrap phase : \_drush\_bootstrap\_drush() \[0.01 sec, 2.37 MB\] \[bootstrap\] Cache HIT cid: 6.2.0-commandfiles-0-da12a99782b48770f5d9ad8965ca5448 \[0.02 sec, 2.39 MB\] \[debug\] Bootstrap to phase 0. \[0.09 sec, 6.4 MB\]
> \[bootstrap\] Bootstrap to phase 6. \[0.14 sec, 6.4 MB\]
> \[bootstrap\] Drush bootstrap phase : \_drush\_bootstrap\_drupal\_root() \[0.14 sec, 6.41 MB\] \[bootstrap\] Initialized Drupal 7.24 root directory at /path/to/site \[0.16 sec, 7.43 MB\] \[notice\] Drush bootstrap phase : \_drush\_bootstrap\_drupal\_site() \[0.16 sec, 7.44 MB\] \[bootstrap\] Initialized Drupal site default at sites/default \[0.16 sec, 7.44 MB\]
> \[notice\] Cache HIT cid: 6.2.0-install\_profile-66ecfeb9791a023150773849f1550c5d \[0.16 sec, 7.45 MB\] \[debug\] Cache HIT cid: 6.2.0-commandfiles-2-699657487b88e8b0c2ede2984aa12913 \[0.16 sec, 7.45 MB\] \[debug\] Drush bootstrap phase : \_drush\_bootstrap\_drupal\_configuration() \[0.17 sec, 7.47 MB\] \[bootstrap\] Drush bootstrap phase : \_drush\_bootstrap\_drupal\_database() \[0.17 sec, 7.51 MB\] \[bootstrap\] Successfully connected to the Drupal database. \[0.17 sec, 7.51 MB\]
> \[bootstrap\] Drush bootstrap phase : \_drush\_bootstrap\_drupal\_full() \[0.18 sec, 8.14 MB\] \[bootstrap\] Cache HIT cid: 6.2.0-install\_profile-66ecfeb9791a023150773849f1550c5d \[0.37 sec, 26.15 MB\] \[debug\] Cache HIT cid: 6.2.0-commandfiles-5-8aee30ce3a469e89d0725cfb79ceb51b \[0.37 sec, 26.16 MB\] \[debug\] Drush bootstrap phase : \_drush\_bootstrap\_drupal\_login() \[0.38 sec, 26.62 MB\] \[bootstrap\] Successfully logged into Drupal as Guest (uid=0) \[0.38 sec, 26.63 MB\] \[bootstrap\] Found command: pm-update (commandfile=pm) \[0.38 sec, 26.63 MB\]
> \[bootstrap\] Calling hook drush\_pm\_update \[0.71 sec, 26.97 MB\]
> \[debug\] Loading release\_info engine. \[0.9 sec, 29.07 MB\]
> \[notice\] Loading version\_control engine. \[0.9 sec, 29.17 MB\]
> \[notice\] Loading package\_handler engine. \[0.91 sec, 29.19 MB\]
> \[notice\] Executing: wget --version Including /usr/local/Cellar/drush/6.2.0/libexec/commands/pm/updatecode.pm.inc \[0.93 sec, 29.21 \[bootstrap\] MB\] Calling hook drush\_pm\_updatecode\_validate \[0.94 sec, 29.31 MB\]
> \[debug\] Returned from hook drush\_pm\_updatecode\_validate \[0.94 sec, 29.31 MB\] \[debug\] Calling hook drush\_pm\_updatecode \[0.94 sec, 29.32 MB\]
> \[debug\] Cache HIT cid: 6.2.0-alias-path--2c8463220c4fed24dfb54242bc0f682e \[0.94 sec, 29.36 MB\] \[debug\] Backend invoke: --backend=2 --verbose --debug --root=/path/to/site \[command\] --uri=site.local pm-updatestatus 2\>&1 \[1.26 sec, 29.37 MB\] --backend=2 --verbose --debug --root=/path/to/site --uri=site.local \[notice\] pm-updatestatus 2\>&1 \[1.26 sec, 29.38 MB\] Illegal string offset 'site' backend.inc:1013 \[1.27 sec, 29.38 MB\]
> \[warning\] The command could not be executed successfully (returned: sh: --backend=2: command not found \[error\] , code: 127) \[1.27 sec, 29.38 MB\] Returned from hook drush\_pm\_updatecode \[1.27 sec, 29.36 MB\] \[debug\] Changes made in drush\_pm\_updatecode have been rolled back. \[1.27 sec, 29.37 MB\] \[rollback\] Command dispatch complete \[1.27 sec, 29.34 MB\]
> \[notice\] Returned from hook drush\_pm\_update \[1.28 sec, 27.27 MB\]
> \[debug\] Command dispatch complete \[1.28 sec, 27.24 MB\]
> \[notice\] Timer Cum (sec) Count Avg (msec) page 1.113 1
> 1113.33 Peak memory usage was 31.64 MB \[1.28 sec, 27.24 MB\] \[memory\]

The issue happens under OS X Mountain Lion and PHP 5.4.20, and continued after upgrading to Mavericks.

# Answer
> 2 votes
This is happening because Drush is trying to find the local Drush executable via `$drush = realpath($_SERVER['argv']['0']);`. In this context, realpath is returning FALSE, because $\_SERVER\['argv'\]\['0'\] does not exist.

As a workaround for this particular problem (which is that pm-update cannot call updatedb), you could run `drush pm-updatecode` followed by `drush updatedb`.

### Note

If you work around the problem instead of solving it, you will also run into this same issue with other commands, such as sql-sync.

# Answer
> 0 votes
I used `drush pm-updatecode --debug` from inside the Drupal root and it shows the failure. I think drush can't find out where it is. The first line of the output is this: "C:\Users\dj\AppData\Roaming\Composer\vendor\drush\drush\drush" --backend=2 --verbose --debug --root="E:\DJs Documents\public\_html\Drupal\_80" --uri=http://default

The "default" seems to be the problem. Also,

```
drush ev 'return $_SERVER['argv']['0']);'

```

returned nothing (no error either).

---
Tags: drush
---


# Question
Title: 404 when using named placeholders for variable parts of Panels path
I'm creating a landing page using a custom content type in Drupal 7, I've set up the views and had everything working correctly, but then I decided to change something at the last minute and add named placeholders to my URL. For some reason I'm receiving a 404 when calling the specific URL. Do I have to do anything specific to my contextual filters in views or in Contexts, so that the URL actually works?

I have this set for my landing page /publications/magazine/2014/SPRING (/Publications/Magazine/%field\_year/%mag\_issue) I have a custom date format set to year only for the date field and have a taxonomy vocabulary called seasons (fall, winter, spring summer)

For my contextual filter, I have Content: Has taxonomy term ID using Raw Value with the specific vocabulary set, one of my views requires this. That's really the only unique thing here. I'm working locally at the moment, so i dont have a url, but any suggestions would be helpful, spending 3 hours so far trying to figure this out.

# Answer
> 3 votes
For others who find this question and have similar scenario make sure for your arguments you set your context up properly, for mine I had context set to Taxonomy term ID, instead of the Name and as soon as I changed it to name and saved it. Cleared Cache, everything worked again.

# Answer
> 0 votes
One additional thing to add is that even if you're not planning on loading a context with the placeholder, you still need to set it to *something* in the Arguments tab in Page Manager.

---

For example, if you just want to pipe it straight into a Views contextual filter in a Views Content Pane:

1. In the Page Manager 'Arguments' tab, set it to "String"
2. In the Views settings page for the Content Pane display of your view, under Argument Input, choose "From Panel Argument"

It'll then stop throwing a 404 error and will pipe the string through to the view as intended.

---
Tags: views, panels, 7, path-aliases
---


# Question
Title: Need to override block.tpl.php in a module
I need to define a block--custom.tpl.php file in a custom module and have that override the theme block.tpl.php.

Here is where I have ended up and it's not working.

Tell Drupal to look in my module:

```
function MODULE_theme_registry_alter(&$theme_registry) {
  $theme_registry['block']['theme paths'][] = drupal_get_path('module', 'MODULE');
  $theme_registry['block']['theme paths'][] = drupal_get_path('module', 'MODULE') . '/theme';
}

```

In `hook_preprocess_HOOK()` suggest a new theme file:

```
function MODULE_preprocess_block(&$variables) {
  $block = $variables['block'];

  if ($block->CONDITION) {
    $variables['theme_hook_suggestions'][] = 'block__MODULE';
  }
}

```

Now, I've created the file in the module's theme/ folder and called it block--MODULE.tpl.php.

I've turned on theme debugging in the settings file by un-commenting out `$conf['theme_debug'] = TRUE;`

Caches have been cleared multiple times. When I load the page I see in the debug comments:

```
<!-- THEME DEBUG -->
<!-- CALL: theme('block') -->
<!-- FILE NAME SUGGESTIONS:
   * block--MODULE.tpl.php
   * block--block--6.tpl.php
   * block--block.tpl.php
   * block--content.tpl.php
   x block.tpl.php
-->
<!-- BEGIN OUTPUT from 'sites/all/themes/THEME/templates/block.tpl.php' -->

```

And as you can see from the debug it is using the theme template file.

How do I get Drupal to select the proper theme file?

# Answer
> 2 votes
The following worked for me:

```
/**
 * Implements hook_theme().
 */
function rals_theme($existing, $type, $theme, $path) {
  $theme = array();
  $theme['block__custom'] = array(
    'render element' => 'content',
    'template' => 'block--custom',
    'path' => drupal_get_path('module', 'rals'),
   );
  return $theme;
}

/**
 * Implements hook_preprocess_HOOK().
 */
function rals_preprocess_block(&$variables) {
  $block = $variables['block'];
  if ($block->bid == 3) {
    $variables['theme_hook_suggestions'][] = 'block__custom';
  }
}

```

and succesfully uses my module-folder-located template file for rendering the block with bid == 3.

Good luck in any case!

---
Tags: 7, theming
---


title: Preprocess Panels or Panelizer content

text:
# Question
Title: Preprocess Panels or Panelizer content
I am trying to change output of some of the fields used inside my panelizer content, i.e node pages, but hook\_preprocess\_page( &$vars) is showing the output as rendered #markup and i just cant get hold of the render-able array for my content?any help please?

# Answer
> 4 votes
There is a template\_preprocess\_panels\_pane

```
/**
 * Implements preprocess_panels_pane().
 */
function YOURTHEME_preprocess_panels_pane(&$vars) {
}

```

Documentation

If you want to change the output of a field you have:

```
/**
 * Implements hook_panels_pane_content_alter().
 */
 function YOUR_MODULE_panels_pane_content_alter($content, $pane, $args, $contexts) {
  $content ...
}

```

# Answer
> 1 votes
I know it is an old question but anyone still looking for answer for this, here goes. Looking at function template\_preprocess\_panels\_pane in panels.module file:

```
$vars['content'] = !empty($content->content) ? $content->content : '';

```

$content is not an object anymore.

I saw a nice solution here. According to this all you have to do is use hook\_theme and set override preprocess functions to true. This way you can copy paste the original function and use it as a way to override. Let me know if you need any more help in this.

# Answer
> 0 votes
I can confirm that hook\_panels\_pane\_content\_alter() works with Panelizer fields (that could not be modified with hook\_node\_view or hook\_ctools\_render\_alter).

You use $contexts to determine the content type and raw field values and modify $content to modify the rendered output e.g. here I modify the formatting of a rendered price with the currency module API taking the 3-letter currency code from a different custom field.

```
/**
 * Implements hook_panels_pane_content_alter().
 */
 function custom_example_panels_pane_content_alter($content, $pane, $args,  $contexts) {
     if(isset($contexts['panelizer']->data->type) && $contexts['panelizer']->data->type = "your_content_type") {
         if ($content->subtype == 'node:field_your_content_type_price' && isset($content->content[0]['#markup']) && isset($contexts['panelizer']->data->field_roomshare_price['und'][0]['value']) && is_numeric($contexts['panelizer']->data->field_your_content_type_price['und'][0]['value']) && isset($contexts['panelizer']->data->field_your_content_type_currency_type['und'][0]['value']) && strlen($contexts['panelizer']->data->field_your_content_type_currency_type['und'][0]['value']) == 3) {
            $currency = currency_load($contexts['panelizer']->data->field_roomshare_currency_type['und'][0]['value']);
            if ($currency) {
                $amount = $contexts['panelizer']->data->field_your_content_type_price['und'][0]['value'];
                $formatted = $currency->format($amount);

                $content->content[0]['#markup'] = $formatted;
            }
            }
    }
}

```

---
Tags: theming, panels
---


# Question
Title: How to delete all data in one field of a particular content type?
We have a content type basic page that has a Date field (field\_bp\_date). We want to use the hook\_update to delete all data in this field. We are having trouble figuring out what is the best way to simply delete all data in the field\_bp\_date field on the basic page content type?

Ideally we would like to do the following:

```
function mymodule_update_7001(...) {
    $content_type = 'page';
    $fieldDataToDel = 'field_bp_date';

    //some function/hook to delete all the data
    ....
}

```

# Answer
> 3 votes
If you only need to do this once you could use Views Bulk Operations https://www.drupal.org/project/views\_bulk\_operations

/admin/structure/views

1. Click "Add new view" link
2. Show "Content" of type "YOUR\_CONTENT\_TYPE"
3. Click "Continue & Edit" button

Under the FORMAT section change Show: click 'Content' change to 'Fields'

1. Click 'Apply' button
2. Click 'Apply' button again

Under FIELDS section click the 'Add' button

1. Checkmark 'Bulk operations: Content'
2. Under SELECTED BULK OPERATIONS choose 'Modify entity values' checkbox
3. Scroll down a little, you will see OPERATION SETTINGS choose that date Field you want to edit.
4. Click 'Apply' button
5. Click 'Save' to save that View

Go to the View Page you just created.

1. Under Operations choose 'Modify entity values'
2. Select one or all of them (I suggest you do one as a test).
3. Click the 'Execute' button. This page will allow you to set the Date to anything you want, even nothing. TIP! for Date if you want no date you need to change all values to blank. You can't delete just the hours, you need to set all of them to blank, which gives you the result you requested.
4. Click the 'Next' button.
5. Click the 'Confirm' Button.

Congrats. Go back and run it on all of them, if it went as expected on the one test node.

# Answer
> 1 votes
You can just run a mysql delete command. As this is a date field, there aren't any dependencies on other tables.

```
function mymodule_update_7001() {
  db_query("DELETE FROM field_data_field_bp_date WHERE entity_type = 'node' and bundle = 'page'");
  db_query("DELETE FROM field_revision_field_bp_date WHERE entity_type = 'node' and bundle = 'page'");
}

```

**Note**: You would only want to use this approach if you felt certain that there weren't any other modules that needed to react to that data.

---
Tags: 7, entities, hooks, datetime
---


# Question
Title: How can I get the taxonomy title from its machine name? (drupal 7)
I am trying to get the taxonomy name which I already got its machine name. The content type "manage field" looks like following image:

Right now, I already got the value "field\_application\_type." How can I get the lable "application type"(in the red circle) for this machine name(in the blue circle)?

# Answer
The correct way to obtain a Label of a taxonomy vocabulary would be something like this:

```
$vocabulary = taxonomy_vocabulary_machine_name_load('machine_name');
echo check_plain($vocabulary->name);

```

However, looking at your screenshot, I guess you actually want to have the field Label of the taxonomy reference field.

In that case your question is a duplicate of How do I get a field label by the field name?
> 1 votes

---
Tags: taxonomy-terms
---


# Question
Title: How do I ignore a module .git directory?
I've got a Drupal 8 installation that I manage with Drush 8.1.2, with nothing in that installation in Git except a custom module I am writing (module directory = location of `.git` directory = `/sites/all/modules/mymodulename`).

Whenever I do a `drush pm-update` it complains about my module:

> Project was not packaged by drupal.org but obtained from git. You need to enable git\_deploy module

I don't see how I can follow the suggestion of `git_deploy` which, as far as I can tell, provides an update source for modules checked out of drupal.org... so how can I let Drush know that my module is a stand-alone Git installation, and stop it from generating that warning every time?

The `--lock` option to `drush pm-update` is probably not appropriate, since my module is neither a core or a contrib module, and it doesn't change the warning in any case. The only thing I've found to make that warning go away is to delete or rename the module's `.git` directory.

**p.s.**, one thing I noticed later: the warning also goes away if the module is uninstalled: probably because uninstalled modules aren't checked for upgrades.

# Answer
Your analysis is correct; git\_deploy is only useful for projects that are ultimately hosted on drupal.org. The pm-\* commands only operate on drupal.org projects, and have no facility for ignoring projects from other sources. This is a limitation of Drush; improvements in this area would be welcome.
> 1 votes

---
Tags: drush, version-control
---


# Question
Title: In Drupal 8 module creation, why don't I have to put the directories "modules" and "src" in the namespace of my yaml file?
I watched a tutorial on Drupal module development, and the namespace he used didn't include modules or src in the yml file (it is around 4:30). I'm sure this is a basic PHP question, but why didn't he have to put in those directories?

# Answer
> 7 votes
"Why", in a general sense, is for convenience. Drupal 8 uses PSR-4 autoloading and maps the respective module namespaces to each module's src/ directory. See drupal\_classloader\_register():

```
function drupal_classloader_register($name, $path) {
  $loader = \Drupal::service('class_loader');
  $loader->addPsr4('Drupal\\' . $name . '\\', \Drupal::root() . '/' . $path . '/src');
}

```

---
Tags: 8
---


# Question
Title: I'm using CiviContribute and need CAPTCHA
I'm new to Drupal and CiviCRM. I work mostly with Blackbaud/NetCommunity. I'm operating a website that using CiviContribute for donations. Our Payment Processor is Paypal Payments Pro.

I'm trying to add in a CAPTCHA or verification method to our donation part. I can't find how to add a CAPTCHA or any verification to the donation form. I don't see any customizable options on the payment page.

Is it possible to add a CAPTCHA on a CiviContribute donation form?

# Answer
> 0 votes
You should probably be asking this on the CiviCRM stack.

You can set a catpcha on a Profile. So check which Profiles you have set for the Contribution page. Then edit the Advanced settings for that Profile where you can set captcha.

Check answer here too

---
Tags: security, payment-gateways, civicrm
---


title: Meta title content based on node fields

text:
# Question
Title: Meta title content based on node fields
Is there a module that will allow me to set the default meta title for a content type to be the title field of the node displayed?

# Answer
Yes that module would be Metatag
> 0 votes

---
Tags: meta-tags
---


# Question
Title: Getting the pretty value of a Select field in Node twig template
I would like to get the pretty value from a field in my content.

Here is the structure of the select box field when I add a content :

```
00|Ground
01|Apartment
02|House / Cottage
03|Business premises
06|Attachments

```

In my node--*content-type*.html.twig, when I call the field with :

```
content.field_*machine_name*.value

```

It display the key of the selection (00, 01, 02,...). I would like to have Apartment, House / Cottage, ....

When I call just this :

```
content.field_*machine_name*

```

It display the pretty value but wrapped in a div that I don't want.

# Answer
> When I call just this :
>
> ```
> content.field_*machine_name*
>
> ```
>
> It display the pretty value but wrapped in a div that I don't want.

This is the correct way, you should if possible render a field in node twigs like this.

The div, that you don't want, is probably in the field twig, that gets invoked by using `{{ content.field_*machine_name* }}`.

You have to put a copy of `field.html.twig` in your theme and name it:

`field--field_*machine_name*.html.twig`

And look there for the div.
> 3 votes

# Answer
Try adding the "raw" filter:

```
{{ content.field_examplefield|raw }}

```

Also, make sure to hide label at

/admin/structure/types/manage/example\_content\_type/display
> 0 votes

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


# Question
Title: Redirect taxonomy term page links to a View page's exposed filter
I'm trying to make every taxonomy term page link direct to a pattern like this:

> /viewpage?\[term:vocabulary\]\[\]=\[\[term:tid\]\]

So, for example instead of `material/bronze` where bronze has term id 7, you'd have:

> /viewpage?material\[\]=7

...and you'd go to a views page where the user could then turn off the materials filter and turn on other filters.

I've tried setting this pattern up using PathAuto at `/admin/config/search/path/patterns`, which does the opposite of what I want: while it does make links to a taxonomy page point to URLs that look like `viewpage?material[]=7`, it then intercepts these and sends them to the default taxonomy term page, breaking the exposed filters!

I've tried using Global Redirect, but it doesn't seem able to apply patterns, it seems I'd need to enter the redirects by hand which isn't sustainable.

**Redirect Tokens** module looks to be designed to do what I want, and even has an example very similar to my case but with users not taxonomy and facets not exposed filters, but on closer inspection a) it only accepts tokens in the "from" field not "to" and b) it only works with global tokens like current user.

I've figured out that it's potentially possible using cTools **Page Manager**:

* Enable and edit the Taxonomy View page
* Set it the HTTP Response Code variant
* Select 301 redirect then input the new URL...

...but I'm not sure how to inject the \[tid\] into the new URL pattern. The help text says "You may use keyword substitutions from contexts" but there doesn't seem to be any way to view or edit contexts for a page override.

How can I bulk redirect all current and future URLs of taxonomy term pages to this exposed filter view?

# Answer
After some trial and error and guesswork I've got it working using **Page Manger** (part of the cTools module):

1. Under Structure \> Pages, Enable and Edit the Taxonomy View page - if there isn't one, you might need the Page Manager Existing Pages module
2. Create a "HTTP Response Code" variant
3. Select "301 Redirect"
4. For the default pattern, enter something like:
> pagename?%term:vocabulary:machine-name\[\]=%term:tid
5. Test this. There might be cases where the field name stub used in the exposed filter doesn't match the actual vocabulary machine-name and where editing this in Views isn't a good option. For example, I had one field named "colours" not matching its underlying vocabulary "colour". You might also have exposed filters using strings like `field_fieldname_tid` which you might have reasons to not change. If this happens:
    1. Go back to "Summary" in Page Manager for this override
    2. Click "Add new variant"
    3. Give it a sensible admin title (e.g. the vocabulary name) else you'll hit an error later on as it'll match the default name
    4. "HTTP response code" again, and tick "Selection rules"
    5. Choose an appropriate selection rule (probably, "Taxonomy: Vocabulary", then tick the awkward vocabulary), continue
    6. Choose 301 redirect again, and enter the same pattern as before but with the token `%term:vocabulary:machine-name` replaced with the string used by the exposed filter, for example `pagename?colours[]=%term:tid`
> 0 votes

---
Tags: views, uri, path-aliases, redirection
---


# Question
Title: Wrap teasers in a div (simple taxonomy page, no views)
I would like to know if there is a way to wrap the nodes teaser in a without using jQuery.

Basically, this is how the DOM is :

```
<div id="block-system-main" class="block block-system"> <!-- printed by the page.tpl.php -->
    <div class="term-listing-heading">
        term description, others custom fields…
    </div>
    <div class="node-teaser">teaser content</div>
    <div class="node-teaser">teaser content</div>
    <div class="node-teaser">teaser content</div>
<div>

```

What I want :

```
<div id="block-system-main" class="block block-system"> <!-- printed by the page.tpl.php -->
    <div class="term-listing-heading">
      term description, others custom fields…
    </div>
    <div class="wrap"> <!-- put a wrapper here -->
        <div class="node-teaser">teaser content</div>
        <div class="node-teaser">teaser content</div>
        <div class="node-teaser">teaser content</div>
    </div>
</div>

```

I'm using Display Suite for a better customization, I checked all the tpl files, but I found nothing…

Thx :)

# Answer
**Using template.php and hook\_preprocess\_page()**

```
function THEMENAME_preprocess_page(&$variables) {
  if (arg(0) == 'taxonomy' && arg(1) == 'term' && is_numeric(arg(2))) {
    $variables['page']['content']['system_main']['nodes']['#prefix'] = '<div class="here-is-your-div">';
    $variables['page']['content']['system_main']['nodes']['#suffix'] = '</div>';
  }
}

```

So what this does is checks if the URLs match the condition /taxonomy/term/%term-id then if it's satisfied then it adds a prefix and a suffix that are to be rendered by `<?php print render($page['content']); ?>`.
> 2 votes

# Answer
Like many other things in Drupal, why this isn't something that was accounted for is beyond me. Here's an alternative approach that seems a little cleaner to me than the accepted answer. I don't like messing with prefixes/suffixes, and it bothers me when I can't access a template directly.

Add some additional template suggestions to nodes based on view mode:

```
THEME_preprocess_node(&$vars) {
  $view_mode = $vars['view_mode'];
  $vars['theme_hook_suggestions'][] = 'node__' . $view_mode;
}

```

Then you can have templates for 'node--full.tpl.php', 'node--teaser.tpl.php', etc., like it should probably do by default.
> 0 votes

---
Tags: theming, taxonomy-terms, nodes
---


title: Contextual filter using taxonomy alias

text:
# Question
Title: Contextual filter using taxonomy alias
I have a list of nodes that I want to attach as a block to another node using a contextual filter. Depending on the URL alias I want a specific node to be attached to it. The problem is that I want the contextual filter to be based on a taxonomy alias as oppose to a taxonomy ID.

I looked at this solution: Contextual filter with a block view and this one: Views contextual filters taxonomy name and I'm close however the second solution has an option that I can't find on my version. It reference a `Filter Value Type` option which would allow me to `Term name converted to Term ID`. This is exactly what I need, however I can't find this option.

I followed the instruction step-by-step; I tried creating different View and display versions, different items as my Contextual filter but nothing works.

These links are from 2011 and 2012, respectively. I'm using Drupal 8, so I'm wondering if this option has been removed or replaced with some other way to accomplish this task. Either way, I'd appreciate it any help.

Thanx

# Answer
I got it to work by adding a relationship to a taxonomy field that exposed the taxonomy name. Then on the Contextual Filter I followed what the links said in regard to `Specify validation criteria`. But since I still can't find the `Filter Value Type` option, I just set the Case option to `Capitalize each word` and in the More section I checked the `Transform spaces to dashes in URL` option.

This allowed the value in the URL (which was a URL alias) to match my Taxonomy term field.

I don't know if there's an easier way to accomplish this and I'd still like to know why I couldn't find the `Filter Value Type` option, but at least it's working.
> 2 votes

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


# Question
Title: Why do the database functions return all fields as strings?
```
db_select('my_table', 'a')
   ->fields('a')
   ->condition('a.campaign_id', $entity->campaign_id)
   ->execute()
   ->fetchObject();

```

my\_table has some columns that are integers, but the query above returns strings.

Why does this happen? It seems strange to me that the query ignores the column types.

# Answer
The `DatabaseStatementBase::fetchObject()` method is inherited from PHP's `PDOStatement::fetchObject()` which returns the object columns as strings. Given that not all RDBMS's have the same set of types & PHP isn't a strongly typed language, it was probably decided to return everything as strings since it's a base datatype that can be relied on.
> 2 votes

---
Tags: 7, database
---


# Question
Title: Drupal 7, login, "form_build_id" not used?
I write some functional tests for my website. I have this test :

* go to login page
* post username/pass/form\_build\_id
* check if the user is connected

In the test script, my form-build-id is "hardcoded". So, I run the connection test severals times and...The user connects each run (whereas the form-build-id does not change)

I don't understand, why the form-build-id is ignored ? I check with my web browser, each time I refreshed my page, the form generate a new form-build-id.

# Answer
As `drupal_prepare_form()` notes:

> The form\_build\_id is used as key to cache a particular build of the form. For multi-step forms, this allows the user to go back to an earlier build, make changes, and re-submit.

More than anything else, `form_build_id` is for maintaining the form state through page requests. As you can see in some of the core processing functions (e.g. `drupal_build_form()`, `drupal_rebuild_form()`, & `drupal_process_form()`), `form_build_id` isn't required for form processing.

In some instances (e.g. multi-step forms) breaking the `form_build_id` would break the behavior of the form since there is previous data to retrieve, but for the login form there's no state needed to be preserved.
> 1 votes

---
Tags: 7, users, testing
---


# Question
Title: How to change webform default email address from sender side?
I'm using webform module, when somebody submits the form mails will go from address which we mentioned in the custom field, this works fine.

But instead of adding in custom field, I want to change the default from email address. Is there any way to do this?

For reference follow this image:

# Answer
> 7 votes
You can usually find a configure link in the module list.

Looks like in `/admin/config/content/webform`

and scroll down to default e-mail values.

(For Drupal 6, go to yoursite.com/admin/settings/webform)

---
Tags: 7, webforms, emails
---


title: One time password

text:
# Question
Title: One time password
I am using profile2 module for user registration.How to create one time password when user is register. Is there any module for this?

If i want to create it by custom then how to do it.Please help me if any body knows.

# Answer
> 1 votes
It seems you're looking for the Login One time module

> Login one time provides the ability to email one-time login links to users. You can also choose the pages they will land on.

Similar module is One-time login

> This module adds two operations to the form at Administration \>\> People: "Send one-time login link to the selected users" and "Download CSV of one-time login URLs for the selected users".

# Answer
> 0 votes
This module OTP Verification helps you, One registration with phone number, it sends you OTP via SMS to verify, SMS gateways are plugable.

---
Tags: users
---


# Question
Title: How do I filter a view based on a multilingual alias?
I have a view with a contextual filter which builds a page based on a product's model number. The path is /support/%, where % is the contextual filter for the model number.
This works fine for English content. I would like additionally take a path of /assistance/% for French content. How can I have one view with two, or variable paths?

# Answer
> 1 votes
You can not two views with same path. You need to create copy of the view and change its path.

For french language you need to use filters? When you create your view, you add a new filter and select "Node translation" from the "Groupes" list and the check "Node translation: Language" and click "Add". Then you can chose language(s) on which you want the view to show.

---
Tags: i18n-l10n, views
---


title: Ajax form an multi-select

text:
# Question
Title: Ajax form an multi-select
I have a form which provides select2 when the select1 is changed. However I would like select2 to be a multi-select. I can't seem to get this to work. It populates a single select input just fine, but not the multi-select. Any tips would be appreciated.

```
public function buildForm(array $form, FormStateInterface $form_state, $options = NULL) {
  $form['expeditions'] = [
    '#type' => 'select',
    '#title' => $this->t('Choose Project'),
    '#empty_option' => $this->t('Select a project'),
    '#default_value' => '',
    '#options' => $options,
    '#ajax' => [
      'callback' => '::getDeployments',
      'wrapper' => 'deployment-wrapper',
    ],
  ];

  // Disable caching on this form.
  $form_state->setCached(FALSE);

  $form['deployment_wrapper'] = [
    '#type' => 'container',
    '#attributes' => ['id' => 'deployment-wrapper'],
  ];

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

public function getDeployments(array &$form, FormStateInterface $form_state) {
  $expedition_id = $form_state->getValue('expeditions');
  if ($expedition_id != "") {
    $arms_config = \Drupal::config('arms.settings');
    $rest_root = $arms_config->get("arms_rest_uri");

    $client = \Drupal::service('http_client');
    try {
      $result = $client->get(
        $rest_root . 'arms/projects/' . $expedition_id,
        ['Accept' => 'application/json']
      );
      $expedition = json_decode($result->getBody());
    }
    catch (RequestException $e) {
      watchdog_exception('arms', $e);
      drupal_set_message('Error fetching project.', 'error');
    }
  }

  $options = [];

  foreach ($expedition->{'deployments'} as $deployment_id) {
    array_push($options, $deployment_id);
  }

  $form['deployment_wrapper']['deployments'] = [
    '#type' => 'select',
    '#title' => $this->t('Choose Deployment(s)'),
    '#options' => $options,
    '#multiple' => TRUE,
  ];

  return $form['deployment_wrapper'];
}

```

# Answer
It is not possible to create a select element in an ajax callback, because the form builder needs to know about it.

Move all code from ajax callback to buildFrom(). Make this code conditional on form\_state.

Your callback contains only:

```
return $form['deployment_wrapper'];

```
> 0 votes

---
Tags: forms, 8
---


# Question
Title: Entity Metadata Wrapper - check filtered text value is set
I'm seemingly unable to check for the existence of a value of a field if the field in question is set to filtered text. The following code returns an error - and any possible combination I've tried to find online results in the same:

```
if ($wrapper->__isset('body')) {
  print $wrapper->body->value->value();
}

```

The error:

```
EntityMetadataWrapperException: Unable to get the data property value as the parent data structure is not set. in EntityStructureWrapper->getPropertyValue() (line 438 of /Applications/MAMP/htdocs/arch-main/httpdocs/sites/all/modules/contrib/entity/includes/entity.wrapper.inc).

```

To be clear, the node does have the body field, but no content has been placed in it.

Any ideas on how to check for this?

EDIT:

Ok this seems to work, but there must be a better way

```
try {
          print $wrap->body->value->value();
        } catch (EntityMetadataWrapperException $e) {
          // ???
        }

```

# Answer
> 0 votes
> but there must be a better way

If you find it, do share :)

Seriously though, this is what the language gives you; exception handling is what you should use to handle exceptional circumstances, and an entity not having a field that you're expecting it to have would probably class as exceptional in most people's book. It does in mine anyway.

---
Tags: entities
---


title: Flippy Pager No Results

text:
# Question
Title: Flippy Pager No Results
I am using the Flippy Module to build an article pager on a client website.

Everything is working well, but I have encountered an issue where several thousand articles have been imported, many of which without an attached image. This of course disrupts Flippy as it sources its thumbnail from the article content type's image field.

Unfortunately Flippy doesn't appear to have any kind of no results behaviour built-in out of the box.

Anyone else encountered this issue too, or may be able to point me in the direction of a patch that may add this functionality to the module?

I would like to set a default image as a fall-back if no image is found.

TIA.

# Answer
You can use `flippy.tpl.php` template. Copy this template in your theme and modify it what ever you want.

```
$image_arr = array(
        'path' => $file->uri,
        'style_name' => '<Style Name>',
        'alt' => '',
        'title' => '',
      );

print theme('image_style', $image_arr);

```
> 1 votes

---
Tags: 7
---


title: Retain "Last edited by" info

text:
# Question
Title: Retain "Last edited by" info
I would like to keep info on the user that last edited a node. From a little search I found that you can easily obtain that info from the node\_revisions table. But what if you don't want to enable revisions? Is there any other way to get the uid of the user?

I thought of manually adding a field to my content type that will be set to the current's user username. So every time a user hits save that field will store his info. But then I would have to add field permissions to make sure the users don't see or edit this field.

I was hoping for a more out-of-the-box solution. Probably there isn't any otherwise google would have given me the answer. All ideas appreciated. Thank you

# Answer
> 3 votes
You can do that by implementing `hook_node_presave` in your custom module, by something like:

```
function MODULE_node_presave($node) {
  $recent_copy = array_shift(array_values((node_revision_list($node))));
  drupal_set_message('User id of the user who edited latest is '.var_export($recent_copy->uid, TRUE));
  drupal_set_message('Username of the user who edited latest is '.var_export($recent_copy->name, TRUE));
}

```

You can find a detailed solution see: Get the edited node details without enabling node revision in Drupal.

# Answer
> 1 votes
In case you are interested ONLY on the last editor and you are ok to lose the information about who was the original author you can substitute the Author reference with the user that has last edited the node:

* Install and enable the Rules module
* Create a rule that works "After updating existing content of type *\<your content type\>*"
* Add and Action of type "Set a data value"
    + parameter to be set: \[node:author\]
    + value to be set: \[site:current-user\]

After this you can show the Author and it will display the last editor instead.

**Note**: this solution it is not intended to be ok in all the scenario but it has pros and cons that in more than few cases makes it valuable:

**Cons:**

* losing the original Author information

**Pros:**

* no need to enable revisions (so saving database usage)
* no need to do database queries
* no need to change the template files

# Answer
> 0 votes
There is a thread on the drupal site about this: http://drupal.org/node/81242

You will have to run a query from your template file, and it will then return the last username and a link to his/her profile.

---
Tags: users, nodes
---


# Question
Title: Add unique class to webform radio form-item div
Can anyone point me in the right direction to show, how to add a unique class to the webform select options container divs .form-item? I would like to theme these divs surrounding the each radio button with a different background image. I don't really care what the class is, numbers, the key, etc. just as long as I can target it in my css.

# Answer
> 0 votes
You can add particular css while creating that field in webform configuration itself.See below section in your webform

For this particular clas you can add css in your code.

---
Tags: theming, webforms
---


# Question
Title: Correct permissions for a services callback?
I wrote a service that, when called and passed the parameters correctly, creates a node of a certain content type. My service endpoint requires authentication, but so far only the maintenance (user 1) of the site can consume this service correctly, any other user gets an "access denied for user xxx", even if this other users have permissions to create that content type.

The content type is managed by Room Reservations, and I have created that content type with the other users through the webpage.

The service definition:

```
function room_reservations_services_resources(){
$room_service = array(
'room_reservations'=>array(
  'operations' => array(
    'create' => array(
      'help' => 'Book a reservation',
      'file' => array(
        'type' => 'inc',
        'module'=> 'room_reservations',
        'name' => 'includes/room_reservations.service'
        ),
      'callback' => '_room_reservations_book_reservation_service',
          //'access_callback' => 'user access',
      'access_arguments' => array('create room reservations standard','bypass minimum advance booking'),
      'access_arguments_append' => TRUE,
      'args' => array(
        array(
          'name' => 'node',
          'type' => 'array',
          'optional' => FALSE,
          'source' => 'data',
          'description' => 'All the node information to book a reservation',
          ),
        ),
      ),
    ),
    'actions'=>array(
      'get_times'=>array(
        'help'=>'Gets the hours and the days reservations can be made',
        'file'=>array(
          'type'=>'inc',
          'module'=>'room_reservations',
          'name'=>'room_reservations'
          ),
        'callback'=>'_room_reservations_service_get_open_hours',
        'access arguments'=>array('view room reservations calendar'),
        'access arguments append'=>FALSE,
        ),
      'get_reservations'=>array(
        'help'=>'Get the reservations from the current loged-in user',
        'file'=>array(
          'type'=>'inc',
          'module'=>'room_reservations',
          'name'=>'room_reservations'
          ),
        'callback'=>'_room_reservations_user_reservations',
        ),
      ),
    ),
);

watchdog("room_reservations","Ran hook_services_resources",null,WATCHDOG_DEBUG);
return $room_service;

```

get\_hours works without problems, while the create operation only works with the maintenance user of the site.

Callback function:

```
function _room_reservations_book_reservation_service($args){
//crear el nodo, junto con todas las salvedades
global $user;
$response = "";
if (isset($args)) {
// Create the node
$node = new stdClass();
$node->type = 'room_reservations_reservation';
$node->title = $args['nombre'];
//$node->title = 'Prueba random 1';
$node->language = 'es';
$node->uid = $user->uid;
$node->status = 1;
$node->comment = 0;
//node_object_prepare($node);

$node->reservation_date['und'][0] = array(
    'value' => date('Y-m-d', strtotime($args['fecha'])),
    'timezone' => 'America/Bogota',
    'timezone' => 'America/Bogota',
  );

$node->reservation_length['und'][0]['value'] = '60';
$node->reservation_repeat_type['und'][0]['value'] = '1';
$node->reservation_repeat_until['und'][0] = array(
    'value' => date('Y-m-d', strtotime($args['fecha'])),
    'timezone' => 'America/Bogota',
    'timezone' => 'America/Bogota',
  );
$node->reservation_room['und'][0]['target_id'] = $args['sala'];
$node->reservation_time['und'][0]['value'] = $args['hora'];
$node->field_codigo_reservation['und'][0]['value'] = $args['codigo'];
$node->field_email_registro['und'][0]['email'] = $args['email'];

$node = node_submit($node);
try {
  node_save($node);
  $node_id = $node->nid;
  $arrResp['nid'] = $node_id;
  return $arrResp;
} catch (Exception $e) {
  $response = 'Hubo un error, no se creó la reserva';
  $arrResp['error'] = $response;
  watchdog('room_reservations','Error in node creation',(array)$e,WATCHDOG_ERROR);
  return $arrResp;
}
} else {
watchdog('room_reservations','Did not recieve args');
return services_error(t('No se subieron datos!'),406, t('No se entregaron datos!'));
}

}

```

Any help would be appreciated.

# Answer
According to the docs your array keys are named incorrectly, they should be:

```
'access arguments' => array('create room reservations standard','bypass minimum advance booking'),
'access arguments append' => TRUE,

```

With no underscores.
> 0 votes

---
Tags: 7, services
---


# Question
Title: Clean URLs enabled but main-menu keeps replacing clean URL with ugly node/ URL
I have enabled clean URL's on my website and had a menu item in my main-menu that pointed to a View that had a URL alias set up for /ebook-register. I just removed that alias and assigned the same alias up to a page (content item). However now the menu item keeps getting set to node/2 instead of ebook-register. How can I get the menu to stop changing my clean URL into ugliness? If I manually navigate to localhost/ebook-register I get to the right page, and under URL aliases in the admin I can see the alias and confirmed it's pointing to the correct page, and the menu doesn't throw an error when I set ebook-register to the path so it's finding the alias.

It does give me the following message:

> The menu system stores system paths only, but will use the URL alias for display. ebook-register has been stored as node/2.

However, despite saying it will display the clean URL, clicking the link sends you to the ugly node/2 URL.

I am using Drupal 7 and have tried clearing the cache already.

# Answer
> 0 votes
You need to also install the Global Redirect module to handle redirection to aliases.

# Answer
> 0 votes
https://www.drupal.org/project/pathologic will convert node id link to your pathauto pretty links. This will fix it in your menu. Additionally, You can configure it to work with your CKEditor too.

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


# Question
Title: How to point a menu link at a View with multiple options on the same exposed filter selected?
I've got a view page that serves like a catalog, using many exposed filters.

I want a menu link that points to a certain combination of filters. Let's say the URL for this filtered view is\>

> view?option\[\]=7&option\[\]=12&option\[\]=14

Sounds simple, but I'm finding this difficult for a number of reasons:

* Menu considers this an invalid path
* I can't turn it into a path alias, because that also considers it an invalid path
* I can set it up as a redirect, but Menu still won't recognise the redirect as a valid path
* I can set it up as a Page Manager page using cTools' page manager, and set that to act as a redirect, but every parameter except the last one gets chopped and it redirects to this. It seems like it doesn't like the ampersands:

> view?option\[\]=14

* If I input it with the ampersands URL encoded, it gets confused because it double URL encodes the URL encoded characters, breaking them.

# Answer
Got it working. I set it up as a Page Manager page with an arbitrary path (e.g. `options` or `view/options`), set to "HTTP Response Code" then "301 redirect".

The problem in the question where the ampersand-seperated characters were getting eaten seemed to be caused by Drupal treating them as duplicates of each other and rejecting all except the last. To get around that, I set the redirect URL to:

> view?option\[1\]=7&option\[2\]=12&option\[3\]=14

Note how each one has a unique number in the square brackets.

Views doesn't seem to care about the numbers in the square brackets, and they stop Drupal merging the parameters into one.

---

Note you should always input the non-encoded version, like above, else Drupal will double-encode it causing it to break. Keep this in mind if you edit it - you'll need to replace the whole string with the original, non-encoded version then edit that before saving.
> 1 votes

---
Tags: views, uri
---


title: Missing Custom Modules

text:
# Question
Title: Missing Custom Modules
I ran into a database problem that required me to reinstall Drupal on my Localhost. In the process, I've noticed that the custom modules I installed previously are no longer listed. They still reside in `sites/all/modules` and I assumed that they would show up again in my module listing after I reinstalled.

That's not the case. I cleared cache assuming that would help, but, it didn't. I ran `update.php` and that did not help. Is there a way to force Drupal to recognize all of the previously installed modules? Is there a database/table I need to rebuild?

# Answer
> 0 votes
I have resolved this issue. My problem was caused by reinstalling the Bitnami stack. I had assumed that it would install into the previous location. However, that was not the case, as I learned, because it was a newer version. Bitnami installed into an entirely **separate** folder. This meant that Drupal was no longer aware of my custom modules, or, the modules I had installed. My resolution was to copy my custom modules from their prior folder location to the new Bitnami reinstall location (folder). I also had to reinstall the other custom Drupal modules.

---
Tags: 7
---


# Question
Title: Why do I get "Theme hook ... not found" after renaming?
I have a module to create and handle surveys. I made a theme originally for it called "survey" and everything worked fine. I am now trying to rename the theme/template to "questionList", but am getting "Theme hook questionList not found" in the logs.

My working code with the theme name "survey" is shown below.

### survey.module

```
 /**
 * Implements hook_theme().
 */
function survey_theme($existing, $type, $theme, $path)
{
    $variables = array(
        'survey' => array(
            'variables' => array(
                'questions'    => NULL,
            ),
        ),
    );
    return $variables;
}

```

### RadioQuestionController.php

```
    public function getAllQuestions()
    {
        $element['#questions'] = array(1,2,3,4,5);

        $element['#title'] = 'Radio Questions';
        $element['#theme'] = 'survey';
        return $element;
    }

```

### survey.html.twig

```
{#
/**
 * @file
 * Default theme implementation to print list of questions.
 *
 * Available variables:
 *   - questions
 *
 * @ingroup themeable
 */
#}
<h1>Test</h1>

```

The above works fine and prints "Test" to the specified path in my .routing.yml file. However the following does not work.

### survey.module

```
 /**
 * Implements hook_theme().
 */
function questionList_theme($existing, $type, $theme, $path)
{
    $variables = array(
        'questionList' => array(
            'variables' => array(
                'questions'    => NULL,
            ),
        ),
    );
    return $variables;
}

```

### RadioQuestionController.php

```
    public function getAllQuestions()
    {
        $element['#questions'] = array(1,2,3,4,5);

        $element['#title'] = 'Radio Questions';
        $element['#theme'] = 'questionList';
        return $element;
    }

```

### questionList.html.twig

```
{#
/**
 * @file
 * Default theme implementation to print list of questions.
 *
 * Available variables:
 *   - questions
 *
 * @ingroup themeable
 */
#}
<h1>Test</h1>

```

Is there something that I am missing that I need to change other than what is changed in the above code? Or is there something else going on?

# Answer
> 1 votes
```
function questionList_theme(...)

```

must have the name of the module, like :

```
function survey_theme($existing, $type, $theme, $path)
{
    $variables = array(
        'questionList' => array(
            'variables' => array(
                'questions'    => NULL,
            ),
        ),
    );
    return $variables;
}

```

will work.

---
Tags: 8, theming
---


# Question
Title: How to create a module Dependency Graph?
I am running a D7 site with 164 enabled modules. I need to create a module dependency graph so that I can get a better understanding of the module dependencies and find out which modules are critical.

I have checked out https://drupal.org/project/drush\_mm but the page says it is obsolete and not present for D7.

Any alternatives?

# Answer
> 5 votes
There is the sandbox drush module dependency\_analysis

It provides a drush command that produces a dependency graph using graphviz. For me, I found that it was a simple matter of installing graphviz using homebrew:

```
$ brew install graphviz

```

And then follow the project page description.

# Answer
> 2 votes
You are looking for Module Filter, it quickly find the module you are looking for and with filter option and category.

> The modules list page can become quite big when dealing with a fairly large site or even just a dev site meant for testing new and various modules being considered. What this module aims to accomplish is the ability to quickly find the module you are looking for without having to rely on the browsers search feature which more times than not shows you the module name in the 'Required by' or 'Depends on' sections of the various modules or even some other location on the page like a menu item.

Take a look at Enabled Modules (enabled\_modules) module provides lists of all enabled modules on a website.

> These features are useful for moving sites to a whole new code base and rebuilding fresh with only the modules actually in use, or doing clean up on your modules folders.

and also Views System module extends the Views module and allows to create customized lists (pages, blocks) of modules, themes, and theme engines that are or have been installed in Drupal's file system.

Using Drush check this List of all active modules used in a site.

# Answer
> 0 votes
Graph API can do this. After installation, it shows you the Module dependencies at `/admin/modules/graph`.

---
Tags: 7
---


# Question
Title: Search API - Search widget with Facet OR Exposed filters clean url
I'm trying to create "Search API widget" using two exposed filters "search: Full text" + "taxonomy term: City"

The good example of what I want to achieve would be visible here:

```
http://olx.in/

```

Whenever you type in the city + full text search it generates the url such as:

```
http://olx.in/city-name/q-something/

```

However if I use exposed filters it doesnt seem to work in that way it creates links like this:

```
http://localhost/search?search_api_views_fulltext={something}&field_city={taxonomy-term-id}

```

When after I do the search I use facet filter with pretty paths it gives a bit better result:

```
 http://localhost/search/field_city/{name_of_region}/field_city/{name_of_region}/field_city/{name_of_sub_region}/field_city/{name_of_region}/field_city/{name_of_sub_region}/field_city/{name_of_city}search_api_views_fulltext=&field_city=1031

```

But I want the end result pretty much to look like this:

```
http://localhost/{name-of-city}/search-something

```

And after searching I want it to activate proper facets for the "field\_city" so if after searching someone would want to add facet it would not create a {field\_city}/{field\_city}

And in order to do that, I was considering instead of using a "exposed taxonomy term filter" to use facet block for "Field\_city" but no luck so far.

\** Update 01.10.2015 \**

I was doing research and I think that the "cities" and "categories" on OLX or any other decent portal are not actually facets or exposed filters, but they are Taxonomy pages with inherited search query.

1. So if someone types in "Exposed full text search api" a "Yorkshire terrier"
2. He is redirected to: `http://localhost/search?search_api_views_fulltext={Yorkshire terrier}`
3. And on left sidebar he have "Taxonomy menu block" with vocabularies of "small ads categories" with terms such as "animals"
4. He clicks on "animals" term and the search value follows him.
5. `http://localhost/small-ads-categories/animals/search?search_api_views_fulltext={Yorkshire terrier}`
6. Of course the taxonomy is a search api view
7. However I also would want to extend this by adding a second parameter which is "city" \<- not sure how to do that

Another feature that I'm trying to figure out how to create a "select box" for a city that is not a exposed filter but a link parameter.

For example: if someone wants to search for: Yorkshire Terrier + he selects locations from select box to be: London

Normally it is done by creating exposed taxonomy filter - however it generates ugly url, the thing that I'm considering is using the value that is selected to redirect user to the proper search results page. so if he selects Yorkshire Terrier in london he is redirected to:

`http://localhost/london/search?search_api_views_fulltext={Yorkshire terrier}`

Where london is also a taxonomy search api url.

\** update: few hours later \**

After further thinking and trying to solve this issue, using taxonomy terms view block seems like a good idea, but it displays ALL possible terms not only the terms that are related to current search query and that I'm not sure how could I limit ?

# Answer
This module should help you getting rid of ugly URLs when using exposed filters: https://www.drupal.org/project/query\_parameters\_to\_url

> ...
>
> An example of a dirty URL like that could be: example.com/events?field\_category\_id\[0\]=100&field\_category\_id=101&field\_author\_name\[0\]=John
>
> Using this module you can transform the URL into: example.com/events/p/field\_category\_id/0\__100--1\__101/field\_author\_name/John
>
> Or an even shorter URL if you use the provided alter hooks: example.com/events/p/cat\_id/0\__100--1\__101/name/John
>
> Isn't that a joy to look at?
>
> ...

Please refer also to this question to achieve the same thing writing your own module.
> 1 votes

---
Tags: views, uri, search
---


# Question
Title: Best settings for xml sitemap, cron time and submission time?
i have news site for about 7 months.

The site get new feeds every hour but google take about 1 day to index them and only few of them.

I see other sites that instantly index. "1 hours ago etc". Mine newest in google says "19 hours ago"+. And after some errors with sitemap, now i have 0 links last 2-3 days.

So, i wan't to share my configs and you tell me if something is wrong:

1. Feeds module import feeds every hour
2. cron runs every 3 hours
3. xmlsitemap sumbission time to search engines is every 3 hour

`I want to notice that i have arround 130.000 links. I have many feeds who import content. Maby are too much to index? idk`

So, what im doing wrong? PS: Also, every time i submit xml sitemap, i must ping google? if yes, i ping home page or xmlsitemap?

# Answer
The indexing you are having is moderate / typical indeed. Only a small percentage of sites (from the 100% existing in the web right now) are being indexed every hour or so (some sites are indexed once smaller times like 20 minutes or even less - Wikipedia for example could be indexed in 10 minutes or less in some cases).

You should use various Drupal modules to raise the both PageRank and PQS (Page quality score) of your sites pages.

Use wisely the modules MetaTag, AdvAgg, xml sitemap, pathauto, search404, redirect and others to insure you achieve that targets.

More ways to handle that many 404's - Either your could redirect all the nodes to the homepage or groups of them to some nodes with suitable context). Moreover, if you have the spare timenergy or resources you could make redirects to NID's 1x1 for all or most of your links. You could also delete some via WMT and than via robots.txt. It is recommended by some to make redirects not in Drupal but rather directly in the main .htaccess file for better performance.
> 1 votes

# Answer
If the site is largely linking back out to other sites, you may be appearing to be a link-farm and Google isn't going to re-index frequently.

If you have good reasons to be pulling lots of feeds with broken links in them I recommend adding a process that checks the new links before making them public. It'll make your users happier as well as Google.
> 0 votes

---
Tags: cron, xml-sitemap
---


# Question
Title: Unable to loop through all nodes in a content type and load them without hitting memory limits
I'm having an issue in Drupal 8 where I am unable to loop through a large amount of nodes without hitting memory limits. The *products* content type in the below example has ~6000 nodes. The memory limit is currently set to 512M and is not changeable.

I've tried unsetting the `$node` variable and clearing the entity cache in the loop without any success.

```
$query = \Drupal::entityQuery('node')
         ->condition('type', 'product')
         ->execute();
$nids = array_keys($query);

foreach ($nids as $nid) {
    $node = \Drupal\node\Entity\Node::load($nid);
    print $node->title->value;
}

```

The goal is to be able to iterate through all nodes of a content type without hitting memory limits.

# Answer
> 6 votes
I was able to get this to work by using the following command pulled from the deprecated `node_load()` function.

`\Drupal::entityManager()->getStorage('node')->resetCache(array('NID'));`

The fixed script would be:

```
$query = \Drupal::entityQuery('node')
         ->condition('type', 'product')
         ->execute();
$nids = array_keys($query);

foreach ($nids as $nid) {
    $node = \Drupal\node\Entity\Node::load($nid);
    print $node->title->value;
    \Drupal::entityManager()->getStorage('node')->resetCache(array($nid));
}

```

---
Tags: nodes, 8
---


title: Service function is not calling

text:
# Question
Title: Service function is not calling
I am trying to validate a key, which I am passing as url argument using service. But service function is not calling.

It's giving "Access denied" error. Am I missing something?

My sample code is:

cunn.routing.yml

```
cunnotification.saverecord:
  path: '/cunnotification/saverecord/{key}'
  defaults:
    _controller: '\Drupal\cunnotification\Controller\SaveRecordToDBController::SaveRecord'
  options:
    no_cache: TRUE
  requirements:
    _access_cunn_saverecord: 'TRUE'

```

cunn.services.yml

```
services:
  cunn.saverecord:
    class: Drupal\cunnotification\Access\CUNAccessCheck
    tags:
      - { name: cunn_access_check, applies_to: _access_cunn_saverecord }

```

CUNAccessCheck.php

```
namespace Drupal\cunn\Access;

use Drupal\Core\Routing\Access\AccessInterface;
use Drupal\Core\Access\AccessResult;

/**
 * Access check for conn routes.
 */
class CUNAccessCheck implements AccessInterface {

  /**
   * Checks access.
   *
   * @param string $key
   *   The conn key.
   *
   * @return \Drupal\Core\Access\AccessResultInterface
   *   The access result.
   */
  public function access($key) {
   // Logic here
   return TRUE; // based on logic
  }
}

```

# Answer
Don't change they tag name, just access\_check:

```
services:
  cunn.saverecord:
    class: Drupal\cunnotification\Access\CUNAccessCheck
    tags:
      - { name: access_check, applies_to: _access_cunn_saverecord }

```
> 1 votes

---
Tags: 8, symfony-services
---


# Question
Title: Inside Panelizer, is there a trick to formatting image fields?
**Summary**
In Panelizer, I have created one Panel. In Content for this panel there is an image field. I can find no option to change the image style.

From Manage Display in the content type, I am able to select Image Style for various display settings but this makes no difference to the image in the Panel in Panelizer.

Where am I not looking?

**Details**
In Panelizer for Content Type = (Person), first row on the left "Full Page override" I clicked "Panelize" and "Provide Default Panel". I think I have created one Panel. In the Content for this panel, I have placed an image field (field\_person\_image) in the right column.

In Panelizer on R of field\_person\_image is a gear listing- -"Settings". Formatter options for can select This Node, override title, change label position. There is an option for "Select a formatter" but the only option is "Image". There is no option to change the image style.
-Style which offers Pane Style for this node (rounded corners) -Visibility rules -Locking -Caching

In Structure \> Content Type \> Person \> Manage Display, I am able to select Image Style for various display settings. Changing from Large to Medium to Small (using Default, Full Content) makes no difference to the image in the Default Panel in Panelizer.

This similar sounding question also has no answer. Using Image 7.43. There are no results at Issues for Drupal Core (Drupal.org) about Panelizer and image formatting.

What am I missing?

# Answer
> 0 votes
Although I could swear that I had done this before, I deleted the image in the panel. **This time**, when I added the image back into the panel, I got image formatter options. Which I set, and the node behaved correctly.

Despite the frustratingly long time I worked on this, it was a non-problem!

AMENDMENT: When the panel is first created and saved, all of the fields appear in the panel. If the image field is left as is, there are no formatter options. However, **if the image field is deleted from the panel and then re-added**, then the formatter options appear. This is noteworthy, I think.

---
Tags: 7, panels, media
---


# Question
Title: How can I display a page element based upon security?
If I want to hide or show a DOM element, say a button that can show further information because the logged in user is a manager, how can I do that in Drupal 8? Do I need to create separate pages for each type of user role?

I saw this but wasn't sure if it was the same thing I was asking,

How can I change page elements (menu, blocks, etc) based on a chosen 'audience' link?

# Answer
> 2 votes
If you want to make a button only available to users who are admins, put this property in the form element:

```
'#access' => \Drupal::currentUser()->hasPermission('access administration pages'),

```

---
Tags: 8, security
---


# Question
Title: Entity reference or viewfield for Drupal8: How to embedd views output in my node?
In Drupal 7 it was possible to include into one node (/node/x/edit) the following lines

```
Label 1
[view:adresses=block_1=argument1]
Label 2
[view:adresses=block_1=argument2]
Label 3
[view:adresses=block_1=argument3]

```

Result: Output of the view depending on the argument.

I need the same solution in Drupal 8! How can I realize this?

Maybe entitity reference can solve this but I am able to use entity reference in Drupal 7 but in Drupal 8 this does not work (or I don't know how).

In Drupal 7 there are other modules like "View reference", "Viewfield" ... to solve this in a similar way.

**But how can I solve this in Drupal 8?** The output (e.g. block) of a view should be displayed in the content of one specific node.

How can I create a node field with a reference to my adresses view output? Thank you.

# Answer
I solved the problem by myself:

I use the modules Twig tweak and Twig input filter

to solve the problem above in Drupal 8. Works fine.
> 1 votes

# Answer
Try this :

```
function views_embed_view($name, $display_id = 'default') {
  $args = func_get_args();
  array_shift($args); // remove $name
  if (count($args)) {
    array_shift($args); // remove $display_id
  }

  $view = views_get_view($name);
  if (!$view || !$view->access($display_id)) {
    return;
  }

  return $view->preview($display_id, $args);
}

```

https://api.drupal.org/api/views/views.module/function/views\_embed\_view/7.x-3.x
> 0 votes

---
Tags: views, entities
---


# Question
Title: use drupal_add_js after external js scripts have already been loaded
I have a simple function to call on a specific page template. I'm calling it using this

```
<?php
    drupal_add_js("
        jQuery('.row).equalize();
    ","inline");
?>

```

and it's using an included js library called equalize.js. Which is included like so

```
<script type="text/javascript" src="mysiteurl/js/equalize.min.js"></script>

```

I receive 'jQuery(...).equalize is not a function'. but I'm assuming that's because

```
<script type="text/javascript" src="mysiteurl/js/equalize.min.js"></script>

```

is being called *after* my inline js. This only needs to be called on one page. Is there a way to force it to run after the external js file is loaded? Or is there something else I'm missing?

Note: When I run the inline js after the page is loaded in the console in the inspector it works fine.

# Answer
I was able to resolve this issue by encapsulating the inline js in a jQuery(document).ready function. Like so

```
<?php
drupal_add_js("
    jQuery(document).ready(function(){
        jQuery('.row').equalize();
    });
", "inline");
?>

```
> 0 votes

---
Tags: theming, javascript
---


# Question
Title: List of nodes that have no taxonomy terms
I'm maintaining a D6 project, where the customer wants to see a list of nodes where no taxonomy terms were added.

I want to solve this with views. I already tried some Filter settings for that, but nothing worked so far.

I would know the solution in D7 with Views 3 but in this case I can't get rid of this problem.

# Answer
Try this: 1. create a node view 2. in 'Fields', add 'Node: nid' 3. in 'Relationships', add 'Taxonomy: Node' 4. in 'Filters', add 'Taxonomy: Vocabulary', in next step, choose 'Is empty (NULL)' as the operator. 5. test some of the nids given in the preview to see if they are the ones you are looking for, you might need to tweak a little the usage of relationship. Step #3 is here to give you extra operators to choose from.

---

**update**

Okay the above assumes the content type only has one term field, so nevermind... Now that I understand the issue better, I think you will probably need views\_or module. Also we don't need 'relationship' anymore.

On my test Views, I use filter 'taxonomy:term(term id)' for each vocabulary, chain them together via Views\_or. Set them to dropdown with hierarchy. Then highlight all terms in the vocab and check 'is none of' for the operator on the left. It's a very ugly query but that's the only way I got it to work...You'd better cache it for a better performance. I attached some screenshots hope to clarify the config part.
> 0 votes

---
Tags: views, taxonomy-terms, 6
---


title: Views Using Current Month +- One Month

text:
# Question
Title: Views Using Current Month +- One Month
I am trying to get a list of seasonal items that *dynamically* display items based on the current month. It also includes items from the prior month and future month.

I have created a content type for this type of item, with an integer checkbox list. The values are 1|January, 2|February, 3|March, etc. When creating/editing a seasonal item. I check the checkboxes for the month(s) that the item is used.

I have created a view for current items, but have yet to find a way to dynamically set the filter for the item month. At the beginning of each month, I have to remember to go into the view, and uncheck the checkbox from (now) two months ago, and check the checkbox for the future month to maintain that three-month spread.

How can I make this filter dynamically create a three-month list based on the current month?

# Answer
You should not have used List as your field type, **you need to use Date as your field type.** Using the Date module and enable Date UI and Date Views.

Then in MORE SETTINGS AND VALUES, Date Entry, select Custom Format and put `F Y`

Now in Views for filter add your date filter, in my example my Date field is called *kewl*

then use is in between `previous month` and `next month`
> 1 votes

---
Tags: views, datetime
---


# Question
Title: Which hook to implement to limit node creation?
I'm looking to limit the number of nodes that a user can create in **Drupal 7**.

Which hook should I implement to step in before the 'add node' page is shown?

# Answer
> 7 votes
**Alter the access callback for the menu callback:**

```
function custom_module_menu_alter(&$items){
    $items['node/add/page']['access callback'] = 'my_custom_access_callback';
    // Next line needed for Drupal 7
    unset($items['node/add/page']['access arguments']);
}

```

**Add a function as your custom access callback:**

```
function my_custom_access_callback() {
   global $user;
   $allowed_limit = variable_get('allowed_limit', 10);

   // If Drupal 6.
   $node_counts = db_result(db_query("SELECT count(*) FROM {node} WHERE uid = %d;", $user->uid));
   // End If

   // If Drupal 7.
   $node_counts = db_query("SELECT count(*) FROM {node} WHERE uid = :uid", array(':uid' => $user->uid))->fetchField();
   // End If

   if ($node_counts < $allowed_limit && user_access("create page")) {
     return TRUE;
   }
   else{
     drupal_set_message(t('Print message about exceeded limit and/or user permissions.'));
     return FALSE;
   }
}

```

This kind of logic will restrict a user to exceed the limit.

# Answer
> 4 votes
The Node Limit project now has a Drupal 7 port as an Alpha release.

> The Node Limit module allows administrators to restrict the number of nodes of a specific type that roles or users may create. For example, if a site has an "Advertiser" role that can create "advertisement" nodes, then the node limit administrator can restrict all users in that role to a specific number of nodes. He may also restrict users on a per-user basis.

There is a plan to include Rules support in the near future as well. The documentation could use some work but if you poke through the module it will likely accomplish what you need.

# Answer
> 2 votes
Hook node validate may be more appropriate here. http://api.drupal.org/api/drupal/modules--node--node.api.php/function/hook\_node\_validate/7

That way if you use Services the solution will work, while the one proposed by Shoaib will only work if a user accesses the actual node creation page. If a remote client calls node.save via Services the menu access hack will fail.

# Answer
> 1 votes
For what it's worth, there's no need to alter the menu and remove the default node access callback.

Drupal provides `hook_node_access` to be used for this purpose:

e.g:

```
/**
 * Implements hook_node_access
 */
function MY_MODULE_node_access($node, $op, $account) {
  // Get node type, can be string or node object
  $type = is_string($node) ? $node : $node->type;
  if ($type == 'type_of_interest') {
    // Check node create limit
    if ($op == 'create') {
      // Check if some condition, limit check, is true
      // omitted for brevity
      // ...
      if($limit_reached){
        return NODE_ACCESS_DENY;
      }
    }
  }
  return NODE_ACCESS_IGNORE;
}

```

---
Tags: 7, nodes, hooks
---


title: how do I call a rest server?

text:
# Question
Title: how do I call a rest server?
I have a Drupal 8 site with a form that I have to submit to another server using the REST protocol.

I have the following information.

* server address
* server port
* form data

I want to submit that information to the other server.

Is there any function I can use in Drupal 8?

# Answer
Because of the new Proudly Found Elsewhere standard, Drupal doesn't have its own client.

It does however include Guzzle, a well respected library. You can use that to make your REST calls, or of course include and use another library if you wish.

You can get to the Guzzle client in a default Drupal 8 install through the http\_client service:

```
$httpClient = \Drupal::httpClient();

```

And the docs for Guzzle are here.
> 5 votes

---
Tags: 8
---


# Question
Title: How to get Node Title and description when nid is avaiable?
In Drupal 7 I am using following code in *Global: PHP*.

```
$data = message_load($row->mid);

if (isset($data->field_related_flag)){
  $fid = $data->field_related_flag['und'][0]['target_id'];
  $ftype = $data->field_flagged_node_type['und'][0]['value'];
  $flag = db_query('SELECT f.entity_id content_id, f.fid flag_id, flag.title type FROM flagging f INNER JOIN flag ON flag.fid = f.fid WHERE flagging_id = :val_fid', array(':val_fid' => $fid))-> fetchAssoc();
  $flag['content_type'] = $ftype;
  return json_encode($flag);
}

```

And from this code, I get the following output:

```
'related_flag' => '{"content_id":"410","flag_id":"1","type":"like","content_type":"event"}',

```

Here `"content_id":"410"` is the node ID.

Now I need to get the node title, description, and other fields. Can anyone please tell me what code I should write to get the desired result?

# Answer
> 1 votes
You can easily load the node using `$node = node_load($nid);`

Hoever it can be a bit tricky to get the values you want, so I recommend Entity metadata wrappers. They are part of the Entity API module and they allow you to access node variables like this:

```
$node = node_load($nid);
$node_wrapper = entity_metadata_wrapper('node', $node);
$node_wrapper->title->value();
$node_wrapper->field_description->value();

```

At the bottom of the linked Entity metadata wrapper page is a section on *Debugging or introspecting wrappers*, you can use that to find all available fields and their names.

---
Tags: 7, nodes, entities
---


title: Display 2 prices?

text:
# Question
Title: Display 2 prices?
How can I display 2 prices for products? I'd like to display a price in the local currency and a price in USD for each product. Is it possible to do this through Ubercart configuration, or does it require custom code?

# Answer
> 0 votes
You Can use this module for multi currency https://www.drupal.org/project/uc\_multi\_currency

---
Tags: 7, ubercart
---