title: permanent image theme setting

text:
# Question
Title: permanent image theme setting
Hy, I'm trying to display an image which has been set in the theme settings. This file should be stored permanently. I'm using drupal 8 and based on the information I found online, this is what I got:

First of all I added the setting to the form with the following code (located in theme-settings.php):

```
function THEME_form_system_theme_settings_alter(&$form, \Drupal\Core\Form\FormStateInterface &$form_state, $form_id = NULL) {
    if (isset($form_id)) {
        return;
    }

    $form['default_avatar'] = array(
        '#type'          => 'managed_file',
        '#title'         => t('default avatar'),
        '#default_value' => theme_get_setting('default_avatar'),
        '#description'   => t("The default avatar for users."),
    );

    $form['#submit'][] = 'THEME_form_system_theme_settings_submit';

    // Get the current theme
    $active_theme = \Drupal::theme()->getActiveTheme()->getPath();
    $form_state->addBuildInfo('files', $active_theme . '/theme-settings.php');
}

```

Then I use the following submit hook (located in theme-settings.php):

```
function dwagulu_form_system_theme_settings_submit(&$form, $form_state) {
    $image_fid = $form_state->getValue('default_avatar');
    if (count($image_fid) > 0) {
        $image = file_load($image_fid[0]);
        if (is_object($image)) {
            // Check to make sure that the file is set to be permanent.
            if (!$image->isPermanent()) {
                $image->setPermanent();
                $image->save();
                // Add a reference to prevent warnings.
                $file_usage = \Drupal::service('file.usage');
                $file_usage->add($image, 'dwagulu', 'theme', 1);
            }
        }
    }
}

```

This seems correct, however, when I add upload an image and save the settings I get the following warnings:

```
Warning: Invalid argument supplied for foreach() in Drupal\Core\Form\FormCache->loadCachedFormState() (line 157 of core\lib\Drupal\Core\Form\FormCache.php).
Drupal\Core\Form\FormCache->loadCachedFormState('form-5FkI3Kf8XhoxscPOAf-slbJ7Nn--ubyPoCQoO5UaQhQ', Object) (Line: 122)
Drupal\Core\Form\FormCache->getCache('form-5FkI3Kf8XhoxscPOAf-slbJ7Nn--ubyPoCQoO5UaQhQ', Object) (Line: 432)
Drupal\Core\Form\FormBuilder->getCache('form-5FkI3Kf8XhoxscPOAf-slbJ7Nn--ubyPoCQoO5UaQhQ', Object) (Line: 257)
Drupal\Core\Form\FormBuilder->buildForm(Object, Object) (Line: 74)
Drupal\Core\Controller\FormController->getContentResult(Object, Object)
call_user_func_array(Array, Array) (Line: 123)
Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber->Drupal\Core\EventSubscriber\{closure}() (Line: 574)
Drupal\Core\Render\Renderer->executeInRenderContext(Object, Object) (Line: 124)
Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber->wrapControllerExecutionInRenderContext(Array, Array) (Line: 97)
Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber->Drupal\Core\EventSubscriber\{closure}()
call_user_func_array(Object, Array) (Line: 139)
Symfony\Component\HttpKernel\HttpKernel->handleRaw(Object, 1) (Line: 62)
Symfony\Component\HttpKernel\HttpKernel->handle(Object, 1, 1) (Line: 57)
Drupal\Core\StackMiddleware\Session->handle(Object, 1, 1) (Line: 47)
Drupal\Core\StackMiddleware\KernelPreHandle->handle(Object, 1, 1) (Line: 98)
Drupal\page_cache\StackMiddleware\PageCache->pass(Object, 1, 1) (Line: 77)
Drupal\page_cache\StackMiddleware\PageCache->handle(Object, 1, 1) (Line: 47)
Drupal\Core\StackMiddleware\ReverseProxyMiddleware->handle(Object, 1, 1) (Line: 50)
Drupal\Core\StackMiddleware\NegotiationMiddleware->handle(Object, 1, 1) (Line: 23)
Stack\StackedHttpKernel->handle(Object, 1, 1) (Line: 628)
Drupal\Core\DrupalKernel->handle(Object) (Line: 19)

Warning: call_user_func_array() expects parameter 1 to be a valid callback, function 'dwagulu_form_system_theme_settings_submit' not found or invalid function name in Drupal\Core\Form\FormSubmitter->executeSubmitHandlers() (line 111 of core\lib\Drupal\Core\Form\FormSubmitter.php).
Drupal\Core\Form\FormSubmitter->executeSubmitHandlers(Array, Object) (Line: 51)
Drupal\Core\Form\FormSubmitter->doSubmitForm(Array, Object) (Line: 583)
Drupal\Core\Form\FormBuilder->processForm('system_theme_settings', Array, Object) (Line: 314)
Drupal\Core\Form\FormBuilder->buildForm(Object, Object) (Line: 74)
Drupal\Core\Controller\FormController->getContentResult(Object, Object)
call_user_func_array(Array, Array) (Line: 123)
Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber->Drupal\Core\EventSubscriber\{closure}() (Line: 574)
Drupal\Core\Render\Renderer->executeInRenderContext(Object, Object) (Line: 124)
Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber->wrapControllerExecutionInRenderContext(Array, Array) (Line: 97)
Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber->Drupal\Core\EventSubscriber\{closure}()
call_user_func_array(Object, Array) (Line: 139)
Symfony\Component\HttpKernel\HttpKernel->handleRaw(Object, 1) (Line: 62)
Symfony\Component\HttpKernel\HttpKernel->handle(Object, 1, 1) (Line: 57)
Drupal\Core\StackMiddleware\Session->handle(Object, 1, 1) (Line: 47)
Drupal\Core\StackMiddleware\KernelPreHandle->handle(Object, 1, 1) (Line: 98)
Drupal\page_cache\StackMiddleware\PageCache->pass(Object, 1, 1) (Line: 77)
Drupal\page_cache\StackMiddleware\PageCache->handle(Object, 1, 1) (Line: 47)
Drupal\Core\StackMiddleware\ReverseProxyMiddleware->handle(Object, 1, 1) (Line: 50)
Drupal\Core\StackMiddleware\NegotiationMiddleware->handle(Object, 1, 1) (Line: 23)
Stack\StackedHttpKernel->handle(Object, 1, 1) (Line: 628)
Drupal\Core\DrupalKernel->handle(Object) (Line: 19)

```

This second warning would lead me to believe that the submit function is not correctly loaded, despite the fact that I added it to the build\_info of the form\_state. Does anyone have any suggestions on what I might be missing.

Kind regards.

// edit:

I continues experimenting with the code. I moved both functions "alter" and "submit" to the THEME.theme file. Then I changed the build\_info to include the THEME.theme file. This removed the warnings and I can see that my code is executed. The file's status is set to permanent. This is good, however, when I ask for the file, the uri is "temporary://default-avatar\_2.png" which is not permanent I assume?

# Answer
> 2 votes
By adding an upload location to the form field:

```
$form['default_avatar'] = array(
    '#type'            => 'managed_file',
    '#title'           => t('default avatar'),
    '#default_value'   => theme_get_setting('default_avatar'),
    '#description'     => t("The default avatar for users."),
    '#upload_location' => 'public://'
);

```

the file is no longer uploaded to a temporary url.

---
Tags: forms, media
---


# Question
Title: How I can create a user programatically using user registration form?
How I can create a user programatically in drupal 8. I am using the following code to generate user registration form.

```
$account = $this->entityTypeManager->getStorage('user')->create([]);
$form = $this->entityFormBuilder->getForm($account, 'register');

```

and form\_sate values using the following code.

```
$form_state = (new FormState())->setValues(['name' => 'user1', 'pass' => 'pass']);

```

Now how can submit this form using the above form\_state values?

# Answer
> 1 votes
I think you needn't use the registration form as you have mentioned. You can use the following code to create a new user:

```
if (!user_load_by_mail('email_id')) {
  $language = \Drupal::languageManager()->getCurrentLanguage()->getId();
  $user = \Drupal\user\Entity\User::create();

  //Mandatory settings
  $user->setPassword('your_password');
  $user->enforceIsNew();
  $user->setEmail('email_id');
  $user->setUsername('user_name'); //This username must be unique and accepts only a-Z,0-9, - _ @ .

  //Optional settings
  $user->set("init", 'email');
  $user->set("langcode", $language);
  $user->set("preferred_langcode", $language);
  $user->set("preferred_admin_langcode", $language);
  //$user->set("setting_name", 'setting_value');
  $user->activate();

  //Save user
  $result = $user->save();
}

```

You can ensure that an user with same email id doesn't exist using `user_load_by_mail()`, and then proceed with the user creation.

---
Tags: forms, users, 8, entities
---


# Question
Title: How do I remove outer/container divs from a view?
I have a view which uses "unformatted list" as it's output format.

```
<div class="view view-featured-causes-view view-id-featured_causes_view view-display-id-block view-dom-id-961c974a51410cb04cdd2a2be4f3c589">
<div class="view-content">...</div></div>

```

Now I want these divs to be stripped.

I tried the solution in this answer, but I just want to change the format. I do not want to use Semantic views as that does not help at all in my case.

I manually created a views theme (copying unformatted list) and changing its code as:

```
<?php if (!empty($title)): ?>
  <h3><?php print $title; ?></h3>
<?php endif; ?>
<?php foreach ($rows as $id => $row): ?>
  <div<?php if ($classes_array[$id]) { print ' class="' . $classes_array[$id] .'"';  } ?>>
    <?php print $row; ?>
  </div>
<?php endforeach; ?>

```

to:

```
<?php if (!empty($title)): ?>
  <h3><?php print $title; ?></h3>
<?php endif; ?>
<?php foreach ($rows as $id => $row): ?>
    </div></div><?php print $row; ?><div><div>
<?php endforeach; ?>

```

but that deeply craps out my overall design.

What is the most appropriate and simplest way to do this?

# Answer
You should override the views-view.tpl.php, not the views-view-unformatted.tpl.php.

The two divs you mention are originating from sites/all/modules/views/theme/views-view.tpl.php, check out lines 30 and 55.

If you copy this over to your theme's templates folder, and rename to be specific to your page/block display, you can remove that part of the template's code and you should get what you need.

> cp sites/all/modules/views/theme/views-view.tpl.php sites/all/themes/your\_theme/templates/views/views-view--your-ul-page.tpl.php

N.B.: This is exactly what the other post's accepted answer is doing in the first part, before going into Semantic Views configuration, you can ignore that part. Here is a modified/simpler version of the code snippet from that answer, for quick reference:

```
<div class="<?php print $classes; ?>">     // 30: delete this line
  <?php print render($title_prefix); ?>
  <?php if ($title): ?>
[...]
<?php if ($rows): ?>
    <div class="view-content">  // 55: delete this line,
      <?php print $rows; ?>
    </div>                      // 57: delete this line
  <?php elseif ($empty): ?>
[...]
</div><?php /* class view */ ?> // 90: delete the div from this line

```

