# Question
Title: how to implement hook_menu so that it recognizes URL like ?q=myterm, as sent by jQuery autocomplete?
The jQuery UI autocomplete source string expects the search string to be appended to the URL as mysite/auto/?q=myterm (see jquery autocomplete doc)

I have written a module that implements hook\_menu and it returns the matching records through JSON. The expected url is mysite/auto/myterm

How should the hook\_menu be written so that it recognizes the ?q=myterm

I am using Drupal 7 and have Clean URL

**Edit:** can you explain with an example or use this code: can you help with an example?

> url localhost/myauto/?q=sometext

```
mymodule_menu(){
$items['myauto/%'] = array(
    'title'= 'My example',
    'page callback' => 'myexample_auto',
    'page argument' => array('1'),
    'access callback' => TRUE,
 );

myexample_auto($arg){
...//user $_GET['q'] or drupal_get_query_parameters to get 'sometext' from $arg
}

```

# Answer
`hook_menu()` don't handle query parameters. It accepts only wildcards. You can get your query parameters in in your menu callback function and build your own logic by getting parameters as `$_GET['q']` or `drupal_get_query_parameters()`
> 1 votes

---
Tags: javascript, hooks
---


# Question
Title: Rate module: Calculating and displaying variance and standard deviation
I would like to calculate the variance and standard deviation and display this alongside the mean 'result' in a view on a site running Drupal 7.

Wondering if anyone has any tips on how I might achieve this.

Awesome module. Thanks in advance for any tips.

Danny.

# Answer
Did this by creating a custom views field handler in a custom module.

The handler contained the simple php logic I need.

/\** * @file * Definition \*/

