How to get Page Manager to react on path alias before node/%node I have a CTools Page Manager Panels Variant that I want to apply to a whole load of different content, based on paths. Basically I want this Page Manager Page to handle all paths matching:

foo/*/*

Some paths will be node path aliases, some will be generated in other ways, i.e. not nodes.

I've set up a Page Manager Page with one Variant on the path foo/%blah/%baz, and this works well.

The problem is that if foo/bar/whatnot is a node's path alias, Page Manager sees this as node/1234 (it's menu path), and reacts with a different variant (node/%node), never considering the page page/variant I want.

My understanding of Drupal's "fitness" logic for menu router items would mean that my thing would win if the node's path alias was used, because foo/%/% has a fitness of 4, whereas node/% has a fitness of 2.

Is there any way to achieve this?

If you want to override the default path like node/%node, taxonomy/term/%taxonomy_term and so on then there is a module for that: Page manager existing pages. Some more details about this module (from its project page):

  Page manager existing pages allows you to override/configure Drupal menu paths so you can create variants with Page manager, which is bundled in the CTools project.

Here is an introduction from the author: Overriding any Drupal path with Page manager existing pages.


Getting field value that attached to Commerce product field From using commerce_price_savings_formatter, I've created field field_diskon where it only contains number. field_diskon purpose is for discount rate.

So, I can assign different discount rate for different SKU.

For getting value in field_specific_blabla attached to node, I can use:

// Extract the first field item
$specific_items = field_get_items('node', $node, 'field_specific_blabla');
$specific_item = array_shift($specific_items);

// Get the field value
$itemvalue = $specific_item['value'];

But how to get value field_diskon attached to commerce product field?

I have no idea what entity hold commerce field. I've tried replacing node with keyword related to commerce, but still not works.

You should be able to use entity_metadata_wrapper quite nicely for this. Note that it is part of the Entity API, but that is a dependency of Drupal Commerce so you'll be fine in this case.

Something like the following code should do it:

$wrapper = entity_metadata_wrapper('commerce_product', YOUR-REQUIRED-PRODUCT-ID);

$discount = $wrapper->field_diskon->value();

You can find out more about how to use entity_metadata_wrapper() here.


Feeds import and related fields I have a content type with an entity reference field (I suppose a term reference field would work as well).  The target type is a taxonomy term.  The taxonomy term has a name and ID field (among others).  My feeds source that I would like to import has the taxonomy ids that I can import but I'd like to display the name not the id.  My problem is I can't get the feeds map correctly unless I have a list of names in my feeds source, not ids.

Thanks
Sharon

I've figured it out.  If I import the ID field as GUID when adding the taxomony terms, then I can select that as an option when I import into my content type :)


get commerce order variables dpm without loading order again I try to get order variables using devel module from inside custom order template page--admin--commerce--orders__%.tpl.php.

I use code $order = commerce_order_load(123);

Question: is it possible not to load full order again and get the variables ? (assuming that I am on order page, the variables should be loaded anyways correct?)
Thank you for explanation.

You need to use commerce_order_load to load the order with all the data. If the order already has been loaded somewhere else on the page, the order won't be loaded twice, but the order will be fetched from static cache instead. So it's fine to load the same order multiple times.

If you do need to clear the cache, (maybe you need to compare the order to what is in the datebase to see what has changed), then you can use use commerce_order_load_multiple or call entity_load directly.


Hide admin email address in user's from field (Webform) I am using the Webform  module.
So far the user can send an email via a form to my admin email.

However when I reply to the user my admin email address shows in their 'from' field! - How do I hide that to the site's name (but still pointing to my admin email address)?

After saving the new component, visit the emails tab. Select the newly created component from the "Component value" select list and select add. The final results will look similar to this.


Display a field for a specific amount of time I'd like to place a small overlay on my video called "New". So I downloaded the date module and added a date field to my video content type.

Anyone know if its possible to then output the date field (which I can style with CSS) only for a certain period of time like a week or two? After a set date the field would not be output.

Thanks guys!

Update: I have found a module called fieldscheduler that will schedule a field, but I cannot schedule a specific node, only all nodes that use that field. So close!

I don't know what format your date field uses so you'll have to adjust for that, but something along the lines of

if(($content['field_date'] >= $first_date) && ($content['field_date'] <= $second_date)) {
  print render($content['field_date');
} else {
  print($wrong_date_message);
}

...where $first_date and $second_date are the beginning and end of the date window for which you want to display the field, and $wrong_date_message is whatever you want to show up there instead when the field isn't displayed.

For more information about date formats in PHP, check out http://php.net/date.


Using Drupal variables in CSS? I'm using CSS to implement a banner image in my theme:

#banner {
    background: url("../images/banner.jpg") no-repeat fixed
}

Site users would like to be able to change the image within Drupal. I'm thinking of adding a file upload field to the Site Information admin form, and insisting that only a file with the same name (banner.jpg) is uploaded.

I wonder if it would be possible to use a Drupal variable in my CSS instead? Then a file name change wouldn't matter. I've used CSS in .php files before (setting the content type back to CSS in the header), but never tried this in a Drupal theme.

You can apply css styles from php. Use the drupal_add_css() function

<?php
drupal_add_css('#banner { background: url("../images/banner.jpg") no-repeat fixed }',$option['type'] = 'inline');
?>


How are node and node_revision tables related? I've noticed that the following does not work to unpublish nodes:

db_update('node')
  ->fields(array('status' => 0))
  ->condition('nid', $array_of_nids, 'IN')
  ->execute();

But it does if you follow up with the same update on the node_revision table. (But perhaps I should only be updating the status of the current revision (vid)?)

I found this confusing because the nodes in question do not use revisioning yet it seems that the revision table holds more authoritative data than the main node table (so if so, what's the point of node table?)

Can anyone explain how node and node_revision are related and therefore how to do a bulk update such as this 'properly'? (I'd prefer to avoid a costly loop of node_load, node_save if poss.) I'd like to understand the Drupal Way here.

(I have read node revisions which covers D6, but that did not give me the understanding I was after.)

The node table holds the basic information about the node, the nid is the primary key on this table and contains the vid field which is a foreign key to the node_revision table. The node_revision table holds each revision of the node, the vid is the primary key on this table and contains the nid field which is a foreign key to node table.

You may think that this information is identical, but it's not. The node table only contains one record relating to a node and also stores the current vid whereas the node_revision table contains the revision data. Just because you're not using revisions it doesn't mean that this process isn't being used.

Also keep in mind that all field tables have 2 versions, field_data_[field_name] and field_revision_[field_name], the data tables contain the current revision and the revisions table contain the revision data.

To get an understanding of how practical revisioning works try looking at Revisioning, a more complex and powerful solution can be achieved using Workbench


How can I add my field of his type of material to be used in the rule I need to compare two different entities in the field after the update term.
Event: "After updating existing term"
One field is in the drupal commerce product, the other in a term. With the help of "entity has a field" do not get to add because you do not see the entitie of the product. What can be done to solve the problem?

I hope it is for D7
I was facing same issue some months ago, I assume that you want tocheck the Boolean value of the fields?
please confirm that is that you want to do.

To compare to different entites I did following

You might not need to add these module to achieve what you want, but they are always good to know.

Drupal Commerce extra conditions

Drupal Commerce Extra Rules

Gives you more options when working with drupal commerce and conditions
Drupal Commerce extra rules - Well it gives you more rules to play with.

But for taxonomy term, Rules would just work out of the box.

The logic would be
a "Data comparison" condition, specify the field name, and enter "1" as the value. If the field doesn't appear in the list of fields, first add an "Entity has field" condition, and select the field there. Then add the "Data comparison" next.

Data Comparsion
Condition, give the field name you want, give the value 1.
If you cant find your field. You will need to add it in the above condition as "Entity has field" - or specifying "Content as type".
Then you will choose the operator which should be == (equals)
Add Data comparsion.
(Field might have to be direct input mode)

Hope it helps


Calendar - Non repeating events displaying in multiple months, how to fix it? I have normal events which are displaying correctly in the month they should but they also appear in the first line (week) of each month after.

I have tried removing the events and creating them again, creating the calendar from scratch but still they appear.

I'm not sure what extra details would help in answering this so if there is anything you need just let me know.

Thanks

It would be a guess as its hard to say without more details but its most likely to do with contextual filters not set up correctly. For month I have them set up as follows:

Provide default value: current date
Granularity: month
Dates to compare: Start/End date range
Add multiple value identifier: Yes
Content: Dates - start date (field_event_date)
Method: OR

For week its exactly the same except using week granularity and so on for days and years. Make sure you dont have any other calendar views (even disabled ones were playing tricks on me before). Also make sure your sort is based on the same date field as the contextual filter.


bulk importing data in articles node catagory based Hello how to bulk Import XML feeds -Content from xml systems category base to drupal

Hello I have custom CMS we are moving to Drupal.Our custom CMS has bulk post system via XML feed.
We post 1000 articles/News via xml per hour on our CMS.

We need to know how to import bulk xml as Categories (Taxonomy) base.

Here is our xml file below

  Sports
  Title
  Image Location

    Bulgaria votes in parliamentary poll
    Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Nam liber tempor cum soluta nobis eleifend option congue nihil imperdiet doming id quod mazim placerat facer possim assum. Lorem ipsum dolor sit amet, consectetur adipisici elit, sed eiusmod tempor incidunt ut labore et dolore magna aliqua. Lorem ipsum dolor sit amet. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi.Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. At vero eos et accusam et justo duo dolores et ea rebum. Sanctus sea sed takimata ut vero voluptua. Consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.
    tag1,tag2,tag3
    2/15/2015 8:26:01 AM

     Sports
    Youssou Ndour awarded Polar Prize
    At vero eos et accusam et justo duo dolores et ea rebum. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. Excepteur sint obcaecat cupiditat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Sanctus sea sed takimata ut vero voluptua.Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Nam liber tempor cum soluta nobis eleifend option congue nihil imperdiet doming id quod mazim placerat facer possim assum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi.
    tag1,tag2,tag3
    2/15/2015 8:26:01 AM

Using Feeds and Feeds XPath Parser will do the trick. I would also take a look at Feeds Tamper. I have used it myself in the past and it works very wel!

Here is also a basic tutorial to get you started.

Good luck!


How to display data in blocks of a given size? Is Drupal 8, which is shown in the accordion (module views_accordion) the terms of the taxonomy. By default, the module displays the list. I want to display in the blocks of a given size (as the picture)

In the module folder found twig template views-accordion-view.html.twig with the following content:

{% if title %}

{{ title }}

{% endif %}

{% for row in rows %}
  {%
    set row_classes = [
      default_row_class ? 'views-row',
    ]
  %}
  {# A div wrapping the row content is required for the accordion to work #}

      {{ row.content }}

{% endfor %}

How to change it for my task? Or is there another way?

copy the file into your custom theme folder and change it in the manner you want , then clear the cache and drupal will use the new file instead


one view show nodes and their referenced nodes - both only published I have 2 content types. Question and Answer. Answers hava a entity reference field and contain reference to certain questions.
Now, I want to build a view with listing of questions and number of answers to each question.

So, my view has one field title. Another field title with set up relationship (to show related answers). Filter is set up to show only published nodes and node types of Question and Answer. Query setings - distinct.

Result: I get all questions with all answers. Like this:
Q1 (published)
-someanswer1 (published)
-someanswer2 (unpublished)
Q2 (published)
-someanswer3 (unpublished)
-someanswer4 (unpublished)

Problem: Only Questions get filtered by using filter - published nodes. The referenced nodes - answers are not filtered and are shown all published as well as unpublished.

What would be the best approach to show ONLY published both answers and questions? Thank you

While there might be other approaches, I'd go with Views Field View.

It allows you to use a view as a field in another view. Then just build a view for the answers, taking a nid argument as an entity reference contextual filter. And use that view as field in your question listing view.


How to grey out fields with non editable permission upon node editing? I need the ability to grey out fields with non editable permission i.e. to show certain field values to the user but forbid him/her to edit them, upon node editing.

How can i achieve this?

Form elements have a disabled property you can set as a boolean. For example:

$form['test'] = array(
  '#type' => 'text',
  '#title' => t('Test'),
  '#required' => FALSE,
  '#default_value' => 0,
  '#disabled' => TRUE,
);

Now, you can use hook_form_alter() to check that you're on the right form ($form_id), and any other conditions you require, like for instance checking user permissions, with the user_access() function.


How to loop through a taxonomy vocabulary to find the top category in a nested tree? What I have so far is this

$term=therm_id_that_I_already_have;

$parent = db_result(db_query("SELECT h.parent FROM {term_data} d INNER JOIN {term_hierarchy} h ON d.tid = h.tid WHERE d.tid = $term"));
$term = $parent;

$th=taxonomy_get_term($term);

probably I need a while of something...

I would recommend using taxonomy_get_parents_all(). If you have a vocabylary that looks like:

Vocabulary

Child 1 (tid=1)

Child 1.1 (tid=3)

Child 2 (tid=2)

Then you can do:

<?php
$parents = taxonomy_get_parents_all(3);
$top_category = array_pop($parents);

Will give you the term for tid 1.


Query condition that needs to return true no longer working I'm working on updating our sites to D9. One of our custom modules stopped working and I narrowed it down to this bit of code that modifies some query conditions for a view filter. It's trying to set a condition that always returns true (i.e. 1 = 1).
function views_taxonomy_filter_process_query_conditions(array &$conditions, $field) {
  foreach (Element::children($conditions) as $key) {
    if ($conditions[$key]['field'] instanceof ConditionInterface) {
      $child = & $conditions[$key]['field']->conditions();
      views_taxonomy_filter_process_query_conditions($child, $field);
    }
    elseif (strpos($conditions[$key]['field'], $field) !== FALSE) {
      // We cannot just unset the condition, because this action might create
      // incorrect query. Let's replace it with 1 = 1 condition.
      $conditions[$key] = [
        'field' => 1,
        'value' => 1,
        'operator' => '=',
      ];
    }
  }
}

This worked fine in D8. However I'm now getting this error as it seems to be looking for a column called 1 instead of evaluating that condition:
Drupal\Core\Database\DatabaseExceptionWrapper:
SQLSTATE[42S22]: Column not found: 1054 Unknown column '1' in 'where clause'

How can I change this to restore the old functionality? Thank you!

I found out here that since Drupal 8.7.0 (at least) the field part of the condition can not be an expression.
Since you can't use "where" you must figure out another way to force the condition to always be true. Maybe you could mess around with the operator like this:

Instead of overriding the entire condition, use the "LIKE" operator:
$conditions[$key]['value'] = '%';
$conditions[$key]['operator'] = 'like';

Or if that doesn't work, the "NOT IN" operator:
$conditions[$key]['value'] = array('w00t');
$conditions[$key]['operator'] = 'NOT IN';

Hope this helps you!


What's the data structure that needed by services for posting new node with drupal7 services? I have content type named "shen" and gona to create new node with services module from crawl machine data.

For now, it can login in system and post new node but it can't save image field data.

this is the data It post to services module:

{'body': {'und': {'0': {'value': 'I am Shen'}}}, 'type': 'shen', 'field_shen_image': {'und': {'0': {'new': 1, 'display': 1, 'fid': '541'}}}, 'title': 'just a little title'}

I'm sure lost a little thing and really need your help.

Cheers

Corrected JSON format and tested on my local environment.

{
    "body": {
        "und": [
            {
                "value": "IamShen"
            }
        ]
    },
    "type": "shen",
    "field_shen_image": {
        "und": [
            {
                "new": 1,
                "display": 1,
                "fid": 541
            }
        ]
    },
    "title": "justalittletitle"
}


How to display additional fileds I've added to a page - the way I want them? I've added some additional fields to the content type - Page. But now when the page is rendered it displays all of them as well - just lists them at the bottom of the content. But that's not what I want - I do not want them to display at all, I just want to use them elsewhere in PHP code. There should probably be a hook for this, but I still just can't get my head around the whole thing. Please?

Hiding additional fields is easy, just notice Display Fields tab at the Manage Fields page for the specified content type (page in this case). There you can easily exclude additional fields from being automatically appended to the $content.

In order to show fields the way you want them use themename_preprocess_page hook and check $vars['node'] object for the particular fields.


Need help on a callback function with login form When a user tries to log into my drupal website, I want to check an external database to see if he is registered there. If he is registered in the external db, an account will be created on Drupal when he logs into Drupal for the first time. This is what I currently have to modify the login form to check the second database and create a drupal account for the user if necessary

function converge_form_alter(&$form, &$form_state, $form_id)  {
  if ($form_id == 'user_login_block' || $form_id == 'user_login') {
    $form['#submit'][] = 'converge_convergeAuthenticate';
  }
}

However, this callback function only gets called on a successful login in Drupal. How can I get the system to run the callback function even if the users password and username are incorrect (and create local account if the incorrect password matches external database)?

I also tried the following code to get the custom function called first but it's not working.

 if ($form_id == 'user_login_block' || $form_id == 'user_login') {
    array_unshift($form['#submit'], 'converge_convergeAuthenticate');
  }

function da_form_alter (&$form, $form_state, $form_id) {
   if ($form_id == 'user_login' || $form_id == 'user_login_block' ) {
     if (isset($form_state['post']['name'])) {
       $form['#validate'][] = da_login_validate($form, $form_state);
    }
  }
}

function da_login_validate($form, $form_state) {
  // Here you should check wheather the user is valid or not..
}

Better way to do this: you should read the source code of any module. For example, read the code of Facebook Connect which does the same thing.


Apache solr access protected parameters I wanted to access the keyword being searched in the Apache Solr. Thus i used the hook_apachesolr_process_results Hook to access the $query variable.
But I am unable to access the keyword as it is inside a SolrBaseQuery [params:protected] object.
It throws a error saying Fatal error:  Cannot access protected property SolrBaseQuery::$params
Is there any way of accessing the protected parameters of Apache Solr or is there any other approach to get the keyword being searched.

It's always a good idea to read through the code for a class you're trying to work with.

For example, a quick look through the code yields SolrBaseQuery::getParams(), whose responsibility is to ensure accuracy for, and return, the protected $params array.


Salesforce API module encryption warning I started working on a legacy Drupal 7 site that uses the salesforce_api at version 7.x-2.0-alpha3 (yes, it's ancient). I noticed in the status report page the following warning:

There is a link on the warning that goes to the Salesforce module configuration page, but no real direction what to change to encrypt this properly.

Does anyone know what could be missing from the Salesforce configuration to throw this warning? Is it because the module is so old? That's my suspicion, but after googling around, nothing came up on that warning at all.

This is most likely related to AES encryption on your Salesforce credential data, not the connection itself. From the relevant doc page:

  By default, all Salesforce credentials are stored in the variables table, unencrypted. If this is a problem for you, this module supports encryption via the AES module

When you have the AES module enabled (which it seems like you do), the message you see in your site status report is:

  Salesforce encryption is enabled but not configured securely.

And if AES is not enabled, you see this instead:

  Encryption is unavailable. Using encryption is recommended in order to better secure your data.

Check out salesforce_api_requirements() and salesforce_api_encryption_available() for more. From the logic in the latter it looks like there was an attempt to return more useful information (specifically about the AES module) along with that generic "salesforce encryption" message, but for whatever reason that text never propagated up to what was printed to the screen.


Open node (internal link) in new tab How can I configure programmatically a node object to open in a new tab? I thought maybe in the $node->path array?

I don't see where and how I can achieve this... There is nothing such as a rendered <a> on which I can add a target="_blank".

EDIT (more specific situation):

I've got a content type "news". It is possible to create news in 2 different ways:

An editor user creates manually through the admin interface (basic).
A custom module imports data from external RSS feeds everytime a piece of news is published in it.

I've got a view that display the list of news (just title, truncated text, date, logo...). When you click on a news' title, you access the full node view (normal). If it is an internal news (created manually), it displays normally. If it is an imported news, however, I redirect using drupal_goto to the source of the news (that I saved on node creation).

I want to make this very redirection in a new tab. It's quite complicated because it is originally an internal link (node/nid) that redirects to an external link (http://www.sourcesite.com).

I can make the difference between an imported/not imported node in the hook_preprocess_views_view. But I can't assign it something like a target _blank or whatever it exists to make this node opened in a new tab.

This is a theming question and there's a choice to be made about whether to use a Views or a node template. By and large when displaying entities in views, I tend to use a particular view mode, because then I can display them similarly outside of Views if necessary. To do that:

Choose which view mode to use. In your case use the Teaser view mode, or if that's not an option create a new one.
Ensure your view's configured to display that view mode.
For more info, download and install advanced_help, and read from the Views help at least Row styles and its children Fields and Node.
Check in the node template you're using: is there a variable that would let you add a target attribute to the title link? (There isn't in core node.tpl.php but there might be in your theme.) For more info you can read Overriding themable output and Core templates and suggestions. I'd suggest using devel_themer to see what template is actually used - make sure you've done step 2 first. The template should either be node.tpl.php or start with node-- and end .tpl.php.
If there wasn't a variable in step 3, then modify the template to have one, eg. by adding $title_link_attributes.
Implement hook_preprocess_node(). Check if the node is of the correct type and view mode and modify the variable appropriately. (And if you created a new variable, ensure that you set it to the empty string for other view modes and content types to avoid warnings.) For more info, see Setting up variables for use in a template (preprocess and process functions).

Let me know if you have any questions, or if that approach isn't appropriate for any reason.

Btw I gave a non-JS answer because I thought that was a requirement, but now I'm not so sure.


Get the title attribute into a lightbox frame I've been exploring and getting somewhat close to what I want (getting the value of the title attribute into my lightbox frame) by reading documentation
and this topic here at Drupal Answers.

I'm working with a custom tpl.php file with the following code (copied from elsewhere):

   if($id == 'field_afbeelding') {
            $samples = explode(';', $fields['field_werken_afbeelding_sampl']->content);
            $originals = explode(';', $field->content);
            for($i = 0; $i < count($samples); $i++) {
                print l($samples[$i], $originals[$i], array('html' => TRUE, 'attributes' => array('rel' => 'lightbox')));
            }
        }

From what I gathered in the documentation, it appears that I need to insert the lightmodal[][] array-thing into my code right at the end, where it says array('rel' => 'lightbox').

In the Drupal Answers topic, the question starts off about how to insert a CCK field (or a caption or whatever) into a lightbox, but ends about how to get the title attribute.

The very last comment says - I quote : 'Type
<?php print_r($node); ?>
 in node.tpl.php to see what's available in the node object (what fields, how formatted, etc.) and then take what you want and output it to the lightbox. I hope that's what you need..'

In my case, it's a view, so I went with devel module, going <?php global $field; dpm($fields);?>

Now as for 'take what you want and output it to the lightbox', the problem is I don't recognize out of these clickable Krumo blocks what I need. I do get these Krumo blocks that the devel module shows where you can click in the them and explore those elements/objects/whatever you want to call them.

I've been expanding all of the arrays and been seing 'title' in nested arrays. I guess the question boils down to what exactly must I put in this lightmodal[][] array if I'm right about the lightmodal thing?

And, before you ask, I made sure than in CCK, when editing the image field, I have alt and title attribute checkboxes checked and also given values to the images at hand.

There are multiple issues for Lightbox about your problem. Atm your best chance is indeed to override the relevant tpl.php file. This would be in the form of views-view-field--viewid--fieldname.tpl.php. The variables exposed in there that are of interest are the following:

$output: The processed output that will normally be used.
$row: The raw SQL result that can be used.

The first one indeed contains a string in the form of:

The above should become something like this:

in order to have a caption in your lightbox.

You could of course use a replace function in order to achieve this, such as your attempted solution.

What I recommend is to use the $row variable to obtain the data itself and construct the output however you wish, for instance to add a title in  as well and why not solve the empty alt attribute value issue as well for the sake of SEO:

<?php
  //print $output;
  //dpm($output);
  //dpm($row);
  $caption = $row->taxonomy_term_data_name, // HERE use your field of choice
  print l(
    theme_image_style(array(
      'style_name' => 'thumbnail',
      'path' => $row->field_field_image[0]['raw']['uri'],
      'alt' => $caption,
      'attributes' => array('typeof' => 'foaf:Image'),
      'width' => NULL,
      'height' => NULL,
    )),
    image_style_url('large', $row->field_field_image[0]['raw']['uri']),
    array(
      'attributes' => array(
        'title' => $caption,
        'rel' =>
          'lightbox[field_image][
' . $caption . '
]',
      ),
      'html' => TRUE,
    )
  );
?>


Return table and item-list, but only table is displayed $build['table'] = array(
  '#theme' => 'table',
  '#header' => array('A','B','C'),
  '#rows' => $items
);

$build['itemlist'] = theme_item_list(array(
  'items' => $products,
  'attributes' => array('id' => 'my-custom-listing','class' => 'custom-class another-custom-class'),
  'title' => "Bonieren:",
  'type' => 'ul',
  'container_id' => 'bonieren',
));

return $build;

Above is my code. The problem is that only the table is being shown on callback. Why does it happen?

Your are mixing render arrays and html, use for both table and itemlist the same:

$build['itemlist'] = array(
        '#theme' => 'item_list',
        '#type' => 'ul',
        '#items' => $products,
        ...,
);


Is there a robust, free module for SE-style social signup? I want to enable users to create accounts using existing Google, Facebook etc accounts, without needing to come up with and remember yet another password. Similar to how the StackExchange network does.

There's a proliferation of modules that have related features to these. I'd like to know if there's any one of them which has proven to be stable, robust, simple (requiring few dependencies or possible points of failure) and working without requiring paid subscriptions.

Some modules I've looked at:

I've seen many recommendations for Janrain Social Login, but I read that it's a paid-for service. This site is a very small project and that's beyond its scope. The demos I've seen also suggest that it removes the ability to create a Drupal-only account should the user want to.
I tried the built-in OpenID module plus OpenID Connect, but discovered that it only supports log in, not sign up.
There's a stack of modules built around OAuth (e.g. OAuth Connector). I gather that OAuth is a different protocol to OpenID, and requires dependencies to be installed on the server. In terms of functionality I haven't yet figured out what the fundamental difference is between the OAuth stack and Drupal's built-in OpenId stack, and I can't find any confirmation in the various docs available that it does indeed support signups. It has all the hallmarks of a serious project, though.
There's the connector module - I think this an API module used by the OAuth stack?
Hybrid Auth looks really promising and is my current front-runner: it explicitly supports signup and login, and has minimal dependencies (one open-source library, php-curl, and ctools), and is under active development with a stable D7 release. Sounds great, but I've not seen many recommendations for it, so I'm wondering if there's something I've overlooked.
There's Gigya, which looks like a 3rd-party service with fancy social features that aren't relevant in my case.
There's OneAll social login, which has a promising-sounding description but doesn't appear to be widely used.
There's Social Connect, but it seems to be Facebook only.
...and loads more, including many more 3rd party services and modules for specific providers.

I'd appreciate any expert advice from experience on the simplest stable way to get a sign up screen similar to this:

I used Hybrid Auth . It works well. I tried anothers. They were not so good. Yes,  Hybrid Auth does not have another functionality to share content. But It should not have it. It uses the separated library. It does not use third party services. It's free and independent.

If you tell me your successful experience with another libraries I will be pleased.


Pass raw html to #markup I have some html content, it comes from a external library so i can not change it, it has many <span> and <div> tags with attributes like:
<span style="color: #0000ff;">, but when i use:

$render = array(
  '#markup' => $myhtmlcontent,
);

In a render array, Drupal strips the attributes, and it keeps just <span> without the styles.

So, how can I avoid Drupal changes what I pass as markup, which doesn't need any filter because the library makes it safe, or at last make it allow styles?

Use inline template:

  return [
    '#type' => 'inline_template',
    '#template' => '{{ somecontent }}',
    '#context' => [
      'somecontent' => $somecontent
    ]
  ];

In your case without context, just straight up html.

You can also use the html_tag element for things like script or link and so on.


How get subscribe to user flag on a node I have a node for example news
I have Message module installed
I've enabled the flag subscribe to user

I want people to be able to subscriber to
a user. To get updates on thier latest post.

I want to add the subscriber user flag to the node template for

This is what flag module suggests to do

Placing a flag link on a page

$account = menu_get_object('user');
print flag_create_link('fools', $account->uid);

How would I add this to a node?

You could create a block with a php filter or create a custom template for that node. You can also alter that node from from template.php

http://www.webomelette.com/altering-node-content-it%E2%80%99s-rendered-page-drupal-7


8 - Node::load is generating an object with circular reference which is crashing kint() and var_export() I have a content type with a Taxonomy term which has fields. When I try and load a node (or possibly nodes) of this type I get unexpected results. While debugging with kint() and var_export() I get errors about "circular references". Is this normal in Drupal 8 node structures?

Or is there an underlying misconfig in the content type or taxonomy causing this problem?

Yes, this is normal and by design.

When you want to dump it, just use $node->toArray(). Then you get an array with the plain values. You can use those field names and properties again to access the values on the node object, e.g. $node->yourfield->value.


How to change the field label on my registration form? Drupal 7 On the default registration form, I want to change the Username label to 'Request your username'

I tried putting this in my template.php::

function mymodule_form_alter(&$form, &$form_state, $form_id)
{
    if ($form_id == 'user_register_form' || $form_id == 'user_profile_form') {
        $form['account']['name']['#title'] = t('Request your username');
    }
}

I cleared cache, but didn't see any changes.

Just tested on a D7 site and it should work fine for you if you name the alter function "mytheme_form_alter" instead of "mymodule_form_alter"?

See this answer for more detail on module options: Changing the registration form


How to show terms in a Views in its hierarchical structure? I have create a view to show the terms of the Products vocabulary.

I the view I set:

Format: Html list

Show: field

Fields: Taxonomy term: Name

It works fine but it the hierarchical structure is lost.

The Products vocabulary has this structure:

-Cars

--Ford

--Volvo

-Computers

--Desktop

--Laptop

But in the Views the terms lost the hierarchical structure and are listed like:

-Cars

-Ford

-Volvo

-Computers

-Desktop

-Laptop

What am I missing here??

I would recommend that you give a try to Views Tree module which installs a tree-style (adjacency) Views style plugin which allows you to list vocabulary in a hierarchical way.

Comment: Views Preview does not show the tree layout but normal page display does output as a tree.


How can I query a database created using the previous core version from the new core version? I want to query users, nodes etc in my D7 database that I am currently migrating to D8 to compare with the migrated content.

I want to use custom Drush commands to run some checks.

Is this possible?

You can add external databases in your settings.php file:

$databases['external']['default']= array(
  'database'=>'',
  'username'=>'',
  'password'=>'',
  'prefix'=>'',
  'host'=>'',
  'port'=>'3306',
  'namespace'=>'Drupal\\Core\\Database\\Driver\\mysql',
  'driver'=>'mysql',
);

Then, in a custom module you can query for nodes, terms etc.

// Switch to external database
\Drupal\Core\Database\Database::setActiveConnection('external');

// Get a connection going
$db = \Drupal\Core\Database\Database::getConnection();

$vid = 5; // The vocabulary I want to query
$query = $db->select('taxonomy_term_data', 't');
$query
  ->join('taxonomy_term_hierarchy', 'h', 'h.tid = t.tid');
$query
  ->addTag('translatable')
  ->addTag('taxonomy_term_access')
  ->fields('t')
  ->fields('h', array(
    'parent',
  ))
  ->condition('t.vid', $vid)
  ->orderBy('t.weight')
  ->orderBy('t.name');
$results = $query->execute()->fetchAll();

Switch back to your current db

\Drupal\Core\Database\Database::setActiveConnection();

Save the results to a d8 vocabulary

foreach($results as $result) {
  Term::create([
    'tid' => $result->tid,
    'name' => $result->name,
    'vid' => 'my_d8_vocabulary_name'
   ])->enforceIsNew()->save();
}


Organic Groups Views contextual filter is not working I am trying to make a view in which I have to show images from an image-field of an organic group content type. I have tried for many hours but I am unable to make it work. I am trying to explain the scenario:

I have a venue (organic group) content type. For each venue there is an image field which can hold multiple images. I want to show a list of images that belong to a specific venue. For that I have to make a view so that I can show a list of images belonging to that specific venue. I have used the following path string:

/group/%/images

Now what I want is that for example, I want to visit a "pizza-house" venue, then the path string of the view will be:

/group/pizza-house/images

Now on this page I only want to show images from multiple image-field that only belong to "pizza-house" venue (Venue content type contains that field).  For achieving this, I have tried the following contextual filter and relationships as in shown the pictures but of no use :/

Please help me figure out what I am doing wrong? I am new to contextual filters and  organic groups.
Thanks in advance.

I had a similar issue and it took me hours to finally find this solution:
http://drupaleasy.com/blogs/ultimike/2013/05/sneaky-previously-undocumented-views-feature

I know it's for overriding the title, but it worked for me when I wanted to display a certain content type in a view for a specific group based on what page I was on. I fiddled for quite some time with relationships and different combos. But, all you need is the contextual filter: OG Membership: Group ID with a default value provided (current OG group from context) and specify validation criteria (OG GrouP).

Hope this helps!


Updating of drupal core and modules impossible I have several different drupal sites (all hosted seperately). Some of them run on 7.22, and some of them run on 7.26.

For some reason the update.php script does not seem to work anymore. I can visit the page and it correctly shows the first step: Verify Requirements is shown in green and I see the Overview step. When I press the Continue button the browser starts loading and never finishes. I have tried this a dozen time, every time with the same result. I tried this on the hosted environment and on my home envirentment (installed a backup of the site).

One site is fairly small so I did a clean install of 7.26, installed all the modules, articles, etc. Same result. I am at a complete loss and now unable to install updates of drupal core and modules. Please help.

BTW 1: I use these modules in all of my sites: ctools, ckeditor, imce, lightbox2, views, metatag token.

BTW 2: nothings strange to be found in Apache error.log and php-errors.log

EDIT: Just found out that this is a known issue for IE. Tried this in Chrome and it works fine. Hope others with the same problem find this post sooner than I found the anwer

See https://drupal.org/node/2157815. Don't know how else to close this question...


Getting average of a numerical field across multiple nodes I have a node type with a decimal field on it that saves percentages from 0-100%.

I want to get the average percentage from across all the nodes in that node type. So that no matter how many nodes are created under that node type, I can show the average on a landing page elsewhere using views.

Using drupal 8 and struggling to get this working.

Follow these instructions:

Open your view in edit mode.
Open the Advanced tab.
Find the section named Other
Enable the Use aggregation option
Click on the Aggregation settings option for your desired field
Select Average from Aggregation type select list


What file contains the queries of customized views? I am trying to understand a previous theme in a website and one view shows different results from expected. Then, I want to check whether the query is being generated wrongly or not.

Are there a file in the Views module that contains the queries for my customized views?

Views settings can be exported through the Features module as custom module code. So, if the site is using Features, and the view has been previously exported, then you will find the code inside one of the module files.

In that case, you can use a command line tool like Grep to find the file which contains the view. I would search recursively for the machine name of the view inside your www folder.

If the Features module is not in use, then you can see the view code if you go to the view edit page, then click "export view" in the upper right hand drop down.


How do I make a custom module trigger a function when content is unpublished? In short:

Utilizing Drupal 8, I'm hoping to to "hook" into an entity update event for a specific content type so that I can then take further action when that event occurs. In this case, delete the node if it's unpublished.

In long:

The Scheduler module allows scheduling of nodes to publish and unpublish as scheduled. My goal is to then delete a specific-type node when it gets unpublished.

At first I tried to use the Rules module to trigger removal of the unpublished node. However, Rules is not working properly on my website currently (getting errors when attempting to configure unpublish event node type). It spurs interest to see how I can accomplish the same task with a small custom module. I'm moving forward with a goal to understand Drupal 8 modules and module development better.

As a result, I wish to move handling of unpublish events for my content type into module code. Other examples I'm finding relate to Drupal 7. I'm building a Drupal 8 module.

Here is my starting module code so far (rough, draft, untested as I work out logistics).

Module structure:

hour_helper
  hour_helper.info.yml
  hour_helper.services.yml
  src
    EventSubscriber
      HourUnpublishEventSubscriber.php

hour_helper.info.yml:

name: Hours of Operation Helper
type: module
description: 'Utilities to assist with hours of operation, starting with the removal of hour content once it is unpublished via the scheduler module.'
package: Custom
core: 8.x

hour_helper.services.yml:

services:
  hour_helper.node_subscriber:
    class: Drupal\hour_helper\EventSubscriber
    arguments: ['@entity.manager']
    tags:
      - { name: event_subscriber }

HourUnpublishEventSubscriber.php:

<?php

/**
 * @file
 * Event subscriber
 */