Good luck!
> 2 votes

---
Tags: 7, views
---


title: Admin language module

text:
# Question
Title: Admin language module
I'm currently building websites with the Administration Language Module. For the first time, the admin language is different than the default language but it doesn't work. For example, my default language is English and I'll set Spanish for the admin menu. My admin menu (and all administration dashboard) is partially translate.

As you can see, sometime item's menu are in English and in Spanish.

>

However, "People" is correctly translate in Translate Admin.

>

Can you help me?

# Answer
1. Visit admin/config/regional/language and select an admin language
2. Visit admin/config/regional/language/admin\_language and enable *Use administration language for the core toolbar*
> 0 votes

---
Tags: 7, users, i18n-l10n, navigation
---


# Question
Title: Alternative to Google Adsense content injector module
I want to "float" ads in the top right of my nodes for which Content Injector was nice enough in D6 moreover such ads convert well in my experience.

But for D7 is there any easy alternative? I know I can sub-theme and place the ads in appropriate positions.

# Answer
It might not be quite as versatile, but the Block Inject module will allow you to embed adsense blocks within the node body.
> 1 votes

# Answer
Without a module, just type adsense1, adsense2 anywhere in content.

(it's ok for any CMS: Drupal 7, WordPress, Joomla etc.)

First, create two or many scripts in your protected /inludes folder, with lines provides by Google Adsense (or somebody else).

adsense1.inc adsense2.inc ... adsense99.inc

// remember: just maximum 3 adsense blocks in a webpage // I've filtered any Flash movies

Second, edit /themes/$your\_theme/page.tpl.php. Write this code replacing line

print render($page\['content'\]);

with

if(strstr(render($page\['content'\]),'adsense1') or strstr(render($page\['content'\]),'adsense2')){ $pContent=explode('adsense1',render($page\['content'\])); $pgContent= explode('adsense2',$pContent\[0\]); print $pgContent\[0\]; if(strstr($pContent\[0\],'adsense2')) include('includes/adsense2.inc'); print $pgContent\[1\]; if(strstr(render($page\['content'\]),'adsense1')) include('includes/adsense1.inc'); print $pContent\[1\]; }else{ print render($page\['content'\]); }

Third, refresh portal performance.

Enjoy!

P.S. www.astralia.ro
> 1 votes

# Answer
Honestly the easiest way to do ad's in Drupal 7 is with blocks. Then style your block. This is a tutorial on how to install google adsense VIA a simple block. It takes less then 3 minutes and takes no code skills. This is much simpler then adsense module or content injector module. Hope this helps you. My drupal username is alex\_drupal\_dev I made the video. http://youtu.be/Ti6eApzJIrY
> 0 votes

---
Tags: 7
---


title: Panels not working with page manager?

text:
# Question
Title: Panels not working with page manager?
I'm testing page\_manager on a fresh install of Drupal 8 (V 8.1.8).

I installed :

When I try to create a Panel variant in a custom page, I've got no option to insert a block...

My UI appears like that :

Where can I add content in this page ?

# Answer
> 1 votes
Panels and Page Manager in Drupal 8 are under heavy development, so probably it's a temporal problem.

In Drupal 7 Page Manager is a submodule of CTools, but in Drupal 8 is a standalone module. The reason for this is Page Manager tasks (configuring UI) are very important but Panels wants to remain independent from the UI. This makes sense, as each module focus on its duty (Panels on doing its magic, Page Manager in configuring Panels through the UI).

To be more accurated Panels in Drupal 8 can be *implemented*. Currently, Page Manager and Panelizer implement panels.

So now they are not working together, but eventually they should, that's the target.

---
Tags: 8, panels
---


# Question
Title: How to make a whole node teaser with a View inside clickable?
I overrode my node's template file, such that my node teasers are clickable and redirect to the full node page. Now, I also have a View that displays some user fields (without links) and I would like to display this View in the node teaser. I added `<?php print views_embed_view('my_view', 'default', $uid); ?>` between the teaser fields:

```
<div id="teaser">
  <a href="<?php print url('node/' . $node->nid); ?>">
    <div id="teaser-header">
      <span class="teaser-title"><?php print $title; ?></span>
    </div>

    <div id="teaser-content">
      <span class="teaser-image">
        <?php print render($content['field_image']); ?>
      </span>

      <?php print views_embed_view('my_view', 'default', $uid); ?>

      <div class="teaser-statistics">
        <span>(<?php print $comment_count; ?>)</span>
        <?php $flag = flag_get_flag('my_flag'); ?>
        <span>(<?php print $flag->get_count($nid); ?>)</span>
      </div>
    </div>
  </a>
</div>

```

The View displays fine, but the whole teaser is not clickable anymore: the anchor wraps correctly around `teaser-header`, but not around the View's `div`.

Why does this happen and how can I solve it?

# Answer
> 1 votes
After Stefanos Petrakis' answer, I checked something that I should have done before. There actually *is* a link in my View: the contextual link trigger! Once I logged out as an admin, these links disappeared (anonymous users don't have permission to use them) and the teasers were clickable as desired. Therefore, my real problem was: *How can I disable the contextual links for my specific View?*

Of course, this is very easily done: go to your View's section *Other* and change the *Hide contextual links* option to *Yes*. Mind that Benia's answer won't work, because the anchor tag will still be there, although one won't see it.

# Answer
> 2 votes
Some detective work is needed here, the prime suspect is - as you already mentioned - the HTML generated by the views\_embed\_view. Without getting a look at what that looks like, it's just a guess game.

But... it could vey well be that your view's HTML is also containing some anchor tags. In other words, you have **nested links** in you HTML, which could very well explain the problem you are experiencing.

Some refs:

Good luck!

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


title: Ctools multistep form cache

text:
# Question
Title: Ctools multistep form cache
I, like other people on here it seems, have been trying to build a multi-step form using this tutorial about how to use the Ctools wizard to do so. My ultimate goal is to replace the registration form with my own multi-step sign up. The problem I am having is that at the moment I am mostly just 'regurgitating' the information on that tutorial link, without truly understanding how the data is passed between the forms, or the manner in which it is stored.

I've read some of the comments on that page and it seems to indicate that the cache object is overwritten after passing through each step, which is no good to me.

The tutorial never really touches upon the submit process and how you access the form items you've created throughout the steps. I know what I want to do with all the information when it's collected and ready, but I think I'm still a little fuzzy on how you retrieve the information.

If anyone has any knowledge about how to use the Ctools multistep wizard so that I can understand and process the user inputs, that would be great

Thanks

# Answer
> 1 votes
I've just gone through the same thing myself, but without using CTools.

While I don't currently have time to write a comprehensive tutorial (which is what's really necessary, as most of the examples out there suck big time) - perhaps on the coming weekend - I can give you an overview of how I've done it. My scenario involves an existing form (for Entity Creation via the Entity Construction Kit).

First and foremost, I'm modifying the form via `hook_form_alter()`, but you can do the same thing in any form builder (for, say, a custom form). For simplicity, I'll refer to my implementation of `hook_form_alter()` as the 'form builder.'

The first thing my form builder does is determine the current 'state' of the form. I define 'state' as a single, distinct step of the form. I check for current state by looking for `$form_state['current_state']` and defaulting it to a default (first step) state if not found.

It is important to understand that the data in `$form_state` will persist between steps of the multi-step, so when we trigger the rebuilding of the form, we can see what state we came from and act accordingly. So, we've set the `$form_state['current_state']` to a default state (`step1`) and added the form elements we wish to display for this state into `$form`. (If you have other elements in `$form` which you don't want to show, set their `#access` property to `false`.) Now we can view the form and see our elements - great.

The next step is adding a new state and switching to it upon form submission. When the form is submitted, our submit handler looks at `$form_state['current_state']` and figures out how to proceed. We can look at `$form_state['triggered_element']['#value']` to figure out which button was clicked to submit the form, and act accordingly. Let's say our button in `step1` was 'Next,' we can identify this click in the submit handler and do the following:

1. Save the current form values (`$form_state['values']`) into `$form_state['step1_values']`.
2. Change `$form_state['current_state']` to be `step2`.
3. Rebuild the form by setting `$form_state['rebuild'] = TRUE;`

When the above events happen, the form builder will be called again, and now your `$form_state['current_state']` will be set to `step2`, so you can identify this and show different form elements. Rinse and repeat for more form steps.

The tricky part I encountered was moving 'back' to a previous state and re-populating the form with previously submitted values. For some reason I had the impression that this would work 'automagically, because Drupal,' but no dice, I had to do it manually. This is no simple task, but (luckily for you!) you can get away with a single line of code:

```
form_set_defaults($fields, $values, $form);

```

... where `$fields` is an array of machine names for the fields you want to populate, `$values` is the data you saved in `$form_state['step1_values']`, and `$form` is the current form, which is accepted by reference and modified. As for the function itself, it's available as part of the form component in my DevTools module.

Disclaimer: `form_set_defaults()` was only tested in my own use case of a textfield, textarea, a series of checkboxes (referencing a taxonomy), and a couple FiveStar widgets. Your mileage may vary.

This should get you most of the way there!

# Answer
> 0 votes
Realize this is an old thread but wanted to throw an additional explanation out there to help people.

I was able to accomplish the same with D7 by using the $form\_state values as default values in the hook\_form().

For example:

```
function brand_step_one_form($form, &$form_state) {

    $form['field_first_name'] = array(
          '#type' => 'textfield',
          '#title' => t('First Name'),
          '#default_value' => $form_state['step_data']['field_first_name'],
          '#size' => 60,
          '#maxlength' => 128,
          '#required' => TRUE,
    );
}

```

*step\_data* in this instance is where I'm storing my data. Using a simple var\_dump on the form\_state variable will show you where yours is.

When you hit the back button, the fields will be preserved and autofilled. The only additional caveat I have is that I had to make sure that the cache wasn't overwritten when the back button was clicked.

```
function custom_module_next(&$form_state) {

    if ($form_state['triggering_element']['#value'] != "Back") {
        StepCache::set('data', $form_state['values']);
    }

}

```

Lastly, make sure to set

```
'show back' => variable_get('step_show_back', TRUE)
```
. Otherwise the back button won't show.

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


# Question
Title: Using Rules to Prune Inactive Users - will this work?
I am relatively new to Drupal and learning as I develop a new website for our network of chapters. Needless to say, that has been quite the challenge :)

One of the functionalities I needed was the ability to prune inactive users. We have this on our current system and like having it to keep our membership numbers accurate, as well as help our members feel more "secure" by knowing only active members have access to the chapter.

There were a couple of modules out there to do this, but they were all for Drupal 6 or only had development modules for Drupal 7.

