title: Internal path in twig template

text:
# Question
Title: Internal path in twig template
I'm trying to link to a Drupal path like "Contact Us" in my Twig template. I've tried this code in my Twig template but I can't get any result.

```
<a href="{{ contact }}">{{ 'Contact'|t }}</a>

```

As well as this:

```
<a href="{{ path('contact') }}">{{ 'Contact'|t }}</a>
<a href="{{ url('contact') }}">{{ 'Contact'|t }}</a>

```

What is the correct way to link to an internal Drupal path in Twig?

# Answer
> 5 votes
The `path()` & `url()` Drupal Twig functions expect a ***route name*** and will not work with a Drupal ***path***. For a relative/absolute path to **/contact**, you can use `path()`/`url()` respectively with the `contact.site_page` route:

```
<a href="{{ path('contact.site_page') }}">{{ 'Contact'|t }}</a>
<a href="{{ url('contact.site_page') }}">{{ 'Contact'|t }}</a>

```

If you don't know your route name, what you're looking for is `link()`

```
{{ link('Contact'|t, 'base:contact', { 'class':[] }) }}

```

See this d.o. page for more explanation about these 3 functions and their differences.

---
Tags: theming, 8, path-aliases, navigation
---


# Question
Title: Add location to to profile2 just after the user registers
I am trying to force add a location to a user's profile2 just after the user register's an account. The user's are able to add locations to their profile by using flags, but since there are no locations just after the user registers, the rules add fails because the locations list has not been initiated.

The below code is what I currently have:

```
if (isset($account->is_new) && !empty($account->is_new)) {
  function user_account_presave_user_presave(&$edit, $account, $category) {
    global $user;

    // Load profile2.
    $profile = profile2_load_by_user(array('type' => 'next', 'uid' => $user >uid));

    // Add in the necessary custom fields and values.
    $profile->field_next_destination['und'][] = array(
      'longitude' => '0.0',
      'latitude' => '0.0',
    );

    // Save the profile2 to the user account.
    profile2_save($profile);

  }
}

```

I am not sure if the IF statement should be in the Function, but if it is not, the Function fails to allow users to register because the CAPTCHA reuse attack function is triggered.

Has anyone ever run into this?

Thank you!

# Answer
> 1 votes
Try using `hook_user_insert` instead. The `$account` will have `$account->uid` set at that stage.

P.S wrapping `hook_user_presave` in that condition looks wrong and probably won't work with the hook registry cache.

---
Tags: 7, users, hooks, location
---


# Question
Title: Using the web interface or using Drush cause different result?
What is the difference executing an upgrade from Drupal 6 or 7 to Drupal 8 using the web interface or it's better to use Drush?

If the database is heavy, using either of them would have different result?

# Answer
From the technical perspective, the PHP configuration can be different for web server (Apache) and when running from CLI (drush), since different `php.ini` is loaded, therefore different limits are applied, sometimes your PHP could be different.

If you're non-technical person and it's one time (simple) process, it's better to use web interface, which is recommended way to upgrade your Drupal. The size of database doesn't make any difference, since the batch operation can perform long operations, but it may fail in the middle if you lost your connection.

On the other hand if you're repeating the process many times in order to test it properly, Drush may be a better solution, since you can test the process in more efficient and consistent way especially across multiple environments, this is especially useful if you've continuous integration in place (such as deployments).

So it's really depending on your needs.
> 1 votes

---
Tags: drush, upgrading
---


# Question
Title: Copying field values from one EntityForm to another on submit
I'm using Drupal 7 and the Entityform module to build a form for people to fill in on my website.

This form will be filled in by a parent and contains some data about his child. There will be 2 buttons:

* 1 for submitting the form data (default submit button/function)
* 1 for submitting the form data + opening a new form (of the same type) for a 2nd child (custom submit button/function).

Since this 2nd child will have a lot of data (address, last name,...) that's the same as the first child I'd like to already have those fields filled in in the 2nd form (by using field values from the first form). The same can be repeated for a 3rd child, a 4th child,...

This is my code so far:

```
function extra_inschrijving_form_alter(&$form, &$form_state, $form_id){

    if ($form_id == 'generiek_inschrijvingsformulier__entityform_edit_form'){
        $form['submit2'] = $form['actions']['submit'];
        $form['submit2']['#value']='Inschrijven en ook een broer inschrijven';
        $form['submit2']['#weight']=100;
        $form['submit2']['#submit'][1]='extra_inschrijving_default_wp_submit';
    }
}

```

This code added another submit-button and attached a submit handler (this works).

```
function extra_inschrijving_default_wp_submit($form, &$form_state){
   $values = &$form_state['values'];

   $prepopulates = array(
      'edit[field_entity_reference][und]' =>
            $values['field_entity_reference']['und'][0]['target_id'],
      'edit[field_1][und][0][value]' => $values['field_1']['und'][0]['value'],
      'edit[field_2][und][0][value]' => $values['field_2']['und'][0]['value'],
   );

   $form_state['redirect'] = array(
     'node/11',
     array(
        'query' => $prepopulates,
     ),
  );
}

```

Here I copy some field values from the form that will be submitted into the new form that has to be filled in. The parent should still be able to change the fields if he wants to. Both the normal fields and the entity reference field (select list) are copied/prepopulated successfully, but if the parent changes the entity reference field on the new form it still contains the old, prepopulated value when he submits it (although visibly something else is selected in the list).

# Answer
If you don't mind using query parameter for passing value. Prepopulate would be your choice.

Example code:

```
function extra_inschrijving_default_wp_submit($form, &$form_state){
  $values = &$form_state['values'];
  $prepopulates = array(
    'edit[title]' => $values['title'],
  );
  $form_state['redirect'] = array(
    'node/add/article',
    array(
      'query' => $prepopulates,
    ),
  );
}

```

`$prepopulates` is an array for query parameter which will pass the pre-filled values to the node add form. The array keys specify the fields prepopulate to. You can learn how to set the key from the handbook page.

At this moment, the latest stable version 2.1 has a known bug and it is discussing here. If you the module is not working on some field, you may need to add the patch in the thread. I don't recommend the older stable version because 2.1 has fixed an exploit.
> 0 votes

---
Tags: 7, forms
---


title: Views pagination, jquery and ajax error

text:
# Question
Title: Views pagination, jquery and ajax error
I have emerged me a problem with a page view and maybe someone can help me solve. Following this tutorial: http://codekarate.com/daily-dose-of-drupal/multiple-views-part-3 I created a view showing a content in 2 ways (such as poster and poster with text). For this purpose uses a javascript file that is responsible for displaying two different ways the contents of the view. Everything worked fine until add a pager and save the view with ajax enabled. Suddenly everything stopped working. It works only on the first page, if you press the Pager (with ajax) the next page and nothing works. The script is as follows:

---

```
(function ($, Drupal, window, document, undefined) {

Drupal.behaviors.my_custom_behavior = {
  attach: function(context, settings) {
//Sets default class for course views and toggles class when changing view.
$('#content').once('course-view', function() {
  if ($(".view").hasClass("course-view")) {
    $(".view").addClass("grid-view"); // Sets .grid-view as default class on the view

    $(".list").click(function() {
      if ($(".view").hasClass("grid-view")) {
        $(".view").addClass("list-view"); // adds .list-view to the view class
        $(".view").removeClass("grid-view"); // removes .grid-view from the view class
      }
    });

    $(".table").click(function() {
      if ($(".view").hasClass("list-view")) {
        $(".view").addClass("grid-view"); // adds .grid-view to the view class
        $(".view").removeClass("list-view"); // removes .list-view from the view class
      }
    });
  }
});

  }

    };

})(jQuery, Drupal, this, this.document);

```

Can somebody help me? Why only works on the first page?

# Answer
> 2 votes
Views Ajax is same as the Drupal Ajax, ajax response also run the behaviors.

What you need to do is removing the `once()` because it will stop your event binding for the second time. For preventing the event bound twice due to the ajax, just remember to add `context` as scope when you search for the element with jQuery.

```
(function ($, Drupal, window, document, undefined) {

Drupal.behaviors.my_custom_behavior = {

  attach: function(context, settings) {

    // Sets default class for course views and toggles class when changing view.
    // Context is important here for limiting the scope.
    var view = $(".view", context);

    if ( view.hasClass("course-view") ) {
      view.addClass("grid-view"); // Sets .grid-view as default class on the view

      $(".list", view).click(function() {
        if (view.hasClass("grid-view")) {
          view.addClass("list-view"); // adds .list-view to the view class
          view.removeClass("grid-view"); // removes .grid-view from the view class
        }
      });

      $(".table", view).click(function() {
        if (view.hasClass("list-view")) {
          view.addClass("grid-view"); // adds .grid-view to the view class
          view.removeClass("list-view"); // removes .list-view from the view class
        }
      });
    }
  }
};

})(jQuery, Drupal, this, this.document);

```

---
Tags: views, javascript, paging
---


# Question
Title: How to disallow users with a username containing test to login?
I created a module but I'm looking to have this module to intercept a user log in. I want to prevent any users with "test" in their login name from using the site. Is there a way to do this?

# Answer
> 1 votes
Custom username validation would be an option

> allows to define a validation pattern for the username on registration. it's also possible to customize the error message on validation failure.

# Answer
> 0 votes
Hope this will help you,

In Drupal 7 you can achieve this using **Clientside Validation** module.

* Clientside Validation : Adds clientside validation for all **forms** and **webforms** using **jquery.validate**

**Note** : Once module is enabled go through **README.TXT** for documentation.

References:

# Answer
> 0 votes
It is pretty straight forward to answer this question using Rules. Here is a rule (in Rules import format) that should answer your question:

```
{ "rules_redirect_to_logout_for_test_users" : {
    "LABEL" : "Redirect to logout for test users",
    "PLUGIN" : "reaction rule",
    "ACTIVE" : false,
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "user_login" : [] },
    "IF" : [
      { "text_matches" : {
          "text" : [ "account:name" ],
          "match" : "\\btest\\b",
          "operation" : "regex"
        }
      }
    ],
    "DO" : [
      { "drupal_message" : {
          "message" : "User names are not allowed to contain TEST ...",
          "type" : "error"
        }
      },
      { "redirect" : { "url" : "user\/logout" } }
    ]
  }
}

```

The rule will be triggered (Rules Condition) right after login was completed. For any user with a username containing "*test*", it will perform these Rules Actions (in the order specified):

1. Set an appropriate error message.
2. Redirect to the page `user/logout` (= force the user to be logged out again).

**Notes**:

