Combine hook_search_execute I have hook for user_search_execute and node_search_execute for both user and nodes but
 i want to merge both into mymoduel_search_execute but only node_search_execute uses index not user_search_execute like below :-

    /* node search execute */

    function node_search_execute($keys = NULL, $conditions = NULL) {
        // Build matching conditions
        $query = db_select('search_index', 'i', array('target' => 'slave'))->extend('SearchQuery')->extend('PagerDefault');
        $query->join('node', 'n', 'n.nid = i.sid');
        $query
            ->condition('n.status', 1)
            ->addTag('node_access')
            ->searchExpression($keys, 'node');

        // Insert special keywords.
        $query->setOption('type', 'n.type');
        $query->setOption('language', 'n.language');
        if ($query->setOption('term', 'ti.tid')) {
            $query->join('taxonomy_index', 'ti', 'n.nid = ti.nid');
        }
        // Only continue if the first pass query matches.
        if (!$query->executeFirstPass()) {
            return array();
        }

        // Add the ranking expressions.
        _node_rankings($query);

        // Load results.
        $find = $query
            ->limit(10)
            ->execute();
        $results = array();
        foreach ($find as $item) {
            // Render the node.
            $node = node_load($item->sid);
            $build = node_view($node, 'search_result');
            unset($build['#theme']);
            $node->rendered = drupal_render($build);

            // Fetch comments for snippet.
            $node->rendered .= ' ' . module_invoke('comment', 'node_update_index', $node);

            $extra = module_invoke_all('node_search_result', $node);

            $uri = entity_uri('node', $node);
            $results[] = array(
                'link' => url($uri['path'], array_merge($uri['options'], array('absolute' => TRUE))),
                'type' => check_plain(node_type_get_name($node)),
                'title' => $node->title,
                'user' => theme('username', array('account' => $node)),
                'date' => $node->changed,
                'node' => $node,
                'extra' => $extra,
                'score' => $item->calculated_score,
                'snippet' => search_excerpt($keys, $node->rendered),
                'language' => entity_language('node', $node),
            );
        }
        return $results;
    }

i want to combine both queries into one even search url anything else.

please help..

Check our the module Search combine, it gives you exactly that.

Here's how I have the admin search configured:

Also related: How to have a combined search view that shows both users and content on search terms?


CSS changes to .menu .leaf affect main-menu AND admin shortcut menu in Drupal 7 I'm using drupal 7 and have created the subtheme of omega using drush omega-wizard. I'm using compass to watch for changes to the scss files and it's +/- behaving as I'd expect. My problem occurs when I try to style the main-menu with something like:

.menu .leaf {
    width: 30px;
}

The restyling works but it also affects the admin's shortcut menu which uses .menu .leaf. Is there a setting in the config that I've missed, should I be targeting the menu in another way. How do I not affect the shortcut menu when styling the main-menu?

Any help would be greatly appreciated.
Thanks, Steve

You need to make your CSS more specific so that it only applies to menu items on your main menu. You can do this by prefixing the CSS rule with the class of its container e.g.

.block--system-main-menu .menu .leaf. {
    width: 30px;
}


Within a view listing, how can I denote whether a node's date is upcoming, current or past? I am working on an art gallery site in which we have two views that are filtered based on the date range of an exhibition. One view filters current exhibits (now >= start date && now <= end date) and another that filters upcoming exhibitions (now < start date).

We would like to combine these into a single page view. This is simple enough to do with this date filter: now <= end date. However, I would still like to denote which events are upcoming (be it a CSS class or by rendering the date field as "Opens on Dec. 12th").

Is there a way to render/rewrite the date field differently based on the field's value relative to today's date?

For example, if today's date is Nov. 1, 2015, I would like these two nodes:

Exhibit #1 (Oct. 1, 2015 - Dec. 1, 2015)
Exhibit #2 (Jan. 1, 2016 - Feb. 1, 2016)

To render like this:

Exhibit #1, Ends Dec. 1 2015
Exhibit #2, Opens Jan 1, 2016

A possible solution is to use the Views feature "rewrite result" (as explained also in Rewriting view fields), combined with the Views PHP module.

If you're not experienced in PHP, you may want to experiment with only the "rewrite result" feature, which may help to come up with an acceptable compromise for what you're looking for.;

Note: The Views PHP module only has an alfa version as of today, but it's used in about 70K sites anyway ... That many sites can't be wrong, right?


Programatically load title of a views page by its machine name I would like to use the current title of a very specific views page in another template. Instead of just manually copying it and in order to stay flexible and always up to date, I would like to programatically load and insert it.

If my views page has machine name views_page, how do I programatically load its current title into a string?

Any of these should work:

Load the View and get the display title:

$view = views_get_view('views_page');
print $view->display['page_1']->display_options['title'];

Note: Change 'page_1' to the name of your display.

You can also get the page title from the path:

$item = menu_get_item(drupal_get_normal_path('path/to/page'));
print $item['title'];


How to create a rule to perform a redirect if user is already logged in and visits the homepage? I have a Drupal 7 installation. In my homepage I have only two forms (login and register) so I need when someone leaves the site and the user is logged in, when he visits it again that he redirect to another page (similar to Facebook functionality).

Currently the user is redirected to user profile page.

I tried to use Rules and I put in Rules Event 'Drupal is initializing', in Rules Condition path to 'check=[site:url]' to be redirected but with no effect.

Any ideas?

Not sure if it will be your only problem to be fixed, but you seem to be using the wrong token in your condition path. Try again using either of these tokens:

[site:current-page:path].
[site:current-page:url].

Below is an example of a rule (in Rules Export format) which illustrates how to use either of these tokens:

{ "rules_redirect_logged_in_user" : {
    "LABEL" : "Redirect logged in user",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "init" : [] },
    "IF" : [
      { "NOT user_has_role" : {
          "account" : [ "site:current-user" ],
          "roles" : { "value" : { "1" : "1" } }
        }
      },
      { "OR" : [
          { "data_is" : { "data" : [ "site:current-page:path" ], "value" : "node\/123" } },
          { "text_matches" : { "text" : [ "site:current-page:url" ], "match" : "something" } }
        ]
      }
    ],
    "DO" : [
      { "drupal_message" : { "message" : "Using the path [site:current-page:path] (or url [site:current-page:url]) makes no sense for authenticated users, which is why you are redirected ..." } },
      { "redirect" : { "url" : "somewhere_else" } }
    ]
  }
}

Some more details about the above Rule:

Rules Event: Drupal is initializing.
Rules Conditions:

the user should NOT be anonymous, AND
either (or both) of these conditions must be true:
the path is node/123 (assuming your homepage is a node with nid=8, adapt to fit your case, or omit this condition if the next condition is sufficient for your case).
the url contains the text something (adapt to fit your case, or omit this condition if the previous condition is sufficient for your case). Instead of using Comparison operation contains you could also use starts with,  ends with or even a regular expression.

Rules Actions:

Show an appropriate message (adapt to fit your needs, or just omit it if you don't want such message at all, I like it for debugging purposes ...).
Perform a redirect to somewhere_else (adapt to fit your needs).

If you have the Rules UI enabled, you should be able to import the above rule in your own site. Then adapt it to fits your needs and you should be good to go.

Easy, no?


Replace integer field value with stars in twig template I have a Drupal 8 site with a node type exposing a "difficulty level" field which is an integer choosen from a list (1 to 5).
Current onsite display is : "difficulty: 3". I would like to replace the value "3" by three black stars and two white ones to picture "3/5" (done via CSS background images).

In field--field-difficulty.html.twig I have replaced item.content by:

{% for i in range(1, 5) %}
  {% if (loop.index <= item.content) %}
    *
  {% else %}

  {% endif %}
{% endfor %}

But this keep giving me five * displayed, just like if the {% if %} statement was always true.
Can someone give me a hint on this please ?

For the field template there are two approaches to get the integer number from a field:

Node object

{% set difficulty = element['#object'].field_difficulty.value %}
{% for i in range(1, 5) %}
  {% if i <= difficulty %}

Find the rendered number

You can try to find the number in #markup:

{% if loop.index <= item.content['#markup'] %}

The node object is the better approach, because the way how the number is rendered can change when updating the code or changing the configuration.


Scheduled rules execute a hour after they are supposed to I have created a scheduled rule that sends a email based on a date field in nodes of a certain content type. The rule executes as scheduled and the email is sent but for some reason it only fires exactly a hour after its supposed to.

E.g on the admin/config/workflow/rules/schedule page the item is scheduled to execute at Thu, 2017-08-03 15:30 but I only receive the email at 16:30.

I could fix this by adding a offset to the trigger time but I would rather want to understand why this is happening and fix the problem accordingly.

Cause 1:

After a rule is scheduled (using the Rules Scheduler submodule), it will only actually execute next time cron runs. Example:

schedule a rule to execute at timestamp X.
if the next time that cron runs is at Y mins after timestamp X, then the Rules execution will only happen then (= at Y mins after timestamp X).

Cause 2:

If your site is set to the correct timezone, but your users are set to a timezone that is 1 hour ahead, then that might also explain what's happening. In that case, correct the timezone accordingly.


Views Search Returning Unexpected Results Problem:
Items are not grouping correctly.

The Setup:
I'm working in Views and trying to customize it to display items grouped by a taxonomy term field called 'Event Type'. Furthermore I'd like them to be grouped WITHIN each taxonomy term grouping by Category (in a specific order). Each resource has both an event type and category. There are three event types: timely event, quick study, and deep dive. There are 10 categories: webinar, conference, articles, etc. 3 of those categories are also in 'Timely Events'. 4 of them are in 'Quick study'. The other 3 are in 'deep dive'.

My categories are setup to be ordered. The category field is a field list and has key/value pairings to match what I want. So, for example:

1|Webinar
2|conference
3|Workshop
4|Articles
etc.

Note that webinar, conference, and workshop will the 3 under 'timely events' and that's why they're ordered that way. The next four starting with Articles are under 'Quick Study', etc.

So I have it structured the way I want it to appear in the view already. And I want the view to reflect this by displaying something like this:

Timely Events
All webinars listed
All workshops listed
All conferences listed

Quick Study
All Articles listed
All [other 3 categories in order as set in the key/value pair above]

Deep Dive
Same as the others

Then in the view itself I have set Format > Unformatted List > Settings (Grouping field Nr. 1: Content: All taxonomy terms).

In Fields I have 'all taxonomy terms' set as the first field, with the following settings: 'exclude from display' and 'limit terms by vocabulary' > set to 'event-type'.

Under 'Content: all taxonomy terms' in 'Fields' I'm displaying icon, price, title, event dates, and body.

My filter criteria is set to published, type=resource, search terms and other exposed filters.

My sort criteria is set to Category (asc), event-dates asc, content: title.

The Result:

    Timely Events (header)
    All webinars listed in the correct order.

    Deep Dive
    All certificates listed in the correct order.

    Timely Events (again - why?)
    All conferences listed in the correct order.

    Quick Study
    All articles listed in the correct order.

    Timely Events (yet again)
    All workshops listed in the correct order.

My Question for you:
How can I get my results to display so that the headers (event type) display ONLY ONCE followed by each of the categories in that header in the order in which I've set them in the key/value pairing in the field list?

It should be like this:

Timely events (header)
all webinars
all conferences
all workshops

Quick Study (header)
all articles
etc.

Deep Dive (header)
all certificates
etc.

And that's it.

Anyone have any idea how to correct my grouping here?

Of course. Since I have 10 sub-categories and I'm ranking them by 'key' number 10 is displaying AFTER number 1 and then 2, 3, 4, 5, 6, 7, 8, 9. That's why it's returning the incorrect results. 10 should be named something else like 99 so it comes after 9.


How to exclude fields from print page version (html, pdf)? As in question, excluding node fields from HTML print page is easy via CSS, but what about PDF version (PDF version module)?

A quick peek in the code shows that the Print module utilizes "View Modes", which is a good thing. More info in Entity view mode and Drupal 7 custom node view modes.

You should create a new suitable view mode or re-use one you already have. This allows you to control the settings with the Field UI, while still allowing you custom templates if you need to.


Change 'Administration theme' not working - still shows current theme for administrative tasks I have a custom theme that works fine. I want to use D7's 'Seven' theme for administration. However, despite it being chosen already, Drupal uses my custom theme for administration and editing.

If I change themes to a Drupal default theme like Bartik, then, I can change the administration theme to whatever I want, even my custom theme, and everything works as expected.

This tells me I have something wrong with my theme.  What am I missing? Are there any default drupal theme variables that I need to include to make sure that the overlay theme is indeed Seven (or whatever I choose).  What could be causing my theme to disregard my Administration Theme choice and use my custom theme regardless of the setting?

note: I am trying to give 'overlay' permissions to others and want them to use the Seven theme.  I forgot to mention that this works fine if I am logged in as Admin (user 1) but everyone else gets the custom theme for admin regardless of what I choose.

Toolbar - Use the Administrative toolbar is a role permission. Check there if you are having the same problem to make sure it's checked for the role you would like to be able to access the toolbar at the top of the page.


How to get the parent name if chid taxonomy term id is known? How to get the parent name if child taxonomy term id is known??

Drupal 5.x: Taxonomy_get_parents()
Drupal 6.x: Taxonomy_get_parents()
Drupal 7.x: Taxonomy_get_parents()
Drupal 8.0.x: TermStorage::loadParents()
Drupal 8.1.x: TermStorage::loadParents()
Drupal 8.2.x: TermStorage::loadParents()


How to implement a semantic search? How can I add or implement a semantic search functionality in my site?

I have rdfx and schema.org modules in my site to add semantic data to my content so I need a way to add semantic search functionality to my site.

The following may or may not meet your needs exactly, but they're ideas.  Since I am now aware of semantic search modules currently available, these would be my workarounds.

The default drupal search does not really provide you with a lot of configuration options to determine which of your nodes' fields/tags can be weighed more heavily when determining search result relevance, I would enable and use the Apache Solr Search Integration module to get at more accurate search results.

With this module, you can get several benefits:

It lets you configure different weights, in terms of search result relevance, for the title, body, text in bold, text in comments, as well as terms in all your vocabularies.  This way, you can weigh very heavily the terms from a certain vocabulary, while omitting text from comments and weighing very lightly text that is in terms from another vocabulary (for example) -- adjust weights to your needs.  What I'm suggesting here is that you can use tagging as a form of search metadata with this module...  (Author name, etc are also fields that can be weighed with this interface)

You can use facets with apachesolr search, which can allow your customers to actually narrow down and interact with search results themselves!  It also provides a 'sort by' block, which users can use to sort results by relevancy (the default), or date, author or type if they prefer.  These aren't exactly what you asked for, but are a way to interactively let users tailor results...  Screenshot below is directly from apachesolr's module demo site.

To use apachesolr search, however, you have to have to install and configure a solr server for drupal to use: http://drupal.org/node/1053074


Add image at form submit I have created a form that has a submit button.

$form['products_submit'] = array(
    '#type' => 'submit',
    "#id"  => "submit_first",
    '#value' => t('Submit'),
    '#ajax' => array(
                'callback' => 'products_submit_driven_callback',
                'method' => 'replace',
                'effect' => 'fade',
                'progress' => array('type' => 'none'),
            ),
            '#prefix' => '
',
        '#suffix' => '
'
    );

  return $form;

And I want to add an image inside the button, at the left of 'Submit' text. I tried to add the img tag inside the t function but it just showed the code and not the image. Does anyone know how can I manage this?

You can handle this from CSS.

Like :

.button-logged-in.input{
    background-image: url(/images/buttons/submit.png);
}

Example : https://stackoverflow.com/questions/2920076/html-css-how-to-add-image-icon-to-input-type-button


How to set the text format of a field in a node object? When I create a node like this:

$nodeSetup = [
  'nid' => NULL,
  'type' => $bundle,
  'uid' => $uid,
  'revision' => 0,
  'status' => 1,
  'body' => ['format' => 'full_html', 'value' => Xss::filter($body)],
];
$_node = Node::create($nodeSetup);

the body value and format work fine. But, when I load an existing node, how can I set the body value keeping the format? This didnt work:

$_node->body->format = 'full_html';
$_node->body->set('format', 'full_html');
$_node->save();

The following worked for me,

$node = \Drupal::entityTypeManager()->getStorage('node')->load($nid);
$node->body->value = 'body';
$node->body->format = 'full_html';//omitting this will retain existing format
$node->save();


How should I fix an incorrect query in hook_update_N()? I made a new release of a module, and soon afterwards an issue was filed that the hook_update_N() used SQL that didn't work on PostgreSQL. In this situation I can see two solutions:

(Let's say the release with the problem is 1.1 and that N=6100.)

Modify update_6100 to have a fixed query and release as 1.2. If a user with Postgres updated to 1.1, got the error, and then updated to 1.2 they still wouldn't have run the query as it wasn't put in a new hook_update_N(). However they should've seen the error when doing the update, and the issue's in the issue queue, and can include instructions on how to fix the problem. It feels ugly to modify an existing (released) update function though.
Add update_6101 that has the fixed query. In the case of this particular query however, it would be destructive to run it after the user's started using some of the new functionality. So if a user with MySQL updated to 1.1, used the module a lot, and then updated to 1.2 there would be a good chance they'd lose data. I could check what DB's being used in update_6101 so that it would only be run for users with Postgres, but that feels ugly too. Also if someone with Postgres ran update_6100, saw the errors and then fixed and ran the query manually, they also could lose data when updating to 1.2.

Note that there's no way to detect if the query has run successfully, or has never been run.

I'd like to know what people think is the best way to deal with this situation?

Something similar happened with Panels, update 7301, a new field was added, and while the column creation happened, Drupal wouldn't accept the update as valid.

If you check the code in panels.install, you will see that the action taken by merlinofchaos, was to modify the 7301 to first check "Does this column already exists? Then smile and pretend we just created it, otherwise create it now."

If merlin does it that way, I would do it that way. Relevant issue here, maybe that will help further.

Since each of your scenarios above have potential for data loss, which is serious, and people dont actually take backups, and in your case, there is no, way to tell, then perhaps you will need to force the user to tell you. Refuse the update unless the variable module_name_has_1_1_content is set to either TRUE or FALSE. Then either you can add a form in the admin UI with an explanation and yes/no button that just sets the variable. Or just one "I have read the issue and understand the consequences, let me update" button.

Perhaps you can provide instructions for "How to export and import all content". That way the user can export, update, truncate the table, and import.


How do I Install Drupal Locally I have a html doc and css for a site that I do not currently have live. I want to use Drupal for the site but have a question about testing when changing the html/css into something compatible with Drupal: How do I check my progress to make sure things are working?

With an HTML doc, all I have to do is click the doc and it opens up in my browser. How do I test with Drupal in that way?

What steps do I take to install Drupal locally? I am running Windows, so do I use WAMP? I am a total noob, any help would be more than awesome.

Yes, you need to install Drupal locally to test the theme progress. There is a nice guide at http://drupal.org/node/307956, I hope it works for you. Please post back if you need more guidance. It is the easier way I know to get started with Drupal on your computer.


Too few arguments to function drush_migrate_tools_migrate_messages() I'm in the middle of a D7->D8 migration and tried running the command drush migrate-messages but got the following error:

ArgumentCountError: Too few arguments to function drush_migrate_tools_migrate_messages(),
0 passed in /mysite/vendor/drush/drush/includes/command.inc on line 422 and exactly 1
expected in drush_migrate_tools_migrate_messages()

but I've never had this error before running the same command and can't find anything in the documentation about it.

The Examples section makes it pretty clear. drush migrate-messages expects one parameter, the machine name of your migration for it to display the migration messages. There's no "show all" option. Run drush migrate-status to see all migration machine names (left column) available.


Error using Drupal Feeds to upload a comment in a text field I am loading data from a CSV file into a content type and everything is working fine except when I try to import a long text field / comment field.  The data in the comment field should be treated as straight text.

Here is my data I am trying to upload via feeds:

LP 8/28/13 strategy:  extend to 2020. LP 4/8 LL First Allied rejected concept. LP 4/17 meeting: 5 yrs. LP 9/24/14 strategy: 10 yrs.3/2-Spoke w/Jordan Raines-First Allied last week. Submitted LOI on 3/2.

When I try to upload this, I receive the error message:

SQLSTATE[22007]: Invalid datetime format: 1366 Incorrect string value: '\xFFexten...' for column 'field_store_comments_value' at row 1

SQLSTATE[22007]: Invalid datetime format: 1366 Incorrect string value: '\xFFexten...' for column 'message' at row 1

So my question is, how do I get Feeds import of a text string into a long text field to ignore the date strings in the comment?  I do not want the dates treated as dates.  I want the dates to be treated as a string of characters.

Or what am I doing wrong?

The CSV file has a comment in it.  I know the Feeds map is correct because I put the test "This is a test comment" in the csv and it loaded fine.  But when I put the full comment in, it does not work.

Any thoughts?

Thanks,

Dennis

I was running into this same issue myself where half of my records were getting cut off when I uploaded them via the Feeds Importer. I found an answer that was posted on a Drupal forum that indicates that the problem is not with Feeds, but with the file itself.

It appears that by default Excel exports your CSV file into ANSI format, which creates issues when there are dates embedded within one of your fields.  By using Notepad++ and converting the file into UTF-8 it works. Here is the link which gives more details.

https://www.drupal.org/node/2502761

NOTE: It also appears that if the file is encoded in UTF-8 BOM, then the CSV file can still be read by Drupal and Excel. Otherwise Excel treats it as a fixed length record.


Custom template for fields in user profiles I'd like to customize the fields in my user profiles. So far I've created field.tpl.php which of course applies to all fields on my whole website and not only to the fields in the user profiles.

How do I have to name the field.tpl.php? Is it field--user-profiles.tpl.php? That didn't work.

According to Drupal's theme hook suggestions for Drupal 7 the following suggested template names are available:

field--field-name--content-type.tpl.php
field--content-type.tpl.php
field--field-name.tpl.php
field--field-type.tpl.php

The content-type in this case is user (I guess it means entity type really), so to theme fields just for user profile pages, your template should be called:

field--user.tpl.php

I've just tested that on a dev site and it works perfectly.


Lightbox2 doesn't show image I have Lightbox2 installed on my Drupal Project. I am trying to use lightbox2 through links, for example:

<a href="/absolute-path-to-image" rel="lightbox">
   Link
</a>

It works only when I turn on the Lite version. How can I make it work on normal one? I have read that there is a possibility of wrong path. Already checked all of the possibilities and I can confirm it's not that. Is it possible that it collide with jQuery?

Thanks.

I think.. It will help to u.. Use views module and add image fields and rewrite the image fields. Look this image nkana-> database name.


URL transliteration in Views rewrite? I have a View of taxonomy terms and for some reason I need to overwrite the terms' fields and link them "manually", using "Output this field as link". How can I process the '[name]' token through transliteration process before outputting it on the screen?

Here's a workaround that worked for me.

Prerequisites: Pathauto and Transliteration modules.

Add a new text field to your taxonomy called "cleaned_name", or whatever you like. In a later step we will populate this field at view execution with the term name after passing it through pathauto_cleanstring.
Add the "Taxonomy term: Name", and "Taxonomy term: cleaned_name" to your view. The "cleaned_name" field must be below the "Name" field.
In the view settings for the "Name" field, mark the "exclude from display" checkbox.
In the view settings for the "cleaned_name" field, click on "Rewrite results" to open the rewrite settings, then mark the "Rewrite the output of this field" checkbox.
This will cause a textbox to appear, where you can build your link html. For example:

[name]

Next implement hook_views_pre_render. The idea is to take the the name, run it through pathauto_cleanstring, and store it in the cleaned_name field.  I used the following code:

function YOUR_MODULE_NAME_views_pre_render(&$view) {
    if ($view->name == "MACHINE_NAME_OF_YOUR_VIEW") {
       //dpm($view->result); INSTALL DEVEL MODULE AND UNCOMMENT THIS IF YOU NEED TO SEE WHAT FIELD NAMES TO USE
   module_load_include('inc','pathauto');
   foreach($view->result as $key => &$result) {
      $cleaned_name = pathauto_cleanstring($result->taxonomy_term_data_name);
  $result->field_field_cleaned_name[0]['rendered']['#markup'] =  $cleaned_name;
   } // End of FOREACH statement
   unset($result);
     }
}

Adding a field to your taxonomy just to have a place to return a transliterated version of your field is a little ugly. Another alternative I tried was to add the name field to the view twice, with the idea of running only one of them through pathauto_cleanstring, and thus having both a clean and uncleaned version available as tokens to build the link. This did not work however, because although you can add the term name field twice to a view, and views will create two tokens ([name], [name_1]), in the backend both tokens point to the same field. If we modify this field, both tokens will output the modified value.

Another alternative I tried was to build the link html inside the hook_views_pre_render function, and use that to overwrite the value in $result->taxonomy_term_data_name. That avoids the need to add a field to the taxonomy. However, the problem here is that views will escape the html when it displays it. I wasn't able to find a way around this.


Increase session timeout So I have a requirement that I'm getting close to stumped on how to complete in Drupal 8.

I'm going to attempt to simplify the requirements. I have two roles. They are essentially mutually exclusive. Let's call them "Internal" and "Client".

The request is to have Clients logged in for an indefinite period of time... let's call it years. Internal users need to be logged in for a short period of time, say 1 day, or even just the session.
(Note: I didn't make these requirements, just coding them... haha)

My understanding of the Drupal login is that there are really two things controlling this... there is the cookie lifetime of a user, and the session lifetime (on the server). If I set the cookie lifetime to 1 week, but the session lifetime is 1 day, the user will essentially be logged out after 1 day, b/c their cookie will match a session that doesn't exist after a day... is that right?

So, I think I have to start with the upper limit. If I want my user to be logged in for 1 year, I need my server session to be 1 year. One of my questions is: what are the risks/downsides/etc to setting my server session to 1 year? Let's say my server gets 50k visits a month. What if it's not 1 year, and I want it at 2 years? I can't seem to find a definitive guide to what the upper limit of server session should be? It seems like there's a lot of factors that could clear out that session as well...

Ok, so the above is one question... assuming I can set the server session, how can I have the cookie lifetime visit based on user role? I'm getting to the point where it seems like it just might not be possible to vary this setting, and I might have to do some kind of route subscriber and custom cookies and whanot to detect the internal users, and log them out when I see they've been logged in too long...

Any help would be much appreciated...

I have achieved this goal in the past for Drupal 7 using a bit of custom code.

Set the cookie lifetime and server session timeout to the larger of the 2 numbers, in your case I guess that's 2 years.
Write a custom script (e.g. in drush) that will find stale sessions and delete them.

For item #2 for you that means it has to find the Internal users with a short lifetime and delete their session if the sessions.timestamp is beyond a limit. According to system.install, that column contains The Unix timestamp when this session last requested a page.

The limit of your sessions table depends on database server hardware, but my experience on a fairly large site is that you can have millions of sessions records and it's not a huge problem for performance. That said, I also found that user interaction followed a power-curve. 90% of users who committed and got engaged did so within the first day. 95% were within the first week and going out to 3 months got up to 98%. Saving the cookie data beyond that for what amounts to a rounding error is generally not super useful.

I found that trying to do a sql delete directly does not scale well. Instead, I wrote a loop that would find records to delete and then run individual delete queries with a condition WHERE sid = :sid so it was using a primary key. This had the greatest performance while having minimal impact. You can even run the select against a read-replica database to reduce the performance impact further. For my scenario, 1 class of users who had not been active in the last hour were logged out so that job ran every hour. The other class of users who got deleted after 3 months would be deleted in a job that ran overnight as it performed more operations and had more impact on server resources.

If you truly need to store session data for 2 years that's fine. However, you might consider if you can instead store the data in the cookie instead of in the session. That way your sessions table stays lightweight and you can still do tracking of the user inside the cookie. For example, if your goal is to track a channel that brought the user to the site you could simply store that channel information in their cookie instead of the $_SESSION. If you can avoid generating/keeping a session then the scalability problem goes away.

Beware that many spiders and bots generate significant traffic and are poorly behaved a it relates to sessions: they may discard cookies, effectively generating a new session for every page request if your app does that. You can either place a bot-blocking/caching network in front (like Cloudflare) or just plan to periodically analyze the sessions table and delete sessions from these bots based on something like IP address.

I would not suggest memcache for this purpose, but instead a sql database (perhaps a dedicated database instance) or Redis. Memcache is optimize as a temporary data store. You purposefully want a persistent data store, which sql or redis do provide.


Get the return value of a hook defined in a module? Is there a way to get the return value of a hook defined in a particular module for eg:

$views_theme_hook = module_invoke('views', 'theme');

By using module_invoke function, I got an array of themes declared in views module. Is this proper way of doing it?

But this function needs arguments for some other hooks for eg: hook_tokens.

How could I get the result for hook_tokens and other similar hooks requiring arguments?

module_invoke() is a very simple function:

function module_invoke($module, $hook) {
  $args = func_get_args();
  // Remove $module and $hook from the arguments.
  unset($args[0], $args[1]);
  if (module_hook($module, $hook)) {
    return call_user_func_array($module . '_' . $hook, $args);
  }
}

As you can see, it passes the arguments straight through to the hook function by way of call_user_func_array().

So, you just need to pass the extra arguments with the call to module_invoke(). For example, to invoke views_block_view() with a specific block delta, you would use:

$block = module_invoke('views', 'block_view', 'some_block_delta');


Views will display entities the user does not have "view" access permission I have a custom entity type that can be viewed by certain people only. This works just fine, when people go to "mysite.com/custom-entity/8" some can see the info, some get "access denied" error.
The problem is I created a view to display a list of those entities and all of them are shown to all users, even if certain users shouldn't have "view" access permission.
LE: Caching is set to "None"
Any ideas on how to fix this? Thanks.

Option A
Create a custom access handler for your view.
Drupal 8 - Views Custom Access with a Plugin is a great guide. It seems like your scenario may fit the use case outlined in the beginning:
"... prohibit the display of a Drupal 8 View dependent upon some custom rules that don't fit easily with Drupal's permissions model ..."
Pro: You will get exactly the control features you want.
Con: A lot of custom code.
Option B
If you want permission for viewing the entity to be directly tied to the view access, there is an "Access" section on the view configuration form. Select "Permission" and then select the permission for viewing the entity you have created.
Pro: Easy to set up.
Con: Your use case must fit into Drupal's permissions system.


Dropping options of exposed filters breaks when user is logged I have a weird problem with Views exposed filters.

When I click on some exposed filters the dropping options are appearing, but when I hover with the mouse, dropping options are immediately dissapearing without letting me choose any of them. This problem only occurs when user is logged, no matter what role is using.
I've disabled the administration module, but the problem still remains.

Using exposed filter as a block doesn't have this problem and anonymous users too.

The same problem I've experienced in my other website too.

As Bala said, it is a CSS issue. I finally fixed it.
The problem comes from my <#section id="main">. It's a wrapper to all the main content area in my theme.
It has display:inline, but when I change it into display:inline-block or by deleting the display, the dropping options are working flawlessly.


Language selection in Panels? I have a panel node and in it I added a node. Is there any way to make Panels load the translation of the node based on the user current language. This is easy to do with Views adding a filter, but I can´t see how to do it with panels (if possible).

Panels should always respect the current users language, I've built several multilingual Panels sites, and never had to tell Panels which language to load.

In fact, the node "task handler", which is responsible for rendering nodes, doesn't even do a lot of work, but hands that responsibility over to Core, and as such, language to the Locale module.


Only admin can see products page for Drupal Commerce I created a subscription product with Drupal Commerce and commerce_sp modules.  I then created a view to display the product subscription I want and as Administrator I can see the product on the product page just fine, but as an authenticated user the page is available to view via a link in a menu, but the page doesn't show the list of products, just white space.  I've gone into the permissions to make sure the user can purchase an item and go through the check out forms, and the view has no access control on it.

I'm pulling my hair out over this, I have no idea why no one but the admin can see the products listed on the page.

Go to Admin menu > People > Permission:
Check 'Authenticated User' for:

'View any product of any type' from 'Product' group
'Access checkout' from 'Checkout' group


Problem adding button to custom content type form I am trying to add a cancel button to a custom content type form (typename/type/add).
I have looked around and there seems to be two main ways of doing this:

Creating a template file with the name page--node--add--typename.tpl
Implementing the hook_form_alter either in the theme template.tpl.php or in a custom module.

then adding code like

$form['actions']['cancel'] = array(
    '#type'   => 'submit',
    '#value'  => t('Cancel'),
    '#access' => TRUE,
    '#weight' => 55,
    '#submit' => array('cancel_button_form_cancel', 'node_form_submit_build_node'),
    '#limit_validation_errors' => array(),
);

In the first case,  after rendering the form with drupal_render($form) the button is added but only the form is rendered. Main menu and other blocks are not rendered.

However in the second case the button never appears. Even though something like drupal_set_title('Title') does change the title.

Any solution to either issue would be most welcome.

Edit
The first part of this question is now a separate one here.

Ok found the problem with implementing the hook, I copy pasted the code from some post and it was passing $form variable by value. The correct signature of the alter_form should be

modulename_form_alter(&$form, &$form_state, $form_id)


Different styling for each teaser display How to style Teasers differently in different displays and pages?

I am struggling very much with Drupal's CSS classes for teasers....Is there anyway to add them separate class name for each case?

Now, if I'm styling Teasers on Taxonomy page - the same class applies to Teasers on Front Page Promoted teasers, in Teaser blocks in Views, etc....

Well, I removed "promoted" teasers and put them in Views block and assigned a class; and it's separate on Taxonomy page....

BUT - what would I do if I would wish to have a separate template on some other (taxonomy) page for...teasers?

All those Teasers are in one big pot, named .node-teaser and the same field names...

//Using D7 and Zen 7.x.5x.

You can create different Entity View modes instead of the single teaser. While you can do that via a custom module in Drupal 7, there is a nice little module for that (https://www.drupal.org/project/entity_view_mode) too.

Create different modes like 'teaser_front', 'teaser_sidebar' and theme them differently using the standard theming convention (can also be found in the module page).


Uninstalling modules doesn't remove them from modules list If I install a module, and then uninstall it, for some reason the modules are not removed from my module list (or from my modules folder)- even after repeatedly clearing the cache.  Why would this be happening?

The modules on the file system are not intended to be deleted if you uninstall them. Although I can see that the terminology may be confusing.

Uninstalling will delete any references to the module in your site (assuming the module is written to do so), but will not affect the file system in any way.

The only reference to the module will be on the modules page, it will not be used in any live pages on your site. So should be harmless, but if you don't want the module to appear on the modules page you will have to manually delete the files.


Login and registration form in a single page Possible Duplicate:
  Print registration and login forms on same page

I found the LoginToboggan module, but it doesn't allow to register and log in from the same page.

What should I do to get registration and login form in the same page?

This has been answered many times here.
See this Print registration and login forms on same page

For this You need to create a page for Registration like this

page-user-register.tpl.php

And print the page contents as usual.
in that page you could try render user_login_block

Additional resources

http://www.trevorsimonton.com/blog/page-usertplphp-profile-php-template-drupal
http://api.drupal.org/api/drupal/modules%21user%21user.module/function/user_login_block/7


Panel Node Page File Selector Variant Hello im back using Panels and im hoping it will help with something that ive ran into with the new Media fields etc.

I want to create a Node Page variant that will overide node page if there is a video file linked via the Media Youtube  Multimedia asset    Media file selector file. If there is an image in the Media field then show a differant variant. I think its to do with File types.

Sorry if im a little out my termenology its just D7 hs so many new things to get my head around.

So a panels node page based on variants of what type of file is added to the Media field.

thanks

Fields are usually available as selector rules, so the solution to your problem: find out in which field the content is stored and use a empty/ not empty selection rule for your variant.

variants are selected by order, so the first variant that matches is selected. You could implement two panel variants, one with selection rule for empty, one for not empty, or use only one with selection rule and order the other on underneath that one.


How to fix menu links going below the fold? How do you fix menu links in the admin toolbar (drop down menus) from going below the fold when you have many different bundles?

For example, the "Paragraph Types" submenus often go below the fold because they sit alphabetically low on the "Configuration" drop-down.  If you have many paragraph types, it's hard to access them from the drop-down submenus.

You can create a new dropdown under the entity type ("Paragraphs types") that groups the links by first letter. Also, you can can change the weight of your item, and even move it out of being nested under configuration.

In the following example, we look for all the children of 'entity.paragraphs_type.collection' and we nest them under a copy of 'entity.paragraphs_type.collection' labeled with the first letter of the paragraphs underneath it.

function mymodule_menu_links_discovered_alter(&$links) {

  $links['entity.paragraphs_type.collection']['weight'] = 8;
  $links['entity.paragraphs_type.collection']['parent'] = 'system.admin';

  foreach($links as $key => $link) {
    if (!empty($link['parent']) && $link['parent'] == 'entity.paragraphs_type.collection') {
      $first_letter = substr($link['title']->render(),0, 1);
      $links['entity.paragraphs_type.collection.' . $first_letter] = [
        'title' => $first_letter,
        'route_name' => 'entity.paragraphs_type.collection',
        'menu_name' => 'admin',
        'parent' => 'entity.paragraphs_type.collection'
      ];
      $links[$key]['parent'] = 'entity.paragraphs_type.collection.' . $first_letter;
    }
  }
}

Here's the same alphabetical grouping technique on vocabularies:

    foreach($links as $key => $link) {
      if (!empty($link['parent']) && $link['parent'] == 'entity.taxonomy_vocabulary.collection') {
        $first_letter = substr($link['title']->render(),0, 1);
        $links['entity.taxonomy_vocabulary.collection.' . $first_letter] = [
          'title' => $first_letter,
          'route_name' => 'entity.taxonomy_vocabulary.collection',
          'menu_name' => 'admin',
          'parent' => 'entity.taxonomy_vocabulary.collection'
        ];
        $links[$key]['parent'] = 'entity.taxonomy_vocabulary.collection.' . $first_letter;
      }
    }

If you move the paragraph types to it's own drop-down, as in the example above, you'll want to style an icon for it.

.toolbar-icon-entity-paragraphs-type-collection:before,
.toolbar-icon-entity-paragraphs-type-collection:active:before,
.toolbar-icon-entity-paragraphs-type-collection.is-active:before {
  background-image: url(../../../../core/themes/stable/images/core/icons/787878/wrench.svg);
}

Here's my current version, which adds an "Add Paragraph Type" link:

/**
 * Implements hook_menu_links_discovered_alter().
 */
function mymodule_menu_links_discovered_alter(&$links) {

  // Move paragraphs to its own drop down.
  $links['entity.paragraphs_type.collection']['weight'] = -7;
  $links['entity.paragraphs_type.collection']['parent'] = 'system.admin';
  $links['entity.paragraphs_type.collection']['title'] = 'Paragraphs';

  // Move taxonomy to its own drop down.
  $links['entity.taxonomy_vocabulary.collection']['weight'] = -7;
  $links['entity.taxonomy_vocabulary.collection']['parent'] = 'system.admin';
  $links['entity.taxonomy_vocabulary.collection']['title'] = 'Taxonomy';

  $links['entity.paragraphs_type.collection.add'] = [
    'title' => new TranslatableMarkup('Add Paragraph Type'),
    'route_name' => 'paragraphs.type_add',
    'menu_name' => 'admin',
    'parent' => 'entity.paragraphs_type.collection',
    'weight' => -100,
  ];

  // Break paragraphs into groups by starting letter.
  foreach ($links as $key => $link) {
    if (!empty($link['parent']) && $link['parent'] == 'entity.paragraphs_type.collection') {
      $first_letter = substr($link['title']->render(), 0, 1);

      $links['entity.paragraphs_type.collection.' . $first_letter] = [
        'title' => $first_letter,
        'route_name' => 'entity.paragraphs_type.collection',
        'menu_name' => 'admin',
        'parent' => 'entity.paragraphs_type.collection',
      ];
      $links[$key]['parent'] = 'entity.paragraphs_type.collection.' . $first_letter;
    }
  }

  foreach ($links as $key => $link) {
    if (!empty($link['parent']) && $link['parent'] == 'entity.taxonomy_vocabulary.collection') {
      $first_letter = substr($link['title']->render(), 0, 1);
      $links['entity.taxonomy_vocabulary.collection.' . $first_letter] = [
        'title' => $first_letter,
        'route_name' => 'entity.taxonomy_vocabulary.collection',
        'menu_name' => 'admin',
        'parent' => 'entity.taxonomy_vocabulary.collection',
      ];
      $links[$key]['parent'] = 'entity.taxonomy_vocabulary.collection.' . $first_letter;
    }
  }

}


How to integrate a booking form? ... preferably with PHP. I am new to Drupal.

My goal is to integrate a page into an already existing project which enables to give to users the possibility to book a Hotelroom or a flight ticket while the Administrator (me) then collects the submitted information and validates the choice in the backend.

I have done this countless of times from scratch in PHP with POST. But on Drupal, when I try to integrate HTML and PHP code into a new webform or new article page, it doesnt really render it.

After reading your question I would do the following:

Create a custom module with a custom block that holds the booking form. This way you can add the booking form on whatever page you like with the Context module for example.

The Drupal 7 example module can show and teach you how to create a block in a custom module.


Massive spam users and spam entries despite triple layer protection I'm going a little nuts here. The entire point of my site resides on the idea of people registering for the site to contribute content. But I get spam accounts created at least once every minute. Im mass deleting these accounts and the content they create every single time I visit my own site.

I currently use Mollom with the CAPTCHA as the default method (not text analysis) and I have text analysis set to every other form across my site, I use the AntiSpam module set to and properly configured Akismet (had good results from Wordpress), and also have Spamicide enabled and properly configured.

But spam users are still being made in some very insane amounts, and generating content all over my site; which leads me to wonder if they're even using the forms at all any more to generate content on my site..

EDIT
may have been a little paranoia but I changed the user credentials to my database just to be sure. And yeah, user accounts by the dozens still being created..

I just tried out the Spamicide module by exposing the form element with Firebug and writing anything in it. Sure enough the form doesn't register the account.

The Captcha works perfectly too.

Note: I understand Captchas is not good enough (Spam bots these days can solve captchas), but its the only option I get from Mollom.

I recommend you try something different from the usual enter text Captchas.

  I personally use Are You A Human module. This is a video tutorial on how to set it up: Drupal 7 Are You a Human PlayThru
  Module - Daily Dose of Drupal episode 78.

If you want another option, I suggest you try Draggable Captcha here is an instruction video on how to set it up Drupal 7 Draggable Captcha - a more friendly way to prevent Spam

A new one that came to my attention is reCAPTCHA. Uses the Google reCAPTCHA web service to improve the CAPTCHA system and protect email addresses.


Apply a product discount if orders are picked up I have a Drupal Commerce site where customers get to choose whether to ship the order, or if they want to come and pick it up. Picking up is free, obviously.
This part works already, and I don't need help with.

There is an additional discount that should apply to one specific product only when the customer comes to pick up his order. There could be other products in the order besides the one specific product, and those products would not be discounted. This discount would be applied if "picking up" is specified during the check out process.
I'm having a bit of trouble getting the event/conditions right: it seems to me that no shipping method has been picked when the sell price is calculated.

Menno

Aren't the shipping methods themselves using rules? I would try to edit the rule for the Pickup shipping method and see if I could add the discount from the Actions of that Rule.

If you know how to use Rules Components, you could further encapsulate this so all the discount-related stuff was in a separate Rule Component.


Find if $view object is a block or page I am unable to debug this because when I print the display object I get a memory error from the size.
so with something like this I can get the display title.

function mailnow_views_pre_render(\Drupal\views\ViewExecutable $view) {
  $displayObj = $view->getDisplay();
  $displayName = $displayObj->display['display_title'];
}

I can get the machine name with $view->current_display == 'companies_page'

But I want to be able to get the display type for instance "Block" or "Page"

You can get it with

$plugin_id = $view->style_plugin->displayHandler->getPluginId();


Form elements update and deletion in D7 I have made a form in D7 using form API,submitted values to that and retrieved entries from database;now what i want is to add a delete link in front of every retrieved row.My retrieval code is:

function form_data_menu() {
$items['formdata'] = array(
'title' => 'Form Data',
'page callback' => 'form_data_form',
'access callback' => TRUE,
);
return $items;
}
function form_data_form()
{
 $results = db_query('SELECT * FROM {drupal}');
 $header = array(t('Id'),t('Name'),t('College'),t('Education'),t('Percentage'),t('Application'));
$rows = array();
foreach($results as $result){
$rows[] = array(
$result->id,
 $result->name,
 $result->college,
 $result->education,
$result->percentage,
 $result->application,
);
}
return theme('table',array('header'=>$header,'rows'=>$rows));
}

any help will be appreciated. Thank You!!

Yes you can easily do it in addition to this code. You need to create another url to delete a record from the database

$items['deldata'] = array(
'title' => 'Delete data',
'page callback' => 'form_delete_form',
'page arguments' =>array(1),
'access callback' => TRUE,
);

function form_delete_form($arg){
$query = db_query("delete * from the 'table_name' where 'id' =$arg");
drupal_set_message("Record deleted successfully.");
drupal_goto('formdata');

}

function form_data_form()
{
  global $base_url;
 $results = db_query('SELECT * FROM {drupal}');
 $header = array(t('Id'),t('Name'),t('College'),t('Education'),t('Percentage'),t('Application'), t('Options'));
$rows = array();
foreach($results as $result){
$rows[] = array(
$result->id,
 $result->name,
 $result->college,
 $result->education,
$result->percentage,
 $result->application,
'id.'>Delete',
);
}
return theme('table',array('header'=>$header,'rows'=>$rows));
}

Hope it works for you!


Combine two fields to be displayed together I have a content type that represents an object and amongst other fields this has two fields for dimensions - width and height. Currently the display has each field displayed one above the other:

                      10cm
                      20cm

because these are in independent divs I do not see a way to use CSS to position these in line with each other to give output like (should be centred on page as well):

                      Size 10cm x 20cm

The 'manage display' for a content type does not have any option to rewrite the output. How do I go about getting the output I require?

A simple way is achieve your job by jquery,( but if you have drupal developing knowledge you can do it in  tpl.php or custom module) but quick method is using jquery, get text from one element , the append it to second and hide first

blah 1

blah 2

and your js will be something like this

$('.second').append($('.first').text());
$('.first').hide();


Display average "Votes: Value" as stars in Views I have created a table in Views 3 where ratings are averaged according to days of a week. But the ratings are showing as values between 1-100.

How can i convert these values in star rating from 1 to 5? I am unable to make it work either using Rate or Fivestar modules. I would prefer a solution through views ui but dont mind alternatives.

It should be easy with a simple theme file.
In the views interface, on the bottom right, you should see "Theme: informtion", click that and you will see relevant theme file names.
Using one like "views-view-field--rating.tpl.php" should work.


Webform file upload with condition I have a webform with file upload element.  This works fine as long as the file upload element does not have a condition tied to it.  Without the condition, one can see that the selected file was uploaded.  With the condition, the file does upload, but the page does not update showing the uploaded file.  It took me a while to realize that

The file was indeed uploading
the condition was causing this behavior

I saw that there was a ticket about this exact issue for drupal 7 and it was marked as won't fix.  I wasn't sure if this meant that it wouldn't be fixed just for Drupal 7 or does this apply to Drupal 8 as well?

I found a good solution.  Since there were multiple elements that depended on the same condition for visibility, I realized I could put them into a fieldset and define the condition for the fieldset instead.  This did the trick.


Expose roles to views I am using the role reference module (https://www.drupal.org/project/rolereference) to allow me to add roles to a content type.

For some context, in my case we are managing policies.  The policy content type will have fields such as "Owner" and "Sponsor" that will reference roles using the module above.

My issue comes when trying to put together views.  I am able to access the role reference field through views without issue, but its sorting is based role id (rid) instead of the role name.

I am attempting to sort by role name, and am unable to create a relationship as Role is not available.

What is the best way to do this?  At the moment it appears that writing a custom module that invokes hook_views_query_alter() to alter the query before it runs might be the best solution.

I'm wondering if anyone has had any success exposing roles as a relationship within views?

Thanks in advance.

Turns out this can only be done programatically in a module.  Here is an example in case its useful for someone else:

function HOOK_views_query_alter(&$view, &$query) {
    /***** Owner ****/
  if ($view->name == "policy_listing" && $view->current_display == "policy_by_owner") {
    //alter the query so role reference fields are sorted by the role name rather than role id (rid)
    //replace the rid with the actual owner name
    $query->fields['field_data_field_policy_owners_field_policy_owners_rid']['field'] = "name";
    $query->fields['field_data_field_policy_owners_field_policy_owners_rid']['table'] = "role";
    $query->fields['field_data_field_policy_owners_field_policy_owners_rid']['num'] = 2;

    //add the join to the role table
    $join = new views_join();
    $join->table = "role";
    $join->left_table = "field_data_field_policy_owners";
    $join->left_field = "field_policy_owners_rid";
    $join->field = "rid";
    $join->type = "LEFT";
    $join->extra = array();

    $query->table_queue['role'] = array (
      'alias' => "role",
      'table' => "role",
      'relationship' => "field_data_field_policy_owners",
      'join' => $join,
    );
  }
}

In this case I am replacing rid with the actual name of the role in the view so the sorting works.  Obviously, replace HOOK with your module name.


Related news block in taxonomy term I'm trying to make a related news block on a term page instead of a node. I've done it on a node and it works fine, but when I try to do it on taxonomy term page it makes the whole block disappear.

This is what I have in the contextual filters and what I'm using as my relationship,

and here's whats in my taxonomy,

and this is what's in my content: nid

and finally whats in my relationship.

It looks like the block disappears because no content is returned by the view. You're filtering for both a taxonomy term id and a node id, while only a taxonomy term is present in the url of a taxonomy term page. Since there are no nodes that match the criterium 'no nid' there are no results. I believe this should work if you use only the taxonomy contextual filter. (This is if I'm understanding correctly what you're trying to do).


Eliminate access to specific user based on url, uid and role I'm using D8 and I have a panel page which has as parameter in the URL the uid (mysite/uid). In this page, are loaded different nodes and forms. What I want to do is to eliminate the access only to this user and the admin. It is not a node of a content type so as I can use the existing permissions (edit your own page).

Any idea how to implement this?

I was thinking to use something, maybe hook(?), triggered every time the user tries to access that page and doing some checks like the url and the uid and if the user is not admin or doesn't have the correct uid, throw an AccessDeniedHttpException();

I don't understand what you want to do specific to the panels page. In general you are looking for some kind of hook triggered every time a user visits a page. In D8 every page is connected to a route. You have to implement an access check on this route, see the documentation Access checking on routes. You can define the access check when you create a route or if you have an existing route from another module you can alter the route definition, see for this the next chapter in the documentation Altering existing routes


Extra empty rows when serving CSV file I'm building a CSV file and serving it up as a downloadable file.  Pretty straightforward.  Thing is, I get 18 leading empty rows in my csv file.  Any ideas?  I've stripped the code down to just about nothing - should I be looking for problems somewhere else?

/**
 * Implementation of hook_menu
 */
  ...
  $items['providers/dashboard/generate-csv/%/%'] = array(
   'title' => t('Export CSV Data'),
   'page callback' => 'generate_csv',
   'page arguments' => array(3, 4),
   'access arguments' => array('administer module_name content'),
   'type' => MENU_CALLBACK
  );
  return $items;
}

/**
 * MENU_CALLBACK function
 */
function generate_csv($source_type, $include_unpublished = FALSE) {

  // start up headers
  $csv_name = $source_type . '-csv_' . date('Y-m-d') . '.csv';
  header('Content-Type: text/x-comma-separated-values');
  header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
  header('Cache-Control: private', false); // required for certain browser
  header('Content-Disposition: attachment; filename="' . $csv_name . '"');

  // write csv data
  $test_output = "test,test,test";
  print $test_output;
}

EDIT - Looks like it is an issue with the headers, not the content.  If I write the contents of my output to a file, I do not have any extra space at the beginning.  Does anyone know:

What's up with the headers that could be causing the extra spaces?  Or..
How can I ditch any output and start over fresh with my headers?

The comments for my question were pretty much the answer, but I'll elaborate here.

The root of the problem was one of the included files had an ending PHP tag.  However, it wasn't in my code and I had no idea where else to look.

I ended up using something similar, to the following code.

watchdog("Module_name", "Check these files: !files", array("!files" => implode(get_included_files(), ', ')));

This gave me a list of all the files that Drupal had included in order to run my code.  There were about 140 of them.

The best way to figure out which might have superfluous end tags would be to cycle through each file programmatically, as Luke Redpath suggests on http://www.designerstalk.com/forums/programming/8005-php-finding-occurences-string-file.html.

In my case the file permissions were giving me trouble, so I brute forced it until I found an unrelated (but custom) module that had a bunch of ?> tags.


Drush bootstrap level error Im running onto some issues with Drush. I worked with php 5.3 and after upgrading to 5.5, i ran into some issues and decided to downgrade my PHP version back to 5.3. Now im running into the issue that Drush isnt working anymore.

Command cache-clear needs a higher bootstrap level to run - you will need invoke drush from a more functional Drupal environment [error]
to run this command.
The drush command 'cc all' could not be executed.                                                                                [error]
Drush was not able to start (bootstrap) the Drupal database.                                                                     [error]
Hint: This error often occurs when Drush is trying to bootstrap a site that has not been installed or does not have a configured
database.

Drush was attempting to connect to :
  Drupal version    : 7.28
  Site URI          : http://default
  Database driver   : mysql
  Database hostname : 127.0.0.1
  Database username : root
  Database name     : drupal_practice2
  Default theme     : garland
  Administration theme: garland
  PHP configuration :
  Drush version     : 4.5
  Drush configuration:
  Drush alias files :
  Drupal root       : /var/www/drupal
  Site path         : sites/default
  Modules path      : sites/all/modules
  Themes path       : sites/all/themes
  File directory path: sites/default/files
  %paths            : Array

You can select another site with a working database setup by specifying the URI to use with the --uri parameter on the command
line or $options['uri'] in your drushrc.php file.

Ive been searching on google for almost 3 days now and re-installing my computer would be a lot faster. I have lots of data so i dont want to re-install.

Someone that can help me with the solution?

Your problem is that Drush is running the PHP version that you have installed for your hosting environment (and Drush's own php.ini). You need to get Drush to run its own PHP that it installs with.

What host are you running on? If it is Windows then open a console and type set. That will show you the environment variables that you are using for your account. If there is a PHP variable in there, note it's contents and delete it by issuing the following command in the command windows: set PHP=

If that doesn't work set it back to what is was before. Any other platform I cannot help you with.

Also check this post: Modifying the PHP or PHP configuration that drush runs under


How do I rebuild table data on submit? I am using Drupal 7, I am using form API to generate a table with select option filters. The data from the table is from an external API.

The table loads as it should, the drop down selection loads as should. When I select an option from the drop down section I am trying to pass the selected value into the URL of the external API and rebuild the table using the new URL but the table does not get rebuilt, instead the page just refreshes, the selected option is updated in the drop down selection. I have tested and think that the URL variable is updated to include the select option but the table does not get rebuilt.

This is the module

function mymodule_form($form, &$form_state) {

$form['type_options'] = array(
  '#type' => 'value',
  '#value' => $options
);

$form['Title'] = array(
  '#title' => $title,
  '#type' => 'select',
  '#options' => $form['type_options']['#value'],
  '#default_value' => isset($form_state['storage']['Title']) ? $form_state['storage']['Title'] : '',
);

$form['submit'] = array(
  '#type' => 'submit',
  '#value' => t(“Filter”),
);

//Get fromtable data from API
if (!empty($form_state['storage']['Title'])) {
 $filter = preg_replace('/\s+/', '+', $form_state['storage']['Title']);
  $url  = $api.'&filter='.$filter;
} else {
  $url = $api;
}
$json = file_get_contents($url);
$data = json_decode($json,true);
$rows = $data[data];

//Set paging items for formtable
$per_page = 30;
$current_page = pager_default_initialize(count($rows),$per_page);
$chunks = array_chunk($rows, $per_page, TRUE);
$form['table'] = array(
  '#theme' => 'table',
  '#header' => $header,
  '#rows' => $chunks[$current_page],
  '#empty' => $empty,
  '#pager' => array('quantity' => 12)
);

$form['pager'] = array(
  '#theme' => 'pager',
);

return $form;
}

function mymodule_form_submit($form, &$form_state) {
  $form_state['storage']['Title'] = $form_state['values']['Title'];
  $form_state['rebuild'] = TRUE;
}

Thanks for any help

Your code should work fine from what I see. You can print the $url value to see what really is passed to API. Please note that $form_state['storage']['Title'] will contain the key, not value - maybe that's the problem?

Plus, you don't need to use storage in this case. When using $form_state['rebuild'] you can just use $form_state to pass variables, like this:

function mymodule_form($form, &$form_state) {
  $storage_val = isset($form_state['values']['title']) ? $form_state['values']['title'] : 'nothing stored yet';

  $form['message'] = array(
    '#markup' => t('Stored value: %storage_val', array('%storage_val' => $storage_val)),
  );

  $options = array(
    'opt1' => 'option1',
    'opt2' => 'option2',
    'opt3' => 'another option',
  );

  $form['title'] = array(
    '#title' => 'Select option',
    '#type' => 'select',
    '#options' => $options,
    '#default_value' => isset($form_state['values']['title']) ? $form_state['values']['title'] : '',
  );

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

  return $form;
}

function mymodule_form_submit($form, &$form_state) {
  $form_state['rebuild'] = TRUE;
}


Is there an hook_node_access() equivalent for users? Is there any way in Drupal to control access to users like it's done in hook_node_access() for nodes?
I'm looking for something like hook_user_access() or hook_entity_access().

I have an entity reference field (user reference). I want that users can only select users from their organic group, in the entity reference field.

I wanted to do it by implementing some hook like hook_entity_access(), but this hook doesn't exist.

There isn't an equivalent of hook_node_access() for users, or generically for any entity.

To check which user accounts can be selected from the Entity reference autocomplete, you could change the menu callback for the autocomplete.

function mymodule_menu_alter(&$items) {
  if (isset($items['entityreference/autocomplete/single/%/%/%'])) {
    $items['entityreference/autocomplete/single/%/%/%']['page callback'] = 'mymodule_entity_autocomplete';
  }
}

function mymodule_entity_autocomplete($type, $field_name, $entity_type, $bundle_name, $entity_id = '', $string = '') {
  $field = field_info_field($field_name);
  $instance = field_info_instance($entity_type, $field_name, $bundle_name);
  $matches = array();

  if ($type = 'user') {
    // Populate $matches with the matching users the currently logged-in user can select.
    return $matches;
  }

  return entityreference_autocomplete_callback_get_matches($type, $field, $instance, $entity_type, $entity_id, $string);
}

Probably you need to change the access callback of the autocomplete path too, with $items['entityreference/autocomplete/single/%/%/%']['access callback'] = 'mymodule_entity_autocomplete';. The access callback defined from the module is the following one.

function entityreference_autocomplete_access_callback($type, $field_name, $entity_type, $bundle_name) {
  $field = field_info_field($field_name);
  $instance = field_info_instance($entity_type, $field_name, $bundle_name);

  if (!$field || !$instance || $field['type'] != 'entityreference' || !field_access('edit', $field, $entity_type)) {
    return FALSE;
  }
  return TRUE;
}

If then you want to avoid users can view a user account directly using the link to the account, you can change the access callback for user/%user/view.

function mymodule_menu_alter(&$items) {
  if (isset($items['user/%user/view'])) {
    $items['user/%user/view']['access callback'] = 'mymodule_user_view_access';
  }
}

The default access callback is user_view_access(), which contains the following code.

  $uid = is_object($account) ? $account->uid : (int) $account;

  // Never allow access to view the anonymous user account.
  if ($uid) {
    // Admins can view all, users can view own profiles at all times.
    if ($GLOBALS['user']->uid == $uid || user_access('administer users')) {
      return TRUE;
    }
    elseif (user_access('access user profiles')) {
      // At this point, load the complete account object.
      if (!is_object($account)) {
        $account = user_load($uid);
      }
      return (is_object($account) && $account->status);
    }
  }
  return FALSE;

Drupal 8 uses hook_entity_access() to control access to any entity (including users) to various operations, hook_ENTITY_TYPE_access() to check the access to specific entities on various operations (for which hook_node_access() is the implementation for nodes), and hook_entity_create_access() to check which users can create an entity.
Drupal 8 code is much simpler than the Drupal 7 code, as as a single hook implementation does the task.


Hide/show pages depending on landing page click Last year i created a drupal 7 website for a MMA Trainer . He's pretty happy about it.
But now he wants to expand his business to personal training and has some new requirements.

He wants a landing page where people can click on 1 of 2 links(Gym / Personal training)
Depending on what the user clicks i have to hide/show certain pages on the website

How would i go about doing this ? Is there somekind of variable i can set on a landing page that i can check in drupal to hide pages ?

You can use Domain Access module with Subfolders Domain to create two instances Gym and personal training. This will allow you to administer content for both sections.


Is it possible to define a field as disabled on creation in field_create_instance? I have a content type that has a mix of user-editable fields and auto-populated fields (from an external source). I would like to mark those fields as disabled right when I create them so the user cannot overwrite them. I know there are readonly modules and ways to do this in hook_form_alter but I'm curious if I can short circuit having to do this on the fly and just have it disabled by default. Thanks.

No, fields don't have a 'disabled' setting by default.

You could however use hook_field_access to restrict access to editing them

/**
 * Implements hook_field_access
 */
function MODULE_field_access($op, $field, $entity_type, $entity, $account) {
  // Define read only fields
  $readonly = array('field_my_field_1', 'field_my_field_2');
  if ($op == 'edit' && in_array($field['field_name'], $readonly)) {
    // Disable edit.
    return FALSE;
  }
  return TRUE;
}


How to track popular categories (taxonomy terms) On a website, we want to be able to produce a list the most popular categories (taxonomy terms). We don't want to rank terms by term page  views but rank terms by content page views. When a user views a node page, the score/rank of all terms associated with the node should increase.

I couldn't find any module that provides this feature. As most statistics modules count and aggregate pages views, an acceptable solution would be using a reliable page view counting module that stores its information in the database (or any query-able external datastore). From there, a periodic ranking of the terms' popularity could be computed.

The solution has to work behind a caching reverse-proxy and when Drupal caching is enabled.

Note: we are already using Google Analytics to track traffic.

I don't know of a module which does this but you may be able to do it via google analyitics

token array will allow you to put all taxonomy terms into a custom variable

google analytics reports allows drupal to create reports from GA

So in theory you should be able to do this, I'm not sure how GA handles multiple values for the taxonomy


How to limit number of "Promoted to Front Page" option for each user/role I want to limit the option "Promoted to Front Page" per role.
For example, a user with role "promoter" should only be able to promote 5 nodes a day to promote to front page.
And same with sticky option.

I am using 'rules_link' module as well.

Any help.

You can achieve above by writing a small custom module in Drupal... Steps are outlined below to achieve the same.

Create install file and define schema hook with table name as user_promote_counter with below fields
uid, timestamp, nid
Using hook_node_presave($node) update above table with a record of uid, timestamp, nid of the node updated whenever promote is set to true so that you can track only promoted to front page actions.
Use hook_node_validate($node, $form, &$form_state) in your custom module to verify current user who has promoter role exceeded the limit of 5 by querying above table using timestamp and uid columns. Raise an error if limit is exceeded. That will prevent user to promote more than 5 nodes per day.


How to know if jQuery UI is being included Is there a good way of checking for if jQuery UI is being included on the current page request?

Found drupal_get_library(), and drupal_add_library(), but neither of them allows me to check if it is being included.

I am trying to do this from the theme, and then load a jquery.ui.touch-punch library to enable iPad/iPhone support.

There's no built in way but as drupal_add_library() uses Drupal's static pattern you can find out by doing this:

function ui_is_included() {
  // Get the list of libraries included in this page load
  $libs = drupal_static('drupal_add_library');

  // The system library will pretty much always exist as it includes jQuery,
  // but it's just good sense to check just in case.
  if (isset($libs['system'])) {
    // If the system library array includes UI then make sure it's enbabled
    return isset($libs['system']['ui']) && $libs['system']['ui'] === TRUE;
  }

  // UI is not loaded if we've got to this point
  return FALSE;
}

You can even compress that down a bit:

function ui_is_included() {
  $libs = drupal_static('drupal_add_library');
  return isset($libs['system']['ui']) && $libs['system']['ui'];
}

I'd advise calling this function as late on in the page build process as possible, to ensure that all modules have had a chance to request that UI is added. hook_preprocess_html() in your theme's template.php file might be a good place to put it.


How to display previous and next arrows in views I am trying to create a views block that will display one item on a page. I like to display next and previous arrows but I see the next arrow by default and I do not see the previous arrow until I am on 2nd page. I can remove the numbers but how can I display only next and previous arrows by default?

There can only be a previous button if there are content before the current page. So logically there is no content before page 1. So obviously there will not be any previous page to go to.


Why can't I change anything in hook_node_view_alter? I'm trying to change one of the side panels, no clue what is rendering it but it displays a list of OG members.

Anyways, in template_block_view and hook_page_alter, the widget has already been rendered into HTML. The only place I've been able to find where its still in pre-render form is hook_node_view_alter but no matter what I do to the $build variable, it has precisely 0 effect on anything (yes, I made sure the function is being called).

So if its not to change the view, what is hook_node_view_alter for? This is on drupal 7.

hook_node_view and hook_node_view_alter are only going to give you control over the inner content of a particular $node that you may be viewing. Such as the inner content when going to www.mysite/node/2

Now if you have additional "blocks" or maybe as you called them "side panels", these are not a part of the $node array and thus cannot be changed in hook_node_view or alter. If the side panel is indeed a block, then you can change it's output with hook_block_view and hook_block_view_alter. Among other things depending on what you are trying to do. The process is to find the block ID, and target it inside your hook. However I may be wrong, because it really depends on what the block is.

You will need to provide a printscreen showing exactly what you are talking about if we are going to figure out the right direction you should take on altering it.

I would suggest downloading the "devel" module, enabling it, then look at the ouptut from hook_block_view_alter and see if it's what you're looking for.

function mymodule_block_view_alter(&$data, $block) {
  dpm($block); //make sure the module devel is installed and enabled for this function
}


Search API: sorting with Scandinavian alphabet We're using the search API something like this, and returning results in alphabetical order:

// Set up
$search_api_index = $this->entityTypeManager->getStorage('search_api_index');
$index = $search_api_index->load($name);
$search_id = 'restful_search_' . uniqid();
$query = $index->query([
  'limit' => $limit,
  'offset' => $offset,
  'search id' => $search_id
]);

// Add some conditions
$query->addConditionGroup($conditionGroup);

// Add sort directive
$query->sort('title', SORT_ASC);

This is working, and the results are coming back in alphabetical order. However, we'd like the sort according to the Finnish/Swedish alphabet.

So instead of things being sorted like "ÄBC", we'd like them sorted like "BCÄ". That is, those beginning with Å, Ä and Ö etc. should come last, not first.

Is it possible to tell the Search API to return results which meet this order?

I believe your question is more tailored to Solr rather than Drupal persay.

I'm using Solr, but not with any special language semantics for Sorting required.

It appears as though solr can be configured to support the kind of alphabetical sorting you requested via a Plugin and a special field type. See the section entitled Unicode Collation on this reference page:
https://cwiki.apache.org/confluence/display/solr/Language+Analysis

Once your Solr instance is configured to support the ICUCollationField field type. You then need to tell Drupal to make use of that field for analysis/sorting. So either in D8 you need to implement some of the below modifications:

alter the Solr Field type that fulltext searches are indexed with to use the ICUCollationField instead of the default fulltext field supplied by Search API using the Search API hooks.
OR, use the copyfield technique described in the Solr reference page under Sorting Text for Multiple Languages, and use the Search API copy field functionality to clone the default fulltext into this collation aware field.

then alter every search performed by your site using Search API hooks to override the Sort parameter to use the collation field.

Your request will likely require a full Solr re-index of all your Nodes, and if you use copyfield be aware the index may be much bigger.

These are some general approaches you can attempt using Search API and Solr. I'm not 100% sure they'll work, but they're the 2 approaches I'd try if I was setting this up.

Any feedback, success or failure is welcome to your original post once you've figured it out.


I'm constantly getting logged out of my account I have a weird issue on a test server where I get constantly logged out. What could cause that?

A lot of different things can cause that, so there are several things to check. One common issue is not having the site direct traffic to either www.[sitename].com or [sitename].com - this causes users to have separate sessions for each version of the site. Solution here: Website saves separate sessions for "www.domain.com" and "domain.com"

Another possible issue is a misconfigured sites/default/settings.php file - this can happen if you copy the site from another location. Check uncommented lines pointing to urls other than your test location. I believe cookie domain can cause session problems if misconfigured.

Finally, since you mentioned that this is a test server, you might check that Drupal's MYSQL user has the correct permissions for its database. I've had strange things happen when it has some but not all of the necessary access permissions to the database.


Check a revision exists for a node How do I check there is a revision exists for a node? I can load the node details using the following code.

$nid = "my_node_id";
$node_details = \Drupal\node\Entity\Node::load($nid);

How do I check if there is a revision for a node? Putting it differently: How can I get the revision ID of a node after creating a new revision?

I create a new revision using this code.

  $original_revision = \Drupal\node\Entity\Node::load($nid);
  $original_revision->my_field_to_be_modified= "my_value";
  $original_revision->setNewRevision(TRUE);
  $original_revision->setRevisionCreationTime($time_stamp);
  $original_revision->save();

Use getRevisionId(); The revision identifier of the entity, or NULL if the entity does not have a revision identifier.

https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Entity%21RevisionableInterface.php/function/RevisionableInterface%3A%3AgetRevisionId/8.2.x


How can I handle restricted items on a Drupal Commerce site with special display and checkout rules? I'm about to undertake the building of a Drupal Commerce site that has special restrictions around purchasing some of it's items.  Specifically these items will not have displayed prices and a sales rep must approve their purchase. I'm new to Commerce but not Drupal I'm basically looking for advice here...

The use case is not set in stone but the case that I would like to achieve is basically this:

user can see restricted item and can add it to their cart but the price displays as 'request a quote' (I thought maybe views could do this with rewrites but I need logic it doesn't offer) I need to add other actions regarding line items as well ('request a sample' in particular).

when request a quote item is added to the cart trigger modal legal mumbo jumbo

once in the cart view the order is categorized into 'purchasable items' and 'request a quote items'

When the cart is submitted only purchasable items will be actually purchased, request a quote items will sent via email to reps/automated in some way/saved in the cart for later.

Maybe a rep can trigger user status change and prices become reveled/items are moved to purchasable, perhaps not?

I'm guessing I'm going to need a custom module?  Is this even possible, processing part of a cart like this?  Any of you E-comm pros build something similar, how did you do it?

So found that I was mostly in uncharted water on this but I waded through and I am mostly done building, so I will explain how I did it for the next guy.

I used quite a few modules, including a few custom modules...

Commerce wishlist was used as a template to create two custom modules 'request a quote' and 'request a sample'.` They are essentially extra carts with custom actions.

Another custom modules was used to alter/disable parts of the commerce line item based on CCK field values. It will also be responsible for altering the checkout process/adding safety coniditions when I get around to that.

Taxonomy maintains a multi-dimensional product hierarchy. Tokens, Url Aliases and Views with 'global exposed filter' + views_php create the catalog. Views are embedded into tpl files and passed arguments programmatically from node properties in lue of using product references (I needed more customization/arguments) than they offered.

The answer in short to building most of my problems was to be very Drupal-y about it and ignore a lot of the out of the box functionality of commerce...Aka: Take the views hammer to it!

That's about it. Good luck future Drupal Commerce dev!


Search Api, fulltext and string for search bar and facets I'm trying to figure out how to make and indexed field (City) play nice with fulltext search exposed filter and a facet term.

As of right now, a fulltext option works with the search bar, but splits 2 word cities into separate facets. And string combines multi-word cities into one facet, but then breaks the search bar.

What setting will work for both?

I had an issue similar to this with 2 separate fields, Country and City.
Country was a taxonomy term while City was a textfield. I wanted to use both for fulltext search and as facets. In my Search API Index I added related fields for my Taxonomy (Country) and used the name (Country:name) as a fulltext field for my search bar. The thing is that the City when indexed as a fulltext didn't work in combination with the Country facet, and when I changed it to string it didn't work with the search bar.

Solution:

Leave your field (City) as a string field
Go to your Search API Index
Click on "Filters"
Check "Aggregated Fields"
Add new field and select your desired field, for example "City" and aggregation type "fulltext"
Go to your view, where you use the fulltext search, click on it and in the Searched fields you will see the aggregated field you had added before.

It should work fine now. If not, try re-indexing the items, clear your cache, double check that the field is set to be indexed, etc.


Custom language switcher block, returning urls problem In Drupal 8, i am trying to create a custom language switcher block.
So, I created a custom module, where I created a new class that extends the "LanguageBlock" class of the core language module.
I utilize the build() method, that builds alright my custom block. The problem though, is that the resulting links of my custom block, return a pattern like this in the url:

http://base_url/?language_content_entity=en
http://base_url/?language_content_entity=de
http://base_url/?language_content_entity=es

and the language does not change, whereas the default language switcher block works fine.
This problem occurs even if the build() method is copy/paste from the parent class, and/or even if I just return parent::build(), with no editing whatsoever.
Does anybody have a clue why this is happening, and maybe a possible solution?
Thank you.

PS: The code of the build() method.

public function build() {
    $build = array();
    $route_name = $this->pathMatcher->isFrontPage() ? '<front>' : '<current>';
    $type = $this->getDerivativeId();
    $links = $this->languageManager->getLanguageSwitchLinks($type, Url::fromRoute($route_name));

    if (isset($links->links)) {
      $build = array(
        '#theme' => 'links__language_block',
        '#links' => $links->links,
        '#attributes' => array(
          'class' => array(
            "language-switcher-{$links->method_id}",
          ),
        ),
        '#set_active_class' => TRUE,
      );
    }
    return $build;
  }

I finally found what the problem was.
This code "$type = $this->getDerivativeId();" was null, and, as a result, this code "$links = $this->languageManager->getLanguageSwitchLinks($type, Url::fromRoute($route_name));" could not build the following part of the $links array:

"[language] => Drupal\language\Entity\ConfigurableLanguage Object
                    (
                        [id:protected] => en
                        [label:protected] => English
                        [direction:protected] => ltr
                        [weight:protected] => -10
                        [locked:protected] =>
                        [preSaveMultilingual:protected] =>
                        [originalId:protected] => en
                        [status:protected] => 1
                        [uuid:protected] => 6c14f789-dcf3-4149-883f-63c29df3e544
                        [isSyncing:Drupal\Core\Config\Entity\ConfigEntityBase:private] =>
                        [isUninstalling:Drupal\Core\Config\Entity\ConfigEntityBase:private] =>
                        [langcode:protected] => en
                        [third_party_settings:protected] => Array
                            (
                            )

                        [_core:protected] => Array
                            (
                                [default_config_hash] => HolYKYAaiuzaHd7bV6FOM0HVbmmEMd3Zq4JAcgW55_4
                            )

                        [trustedData:protected] =>
                        [entityTypeId:protected] => configurable_language
                        [enforceIsNew:protected] =>
                        [typedData:protected] =>
                        [cacheContexts:protected] => Array
                            (
                                [0] => languages:language_interface
                                [1] => url.site
                            )

                        [cacheTags:protected] => Array
                            (
                            )

                        [cacheMaxAge:protected] => -1
                        [_serviceIds:protected] => Array
                            (
                            )

                        [dependencies:protected] => Array
                            (
                            )

                    )"

All the above was missing, so the url could not be properly build.
The solution was to add "Derivative" php file for my class, just like the core language module includes both the "core/modules/language/src/Plugin/Block/LanguageBlock.php" and the "core/modules/language/src/Plugin/Derivative/LanguageBlock.php".
Of course, you have to fix the machine names and namespaces if you do something similar.


How to add a class to scald images? I am using the Drupal 7 Bootstrap theme and Scald. I have figured out how to use contexts but would like it so that when an image is shown it has the img-responsive class.

Can this be done by manipulating the render array?

Can anyone point the best way to achieve this?

Putting an extra <div class="img-responsive"> wrapper around the standard atom markup generated by Scald works (sort of - the legend doesn't look good).

However, I've solved this by just copying the Bootstrap img-responsive class, using it as an override for the Scald dnd-atom-wrapper class:

// Just copy the Bootstrap CSS for img-reponsive.
.dnd-atom-wrapper {
  max-width: 100%;
  display: block;
  height: auto;
}

This seems to work for all image atoms in Scald (it may break other types of atoms - I only use Scald atoms for images).

I really want to emulate the complete Bootstrap "thumbnail" concept (including nice borders and captions), but using  standard Scald atom css classes, so I ended up with these overrides for the relevant classes (this is the default player - must be slightly adapted to work with the HTML5 player):

// CSS fror Scald image atoms
.dnd-atom-wrapper {
  max-width: 100%;
  display: block;
  height: auto;
  background-color: #ffffff;
  border: 1px solid #dddddd;
  border-radius: 4px;
  line-height: 1.42857;
  margin-bottom: 5px;
  padding: 4px;
  transition: border 0.2s ease-in-out 0s;
}
.dnd-legend-wrapper {
  margin: 0;
  text-align: center;
  font-size: 0.8em;
  width: 100%;
}
.dnd-atom-wrapper,
.dnd-drop-wrapper img {
  margin-left: auto;
  margin-right: auto;
  float: none;
  display: block;
}
.dnd-atom-wrapper.atom-align-right {
  @media (min-width: @screen-lg-min) {
    margin-left: 0.7em;
  }
}
.dnd-atom-wrapper.atom-align-left {
  @media (min-width: @screen-lg-min) {
    margin-right: 0.7em;
  }
}
.atom-align-right {
  @media (min-width: @screen-lg-min) {
    float: right !important;
  }
}
.atom-align-left {
  @media (min-width: @screen-lg-min) {
    float: left !important;
  }
}

I have this CSS in less/overrides.less in my Bootstrap subtheme.

Remember to compile it with lessc and clear caches for it to work.

Below you can see it in action.  Big screen on the left, small screen on the right.


How to compare Profile2 field with PCP percentage in drupal 7 while creating Rule? I am using Rules, PCP & Profile2 Module in drupal 7. I want to send mail to those user whose profile is <60%, how to add condition for sending mail? How can i compare the profile2 field with pcp %. I already created a Event & Action. Problem in add contion. Please help. Thanks

I want condition like this i.e. $complete_profile<60. If by using php code then how can i implement.

See Rules Integration for D7 version issue in Profile Complete Percent issue queue. Only condition they implemented is, it seems, "User profile is completed".

Maybe there are additional conditions now. Open this window and see. If condition you want is lacking, you will need to either file a feature request for PCP, or write own custom module, clone "User profile is completed" in it, changing name and switching from =100% (or how they actually implemented it) to <60%.


How to display image instead of a value in Drupal 7? I'm having a field 'List (text)' in my custom content type as 'Select list' with Number of values as 'Unlimited', what I'm searching is to display an image instead of a value, for an instance I'm having values like Condo, Single Family & Multi Families so for these 3 different values I'm having 3 different logos which I want to display so what should I do to get this thing done?

I can suggest an idea I used in Views output — this may help you find a solution for your case. I needed to display an icon near an article depending on its material type. I added a hidden PHP field with the following code (image names are not directly the same as the type name, that was the brief :)):

<?php
switch ($row->type) {
case 'article':
  print 'articles'; break;
case 'gallery':
  print 'gallery'; break;
case 'music':
  print 'music';
}
?>

And then a “type” field, which had the following override:

<img src="/sites/all/themes/my_theme/images/[php].png" alt="[type]" title="[type]" width="22" height="22" />

[php] is where Views output inserts the output of the PHP field I showed earlier. This same approach can be used to add a class to the HTML tag, and define a CSS image background for each class.

I hope this helps to find a solution for your problem.