I found this link: https://drupal.org/node/1582710

and have followed it to set up my own "prune users" using rules. But I have NO idea how to test this in the development stage and certainly don't want it to screw up and accidentally mess up memberships when we move to the live versions.

What I have done is as follows:

Set up the following components:

1. Send email stating user has been inactive for 30 days and schedule next letter in 30 days
2. Send email stating user has been inactive for 60 days and schedule next letter in 25 days
3. Send email stating user is in danger of being pruned and must login to keep account and schedule blocking user in 5 days.
4. Block user

Set up the following rules:

1. Inactive User: When user logs in, remove all currently scheduled rules and set component evaluation for inactive for 30 days letter.
2. Never Logged In: When user account is first approved, set component evaluation for inactive for 30 days letter.

I *think* this means that when a user first signs up, they will get scheduled for the inactive user letter. Every time they log in, it will reset to the 30 day letter in 30 days. If they never log in, in 30 days, they will get the first letter and the 2nd letter will schedule... until they are pruned. If they log in, everything resets.

I know this means that every user will have a scheduled inactive user letter task -- not sure if this will bog down my system too much?

Also, if this does sound *right* -- how do I go about testing it to make sure it works the way it is supposed to and doesn't accidentally block users its not supposed to?

One last thing -- what can I do to automatically delete the users that are "blocked" and have been members for a certain amount of time (to ensure that new members who are just not approved yet don't accidentally get "pruned"?)

If I have made a complete mess of this, please feel free to tell me so! Like I said, I am really new at this and still figuring it out as I go along... I appreciate any help you can give me!

# Answer
Your solution "may" work, but another approach is to *process the results of a VBO enabled view via Rules*, whereas your rule performs 2 Rules Actions:

* load the VBO list of users that are candidate for deletion.
* add a loop to perform a Rules Action "delete user", for each user contained in your Views results.

For more details, have a look at the tutorial "How to process the results of a VBO enabled view via Rules?".

The advantage is that, if you first run it manually, you can see which users will get deleted (simply by browsing the Views results). When you feel comfortable enough, just automate this by rescheduling it every day (at the end of the rule itself, after you first triggered the rule manually).
> 2 votes

---
Tags: 7, users, rules
---


# Question
Title: How to set custom block to not in any region, therefore user can selete region by ownself?
This is my custom block hoo\_block\_info():

```
 function myblock_block_info() {
   $blocks = array();
     if (variable_get('hare_block', 0)) {
       $blocks['abc'] = array(
         'info' => t('test block'),
         'visibility' => 0,
         'status' => TRUE,
         'region' => 'none',
         'weight' => 99,
         'cache' => DRUPAL_NO_CACHE,
       );
     }
   return $blocks;
 }

```

Now by setting 'region'=\>'none' there is an error that block region is not defined. Please let me know how to place block in none region?

# Answer
> 3 votes
Simply remove `'region' => 'none'` from hook\_block\_info().

**region:** (optional) Initial value for theme region within which this block is set. Most modules do not provide an initial value, and any value provided can be modified by a user on the block configuration screen.

> Note: If you set a region that isn't available in the currently enabled theme, the block will be disabled.

---
Tags: hooks
---


title: Remove http:// from $base_url

text:
# Question
Title: Remove http:// from $base_url
I am trying to generate a email address that reads as no-reply@example.com.

Using the global base\_url the output is http://example.com.

Is there another global, or some other easy solution, to remove the "http://", so that I get the string example.com?

Thanks in advance

# Answer
Think you're looking for `$_SERVER['HTTP_HOST']`. Also see $base\_path, $base\_url, $base\_root
> 3 votes

---
Tags: emails, uri
---


# Question
Title: DrupalVM ubuntu 14.04 vagrant provision error 'packages cannot be authenticated'
I ran `vagrant provision` and I get this error:

```
at: apt-get install -y -qq software-properties-common python-software-properties

error message:
WARNING: The following packages cannot be authenticated!
python-software-properties

```

When I try run `sudo apt-get update` on the VM I get these errors.

```
W: Failed to fetch http://us.archive.ubuntu.com/ubuntu/dists/trusty/InRelease
W: Failed to fetch http://us.archive.ubuntu.com/ubuntu/dists/trusty-updates/InRelease
W: Failed to fetch http://us.archive.ubuntu.com/ubuntu/dists/trusty-backports/InRelease
W: Failed to fetch http://us.archive.ubuntu.com/ubuntu/dists/trusty/Release.gpg  Could not resolve 'us.archive.ubuntu.com'
W: Failed to fetch http://us.archive.ubuntu.com/ubuntu/dists/trusty-updates/Release.gpg  Could not resolve 'us.archive.ubuntu.com'
W: Failed to fetch http://us.archive.ubuntu.com/ubuntu/dists/trusty-backports/Release.gpg  Could not resolve 'us.archive.ubuntu.com'
W: Some index files failed to download. They have been ignored, or old ones used instead.

```

Note that there is no `InRelease` file in these directories:

http://us.archive.ubuntu.com/ubuntu/dists/trusty/

http://old-releases.archive.ubuntu.com/ubuntu/dists/trusty/InRelease

I am using:

Host machine: OS: Ubuntu 16.04 x86\_64 vagrant: Vagrant 1.8.5

VM: box 'geerlingguy/ubuntu1404' (v1.1.3) for provider: virtualbox

config.yml:

```
vagrant_hostname: iemp.local
vagrant_machine_name: iemp

vagrant_box: geerlingguy/ubuntu1404
php_version: "5.6"
drupal_major_version: 7
drush_version: "7.x"

php_packages:
  - php5
  - php5-apcu
  - php5-mcrypt
  - php5-cli
  - php5-common
  - php5-curl
  - php5-dev
  - php5-fpm
  - php5-gd
  - php5-sqlite
  - php-pear
  - libpcre3-dev
php_conf_paths:
  - /etc/php5/fpm
  - /etc/php5/apache2
  - /etc/php5/cli
php_extension_conf_paths:
  - /etc/php5/fpm/conf.d
  - /etc/php5/apache2/conf.d
  - /etc/php5/cli/conf.d
php_fpm_daemon: php5-fpm
php_fpm_conf_path: "/etc/php5/fpm"
php_fpm_pool_conf_path: "/etc/php5/fpm/pool.d/www.conf"
php_mysql_package: php5-mysql

build_makefile: false
build_composer: false
build_composer_project: false
install_site: false

vagrant_synced_folders:
  - local_path: ./
    destination: /var/www/drupalvm
    type: nfs
    create: true

```

# Answer
> 0 votes
I ended up reinstalling the host machine, Virtual Box and Vagrant. It seems like I broke something by manually deleting the Virtual Machine via the Virtual Box Admin Interface.

With the new installation and the same configuration it worked perfectly.

I suggest using `vagrant destroy` to delete your virtual machine files.

---
Tags: virtual-machine
---


# Question
Title: Custom node access, need to rebuild permissions for each content item created
I have a module that handles node access to a custom content type with `hook_node_access`. Basically, an anonymous user needs to enter a passcode to view the page. Currently, I'm doing this through session variables. If they have `$_SESSION['example']` set, `return NODE_ACCESS_IGNORE`, otherwise

```
drupal_goto('form');
return NODE_ACCESS_DENY;

```

Currently, after I create a new content item, the anonymous user will submit the code, be redirected to the content item, and then get an access denied error.

If I rebuild the permissions, the access will work properly, but *not* for any content items I create after the rebuild.

The Content Access module is enabled on the site. Testing locally, I have tested both disabled (not uninstalled) and enabled content access module and access is currently working as intended.

# Answer
> 0 votes
It seems like your problem matches the following:

> This function is called when a node is saved, and can also be called by modules if something other than a node save causes node access permissions to change.

This is an excerpt from the `node_access_acquire_grants` documentation. I believe a way to go about your problem would be to call this function, inside your form\_submit handler (guessing you have one).

So, on a conceptual level, as soon as the anonymous user enters the code, the node access permissions for that specific page changes and you should update them (writing them to the database) through a call to `node_access_acquire_grants`

Good luck, let us know how this goes!

---
Tags: 7
---


# Question
Title: How do I declare a Telephone field in a content entity?
I want to create a custom content entity with a telephone field. I'm baffled on how to do it; I can't figure out what should go into `setDisplayOptions()` to have it show up as a telephone field on the form. Does anyone know where I could find an example of this?

# Answer
Okay, the following configuration seemed to work:

```
$fields['display_number'] = BaseFieldDefinition::create('telephone')
      ->setLabel(t('Display Number'))
      ->setDescription((t('The phone number to display')))
      ->setDefaultValue('')
      ->setDisplayOptions('form', array(
        'type' => 'telephone_default',
        'weight' => 0,
      ))
      ->setDisplayConfigurable('form', TRUE);

```
> 5 votes

---
Tags: 8, entities
---


title: Page manager (or panels) override path

text:
# Question
Title: Page manager (or panels) override path
I want to override Drupal 8 paths (routes) like node/{node} or taxonomy/term/{taxonomy\_term} with custom panels variants. Is it possible?

# Answer
> 2 votes
Page Manager module. Add a new page that has the Path of `/taxonomy/term/%` and as @Todd Young wrote, disable the default Taxonomy view.

However, there is a bug that this is not working at https://www.drupal.org/node/2785195

# Answer
> 1 votes
There is a Page Manager module which you could use for this purpose.

> This is the Drupal 8 version of Page Manager, formerly part of the CTools module written by merlinofchaos
>
> It supports the creation of new pages, and allows placing blocks within that page. Like Drupal 7's Page Manager, it provides a concept of "page variants", each with their own selection conditions. Additionally, it can be used to take over an existing page, like overriding /node/% to change what is displayed when viewing a node.

# Answer
> 1 votes
I would comment but I don't have a reputation here yet.

The Page Manager module will indeed do what you are trying to accomplish. The problem you are having in the comments is due to the path you are trying to use already being taken.

Drupal 8 comes with a stock View for the Taxonomy page. You're probably setting the Page Manager page up correctly but you will need to disable this built-in View to "release" that path before it takes effect in your Page Manager page.

---
Tags: 8, panels
---


title: Symlink inside profile

text:
# Question
Title: Symlink inside profile
I forked a repo from a third party development team that I am taking over for, and inside the "profiles" folder is a file just named foo.

When I open it, it as this ../../foo and nothing else.

Is this a symlink to the install profile?

There is an install profile, just not in the docroot folder, it sits outside of it with the grunt and build files.

If so, is there a difference on how Nginx and Apache handle symlinks? They used a Nginx server to develop and I'm using Apache.

Thanks everyone.

# Answer
It is fairly common practice to use symlink on web server. You might also see it on your private folder so that I can be hosted on a NAS or AWS EFS for example.

Symlink should work regardless of the web server you use as they are specific to the server operating system and not to the web server by itself.
> 0 votes

---
Tags: users
---


title: Add custom payment widget to a node?

text:
# Question
Title: Add custom payment widget to a node?
I have a widget that allows the user to book and pay on a site. I used:

```
function capewinefarms_preprocess(&$variables, $hook)

```

And ended up with something like this:

```
$variables['book_now_widget'] = '<div style="font-weight: bold">bla bla bla</div>';

```

Which I then output in the template using:

```
{{ book_now_widget }}

```

The problem is that instead of seeing:

```
 bla bla bla

```

in bold text, i see:

```
<div style="font-weight: bold">bla bla bla</div>

```

Because the widget is "self-contained", it needs all the javascript and html and everything to be outputted exactly as is, and not be formatted. It seems twig is somehow doing this.

Any idea as to how to get around this? Or any insight into why this is happening? Or perhaps an even better question might be: how do I do this the most correct way?

I suppose I can do it as a block, but then I would have to attached a JS file, and I can't do this, because it all needs to be self contained as it is also re-used on a mobile app.

Any ideas?

# Answer
This solved my problem:

```
{{ book_now_widget|raw }}

```
> 0 votes

# Answer
**1.) What is happening**