namespace Drupal\hour_helper\EventSubscriber;

use Symfony\Component\EventDispatcher\EventSubscriberInterface;

//!!! use (... something entity or node related, we want to subscribe to entity updates?)

/**
 * Remove hour of opperation nodes after/when they are scheduled to unsubscribe to prevent garbage accumulation
 */
class HourUnpublishSubscriber implements EventSubscriberInterface  {
  /**
   * {@inheritdoc}
   */
  public function getSubscribedEvents() {

    // Subscribe to node update events with priority 0.
    //!!! which event....
    $events[SomethingEvents::SOMETHING][] = array('checkForRemoveStatus');
    return $events;
  }

  /**
   * This method is called whenever the ????? event is dispatched.
   *
   * @param GetResponseEvent $event
   */
  public function checkForRemoveStatus(GetResponseEvent $event) {

    //print '<pre>';
    //print_r($event);
    //print '</pre>';

    die('Well, at least an event has been triggered to be handled here...');

  }

}

I continue to ponder
the Drupal events doc page...

Based on this: My goal is to then delete a specific-type node when it gets unpublished.

You can use hook_ENTITY_TYPE_update.

You will have to just check, if the (not the original) entity is unpublished, and the it's type is the one you are looking for.

+1: From OO perspective you can also take a look on events.