class rate\_calc\_handler\_result extends views\_handler\_field {

```
/**
* Loads additional fields.
*/
function query() {

}

/**
* Renders the field handler.
*/
function render($values) {

// Calculate the variance and Standard Deviation
$criteria = array();
$criteria["entity_id"] = $values->nid;
$criteria["entity_type"] = "node";
$criteria["value_type"] = "points";
$criteria["tag"] = "Score";

$votes = votingapi_select_votes($criteria);
$count = count($votes);

if (!empty($votes) && ($count > 1)){

    foreach($votes as $vote){
        $sum += $vote['value'];
    }

    $mean = $sum/$count;

    foreach($votes as $vote){

        $diff = $vote['value'] - $mean;
        $sumdiff += pow($diff, 2);
    }

    $variance = $sumdiff / $count;
    $stddev = round(sqrt($variance), 1);

}

return ($stddev);

}

```

Danny.
> 0 votes

---
Tags: 7, views, rating
---


title: Drupal Migrate doesn't register

text:
# Question
Title: Drupal Migrate doesn't register
When trying to set up a migration, I can't seem to register new Migrations. When running `drush migrate-status`, I only see my User migration, even after a `drush migrate-register`.

My `migrate.inc` looks like this:

```
function module_migrate_api() {
    $api = array(
        'api' => 2,
        'migrations' => array(
            'User' => array(
                'class_name' => 'UserMigration'
            ),
            'News' => array(
                'class_name' => 'NewsMigration'
            ),
            'Activity' => array(
                'class_name' => 'ActivityMigration'
            )
        )
    );

    return $api;
}

```

And my `module.inc` file contains classes for each of these Migrations, based off of the `UserMigration` I wrote first (example given is `UserMigration`, which works, and `NewsMigration`, which does not work):

```
class UserMigration extends TestMigration {
    public function __construct($arguments) {
        parent::__construct($arguments);

        $this->description = t('Migrates users');

        $query = Database::getConnection('default', 'original')
            ->select('users')
            ->fields('users', array(
                'user_id',
                'username',
                'firstname',
                'lastname'
            ));
        $this->source = new MigrateSourceSQL($query);

        $options = array();
        $this->destination = new MigrateDestinationUser($options);

        $this->map = new MigrateSQLMap($this->machineName, array(
            'user_id' => array(
                'type' => 'int',
                'unsigned' => TRUE,
                'not null' => TRUE,
                'description' => t('Source ID')
            )
        ), MigrateDestinationNode::getKeySchema());
    }

class NewsMigration extends TestMigration {
    public function __construct($arguments) {
        parent::__construct($arguments);

        $this->description = t('Migrates news');

        $query = Database::getConnection('default', 'original')
            ->select('news')
            ->fields('news', array(
                'news_id',
                'user_id',
                'title',
                'text'
            ));
        $this->source = new MigrateSourceSQL($query);

        $options = array();
        $this->destination = new MigrateDestinationNode('news');

        $this->map = new MigrateSQLMap($this->machineName, array(
            'news_id' => array(
                'type' => 'int',
                'unsigned' => TRUE,
                'not null' => TRUE,
                'description' => t('Source ID')
            )
        ), MigrateDestinationNode::getKeySchema());

        /* $this->addFieldMapping('target', 'source'); */
    }
}

```

So far, I haven't added fieldmappings, since I want to set up everything that should be migrated first, to get a complete view of the work that's left.

When running `drush migrate-register`, I'm getting the following output:

```
All statically defined migrations have been (re)registered.                                                                                [success]

```

And a `drush migrate-status` gives me the following:

```
 Group: Test  Total  Imported  Unprocessed  Status  Last imported
 User         55     0         55           Idle    2015-12-03 13:40:30

```

So as you can see, no errors, not even when running with -v. But only User is recognized. Both classes are in the same file. Am I missing something simple?

# Answer
> 0 votes
Make sure you clear your cache (`drush cc all`) after (re)registering your classes. Not doing so will often result in the migrate page showing error ClassName no longer exists.

# Answer
> 0 votes
Sometimes it helps to specify the exact name, e.g.

```
drush migrate-register NewsMigration

```

If won't work, clear cache and restart your memcached if in use.

Also when sometimes re-registering the class, but you should try unregister and register it again, e.g.

```
drush migrate-reset-status User
drush migrate-deregister User
drush migrate-register User

```

Using `deregister` will remove the old `migrate_map_%` table and `register` should recreate it. See also this post for further suggestions.

---
Tags: migrations
---


# Question
Title: How to add the datepicker jQuery UI element to Highcharts in a Drupal site?
I am creating a Highstock (Highcharts) page in a Drupal site and I cannot seem to add the datepicker element. I have successfully implemented it in a non-Drupal environment here:

https://jsfiddle.net/MrSnrub/g7u14p10/

...but when I try to migrate it to a Drupal module, it fails. As I understand it, both jQuery and jQuery UI are installed by default in Drupal, is there a specific version that I need to worry about? When I load up Firebug, it does not give me an error about the datepicker, so it must be interpreting it correctly, but when I load the page and click on the textbox, no datepicker appears. I have jquery\_update module installed, and I'm running Drupal 7. Here is my relevant Highstock JavaScript code:

```
$('#div-highstock-container').highcharts('StockChart', {
  chart: {
    renderTo: 'div-highstock-container',
    events: {
      load: create_new_legend
    }
  },

  // ...

  series: seriesOptions
},
function(chart) {
  // apply the date pickers
  setTimeout(function() {
    $('input.highcharts-range-selector', $('#' + chart.options.chart.renderTo)).datepicker()
  }, 0)
});

```

HTML:

```
<div id="div-container">
  <div id="div-highstock-container"></div>
  <div id="div-new-legend"></div>
</div>

```

PHP (in hook\_page):

```
drupal_add_library('system', 'ui.datepicker');
drupal_add_js('
  jQuery(document).ready(
    function() {
      jQuery( ".highcharts-input-group" ).datepicker({
        autoSize: true
      });
    }
  );
', 'inline');

```

Do I need to call the datepicker() method in the PHP code or in the JavaScript code at the end of the highcharts() object creation function call, or both?

**UPDATE:** I changed the PHP code to the following, but the datepicker is still not showing:

```
drupal_add_js('
  (function ($) {
    Drupal.behaviors.addHighStockDatepicker = {
      attach: function(context, settings) {
        $( ".highcharts-range-selector" ).datepicker();
      }
    }
  })(jQuery);
', 'inline');

```

If I change the element from ".highcharts-range-selector" to "#div-highstock-container" the datepicker does appear in the main container (therefore, I know I am loading the jQuery library datepicker file successfully), so why does it not appear when I try to apply it to all elements with class "highcharts-range-selector"?

# Answer
> 2 votes
The datepicker was being displayed, it was just hidden by the Highchart. Adding `z-index: 9999 !important;` to the `.ui-datepicker` CSS solved it.

# Answer
> 0 votes
You need to wrap your JS code with Drupal behaviors, which can ensure your JS run after all required DOM elements in page are ready.

```
(function ($) {
  Drupal.behaviors.exampleModule = {
    attach: function (context, settings) {
      // Code to be run on page load, and
      // on ajax load added here
    }
  };
}(jQuery));

```

Also, you are not sure how to know if the jQuery is working. You can add `console.log` to output the jQuery object in console.

```
var obj = jQuery( ".highcharts-input-group" );
console.log(obj);

```

---
Tags: javascript
---


# Question
Title: Add an image to a views title (Taxonomy Term View)
I have a view listing nodes of my taxonomy terms. All well and good and my view shows nodes of every taxonomy term with the taxonomy term name as the view title.

My taxonomy terms though have an image assigned to them. So is there any hook or any other way to show the taxonomy term title next to its corresponding image? Something like this?

**Example image:**

>

And here is a screenshot of the view. Notice the path that is taking the term id as a parameter to display nodes of a specific term.

EDIT: I am using the default Taxonomy Term View

**Views UI**

>

# Answer
I would use Panels for that. You may combine any elements from Drupal on the same page (node fields, views, terms, blocks, etc.) with Panels.

With this module you can edit the taxonomy term page as you wish (Structure \> Pages \> Taxonomy view \> Active then edit).

In the Content section, after setting path, context and layout, you add your taxonomy term custom image field, followed by your taxonomy term name (with a little CSS float, you will have your image on the left).

Finally, you add your View below (do not forget to activate the Chaos tools sub-module "Views content panes") and you're done.

Panels needs a little practice but it is a powerful tool to work on page templates.
> 2 votes

# Answer
Thanks to @Toki I figured out a simple solution using Context instead of Panels.

1. I created a new view of taxonomy terms with a contextual filter of Term ID provided by the URL. In my View I have a limit of one item to display, and I show only the term name and icon field without anything else.
2. I created a block and using Context I placed my block to the Term Pages (I don't think this is needed because the Block will only show up in Taxonomy Term pages anyway, because of the Contextual Filter).
3. I added some css and done.

Sometimes we complicated things. Thanks again @Toki for the main idea.
> 1 votes

---
Tags: 7, views
---


# Question
Title: How to allow for redirecting on same URL with different query strings?
I'm using Drupal 7. I have about 120 urls with different query strings, and **Drupal is not allowing me redirect on same url with different query strings/parameters**.

For example:

I have to redirect **from this url blog/its-time-occupy-it?page=1** to **blog/its-time-occupy-it**. See more example given below;

```
(from url) blog/about-author?page=1  -> (to url) blog/about-author
(from url) blog/about-author?page=2  -> (to url) blog/about-author
(from url) blog/about-author?page=3  -> (to url) blog/about-author

```

Any suggestions to give me solution to fix this issue?

# Answer
Using the Rules module you can implement a rule that looks like so:

```
{ "rules_redirect_all_node_aliases" : {
    "LABEL" : "Redirect all node aliases",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "init" : [] },
    "IF" : [
      { "text_matches" : {
          "text" : [ "site:current-page:path" ],
          "match" : "blog\/about-author?page",
          "operation" : "starts"
        }
      }
    ],
    "DO" : [
      { "redirect" : { "url" : "blog\/about-author" } }
    ]
  }
}

```

It will redirect any path starting with `blog\/about-author?page` to a path named `blog/about-author`. So this will "***redirect any such paths but with different query strings/parameters to the same url***" (as in your question ...).

To experiment with this rule in your own site, just copy the entire Rules code above, and paste it in a new Rule in your own site, created via the "Import" function (available if you have the Rules UI enabled).

## But wait, there is more ...

You could also check if `page` was specified as an URL argument. And make the actual value specified for such argument (like in your question: the `1`, `2` or `3` after `page=`) available as a new variable to Rules. To do so, use the Rules URL Argument module. Here is a quote about it (from its project page):

> ... provides two rules conditions based on URL arguments:
>
> * check if a URL argument is present.
> * compare the value of an URL argument.
>
> It also provides an action that makes the value of an URL argument available as new variable to Rules.

The newly provided Rules actions and conditions can be found under the "URL Argument" conditions and actions groups in the rules configuration interface.

For an example of how to use it, refer to Comment # 3 in issue # 1686360 which is about "*Pass an amount to the url, ie; site/content/node-title?amount=10 or /node-title?=amount:10*". Here is the relevant part of it:

> * add a "Check if URL argument exist" condition to your rule and set the "ARGUMENT" value to "amount".
> * add "Provide URL argument value" action to the rule and set "URL ARGUMENT NAME" value to "amount" and in the "Provided variables" section "ARGUMENT FROM URL - Variable name" to e.g. "`amount_from_url`".
>
> You will now be able to use the amount value as a variable "`amount-from-url`" for other actions in this rule.
> 3 votes

---
Tags: 7, uri, redirection
---


# Question
Title: Create link to users created content only
I have a content type Business, When a user creates a business and then signs into the site, I have a link called "my business" that when the user clicks on i want it to take them to only their created business.

Not sure what to "link" too for this to happen.

# Answer
You can link to a view, that filters the content type Business and the current user.

This is a similar question for D7, I think both solutions provided there work in D8 the same way:

Filtering on node whose user ID is equal to the current user
> 1 votes

# Answer
If you create a custom module you can either use `hook_user_login()` or a custom user login form submit handler (see the answers to this question) to conditionally redirect the user.

You can get their most recently created *Business* node using an EntityFieldQuery and redirect them to that using either of the above approaches.
> 0 votes

---
Tags: 8, navigation
---


title: Passing variables to custom block

text:
# Question
Title: Passing variables to custom block
I am trying to pass variables to a custom block in a module. I can see that the custom block is used in the code, however I cannot get the variables to show up.

Any help much appreciated:

I am themeing the block in the module file

```
function etypeservices_theme($existing, $type, $theme, $path) {
   return [
    'block__etypeservices' => [
      'variables' => [
        'facebook' => '',
     ],
   ],
];
}

```

I am building the render array

```
class SocialBlock extends BlockBase implements BlockPluginInterface {
/**
 * {@inheritdoc}
 */
public function build() {
    $config = \Drupal::config('etypeservices.settings');
    $facebook = $config->get('facebook');
    return [
      '#theme' => 'block__etypeservices',
      '#facebook' => $facebook,
   ];
 }

}

```

and here is the template

```
{%
    set classes = [
   'block',
   'block-social-icons',
   ]
%}
<div{{ attributes.addClass(classes) }}>
   <ul class="list-style-none">
    {% if facebook %}
    <li><a href="https://www.facebook.com/{{ facebook }}" target="_blank">Facebook</a></li>
    {% endif %}
   </ul>
</div>

```

Can anybody see why this is not working?

# Answer
> 2 votes
For a custom template use your own theme hook `etypeservices`:

```
function etypeservices_theme($existing, $type, $theme, $path) {
   return [
    'etypeservices' => [
      'variables' => [
        'facebook' => '',
     ],
   ],
];
}

```

Which uses it's own variables space:

```
public function build() {
    $config = \Drupal::config('etypeservices.settings');
    $facebook = $config->get('facebook');
    return [
      '#theme' => 'etypeservices',
      '#facebook' => $facebook,
   ];
 }
}

```

**etypeservices.html.twig**

```
{{ facebook }}

```

The content of the block is a normal render array, which can contain one or more custom templates to make them accessible in theming. These custom templates are reusable, not only in blocks.

In a module you can override the block template, as you tried to do by using `block__...`, but you need this in very rare cases. In drupal core there is only one. Then you will inherit the variables of the base hook `block`.

But normally you leave the block template as it is, so that it can be themed on it's own.

---
Tags: theming, 8
---


# Question
Title: How to grant userpoints to users who perform a login 5 days consecutively?
I need to know if a user has performed a login, for example, 5 days consecutively. The reason for this is I want to award User points to them.

For example:

* User A performs a login on Monday, Tuesday, Wednesday, Thursday and Friday. (granted 10 points)
* User B performs a login on Monday, Tuesday, Thursday, Friday and Saturday. (no points)

I'm trying to do this with Rules but failed miserably. Any ideas?

**Note**: I'm trying to use Rules condition to compare my\_last\_login values against today's date with an offset of -1 days but it always return False.

# Answer
> 2 votes
Actually, this is what I am trying to build right now. Use the `hook_user_login()` with the following code:

```
global $user;
$last_access = $user->access;
// if last_access is today, do nothing
$yesterday_start    = mktime(0, 0, 0,date('m'), date('d')) - (60*60*24);
$yesterday_end  = $yesterday_start + (60*60*24)-1;

// if last access is yesterday, increment counter
if ($last_access > $yesterday_start && $last_access < $yesterday_end) {
  //increment counter
}
// if last access is before yesterday, set counter = 1
else if ($last_access < $yesterday_start) {
  $counter = 1;
}

if ($counter == 5) {
  // put you magic code here
  // set the counter to 1
}

```

The `$counter` can be something like `variable_get()`. Alternatively, I guess that you can put the code above in your Rules, if you don't want to write a module. In both cases, however, the code will not be executed if the user leaves his browser logged in.

# Answer
> 3 votes
Statistics module in the core would work in this case.

# Answer
> 1 votes
Using the Rules module to solve this challenge is indeed part of the solution. But the key part of your challenge is that you want a Rules Action to be triggered, for a Rules Event (= user performs a login) which:

1. has to be repeated
2. within a specified timeframe
3. which don't all happen at the very same moment.

Rules is great (actually amazing), but it does **not** support any of the 3 bullets above. So far the bad news ...

However, your question seems like a perfect case for using the Goals module (disclosure: I'm the maintainer of it). Below is a possible configuration for it, using Goals.

# Configure a goal

Navigate to the relative path `admin/config/goals/manage` and use the link "Add a goal" to define just 1 **goal**, with a description (say):

***`Perform a login, 5 days consecutively`***.

# Configure a task

To achieve the above *goal*, define the **Task(s)** to be completed. Even though there could be multiple tasks to be completed for a single goal, in your case you just need 1. It's simply ***`Perform a login`***.

Obviously, that doesn't take into account the ***`5 days consecutively`***-part of your question. For that you would use some of the more advanced ways to use (configure) Goals, i.e. by using these optional configuration options for this specific task:

* this task has to be repeated multiple times: in your case **5 times**.
* this task requires some amount of time to expire in between any 2 similar tasks: in your case, if a user performs a login/logout multiple times a day, **only the first one of every day counts**.
* this task must be completed within a specific time frame (a number of times, expressed in hours, days or weeks): in your case **5 days**.

# Track progress while performing tasks

To track the progress made by a single user to complete this task, you only have to write an appropriate rule, using the Rules module, to record relevant events happening in your site, which are related to the completion of the ***task*** to reach the ***goal***.

For the goal/task described above, you'd only need 1 (extremely basic) rule, which would look like so:

* Rules Event = After a user performs a login.
* Rules Action = Record a task for Goals (obviously, the task to be recorded is "Perform a login"). This is where part of the Goals magic happens, such as verifying the requirements in the optional task configuration options for a task (only once a day, etc).

Note: if the user leaves his/her browser logged in, then using this Rules Event might not be the most appropriate event. If you'd replace that event by "Drupal is Initializing" (within "System"), then such rule will be triggered for any path that the user visits. Optionally you may want to combine that Rules Event with an extra Rules Condition "User has role, with role = authenticated", so that the Rules Action(s) are only performed for logged in users.

# Use Rules to process completed goals

After all tasks specific to a goal are completed by a user, the goal is automagically marked as completed. **But**, that's where it gets really interesting: you can also create additional rules that will be triggered (Rules Event) when a goal is completed by a user. With that, the answer to your question is extremely easy: perform a Rules Action to "***... grant userpoints to the user who completed the goal***" ... which is exactly what your question is about, no?

# More info

Refer to my answer to "How to implement gamification in a Drupal site and award incentives?" for additional details about the Goals module.

Note: Using Goals only requires typical administration tasks (configuration), though it does come with various hooks also for custom module development (if you want to).

# Answer
> 0 votes
Enable the PHP Filter module.

Add a two fields to user profile (*admin/config/people/accounts/fields*): for the login counts (name: cons\_login\_counts, type: integer, default value: 0, permissions: custom(only for admin)) and for the last login date (name: cons\_last\_login\_day, type: text, permissions: custom).

Create a new rule with reacting on event "User has logged in". Add an action "Execute custom PHP code" and put this code:

```
$user = entity_metadata_wrapper('user', $account);
$login_counts = $user->field_cons_login_counts->value();
$last_login_day = $user->field_cons_last_login_day->value();

$today = date('Y-m-d');
$yesterday = date("Y-m-d", time() - 60 * 60 * 24);

if ($last_login_day == $today)
  return;

if ($last_login_day == $yesterday) {
  $login_counts++;
} else {
  $login_counts = 1;
}

$last_login_day = $today;

if ($login_counts == 5/* and not gived a points to user*/) {
  // give them point
}

$user->field_cons_login_counts = $login_counts;
$user->field_cons_last_login_day = $last_login_day;

$user->save();

```

# Answer
> -1 votes
Rule has to be triggered when a user is logging in and you need to write Custom PHP Code in the Do Action part of Rule. Like

```
if(check_user_logins($uid)){
  db_query("UPDATE <table> set points = points + 5 WHERE uid = %d", $uid);
}

function check_user_logins($uid){
  // Code to check consecutive user logins goes here
  if($logins >= 5){
    return TRUE;
  }else{
    return FALSE;
  }
}

```

---
Tags: users, rules, userpoints, nodes
---


# Question
Title: Default File Display is Using Incorrect Image Style
I'm using Media-7.x-2.0-beta1. When adding an image with the default file display (default file display is identical to Original), it uses the "Medium" thumbnail display. I've checked to make sure the default is not configured to this display.

Where would these settings be saved that I could double check to make sure they were actually changed when I altered them? Is there any other reason for the Default display to be displaying the image in the wrong image style?

# Answer
After some search, I got your issue and from where you can set that. So I delete my previous answer and following is the updated one.

As in my setting, I have four Image settings,

* Default
* Teaser
* Preview
* Wysiwig

Now, by default it is taking some `height` and `width`.

Now those all four setting you can change at `Admin/Structure/File types/Images/Manage file Display` and you can find all four image file set on right hand top corner in following images. Now, you can see as I have selected Default and at bottom of the page it is showing `None(original image)`.

>

Note: Now, image uploaded in the body field area before save/post of the body content may not show what you have selected, but if you post it it will show what you image style you had selected. As stated in following image.

>
> 1 votes

---
Tags: 7, files
---


# Question
Title: Why some twig templates have no file name suggestions
I have enabled twig debug. The following source snippet shows that there are some templates has no any suggestions such as `views-view.html.twig`:

```
<!-- THEME DEBUG -->
<!-- THEME HOOK: 'block' -->
<!-- FILE NAME SUGGESTIONS:
   x block--saidbakr-content.html.twig
   * block--system-main-block.html.twig
   * block--system.html.twig
   * block.html.twig
-->
<!-- BEGIN OUTPUT from 'themes/saidbakr/templates/block--saidbakr-content.html.twig' -->
<section class="row" id="website_templates">
    <div class="row">
    <div class="col-xs-12 col-md-12">
        <h3>Latest Articles</h3>
    </div>
  </div>
  <div class="row">
    <div class="col-xs-12 col-md-12">
<!-- THEME DEBUG -->
<!-- THEME HOOK: 'container' -->
<!-- BEGIN OUTPUT from 'themes/saidbakr/templates/container.html.twig' -->
 <div class="views-element-container">
<!-- THEME DEBUG -->
<!-- THEME HOOK: 'views_view' -->
<!-- BEGIN OUTPUT from 'themes/saidbakr/templates/views-view.html.twig' -->
  <div class="js-view-dom-id-e66395c77e6b1af2b2d7c58650cebe72cb3979b5875ff26b9f67fcdf025f6b47 item_container" style="position: relative; width: 338px; height: 220px;">

```

The question is: why those templates has no suggestions like others? Is there any way to have suggestions for them or even any way to replace them with another templates files for specified place such as, hypothesis name of course, `node--article--teaser--view-views`

# Answer
You can use the theme hook given to create your own theme hook / template suggestions or see additional suggestions that are not showing up in Twig debug, this happens occasionally. (I wonder if this is a bug?)

For example, the theme hook here you are targeting is `views_view`.

If I do:

```
function MYTHEME_theme_suggestions_views_view_alter(&$suggestions, $vars, $hook) {
  kint($vars);
}

```

... If the name of my view is "News" and it's a page display, I see in the theme area printed out in kint:

```
views_view__news__page_1
views_view__page_1
views_view__news__page
views_view__page
views_view__news

```

You can take any of these and replace the underscores with dashes and then add `.html.twig` and you should be good to go.

e.g. `views-view--news--page-1.html.twig`

**Resources:**
> 6 votes

# Answer
For Views in particular, there is a project which adds some of the templates that didn't make it into core: Views Templates.

If, like me, you just need to add a template for a specific view, you can add a function to your theme that implements `hook_theme_suggestions_views_view_alter()`.

```
/**
 * Implements hook_theme_suggestions_views_view_alter().
 */
function mytheme_theme_suggestions_views_view_alter(array &$suggestions, array $variables) {
  if (isset($variables['view']->element['#view_id'])) {
    $suggestions[] = 'views_view__' . $variables['view']->element['#view_id'];
  }
}

```

This would go in your `mytheme.theme` file of your custom theme. This will then make it possible to add a template that matches your view. EG: for a view named `latest_posts`, you could create a template: `views-view--latest_posts.html.twig` to override the core `views-view.html.twig` template.
> 1 votes

---
Tags: theming, 8, debugging
---


# Question
Title: Use Twig to render HTML email body for SwiftMailer
I have a custom module with a controller where I'm building a PDF file with a node's data that will be mailed to a certain user.

I have installed the SwiftMailer module and I have been able to produce my desired outcome, but it isn't very clean.

I was wondering if I could use a `twig` template to build the body of my HTML email. Is there anyway I can make use of Drupal's Twig Extension for this purpose?

I already created a `email.html.twig` file with the layout I need and I already have a `$parameters` array with all the variables I need to use in the template, but as SwiftMailer uses an HTML string in the `setBody()` method, I'm trying to use Twig to produce the HTML I need to use there. Any thoughts?

Please note that I don't want to use the twig template *in* my module ( to show a Drupal page or something), but rather have Twig render an HTML string I can use with SwiftMailer. Also, the instructions for the SwiftMailer module regarding theming are rather confusing for me and they are for Drupal 7, so I don't see how I can make use of them in my case.

Any help would be very welcome!

# Answer
Sure, that's possible. It works exactly as if you would render something for the page.

After preparing your render array like you always do, all you need to do is call the renderPlain() method of the renderer service, that gives you a string (Actually, a Markup object containing a string).

`contact_mail()` does exactly that, the relevant part:

```
$build = entity_view($contact_message, 'mail');
$message['body'][] = \Drupal::service('renderer')->renderPlain($build);

```

PS: The fact it is a Markup object is important, do not try to cast it to a string.
> 2 votes

---
Tags: theming, 8, emails
---


# Question
Title: How can I get pathauto to generate language-inspecific rules?
I have created a new pattern for a specific content type, and did not select any language at the /admin/config/search/path/patterns/XYZ page so that it would apply to nodes in any language.

What I want is for this pattern to be available in every site language. However, when I create new content the alias created has language set to English, and if I navigate to /fr/new-alias it gives 404. I need to manually edit the created URL Alias and set language to "None" for it to work.

I don't see a way to specify this in the pathauto rule. Is it possible or is their a hook I can use in a custom module to force this somehow?

# Answer
> 2 votes
This is currently not possible.

Pathauto always uses the language of the entity, just like the node edit form does.

This is a pretty common scenario and there are feature requests for it, for example: https://www.drupal.org/node/2775275.

There is also a related core issue, about allowing that for manual aliases as well: https://www.drupal.org/node/2689459.

What it needs now is someone to work on those. If you have a budget, you could offer a bounty for someone to work on it. The core issue has a needs review patch, so you could help to test that, that would also help if forward.

I'm considering to implement it in pathauto following the same rules as the core issue suggests, based on whether the path field is translatable or not. That shouldn't be too hard to implement, but it will also need tests.

Disclaimer: I am a (the) pathauto maintainer, you can also contact us (my company) to work on it.

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


# Question
Title: Clean URLs not working in Drupal 8.1.8 and IIS 8
I am working on a new installation of Drupal 8 (8.1.8) on a Windows Server 2012 running IIS 8. I have installed PHP v7.0.9 and MySQL v5.7.14. During the installation process, I must have done something wrong. Upon completion, the home page is just the HTML without any styling and all of the links return an HTTP Error 404.

**The error**:

I've tried as much as I can think of (eg reinstalling IIS/Drupal/PHP/MySQL, triple checking passwords for MySQL, making sure URL Rewrite is working, etc)

**UPDATE:** I have also tried using drush to clear the cache.

**UPDATE #2:** It would seem as though my HTTP problem comes from the URL Rewrite module not working properly.

**UPDATE #3:** The site now has styling!!!!!! After reading this post, I realized that there was no 'tmp' directory in '/sites/default/files'. However, there is still a problem with the URL Rewrite. I have to include '/index.php' in every url to go to any pages.

# Answer
> 0 votes
Apparently, the URL Rewrite module had become corrupted. After repairing it, I began receiving an HTTP Error 500.50. While in discussion with one of my colleagues, we learned that I needed to set HTTP\_PROXY as a server variable. Then the whole thing worked!

Lots of stress off my shoulders.

http://forums.iis.net/t/1178209.aspx?URL+Rewrite+Module+Not+working+at+all

http://weblogs.asp.net/owscott/500-50-error-using-url-rewrite

# Answer
> 0 votes
Probably it's a directory permission issue. Drupal is not able to write into web/sites/default/files. Give this file directory right permissions for your server user. (www-data in case of apache)

# Answer
> 0 votes
I don't sure if Drush works on IIS but if it works the command for D8 is `drush cache-rebuild all`.

However, I share the answer of ssibal check the permissions, on sites/default/files and themes/your-default-theme

---
Tags: installation, uri
---


# Question
Title: How to get Entity Reference Autocomplete results to display in a table?
I am currently working on a site which will take in an unlimited amount of nodes (in this case inventory numbers) for a Sales Order which I can then save, view and export into a CSV in Drupal 7. I am wondering how I can take the results of the Sales Order and form the results into a Views Block that is attached to the Sales Order NID page.

For example here is my Entity Reference Autocomplete:

Then when I save this, I want to be able to view the results in a table when I click on the Sales Order. I would like the table to display certain information from the item (which I know is done in a view).

Here is how my Views Block is set up currently (with the preview results):   I am unsure as to why nothing shows up on either the preview or the page.

I have also tried using Inline Entity Reference but that doesn't seem to work either. I am a Drupal Ameteur, but need some help with this.

Is the Entity Reference Autocomplete list not saving properly or does it save it anywhere at all? If so, how do I access it?

EDIT: So I have the block assigned to the Sales Order Content type and it is assigned in the Content section in the Blocks menu. (I think this is right)  I also just changed the Pages section to No Restriction and nothing changed.

# Answer
The first thing thats jumps out at me is that you have "Referencing Entity" rather than "Referenced Entity" in your views relationship.

Because you are showing a view of content with the field, you are already showing the referencing entity. What you want is a relationship to the **referenced** entities.

Have you also got the views block to display on the correct content type?

You have the correct contextual filter set up (you can use "get content id from url" rather than raw value).

Make sure the block is shown in a region on all of the referencing entities content type.
> 0 votes

---
Tags: views, entities, blocks
---


# Question
Title: Change Exposed Filter from Dropdown to List
How can one change an exposed filter format so it is displayed as a list rather than a dropdown list? If it is relevant, I am using the Better Exposed Filters module.

# Answer
Go to BEF settings in the view....

Find your exposed filter, and choose the display type. (list)
> 2 votes

---
Tags: views
---


# Question
Title: Trigger Drupal Rule Based on Taxonomy Term
I have a rule built that sends an email to users of a specific role, when new, published content is created. What I want to do is be able to send this email only when the content matches a specific taxonomy term. Unfortunately, I'm struggling with this -- any help would be much appreciated!

# Answer
> 2 votes
When you say the content "matches" the term, do you mean the content has a field to select that term, and you want the email to send when the content has been tagged with that term?

If thats the case...

1. Create a new condition "Entity Has Field"
2. Choose the **taxonomy field**.
3. Create a new condition "if **taxonomy field** == taxonomy name"
4. Create action to send mail to user of a role.

---
Tags: 7, taxonomy-terms, rules
---


# Question
Title: Form elements created with AJAX aren't sending values through form_state
I've created a AJAX block form that allows a user to specify the number of fields they would like to have available. like so

```
    $form['columnNum'] = [
        '#title'   => t('Number of Columns'),
        '#type'    => 'select',
        '#options' => [
            1         => '1',
            2         => '2',
            3         => '3',
        ],
        '#default_value' => $this->configuration['columnNum'],
        '#empty_option'  => t('-select-'),
        '#ajax'          => [
            'callback'      => [$this, 'columnCallback'],
        ],
    ];

    $columns = $this->colFieldGen($this->configuration['columnNum'], $this->configuration['columns']);

    $form['column_wrapper'] = [
        '#type'       => 'container',
        '#attributes' => ['id' => 'column_wrapper'],
        $columns,

    ];
return $form;

```

the colFieldGen form, generates the number of fields like so.

```
public function colFieldGen($num, array $config) {
    for ($i = 0; $i < $num; $i += 1) {
        $numTitle    = $i+1;
        $columns[$i] = [
            $i             => [
                '#type'       => 'details',
                '#title'      => t('Column '.$numTitle),
                '#open'       => FALSE,
                'columnTitle' => [
                    '#type'      => 'textfield',
                    '#title'     => t('Column Title'),
                ],
            ],
          ];

```

And below is the callback.

```
public function columnCallback(array&$form, FormStateInterface $form_state) {
        $response = new AjaxResponse();
        $columns = $this->colFieldGen($number, $this->configuration['columns']);

        $content = [
            '#type'       => 'container',
            '#attributes' => ['id' => 'column_wrapper'],
            $columns,
        ];

        $response->addCommand(new ReplaceCommand('#column_wrapper', $content));
        return $response;
    }

```

I'm using the replace command to replace the fields that were present in the container, with a set of new fields. However any of the data in the new fields aren't sent through form\_state. Fields that existed already like $form\['columnNum'\] are sent through $form\_state just fine.

Is there a way to see values of ajax created form elements in $form\_state? Or is there a better way to do this entirely?

NOTE: This is all being performed in a blockForm if that makes any difference.

---

UPDATE:

I changed the field generator to be based on a form\_state variable like so

```
if (empty($form_state->getValue('number'))) {
    $form_state->setValue('number', 1);
}

$columns = $this->colFieldGen($form_state->getValue('number'), $this->configuration['columns']);

```

and then in the AJAX call performed this

```
public function columnCallback(array&$form, FormStateInterface $form_state) {
    $form_state->setValue('number', 10);
    $form_state->setRebuild(true);
    return $form;
}

```

But the form never rebuilds with the new amount of specified fields. I receive the progress animation on change, so I know something is firing. I just get no results. To see if the form was attempting a rebuild I added

```
if (empty($form_state->getValue('number'))) {
    $form_state->setValue('number', 1);
} else {
    die($form_state->getValue('number'));
}

```

to have the form fail if the form\_state already exists but it never dies.

# Answer
> 3 votes
Move all form building activities from the callback to the form build function.

The form elements you add in the callback go directly through javascript to the DOM in your browser. You see them as normal form elements, but the form API doesn't know that they are in your browser and will ignore them.

**Edit for the questions in comments:**

In the form build function you know that you are rebuilding because $form\_state is filled with data. On the first run it is empty.

You have the number of columns in the value of the select element.

You should wait with handling of the configuration data until submit.

In general an ajax form should have the same code in form build as a normal form, because if jquery is not available, ajax will fallback to a normal rebuild.

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


# Question
Title: Ordering by taxonomy field ascending but leaving those node without taxonomy at the bottom
I have a View of products (nodes). They have taxonomy associated, and I am displaying the taxonomy first and ordering by taxonomy ascending. However, I would like to have all with taxonomy ordered first, but I find that the View shows first those without taxonomy, and later those with taxonomy, in this case in the correct order. How could I indicate the View that it must reserve those without taxonomy for the last, i. e.

```
 A Taxonomy
   - Product 1
   - Product 2
 B Taxonomy
   - Product 3
   - Product 4
 ...
 Z Taxonomy
  - Product 5

  -- Products with No taxonomy -- (this message does not display, it is only for clarification here)
  - Product 6
  - Product 7

```

...

# Answer
My suggestion is to modify your main view to list only Product nodes with a taxonomy term selected, then use an attachment to your main view that lists Product nodes with no taxonomy term. The attachment would be displayed after your main view.

# Steps

**1. Filter your main view to list only Product nodes with a taxonomy term value**

In your main view's configuration, under Filter Criteria, add a filter for your taxonomy term field (choose either dropdown or autocomplete), and select **"Is not empty (NOT NULL)"**.

**2. Create the attachment that lists Product nodes with no taxonomy term value**

Add an **Attachment** display to your view.

Under **Attachment settings**, set **Attach to** to your main view display (in this example the main view is Page), and set the **Attachment position** to After.

In the attachment display's **Filter Criteria**, change the taxonomy term filter to **"Is empty (NULL)"**. Make sure to override this setting for the attachment display only or it will apply to the main view as well.

# Note about the attachment header

Your attachment view will be displayed right after your main view, so you may want to add a Header to the attachment (make sure to override to the attachment display only).

In this example I used a Text area.

Alternatively, you could add a label to the taxonomy term field. **Make sure to override this setting for the attachment display only** or it will apply back to the main view.

# Results

Your main view should now list your Product nodes by taxonomy term in ascending order, and your Product nodes with no value selected for the taxonomy at the bottom of the list.
> 4 votes

---
Tags: 7, views, taxonomy-terms
---


# Question
Title: Working with views, better use various displays or create more views?
The main task is:

**Create a couple of pages with terms of a specific list of taxonomy vocabulary. (Its about 20+ pages).**

So, its simple, create a view with a particular route, and set to display taxonomy terms, set the right vocabulary to display, set exposed filters and so on.

Now comes the question, speaking in perfomance, its better create a view to each page (with almost the same config, only vocabulary terms is different), or create just one view and create a display for each page?

Both scenarios work's great, using just one view for all pages and using a view for each page, but which one can be the best alternative for this case?

Looking in Working with Views in Drupal 8, there is nothing about perfomance and best practice. Any advice are welcome.

# Answer
> 2 votes
In the book "Mastering Drupal 8 Views" Greg Marshall suggests that there is no strong reason to prefer one or the other. He suggests using separate views most of the time, for the simple reason that it's very easy to make a mistake in the UI and apply a change to all displays when that wasn't what you wanted.

I would suggest that you think carefully about in what circumstances you are going to want to modify a view. If changes are likely to affect all displays, or be only applicable to one display of a certain type, then having a single view is fine.

If changes would likely be to multiple characteristics that could apply to all displays but you would want to be different on each display, then isolating them as separate views reduces the risk of getting in a mess.

---
Tags: views, 8
---


# Question
Title: Features - Custom User Fields Not Available after Import
I have two Drupal sites.

On Site1, I created 4 custom text fields for the User Profile. I created a Feature that included these fields. I didn't see an area where I could export the settings for Custom User fields, so I searched for their respective machine names and added them.

On site #2, I added the feature and the fields now appear to be imported.

Despite this, when going to Configuration \> People \> Account settings, going to "Add existing field" does not list the newly imported fields to that list. They also are not available as "Existing Fields" when modifying a Content Type.

On top of that, when attempting to create a field with the same machine name, it states that it is already taken.

It seems the Features has indeed imported the desired fields but they are for some reason inaccessible.

How can this be fixed?

# Answer
> 2 votes
**Solution**

You have to add the corresponding field instances in feature as well. The field instance name should be in this format:

`[entity_type]-[bundle]-[field_name]`

In your case, they should be:

* `user-user-field_first_name`
* `user-user-field_last_name`
* `user-user-field_title`
* `user-user-field_email`

---

**Sub Question 1**

> Despite this, when going to Configuration \> People \> Account settings, going to "Add existing field" does not list the newly imported fields to that list. They also are not available as "Existing Fields" when modifying a Content Type.

**Answer**

You cannot find existing fields because there is no field instance attached on the field base. Drupal won't be able to load those field base without field instance.

---

**Sub Question 2**

> On top of that, when attempting to create a field with the same machine name, it states that it is already taken.

**Answer**

The field base is stored in database and also the table is created. So Drupal will stop you from recreation.

---
Tags: features
---


# Question
Title: How to change the default logo size in the OpenChurch theme?
I'm trying to upload an image for the logo with a slightly higher resolution than the default logo, but I don't find any way to change the default logo size in the OpenChurch theme. I don't need the text beside the logo there, but I need a bigger logo.

Any suggestions?

# Answer
In your Admin toolbar, click on appearance, then click on settings.

Scroll down to **LOGO IMAGE SETTINGS** and ***uncheck*** `Use the default logo supplied by the theme` and upload your own logo.
> 1 votes

---
Tags: 8
---


# Question
Title: Load a view block into a custom page generated in a module
Is it possible to programatically insert an existing view into a block generated by a custom module and pass it a parameter?

I am generating a block based on some external api data. I have been asked to add a view that pulls in related content from the website. To do this I would like pass a view to my block and pass it a parameter I extract from the api data.

Can this be done, and if so... how?

# Answer
> 2 votes
Just like in D7, using views\_embed\_view.

```
print views_embed_view('view_name','machine_name', $parameter);

```

In case you are wondering, this is the machine\_name

Example:

```
$parameter = 1;
print views_embed_view('hello_world','block_1', $parameter);

```

---
Tags: views, 8, blocks
---


# Question
Title: Help getting the values from user profile fields from currently logged in user
As the title says, I am trying to get the values from a custom field I added to the user profile. I am using this code from a previously asked question regarding this.

```
$user = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id());
$value = user->custom_field->value;

```

This seemed to work for the person that previously asked this question but the problem I am running into is that it is only returning values of an anonymous user regardless of who I am logged in as. For example if I replace custom\_field with uid it will return a value of '0'. Any idea where I could be going wrong?

# Answer
> 1 votes
You're missing a $ in your second line.. Should be $user-\>

I always use the below.

```
global $user;
$user = user_load($user->uid)

```

And then get the field like your last line. If someone else could confirm if that is a waste and there's a better way to load the field, that'd be great.

---
Tags: users, 8
---


# Question
Title: How do I check if the form is an add/edit/delete form?
I need to check if the form is for creating, editing, or deleting a node.

Currently, the below snippet allows me to check if the form is for adding or editing a node. How do I check if the form is for deleting a node?

```
    if (!isset($node->nid) || isset($node->is_new)) {
      // The form is for creating a new node.
    }
    else {
      // The form is for editing the node.
    }

```

# Answer
You could use what said in this answer, with a slight modification.

```
function example_form_alter(&$form, &$form_state, $form_id) {
  if (strpos(request_path(), '/add') !== FALSE) {
    $page = 'add';
  }
  elseif (strpos(request_path(), '/edit') !== FALSE) {
    $page = 'edit';
  }
  else if (strpos(request_path(), '/delete') !== FALSE) {
    $page = 'edit';
  }
}

```
> 1 votes

# Answer
Try this:

```
function example_form_alter(&$form, &$form_state, $form_id) {
  if (strpos($form['#action'], '/add/') !== FALSE) {
      $page = 'add';
   }
  if (strpos($form['#action'], '/edit') !== FALSE) {
      $page = 'edit';
  }
  if (strpos($form['#action'], '/delete') !== FALSE) {
      $page = 'edit';
  }
}

```
> 0 votes

# Answer
Check if the `$form_id` is `node_delete_confirm`

```
if ($form_id == 'node_delete_confirm') {
  // delete form
}
else if (isset($node->is_new)) {
  // add form
}
else {
  // edit form
}

```
> 0 votes

# Answer
```
function hook_node_access($node, $op, $account) {
  $type = is_string($node) ? $node : $node->type;

  if (in_array($type, node_permissions_get_configured_types())) {
    if ($op == 'create') {
      //do somthing
    }

    if ($op == 'update') {
     //do somthing
    }
    if ($op == 'delete') {
    //do somthing
    }
  }
}

```

check this for more info https://api.drupal.org/api/drupal/modules%21node%21node.api.php/function/hook\_node\_access/7.x
> 0 votes

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


# Question
Title: How to create field template for displaying taxonomy terms as list in full content page?
We have a content type displaying taxonomy term input as one of its fields. The goal is to display the one or more terms as an unordered list. That is not an option available in the Manage Display tab, and the default display does not break the entries into separate lines:

Editing the theme's template.php file by changing

```
$output .= ($variables['element']['#label_display'] == 'inline') ?
'<ul  class="links inline">' : '<ul class="links">';

```

to

```
$output .= ($variables['element']['#label_display'] == 'inline') ?
'<ul class="links inline">' : '<ul class="list">';

```

we get the desired bulleted list:

– but that is not desired as the default in other content types.

How can this display be customized to be unique to this content type? From some reading it is understood that a custom field tpl.php could do this, but help is needed in understanding how to set that up for this unique situation. Can anyone suggest a path?

--Thanks--

# Answer
# Use template\_preprocess\_field()

You can try something like this in your template.php:

```
/**
 * Implements template_preprocess_field().
 */
function YOURTHEMENAME_preprocess_field(&$variables, $hook) {
  if ($variables['element']['#object']->type == 'YOUR_CONTENT_TYPE_NAME') {
    $output = '';

    // Render the label, if it's not hidden.
    if (!$variables['label_hidden']) {
      $output .= '<h3 class="field-label">' . $variables['label'] . ': </h3>';
    }

    // Render the items.
    $output .= ($variables['element']['#label_display'] == 'inline') ? '<ul class="links inline">' : '<ul class="list">';
    foreach ($variables['items'] as $delta => $item) {
      $output .= '<li class="taxonomy-term-reference-' . $delta . '"' . $variables['item_attributes'][$delta] . '>' . drupal_render($item) . '</li>';
    }
    $output .= '</ul>';

    // Render the top-level DIV.
    $output = '<div class="' . $variables['classes'] . (!in_array('clearfix', $variables['classes_array']) ? ' clearfix' : '') . '"' . $variables['attributes'] .'>' . $output . '</div>';

    return $output;
  }
}

```

Once implemented, try flushing you theme cache, it should work.
> 0 votes

---
Tags: theming, entities
---


title: Link format as a preview

text:
# Question
Title: Link format as a preview
I'm asking if it exists a drupal module that let you make a preview of a link like the Facebook do.

In another way a display format which it gives a preview.

# Answer
> 4 votes
There is one more similar module called External Link Preview

> This module allows users to preview all the external links that are added into any text area field by fetching their metatags - title, description and image.

# Answer
> 5 votes
You can also try the Opengraph Filter which sorts of acts like Facebook's link preview. I haven't tried on link fields but it does work on a text body. Pretty neat actually :)

# Answer
> 2 votes
WebSnapr Preview Bubble module display screenshot of target page in popup.

---
Tags: 7, entities, navigation
---


# Question
Title: How to set the Organic Group while saving a node based on the node's current language
We want to use a hook\_node\_presave to set the Organic Group (OG) field on the basic page content type based on the node's language. We have created several OGs using nodes and each one is assigned a language so there is a mapping between Language to OG based on the OG node.

So basically, when the basic pages' language is set to en, then the OG with a language of en, will be assigned to the basic page's OG field.

Current nodes:

OG1 --Title = test 1 --language = en

OG2 --Title = test 2 --language = en-gb

OG3 --Title = test 3 --language = fr

basic page1 --title = some title1 --language = en --og\_field = ??

basic page2 --title = some title2 --language = fr --og\_field = ??

---

Expected result when the hook\_node\_presave is done:

basic page1 --title = some title1 --language = en --og\_field = OG1

basic page2 --title = some title2 --language = fr --og\_field = OG3

---

here is what i have tried, but not sure why it is not working (assume organic\_group is the content type machine name)

```
function mymodule_node_presave(&$node) {

    if($node->type == 'page') {
        //get the OG node that has the same language as the current node
        $result = db_select('node', 'n')
           ->fields('n', array('nid', 'language', 'og_field'))
           ->condition('n.type', 'organic_group')
           ->condition('n.language', $node->language)
           ->execute()
           ->fetchAll();

        //store OG node's nid into og_field
        $node->og_field = $result->nid;
    }
  }

```

# Answer
Using Rules, you can add an event for when a new node is saved, add conditions for both content type and language and then use an action for assigning the OG's nid to the og\_group\_ref field.

Use set a data value if cardinality of the node is set to 1 or add to list for more than 1.

Without rules or code, I would have a new node link in each organic group and prepopulate the language and og\_group\_ref fields.
> 0 votes

---
Tags: 7, nodes, entities, hooks, organic-groups
---


# Question
Title: How to resolve the error about 'A partially-completed form was found'?
Yesterday I have updated Webform module from 7.x-4.0-beta3 to 7.x-4.13.

After doing so, I am getting this notification message, throughout the site:

> A partially-completed form was found. Please complete the remaining portions

I have also checked some threads.

When I check log entries I got this error :

> Notice: Undefined property: stdClass::$is\_draft in webform\_client\_form()

And deleting partially filled nid in webform submissions table is not working for me.

What can I do with it?

# Answer
> 1 votes
Since "*deleting partially filled nid in webform submissions table*" (as in your question) seems to not solve your issue, you may want to have a look at comment nr 2 in issue 2560907, which states:

> A webform node is being displayed on that page and there is a draft submission for the current user. You don't have to find the id -- the form will be displayed, unless theming or another module is preventing it.

---
Tags: 7, webforms, debugging
---


# Question
Title: Mix taxonomy and node title in ordering in a View
I have a View which lists books (nodes). They are sorted by alphabetical order (Title). Good. They are linked to taxonomies (categories). I could sort by taxonomy to group books of the similar theme together, and a second sort by title. Good.

Now the problem. My client want to list both taxonomies (categories) names and title books together, so we have the following beautiful omellete of data (imagine that the lists which are book titles beggining with prefix "-" are hidden after you click on the taxonomy they belong):

```
 Antologies (category)
  - Interesting antology (book) *hidden until you click Antologies*
  - More interesting antology (book) *hidden til you click Antologies*

 Book about everything the meaning of life (book) *visible*

 Cooking books (category)
   - A guide on cooking data (book) *hidden til you click Cooking books*
   - How to cook an alien (book) *hidden til you click Cooking books*
 Course of the pyramid (book) *visible*
 Decameron (book) *visible*

```

Nonetheless to say, I am completely at lost here. I have considered to use an extra field data to the content (node = book) to set an alias, which is the category. Then order by alias and to achieve the " - " indentation, use some hook code to identify the taxonomy.

# Answer
> 0 votes
I would try Views Tree.

Edited: To use Views Tree, the genres would have to be a content type and the books would the use entity reference. It will do an alphabetical list as OP asked but it's unsuitable for his requirements.

---
Tags: 7, views, taxonomy-terms
---


title: Private files not found 404 error

text:
# Question
Title: Private files not found 404 error
My installation is Drupal 7 + Nginx + Varnish cache

My private files path: sites/default/files/private/demo.img URL in browser: system/files/demo.img

When I try to open private file: http://domian.com/system/files/demo.img server throws 404 not found error. So I check all the file system config and directory permissions, everything seems to be fine.

Now I tried to debug Drupal core files, what I have understood is,

1. System.module has defined url "system/files" with callback function "file\_download" using hook\_menu()
2. function file\_download() is defined in 'includes/file.inc' core file and it is not invoked when I try to access the file: http://domian.com/system/files/demo.img

So my private file request is not handled by Drupal, which is wrong? In my local setup though, which has Apache instead of Nginx, private files are normally accessed from Drupal as is expected.

So is my Nginx conf is wrong? Pasting my nginx site configuration:

```
server {
    server_name www.demo.com;
    root /var/www/demo/; ## <-- Your only path reference.

listen 127.0.0.1:8080;

location = /check.php {
     access_log off;
     log_not_found off;
  }

location /nginx_status {
       stub_status on;
       access_log   off;
       allow 127.0.0.1;
       deny all;
}

location ~ ^/(status|ping)$ {
        include fastcgi_params;
        fastcgi_pass 127.0.0.1:9000;
        fastcgi_param SCRIPT_FILENAME $fastcgi_script_name;
        allow 127.0.0.1;
        #allow stats_collector.localdomain;
        #allow watchdog.localdomain;
        deny all;
}

# Enable compression, this will help if you have for instance advagg module
# by serving Gzip versions of the files.
#gzip_static on;

location = /favicon.ico {
        log_not_found off;
        access_log off;
}

location = /robots.txt {
        allow all;
        log_not_found off;
        access_log off;
}

# This matters if you use drush prior to 5.x
# After 5.x backups are stored outside the Drupal install.
#location = /backup {
#        deny all;
#}

# Very rarely should these ever be accessed outside of your lan
location ~* \.(txt|log)$ {
        #allow 192.168.0.0/16;
        deny all;
}

location ~ \..*/.*\.php$ {
        return 403;
}

# No no for private
location ~ ^/sites/.*/private/ {
        internal;
}

# Block access to "hidden" files and directories whose names begin with a
# period. This includes directories used by version control systems such
# as Subversion or Git to store control files.
location ~ (^|/)\. {
        return 403;
}

location / {
        # This is cool because no php is touched for static content
        try_files $uri @rewrite;

 location ~* ^(?:.+\.(?:htaccess|make|txt|engine|inc|info|install|module|profile|po|pot|sh|.*sql|test|theme|tpl(?:\.php)?|xtmpl)|code-style\.pl|/Entries.*|/Repository|/Root|/Tag|/Template)$ {
         return 404;
 }

rewrite ^/(.*)\.css /$1\.css\.gz;
rewrite ^/(.*)\.js /$1\.js\.gz;

}

location @rewrite {
        # You have 2 options here
        # For D7 and above:
        # Clean URLs are handled in drupal_environment_initialize().
        rewrite ^ /index.php;
        # For Drupal 6 and bwlow:
        # Some modules enforce no slash (/) at the end of the URL
        # Else this rewrite block wouldn't be needed (GlobalRedirect)
        #rewrite ^/(.*)$ /index.php?q=$1;
}

location ~ \.php$ {
        fastcgi_split_path_info ^(.+\.php)(/.+)$;
        #NOTE: You should have "cgi.fix_pathinfo = 0;" in php.ini
        include fastcgi_params;
        fastcgi_read_timeout 120;
        fastcgi_param SCRIPT_FILENAME $request_filename;
        fastcgi_intercept_errors on;
        fastcgi_pass phpbackend;
}

# Fighting with Styles? This little gem is amazing.
# This is for D6
#location ~ ^/sites/.*/files/imagecache/ {
# This is for D7 and D8
location ~ ^/sites/.*/files/styles/ {
        try_files $uri @rewrite;
}

location ~* \.(js|css|png|jpg|jpeg|gif|ico)$ {
        expires max;
        log_not_found off;
}

```

}

**Latest development**: The private file which I am trying to view is webform submission and While I try to view file, the function webform\_submission\_access() see logged in user as anonymous.

# Answer
Ok, I got this issue fixed.

The Vanish installed on server was causing the issue more specifically the following code.

```
# Always cache the following file types for all users.

    if (req.url ~ "(?i)\.(pdf|woff|eot|svg|ttf|png|gif|jpeg|ico|swf|css|js|html|htm)(\?[a-z0-9]+)?$") {
      unset req.http.Cookie;
      # Stop processing further for those file types. This way, we ensure to have
      # X-Varnish-Cache HIT for those requests.
      return (lookup);
    }

```

You can either remove the file extensions from above code or comment the entire block. This should solve the issue.
> 2 votes

# Answer
The accepted answer will solve the issue but will also hit the site's performance. Instead, consider not caching these specific requests.

For example, in the beginning of Varnish `vcl_recv`:

```
  # Do not cache requests to private files.
  if (req.url ~ "^/system/files/.*$") {
    return (pass);
  }

```

Yo may combine this with other request paths:

```
  # Do not cache these paths.
  if (req.url ~ "^/status\.php$" ||
      req.url ~ "^/update\.php$" ||
      req.url ~ "^/admin$" ||
      req.url ~ "^/admin/.*$" ||
      req.url ~ "^/flag/.*$" ||
      req.url ~ "^.*/ajax/.*$" ||
      req.url ~ "^.*/ahah/.*$" ||
      req.url ~ "^/system/files/.*$") {
    return (pass);
  }

```

Reference: https://www.drupal.org/node/2375961
> 2 votes

# Answer
As well as this, you can sometimes have some issues serving images from the private folder if you're following Perusio's config and your private file folder is within the folder `sites/default/files`.

The thing to do is alter in your nginx config from

`~*\.(jpg|jpeg|png|gif|css|js|ico)$ to /sites/default/files/~*\.(jpg|jpeg|png|gif|css|js|ico)$`
> 0 votes

---
Tags: 7, files, proxies
---


# Question
Title: Drupal 8:How to add tags for custom content types
Newbie here!

I go to Structure \> Content types \> Add content type and create a new content type.

But how can I add tags to my new content type, just like when you go to Content \> Add content \> Article, you get the option to enter a title, tags and body.

How can I add the capability to add tags to my new content type?

Thanks

# Answer
> 4 votes
Go to `/admin/structure/types` and press on `manage fields` of your custom content type

Press on the `+Add field` button, and use **Re-use an exiting field** (the drop down on the right) to select the existing `Entity Referenc: field_tags`

Then go to **manage form display**, for tags change the widget to `autocomplete (Tags style)`

**PS**: I suggest you install admin toolbar if you haven't already.

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


title: How to remove creation of file paths?

text:
# Question
Title: How to remove creation of file paths?
I have created a Drupal project, on that project I have many files uploaded. But when I crawl the project through crawlers I am getting files as file url like the following.

`http://project.com/files/file2png`
This means I have a file in my files directory as `file2.png` `http://project.com/files/file1png`
This means I have a file in my files directory as `file1.png`

I have a **File Entity** module. Does it create url in this format? If yes, how to avoid this?

And I don't know which module makes this. I want to avoid this. Is there any way to remove creation of file paths for my files?

# Answer
> 2 votes
According to your comment:

> I don't want to create pages for the Files

The url `file/%file` is registered as menu item in `file_entity_menu()`. You can disable the page by implementing `hook_menu_alter()` in custom module.

**Example**

```
/**
 * Implements hook_menu_alter().
 */
function mymodule_menu_alter(&$items) {
  // disable the file entity page
  $items['file/%file']['access callback'] = FALSE;
}

```

Another question you mentioned.

> Can I redirect to home page for file url's?

You can override the page callback and add the redirection in it.

**Example**

```
/**
 * Implements hook_menu_alter().
 */
function mymodule_menu_alter(&$items) {
  // disable the file entity page
  $items['file/%file']['page callback'] = 'mymodule_file_callback';
}

function mymodule_file_callback($file) {
  drupal_goto('<front>');
}

```

---
Tags: files
---


# Question
Title: Media Module Bulk Upload for Image Field
Using Media 7.x-2.x-version I am trying to use the integrated Bulk Upload Module. I have activated Media Bulk Upload sub module as part of Media. Now if I use a image field with media selector I can still upload only one image at a time. Only if I go to "file/add" I have the multiple file upload option. Is this by design or is there a possibilty to use multiple file upload directly when adding content via Image field.

# Answer
I'm also faced the same issue. But after applying this patch (check your media module version) it works great.
> 1 votes

# Answer
Go to Content types -\> Manage fields and edit the image field. select "Number of values" as "unlimited" and save. This allows you to add multiple files.
> 0 votes

# Answer
I could not find a solution to conveniently bulk upload a number of images directly in a node with the Media Bulk Upload feature. Media Bulk Upload allows me to bulk upload images to the files library (add/files). But if I want to include them in a multiple value image field in a node, I have to add each image separately from the Media library.

So I ended up using Block Upload module. I create the node first without images and then I bulk upload as many images as I like in one step to the image field with the Block Upload module. That's really a great time saver.

Actually there is a issue with the bulk upload form of the module, but the issue can be fixed easily, look here
> 0 votes

---
Tags: 7, media
---


# Question
Title: How can I display content from one node to another?
With some design in mind, I have to display the some content of one node to another node. For ease of understanding, I have just put some drawing.

Suppose, I have,

`Content type`: **Article** which has -\> **Node/5** which has -\> **field\_123** (Text type)

and I want to show that field content to another node,

`Content type`: **Basic Page** which has -\> **Node/6** which will be -\> **copy\_field\_123** (Text type)

Hence, in short I want to display content of one node to another node. *I do not want entire node content to be transferred to another node as it is, but a specific fields which I choose.*

>

Any suggestions, please?

# Answer
> 3 votes
I think after some research I found the solution. Again Thanks to @Niall Murphy and @drupality For their input.

I think for my purpose Field Reference will be the right module. As it not only allows to choose the particular node, but which field you want to choose from that particulate node.

Although any suggestion is appreciated.

---
Tags: 7, entities
---


# Question
Title: Skip a step on a multipage form based on field input
I'm using field group module to create a multipage content creation node. I have one field that if "checked" should make the next button skip to final page of form.

For example a 3-page form, if on the first page the user checks "no" on a field, they will skip the second page when they click next and go to the third and final page.

# Answer
> 0 votes
You can give a try on this module Conditional Fields.

> Conditional Fields allows you to manage sets of dependencies between fields. When a field is “dependent”, it will only be available for editing and displayed if the state of the “dependee” field matches the right condition. When editing a node (or any other entity type that supports fields, like users and categories), the dependent fields are dynamically modified with the States API. A simple use case would be defining a custom “Article teaser" field that is shown only if a "Has teaser" checkbox is checked, but much more complex options are available.

---
Tags: entities
---


# Question
Title: "cannot use a scalar value as an array" warning for adding #prefix and #suffix in template.php via hook-form-alter – Drupal 7
I have the following code in my Drupal’s template.php file. What it does is to embed every element of my site's contact form (created with the Webform module) in a li element (the form itself is already embedded in a ul element).

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