Twig sanitizes all variables before displaying them. Because it assumes, that the style attribute is from user input and is considered to be unsafe. You can pass most html as `#markup`, but not the style attribute.

**2.) You asked about the most correct way to do this is.**

This would be to put all html markup in templates.

**3.) How to get around this**

If you don't want to build a custom twig template for this, you can use an inline template instead:

```
$variables['book_now_widget'] = [
        '#type' => 'inline_template',
        '#template' => '<div style="font-weight: bold">{{ var1 }}</div>',
        '#context' => [
          'var1' => 'bla bla bla'],
];

```
> 0 votes

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


# Question
Title: Using php command to pass custom php.ini values into drush phar
I'm struggling with adding php values into drush.phar. Last time I installed drush I used composer and for that method I could add the php.ini values into the drush.ini, but with the new way to install the drush.phar, the drush.ini doesn't seem to be supported. I've been trying to use the new method of adding php values into the drush.phar, but either it doesn't work or I am doing it wrong. Here's an example of what I tried:

`php -d memory_limit=256M /usr/local/bin/drush --php-options=memory_limit=256M`

When I try something like that it just gives me the drush help so I'm assuming I've got something wrong.

Here's the example from the drush docs:

```
php -d foo=bar drush.phar --php-options=foo=bar

```

I'm not familiar with using the php command, but I guess I can just go back to using composer if I am not able add a few php values to the drush.phar this way. I also need to add open\_basedir with an empty value since I need my php.ini to use open\_basedir. I'm not sure how this php command is suppose to handle empty values.

Hoping someone has been able to do this.

# Answer
> 0 votes
You did it exactly right -- just add the additional Drush command, options and arguments after the part you already typed in. For example:

`php -d memory_limit=256M /usr/local/bin/drush --php-options=memory_limit=256M --root=/path --uri=example.com status`

That's kind of a lot of typing, so you might want to make an alias:

`alias drush='php -d memory_limit=256M /usr/local/bin/drush --php-options=memory_limit=256M'`

Then:

`drush --root=/path --uri=example.com status`

---
Tags: drush
---


title: Apachesolr sort based on nodeviewcount

text:
# Question
Title: Apachesolr sort based on nodeviewcount
I need to provide the option for sorting on the basis of nodeviewcount. The criteria is that if any text is provided for search, the search results will be displayed according to maximum number of nodes viewed.

# Answer
> 0 votes
Take a look at Apache Solr View Count module which does exactly the same.

> This module allows you to index the node view count to Apache solr index as a custom field and let you sort SOLR results. The module requires Apache solr search module.

Disclosure: I'm one of the module maintainer.

---
Tags: search, 7
---


# Question
Title: Contextual Shared comments on nodes that are clones of one another
I'm creating a Drupal 8 system where I need commenting to be shared across cloned nodes. When cloning a node the new node is assigned with a new nid, but the title contains the cloned title of the previous node. I was thinking I can use that as a contextual variable to show the shared comments, but I'm unsure of how to go about this.

Or maybe there is better way of solving this approach to display shared commenting?

# Answer
> 0 votes
There's many routes which to take for this. Drupal 8 gives you a bit more flexibility than previous versions. For the sake of managing a shared comment section, you can go about creating a new body-less content type that only contains:

* A comment field
* A node reference field with 2 entries (one for the parent & child cloned node)

Upon your clone operation, you can create a new entity with a dummy, to-be-hidden, title and the node reference field populated with the parent/child nodes.

For display/commenting, you can create a block view that uses a **Provide default value**: *Raw value from url (Path component: 2)* (i.e. the node id) contextual filter so the block only displays the shared comment entity on viewing the child/parent nodes.

---
Tags: 8, comments
---


# Question
Title: How can I determine if a $form (or $form_state) is an entity create/edit form
When in a function (e.g. a hook\_form\_alter) is there a reliable way to determine if the form is an entity form and if so, what type of entity?

# Answer
> 9 votes
You can check if the form is an instance of EntityForm and then get the entity to check the entity type:

```
if ($form_state->getFormObject() instanceof \Drupal\Core\Entity\EntityFormInterface) {
  $entity_type = $form_state->getFormObject()->getEntity()->getEntityTypeId();
}

```

---
Tags: forms, 8, entities
---


title: DrupalChat module polling method

text:
# Question
Title: DrupalChat module polling method
I am using drupalchat module for my website. And I wanted to check which polling method is best - "Normal AJAX" or "Long Polling". Actually We are facing performance issue. Currently we are using "Normal AJAX" as polling method. Can somebody suggest which polling method we should use and why?

# Answer
I had a experience about that, when using Ajax each short time each user and all of open each pages has requested to server ( if you look at firebug console you see what I mean ), another method is Long Polling method that also it is not the best way ( although it is better than Ajax method if very quick response time is not important for you), **In Both cause heavy load on server (especially memory exhausted)**.ajax and polling is old method to interactive real time applications like chat **I strongly recommend you using Nodejs method, Nodejs is very good for realtime chat system**

So use **Drupalchat nodejs** integration solution

> f you use node.js as backend in this module, then it will be highly scalable. There are two ways to use this backend:
>
> ```
>  First way is to setup your own node.js server and install Nodejs Integration module. This is currently under development.
> If you don't want to or can't setup your own node.js server, then you can checkout our ready to use node.js server. If you opt for this
>
> ```
>
> method, then there is no need to install any additional software/package on your web server. To do so, please visit us at https://iflychat.com.

another solution is using nodejs\_chat drupal module ( in both solution you require nodejs on yourserver).
> 0 votes

---
Tags: 7, performance
---


# Question
Title: How to add the search form in Bootstrap theme?
I am trying to set the search form with submit button in the Navbar as shown in the following image(Following image I have taken from the Bootstrap tutorial page).

>

---

* Now, When we install the default Bootstrap theme from drupal.org it will be ended up like as shown in following image.

>

Now, if I simply move that block to the Navigation bar, it will end up as shown in following image, which is not a solution for this.

So, I dig out on the bootstrap tutorial page and found the following code.

>

So, I can paste that code in the *page.tpl.php* and can achieve as shown in following image, BUT it will not search anything, as it is just a plain HTML code.

---

How can I achieve that? If CSS is the answer, for now I do not want to go with that. As IMHO, since this display of search form is described as a default on the bootstrap tutorial and in every theme demo display pages, So, there should be some way to enable that, or some way to place that.

Any suggestion or direction? Thanks.

# Answer
> 3 votes
After some search I figure out the following solution, it is working, But the issue is it is applying to `search_block_form` also, might be function `lsubtheme_bootstrap_search_form_wrapper($variables)` is the reason, which is getting applied everywhere. Might be giving False positive result.

**PLEASE anybody have any suggestion, how to imptove this, I am trying will update.**

**Codes in *template.php***

```
function lsubtheme_preprocess_page(&$variables){
  $search_form = drupal_get_form('search_form');
  $search_box = drupal_render($search_form);
  $variables['search_box'] = $search_box;
}

/*
 *  Form alter to add missing bootstrap classes and role to search form.
 */

function lsubtheme_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'search_form') {
    $form['#attributes']['class'][] = 'navbar-form navbar-left';
    $form['#attributes']['role'][] = 'search';
  }
}

function lsubtheme_bootstrap_search_form_wrapper($variables) {

  $output = '<div class="form-group">';
  $output .= $variables['element']['#children'];
  $output .= ' <div class="form-group">';
  $output .= '<button type="submit" class="btn btn-default">Search</button>';
  $output .= '</div>';
  $output .= '</div>';
  return $output;
}

```

**Code in *page.tpl.php***

```
 <?php print $search_box; ?>

```

>

# Answer
> 2 votes
You will basically have to re-implement the rendering yourself.

The best way to do this, to me, is to implement hook\_theme, provide a function, template, and variables to pass on, and change (via hook\_form\_alter or your provider Form class if you have one, Drupal 8) the form rendering function to your new one.

This will result in a cleaner more manageable approach, as you can then drop the HTML from the Bootstrap docs into your designated template. Then, any time you want to render a basic search form to be the Bootstrap one, change the forms `#theme` to your function. Then you don't have to fool with a lot of spaghetti code.

I would not copy/paste HTML into page.tpl.php as that will have no effect at all.

I see where you are getting the above code from, but I personally would not store markup like that in template.php. Easy to miss, and hard to adjust. The goal for an override like this is to isolate the behavior and ensure that no other form later on is inadvertently altered.

I wish I had an example on hand, but I cannot find one at the moment.

# Answer
> 0 votes
Why not solve this on the theme level? Add the following to your sub theme javascript file. See https://www.drupal.org/node/304255 for more info

```
jQuery('#search-block-form .input-group button.btn.btn-primary span')
  .text('Submit')
  .removeClass('glyphicon glyphicon-search icon')

```

Or in a new javascript file like

```
jQuery(document).ready(function() {
    var $button = jQuery('#search-block-form .input-group button.btn.btn-primary span');
  $button
    .text('Submit')
    .removeClass('glyphicon glyphicon-search icon');
  });

```

Resulting in  I've tried other solutions in projects which never were more satisfying than this.

To test without sub theme I placed it in a module dummy hook\_init().

```
/**
 * Implements hook_init().
 */
function dummy_init() {
    drupal_add_js('jQuery(document).ready(function () { jQuery("#search-block-form .input-group button.btn.btn-primary span").text("Submit").removeClass("glyphicon glyphicon-search icon") });', 'inline');
}

```

---
Tags: 7, theming
---


# Question
Title: How to display a field in a content type template?
I edit my template field--field-email--customer.tpl.php and it works but I would like to display a field twice. I tried with this but it doesn't work : print render($content\['field\_nom'\]);