* By default the rule is disabled (so don't forget to enable it also).
* The above approach limits such user to only visiting anything that can be accessed by anonymous (you can't prevent a user with a name containing "test" to visit the site anonymous).

---
Tags: 7, users
---


# Question
Title: Inserting submenu to main menu using jquery - good idea?
I have main menu showing only first level links (3 items).

```
**Home**
**Themes**
-green
-blue
-red
**Jokes**
-long
-short
-medium

```

I am using Menu block module (to show second level items) + Power menu (to make menu items active if current node has certain term). So when a node with taxonomy "theme" is displayed, the items under "themes" shows up in block menu.

What I would like to do is to somehow inject the block menu items inside primary menu. The main reason is to be able to use responsive menu, that immediately shows user menu options based on node term. (It is more of a usability idea for mobile users - not having to click through full menu).

**Question:** Do you think it is a good idea to inject such menu using jquery? Or is there a better drupal way of doing this? Thank you

# Answer
> 0 votes
> What I would like to do is to somehow inject the block menu items inside primary menu.
>
> Or is there a better drupal way of doing this?

**TB Mega Menu** allows you to put blocks and view blocks inside your menus. Perhaps you should consider using this module instead.

---
Tags: 7, theming, navigation
---


# Question
Title: How to allow users to login with a particular role they have selected?
I have a multiple roles in my site, let's say I have role A, B, C, D.

I want users to be able to choose which role a user wants when logging in. And then the user should only be able to access the content for the selected role (even if the user has multiple roles).

Any suggestions about how to implement this?

# Answer
Changing roles would probably require the permission "Administer permissions" so it could be hard. There's a module that does what you want, but it would probably require some modification: https://drupal.org/project/roleswitcher

There's also the Masquerade module (https://drupal.org/project/masquerade) which offers the ability to switch user account - which may be useful depending on your needs.
> 0 votes

# Answer
### Add a profile field

Add a field, say "**Desired User Role**", to the user profile.

### Create a 1st Rule

* Rules Event: After user login.
* Rules Actions:
    + Remove role A, B, C and D for user.
    + Perform a redirect to `user/uid/edit` (to show the user's profile in edit mode).
    + Set a Drupal message like "*Select your desired User Role*".

### Create a 2nd Rule

* Rules Event: After updating a user profile.
* Rules Conditions (AND):
    + User ID of the user for which the profile is updated is current site user (to not block user profile edits by other authorized users).
    + Field **Desired User Role** (unchanged) is not eaqual to **Desired User Role**.
* Rules Action (using the Conditional Rules module to allow conditions to be contained within Rules Actions):
    + If selected **Desired User Role**=A then grant access to role A.
    + If selected **Desired User Role**=B then grant access to role B.
    + If selected **Desired User Role**=C then grant access to role C.
    + If selected **Desired User Role**=D then grant access to role D.

This rule also facilitates swapping from one role to another (without forcing an indermediate logout/login). If that's NOT what you want, then this rule needs further refinement. I.e. add an extra Rules Condition to also check that no **Desired User Role** (unchanged) was selected before trying to update it.

**Note**: for this to work, a user can have multiple "other roles", but they should not overlap with A, B, C or D.
> 0 votes

---
Tags: 7
---


# Question
Title: How to only allow a node to be viewed in its assigned language?
I have three languages on my site:

```
/en
/es

```

If I have a node with ID = 1234 and this node in english, then I can view it as follows:

```
/en/node/1234

```

And this will redirect to

```
/en/my-page

```

Which is great! The problem is, if I view this ENGLISH page from another language. I.e. If I open this:

```
/es/node/1234

```

Then it opens the english page but the link remains at /es/node/1234

I enabled the "Translation Redirect" module, but this doesn't do exactly what I was hoping it would do. In the above case, if you open:

```
/en/node/1234

```

And there IS a "ES" version of the page, it will redirect to that page. Which is great, except sometimes I have a page that does not have a translation, and in the case I want that link to redirect to the correct page. In other words, opening this:

```
/es/node/1234

```

Must take you to:

```
/en/node/1234

```

Which will then automatically take you to:

```
/en/my-page

```

Is there a way to enable this in i18n or must I write something custom to do this?

# Answer
i18n\_redirect module has simple code, so turn it off, and add next code to custom module:

```
/**
 * Implements hook_init()
 */
function CUSTOMMODULE_init() {

    $path = $_GET['q'];
    $language = i18n_language_interface();
    // Not for logged in users nor for home page
    if (!$path || drupal_is_front_page() || !empty($GLOBALS['user']->uid)) {
        return;
    }
    elseif ($translations = i18n_get_path_translations($path)) {
        if (isset($translations[$language->language]) && $translations[$language->language]['href'] != $path) {
            drupal_goto($translations[$language->language]['href'], array('language' => $language), 301);
        }
        else {
            // Here we working with node, since question about node redirections
            $node = menu_get_object();
            if ($node && $node->language && ($node->language != $language->language)) {
                $languages = language_list();
                if (isset($languages[$node->language])) {
                    $language = $languages[$node->language];
                    drupal_goto('node/' . $node->nid, array('language' => $language), 301);
                }
            }
        }
    }
}

```
> 1 votes

---
Tags: 7, i18n-l10n
---


# Question
Title: how to make multiple ajax callbacks from a drop-down field?
I have a select field in my custom module (Drupal 7), which needs to refresh the values of 2 different field types when a value is selected, firstly a checkbox field, which currently is refreshed correctly when am changing the dropdown value, and a text field, which is not changing, as it keeps the value from the first dropdown option by default.

Samples of my codes:

```
$form['webform_name'] = array(
'#type' => 'select',
...
#ajax' => array(
  'event' => 'change',
  'callback' => 'ajax_checkbox_callback',
  'method' => 'replace',
  'wrapper' => array('checkboxField','txtField'),
)

$form['checkboxField'] = array(
'#type' => 'checkboxes',
...
'#prefix' => '<div id="checkboxField">',
'#suffix' => '</div>',

$form['txtField']=array(
'#type' => 'textfield',
...
'#prefix' => '<div id="txtField">',
'#suffix' => '</div>',

function ajax_checkbox_callback($form, &$form_state) {
    return array(
    '#type' => 'ajax',
    '#commands' => array(
    ajax_command_replace("#checkboxField", render($form['checkboxField'])),
    ajax_command_replace("#txtField", render($form['txtField']))
    )
  );
}

```

How can I make the `txtField` field to clear and load the corresponding value every time I change my drop-down values?

# Answer
> 3 votes
In your ajax\_command\_replace where the form is rendered, do this: ajax\_command\_replace("#checkboxField", render($form\['checkboxField'\]\['values'\]=$text)), where $text is the value from the checkboxes, as shown below:

```

function ajax_checkbox_callback($form, &$form_state) {
    return array(
    '#type' => 'ajax',
    '#commands' => array(
    ajax_command_replace("#checkboxField", render($form['checkboxField']['values'] = $value_text_form_text_field_1)),
    ajax_command_replace("#txtField", render($form['txtField']['values'] = $value_text_form_text_field_2))
    )
  );
}

```

# Answer
> 0 votes
Well, I believe `wrapper` should be a string and not an array. So can't you just change it to string :

```
wrapper => 'checkbox_textfield'

```

Something like above and change code to :

```
$form['checkbox_textfield'] = array(
  '#prefix' => '<div id="checkbox_textfield">',
  '#suffix' => '</div>',
);
$form['checkbox_textfield']['checkboxField'] = array(
  ...
);

$form['checkbox_textfield']['txtField']=array(
  ...
);

```

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


# Question
Title: How to get a two layer sort with a taxonomy term relationship and avoid duplicates in a user view
I have a user view, that needs to list users, sorted by the weight of an taxonomy term associated with the user via an entity reference field and added as a relationship in the view. Once I've sorted by term weight, I next need to sort by the family name field of the user. As soon as I add the second sort I start getting duplicates. How can I accomplish the sort I need without the duplicates?

Turning on aggregation and grouping by the sort AND adding distinct to the query settings works in my simplified version of the view, but once I add in the other things the view won't load with aggregation on.

**Update:** I thought I had it simplified as far as it could go, but it turns out the relationship has nothing to do with it. I get duplicates just be adding a sort of family name. Curiouser and curiouser.

# Answer
> 1 votes
You need to add a filter that restricts family name to one language.

Credit: @ratface, answering this Q as per What should I do when an answer has been added as comment?

---
Tags: 7, views
---


# Question
Title: Why are my nodes not showing up in a Panel?
I am experiencing something strange: the nodes in my Panels are not showing up anymore. When adding content to my Panels, I can select *Existing node*, pick the right node title (e.g. *Test article*) and save the Panel without any problem:

But, afterwards, the node is not printed on the according Panel page:

However, everything worked fine in the past and a quick test on a fresh website shows that there is no bug in the Panels module. Also, other entities like Views are displayed just fine. I have already checked some things that might cause the problem:

* The node template at **Structure/Panels** is enabled, but that doesn't matter: disabling it does not change anything.
* The node in the Panel does neither have a style, nor any visibility rules.
* My custom modules do not interfere with the printing of nodes or panels.
* Clearing the caches doesn't change anything.
* All users have permission to view published nodes; visiting the node's full page works fine:

Do you have any idea what might be causing the problem?

# Answer
Since the problem of non-displayed Panes can be caused by quite a lot of things, it can also take quite a lot of time to find a solution (2 days in my case). It turned out that I had overwritten `panels-pane--node.php.tpl` in my custom theme and that I accidently put an `if` statement around the whole code, which only returned `TRUE` for one specific node. Woops...

In order to make the searching process a bit easier for future users who have a similar problem, I will sum up some stuff to try underneath.

## Maybe it's a theming thing

If you have a custom theme, your first reflex should probably be to take a look at it. (That being said, my reflexes aren't that good apparently.) First, use a tool like Firebug to inspect your Panel and make sure that the Pane isn't printed. Something like a lost `visibility: hidden;` can easily be solved in your CSS files. If your Pane just isn't there, maybe there is something wrong with one of your templates. Take a look at the templates that start with `panels-pane`.

## Maybe it's a Panels thing

Take a look at the Pane's settings in your Panel. As CodeNext suggested in the comments above, check that the active style is *No Style*. In other cases, there can be a problem with (the CSS of) that style. Also, make sure that you didn't set a visibility rule that hides the Pane for you.

## Maybe it's a clashing modules thing

P Magunia suggested that the jQuery version can affect the proper working of Panels. If you installed jQuery Update, you can temporarily deactivate this module to see whether something changes. In my case, nothing happened. Also, install the latest versions of all modules on your website. Maybe the Panels module clashes with another outdated module or is outdated itself (see No Sssweat's comment).

Taking Jimmy Ko's remark into consideration, I reinstalled an old backup of my website, where the problem did not arise, and updated all installed modules. Since the problem was still there, I could convince myself that the hidden Pane was not related to any module. Yet another reason for backing up your website's (WAMP) folder and database.

## PS: Maybe it's an alien thing

If none of the above hints worked, no error messages are shown, Google lets you down, and you have been clicking and typing around for days, probably some aliens hacked your website and are making fun of you. Beware, they are potentially dangerous. Never lose your temper...
> 1 votes

---
Tags: 7, nodes, panels
---


# Question
Title: What is the #target_type value used by the EntityAutocomplete class?
What is the #target\_type value accepted by `EntityAutocomplete`?

The documentation for `EntityAutocomplete::processEntityAutocomplete()` says it's the ID of the target entity type.

How can I get a list of possible IDs I could use?

# Answer
> 7 votes
The ID accepted from `EntityAutocomplete` is an entity type identifier for an entity defined from Drupal core, or third-party, modules.

You don't normally need to have a list of all the possible entity type IDs, since you normally know which entity your code is going to autocomplete, but the list can be easily obtained using the following code.

```
print_r(array_keys(\Drupal::entityTypeManager()->getDefinitions()));

```

I ran `drush ev "print_r(array_keys(\\Drupal::entityTypeManager()->getDefinitions()));"` on my test site, and I got the following.

```
[0] => block
[1] => block_content
[2] => block_content_type
[3] => comment
[4] => comment_type
[5] => editor
[6] => field_config
[7] => field_storage_config
[8] => file
[9] => filter_format
[10] => image_style
[11] => configurable_language
[12] => language_content_settings
[13] => mollom_form
[14] => node
[15] => node_type
[16] => rdf_mapping
[17] => responsive_image_style
[18] => search_page
[19] => shortcut
[20] => shortcut_set
[21] => action
[22] => menu
[23] => taxonomy_term
[24] => taxonomy_vocabulary
[25] => tour
[26] => user_role
[27] => user
[28] => view
[29] => menu_link_content
[30] => date_format
[31] => entity_form_display
[32] => entity_form_mode
[33] => entity_view_display
[34] => entity_view_mode
[35] => base_field_override

```

---
Tags: 8, entities
---


# Question
Title: Gif animation and responsive image styles are not working
I have a multiple image field and need it to upload images and animated gifs. These images might be resized. When this happens, the animated gif loses its animation.

Has anyone solved this problem in drupal 8?

# Answer
> 4 votes
There's now imagemagick for Drupal 8. I've been using it with D8 responsive image styles and it works well, the gif animation stays intact.

You'll need to have imagemagick installed on your server and will need the path to the *convert* binary as well. Typically it's `usr/bin` or for example with MAMP, it's `/Applications/MAMP/Library/bin/`

---
Tags: 8, media
---


# Question
Title: Starting a site from scratch after running "drush sql-drop"
In drupal 7 I was able to just do a **drush sql-drop** and then visit the site and it would throw the install screen. But in Drupal 8 I'm getting an error when I do a drush sql-drop when going back to the site. Are there static files I need to also delete in Drupal 8 along with doing a sql-drop?

# Answer
It looks like your **settings.php** file is still persisting after the command. Removing it should prompt you for installation on root request.

```
# Replace with location of settings.php file
settings_file=sites/default/settings.php
drush -y sql-drop && rm "$settings_file"

```
> 1 votes

---
Tags: 8, database, drush
---


# Question
Title: How to use Rules to send an email after a user submits a first node and grant a new role after 5 nodes?
I want to send a congratulations **email to user on submitting his/her first node**.

I want to implement this through the Rules module. But I am confused and think that there is no such option except PHP evaluation which seems bad to me due to `eval()`.

And I also want to assign a special role to a user after a user submitted (= Save new content) 5 nodes.

Any suggestions?

# Answer
This can be implemented perfectly by using the Goals module (disclosure: I'm its maintainer), as further detailed below.

# Part 1 - Configure 2 goals

You'd start by configuring the appropriate set of **Goals** and related **Tasks**. For a basic introduction about Goals, have a look at:

Here is what it would take:

1. **Goal1** = "New user", with only 1 **Task** = "Save 1 node" (say with machine name = `save_a_node`).
2. **Goal2** = "Mature user", with **Task** = "Save 5 nodes".

# Part 2 - Create a rule to record progress on the tasks

Create a rule using Rules Event "After saving new content". The purpose of this rule is to make Goals automatically track the progress on completing the tasks (which you can do via an appropriate Rules Action to record that progress).

The interesting part of this is that you can reuse the same rule (related to that machine name = `save_a_node`) to keep track of the progress of any user to become a New/Mature customer (check the video for a similar sample).

# Part 3 - Trigger your rules after a goal is achieved

Together with what is above, you should write these 2 rules to implement what your question is actually about:

1. a rule with these specs:

* Rules Event: "After a user completed Goal1"
    * Rules Action: "Send an eMail"
2. a rule with these specs:

* Rules Event: "After a user completed Goal2".
    * Rules Action: "Assign role to user".
> 1 votes

# Answer
I would use Rules and I would set up multiple roles.

* Role 1: new user
* Role 2: after Role 1 New User creates new content, they get their role changed to Role 2
* Role 3: after Role 2 creates new content, they get their role changed, etc.

I would think about a different # than 5 if possible, just to start, to keep roles down. This is the easiest way to handle this without custom code. Also, having multiple roles makes it easy to target for other things, like notices or other email campaigns.
> 0 votes

---
Tags: nodes, rules, emails, workflows
---


title: Drupal Caching Files

text:
# Question
Title: Drupal Caching Files
After install and setup of my Drupal site, I've noticed that Drupal has placed a few dirs/files in my file directory like css/js. Is it safe to remove these files when I move my site? What other cache dirs/files does Drupal generate?

# Answer
These are the dirs that Drupal 8 core places into your file directory:

* **config\_HASH**: This is a unique directory (where **HASH** is generated specifically for your site) that used for configuration management syncing.
* **css**: This directory contains minified/compiled CSS files.
* **js**: This directory contains minified/compiled JS files.
* **php**: This directory contains compiled Twig PHP template files.

In general, if you're moving a site you can empty out the **css**/**js**/**php** directories; these are page cache generation artifacts and be cleaned out as long as you've emptied your site's cache aftering moving.

As for **config\_HASH**, you'll want to keep it around in case you need to sync CM between environments. (e.g. adding/changing settings in a development then pushing those changes to staging/production environment).
> 1 votes

---
Tags: 8, files, caching
---


# Question
Title: Is there a way to order views grouped fields?
I am using views to group a list of nodes by taxonomy term and display these groups as accordion headers (displayed by the views accordion module).

eg:

> Yellow:

* node1
* node2

> Green:

* node1
* node3
* node4

> Mauve:

* ..

I have the nodes sorted by node:title (asc), but with or without the title sort, putting in a sort in for term:title does not seem to order the accordion headers as I had hoped. This might normally be a small niggle, but in this instance the end users are librarians...

I suppose I could go down the custom module route and devise my own block to display the terms/nodes without going through views. I would very much prefer not to do this, as it will be another maintenance demand for a quite complicated site.

The best I have found in looking for a solution is this discussion, but no solution is proposed, and I just have a nagging feeling that there **must** be a way to do this.

I would be really grateful for any suggestions.

# Answer
> 7 votes
## How I resolved this

I don't know what I did wrong in the first place here, as after having removed sorts from my view and added them again the ordering is fine, and not complicated at all

## Summary

If you are contructing a view of nodes, grouped by taxonomy term, and using the grouped field (term:title) as views accordion headers, then you can easily sort the accordion headers by taxonomy title/weight, and their child items by node title. To do this add a first sort criteria for term:title/weight(asc), and a second sort criteria for Content:title(asc).

I opted for a sort based on weight in the end, as I can always reset vocabulary weights to alphabetical order, and this allows the editors a bit of free choice if they need to prioritise the list.

# Answer
> 9 votes
It's important to note that to make this work, you have to create a relationship in the view. The relationship should refer to the taxonomy vocabulary. Otherwise, you won't get the term weight as an option in the sort criteria.

Then, once you have added the relationship, create the sort option and be sure to choose the relationship you just created.

# Answer
> 4 votes
I solved mine similarly to autopoietic, except I needed to add the Relationship to the term reference field in order to get the weight to show up in the Sort section.

# Answer
> 2 votes
I would like to share my personal experience with this grouping and sorting 'thing' from within Views. In this short 3 minutes demo video i am illustrating the scenario in my Ubercart Products catalog view, which is filtered both on regular as contextual (via URL) expressions : http://castabo.rawdesk.be/temp/Views-grouping-taxonomy-tags.flv As you can witness this setup works for me as long as no pagination occurs in the eventual result set. Once pagination occurs, the grouping is apparently performed on each page separately. EG. my Cardiology panel taxonomy tag group is spread among 3 pages.

Important note : this recorded scenario does not contain the additional Views Advanced Relationship addition as suggested in this similar case study : http://www.wdtutorials.com/2013/08/14/drupal-8-tutorial-how-order-view-groups-taxonomy-terms-also-drupal-7#.VB1sHBaOp8G I also tried with this additional relationship, but the result was exactly the same as recorded in my video.

So it is in my opinion not 100% waterproof unless someone else proofs here otherwise (ps. avoiding a question..)

# Answer
> 1 votes
You should be able to add the `term id` as a field. Exclude the field from the view and group based on that. Then however you arrange the terms in the backend should show in the view. The sort you add to the view will affect the child elements.

If the titles show the term id instead of the title just rewrite the output of the field to include the title.

---
Tags: navigation, views
---


# Question
Title: Rule to fire only on first time publish of node
We are using workflow moderation for some content types and sent out emails to the author once a node has been published.

Sometimes we have the case that an author changes a node after he has been published. When this revision gets published we want to send out a different email.

I have tried many different things but I haven't been able to find a way how to determine if this was the first time the node is published or a subsequent publish. Can someone please point me in the right direction how this can be achieved?

Thanks

# Answer
> 3 votes
This is how I would try doing it:

* create a field for the content type named first\_publish, boolean, hidden, default value 0
* create a Rule that when that content type is published, as a condition if first\_publish is 0, first\_publish becomes 1, add email output to user
* create a second Rule that when the content type is published, as a condition if first\_publish is 1, send out a different email

This will use a data field as a variable that follows the node - the rules will trigger appropriately depending on the conditions of whether or not the variable is set, giving different outcomes.

# Answer
> 0 votes
I found another way to do this if you don't want to add an extra field to the node.

In Rules add a condition of type "Execute custom PHP code".

Then in the PHP code field add the following:

```
$times_published = db_query('select count(nid) from node_revision where status = 1 and nid = ' . $node->nid)->fetchField();
return ($times_published < 2);

```

This checks for the number of published revision entries for that node.

---
Tags: nodes, rules, workbench
---


# Question
Title: How can we achieve multiple forms in a single page?
I have menu callback which is getting called multiple times on the same page by an AJAX request resulting rendering the form with same **HTML id**

```
$items['mymodule/page'] = array(
    'page callback' => 'drupal_get_form',
    'page arguments' => array('page_callback_form'),
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
  );

function page_callback_form($form, &$form_state, $thing) {
  $form['message'] = array(
    '#type' => 'textarea',
    '#title' => t('Message'),
    '#cols' => 80,
    '#rows' => 5,
  );
  return $form;
}

```

Result:
`<textarea id="edit-message" name="message" cols="80" rows="5" class="form-textarea"></textarea>`
`<textarea id="edit-message" name="message" cols="80" rows="5" class="form-textarea"></textarea>`

i was wondering is there a way i can have unique Ids, i have tried \[hook\_forms\].

# Answer
> 0 votes
You can do it!

With the drupal fapi. You can overload every HTML attributes by using the element #attributes.

Exemple:

```

  $form['form_element'] = array(
    '#type' => 'textfield',
    '#title' => t('If you Have a Code, Redeem it here:'),
    '#attributes' => array(
      'id' => 'your_id',
    ),
  );

```

If you add a counter or something to your id, you will have a different id for each fields.

Cheers

---
Tags: 7, forms, hooks
---


# Question
Title: Create a subtype of Panel & style it with a template
So I'm trying to build a independent Landing Page for an event on our drupal 7 site. I would like to have the page contain a different main navigation menu then our site and also has the functionality of the content type "Panel".

I was Thinking to create a Content Type "Event" but how can I assign the Panel layout to it and how should I Assign that content type a specific menu?

The best solution would be to have a content type with the Fields:

* Event Name
* Panel Layout
* Top Navigation Menu
* ...

after creating that content type I would create a theme template for that type. The template would modify the top and bottom of the page but the center should still be modified as the same as a traditional panel.

Atm I don't know how to accomplish that :(

Would love to hear some feedback guys!

# Answer
when I have to create this type of "landing pages" I m usually following these steps.

### 1/ The Layout.

Create a Panel Page. **Admin \> Structure \> Panel \> New panel page**

1A/ If you want to get ride of header/footer region \> there is an option for that.

1B/ If you want to keep these regions, but diplay other blocks, go to Admin \> **Block \> your block \> Configure \> Visibility settings \> and setup the thing whith the page settings**.

### 2/ Then your content.

What I'm usually doing here is depending on what you try to achieve, but if you are displaying only 1 event content, create a content type event is probably not the right approach.

But my point is, now you can create a page with what you want. So think about what you want to display (do you need a view of items ? do I need a block ? some blocks? do I need some beans ?) and architecture it as it was a standard page. Just prefix all you items type with one commun name, so you will be able to retrieve them later.

I hope it helps

Cheers
> 0 votes

---
Tags: 7, theming, entities, panels
---


# Question
Title: How do I show a percentage value in a views_field?
How do I show the percentage value in a views\_field?

* col(1) (group by) field\_a
* col(2) (count)field\_a \*100/number of results " --\>@total"

I'm still not able to use @total in a computed\_field or a math-expression\_field or a global\_custom\_field.

I need this value for the Highcharts module, so using "aggregation plus" also seems not the solution.

Using a PHP field inside views is highly risky for security reasons as I read here in other answers.

# Answer
to achieve some calculations I see 2 different solutions.

1/ You create a custom sql query with (db\_query) inside a custom module that gonna trigger a view to render, your select clause will make the calculation for you so you will have your result that you are going to display inside a custom field in your view. You can see the actual query you are executing by using the devel module and then tweak it.

2/ You can use computed\_field module but it's a really dangerous thing to integrate PHP inside a field somewhere, because if your php breaks, you will break your complete site, and need to rollback your database. But I don't suggest this solution because it's really risky for your site.

I hope it helps

Cheers
> 0 votes

---
Tags: 7, views, entities
---


# Question
Title: Best way to add edit + flag links to a node being displayed inside Colorbox Node?
One of my content types opens in a colorbox node but I need an edit link and flags to appear for certain roles. I'm not using panels for this content type and I'm not using Display Suite either.

Blocks don't get displayed in a colorbox node so I'm wondering what's the easiest and most efficient way to add these links.

Php filter is fine to use.

Thanks

# Answer
> 1 votes
You could use Views, create a block view.

Under advanced, add relationship of flags of the node and check mark require relationship.

Add flag link and edit link as fields.

Add Contextual filter of nid and select provide default value, then select get ID value from url. (preview will go blank, which is normal here)

Place view block on your node.

---

> Php filter is fine to use.

This is very risky, see: What are the downsides of using PHP Filter code in blocks, nodes, views-args, etc?, if you want to use php, create a template file for your node, block, or view.

Therefore, another option is to create a template file for your content type.

**node--\[type-name\].tpl.php** and do php code there.

Ex: `node--article.tpl.php`

In your template file put

```
<div class="myedit">
  <?php print '<a href="/node/' . $node->nid . '/edit"> edit </a>'; ?>
</div>

<div class="myflag">
  <?php print flag_create_link('FLAGNAME', $node->nid); ?>
</div>

<?php print render($content['title']); ?>
<?php print render($content['body']); ?>
<?php print render($content['field_name']); ?>

```

and so on, you print all the fields you have.

**Remember to flush/clear the cache to see changes.**

---
Tags: javascript
---


# Question
Title: Delete button not working on forum comment
I am using the AJAX Comments module. For forum I am using the Advance Forum module. In forum topic I have some post replies, my issue is when I am click on delete button on forum comment a popup is shown with message:

> You are not authorised to access this page

I have assigned the permission so any one can delete their own comment.

I don't know what is the issue because on other content type comment its working fine but only on forum comment its not working.

# Answer
> 1 votes
There is a bug report about this

According to one of the comments written by Ravathi.M

> i am also having the same issue the comment wraper class is missing.for the initial execution.then i have added the ajax-comment-wraper class by custom js code.now it is working fine

Looks like the solution is that you need to add the `ajax-comment-wraper comment-wrapper-[post#]` class name to your forum comments.

Go to `/sites/all/modules/advanced_forum/styles/naked` folder and replace the **advanced-forum-naked-post.tpl.php** with this code:

```
<?php

/**
 * @file
 * Theme implementation: Template for each forum post whether node or comment.
 *
 * All variables available in node.tpl.php and comment.tpl.php for your theme
 * are available here. In addition, Advanced Forum makes available the following
 * variables:
 *
 * - $top_post: TRUE if we are formatting the main post (ie, not a comment)
 * - $reply_link: Text link / button to reply to topic.
 * - $total_posts: Number of posts in topic (not counting first post).
 * - $new_posts: Number of new posts in topic, and link to first new.
 * - $links_array: Unformatted array of links.
 * - $account: User object of the post author.
 * - $name: User name of post author.
 * - $author_pane: Entire contents of the Author Pane template.
 */
?>

<?php if ($top_post): ?>
  <?php print $topic_header ?>
<?php endif; ?>

<div id="<?php print $post_id; ?>" class="<?php print $classes; ?> ajax-comment-wrapper comment-wrapper-<?php print str_replace('post-','',$post_id); ?>" <?php print $attributes; ?>>
  <div class="forum-post-info clearfix">
    <div class="forum-posted-on">
      <?php print $date ?>

      <?php
      // This whole section is for printing the "new" marker. With core comment
      // we just need to check a variable. With Node Comment, we need to do
      // extra work to keep the views caching used for Node Comment from
      // caching the new markers.
      ?>
      <?php if (!$top_post): ?>
        <?php if (!empty($new)): ?>
          <a id="new"><span class="new">(<?php print $new ?>)</span></a>
        <?php endif; ?>

        <?php if (!empty($first_new)): ?>
          <?php print $first_new; ?>
        <?php endif; ?>

        <?php if (!empty($new_output)): ?>
          <?php print $new_output; ?>
        <?php endif; ?>
      <?php endif; ?>
    </div>
    <?php /* End of posted on div. */ ?>

    <?php if (!empty($in_reply_to)): ?>
     <span class="forum-in-reply-to"><?php print $in_reply_to; ?></span>
    <?php endif; ?>

    <?php /* Add a note when a post is unpublished so it doesn't rely on theming. */ ?>
    <?php if (!$node->status): ?>
      <span class="unpublished-post-note"><?php print t("Unpublished post") ?></span>
    <?php endif; ?>

    <span class="forum-post-number"><?php print $permalink; ?></span>
  </div> <?php /* End of post info div. */ ?>

  <div class="forum-post-wrapper">
    <div class="forum-post-panel-sub">
      <?php if (!empty($author_pane)): ?>
        <?php print $author_pane; ?>
      <?php endif; ?>
    </div>

    <div class="forum-post-panel-main clearfix">
      <?php if (!empty($title)): ?>
        <div class="forum-post-title">
          <?php print $title ?>
        </div>
      <?php endif; ?>

      <div class="forum-post-content">
        <?php
          // @codingStandardsIgnoreStart
          // We hide the comments and links now so that we can render them later.
          hide($content['taxonomy_forums']);
          hide($content['comments']);
          hide($content['links']);
          if (!$top_post)
            hide($content['body']);
          print render($content);
          // @codingStandardsIgnoreEnd
        ?>
      </div>

      <?php if (!empty($post_edited)): ?>
        <div class="post-edited">
          <?php print $post_edited ?>
        </div>
      <?php endif; ?>

      <?php if (!empty($signature)): ?>
        <div class="author-signature">
          <?php print $signature ?>
        </div>
      <?php endif; ?>
    </div>
  </div>
  <?php /* End of post wrapper div. */ ?>

  <div class="forum-post-footer clearfix">
    <div class="forum-jump-links">
      <a href="#forum-topic-top" title="<?php print t('Jump to top of page'); ?>" class="af-button-small"><span><?php print t("Top"); ?></span></a>
    </div>

    <div class="forum-post-links">
      <?php print render($content['links']); ?>
    </div>
  </div>
  <?php /* End of footer div. */ ?>
</div>
<?php /* End of main wrapping div. */ ?>
<?php print render($content['comments']); ?>

```

Since the forum post and the 1st comment have the same number `1` you will notice that clicking `reply` will affect the node post as well. Therefore, you will need to use jQuery to modify or remove the `1` from `comment-wrapper-1` of the forum (node) post.

---
Tags: 7, ajax
---


# Question
Title: how to set minimum quantity of products in the shopping cart?
I want to set minimum quantity of goods that customer may order in the shop. For example minimum quantity is 20, so if customer order less then 20 his order won't process and there will be message telling him that he must purchase 20 or more and redirecting him to his shopping cart

# Answer
> 0 votes
You could try using the Commerce Minimum Order Quantity and Increment sandbox module.

> The module allow you set minimum order quantity and an order quantity increment. This quantity is for the entire order not each product line item. Your shoppers will not be able to check out until their order quantiy reaches the minimum and/or meets the increment.
>
> Download this module and install it. Go to admin/commerce/config/moqi to config.

Source: Twitter

---
Tags: commerce
---


# Question
Title: How to make the radio field checked by default?
I have a field group which consists of a radio box and other fields. This field group can have multiple values. My radio box field have two options and the first is checked by default. But when I add the second value (of the field group) – my radio field has no checked option, both options are empty (in the newly added field group). Is it possible to make the first checkbox option always checked?

Here's the short video showcasing the problem: https://www.dropbox.com/s/366xt4q57ryvteu/drupal-radio-issue.mp4?dl=0

# Answer
I canno't comment to suggest you a solution, but it's probably due to the module field\_group (or fieldgroup).

You should try the same content type configuration by using field\_collection, because i have never faced any issue with this module.

1/ You create a new field type : field collection. You setup the field with an unlimited number of occurrences.

2/ You go to structure \> field collection and add your fields.

I hope it help

Cheers.
> 0 votes

# Answer
The second occurrence of the field group is appearing on the form with the help of AJAX.Post AJAX the form is unable to rebuild itself which is causing the issue. You can define a custom submit handler in hook\_form\_alter for the particular form and rebuild the form in the custom submit handler.

```
 function module_name_form_alter(&$form, &$form_state, $form_id)
{
    if($form_id =="your_form_name")
        {
        $form['actions']['submit']['#submit'][] = 'ajax_rebuild_form';
        }
}
function ajax_rebuild_form($form, &$form_state)
{
    $form_state['rebuild'] = TRUE;
}

```
> 0 votes

---
Tags: 7, entities
---


# Question
Title: Letting a view know in which pane it's being displayed
I've got a very non-trivial question on integrating Panels and Views. Maybe there's no solution out of the box, but I would really appreciate any help.

Essentially, I've got a lot of tagged nodes. For simplicity, let's say image nodes that are tagged as "flowers", or "animals", or "mountains", etc.

Then I have a view block that displays the images depending on their tag. This view block is then used in panel panes across the website.

Here's the issue: I can't use the URL to pass the tag information. In fact, on the same web page, I need to show several blocks (within panel panes) with different sets of images. One block would show "animals", another one "flowers", etc. And that depends only on the panel pane in which the view block is being displayed.

Of course, I could just create several preset view blocks, one only for "animals", another one for "flowers" etc, but I've got tens of different tags and can't create a separate block for each tag. So I was thinking of a more elegant solution.

Here's what my idea is: when I add content to a panel pane, I've got an option to override the title. I was thinking of adding another text field there "Tags to display" where I would say "flowers", or "animals", etc. Then I would just add the view block to the pane and that view block would pull that tag from the panel pane.

So, bottom line: how can I let the view know in which panel pane it's being displayed? Just pane ID would be enough, the rest (the tag to use) I could simply pull directly from the database.

Thanks for your ideas.

# Answer
Build your views as "view content pane" displays. That way any context you require for use in contextual filters can be provided in the panel UI when you set up the pane.
> 0 votes

---
Tags: panels, views
---


# Question
Title: Adding a new separate menu link to /admin/config in page?
Adding new separate menu link in admin config page like development service

# Answer
Adding link to admin config under development, media, service is easy but creating new separate menu like admin\_config\_development, admin\_config\_service , admin\_config\_media is bit tricky.

As mentioned in

> Create same file with small alteration **modulename.links.menu.yml**
>
> ```
> modulename.admin_config_modulename:
>   title: ' settings'
>   description: ' selection.'
>   route_name: modulename.settings
>   parent: 'system.admin_config'
> modulename.second_link:
>   title: 'settings'
>   description: 'selection.'
>   route_name: modulename.settinganother
>   parent: 'modulename.admin_config_modulename'
>   menu_name: modulename
>
> ```
>
> By: monkpal
> 4 votes

---
Tags: 8
---


title: Custom views twig template

text:
# Question
Title: Custom views twig template
I am trying to create a new twig template that defines different types of views templates - or some sort of option based format.

**Example 1**:

Generic view blocks: *block--views-block.html.twig*

**Example 2**:

News Block specific views with no container: *block--views-block--news-elements-block-1.html.twig*

**Example 3**:

List Block specific views with no container: *block--views-block--list-elements-block-1.html.twig*

**What i want to achieve**: - if i can present an option on the block, that would also work.

Views block with no container: *block--views--no-container--block.html.twig*

So far:

```
function THEME_theme_suggestions_alter(array &$suggestions, array $variables) {

  // dpm($variables);

  // $content = $variables['elements']['content'];
  // if (isset($content['#block_content']) && $content['#block_content'] instanceof \Drupal\block_content\BlockContentInterface) {
  //   $suggestions[] = 'block__' . $content['#block_content']->bundle();
  // }
}

```

# Answer
For my circumstance i have adopted to use the `block_alter` hook to define the new suggestion for the template. Since homepage only contains the unique views template and the others wouldn't.

```
function THEME_theme_suggestions_block_alter(&$suggestions, $variables) {
  $path_check = \Drupal::service('path.matcher');

  if (in_array("block__views", $suggestions) && $path_check->isFrontPage() == FALSE ) {
    $suggestions[] = 'block__views__blah__custom';
  }

}

```
> 0 votes

---
Tags: theming, 8
---


# Question
Title: How to use hook_form_search_block_form_alter?
I was referring this page in the process of learning hooks How to Customize the Block Search Form and found following code.

```
/**
* hook_form_FORM_ID_alter
*/
function YOURTHEME_form_search_block_form_alter(&$form, &$form_state, $form_id) {
    $form['search_block_form']['#title'] = t('Search'); // Change the text on the label element
    $form['search_block_form']['#title_display'] = 'invisible'; // Toggle label visibilty
    $form['search_block_form']['#size'] = 40;  // define size of the textfield
    $form['search_block_form']['#default_value'] = t('Search'); // Set a default value for the textfield
    $form['actions']['submit']['#value'] = t('GO!'); // Change the text on the submit button
    $form['actions']['submit'] = array('#type' => 'image_button', '#src' => base_path() . path_to_theme() . '/images/search-button.png');

    // Add extra attributes to the text box
    $form['search_block_form']['#attributes']['onblur'] = "if (this.value == '') {this.value = 'Search';}";
    $form['search_block_form']['#attributes']['onfocus'] = "if (this.value == 'Search') {this.value = '';}";
    // Prevent user from searching the default text
    $form['#attributes']['onsubmit'] = "if(this.search_block_form.value=='Search'){ alert('Please enter a search'); return false; }";

    // Alternative (HTML5) placeholder attribute instead of using the javascript
    $form['search_block_form']['#attributes']['placeholder'] = t('Search');
}

```

This code is very helpful and precise to point. For example, if we want to change the `placeholder`, we need to put following code inside the template.php file and it works.

```
function YOURTHEME_form_search_block_form_alter(&$form, &$form_state, $form_id) {
    $form['search_block_form']['#attributes']['placeholder'] = t('Search');
}

```

Now,

1. From the literature on api.drupal.org, I can get the information that Hook, `YOURTHEME_form_FORM_ID_alter(&$form, &$form_state, $form_id)`, can be used to alter the various parts of forms.
2. But on that page, there is nowhere a description about any part which all are described in above first code, For example, `$form['search_block_form']['#attributes']['placeholder'] = t('Search');` This code is used to change the `placeholder`. And same way all other like `title`, `#title_display` etc...

Why I am asking this, because for hooks all things are already defines and to use them we have to use them as they are provided, So What is the method to connect this all dots, from Hook name to what can we change with that hook.

**Precise Question,**

3. To make this question to the point, I what to know from where on api.drupal.org shall I find out, this part `$form['search_block_form']['#attributes']['placeholder']`? Or how shall I come to know that, if I have to change `placeholder` I have to use `$form['search_block_form']['#attributes']['placeholder']` this code only?

# Answer
> 1 votes
> **where on api.drupal.org shall I find out**, this part `$form['search_block_form']['#attributes']['placeholder']?`

I don't know, but this is basic PHP. `$form` is a multidimensional array with keys of search\_block\_form, #attributes, placeholder, etc...

All I know is that you can use the Devel module to see the structure and what's inside of the array by using `dpm($form)`

```
function YOURTHEME_form_search_block_form_alter(&$form, &$form_state, $form_id) {
    dpm($form);
}

```

# Answer
> 2 votes
> So What is the method to connect this all dots, from Hook name to what can we change with that hook.

There isn't one - each hook is different, has different input, different output, different contents, affects different parts of the system, and so on. You have to look for documentation contextual to what you're working with, each time you have something different.

In this case, you're working with a form, which means you should be referring to the Form API. From there it's an easy search to find information about `#attributes`:

> **Description:** Additional HTML attributes, such as 'class' can be set using this mechanism.
>
> **Values:** Any HTML attribute not covered by other properties, e.g. class (for control types), enctype (for forms).

It's basically an arbitrary pass-through of the key/value, so

```
$form['search_block_form']['#attributes']['foo'] = 'bar';

```

Will get you (e.g.)

```
<input type="text" foo="bar" />

```

---
Tags: 7, hooks, forms
---


title: Ajax shopping cart

text:
# Question
Title: Ajax shopping cart
I installed several ajax carte modules but none have possibility to display shopping cart in there menu as on the image, if you add some products, shopping card displays number of added products

# Answer
> 1 votes
I think this module will be helpfull **Commerce Popup Cart**

---
Tags: commerce
---


# Question
Title: Adding custom variable to twig's html.html.twig which is not cachable
In the html.html.twig file of the theme I'm using, I want to add a custom variable called {{ amount }} like: `<div>Amount of items in cart: {{ amount }}</div>`

And I want it to be (in php): count($\_SESSION\['cart'\]).

If I add this to my custom module's hook\_preprocess(\_html) function:

```
$variables['cart'] = count($_SESSION['cart']);

```

Then it will work when I clear the cache, and then it will remember the value. So let's say there are 3 items in cart (variable $\_SESSION\['cart'\]), then it shows 3. If I then add one more, then next time I refresh the page, it shows 3 again, but it should say 4!! If I clear the cache, then it says 4! How can I make it "dynamic" without clearing the cache all the time.

# Answer
Ok - so to write your own extension see this answer, refeer to the twig tweak module. Or follow this article, that's it's content adapted to session (using a funcition) - like twig tweak, but different form the linked answer:

In this exemple, we built an extension du display a Drupal block directly from a twig template :

```
{{ session_var('my_var_name') }}

```

To to it, you must create a custom Drupal module. You can use the Drupal console to easily create your module.

In your module folder, frist create a new class in in a src subfolder :

For exemple : src/MyTwigExtension.php

```
<?php
namespace Drupal\MyTwigModule;

/**
 * Class DefaultService.
 *
 * @package Drupal\MyTwigModule
 */
class MyTwigExtension extends \Twig_Extension {

  /**
   * {@inheritdoc}
   * This function must return the name of the extension. It must be unique.
   */
  public function getName() {
    return 'session_var';
  }

  /**
   * In this function we can declare the extension function
   */
  public function getFunctions() {
    return array(
      new \Twig_SimpleFunction('session_var',
        array($this, 'session_var'),
        array('is_safe' => array('html')
      )),
  }

  public function session_var($key) {
    return \Session->get($key);
  }

}

```

In a second time you must register your extension as service :

Create a service configuration file

```
# src/MyTwigModule.services.yml
services:
  MyTwigModule.twig.MyTwigExtension:
    class: Drupal\MyTwigModule\MyTwigExtension
    tags:
      - { name: twig.extension }

```

And you are done :-)

You can now enable your module and use your Twig extension.

---

The simple workaround could look like this in twig:

```
{% app.session.get('cart')|length %}

```
> 1 votes

---
Tags: 8, theming
---


# Question
Title: Captcha session reuse attack detected error message in form with anonymous user
I am experiencing a problem with the Captcha module 7.x-1.3 version (under Drupal 7.39)

* I don't use webforms
* My form is a simple Contact form
* My form does not contain any AJAX field
* My form does not contain any file or image upload system
* I configured the captcha Module, giving the good name for the form
    + form\_id : xxxxxx\_contact\_form
    + Challenge type : Image (from module image\_captcha)
* In the Configuration (admin/config/development/performance)
    + The page cache for anonymous users is unchecked = NOT ACTIVATED
    + The cache for blocks is unchecked = NOT ACTIVATED

The code of the Captcha for my form is :

```
$form['xxxxxx_contact_captcha'] = array(
  '#title' => t('Vérification'),
  '#type' => 'captcha',
  '#captcha_type' => 'image_captcha/Image',
);

```

When a user is connected the form submission works well without any problem BUT **when NO user** is connected (= anonymous session), i get the following errors :

> * CAPTCHA session reuse attack detected.
> * The answer you entered for the CAPTCHA was not correct.

(in french) :

> * Attaque à base de réutilisation de session de CAPTCHA détectée.
> * La réponse saisie pour le CAPTCHA est incorrecte.

**EXAMPLE :**

For example, with a "TT7Zi" Captcha image, when I submit the form (in anonymous) : I get the following errors on the screen :

> * CAPTCHA session reuse attack detected.
> * The answer you entered for the CAPTCHA was not correct.

And in the logs (watchdog) I get **two times** the same entry :

> Message xxxxxx\_contact\_form post blocked by CAPTCHA module: challenge Image (by module image\_captcha), user answered "TT7Zi", but the solution was "542dda8e8d7fda2358b4b2f319ef198b".

Any solution for this issue will be really helpful. Thank you all.

# Answer
> 0 votes
The problem comes from the fact that **it is NOT necessary to add the form\_id and Captcha method in the Captcha Configuration when you use a custom form**.

If you do this, when the form is generated on the page, the Captcha module is called TWO TIMES instead of only one, and this causes some troubles in the database, because when you call the form page, **and** when you submit it, TWO lines are created in the captcha\_sessions table instead of only ONE !!

So, you will have :

```
Line number | Token    | Code
------------------------------------------------
N           | AAAAA... | TT7Zi                   <=== FIRST CALL
N+1         | BBBBB... | dccedb00fa1234567890... <=== SECOND CALL (ABNORMAL)

```

Then, when you submit, a new line is created in the captcha\_sessions :

```
Line number | Token    | Code
------------------------------------------------
N           | XxXxX    | Zjj7R    ( UPDATE of the whole former TT7Zi line )
N+1         | BBBBB... | dccedb00fa1234567890...
N+2         | CCCCC... | 542dda8e8d7fda2358b4b2f319ef198b <== SECOND CALL !!

```

That's why the generated WATCHDOG error line says :

> user answered "TT7Zi", but the solution was "542dda8e8d7fda2358b4b2f319ef198b".

---
Tags: 7, forms, captcha
---


title: Displaying entity form on node page

text:
# Question
Title: Displaying entity form on node page
I'm a bit new to Drupal, but I'm on a project, where the most handy stuff is drupal. I only used it for 6 months, then I used mvc-s and stuff. Now I'm back to it.

The project is kinda simple. There is a site admin, who creates events and a registration form for that event (almost every registration form is different).

I want to display that entity form on the event page. I downloaded entityform blocks and it works, but I was just wondering if there is a module out there that creates a field type with the entityform types and the user can easily chose the entityform to display on the event page, when creating a new event.

If there is no such a module, then can it be solved by writing a custom field type? Thanks in advance!

# Answer
> 1 votes
Entity Reference lets you do this.

1. Add an entity reference field.
2. Target Type: Entityform Type.
3. If you want to limit the options for a user, you can create an entity reference view for entityform types and select it in the options.
4. Go to your content type's "Manage Display" and select "Rendered Entity" for the field.
5. Or for Panels, add a Context\>Relationship\>Entityform Type from Node.
6. Add it to the page under Page Content\>Rendered Entityform Type.

---
Tags: 7, nodes, forms
---


# Question
Title: how can I use special Font awesome character in Twig link()?
How can I use a special Font awesome character instead of the *text* parameter with \`link($text, $url, $attributes)?

I tried the following code for the *Contact us* button, but it doesn't show the envelope symbol properly. Instead, it shows `#xf0e0;`.

```
{{ link('', 'base:contact', { 'class':['fa', 'fa-lg'] }) }}`

```

Is there any way to output that symbol without using the *fa-envelope* CSS class?

# Answer
> 3 votes
If you are really set on not using the class (and want to use the unicode char) just don't use `link()`, the $text parameter is escaped. Just build a link normally:

```
<a href="{{ path('contact.site_page') }}" class="contact-us-link"><i class="fa fa-lg"></i></a>

```

# Answer
> 3 votes
The point of the FontAwesome selectors is that you do not need to print out the Unicode equivalent for the character. FontAwesome usually works by adding a pseudo element before or after the HTML element using the class.

In this case, use the `fa fa-envelope` classes and optionally add in a class to hide the text with a text-indent or something.

```
{{ link('Contact Us', 'base:contact', { 'class':['fa', 'fa-envelope', 'fa-lg', 'contact-us-link'] }) }}

```

---
Tags: theming, 8
---


title: Set legacy database in Aegir context

text:
# Question
Title: Set legacy database in Aegir context
Im fairly new to aegir and I have some hard time finding out the proper way to set a legacy database in aegir context. As far as I can see settings.php inside a platform is automatically generated so if I edit this file and run verify all changes will be lost. Other option is to insert it into drushrc file but Im still not sure what the syntax should be there. I see that database is inside the options array. Anyone with similar experience and few advice how to tackle this properly?

# Answer
> 2 votes
Such definitions can be placed in a `local.settings.php` file, alongside the generated `settings.php`.

You'll find an include statement at the bottom of the generated `settings.php`

---
Tags: drush, migrations, aegir
---


# Question
Title: Why is my table not automatically created at the time of custom module install?
I am writing a custom module for Drupal 7. For the table creation I have created the .install file, but the table is not getting created automatically, when the module is installed. I have already uninstalled and reinstalled the module many times. All the times I do it, I get the following error:

> Base table or view not found: 1146 Table 'drupal.drupalform' doesn't exist

This is the code in the drupalform.install file.

```
function drupalform_schema() {
    $schema = array();
    $schema['drupalform'] = array(
        'description' => t('A table for holding the drupalform data!'),
        'fields' => array(
            'id' => array(
                'description' => t('Auto increment of the ID'),
                'type' => 'serial',
                'unsigned' => TRUE,
                'not null' => TRUE,
            ),
            'name' => array(
                'description' => t('Person\'s first name.'),
                'type' => 'varchar',
                'length' => 64,
                'not null' => TRUE,
            ),
            'last_name' => array(
                'description' => t('Person\'s last name.'),
                'type' => 'varchar',
                'length' => 64,
                'not null' => TRUE,
            ),
            'email' => array(
                'description' => t('Person\'s email'),
                'type' => 'varchar',
                'length' => 64,
                'not null' => TRUE
            ),
        ),
        'primary key' => array('id'),
    );
    return $schema;
}

function drupalform_install() {
    drupal_install_schema('drupalform');
}

function drupalform_uninstall() {
    drupal_uninstall_schema('drupalform');
}

```

# Answer
> 3 votes
The following line is not correct.

```
'primary_key' => array('id'),

```

Replace `'primary_key'` with `'primary key'`.

In Drupal 7 you do not need to call `drupal_install_schema()` nor `drupal_uninstall_schema()` for the database tables your module uses.

You can just declare the functions.

```
function drupalform_install() {}

function drupalform_uninstall() {}

```

Just update the code, uninstall the module, and re-install it.

---
Tags: 7, forms, database
---


# Question
Title: Why is my javascript not being executed?
I have a Drupal 8 form and I'm applying some custom javascript to it. I've added a JS file, and a libraries file for my module containing a reference to it, but the code doesn't run.

in **module\_name/js/autocomplete.js**

```
(function ($, Drupal, drupalSettings) {

  Drupal.behaviors.modulename_autocomplete = {
    attach: function (context, settings) {

      jQuery(function() {
        // Doesn't work
        console.log('foo');

        // Doesn't work
        alert('bar');

      });
    }
  };
})(jQuery, Drupal, drupalSettings);

```

and in **module\_name.libraries.yml**

```
module_name.autocomplete:
  version: 1.0
  js:
    js/autocomplete.js: {}
  dependencies:
    - core/jquery
    - core/jquery.ui.autocomplete

```

As the comments suggest, I see no console messages and no alert, so it's clear the behavior is not being executed.

What do I need to change for this to work?

# Answer
You don't attach your to your form:

```
$form['#attached']['library'][] = 'module_name/library_name';

```

Just a suggestion:

In your library yml it's unnecessary to append your module name to your library name.
> 2 votes

# Answer
If this is a content type form and you have defined this content type as a child of ContentEntityBase in your module, you should use the form builder that you have specified in your @ContentEntityType annotation.

For example:

```
 * @ContentEntityType(
 *   id = "anwalt_entity",
 *   label = @Translation("Anwalt"),
 *   handlers = {
 *
 *     "form" = {
 *       "default" = "Drupal\preosanwalt\Form\AnwaltEntityForm",

```

Now, in your class AnwaltEntityForm extends ContentEntityForm, you can add your library attachment like ssibal said:

```
  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {

    $build = parent::buildForm($form, $form_state);

    $build['#attached']['library'][] = 'module_name.autocomplete';
    $build['#attached']['drupalSettings']['x'] = ...

    return $build;
  }

```

You don't need hooks if you have OO :-)
> 3 votes

---
Tags: ajax, 8
---


# Question
Title: How to filter 1 view with two fields based on 1 contextual filter?
I having a view which result in a table with three fields like:

```
                 field1, field2,field3
row1 with values 100,    110,   503
row2 with values 200,    520,   110
row3 with values 300,    530,   210

```

All numbers are nid. All fields are in different node types. I'm calling /foo?nodeid=110.

I'm trying to setup a view so that row3 is not displayed anymore and I can eventually have a table with row1 and row2 with the values of field1.

I tried a lot but do not get it. If I have one contextual filter I can filter the table on field2 and if I have another contextual filter I can filter on field3. But I cannot combine them like a normal filter like and/or.

Any suggestion how to solve this?

**Note**: For now my view is a table but in the end I will use it under webform so it then will be a webform display with a webform selection list.

# Answer
> 3 votes
Try Views Argument Substitutions. It lets you use contextual filter values in the regular filters.

1. Add a **Global: Null** contextual filter to get your default value. It's very important to use Global: Null so the view isn't filtered.
2. In your regular filters, you can add that value with * * * 1 * * * (no spaces) so that you can add AND / OR stuff. Use a different number if your Global: Null isn't at the top of the contextual filter list.

# Answer
> 0 votes
If you can achieve this using normal filter, you should go for that. You can fine-tune your Normal filter by creating new filter group in filter and then you can use And/Or inside one group of filters and in-between the filter groups. You can refer the first image in answer of this question Excluding Book children from a Custom view as an example.

---
Tags: 7, views
---


title: Editing status message contents

text:
# Question
Title: Editing status message contents
I want to change the contents of a status message, it is being brought in via the commerce module (`commerce_cart.rules.inc`).

The error message I want to change is:

```
/**
* Rules action: displays a the default translatable Add to Cart message.
*/
function commerce_cart_rules_add_to_cart_message($product) {
  drupal_set_message(t('%title added to <a href="!cart-url">your cart</a>.', array('%title' => $product->title, '!cart-url' => url('cart'))));
}

```

I don't want to apply a patch to commerce just to change a status message so does anyone know of any alternate solutions?

Thanks

# Answer
You can just remove the default `Display a translatable Add to Cart message` action and add a custom message that you want to be displayed yourself.

You can do this at `/admin/config/workflow/rules/reaction/manage/commerce_cart_add_to_cart_message`.
> 1 votes

# Answer
A easy way is to use the module stringoverides.

* Extract to your sites/all/modules directory.
* Enable the module in admin/build/modules.
* Configure the access permission in admin/user/access or admin/user/permissions.
* Visit admin/settings/stringoverrides or admin/config/regional/stringoverrides and fill in the strings you'd like to replace.

For this question you have to replace

```
%title added to <a href="!cart-url">your cart</a>

```

into that what you want.
> 0 votes

---
Tags: 7, commerce, status-messages
---


title: URL specific form for anonymous user

text:
# Question
Title: URL specific form for anonymous user
I'd like to investigate if the following scenario is plausible somehow in Drupal 7:

The creation of a public form (node form/webform or whatever) with many instances so that each instance can be accessed only by a specific URL and can be filled by an anonymous user. The anonymous user should be able to fill in some of the fields, save his progress and come back later to fill some more using the same URL.

This scenario would allow the admin to create new instances, pre-fill some fields and send the form url by email to the final anonymous user.

The reason for all this is basically to avoid user registration and hold each user's submission to his unique URL form.

# Answer
Any instance of a Webform is a node so each anonymous user get his own submissionreference. So e.g the name of the form is harrypotter the user is getting harrypotter/1 Where 1 is the submission nr.

In rules you are able to get the submission id, get the content and redirect to the form again.

However you have to protect it again other users. Therefore you can use another Web form in front of it which ask for a pincode. You can redirect the user with the help of the pincode and rules to the correct submissionid
> 2 votes

---
Tags: forms, webforms, users, uri
---


# Question
Title: weird error - failed to open stream - .module file in theme path?
I am just editing empty template, creating regions and so on. After I first time cleared cache weird error started to appear at every cache clearing:

> Warning: include\_once(C:\xampp\htdocs\hkmzvolen/sites/all/themes/activit/activit.module): failed to open stream: No such file or directory v \_theme\_process\_registry() (riadok 565 z C:\xampp\htdocs\hkmzvolen\includes\theme.inc).
>
> Warning: include\_once(): Failed opening 'C:\xampp\htdocs\hkmzvolen/sites/all/themes/activit/activit.module' for inclusion (include\_path='.;C:\xampp\php\PEAR') v \_theme\_process\_registry() (riadok 565 z C:\xampp\htdocs\hkmzvolen\includes\theme.inc).

It is trying to include activit.module from theme folder and not from module folder. There are a custom module and custom theme with the same name - activit. But there is no any activit.module file in theme directory nor I am including the file anywhere in my code.

Why is drupal trying to include this nonexisting file from my theme path?

# Answer
> There are a custom module and custom theme with the same name - activit

That's what causes the problem. Module and theme names need to be unique amongst one another. Drupal doesn't support duplicate names, and weird things can happen if you go against that.

See Module/theme name collision for more information.
> 1 votes

---
Tags: 7, theming, files
---


# Question
Title: drush --quiet cron generates watchdog notices
We have started using `drush cron` to manage our basic Drupal sites' scheduled tasks. I set this up using the guide at http://docs.drush.org/en/master/cron/ and it seems to be working well, except that these messages are generated on every run:

```
 [notice] WD Periodic: No periodic processes to run.
 [notice] WD cron: Cron run completed.

```

despite passing the `--quiet` option.

Is there a way to silence this output while still being made aware of any issues that come up with the cron task in future? We can redirect these two lines to standard out and filter on them but I wanted to find out if there is something about our Drupal setup that is causing the lines to be generated.

Our cron line is almost identical to the one in the article, but for the sake of completeness I've included it below:

```
0 * * * * apache /usr/bin/env PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin COLUMNS=72 /bin/drush --root=/path/to/our/drupal/site --uri=our.drupal.url --quiet cron

```

The drush version is 9.0-dev. Drupal version is 7.50.

Thanks for any suggestions you can provide.

# Answer
`drush cron` simply calls the Drupal cron function. Drupal is initiating the watchdog messages; Drush implements `system_watchdog()` to convert these messages to drush log entries (Drupal 6 and 7). If you set the option `--watchdog=0`, then these messages will not be printed by Drush.

If there is a problem with cron, then `$?` should still be set to a nonzero value when `drush cron` exits, and the watchdog messages will still be available in the Drupal Watchdog log (visible via `drush watchdog`).

If you need a finer level of control over the error behavior of Drush cron, please submit a feature request in the issue queue.
> 3 votes

---
Tags: drush
---


# Question
Title: hook_form_alter() does not work for the contact form?
I have contact form module enabled from core drupal 8 modules.

When I use the below code it has

```
   $form['field_consumer_name']['widget'][0]['#title'] = 'Individual Name';

```

I want that this code which I have written should override default title but it does not . I would be interested in knowing how I can override title?

```
 function referral_q_form_contact_message_referral_form_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state ) {
   // print_r($form['field_consumer_name']['widget'][0]['#title']);
$form['field_consumer_name']['widget'][0]['#title'] = 'Consumer Name Works';

   $form['#prefix'] = '<div class="referral-container">';

   $form['field_consumer_name']['widget'][0]['#title'] = 'Individual Name';
   $form['field_referral_date']['widget'][0]['#title'] = 'Date';

   $form['field_diagnostic_code_1']['widget'][0]['#title'] = 'Diagnostic Code';

   _referral_q_remove_radio_na($form['field_veteran']);

   $form['#suffix'] = '</div>';
 }

```

# Answer
This is the array structure of the relevant part of the form.

>

Using \`$form\['field\_consumer\_name'\]\['widget'\]\[0\]\['value'\]\['#title'\] = 'Individual Name'; worked for me.
> 1 votes

---
Tags: 8, emails
---


# Question
Title: Upgrading and creating entity references
I have a Drupal 6 site which I plan to upgrade to Drupal 7, but I would like to do some alterations to one of the content types on the upgrade.

When I built the site I did not use D6 Node References on a content type when I probably should have; for example, instead of referencing a company content type containing fields for its name and website, I just have two plain fields, company name and URL. I would like to find a way to fix this on the 'new' site.

Do I try to fix this on the Drupal 6 site then do the Drupal 7 upgrade, do the upgrade and then create the D7 entity references, or can I, as part of the upgrade, build the entity references automatically?

I'm not planning on doing a Drupal 7 or Drupal 8 data migration, so that option is out.

# Answer
> 0 votes
If you attempting a Drupal 6 to Drupal 7 update without migration, you want to keep the structures as simple as possible since minimizing rough edges. Therefore, I would wait until after the update.

Once the site is upgraded, I would update the content types involved, and then write a simple custom module that creates a batch job for the conversion.

---
Tags: 7, upgrading
---


# Question
Title: Does the Context module check block visibility settings?
I am using Drupal 7.14 and the Context module (7.x-3.0-beta4).

I set block visibility settings and the Context module doesn't seems to be checking them before rendering. Only context conditions are validated before rendering a block.

I would like to use PHP code as visibility conditions to render a block, but Context module is not respecting block visibility settings.

Is it a bug? Or context module is designed to respect only Context Visibility settings but not block visibility settings that are enabled in a particular context.

Any idea ?

# Answer
### Context module ignores Block visibility settings

The Context module does not check (take into account) the "*Block visibility settings*". If you want that to be the case, then you need to also use the Context Respect module. Some details about this module, from its project page:

> Extends the Context module by making it respect default block settings.
>
> This makes it so you can retain your block visibility when assigning them into various Contexts. You can also 'Override' from the block level to ignore Context Respect.

### Alternative to Context module

Have a look at the Rules block visibility module as a valid alternative. Refer to my answer to "How to stop a Views block from displaying to admins, such as user/1?" for more details about it.

By using this module as an alternative, you'd only have to create a Rules Component with Rules Conditions that could be identical to the "PHP code" as in your question. However, if you can, you should try to avoid such PHP code if you have other Rules Conditions available that could be used as an alternative to such PHP code.
> 3 votes

# Answer
Context module does not care what you write on block visiblity settings. It will only check context conditions. Here is the link which will help you have context and drupal core block system work together. http://www.echoditto.com/blog/mixing-context-and-drupals-native-block-ordering-system
> 0 votes

# Answer
Try the Context Respect Module:

> Extends the Context module by making it respect default block settings.
>
> This makes it so you can retain your block visibility when assigning them into various Contexts. You can also 'Override' from the block level to ignore Context Respect.
> 0 votes

---
Tags: 7, blocks
---


# Question
Title: Paragraphs item doesn't load on node/add
I have one content type were I cannot add Paragraph items. I select the item, And I get the table header, but no paragraph loads, no error.

In logs I see:

> Location: .../system/ajax/
>
> Referrer: .../node/add/product/
>
> Message:
>
> Notice: Undefined index: #bundle in theme\_paragraphs\_field\_multiple\_value\_form() (line 1170 of .../sites/all/modules/contrib/paragraphs/paragraphs.module).

Line 1170 is:

```
// Add the items as table rows.
foreach ($items as $key => $item) {
  $item['_weight']['#attributes']['class'] = array($order_class);
  $delta_element = drupal_render($item['_weight']);
  $cells = array(
    array('data' => '', 'class' => array('field-multiple-drag')),
    drupal_render($item),
    array('data' => $delta_element, 'class' => array('delta-order')),
  );
  $rows[] = array(
    'data' => $cells,
    'class' => array('draggable', drupal_html_class('paragraphs_item_type_' . $item['#bundle'])), // Line 1170
  );
}

```

This has worked, and I have other content types on which this field works. I can not see any difference in the field or content types.

Has anyone run into this before? I would love some direction on where to look for problems.

# Answer
This seems like it can be related to the Entityqueue module. The Draggable tables widget provided by the Entityqueue module doesn't take into account that their are other entity forms (like paragraphs in your case).

There is a patch to fix this currently but it needs some work: https://www.drupal.org/node/2460503
> 1 votes

---
Tags: 7
---


# Question
Title: Overriding fields from one content type which inherit from another content type
Imagine we have 50 different professions in the same domain (medicine for example). In a region, we can have 5 doctors who have the same addresses, and in another region we can have 15 doctors in different addresses. We want their information to be stored in the database (e.g. addresses, telephone number).

So I decided to do this:

* Content type 1 (general information): title, field\_region, field\_tel, field\_email, etc.
* Content type 2 (specific information): title, field\_region, field\_inherit\_from, field\_tel, field\_email, etc.

Thus, when we want to add specific information to a profession X from region Y, we have to create a new content of content type 1 and then create content type 2 which will override specific fields from content type 1.

Keep in mind that a same region may have 10 professions who have same phone number, same email address but 7 professions have its own email address for instance. Also, keep in mind that there is more than 15 different fields (so 10 different type of information about the professions).

How can I do this? I just don't know what the best way to do it is.

# Answer
> 1 votes
As you say Content Type 2 has the same fields of Content Type 1 (except for the reference) I think you don't need 2 content types in your model.

You can have a region with 10 professions with similar information, but they need something different between each other. They can have many similar fields (infos), but they need a field with a different value. If not, why do you need 10 nodes (professions) with the same information?

And you can have other 7 professions who have different information than the first 10 professions, but they are all Profession. All the 17 professions have the same fields with more differences others with less.

In this case, you can use only one Content Type and create in first place the most general professions nodes (with the most general fields) and use a module like Node clone.

> The clone module allows users to make a copy of an existing item of site content (a node) and then edit that copy. The authorship is set to the current user, the menu and url aliases are reset, and the words "Clone of" are inserted into the title to remind you that you are not editing the original content.

# Answer
> 1 votes
I am not sure if you are using D7 or D8, so will take a high level approach.

I would suggest that you will need to use an entity reference field on Content Type 2 (Person) to reference the item of Content Type 1 (Profession template) that will provide the default values for fields that are not filled in. They might even be the same content type if all the fields are the same, and all can accept default values (though if so watch out for recursion in the next step).

Now using a custom module, on node load, you can check for empty fields and replace their values with those of the referenced node.

---
Tags: 7, nodes
---


title: Writing a LEFT JOIN

text:
# Question
Title: Writing a LEFT JOIN
I have the following raw SQL:

```
 SELECT *
 FROM node_field_data n
 LEFT JOIN book b ON n.nid=b.nid
 WHERE n.type IN ('book')
 AND (b.has_children != 1 OR b.nid IS NULL)

```

I have a module that I need to add this query to, so I already have a $query object. The problem I'm having is finding the documentation/syntax to do the LEFT JOIN part of my query.

This is what I've added to `$query`.

```
 $query->addWhere(0,'node.nid', 'b.nid');
 $query->addWhere(0,$types,'IN');
 $query->addWhere(0,'b.has_children',1,'<>');
 $query->addWhere(1,'b.nid','IS NULL');

```

How do I add the `LEFT JOIN` part?

# Answer
The method is actually named `leftJoin`:

```
$query->leftJoin('book', 'b', 'n.nid = b.nid');

```
> 5 votes

---
Tags: 8, database
---


# Question
Title: How to add a button to a custom table that opens a form in a new tab and automatically fills out with data from that table
I have a custom module where I create a table from some data. In one of the columns I need to have a button that when clicked will open a new tab and show the user a form and a submit button and some of the form fields are pre-filled with data from the table (data from the same row).

I know how to add a button but I don't know how to pass the data to the form.

Also, for the button I'm using the following code and maybe this is already wrong:

```
$new_button = '<a href="/examples/form-example" target="_blank" class="btn btn-primary" role="button">New form</a>';

```

Note: the data is not in the drupal database. The table is made on the fly using REST.

Any help will be greatly appreciated. Thanks!

# Answer
Prepopulate module can pass value to form with query parameter.

Simple example:

```
<a href="/node/add/content?edit[title]=This is the title" target="_blank" class="btn btn-primary" role="button">New form</a>';

```

More examples can be found on its documentation.

If you find problems, please check this issue, some known bug has been introduced from 7.x-2.1 version. You may need to patch it.
> 3 votes

---
Tags: forms
---


# Question
Title: Rewrite the image markup from specific image field
In a Drupal 7 site, I have an image field that allows unlimited images, called `field_gallery_images`. I built a template file for this field to create a custom image slider. I want to rewrite the HTML markup for the image to add a lazy-load component. So, instead of:

```
<img src="/sites/default/files/myimage.jpg" width="668" height="500">

```

I want:

```
<img data-lazy="/sites/default/files/myimage.jpg" width="668" height="500" class="lazyload">

```

Right now, the images are being run through theme\_image() and so by the time it gets to the template, the markup is all set. I only want to alter the markup for this one field. I tried theme\_preprocess\_image(), but that altered all images.

# Answer
I assume that you are using Drupal 7.

# Short Answer

Implements `template_preprocess_field()` and overrides `theme_image()`.

```
/**
 * Implements template_preprocess_field().
 */
function mytheme_preprocess_field(&$variables) {
  $element = &$variables['element'];

  if ($element['#field_name'] === 'field_image') {
    foreach (element_children($element) as $key) {
      $item = &$element[$key]['#item'];

      $src = file_create_url($item['uri']);
      unset($item['uri']);
      $item['attributes']['data-lazy'] = $src;
      $item['attributes']['class'] = array('lazyload');

      $element['#items'][$key] = $item;
      $variables['items'][$key]['#item'] = $item;
    }
  }
}

/**
 * Overrides theme_image().
 */
function mytheme_image($variables) {
  $attributes = $variables['attributes'];

  if (!empty($variables['path']) || !isset($attributes['data-lazy')) {
    $attributes['src'] = file_create_url($variables['path']);
  }

  foreach (array('width', 'height', 'alt', 'title') as $key) {

    if (isset($variables[$key])) {
      $attributes[$key] = $variables[$key];
    }
  }

  return '<img' . drupal_attributes($attributes) . ' />';
}

```

---

# Long Answer

By implementing template\_preprocess\_field(), you can alter the **theme variables** and also the **theme function** for a field.

Example code:

```
/**
 * Implements template_preprocess_field().
 */
function mytheme_preprocess_field(&$variables) {
  $element = &$variables['element'];

  if ($element['#field_name'] === 'field_image') {
    foreach (element_children($element) as $key) {
      $item = &$element[$key]['#item'];

      $src = file_create_url($item['uri']);
      unset($item['uri']);
      $item['attributes']['data-lazy'] = $src;
      $item['attributes']['class'] = array('lazyload');

      $element['#items'][$key] = $item;
      $variables['items'][$key]['#item'] = $item;
    }
  }
}

```

Remember to change `field_image` to the field name you defined.

It is the structure of `$variables`:

`$variables['items'][0]['#item']` is a typical usage of theme function in render array. The code above has done a couple of things:

* unset `uri`, which is used to format the attribute `src` in `theme_image()`
* construct image path and assign it to the attribute `data-lazy`
* add `lazyload` to class
* synchronise the item array to different location of `$variable`

The last point is a bit weird, but there are 3 different location always store the same item array. They are

* `$variables['element'][0]['#item']`
* `$variables['element']['#items'][0]`
* `$variables['items'][0]['#item']`

Theoretically, `$variables['items'][0]['#item']` is the only one be used in theme function, But, in my opinion, it is better to change them at the same time for preventing any potential issue in future. **(Maybe someone can provide more suggestion here?)**

The last but not the least, you have to override the `theme_image()`. It is a global change but won't affect too much.

```
/**
 * Overrides theme_image().
 */
function mytheme_image($variables) {
  $attributes = $variables['attributes'];

  if (!empty($variables['path']) || !isset($attributes['data-lazy')) {
    $attributes['src'] = file_create_url($variables['path']);
  }

  foreach (array('width', 'height', 'alt', 'title') as $key) {

    if (isset($variables[$key])) {
      $attributes[$key] = $variables[$key];
    }
  }

  return '<img' . drupal_attributes($attributes) . ' />';
}

```
> 4 votes

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


# Question
Title: views entity reference to point email instead of uid in contextual filter?
I'm using Drupal 7 and Views. I've been trying to sort out, entity reference to enable a contextual filter to sort by email, instead of UID as currently I am doing.

Is that possible?

# Answer
Yes. If you're look to contextually filter a view based on an Entity reference's (user) email, you can add a **Relationship** with the value of *Entity Reference: User*. This allows your view rows to be join with the rows in the entity that is referenced.

With the relationship added, you can add a new *User: E-mail* contextual filter for the view.
> 1 votes

---
Tags: 7, users, views
---