  if ($form_id == 'webform_client_form_MYFORMID') {
    foreach($form['submitted'] as &$field) {
      $field['#prefix'] = '<li>';
      $field['#suffix'] = '</li>';
    }
  }

```

This works, but I get '*Warning: Cannot use a scalar value as an array in MYTHEME\_form\_alter()*' when accessing a page that contains such a form. The warning shows twice, once for each of the two lines where I add the prefix and suffix, respectively.

I have searched far and wide, but I do not know what to do. To the best of my knowledge, this is how Drupal wants me to handle this. And like I said, it does work, but it would be nice to get rid of the warnings and do everything 100 % correct.

(I'm using Drupal 7 and PHP 5.6.24.)

Does anybody know a better / the correct way to do this? Thank you.

# Answer
Not everything in a render array is an element to be rendered. The field contains other data in the form of properties, and some of those values will be scalar types, which causes the errors you see.

To fix, use `element_children`:

```
foreach (element_children($form['submitted']) as $key) {
  $form['submitted'][$key]['#prefix'] = '<li>';
  $form['submitted'][$key]['#suffix'] = '</li>';
}

```
> 1 votes

# Answer
> Warning: Cannot use a scalar value as an array in MYTHEME\_form\_alter()

It is a common PHP error which means you are treating a scalar value (eg: int, string) as an array.

You can fix it by checking if it is an array before using it.

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

  if ($form_id == 'webform_client_form_MYFORMID') {
    foreach($form['submitted'] as &$field) {
      if (is_array($field)) {
        $field['#prefix'] = '<li>';
        $field['#suffix'] = '</li>';
      }
    }
  }

```

As mentioned by @Clive

Since you are adding `#prefix` and `#suffix`, you are obviously trying to change for the render element. So it would be better to limit the change occurred on render element only.

`element_children` is the API provided by Drupal for that purpose.

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