# Answer
As per my knowledge you can not use `$content` array in `field.tpl.php`. You need to use `$items`.

> Available variables:
>
> ```
> $items: An array of field values. Use render() to output them.
> $label: The item label.
> $label_hidden: Whether the label display is set to 'hidden'.
> $classes: String of classes that can be used to style contextually through CSS.
>
> ```
>
> from preprocess functions. The default values can be one or more of the following:
>
> ```
> field: The current template type, i.e., "theming hook".
> field-name-[field_name]: The current field name.
> field-type-[field_type]: The current field type.
> field-label-[label_display]: The current label position.
> $element['#object']: The entity to which the field is attached.
> $element['#view_mode']: View mode, e.g. 'full', 'teaser'...
> $element['#field_name']: The field name.
> $element['#field_type']: The field type.
> $element['#field_language']: The field language.
> $element['#field_translatable']: Whether the field is translatable or not.
> $element['#label_display']: Position of label display, inline, above, or hidden.
> $field_name_css: The css-compatible field name.
> $field_type_css: The css-compatible field type.
> $classes_array: Array of html class attribute values
>
> ```
> 0 votes

---
Tags: theming, entities
---


title: Doesn't have author picture field

text:
# Question
Title: Doesn't have author picture field
I am building a drupal site using Views, search API module and user-points module.

I created the "database server", and indexed many fields of nodes.

I created a search page using views and the search API, that present content (image, title etc.) In addition, I want to add to every content in this search view the name of the author that wrote it, his author picture.

I add the *Indexed Content: Author* relationship. Unfortunately, I can't find a way to add the author picture and the current total point to my view.

Can somebody advice how to do that?

# Answer
> 0 votes
I have not tried any of the following before, these are result of googling, so might not work.

I see two ways, hope any one helps you.

1. Solution might be as simple as using Apache Solr Image module, but not sure if it will work with user image.
2. The second needs custom coding, which will basically tell apache solr to index the image field uri and then add the uri field in your views and finally theme it as image using a custom template, Refer this for sample code.

# Answer
> 0 votes
So what i did was that i included the "Rendered user" field as part of the fields to be displayed in my view. In the Rendered user view mode settings, i choose "User account".

Finally i went to the "Manage display" tab of the Account settings to remove unwanted fields.

# Answer
> 0 votes
We do it something like

```
function MY_MODULE_entity_property_info_alter(&$info) {
  $info['user']['properties']['picture'] = array(
   'label' => t('User Picture'),
   'type' => "file",
   'description' => t("The user profile picture."),
  );
  return $info;
}

```

This way the user picture field would be available under Fields of Search Index.

---
Tags: views, search
---


# Question
Title: devel module use anonymous user as author in generate content?
i have been created 'job' content type, i used 'Devel module' to generate content of 'job' type, but in some 'jobs' its taking anonymous user as a author, but i don't want anonymous user as author, so what should i do to avoid anonymous user as a author?

# Answer
> 0 votes
Answer for you question is **Yes** it do,and you can resolve your problem with following solutions:

The First solution is

1. Install the views, views\_bulk\_operations, and admin\_views modules.
2. Go to the content listing (admin/content).
3. Filter the results to get the nodes you are interested in.
4. Check the checkboxes next to the node (there is also an option to select all).
5. Select "Change author" from the operations dropdown and click the "Execute" button.
6. Select the user you want to change the author to and click the "Next" button.

Admin views uses views bulk operations to override the default drupal administration views with something a lot more useful.

And also another solution is using bulk author update module

# Answer
> 0 votes
If you first set your permissions so that only authenticated users are allowed to create content of type 'job', then the Devel module should not be able to create this kind of content. At least that is what I would expect.

However, as per Devel generate not respecting node create persmission (which dates from 2009 and is still active), after tuning your permissions, Devel doesn't seem to work like that. Maybe not the answer you would want to get, but I'm pretty sure that this is the explanation of what happens.

**Possible workaround**:

I would use the Rules module and create a custom rule that looks like so (in Rules Export format):

```
{ "rules_change_node_author" : {
    "LABEL" : "Change node author",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "node_insert" : [] },
    "IF" : [
      { "node_is_of_type" : { "node" : [ "node" ], "type" : { "value" : { "job" : "job" } } } },
      { "data_is" : { "data" : [ "node:author:uid" ], "value" : "0" } }
    ],
    "DO" : [
      { "data_set" : { "data" : [ "node:author" ], "value" : [ "site:current-user" ] } }
    ]
  }
}

```

Some more details about what the above Rule actually does:

* Rules Event: After saving a node.
* Rules Conditions:
    + Check if the author's `uid` = `0`.
    + Check if the content type is `Job`.
* Rules Action: Update the node's author (i.e. to the user using the Devel module).