How to tag content from external databases? I have an external database with a couple of hundred rows and columns. Is there a way in which I can tag content while or after I import the database to my drupal 7 website? Is there any module already contributed which could be used for this purpose?

by tagging you mean reference taxonomy terms ?

you could import those rows with the migrate module as nodes, with taxonomy reference (a normal taxonomy field), into your drupal DB.


Unable to add images to content "Image field is required" Developing a new site with Drupal 8, I was attempting to add an image to a custom block. In the editor I clicked the image icon and got a dialog to upload an image. After specifying a file (making sure it was within the upload file size), I got a strange error "Image field is required."

I took the error message literally, and created a new custom block type, adding a field of type "image" to the block. So now in the form, I have a Body and an Image field. If I try to upload using the "image" field below the body, I get the same error "Image field is required."

I tried again using the Content / Media tab, to add an image file, and get the same error:

(I also notice that there's a "Caption" checkbox but no field to enter a caption. I'm assuming I'll have a text field once the image is uploaded.)

Drupal 8.8, all current.

The error message appears to be a red herring. Even though I thought I had fixed the nginx upload file size limit, I found that it was still at the default of 1mb. I fixed the upload limits to be sufficiently large in both nginx and php, and I was able to successfully add media content.


Why do we use "target_id" as the name of the index in php instead of "entity_id"? I'm finding that while I'm coding that I type in things like $entity->field_fieldname['und'][0]['entity_id'] and that this doesn't work.  When the Drupal 7 developers were developing it, why did they select 'target_id' as the index instead of 'entity_id' (or even better, why not try eid? ) I don't know how to contact the Drupal Coders who made this decision, do does anyone know who made this decision?

Drupal 7 has become quite harder to write code in.

Is there a better way for me to be coding that would avoid this problem?

target_id is generally used in entity references.  So if you have an entity reference to another entity the target_id is the id of that entity.  This depends if it is a node or an entity though.  But I will mention that generally you want to avoid $entity->field_fieldname['und'][0]['entity_id'] but instead using the entity_metadata_wrapper to target values instead:

$node = node_load($nid);
$node_wrapper = entity_metadata_wrapper('node', $node);

$mytitle = $node_wrapper->title // Title
$myfield = $node_wrapper->field_my_field->value(); // Value of the field, cleaner

You can also use the set method
$node_wrapper->field_my_field->set("My value"); // If single value

$node_wrapper->save(); // Save my entity


How do I implement a node hierarchy? This may be a trivial question, but I haven't been able to find a clear answer how to do this in Drupal 8.

How can I organize nodes in a hierarchy like this?

Node
- child
- child
- - child
- child
Node
- child

I know about Node Hierarchy and several other modules which seem to offer this functionality, but I haven't found anything for D8.

It would also be good if this would work in a way allowing for listing chilren of a given node (like "In this section:", followed by a listing of child nodes.

Still, this seems like such a must-have ability to me, it's possible that Drupal can do it out of the box and I just don't know about it. Am I missing something?

In Drupal 8 you can do this out of the box. Put a reference field in the parent and target it on the child content type. The label of the field would be "In this section". You can theme the section in a field twig of this specific field, for example field--field-reference.html.twig.

You can nest the entities, but if you reference the same content type and you leave the reference field in the view mode of the child there is a risk of an infinite loop, which will result in a time-out.


Order Total not updating after I change the line item price I have a custom form which on submit creates a new order, loads a product and a custom line item type. I then save the information from the form in the line item. The line item price is updated via a rule which calls a custom PHP function. The problem is when I redirect to checkout/order_id the Order Total is not updated.

I've tried altering the order directly using my order_wrapper and i've also tried using commerce_price_component_add. I tried a rule which called "Save entity" again but nothing seems to be working.

Can somebody give me a point in the right direction on how to get the order total to re-calculate.

Also if anyone has any good examples of creating orders using custom line item types from a custom form that may be helpful

The solution was to use commerce_price_add_component()

    $line_item_wrapper = entity_metadata_wrapper("commerce_line_item", $commerce_line_item);
    $line_item_wrapper->commerce_unit_price->data = commerce_price_component_add(
        $line_item_wrapper->commerce_unit_price->value(),
        'base_price',
        array(
                'amount' => $booking_price,
                'currency_code' => 'AUD',
                'data' => array(),
        ),
        TRUE
);
}


Commerce framework: How on earth do I offer recurring license subscriptions? I'm new to the Commerce framework. My goal is to sell licenses to users (via the commerce_license module). Purchasing a license should grant the user a particular role for the duration of the license.
I need to offer the license in four different versions, described below. I'm struggling to figure out how to accomplish this:

License is good for one year; does not auto-renew ($99/year)
License is good for one year; auto-renews each year (via the commerce_recurring module) ($89/year)
License is good for one month; does not auto-renew ($9.99/month)
License is good for one month; auto-renews each month ($8.99/month)

Can someone please explain to me how to implement this, in straightforward, step-by-step terms? What product types, product variation types, products, product attributes, order types, order item types, etc. do I need to create – and how should they be configured?
(My main problem is that I really don't understand the relationships between these various objects. I've read the docs. I've watched tutorial videos. I've scrutinized ERDs. I've spent hours experimenting in the Drupal dashboard. I've tried to read the code – but it's too convoluted for me. Maybe I'm dumb, but the Commerce framework is extremely confusing and counterintuitive.)
I would prefer to avoid any custom code – I just need the simplest solution that will satisfy the above requirements.
Any guidance ?

Commerce License is in alpha.  That means it is not generally ready for production use.
Further, Commerce Recurring is in beta, but the module page itself notes, as of January 2021:

This module is not production ready! Expect pain.

Using these modules now will require writing custom code and debugging; there is no out-of-the-box easy solution at this time.
However, I needed a license solution today, so I decided to implement one in Commerce without using these modules.  Here's a rough sketch of how I did it.  Note that I am renewing the subscriptions manually, which is prone to human error; the following flow only provides a UI for users to purchase and configure the period of their subscriptions.
However, this example will hopefully give you an idea of the large amount of work involved in getting subscriptions set up.  It's not easy; if you want something simpler but still not easy, and in which the subscriptions actually recur properly, you could look at Recurly or other SaaS.

Add a role, Premium user.  Give this role the additional permissions that users will purchase.
Add a datetime field to the user account, Subscription expire date.  Add another list text field to the user account, Subscription type.
Add custom code to restrict permission for the Subscription expire date field to admins only.
Configure your store + checkout flow in Commerce.
Create a product type "My license."  Add product variations "One year autorenew," "One month," etc.
Add an EventSubscriber to Commerce to automatically set the user account field Subscription expire date when the purchase is complete.  Also, add a redirect to skip the cart because for individual users, having a cart makes no sense for licenses + I don't want users to purchase multiple subscriptions.

Skipping carts requires this patch in composer.json:
    "drupal/commerce": {
        "allow order types to have no carts": "https://www.drupal.org/files/issues/2020-10-05/2810723-130.patch"
    },

Even with all this effort, you will still have to renew the subscriptions manually.  I did this by adding a view for the admin of "expiring subscriptions" and then using the token stored in the user account by Commerce Stripe to make the recurring payment.
Custom EventSubscriber
Notes about this code: It includes an additional field, a list text field on the user account to let the users change between different subscription types.  This allows members to change from a monthly to an annual subscription, or vice versa.
It also assumes that "monthly" subscriptions are always 30 days.
First, services.yml:
services:
  mymodule_subscriber:
    class: Drupal\MYMODULE\EventSubscriber\MyModuleEventSubscriber
    arguments: ['@request_stack', '@logger.factory', '@datetime.time']
    tags:
      - { name: 'event_subscriber' }

And here's the Event Subscriber from mymodule/src/EventSubscriber/MyModuleEventSubscriber.php:
<?php

namespace Drupal\MYMODULE\EventSubscriber;

use Drupal\Component\Datetime\TimeInterface;
use Drupal\Core\Logger\LoggerChannelFactory;
use Drupal\datetime\Plugin\Field\FieldType\DateTimeItemInterface;
use Drupal\state_machine\Event\WorkflowTransitionEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Drupal\commerce_cart\Event\CartEntityAddEvent;
use Drupal\commerce_cart\Event\CartEvents;
use Drupal\Core\Url;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpKernel\Event\FilterResponseEvent;

/*
 * Event Subscriber MyModuleEventSubscriber.
 */
class MyModuleEventSubscriber implements EventSubscriberInterface {

  /**
   * The request stack.
   *
   * @var \Symfony\Component\HttpFoundation\RequestStack
   */
  protected $requestStack;

  /**
   * Logger factory.
   *
   * @var \Drupal\Core\Logger\LoggerChannelFactory
   */
  protected $loggerFactory;

  /**
   * The time service.
   *
   * @var \Drupal\Component\Datetime\TimeInterface
   */
  protected $time;

  /**
   * MyModuleEventSubscriber constructor.
   *
   * @param \Symfony\Component\HttpFoundation\RequestStack $request_stack
   *   The request stack.
   * @param \Drupal\Core\Logger\LoggerChannelFactory $logger_factory
   *   The logger factory.
   * @param \Drupal\Component\Datetime\TimeInterface $time
   *   The time service.
   */
  public function __construct(RequestStack $request_stack, LoggerChannelFactory $logger_factory, TimeInterface $time) {
    $this->requestStack = $request_stack;
    // Specify that logs should be for this module.
    $this->loggerFactory = $logger_factory->get('mymodule');
    $this->time = $time;
  }

  /**
   * {@inheritdoc}
   */
  public static function getSubscribedEvents() {
    $events = [
      'commerce_order.place.post_transition' => 'postPlaceTransition',
      'mymodule_order.fulfill.post_transition' => 'onFulfillTransition',
      CartEvents::CART_ENTITY_ADD => 'tryJumpToCheckout',
      KernelEvents::RESPONSE => ['checkRedirectIssued', -10],
    ];
    return $events;
  }

  /**
   * Set fields and roles for user accounts that purchase subscriptions.
   */
  public function postPlaceTransition(WorkflowTransitionEvent $event) {
    $order = $event->getEntity();

    $order_type = $order->bundle();

    if ($order_type === 'MYORDERTYPE') {
      $price_monthly = 500;
      $price_annual = 5000;
      $subscription_monthly = 'monthly';
      $subscription_annual = 'annual';
      $customer = $order->getCustomer();

      $total_price_array = $order->get('total_price')->getValue();
      $total_price = intval(round($total_price_array[0]['number']));
      $drupal_now_timestamp = $this->time->getCurrentTime();
      $days_in_month = 30;
      $seconds_in_month = 60 * 60 * 24 * $days_in_month;
      $seconds_in_year = 60 * 60 * 24 * 365;
      $subscription_end_timestamp = '';
      // If the user has already purchased, extend the subscription.
      if ($customer->hasRole('subscriber')) {
        $current_subscription_datetime = $customer->get('field_datetime_sub_end')->value;
        $current_subscription_datetime_object = \DateTime::createFromFormat(DateTimeItemInterface::DATETIME_STORAGE_FORMAT, $current_subscription_datetime);
        $current_subscription_timestamp = $current_subscription_datetime_object->getTimestamp();
        if ($total_price === $price_monthly) {
          $subscription_end_timestamp = $current_subscription_timestamp + $seconds_in_month;
          $customer->set('field_list_text_sub_period', $subscription_monthly);
        }
        elseif ($total_price === $price_annual) {
          $subscription_end_timestamp = $current_subscription_timestamp + $seconds_in_year;
          $customer->set('field_list_text_sub_period', $subscription_annual);
        }
        else {
          $this->loggerFactory->error('Total price was outside the assigned range for subscription. (has subscriber role)');
        }
      }
      // Set the date for a new subscription.
      else {
        // The user is henceforth a subscriber.
        $customer->addRole('subscriber');

        if ($total_price === $price_monthly) {
          $subscription_end_timestamp = $drupal_now_timestamp + $seconds_in_month;
          $customer->set('field_list_text_sub_period', $subscription_monthly);
        }
        elseif ($total_price === $price_annual) {
          $subscription_end_timestamp = $drupal_now_timestamp + $seconds_in_year;
          $customer->set('field_list_text_sub_period', $subscription_annual);
        }
        else {
          $this->loggerFactory->notice('Total price was outside the assigned range for subscription. (no subscriber role)');
        }
      }
      $subscription_end_date_object = new \DateTime();
      $subscription_end_date_object->setTimezone(timezone_open('UTC'));
      $subscription_end_date_object->setTimestamp("$subscription_end_timestamp");
      $subscription_end_date_value = $subscription_end_date_object->format(DateTimeItemInterface::DATETIME_STORAGE_FORMAT);
      $customer->set('field_datetime_sub_end', $subscription_end_date_value);

      $customer->save();
    }
  }

  /**
   * Tries to jump to checkout, skipping cart after adding certain items.
   *
   * @param \Drupal\commerce_cart\Event\CartEntityAddEvent $event
   *   The add to cart event.
   */
  public function tryJumpToCheckout(CartEntityAddEvent $event) {
    // $purchased_entity = $event->getEntity();
    // if ($purchased_entity->bundle() === 'training_event') {
    $checkout_url = Url::fromRoute('commerce_checkout.form', [
      'commerce_order' => $event->getCart()->id(),
    ])->toString();
    $this->requestStack->getCurrentRequest()->attributes->set('mymodule_jump_to_checkout_url', $checkout_url);
    // Clear status message "Product added to your cart".
    // @todo fix deprecated code.
    // drupal_get_messages('status');.
  }

  /**
   * Checks if a redirect url has been set.
   *
   * Redirects to the provided url if there is one.
   *
   * @param \Symfony\Component\HttpKernel\Event\FilterResponseEvent $event
   *   The response event.
   */
  public function checkRedirectIssued(FilterResponseEvent $event) {
    $request = $event->getRequest();
    $redirect_url = $request->attributes->get('mymodule_jump_to_checkout_url');
    if (isset($redirect_url)) {
      $event->setResponse(new RedirectResponse($redirect_url));
    }
  }

}


File upload error. Could not I have Drupal 8.4 running on Windows Server 2016, and when trying to use an upload field on a content type I get this error

The file phpC128.tmp could not be saved. An unknown error has occurred.
File upload error. Could not move uploaded file.

I deleted the files folder and IUSR, account PHP is running under, recreated it for this month as expected, but this still errors out. I see the file in c:\windows\temp but it doesn't make it to my site folder. IUSR has full control to the files folder and the 2018-06 folder.

In IIS, the AppPool is running under ApplicationPoolIdentity as well.

Moving the file path from `c:\windows\temp' to another location, and after setting the IUSR permissions on that new folder, it worked as expected!


How to access the administration panel if you cannot login again? I have created a custom theme. I have added the region user account menu in footer, but I forgot to add the region primary admin access.

Unfortunately I clicked on the logout button, and I am not able to log in again. The page at /user/login appears empty. Now how can I access the administration page?

You change your default theme in setting.php.Uncomment this line in your setting.php file

 $conf['theme_default'] = 'garland';


Access_Callback problem From time to time (and anytime after I run "drush cc all") my custom module with an access callback returns an 'access denied' error for Admins when they attempt to edit a user. I can solve this issue by disabling and re-enabling (any) module -- not just the one with the access callback code. If I remove this code, an admins ability to edit a user is fully and permanently restored. Here is the code in my custom module:

function cs_menu_alter(&$items) {
    $items['user/%/edit']['access callback'] = 'cs_user_edit_access';
}
function cs_user_edit_access() {
    global $user;
    if (!user_has_role(3, $user) || !user_has_role(4, $user)) {
        return FALSE;
    }
    else {
        return TRUE;
    }
}

I don't know why this code would suddenly stop working, but I don't really want to lose the functionality that this custom code supplies (most of the time).

I was able to solve for my use case by dropping the secondary function, and just using the following code:

function cs_menu_alter(&$items) {
  $items['user/%user/edit']['access arguments'] = array('administer users');
  $items['user/%user/edit']['access callback'] = 'user_access';
}


Remember users Taxonomy choice, such as which city to filter the site by? I want to convert an existing site to support the selection and association of Cities. Each node can be associated with a City, and the Cities will be selectable as tabs at the top of each page.

Lets say the City Taxonomy is:

All Cities (mainly used for old content the client doesn't want to convert)
London
New York
Paris

If a user browses to any City's front page then that will stamp that city in their cookie/user profile, such as:

site.com/all-cities
site.com/london
site.com/new-york
site.com/paris

Then when the user returns to the site front page site.com/ without a city specified, they'll be redirected to their remembered front page.

The site does not support user accounts however, so only anonymous users will visit, so it only needs to use cookies rather than store data in the DB per user.

Importantly, on top of this, the site is using 1 hour page caching due to relatively low traffic and poor page load speeds, so the redirect will need to run before the cache.

What is there a standard Drupal way to achieve the above, or will it need to be entirely custom in order to run outside any form of caching?

Thanks for any advice!

I would create a custom module and.

Save the choice in the users session (sessions is mapped to a cookie)
Use hook_boot to do the redirect, a simple drupal_goto should be enough.

Using sessions is more simple, but depending on your settings the data will persist for a shorter period of time than cookies. But that might be a good thing.


Use mytheme_preprocess_block() to display HTML (icon fonts) in block titles Unfortunately, HTML commands in block titles are not being rendered. I would like to be able to add icon font symbols to my block titles by adding comands like <i class="icon-envelope"></i> (this is Font Awesome syntax) to them WITHOUT installing yet another contrib module.

Is there a way to let HTML in block titles being rendered by adding a mytheme_preprocess_block() function to my template.php?

I came across a solution to let HTML commands in menu links being rendered by adding
function mytheme_link($variables) {
    $variables['options']['html'] = TRUE;
    return '' . ($variables['options']['html'] ? $variables['text'] : check_plain($variables['text'])) . '';
} to my template.php but haven't managed to modify the code for block titles.

In preprocess_block() function you can only define the title prefix and suffix for each title.

For example:

/**
 * Override or insert variables into the block template.
 */
function YOURTHEME_preprocess_block(&$variables) {

  $variables['title_prefix'] = array(
    '#type' => 'markup',
    '#markup' => '<i class="icon-envelope">',
  );
  $variables['title_suffix'] = array(
    '#type' => 'markup',
    '#markup' => '</i>',
  );

}


How to get the user_picture styled I have a $user and what to get the style image as a URL

originally found this answer How do I access a user image?

but it was not what I was looking for

I have found this to work

Use Drupal\image\Entity\ImageStyle;
$file_uri = $user->get('user_picture')->entity->getFileUri();
$styled_image_url = ImageStyle::load("large")->buildUrl($file_uri);


How to set a validation error via ajax? I am using the formapi to create a form. On one of my fields I have an #ajax call. When the field is changed I call the function. I recreate the form and then replace the whole form on the page. This works fine.

When creating the form I have some logic that sets the form state to see if a field has a value. If it has a value then I show some more fields. If the value is not set then I don't show the fields. I am showing the fields by setting the #access on the field.

I need to add some validation on the form when the ajax call is triggered. I have tried adding the validation using form_set_error() in the function that creates the form and in the ajax callback but the error is not displayed on the screen.

Am I going about this the wrong way completely? How can I get the form error to display?

If the name of your form is modulename_admin_form() then you can add a function modulename_admin_form_validate(&$form, &$form_state).

In that validate function you can form_set_error() from in that validate function.


Access Denied After ERPal Platform Install I've successfully installed ERPal Plaform with a LAMP stack on a fresh install of Ubuntu 12.04 on a VPS, and it goes to the administrative console after install. It's fully functional until I log out. When I log out, I get an Access Denied message whenever I trying to go to the domain it is installed on. I tried to chmod 777 the document root, but that didn't have any effect. Any ideas how I can deal with this issue and get access to the home page?

Currently ERPAL platform is in active development status, and you can use ERPAL platform in full power, like admin user only. As ERPAL platform is based on Drupal, you can configure permissions by yourself on admin pages.


Managing groups of users Please help find the modules that allows me to create the following scenario

Admin can create a User-A
a. User-A will receive an activation email
After activation User-A will be able to:
a. create User-B with another permissions, which will also recieve an activation email
b. create groups of Users-B
c. assign Users-B to the selected group
d. managing and see only Users-B which he created
e. assign content to the selected group
After activation User-B will have access to the content of the group to which he is assigned.

I will be grateful for an any help.

You want to use Organic Groups, and if needed, Role Delegation. I think you can get by with just Organic Groups maybe ... Drupal core can send out notifications of new accounts by itself upon account creation.

Orangic Groups is a contrib module:

  Enable users to create and manage their own 'groups'. Each group can
  have subscribers, and maintains a group home page where subscribers
  communicate amongst themselves.

  They do so by posting the usual node types: blog, story, page, etc. A
  block is shown on the group home page which facilitates these posts.
  The block also provides summary information about the group.

  Groups may be selective or not. Selective groups require approval in
  order to become a member, or even invitation -only groups. There are
  lots of preferences to configure groups as you need.

A synopsis from Role Delegation project page is:

  This module allows site administrators to grant some roles the
  authority to assign selected roles to users, without them needing the
  administer permissions permission.

  For each role, Role Delegation provides a new assign ROLE role
  permission to allow the assignment of that role.

Fully understanding and leveraging these modules to fit your workflow, business logic, etc is a task I leave up to you. Your question is far from simple.


why doesnt Drupal recognize my route name? I have a module I am upgrading  from 7 to 8. I am working on the mymodule.routing.yml file

mymodule.admin:
  path: '/admin/structure/mymodule'
  route_name:mymodule
defaults:
  _controller: '\Drupal\mymodule\Controller\QuicktabsController::adminOverview'
  _title: 'mymodule'
requirements:
 _permission: 'administer mymodule'

Now when I try to enable my module the log shows this error

Uncaught PHP Exception Drupal\\Component\\Plugin\\Exception\\PluginException: "Plugin (mymodule.admin) definition must include "route_name"" at /srv/www/appdocroot/releases/20150428151557/core/lib/Drupal/Core/Menu/LocalTaskManager.php line 161

I assume this error means that the snippet of code from my routing.yml file is the offending piece.

I have gone through the upgrade tutorial on the drupal site and it does not include the  "route_name" field in the section.  I originally tried it without and later put it in when I discovered the error.

Am I correct in my assumption of where the error is coming from?  If thats true what is wrong with my route_name field?

That code snippet looks very strange, is it really like that in your yml file or is it just wrong in the question here?

There is no route_name key inside the definition, and everything needs to be inside the first key, which is the route name. There are plenty of examples in system.routing.yml. Always try to find actual examples in Drupal core and not some online tutorials when you're not sure, as they might be outdated.

Make sure that you always use two spaces for indentation.

Your example should look like this:

mymodule.admin:
  path: '/admin/structure/mymodule'
  defaults:
    _controller: '\Drupal\mymodule\Controller\QuicktabsController::adminOverview'
    _title: 'mymodule'
  requirements:
    _permission: 'administer mymodule'


How to translate a panel page title and a pane title I want to ask if there is a way to translate the title of a panel and also its panes titles whatever content they are. I use panels to override user/%user page and there i putted  as panel title the token "Profile of %user:user-raw" and i have also other content(views,blocks,nodes) with their titles. Thanks in advance.

Latest version of Panels module (7.x-3.4 as today) includes Panels translation module (i18n_panels), which provides a fix for this issue.


Showing Error while insertion of data in database, Drupal 7 I am new to drupal, and i am trying to insert data in database from form using Database API.
But its showing an error. That error is given below:

PDOException: SQLSTATE[HY000]: General error: 1364 Field 'x1' doesn't have a default value: INSERT INTO {members} (first_name, last_name, email, username, password, country) VALUES (:db_insert_placeholder_0, :db_insert_placeholder_1, :db_insert_placeholder_2, :db_insert_placeholder_3, :db_insert_placeholder_4, :db_insert_placeholder_5); Array ( [:db_insert_placeholder_0] => Ravneet [:db_insert_placeholder_1] => Singh [:db_insert_placeholder_2] => rvtsingh@gmail.com [:db_insert_placeholder_3] => rvtsingh [:db_insert_placeholder_4] => 123456 [:db_insert_placeholder_5] => India ) in form_test_form_submit() (line 63 of C:\wamp\www\Biding\sites\all\modules\own\form_test\form_test.module).

The code I used in module file to create code and insert in database is :

<?php
function form_test_menu() {
  $items['formtest'] = array(
    'title' => 'Sign up',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('form_test_form'),
    'access callback' => TRUE,
    );
  return $items;
}

function form_test_form($form, &$form_submit) {
  $form['firstname'] = array(
    '#title' => t('Firstname'),
    '#type' => 'textfield',
    '#required' => TRUE,
  );
  $form['lastname'] = array(
    '#title' => t('Lastname'),
    '#type' => 'textfield',
    '#required' => TRUE,
  );
  $form['email'] = array(
    '#title' => t('Email'),
    '#type' => 'textfield',
    '#required' => TRUE,
  );
  $form['username'] = array(
    '#title' => t('Username'),
    '#type' => 'textfield',
    '#required' => TRUE,
  );
  $form['password'] = array(
    '#title' => t('Password'),
    '#type' => 'password',
    '#required' => TRUE,
  );
  $form['country'] = array(
    '#title' => t('Country'),
    '#type' => 'select',
    '#options' => array('India' => 'India', 'Pakistan' => 'Pakistan', 'USA' => 'USA', 'UK' => 'UK', 'China' => 'China'),
    '#required' => TRUE,
  );
  $form['submit'] = array(
    '#value' => 'Submit',
    '#type' => 'submit',
    );
  return $form;
}

function form_test_form_submit($form, $form_submit) {

  global $user;
    $user = db_insert('members')
    ->fields(array(
        'first_name' => $form_submit['values']['firstname'],
        'last_name' => $form_submit['values']['lastname'],
        'email' => $form_submit['values']['email'],
        'username' => $form_submit['values']['username'],
        'password' => $form_submit['values']['password'],
        'country' => $form_submit['values']['country'],
    ))
    ->execute();

    drupal_set_message("You have registered successfully.");

}

Please help me to resolve this error. Thanks in advance.

Looks like the issue is related to your mysql table member structure. The member table field x1 doesn't have a default value that means you need to serve a value on every insert,  you can solve this in three ways,

Pass the value in the field array Ex: 'x1' => "<value here>",
Add a default value / NULL (based on your requirement) through altering your table

  (ALTER TABLE member CHANGE x1 x1 NOT NULL DEFAULT '') OR (ALTER TABLE member CHANGE x1 x1 NULL)

3.Check your table mode, if the table mode is STRICT change it to SET GLOBAL sql_mode=''; REFERENCE : SQL Mode


Migrating with the migrate module I am using Drupal 7 and the latest Migrate module. I am trying to create a class to migrate products from an OpenCart DB into my new D7 site. I figured out all the SQL I need and got most of that programmed in. But I am having a little trouble understanding how I am going to do the categories.

My migration target is Ubercart.

What I am trying to understand sits in the migrate_example module which is a submodule of Migrate. Specifically I am looking at the wine.inc file at the WineWineMigration class. I am trying to understand the term migration.

I have two lists that will become taxonomy terms in the Ubercart products. First is the categories. I have setup the categories manually, so when I bring the list of those over (using the GROUP_CONCAT SQL func) I will have a bunch of IDs that I will map using an array that will hold all the ID conversions. That is fine, but when I look at their BestWith info that they are migrating it shows that it is using the WineBestWith class above to import the term.

I am confused by this because it looks like some kind of secondary migration of terms. Is that what is happening? Further, is this where I would put my mapping array, in this term migration class?

The next thing I need to do is deal with tags. In OpenCart we have a bunch of free form tags. And when I manually create a product in Ubercart I have an autocomplete field for tags. In that field I can just put in a comma separated list of terms and it creates multiple terms. Can I do the same thing in the Migrate module? Can I just map the field to the list of comma separated terms? Will that add the tags in there for each product?

I'm working on the same problem right now so I understand your confusion.  You have a lot of questions, but I think they can be summed up into a singular question:

  How does the Migrate module handle migrating a normalized database
  into a Drupal installation?

It's definitely not straightforward, but here's my understanding of how it works.  We'll start from the top (WineWineMigration) going down and ask questions as we go.

We start off by looking at the code at the top of the WineWineMigration class.

...
$this->dependencies = array('WineVariety', 'WineRegion',
  'WineBestWith', 'WineUser', 'WineProducer');
...

This tells the Migrate module that in order to migrate your Wine content, the dependent migrations - WineVariety, WineRegion, WineBestWith, WineUser, WineProduce - must be completed first.

So what we've learned here is that migrations can be dependent on other migrations.

Next we have the mapping between the table that currently holds the base wine info and the Drupal node:

$this->map = new MigrateSQLMap($this->machineName,
  array(
    'wineid' => array(
      'type' => 'int',
      'unsigned' => TRUE,
      'not null' => TRUE,
      'description' => 'Wine ID',
      'alias' => 'w',
    )
  ),
  MigrateDestinationNode::getKeySchema()
);

This is pretty straightforward so if you need clarification I will provide it.

I'm going to skip over some interim stuff that isn't really pertinent to hooking up the various categories and wine objects.

Now we get to the field mappings.  Observe:

// Mapped fields
$this->addFieldMapping('title', 'name')
     ->description(t('Mapping wine name in source to node title'));
$this->addFieldMapping('uid', 'accountid')
     ->sourceMigration('WineUser')
     ->defaultValue(1);
// TIP: By default, term relationship are assumed to be passed by name.
// In this case, the source values are IDs, so we specify the relevant
// migration (so the tid can be looked up in the map), and tell the term
// field handler that it is receiving tids instead of names
$this->addFieldMapping('migrate_example_wine_varieties', 'variety')
     ->sourceMigration('WineVariety')
     ->arguments(array('source_type' => 'tid'));
$this->addFieldMapping('migrate_example_wine_regions', 'region')
     ->sourceMigration('WineRegion')
     ->arguments(array('source_type' => 'tid'));
$this->addFieldMapping('migrate_example_wine_best_with', 'best_with')
     ->separator(',')
     ->sourceMigration('WineBestWith')
     ->arguments(array('source_type' => 'tid'));
$this->addFieldMapping('field_migrate_example_wine_ratin', 'rating');
$this->addFieldMapping('field_migrate_example_top_vintag', 'best_vintages');

See where it says:

->sourceMigration(...)

This indicates to the migration that in order to map this field, another migration must be satisfied first.  I believe this is the "secondary migration" that you spoke of.  Let's use the region field mapping as the example here.  Breaking it down...

$this->addFieldMapping('migrate_example_wine_regions', 'region')
     ->sourceMigration('WineRegion')
     ->arguments(array('source_type' => 'tid'));

This says that the category region in the source database is mapped to a region vocabulary term.  As the TIP comment states in the field mappings code chunk, it assumes that mappings are made based on field_names, but since we are dependent on a secondary migration as you put it, we need to specify the migration it is dependent on and instruct it to use tids instead of field names.

So pretty much for every normalized table you have in your source database, you're going to be specifying a migration for each, and then in the relevant field mappings that involve those tables, you'll be specifying dependent migrations in your field mapping calls, as well as the dependent migrations declaration at the beginning of each migration.

I hope this helps.  I don't fully understand this myself so I used this question as an opportunity to enhance my understanding of how Migrate relates databases.  As I learn a bit more I'll update my answer accordingly.


Print image URL with image style I would like to print an image URL with an image-style.
This doesn't work, since I don't have a ".value"-value for the image: How to find image style URL from within twig template?

Is there anything different on field-templates?

My code in field--field-images.html:

{% for item in items %}

{% endfor %}

This doesn't work (results in no filename since .value isn't available:

This crashes the page:

Thanks!

Change the display mode of your field with the image style you want. And it's ok

But If you want do this with a custom module, you can do this:

$imageFile = Media::load($media_mid);
$style = \Drupal::entityTypeManager()->getStorage('image_style')->load('thumbnail');
$imageThumbnailUri = $style->buildUrl($imageFile->get('thumbnail')->entity->getFileUri());


Form api custom validation function doesn't work I'm trying to reuse the login form in my own form. So far so good, everything is populated and shown properly. Now I want to use my validation functions to validate some data, so I tried to add them:

$userLogin = drupal_get_form('user_login');
array_unshift($userLogin['#validate'], 'MY_UBERLEAD_FUNC_validate');
$form['selfservice_ad_tabs']['tab_3']['login'] = $userLogin;

Printing the form shows that the function is in the proper place, but it was not invoked when expected.

I tried several other methods:

$userLogin['actions']['submit']['#validate'][] = 'MY_UBERLEAD_FUNC_validate';

also removing all validation handlers and leaving just mine, but those didn't work either.

Can somebody point what i am doing wrong or explain how i can reuse existing form into my custom form using my validation functions.

Thanks in advance!

I think that if you use drupal_get_form() you can't alter the form because the form will be already built, cached and all the processing done.

Try this instead.

$form_init = array();
$userLogin = user_login_block($form_init);

array_unshift($userLogin['#validate'], 'MY_UBERLEAD_FUNC_validate');
$form['selfservice_ad_tabs']['tab_3']['login'] = $userLogin;


How to delay sending emails using Rules to avoid being considered as a spammer? I created a rule for users, who subscribed on another user to get messages of this user new content:

Events
  EVENT
    After saving new content
Conditions
  ELEMENTS
    None
Actions
  ELEMENTS
    Fetch users who have flagged a user
      Parameter: Flag: subscribe_this_user, user: [node:author]
      Provides variables: subscribers (user)

    Loop
      Parameter: List: [user]
      List item: Current list item (liker)

     Send mail
       Parameter: To: [liker:mail], Subject: New event on [site:name]!, Message: New content [node:title] by..., From: [site:name

How can I send these emails with delay? I heard that sending a lot of emails is spamming. I heard about Rules Scheduler, but don't know how to integrate that in my rule.

Below is a summary of how you can get this to work:

Introduce an additional flag to allow "flagging" these (new) nodes by all users "who subscribed on another user to get messages" (as in your question). Let's assume you label that flag as "eMail notification outstanding" (to indicate that something still needs to happen to send that eMail later on).
Adapt the rule you already have, like so:

Remove the Rules Action "send eMail".
Flag the newly saved content, using the new flag (from step 1) for each of the users you already have in your existing list in your existing Rules Action.

Use the Views and the Views bulk operations (VBO) modules to create a VBO list of all flagged nodes (flagged by the new flag in step 1), sorted by flagging date (oldest first), and limit the results to the first X users only (pick a value for X that fits your needs).
Create a new Rules Component that "loads the VBO list" (from step 3) and add a loop to that rule to perform these Rules Actions:

eMail each of the users in that VBO list (you can probably reuse the Rules Action "send eMail" that you already had, but removed in step 2).
unflag (using flag from step 1) the node (for the user for which you just produced an eMail). This to indicate that the eMail notification was completed (no longer outstanding).

In that same rule, as the very last Rules Action, add an action to reschedule the exectuion of the same rule within Y minutes or hours  (pick a value for Y that fits your needs).
Use the Rules UI to manually trigger the very first execution of that self-rescheduling Rules Component (from step 4.).

Using the above approach, every Y minutes (or hours), Rules will notify X users "as requested".


How do I pull content from a view into an array? I hav a strange task where I need to pull the content from a (well some) drupal view into an array so I can use that data later. I dont want to display contents right away, but I'll need to access it later.

I have already built the view but it was suggested that I can export the view and then create a module to grab the view data but I have no idea how to do that.

Basically what Im doing, is creating a view to pull say, 9 records of node type "blog" and on the front page, I want to pull that view, throw the results into a json array, and then do stuff with it later.

Not sure if it's what you're looking for, but if you're using a template to display that view, you can access an array of the view data by using the php code

$view->style_plugin->rendered_fields;

This will give you an array of everything that the view has returned.


How to sort taxonomy terms by their tid? I'm using a custom module to print taxonomy terms as filters inside a View.

I want to sort the taxonomy terms by their tids not by their names.

The below is from the custom-filter.tpl.php:

<?php foreach($data as $tid => $name): ?>
<div data-filter=".filter-<?php print $tid; ?>" class="cbp-filter-item">
  <?php print $name; ?>
  <?php print $text_counter; ?>
</div>
<?php endforeach; ?>

How can I sort the taxonomy terms by their tids?

Base on your code, I think the key for the $data is tid.

You can just add <?php ksort($data);?> before your foreach loop.


Why I'm having fatal error when adding PHP code to my text format? So I set the text format to "PHP code" and add the following code:

<?php
function f($x) { return $x; }
?>

When I hit Preview, the page dies with Fatal error: Cannot redeclare f(). I have tried this on two separate Drupal 7 sites, one more or less brand new, with the same result.

Is there a step I'm missing to use D7's PHP filter?

I just tracked this down.

What happens is that previewing a node will invoke both the teaser display and full node display, and both of those invoke the PHP code.

My solution was to set the teaser to hidden for the content type (at Structure > Content Types > [your node type] > Manage Fields > Teaser). However, I didn't want to do this for default types like Basic Page, so I created a new type "PHP Tests" and only made the change there.

So I think this shows how PHP in nodes can get ugly, but for people like me who basically want to eval code in the Drupal environment without making a module sometimes, the above is an okay solution.


How to test if current page is an admin page? At some point I started using the following code to test if current page is an admin page:

  $route = \Drupal::routeMatch()->getRouteObject();

  $is_admin = \Drupal::service('router.admin_context')->isAdminRoute($route);

But I found that this fails on node edit pages in hook_entity_load().

How do we test if we are on an admin page in Drupal 8?  Something like path_is_admin() in Drupal 7?

I found that if I test the same node edit page path from outside hook_entity_load, using the code on this page (https://api.drupal.org/api/drupal/includes%21path.inc/function/path_is_admin/7.x) it works.

use Symfony\Component\HttpFoundation\Request;
use Symfony\Cmf\Component\Routing\RouteObjectInterface;

$path = '/node/75/edit';
$request = Request::create($path);

$route_match = \Drupal::service('router.no_access_checks')->matchRequest($request);
$route = $route_match[RouteObjectInterface::ROUTE_OBJECT];
$is_admin = \Drupal::service('router.admin_context')->isAdminRoute($route);

But if I try to add this code in hook_entity_load using the current path, I get a  fatal loop.

I think where I'm stuck is loading the current route in hook_entity_load.

* Updated *

When I first answered this question, node edit and taxonomy edit pages weren't set as admin routes.  So I added separate checks for those.  Such separate checks aren't necessary any more.  The following seems to cover it pretty well:

if (\Drupal::service('router.admin_context')->isAdminRoute()) {
 // do stuff
}

If you want to check a route other than the current route, you can pass it into isAdminRoute().

Note, the above way won't work for node edit pages or taxonomy term edit pages if you uncheck "Use the administration theme when editing or creating content" on the theme admin page at /admin/appearance.  Then you'd need a separate check.

* Original Answer: *

To test if a page is an admin page, you can use a two step process.  Since regex for the node edit may not be using the admin theme.

First I use the isAdminRoute method:

  $route = \Drupal::routeMatch()->getRouteObject();

  $is_admin = \Drupal::service('router.admin_context')->isAdminRoute($route);

Then you can use an additional check for the path to see if it's a node edit page:

  $current_path = \Drupal::service('path.current')->getPath();
  if(preg_match('/node\/(\d+)\/edit/', $current_path, $matches)) {
    $is_admin = TRUE;
  }

Here's a pretty elaborate, but pretty complete way to test for node and taxonomy term edit pages as well as other admin routes:

  $route = \Drupal::routeMatch()->getRouteObject();

  $is_admin = FALSE;
  if (!empty($route)) {
    $is_admin_route = \Drupal::service('router.admin_context')->isAdminRoute($route);
    $has_node_operation_option = $route->getOption('_node_operation_route');
    $is_admin = ($is_admin_route || $has_node_operation_option);
  }
  else {
    $current_path = \Drupal::service('path.current')->getPath();
    if(preg_match('/node\/(\d+)\/edit/', $current_path, $matches)) {
      $is_admin = TRUE;
    }
    elseif(preg_match('/taxonomy\/term\/(\d+)\/edit/', $current_path, $matches)) {
      $is_admin = TRUE;
    }
  }


How do I save patched core after new upgrade? I had to apply custom patch on Drupal 7 core and now I'm afraid that after rolling a new minor-upgrade over, it'll overwrite my changes.

Is there any way for me to preserve my changes even after upgrading to a new minor patch of core (in case that this patch haven't been applied to that version I'm upgrading to ), like creating a patched folder or something and make sure that my core stays operational?

Normally you should never hack the Drupal core. However, there are few exceptions:

you're applying patch downloaded from Drupal.org which has been QA tested,
you're applying patch implemented by people who're extremely familiar with the Drupal code base, development practices, and security model,
you've tested the patch using unit tests (SimpleTest) included with your Drupal core and you properly document the change (e.g. by practicing proper revision control with your code).

If you decide for that, you should keep the patches well documented and ideally in your repository (e.g. one level up from Drupal docroot level, Drupal core folder, or create new patches/ folder for that).

Then each time you upgrade your Drupal core, you need to remember to apply those patches again (this should be part of your Drupal upgrade steps).

To automate this, you've the following possibilities:

using drush command to upgrade your core (e.g. as part of the script):

drush -y up drupal
find . -name "*.patch" -depth 1 -print -exec sh -c "patch -p1 <'{}'" ';'

using drush make, e.g.:

.make file` (see: Full example drupal-org.make file)

api = 2
core = 7.x
projects[drupal][patch][] = http://drupal.org/files/issues/992540-3-reset_flood_limit_on_password_reset-drush.patch
projects[drupal][patch][] = http://drupal.org/files/issues/object_conversion_menu_router_build-972536-1.patch

YAML file (see: examples/example.make.yml)

core: "7.x"
api: 2
projects:
  drupal:
    version: ~
    patch:
      - "https://www.drupal.org/files/issues/add_a_startup-1543858-30.patch"

If you're not working on make files, you can still download Drupal core files into empty folder, this will automatically apply the patch files, maybe consider running some unit test, then replace your generated files into your Drupal core instance.
upgrading and patching manually in Drupal docroot:

curl https://ftp.drupal.org/files/projects/drupal-7.4?.tar.gz | tar xvf - --strip-components=1
patch -p1 < add_a_startup-1543858-30.patch


Views: List content NOT authored by the logged-in user I want to list all the content that was NOT authored by the logged-in user in Drupal 9.
Getting the list of content authored by the logged-in user is pretty easy.

Create a View showing content.
Add a required relationship to Author.
Add a contextual filter User ID and set When the filter value is NOT in the URL to Provide default value User ID from logged in user.

But I'm stumped about how to negate this; I want the opposite (all content not created by the logged-in user).

In contextual filter, scroll all the way down, click on "▾ MORE" and check mark ☑ Exclude