  if ($form_id == 'webform_client_form_MYFORMID') {
    foreach($element_children($form['submitted']) as $key) {
      $field = &$form['submitted'][$key];
      $field['#prefix'] = '<li>';
      $field['#suffix'] = '</li>';
    }
  }

```
> 0 votes

# Answer
if you change it to

```
 foreach($form['submitted'] as $key => $field) {
  $form['submitted'][$key]['#prefix'] = '<li>';
  $form['submitted'][$key]['#suffix'] = '</li>';
}

```

i think that will solve your problem
> 0 votes

---
Tags: 7, theming, webforms, forms
---


# Question
Title: How to make Entity View show Entity's custom dynamic label as page title (D8)
My custom content Entity overrides label() to provide a dynamically generated, human-readable label like:

```
public function label() {
  return $this->displayName();
}

```

Unfortunately, that label does not get used by the EntityViewController. In my module.routing.yml file I have:

```
entity.veranstaltung.canonical:
  path: '/admin/veranstaltung/{veranstaltung}'
  defaults:
    _entity_view: 'veranstaltung'
  requirements:
    _entity_access: 'veranstaltung.view'

```

I can now view my "veranstaltung" entities, but the page title is blank and the breadcrumb just shows the entity's id instead of its label.

Looking in EntityViewController::buildTitle() I can now see why this is the case:

```
$label_field = $entity->getEntityType()->getKey('label');
if (isset($page[$label_field])) {
  $page['#title'] = $this->renderer->render($page[$label_field]);
}

```

I don't have a label key, as I want the labels to be dynamically generated.

Any suggestions how to best deal with this problem?

# Answer
> 4 votes
Similar to the `NodeViewController`, you can write you own `VeranstaltungViewController` extending `EntityViewController`, and implement a title function. In your route can then set `_title_callback` to use this function (see `NodeRouteProvider` as reference).

---
Tags: 8, entities
---


# Question
Title: How to change the functionality of FILE_EXISTS_RENAME?
I am using `files_save_upload` function to save the file. Here, I can use `FILE_EXISTS_RENAME` this to rename the current file name if already this name existed. By default it rename by appending \_indexes(0,1,2..). But I want to append some other things not the default one. So how can I achieve this? Thanks for any suggestions.

# Answer
There's no way to do it without changing the core function `file_create_filename`. That could obviously have unwanted side-effects for other parts of the system, and make updating difficult.

If you have to do it differently for whatever reason, you should write your own function and use that instead. Once you see how much code you need to copy and maintain from `file_save_upload` and `file_create_filename`, though, you might think twice about whether it's worth it.
> 1 votes

---
Tags: 7, files
---


title: Ajax call undefined validate of form

text:
# Question
Title: Ajax call undefined validate of form
I have a form wich allow to create content, it's build like :

1. get the owner part in a form
    * if the user isn't connected show him a login form and registration form
    * if the user is connected show him the user profile form to edit his informations
2. get the content form
    * include 1 by drupal get form
    * add an ajax system to add/remove lines of content creation

But when i clic on add or remove button (before i commented the user form and it works perfectly) i get this ajax error : `Error : Call to undefined function user_profile_form_validate() dans form_execute_handlers() (ligne 1519 dans /Applications/MAMP/htdocs/fritr/includes/form.inc).`

I've seen this post wich may contain the solution : https://www.drupal.org/node/1229882 Maybe it's because i don't use a form\_load\_include() but i don't know what include...

Here is my code :

/\*

THE USER FORM

\*/

```
function fritr_register_friterie_owner_form($form, &$form_state) {
    // GET THE USER ENTITY IN FORM
    global $user;
    global $language;
    if(user_is_logged_in())
        $user = user_load($user->uid);
    form_load_include($form_state, 'inc', 'user', 'user.pages');

    // MAIN
    $form = array(
        '#type' => 'fieldset',
        '#tree' => TRUE,
        '#collapsible' => FALSE,
        '#collapsed' => FALSE,
        '#attributes' => array(
            'class' => array('clean-panel'),
        ),
    );

    // SHOW LOGIN FORM IF USER ISN'T CONNECTED
    $form['connexion'] = array(
        '#type' => 'fieldset',
        '#title' => t('Se connecter'),
        '#tree' => TRUE,
        '#collapsible' => FALSE,
        '#collapsed' => FALSE,
        '#weight' => 1,
        '#attributes' => array(
            'class' => array('clean-panel titled'),
        ),
    );

    // USER FORM
    $form['user'] = array(
        '#type' => 'fieldset',
        '#title' => t('Editer ses informations'),
        '#tree' => TRUE,
        '#collapsible' => FALSE,
        '#collapsed' => FALSE,
        '#weight' => 2,
        '#attributes' => array(
            'class' => array('clean-panel titled'),
        ),
    );

    if (user_is_logged_in()) {
        unset($form['connexion']);
        $form['user']['#title'] = t('Editer ses informations');
        $form['user']['content'] = drupal_get_form('user_profile_form', $user);
        $form['user']['content']['#validate'] = array();
    } else {
        $form['connexion']['content'] = drupal_get_form('user_login');
        $form['user']['#title'] = t('Créer un compte');
        $form['user']['content'] = drupal_get_form('user_register_form');
    }

    return $form;
}

function fritr_register_friterie_connexion_form_submit($form, &$form_state) {
    $form_state['redirect'] = current_path();
}

```

/\*

THE FRITERIE FORM WICH CONTAIN USER FORM

\*/

```
/*
 * Implements hook_form().
 */
function fritr_register_friterie_form($form, &$form_state) {
    module_load_include('inc', 'fritr_register_friterie');
    form_load_include($form_state, 'inc', 'user', 'user.pages');

    // USER REGISTER FORM
    $form['owner'] = drupal_get_form('fritr_register_friterie_owner_form');
    $form['owner']['#weight'] = 2;

    $form['friteries'] = array(
        '#type' => 'fieldset',
        '#title' => t('Créer des friteries'),
        '#tree' => TRUE,
        '#collapsible' => FALSE,
        '#collapsed' => FALSE,
        '#weight' => 3,
        '#attributes' => array(
            'class' => array('clean-panel titled'),
        ),
    );
    $form['friteries']['content'] = array(
        '#type' => 'container',
        '#weight' => 80,
        '#tree' => TRUE,
        '#prefix' => '<div id="wrapper-friterie">',
        '#suffix' => '</div>',
    );

    $form_state['friterie_deltas'] = isset($form_state['friterie_deltas']) ? $form_state['friterie_deltas'] : range(0, 0);
    $field_count = $form_state['friterie_deltas'];

    foreach ($field_count as $delta) {
        $form['friteries']['content'][$delta] = array(
            '#type' => 'fieldset',
            '#tree' => TRUE,
            '#collapsible' => FALSE,
            '#collapsed' => FALSE,
            '#weight' => 1,
            '#attributes' => array(
                'class' => array('clean-panel'),
            ),
        );

        // FRITERIE FORM
        $form['friteries']['content'][$delta]['remove_friterie'] = array(
            '#type' => 'submit',
            '#value' => t('-'),
            '#submit' => ['fritr_register_friterie_remove'],
            '#limit_validation_errors' => array(),
            '#weight' => 1,
            '#ajax' => array(
                'callback' => 'fritr_register_friterie_remove_callback',
                'wrapper' => 'wrapper-friterie',
            ),
            '#attributes' => array(
                'class' => ['button-small'],
            ),
            '#name' => 'remove_name_' . $delta,
        );
        $form['friteries']['content'][$delta]['friterie_fields'] = array(
            '#type' => 'fieldset',
            '#title' => t('Informations friterie (cliquez pour basculer l\'affichage)'),
            '#tree' => TRUE,
            '#collapsible' => TRUE,
            '#collapsed' => FALSE,
            '#weight' => 2,
            '#attributes' => array(
                'class' => array('clean-panel titled underline collapsible'),
            ),
        );

        if (!isset($form['friteries']['content'][$delta]['#node'])) {
            global $language;
            $form['friteries']['content'][$delta]['#node'] = entity_create('node', array('type' => 'friterie', 'language' => $language->language));
        }
        field_attach_form('node', $form['friteries']['content'][$delta]['#node'], $form['friteries']['content'][$delta]['friterie_fields'], $form_state);
    }

    $form['friteries']['content']['add_friterie'] = array(
        '#type' => 'submit',
        '#value' => t('Ajouter une friterie'),
        '#submit' => ['fritr_register_friterie_add'],
        '#limit_validation_errors' => array(),
        '#ajax' => array(
            'callback' => 'fritr_register_friterie_add_callback',
            'wrapper' => 'wrapper-friterie',
        ),
        '#weight' => 100,
    );

    $form['#submit'][] = 'fritr_register_friterie_form_submit';
    $form['submit'] = array(
        '#type' => 'submit',
        '#value' => t('Enregistrer la friterie'),
        '#weight' => 100,
    );

    dsm($form);
    dsm($form_state);

    return $form;
}

```

/\*

THE AJAX AND SUBMIT CALLBACK OF BUTTONS WICH ADD OR REMOVE A FRITERIE NODE FORM CREATION

\*/

```
function fritr_register_friterie_remove($form, &$form_state) {
    $delta_remove = $form_state['triggering_element']['#parents'][1];
    $k = array_search($delta_remove, $form_state['friterie_deltas']);
    unset($form_state['friterie_deltas'][$k]);

    $form_state['rebuild'] = TRUE;
    drupal_get_messages();
}

function fritr_register_friterie_remove_callback($form, &$form_state) {
    return $form['friteries']['content'];
}

function fritr_register_friterie_add($form, &$form_state) {
    $form_state['friterie_deltas'][] = count($form_state['friterie_deltas']) > 0 ? max($form_state['friterie_deltas']) + 1 : 0;

    $form_state['rebuild'] = TRUE;
    drupal_get_messages();
}

function fritr_register_friterie_add_callback($form, $form_state) {
    return $form['friteries']['content'];
}

```

# Answer
> 1 votes
You need to use `form_load_include` instead of `module_load_include` in forms:

> Use this function instead of module\_load\_include() from inside a form constructor or any form processing logic as it ensures that the include file is loaded whenever the form is processed. In contrast to using module\_load\_include() directly, form\_load\_include() makes sure the include file is correctly loaded also if the form is cached.

e.g.

```
form_load_include($form_state, 'inc', 'user', 'user.pages');

```

# Answer
> 0 votes
Please include the required handler with `form_load_include`:

```
form_load_include($form_state, 'inc', 'user', 'user.pages');

```

You may have below question.

> **How to find the correct file to include?**

You can use the function name as key word (e.g. `function user_profile_form_validate`) and search in your Drupal project, then you can find the file contains its definition. It is easy be done in Sublime or other editors/IDEs.

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


# Question
Title: How can I theme a form element with hook_preprocess_form_element()?
I have an exposed form in a D8 view which includes several fields, output through form-element.html.twig (amongst others). I added a function:

```
function MYTHEME_preprocess_form_element(&$variables) {
...
}

```

This contains an 'element' key and I could add a class in there, BUT I see no way of identifying which form this is part of. The 'element' has a child '#parents' but this is simply the name of the field.

The whole point of this is to add some Bootstrap responsive classes to these different form items for layout. I tried `template_preprocess_form` and while I see the fields listed as elements, I don't see a way to add classes to the form element label.

What is best practice for theming D8 exposed forms?

Update: I used XDebug with PhpStorm to debug both `MYTHEME_preprocess_form_element` and `MYTHEME_preprocess_form` and explored the entire tree of `$variables` but could see nothing hinting at parent form ID or similar.

# Answer
> 2 votes
As @4k4 said, if all you want is to add some classes, then use `hook_form_alter()` or `hook_form_FORM_ID_alter()`. `$form['your_element']['#attributes']['class'][] = 'your-class` is all you need.

I'm pretty sure that single form elements don't have the form ID stored somewhere.

# Answer
> 0 votes
In order to set a class to the label, you can write your own `form-element-label.html.twig`.

---
Tags: views, theming, 8
---


# Question
Title: How do I render user Login block in main menu?
I wrote the following code but I see only 'array' word.

```
function mytheme_menu_tree__primary(&$variables) {
   return '<ul class="menu nav navbar-nav">' . $variables['tree'] . module_invoke('user', 'block_view', 'login')['content']
    . '</ul>';

}

```

# Answer
> 0 votes
Block content can either be a string or a render array. As such you need to run it through `render`:

```
$block_content = module_invoke('user', 'block_view', 'login')['content'];
return '<ul class="menu nav navbar-nav">' . $variables['tree'] . render($block_content) . '</ul>';

```

It's worth bearing in mind that the user login form isn't wrapped in `<li>` tags, so unless you're altering the markup for that form elsewhere, your code will produce invalid markup.

---
Tags: 7, theming
---


# Question
Title: How to check condition and print a value using views-view-field--viewname.tpl.php?
I'm having a view and I've created a template file for the row style output. I'm able to access the fields using the below code:

```
$fields: An array of $field objects. Each one contains:
$field->content: The output of the field.
$field->raw: The raw data for the field, if it exists. This is NOT output safe.

```

I'm getting output for the below code:

```
<?php print $fields['field_some_field_name']->content; ?>

```

But when I'm trying to print the fields nothing is getting returned:

```
<?php print_r($fields); ?>

```

I'm also unable to check the condition for the fields:

```
<?php if($fields['field_some_field_name']->content == 'Test') { } ?>

```

# Answer
> 1 votes
> I'm also unable to check the condition for the fields:
>
> ```
> <?php if($fields['field_some_field_name']->content == 'Test') { } ?>
>
> ```

That is probably because in actuality:

`$fields['field_some_field_name']->content` = `<div>Test</div>`

Therefore, `<div>Test</div>` is not equal to `Test`

So what you could do is use `raw` instead, as `raw` has no html/markup around the value.

```
<?php if($fields['field_some_field_name']->raw == 'Test') { } ?>

```

else, you could still use `content` with the PHP striptags() function

```
<?php if(striptags($fields['field_some_field_name']->content) == 'Test') { } ?>

```

Or else, you could still use your original `<?php print $fields['field_some_field_name']->content; ?>` but as long as you strip all the markup added by views as shown in my answer to "Is there a more performant alternative than overriding template files?".

---
Tags: views, theming
---


# Question
Title: how to stream video on-site generated from link preview in a text area?
I am using opengraph filter module to generate preview from url. It is working perfectly. Now if a user has shared a video or image through url on the site and the preview is generated, when someone clicks on that preview, it takes the user to the link page (external website). What I want is, it should open on my site i.e embed on my site so that user can see the picture or video, generated from link preview, on my website. Currently, there is a video filter module which converts links to embeded videos, but it requires users to use this format \[video:url\] when sharing videos, but this format \[video:url\] for sharing a video link is not desirable, so leave it. I just mentioned it for reference/information.

# Answer
> 1 votes
Opengraph Filter module provides this: `template_preprocess_opengraph_filter()`

You can implements it in your custom module or theme for reading the video url. Then you can use the video url to output the player.

```
function mytheme_preprocess_opengraph_filter(&$variables) {
  $key = 'video';
  if (isset($variables['metatags']['og'][$key])) {
    $video_url = $variables['metatags']['og'][$key];

    // more code to operate $video_url.
    // dpm($video_url);
  }
}

```

You can start with it. It would be a long story if you want to load the video after clicking the thumbnails. I would suggest you to split the question into multiple specific questions for different step. It is more easy for other to provide answer and also for those who is looking for answer. Thanks.

---
Tags: 7, media
---


# Question
Title: How to create an EMPTY anchor-only link with l()?
I'm trying to use `l()` to get something like `<a href='#' ...>`, for ajax-calling purposes. https://stackoverflow.com/questions/1698453/drupal-creating-anchor-only-link-with-l is very close to the right thing -- use an option in `l()` like `'fragment' => 'foo'` to produce a link like `<a href='#foo'...>` -- but I'm trying to get a clean '#'. Is there any way to do this, or should I just put something in as part of the fragment and not worry about it?

# Answer
> 12 votes
If you could not use clean "#" with fragment, I would suggest you to use `<a href="javascript:">link</a>`.
When adding "javascript:" or "javascript:void(0)" to `href` attribute, the `<a>` tag will do nothing. Then you can bind "onclick" to the link for your ajax purpose.
You can implement this using `l()` function as below:

```
     l('link', 'javascript:',  array('external' => TRUE));

```

# Answer
> 16 votes
PHP typecasting pop quiz time! (Full disclosure: I didn't win in our office).

As pointed out already, this is the code in `l()` that we're concerned with:

```
if (isset($options['fragment']) && $options['fragment'] !== '') {
  $options['fragment'] = '#' . $options['fragment'];
}

```

So here's the question: What value casts to an empty string but passes the following?

```
(isset($var) && $var !== '')

```

The answer is: `FALSE`!

So, we could try this:

```
l(t('My link'), NULL, array('fragment' => FALSE));

```

Which gives us:

```
<a href="/#">My link</a>

```

Thankfully we can strip that leading slash by passing along `external => TRUE`:

```
l(t('My link'), NULL, array('external' => TRUE, 'fragment' => FALSE));

```

Which gives us:

```
<a href="#">My link</a>

```

Boom. The things we do to avoid concatenating html strings manually, eh?

**Postscript:**

I'm not sure I'd actually recommend printing a link like this from php under normal circumstances. Without your javascript, all that link is going to do it jump your user to the top of the page (which, to my slight surprise, is specced behaviour). It should probably point somewhere that works without javascript.

If the link *really* only makes sense with javascript around (like the controls for a js-only slideshow or something), I think it's better to add the link to the page with javascript. Alternatively, if you really want to put it in your source, make sure it's `display:none`'d by default. Drupal has the `.js` class on the html for then showing it when javascript is around.

# Answer
> 7 votes
Unfortunately the `url()` function (which `l()` calls internally) pretty much nukes any chance of an empty fragment with the following lines:

```
if (isset($options['fragment']) && $options['fragment'] !== '') {
  $options['fragment'] = '#' . $options['fragment'];
}

```

It checks to make sure the fragment isn't an empty string, which is what you'd need to pass to get the clean `#`. I think the easiest solution would be to pick the id of a suitable element somewhere in the page and use that for the fragment instead (or `javascript:void` as Sithu has mentioned).

However...the most accessible way (and subsequently, in many countries, legal way; think section 508 in the States, the DDA in the UK, etc.) would be to provide the content that's being loaded/adjusted by your link on a separate page, and use the URL for that page as the link's href instead. You would then use javascript to stop the event on the link from actually redirecting the page for those browsers which have it enabled.

That way you have fallback content for users without javascript, you stay legal, and you keep everyone and their dog happy :)

# Answer
> 4 votes
You could't use clean `#`.

But it's possible to add `space symbol` after `#`:

```
  l('Link title', '# ', array('external' => TRUE));

```

# Answer
> 2 votes
I just had the same issue, but none of the solutions were satisfying, so i came up with my own one:

```
l('link', '', array('fragment' => ' ', 'html' => TRUE, 'external' => TRUE));

```

This produces a clean `#`

```
<a href="#">link</a>

```

# Answer
> 2 votes
I would use render type *html\_tag* instead because I believe render *link* receive special attention from Drupal. The downside being there is no short-cut function for it, so we'll have to use a render array:

```
array (
  '#type' => 'html_tag',
  '#tag' => 'a',
  '#attributes' => array (
    'href' => '#',
  ),
);

```

# Answer
> 0 votes
This is basically the same answer I posted here... Setting `fragment` to a single space will convert to a `#`, and `$current_path` is included because otherwise the link will just be set to `www.example.com/#` instead of `www.example.com/current-page#`:

```
$current_path = check_url(drupal_get_path_alias($_GET['q']));
$link = l('link', $current_path, array('fragment' => ' '));

```

---
Tags: navigation
---