If you have the Rules UI enabled, you can simply import the above rule in your own site. If you want to use it for another content type, first adapt the machine name `job` prior to trying to import this rule (to avoid the import would fail if you don't have a `Job` content type).

PS: if you've configured your permissions that you do not allow anonymous users to create nodes of type 'Job', I think it is reasonable to assume that it must be that these kinds of nodes were created using Devel.

---
Tags: 7, users
---


# Question
Title: Correct way to massively change node author
I want to change all the nodes where $user1 is author and set $user2 as author. I use this PHP Code and it works, but is it the correct way to do it? Or should I use a batch process and load each node to change the author?

```
   $num_updated = db_update('node')
      ->fields(array(
        'uid' => $user2->uid,
      ))
      ->condition('uid', $user1->uid, '=')
      ->execute();

```

# Answer
Well, at the end, because in my organization there is an important turn over and everybody has to manage its own nodes, I decided to create a module and to do things properly. I used the node\_load/node\_save functions to do it.

I put the module in my sandbox if you need it: https://drupal.org/sandbox/franperr/2109987 Feel free to send me a message for bugs/help/new features...
> 1 votes

# Answer
It sounds like your Administering a Drupal site (not just a content moderator) -- but a site administration / developer.

Your code is fine. I recommend using Drush and calling your code as `$ drush php-script massively-change-node-author.php` from the command line. This way there is no timeout issues and you don't need to worry about using the Batch API and stuff like that.

Running code from `php-script` and drush performs a `FULL BOOTSTRAP` of drupal by default, and if needed you can pass a user argument to run the script as (faking a logged in user of `$user`) by using `--user=1` for instance. For example: `$ drush php-script --user=1 massively-change-node-author.php`.

**EDIT:**

To avoid out-of-sync errors between `node` and `node_revision` table it's recommend to use `node_load()` and `node_save()` on the Nodes you want to update. Eg,

```
global $user;
foreach ($node_ids as $nid) {
  $node = node_load($nid);
  $node->uid = $user->uid;
  node_save($node);
}

```

Getting the list of node ids you want to affect, I leave as a task for you. The issues such as timeouts, using batch api etc -- are all still gone when using Drush. The logic is very similiar just using the better drupal API rather than direct database updates.
> 2 votes

# Answer
You can use Bulk Author Update module or also you can use views bulk operations module

The First solution is

1. Install the views, views\_bulk\_operations, and admin\_views modules.
2. Go to the content listing (admin/content).
3. Filter the results to get the nodes you are interested in.
4. Check the checkboxes next to the node (there is also an option to select all).
5. Select "Change author" from the operations dropdown and click the "Execute" button.
6. Select the user you want to change the author to and click the "Next" button.

Admin views uses views bulk operations to override the default drupal administration views with something a lot more useful.
> 1 votes

# Answer
May you can schedule the update task on cron run when site expects the least tracffic.In order to schedule the udpate process at specific time you can use elysia cron module. This way you will be able to update in bulk keeping revisions update as well and also the script will run as standalone.

Step 1 : Schedule the updat task(assuming you are using elysia module).

```
function mymodule_cron_cronapi($op, $job = NULL) {

    $items['update_node_user_author'] = array(
    'description' => 'Update node user author',
    'rule' => '0 12 * * *',
    'callback' => 'mymodule_update_node_author',
  );
 return $items;
}

 //cron call back
function mymodule_update_node_author() {
  // add logic to get $uid and $uid2
  // $uid is the user id you want to change for.
  // $uid2 is the user id you want to change with.
  exec("/usr/bin/php update_author.php $uid $uid2> /dev/null 2>&1 &");
}

```

Now create a php script named as update\_author.php in your drupal root add the following code inside it.

```
<?php

if (!isset($_SERVER['REMOTE_ADDR'])) {
  $_SERVER['REMOTE_ADDR'] = '127.0.0.1';
}
$uid = $argv[1];
$uid2 = $argv[2];

define('DRUPAL_ROOT', getcwd());
require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

  $query = new EntityFieldQuery();
  $query->entityCondition('entity_type', 'node');
  $query->propertyCondition('uid',$uid);
  $result = $query->execute();

  if (isset($result['node'])) {
    $nids = array_keys($result['node']);
    $nodes = node_load('node', $nids);
  }
  foreach($nodes as $node) {
    $node = node_load($nid);
    $node->uid = $uid2;
    node_save($node);
  }

```
> 0 votes

# Answer
I think the most comfortable and clean solution is to prepare view based on views\_bulk\_operations module (remember to install it).

Here is my exported view (you can import it on admin/structure/views/import).
> 0 votes

---
Tags: 7, nodes, database
---


# Question
Title: Adding a form to a product drupal commerce
I just want to add a form to a product and after I check the services in that form the amount increases. image of the page in the Picture the product price is 7$ but when I add the service it added 10$ then the amount become 17$. any solution for this?

# Answer
> 0 votes
Your looking for product variations. Here are the official docs.

> Product attributes are the descriptors we use to define kinds of products. For example, we could describe a tshirt by the color and size. These attributes mean that in the real physical world your store may only carry one red shirt, but you have three sizes or three "variations." Commerce software must deal with product variations in a flexible way. Here's how Drupal Commerce abstracts it:
>
> **Product Types**. A product type is a specific bundle based on a custom product entity. Each bundle can have fields attached to it, including pictures and other kinds of information.\<
>
> **Product "Informational" Fields**. Any field on a product can be a simple "informational" field. Typical informational fields include an image of that specific configuration of a product. For example, if you sell a tshirt with a cool print in multiple colors, each product with a different color could have an image field that, when displayed on the product display node, will change when you select different attributes (like color).
>
> **Product "Attribute" Fields.** Any field on a product type with a defined list of options (list of text options, list of taxonomy terms, list of colors). The attribute fields are special because of the way they turn into selection widgets on a product display. Often you will pair an attribute field (like a color dropdown) with an information field (like an image field) to let the user "select" the blue tshirt and the Drupal Commerce system will quickly load the picture associated with the blue product.
>
> **Product Displays.** If needed at all, these are groupings of products. You can reference any type and number of products on a product display. In order to make use of product displays, we recommend only showing one type of product per product display. The product display is where you typically see the product with drop downs to "configure" or "order" the right kind of product.

For the different pricing of the variations refeer here: Automatic product variations pricing.

---
Tags: 7, commerce
---


# Question
Title: Conditionals with Combining Fields in Views
I'm having issues with rewriting the results of a field. I am trying to rewrite the field to be a combinations of 3 fields:

* \[field\_products\]
* \[field\_downloadable\_products\]
* \[field\_product\]

When I preview my field I see this:

Is there a way to add a conditional statement to fix the issue where the other tokens are showing when there isn't a value there for those tokens?

Here is a view of my rewritten results:

# Answer
Instated of

```
 [field_products} [field_downloadable_products] [field_product]

```

Try

```
[field_products] [field_downloadable_products] [field_product]

```
> 1 votes

---
Tags: views, entities, log-messages
---


# Question
Title: How do I get an instance of AccountInterface in my Unit Test
I want to write a Unit test. But the class I want to test has a AccountInterface dependencie Injection.

When I try to get the AccountInterface Object I get:

> Drupal\Core\DependencyInjection\ContainerNotInitializedException: \Drupal::$container is not initialized yet. \Drupal::setContainer() must be called with a real container.

My test looks like this

```
<?php
namespace Drupal\mymodule\test;

use Drupal\mymodule\MyModuleQuery;
use Drupal\Tests\UnitTestCase;
use Drupal\user\Entity\User;

class MyModuleQueryTest extends UnitTestCase {

  protected $user;

  public function __construct() {
    $this->user = \Drupal::currentUser();
  }

  public function testResult() {
    $MyModuleQuery = new MyModuleQuery(1, $this->user);
    $countUser = $MyModuleQuery->mymodule_get_user();
    $countNode = $MyModuleQuery->mymodule_get_node();
    $bool = FALSE;
    if (!isset($countNode) && !isset($countUser)) {
      $bool = TRUE;
    }
    $this->assertTrue($bool);
  }
}

```

# Answer
You most likely want to mock your dependencies rather than trying to instantiate actual objects because a unit test *should* only test the class it describes. However this is not always as convenient.

In this case you are trying to call the `\Drupal::currentUser` static method which is dependent on the dependency injection container. An empty container can be created and used for the test, and test doubles available for it.

```
protected function setUp() {
  // use Drupal\Core\DependencyInjection\ContainerBuilder;
  $container = new ContainerBuilder();
  $account = $this->prophesize('Drupal\Core\Session\AccountProxyInterface');
  $container->set('current_user', $account->reveal());
  \Drupal::setContainer($container);
  $this->user = \Drupal::currentUser();
}

```

However you do not actually need the container, and can just use the test double.

```
public function testResult() {
  $accountProphecy = $this->prophesize('\Drupal\Core\Session\AccountProxyInterface');
  // Mock some methods.
  // $accountProphecy->getUserName()->willReturn('admin');
  $MyModuleQuery = new MyModuleQuery(1, $accountProphecy->reveal());
}

```
> 1 votes

---
Tags: 8, testing
---


title: How to modify comment reply form?

text:
# Question
Title: How to modify comment reply form?
I've installed the Ajax comments module.

I am not able to modify comment form. I want to modify the comment form which one is coming when click reply link.

**Note**: When I click add new comment the form will show subject, name, comment field. In reply option also showing same form. But I don't want subject and name in reply comment form.

# Answer
First of all the reply form and the comment form are the same forms (form\_id: comment\_node\_NODE\_TYPE\_form), you shouldn't think they are different forms.

Second, you would need some custom coding in your own module, that would look like this:

```
/**
 * Implements hook_form_FORM_ID_alter().
 */
function yourmodule_form_comment_form_alter(&$form, &$form_state, $form_id) {

```

OR, even more specific to comments on article nodes (you can replace article with page, blog, YOUR\_CUSTOM\_CONTENT\_TYPE)

```
function yourmodule_form_comment_node_article_form_alter(&$form, &$form_state, $form_id) {
  if (isset($form_state['comment'])) {
    $comment = $form_state['comment'];
    // if this is a reply, hide the two fields
    if($comment->pid > 0) {
      $form['subject']['#access'] = FALSE;
      $form['author']['#access'] = FALSE;
    }
  }
}

```

Good luck!
> 1 votes

# Answer
I know the pain. I already face the issue.

Just copy the below two functions in an new module and rename the first function name to module name.

***Explanation:***

Here we just need to remove ' + .indented' in line no 602 & 607. So copy entire `function ajax_comments_reply` code on to new module This does the trick

Use Menu alter function to modify page callback

```
function <MODULE_NAME>_menu_alter(&$items) {
// Altering Comment reply function to load form next to reply button
  $items['ajax_comment/reply/%node']['page callback'] = 'ajax_comments_reply_alter';

}

```

Remove 'indent' when rendering commands `ajax_command_append`.

```
 /**
 * Callback for clicking "reply".
 * Note: $pid is an optional parameter. This functionality is utilized by the
 * "Add new comment" link on pages where there is no default comment form
 * (comment_form_location is COMMENT_FORM_SEPARATE_PAGE)
 */
function ajax_comments_reply_alter($node, $pid = 0, $flag = 0) {
  if (!user_access('post comments')) {
    return MENU_ACCESS_DENIED;
  }

  // If there is a pid this is a reply to a comment.
  if (!empty($pid)) {
    if (!user_access('access comments')) {
      return MENU_ACCESS_DENIED;
    }

    // Make sure the comment is valid and published.
    if (!($comments = comment_load_multiple(array($pid), array('status' => COMMENT_PUBLISHED)))) {
      return MENU_NOT_FOUND;
    }
    $comment = $comments[$pid];

    // Make sure the comment belongs to this node.
    if ($comment->nid != $node->nid) {
      return MENU_NOT_FOUND;
    }
  }

  if ((!user_is_anonymous() || (user_is_anonymous() && variable_get('cache', 0) != 0))) {
    // Authenticated user or anonymous and page cache is enabled
    $key = _ajax_comments_cache_key($node->nid, $pid);
    if ($cache = cache_get($key)) {
      // Get form from cache
      $form_build = $cache->data;
    }
    else {
      // Build form and Save to cache*/
      $form_build = drupal_get_form("comment_node_{$node->type}_form", (object) array('nid' => $node->nid, 'pid' => $pid), array('flag' => $flag));
      cache_set($key, $form_build, 'cache', time() + 360);
    }
  }
  else {
    // Anonymous and page cache is disabled
    $form_build = drupal_get_form("comment_node_{$node->type}_form", (object) array('nid' => $node->nid, 'pid' => $pid), array('flag' => $flag));
  }

  $form = trim(drupal_render($form_build));

  if (variable_get('ajax_comments_reply_autoclose') && !empty($pid)) {
    $commands[] = ajax_command_remove('.ajax-comments-form-reply');
    $commands[] = ajax_command_invoke('.ajax-comments-reply', 'show');
  }

  // Add the new form.
  if (!empty($pid)) {
    $mode = variable_get('comment_default_mode_' . $node->type, COMMENT_MODE_THREADED);
    if (empty($mode)) {
      $commands[] = ajax_command_after('.comment-wrapper-' . $pid, $form);
    }
    else {
      // Add div with class "indented" if they are not exist
      $commands[] = array('command' => 'ajaxCommentsAddDummyDivAfter', 'selector' => '.comment-wrapper-' . $pid, 'class' => 'indented');
      // Check sort by comment_goodness.
      if (_ajax_comments_get_comment_sort_order($node) == 1) {
        // Newer first.
        $commands[] = ajax_command_append('.comment-wrapper-' . $pid, $form);
      }
      else {
        // Older first.
        $commands[] = ajax_command_prepend('.comment-wrapper-' . $pid, $form);
      }
    }
  }
  else {
    // Check Views Add form
    if (!empty($flag)) {
      $commands[] = ajax_command_after('.views-comment-wrapper-nid-' . $node->nid . ' > .ajax-comment-wrapper:last', $form);
    }
    else {
      // Check sort by comment_goodness.
      if (_ajax_comments_get_comment_sort_order($node) == 1) {
        // Older first. Append comment to last wrapper.
        $commands[] = ajax_command_after('.comment-wrapper-nid-' . $node->nid . ' > .ajax-comment-wrapper:last', $form);
      }
      else {
        // Newer first. Append comment to top.
        $commands[] = ajax_command_before('.comment-wrapper-nid-' . $node->nid . '> .ajax-comment-wrapper:first', $form);
      }
    }
  }

  // Hide reply to comment link
  $commands[] = ajax_command_invoke('.ajax-comments-reply-' . $node->nid . '-' . $pid, 'hide');

  if (!variable_get('ajax_comments_disable_scroll', 0)) {
    $commands[] = array('command' => 'ajaxCommentsScrollToElement', 'selector' => '.ajax-comments-reply-form-' . $node->nid . '-' . $pid . '-0');
    $commands[] = ajax_command_invoke('.ajax-comments-reply-form-' . $node->nid . '-' . $pid . '-0 .form-textarea' , 'focus');
  }

  return array('#type' => 'ajax', '#commands' => $commands);
}

```

And Dont forgot to clear cache.
> 1 votes

# Answer
There are couple of ways to modify the comment form. For example you can use **CSS** to hide the elements.

`.comment-wrapper .form-item-name { display: none; }`

OR place the following in your custom module to remove 'Your Name' from the output

```
function YOUR_MODULE_form_comment_form_alter(&$form, &$form_state)
{
  $form['author']['#access'] = FALSE;
}

```

or you can override the comment form tpl
> 0 votes

---
Tags: ajax, comments
---


# Question
Title: In Drupal 7 Commerce, where do you send an order completion confirmation email to administrators or store owners?
I just noticed that I wasnt getting any confirmation emails when there is a order completion. Where do I set this up so I can get an email notifying me of a completed order for Drupal 7 commerce?

# Answer
By default for Drupal Commerce (not the Aquia version) there is no email connectivity set up for order complete confirmations - yes there is a rule which defines the message that is sent and when it is sent, but the third party module Commerce Message available here https://www.drupal.org/project/Commerce\_message must be installed. There is no place in the rule which allows configuration of a specific e-mail address. This functionality also requires the Message and Message Notify modules
> 1 votes

# Answer
I guess this is available in the rules provided by the drupal commerce at (`admin/commerce/config/checkout/rules`):

```
admin -> commerce -> config -> checkout -> rules -> "Send an order notification e-mail"

```

Configuration of recipient email address including the admin address you want the order confirmation sent to can be done at this place.

Also you can check the doc for commerce order mail: https://drupal.org/node/2061215
> 2 votes

---
Tags: 7, commerce
---


# Question
Title: Contact Forms - Change Recipient Address Dynamically - D8
I'm using the core contact forms module in Drupal 8, and what I need to do is add a select with multiple options, each option needing to change the recipient address.

How can I do this using the built-in module, or do I need a different module?

# Answer
> 3 votes
After a lot of playing around and digging about, I've actually found out that it's quite easy to do this. After installing the Contact Storage module, when editing a contact forms' fields, you can add a field named `Options email`.

You then are given a large text area to input keys, labels and email addresses.

```
Support Query|Support Query|example@example.com
Sales Enquiry|Sales Enquiry|example@example.com
Admin/Accounts Query|Admin/Accounts Query|example@example.com
Partner Query|Partner Query|example@example.com

```

After adding the above, I was given a `select` to pick from one of my options. This successfully changed the email recipient.

# Answer
> 3 votes
The contact\_storage module has a feature that allows you to create a list that include a key, value and e-mail and then the mail is sent to that.

You can either use that, or you can do it yourself in a similar way. You could use a term reference for example and have a field on your terms for the e-mail. The relevant code is in `contact_storage_mail_alter()`:

```
$contact_message = $message['params']['contact_message'];
foreach ($contact_message->getFields() as $field) {
  if ($field->getFieldDefinition()->getType() === 'contact_storage_options_email') {
    // One of the Option email item fields. Add the recipient to the message.
    foreach ($field as $delta => $item) {
      $label = $item->value;
      // Obtain the email to add to the message, using the label.
      $email = $item->getFieldDefinition()->getSetting('allowed_values')[$label]['emails'];
      $message['to'] .= ',' . $email;
    }
  }
}

```

}

---
Tags: 8, emails
---


# Question
Title: Why I'm getting theme related error when trying to add external JS to form?
I'm trying to add Google Map API to node form:

```
/**
 * Implements hook_form_FORM_ID_alter().
 */
function mm_form_node_foo_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id)
{
    $form['#attached']['library'][] = 'google/maps';
}

```

Library config (mm.libraries.yml in module root directory):

```
google.maps:
  js:
    https://maps.googleapis.com/maps/api/js?key=API_KEY&libraries=places&callback=initMap: {type: external, attributes: { defer: true, async: true, data-test: map-link } } }

```

and the error is:

> User warning: The following theme is missing from the file system: google in drupal\_get\_filename() (line 234 of core/includes/bootstrap.inc).

# Answer
You probably need to add the module/theme name before the attached library:

```
$form['#attached']['library'][] = 'mm/google.maps';

```

Otherwise drupal is looking for google as your module/theme name.
> 4 votes

---
Tags: forms, 8, javascript
---


# Question
Title: Including Part Template within a Custom Module
I am writing a custom module that uses several twig templates in my modules /templates directory. I want to use part templates (https://www.drupal.org/node/2634166) so that I could reference the following:

```
{% include directory ~ 'includes/spr_table_selectors.twig' %}

```

The problem is my include keeps referencing my main site theme (themes/mytheme/...). Is there an easy way I can reference my includes directory within my custom module?

# Answer
There should be a change to the theming documentation in this case. Namespace for twig is always set to `MYTHEME/templates` or `MYMODULE/templates`.

The `directory` variable is to `ACTIVETHEME/templates`.

So if you look at how the Symphony folks have been do things, you will find out they have their template parts in a subdirectory named `parts` rather then a sibling directory named `includes`. Use the subdirectory will fixed your problem. **BONUS** you can use `@` to call the namespace of your module or theme like this:

```
<header>
  {% include '@MYMODULE/parts/header.html.twig' %}
</header>

```

Remember to keep your template part name(s) unique from the templates in use by your Drupal install to avoid them being used as a full template item that overrides something provided by core or another module.
> 5 votes

---
Tags: theming, 8
---


title: Set class to an input with twig

text:
# Question
Title: Set class to an input with twig
Hello i am working on theming for Drupal 8 using twig My question is :
I want to assign css class to each input swicth the type of the input
exemple
`<input type='email' class='email_cls'>`

```
<input type='submit' class='submit_cls'>

```

what code should i use ,knowing that i use the default template twig file **input.html.twig**
I did this

```
<input{{ attributes.addClass('submit_cls email_cls') }} />{{ children }}

```

The problem is on my form both of the inputs email & submit have the same display

# Answer
You could use this in your theme:

```
function template_preprocess_input(&$variables) {
  $variables['attributes']['class'][] = 'your_class';
}

```

and maybe even check the type like:

```
function template_preprocess_input(&$variables) {
  if ($variables['attributes']['type'] == 'email') {
    $variables['attributes']['class'][] = 'your_class_email';
  }
}

```
> 3 votes

# Answer
You have to enable suggestion templates by adding in your settings.php (in /site/\_your\_website\_)

```
$settings['theme_debug'] = true;"

```

and you will see in your DOM inspector some suggestions in HTML comments like "input--file.html.twig" for input of type file.
> 0 votes

---
Tags: 8, theming
---


# Question
Title: When creating content: Force the checkbox "Provide a menu link" to be checked by default
When creating content, I would like to force the checkbox "Provide a menu link" to be checked by default.

What I'm really trying to do:

* I created a new content type
* I used `node_add` to get the form associated to my content type and render it into my template.
* In my module I used the `hook_form_alter` to hide some fields of my form.

But when the user submit the form and the node is created, there is no menu link created by default.

# Answer
> 2 votes
I solved my problem.

To force the creation of a menu link I used the hook function hook\_node\_insert:

```
function *MODULE*_node_insert($node){
        if($node->type == '*CONTENT TYPE*'){
            $node->menu['enabled'] = true;
            $node->menu['link_title'] = $node->title;
        }
}

```

# Answer
> 3 votes
I looked everywhere for this! The Menu Force module does this:

> This module enables you to make the Menu Settings required on specific content types.

After installing a *"Make the Menu Settings mandatory for this content type"* tick box becomes available on the settings for each content type.

# Answer
> 1 votes
Use `hook_form_alter` to set the `#default_value` of the *Provide a menu link* checkbox to `true`.

# Answer
> -1 votes
Simple install https://www.drupal.org/project/default\_menu\_link and there you go.

There is a similar module called Menu Force that does just that. Whereas Menu Force mandates menu assignment, Default Menu Link merely changes the status of "Provide a Menu Link" to true. The user can still create content and choose to un-check this box. However, the default state (on node creation) will be true, and as long as you've set a default menu parent item, all content will be filed under that parent.

---
Tags: 7, routes, forms
---


# Question
Title: Adding additional dynamic to a canonical view
Wasn't sure exactly what to search for in trying to find recommendations for this.

I have created a custom content entity type with some numerical fields. The canonical view for this entity uses `"views_data" = "Drupal\views\EntityViewsData"` as specified in the entity definition annotation. This entity type does not depend on `node`. Some modifications are made to the display of the field data using hook\_entity\_view\_alter and hook\_page\_attachments. This is all working fine.

What I would like to do is two things:

1) add an additional HTML section to the canonical view, below the display of all the entity parameters, which displays the results of a database query. The query being executed will depend on the content of the entity being loaded. Currently I am just using "echo" to test, but that spits the results out at the top of the document.

2) add a form to the canonical view containing one text field, one dropdown, and one button. The contents of the dropdown will also depend on the entity field content. The button should perform some calculations on the numerical fields based on the form inputs, and adjust the build array contents accordingly after reloading the page.

I am not really sure what approach to take here or how to execute it, and would like to ask for recommendations and examples to look at. Should I be creating a custom class that extends `Drupal\views\EntityViewsData` to accomplish all of this? Should I be doing this with Twig instead (which I am not very familiar with and can't seem to find many examples similar to what I'm trying to do)? Would using jQuery instead be a better approach?

# Answer
This would be the answer to the two questions:

1) add additional HTML to the canonical view

When using `hook_ENTITY_TYPE_view()` you have a render array and you can place new array keys with additional render elements. Don't use echo for testing, put it in the build array like this:

```
$build['text1'] = ['#markup' => '<p>Text 1</p>'];

```

2) add a form to the canonical view

Build a form class for this form. Then you can place the form also in `hook_ENTITY_TYPE_view()`:

```
$build['myform'] = \Drupal::formBuilder()->getForm('Drupal\mymodule\Form\MyForm');

```

You can pass additional parameters in `getForm()`, if you need information from the entity to build the form.

I don't understand what you are trying to do with `Drupal\views\EntityViewsData`. Other than mentioning this one class you are not writing anything else about views.
> 2 votes

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


title: Module webform2pdf modify template

text:
# Question
Title: Module webform2pdf modify template
I have sereval webforms et each webform send a mail with a pdf. I would like to do a template for each webform. I use webform2pdf in Drupal 7 to send pdf by email. How can i do that ?

# Answer
I'm working with this module right now too.

Once the module is enabled (and the required tcpdf library is intalled), you will see a new "Generate PDF" tab when editing each of your webforms. This is where you can add your PDF template under "Content of the PDF Document"

If you enter stuff here, it overrides anything you may have set globally (under /admin/config/content/webform2pdf).

You can use html and tokens here, for example...

```
<p>INTERN NAME: [submission:values:intern_name]</p>

```

I hope this helps.

If you get this working, maybe you (or somebody reading this) can help me with a problem I'm having: I want to add conditional logic for some of my fields so they only show up in the PDF if a value is entered.

I tried this via the interface (I have PHP filter module installed), but it resulted in a completely blank PDF, so now I'm going to try doing a template override instead.
> 0 votes

---
Tags: webforms, files
---


# Question
Title: Retrive specific deleted nodes and re-import
Some nodes (from two different CTs) have been deleted accidentally and there is no way to restore them.

The question: is it possible to retrieve and import these very specific deleted nodes from our backups without making a full database restore, and having the reassembled nodes back to the UI, is there any method/technique that will work ?

One of our CTs consists of many many fields (~80) of any possible type image, link, entity/taxonomy reference, integer, text, file and Boolean.

I have already looked at the Node export but it depends on the uuid module and I don't have that installed.

# Answer
We had this same problem on one of our sites and the best solution we could come up with was to use Node Export as you mentioned. Like you, we didn't have it or UUID installed at that time, but we installed them just for this purpose, and it worked fine.

The only catch is you need to be able to load the backed-up database into a functioning site (we did it on our test server) before you can export the missing nodes.
> 2 votes

---
Tags: 7, database
---


# Question
Title: Fatal error: Class 'Drupal\module_name\DOMDocument' not found
> Fatal error: Class 'Drupal\module\_name\DOMDocument' not found in /var/www/drupal/modules/module\_name/src/form\_xml.php on line 359

Any idea why Drupal cannot find DOMDocument class?

I want to execute a code when a form is submitted

```
  public function submitForm(array &$form, FormStateInterface $form_state) {
    // Find out what was submitted.
    $form_field = $form_state->getValue('content_types');

    foreach ($form_field as $key => $value){
      if (!empty($value)){
        $return = File::generate();
      }
    }
  }

```

In case you are wondering, module\_name is the name of my custom module.

File::generate() is a static method which contains the DOMDocument class

**The code works fine when I use devel to execute it**, so any idea why can't it find the DOMDocument class on form submit?

Seems to me as if the form blocks access to the DOMDocument class.

# Answer
You need to rename the form class file CamelCase and make a namespace declaration at the top. The namespace will be `Drupal\module_name\Form`. Place the form class file in directory module\_name/src/Form/.
> 1 votes

---
Tags: forms, 8
---


title: How to get route name YAML Block/Form?

text:
# Question
Title: How to get route name YAML Block/Form?
I am not a coder, how can I get a route name from YAML Form (ex.Contact form) and put it to YAML Block? Is there a route name UI like path auto UI? thank you

# Answer
> 0 votes
Drupal routes aren't display in a UI anywhere, but you can look them up in a database client (e.g. PHPMyAdmin). The route defnitions are stored in the `router` table. The `name`, `path`, & `pattern_outline` columns should be enough to search for what you're looking for. The name column contains the unique ID for each route. In your case, `contact.site_page` is the name of the contact form route.

---
Tags: 8
---


# Question
Title: Pre-select a role on user register form and hide from display?
I have this scenario that I am trying to walk through. I am new to creating custom modules, but I'm working on it (only way to learn...right?)

How would I go about doing this as I'm currently getting an error when trying. I have a role: 'venue admin' that will be responsible for adding other users with the role of 'customer'. I already am using the module: Role Delegation to handle the permissions side of things. But on the User Registration screen, I would like the customer role to be pre-selected and hidden from display.

This is what I have so far:

```
/**
 * Implements hook_form_FORM_ID_alter().
 *
 */

function mandatory_role_form_user_register_form_alter(&$form, &$form_state,   &$form_id) {
global $user;

if(in_array('venue admin', $user->roles)) {
// by default notify user of new account is checked
    $form['account']['notify']['#default_value'] = TRUE;
// the only role the venue admin role can create is a customer so this is checked and hidden.
    $form['account']['roles']['#access'] = FALSE;
  }
}

```

obviously, this is not complete and missing the ability to set the role. Any suggestions?

# Answer
well..after staring at this question and trying a bunch of things on my own I think I stumbled upon the answer. Using HOOK\_user\_presave did the trick! This helped immensely: https://drupal.stackexchange.com/a/79065/28353

```
function mandatory_role_user_presave(&$edit, $account, $category) {
global $user;
if(in_array('venue admin', $user->roles)) {
  if($account ->is_new) {
    $roles = user_roles(TRUE);
    $rid = array_search('customer', $roles);
    if($rid != FALSE) {
      $edit['roles'][$rid] = 1;
        }
      }
    }
  }

```
> 0 votes

---
Tags: users, hooks
---


# Question
Title: Multiple Custom Modules Using Same External JS Lib (e.g. Angular)
I've been pulled onto a Drupal 8 project with multiple custom modules that need to use Angular.js. What is the best way to provide the Angular files to each module?

Right now, each module references the remote Angular files hosted by googleapis.com in `my-module.libraries.yml`.

```
my-module:
  version: 1.x
  js:
    https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js: { type: external, minified: true }
    https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular-sanitize.min.js { type: external, minified: true }
    js/my-module.js: {preprocess: false}
  dependencies:
    - core/jquery
    - core/jquery.ui
    - core/jquery.ui.accordion

```

However, I would prefer to host the Angular files locally and list them as dependencies just like jQuery.

I know I could put the Angular files in the module itself, but then each module would need its own copy.

Whatever is the proper way to do it, my goal is to host the Angular files locally and reference them from each module that depends on Angular.

# Answer
> 1 votes
The simplest way to solve this is to add a `/libraries` folder at the root of the Drupal project. Then create a sub-directory for each external library you are using, and reference that from your `module.libraires.yml` file.

For example, I created `/libraries/angular/js`, placed the files in there, and then referenced them by starting with a `/` in the code below.

```
my-module:
  version: 1.x
  js:
    /libraries/angular/js/angular.min.js: {}
    /libraries/angular/js/angular-sanitize.min.js: {}
    js/my-module.js: {}
  dependencies:
    - core/jquery

```

Now any module within the project can reference the same files.

---
Tags: 8, javascript
---


# Question
Title: how to delete the nodes having a specific entity reference but not the parent
I have a content type "students" and another "courses". Student nodes are created with an entity reference to a course node.

I need to delete all students of "couses123" in a quick way. How can I make a view which has a dropdown of all course names and when selected it shows list of all students.

From there, I can use the VBO to show a checkbox next to them for selection and deletion .

How can I achieve this?

# Answer
If this a one-time need, you could build a custom query DB query if you wanted to go the developer route. However, if this is an ongoing need you're better off with the site builder route you've hinted at in your question.

In your case, you want to a create a node view filtered by content type *Students*. Add a **Entity Reference: Referenced Entity** for the field that contains your references to *Courses*. The last step is to add an exposed filter for the same *Courses* field making sure enable relationship that you added; that will present a select list of referenced Courses from which you can filter down the *Students* and present your VBO delete widget.
> 2 votes

---
Tags: 7, views
---


# Question
Title: How to get a notification when user is blocked following flood
I'm trying to get an email sent to me every time an account is banned following a flood (5 tries).

Unfortunately, a user that is blocked isn't set to "status = 0", so I cannot use a rule based on user status. I did a few search and couldn't find Rules integration with the Flood Module.

Is it part of the core? Is there anything other way to provide Rules integration with Flood?

# Answer
> 1 votes
Yes, Flood is part of core (it lives in `includes/common.inc`, and because Rules is a contrib module, there is no set way to integrate cleanly in Drupal 7.

The one thing you might be able to do is to do a form\_alter() on functions like `user_login_final_validate($form, &$form_state)`, since if a flood event has been triggered they will include a form value such as `$form_state['flood_control_triggered']` which, when it is not empty, will indicate that a login attempt has been blocked. Then of course your custom form\_alter implementation can call any Rules events it likes.

This is totally untested so I can't verify that it would work, but for now there doesn't seem to be an easy or clean way to do this in D7.

---
Tags: rules, users
---


# Question
Title: Set Home link in breadcrumb for items in a particular menu
I have two menus: **Main** and **Members**. My breadcrumbs in the **Main** menu are working just fine as defaults.

I would like to customize the breadcrumb for any menu item in the **Members** menu. Specifically, I'd like *Home* to be changed to *Members* and the URL to be `\members` instead of `\`.

Is there a hook or module that can do this?

# Answer
In my opinion, if you want to customize the breadcrumb, the Path Breadcrumbs is the best module for this kind of purpose.

> This module is a solution for all problems with the breadcrumbs on your site!
>
> Path Breadcrumbs module helps you to create breadcrumbs for **any page** with **any selection rules** and load **any entity** from the URL!

You can follow this tutorial for the help.
> 2 votes

---
Tags: breadcrumbs
---


# Question
Title: How to find and remove string in front of URL?
We have a url pattern of \[node:menu-link:parents:join-path\]/\[node:title\].

We are finding that it is resulting in the following urls and we wanted to see if we could use hook\_pathauto\_alias\_alter to remove the undesired string. We are finding that when doing the preg\_replace, that is removing all instances where the "/" is found. We just want to remove the string upto the first "/" character. Need assistance in figuring out why it is not working.

```
function mymodule_pathauto_alias_alter(&$alias, array &$context) {
       $patt = '.+(\/)';
       $replacement = '';
       preg_replace($patt, $replace);
}

```

Current results:

* some-text/menu-linka/menu-linkb
* some-text/menu-linka/menu-linkb/menu-linkc

Desired results:

* menu-linka/menu-linkb
* menu-linka/menu-linkb/menu-linkc

# Answer
I see many problems in the code you posted in your question. First of all, you are missing a parameter in `preg_replace`. Take a look at the PHP documentation.

Second, you have no delimiters in your pattern. The correct pattern should be:

`$patt = '/.+\//';`

(You don't need the parenthesis, but you do need delimiters such as slash bars. See this).

Third, `preg_replace()` returns an array with the replacement. You need to assign the result to $alias, as in `$alias = preg_replace(...)`

I have not use this hook before, but keep in mind (from the description) that this is only invoked before the alias is saved.
> 1 votes

# Answer
you can handle this with global redirect module, it is useful module that could handle what you want and give your some ability to improve your site SEO.

> GlobalRedirect is a simple module which…
>
> ```
> Checks the current URL for an alias and does a 301 redirect to it if it is not being used.
> Checks the current URL for a trailing slash, removes it if present and repeats check 1 with the new request.
> Checks if the current URL is the same as the site_frontpage and redirects to the frontpage if there is a match.
> Checks if the Clean URLs feature is enabled and then checks the current URL is being accessed using the clean method rather than the
>
> ```
>
> 'unclean' method. Checks access to the URL. If the user does not have access to the path, then no redirects are done. This helps avoid exposing private aliased node's. Make sure the case of the URL being accessed is the same as the one set by the author/administrator. For example, if you set the alias "articles/cake-making" to node/123, then the user can access the alias with any combination of case. Most of the above options are configurable in the settings page. In Drupal 5 you can access this after enabling the globalredirect\_admin module. In Drupal 6, the settings page is bundled into the module.
> 0 votes

---
Tags: 7, hooks, path-aliases, navigation
---


# Question
Title: Help required to set up multisite using organic groups (OG module)
I would like to create different multisite using organic groups in drupal. Each organic group would be a subdomain or domain. How can I achieve this functionality? I do not want to use domain access module.

What I exactly want is, when an organic group is created it should ask for the subdomain or domain and the user can enter the subdomain or domain which is to be associated to that organic group. Then when the user enters the subdomain.site.com the appropriate organic group should load. site admin associate to this organic group can login like this subdomain.site.com/user.

How can the above scenario achieved through organic groups?

# Answer
> 1 votes
Ok I have done it using Organic groups, spaces module and PURL.

1. First Install Spaces module after installing drupal
2. Then you can install PURL module and then organic groups module and OG theme module. OG theme associates theme to a group. You can also install OG menu if needed.
3. Once PURL is installed, go to admin/config/search/purl/types, enable subdomain option and domain option if needed.
4. Now create a content type of Group type or install OG example module (it automatically creates a organic group content type)
5. Now create a node which is of type group - node/add/group
6. Fill in the options and enter the Subdomain. For the subdomain to work you should have added ServerAlias \*.site.com in your httpd.conf file
7. Once the node of type group is created your minisite is ready.
8. Using OG theme you can associate a separate theme for your organic group created.
9. Using og menu you can associate a separate menu for your organic group.

---
Tags: organic-groups
---