How to compare custom product bundles in Drupal Commerce I am a Drupal Commerce newbie, and would like advice on how to accomplish a particular project requirement.

I have two kinds of products - Panel and Converter. Each project has a mix of those panels and converters. The type and amount of each panel and converter comes from a custom module. Each of these converters and panels have different prices.

I'm supposed to create a view with the top 5 combinations of converters and panels, sorted by price and allow the user to select the one they want, which then goes into the cart.

I hope that all made sense...

Does anyone know of any tools, modules, or methods that I could look into to accomplish this task? I feel like I'm looking for the ability to create dynamic product bundles, that are then able to be put into a view to compare. Is that even possible?

Thanks for the help

NOTE: I am just beginning this part of the project, so if this is easily accomplished with ubercart or some other ecommerce module, I'm open to that as well.

For comparing drupal commerce products check out this module: https://drupal.org/project/commerce_product_comparison

There is also a module available which allows you to create product bundles using products of your choosing: https://drupal.org/project/commerce_product_bundle


Mathjax module does not render on edit ckeditor I have installed mathjax module and ckeditor module, but when I try to insert math code using math button on ckeditor, the math codes does not rendered correctely, math code become hidden. Math code rendered successly after content is submited.

is there anyone can help me to fix?

here my screenshot

Assuming you are using D7, it seems like the solution is in this MathJax issue.  Requires some patching / adding plug-ins to ckeditor.


How can I fix a call to undefined function libraries_load() in GeShi Filter? I just installed GeSHi Filter and had to install the Libraries API for it. When I try to go to configuration settings I get this error:

Fatal error: Call to undefined function libraries_load() in /home/username/public_html/drupal/sites/all/modules/geshifilter/geshifilter.module on line 23

For the moment, I uninstalled all the above modules and its back to normal. Does anyone have any idea on how to fix it?

It appears you tried to use the recommended branch of Libraries API (marked green): 7.x-1.0. Generally, this is a good thing to do, but it can cause problems when modules have dependencies that are still in development.

In this case, Libraries API 7.x-1.0 doesn't the define the libraries_load() function that GeSHi Filter needs. You need to use the latest 7.x-2.x development snapshot.


Boolean field not in CSV views export I have a boolean field (a checkbox) in my user profiles. I have left it with the default settings (1= ticked, 0=unticked).

I have created an CSV export in Views of the user data. All the fields in the user profile work, apart from the boolean value, which is not exported (it just appears as "", for all users). If I look at user profiles however, the box is ticked (or unticked) so the data is there, just not being exported.

How can I get this field to export?

I have managed to solve this - I needed to change the formatter for the field to "Key".


How to create a name-surname structure for taxonomy terms? I have a content type book and it has a taxonomy term reference field: author

I want to enter name and surname separately for each author on node add/edit page. Name and surname together will be the taxonomy term.

If I enter John for the name and Smith for the surname the taxonomy term will be John Smith.

I want to display the author name as surname, name in somewhere and in some other place I want to display as full name [name + surname].

I know I can add custom fields to taxonomy terms and use the Automatic Entity Label module to combine name and surname for term name but I want to create this structure for node form without editing the taxonomy term on taxonomy term edit page.

I was using a method like this but it is useless for this case.

How can I create a name-surname structure for taxonomy terms on node form?

Note: This question is not a duplicate of "How to reference existing term if it exists or create new one if not exist via Inline Entity Form module?" ... even though they use the same image. In this question the main point is how to create a name-surname structure on node form, in the other question "how to combine creating new term and choosing existing one options" is asked.

This definitely worked for me:

Inline Entity Form + Automatic Entity Label + Token.
I added an entity reference field to my content type, pointing to a Taxonomy Term entity and selected "Inline entity form - Single value" as the widget.
What works great is that every time you edit the term from the node edit form, the term's label changes automatigally.

Here are some snapshots.

Add/Edit Node:

Newly created term (vocabulary list):

Node view:

Hope it works for you too!


How to correct term alias? I don’t know why in Drupal 6 some of my parent taxonomy terms have duplicate URLs. For example, I have http://example.com/carrers-0 instead of http://example.com/carrers.
I am not finding any duplicate taxonomy term.

How can I correct it?

Once you had something under that alias, alias is treated as "used" and blocked from reuse.

Search http://example.com/admin/config/search/path (or similar page in 6, if address was changed) and look there for aliases you want. Remove them. Remove aliases with -0. Re-save your node / term / anything. That should do it.


Customized Vertical Menu I am little bit familiar with Drupal but have no idea how to approach this problem. I want to create a menu in the following style with straight continuous lines for each tab.

                  ----- sub1
                 |
    tab1---------|----- sub2
                 |
                  ----- sub3

How can I do it?

use the super fish module. http://www.drupal.org/project/superfish that should do what you need.


How to add a form to $node in hook_node_load()? I want to add a form to a node before it is passed along to the theme layer.

My module has a hook_node_load, as follows:

function gp_shop_node_load($nodes, $types) {
  foreach($nodes as $nid => $node) {
    //Determine if we should process. aka: only run on Record->type() types.
    if (!in_array("product", $types)) {
      continue;
    }

    $nodes[$nid]->gp_shop_order_button = "[BUTTON]";
  }
}

This works: the text [BUTTON] is added to $node if it is type "product";

However, when placing an actual form, it breaks in a Maximum function nesting level of '100' reached, aborting!-error. An endless loop of some sorts. As follows:

    $nodes[$nid]->gp_shop_order_button = drupal_get_form("gp_shop_order_button", $node);

Edit: In the final code, I problably have to wrap this in a drupal_render() even; for now it makes no difference. The relevant line would then be:

$nodes[$nid]->gp_shop_order_button = drupal_render(drupal_get_form("gp_shop_order_button", $product));

And then with the callback-hook for the form.

function gp_shop_order_button($form, &$form_state, $node) {
  $form = array();

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

  return $form;
}

The part about passing along the $nodeis not very relevant and is not causing the problem. Just left it in my examples here, to illustrate that passing along parameters is a requirement.

What am I doing wrong?

Not entirely sure why hook_node_load does not work, but some trial and error (in contrast to the documentation) led me to a working solution using hook_node_view instead.

The example code being:

function gp_shop_node_view($node, $view_mode, $langcode) {
  if ("product" == $node->type) {
    if ($view_mode == 'full' && node_is_page($node)) {
      $node->content['gp_shop_order_button'] = drupal_get_form("gp_shop_order_button", $node);
      }
    }
  }
}

function gp_shop_order_button($form, &$form_state, $node) {
  $form = array();

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

  return $form;
}


db_select query advice I have two content types: development and house.

A development has many houses.

Each house has a house_type field

I'm trying to perform a db_select query that allows me to search all developments and find the house_types attached to them.

I've managed to find the developments, then found the attached houses_on_development (i've used group_concat for this), AND THEN, WHERE I'M STUCK...

I need to query each of the house_types of these concatenated house_ids individually to find out their house_type.

I've started with:

$search_type = 'development';
$query = db_select('node', 'development');
$query->condition('development.status', '1', '=');

 $query->leftjoin('field_data_belongs2dev', 'property',
        'development.nid = property.field_data_belongs2dev_target_id');
$query->addExpression('group_concat(property.entity_id)', 'houses_on_development');

And now i'm stuck.  I know how to write the query to get the house_types if I was querying house_id one at a time but don't know how to fit that query into a bigger db_select.  For this I would use:

SELECT field_property_type_tid
   FROM field_data_field_property_type
   WHERE entity_id
   IN  ( house_id1, house_id2, etc... )

I feel like i'm so close but missing that final bit od knowledge.  Please help.

Think your query needs to be:

$query = db_select('node', 'development');
$query->fields('property_type', array('field_property_type_tid'))
  ->condition('development.status', 1, '=')
  ->addJoin('LEFT', 'field_data_belongs2dev', 'property', 'development.nid = property.field_data_belongs2dev_target_id');
$query->addJoin('LEFT', 'field_data_field_property_type', 'property_type', 'property.field_data_belongs2dev_target_id = property_type.entity_id');
$query->addExpression('group_concat(property.entity_id)', 'houses_on_development');
$results = $query->execute();

Hope this should point you in the right direction.


Get the user id for triggers when deleting a user I have a script that sets up a specific url for a user when they register on a site,

There are no real issues at the moment, but I need to cater for those 'unlikely things to happen that happen 20 times when not prepared for'

Part of this is deleting certain user data when a user deleted (or requests to delete) their account.

I have set up a trigger which at the moment compares the list of uid's with those in the table I wish to delete but this is laborious because every time a user is deleted it has to loop through them all,

What I need is the uid of the user being deleted passed to the trigger so that the trigger than then go directly to the table and delete all user data belonging to uid x.

Is there a method or a way pf programmatically discovering at run time, which uid has been deleted (or being deleted).

The main problem is that the trigger is supposed to be fired after the user is deleted, but it seems to fire beforehand because when I run tests the user data is not removed until the next time, so this is what is happening:

User A is created
User A stores data
User A is deleted
- trigger fired, nothing happens
User B created
User B stores data
User B deleted
- trigger fired User A's data removed, User B's data remains until User C is deleted.

so comparing the user table id's with the id's of the table is useless because until after the user has been deleted their uid is still present in the users table.

Any help or pointers on how to get this uid would help me a GREAT deal :)

Sounds like a job for hook_user_delete():

  Respond to user deletion.

  This hook is invoked from user_delete_multiple() before field_attach_delete() is called and before users are actually removed from the database.

  Modules should additionally implement hook_user_cancel() to process stored user data for other account cancellation methods.

e.g.

function hook_user_delete($account) {
  db_delete('mytable')->condition('uid', $account->uid)->execute();
}


How to skip first row in a dynamic query? I've not yet found the right way to use ->range($offset,$limit) in a dynamic query to skip first result, but without limiting the resultset (LIMIT clause).

The only workaround I've found is to use an high value for LIMIT, for example:

->range(1,99999999);

(see my comment in Drupal API documentation: https://api.drupal.org/comment/49938#comment-49938)

What's the right sintax?

You could do something like this:

// Begin query build
$query = db_select('node');
$query->fields('node', array('nid', 'title'));
$query->condition('type', 'article');
$query->condition('uid', 1);

// Get total count for query
$count = $query->countQuery()->execute()->fetchField();

// Execute range query
$start = 1;
$query->range($start, ($count - $start));
$result = $query->execute();


Duplicate content between multi-sites I'm working on a feature of a Drupal 8 multisite with separated databases for each site trying to implement the following requisite.

When posting news to the main site (all the other sites are subdomains) the user has to have the option to choose other sites where he wants the same news to be available.

I"m starting doing this with a module and hooks, BTW I never worked with Drupal before, and I'm guessing if there is an existing module that could do that.

Would someone recommend a module I could try?

Thanks for any help

On the publishing end, you'd need to categorize the data by site (e.g. use term references). Then expose that data as JSON using the built-in Views module. Allow that view to filter by site, to allow the subsites to select the content it wants to import.

On the consuming end:

There used to be the Feeds module that allowed a Drupal site to fetch data from a source and load that data onto content types on the site. But that module is still in development.
Alternatively, you could build a migration that is triggered in a hook_cron(). Migrate is already in core, I recommend also installing Migrate Plus and Migrate Tools for additional utilities.

In both cases, they would hit the main site at the url that Views is exposing, filter by the site term they want, and consume the JSON it returns.


Updating the block region/pages settings for a NEW views block during an implementation of hook_update_N I have a feature module which provides a view which has a block component.

To keep things simple, the module I'm writing a hook_update for is 'mymodule' the feature which implements the view is 'myfeature', the view which contains the block is 'myview' and the block is just block_1 of that view.

The block needs to be visible in the region sidebar_second
The block needs to be visible only on pages which match users/*
The following is my hook_update simplified:

function mymodule_update_7001(){
 features_install_modules(array('myfeature'));
 drupal_flush_all_caches();
  //Change block settings
  db_update('block')
  ->fields(array(
      'pages' => "users/*",
      'visibility' => 1,
  ))
  ->condition('module', 'views')
  ->condition('delta', 'myview-block_1')
  ->execute();

  db_update('block')
  ->fields(array(
      'region' => 'sidebar_second',
      'status' => 1,
  ))
  ->condition('module', 'views')
  ->condition('delta', 'myview-block_1')
  ->condition('theme', 'mytheme')
  ->execute();
}

Unfortunately it doesn't work, and this is largely because at the point after running drupal_flush_all_caches(); the block doesn't exist in the table yet.

drupal_flush_all_caches() should run block_flush_caches() which should run _block_rehash() against each theme, expected behaviour is that this would cause the writerecord to occur putting the new views block in the 'blocks' table. (if i ran 9 flush all caches followed by a block flush cache and a rehash this would still not work)

I have experimented with varying combinations of these cache flushes to no avail, i have also tried giving 'mymodule' a higher weight.

Bizaarely using the following drush command directly after the update:

drush php-eval "_block_rehash('mytheme');"

causes the block to exist in the database. I have tried using this exact command in the hook_update_n and that did not work.

any advice would be appreciated.

This can be resolved by using db_merge instead of db_update, which effectively updates if it exists else creates the entry.

An alternative line of enquiry would be to look at using one of the new hooks available in the features module. In theory 'hook_post_features_rebuild()' would reactively move the block after the features been rebuilt, and therefore the blocks been created.

http://drupal.org/node/1782492


Why are new users having their role deleted on signup? Today my client added some new users & gave them a role, and checked 'Notify user of new account'. The users clicked the email link, entered their password and all was well - except that the role they had been given had been removed, so they had no useful access.  I've never seen this before, and in replicating it I can see that the role is removed at the point where the new user clicks save on their new password.  I'm  so puzzled by this, as we're at Drupal 7.69 which hasn't changed for a while and I can't see that anythig else has changed.

The problem was caused by the module 'Civigroup Roles Sync'.  Adding the new user with a role that was synced to CiviCRM caused the user's role to be dropped because in CiviCRM they weren't in that group.


node-NAME.tpl.php doesn't override the node template. I've cleared theme registry I'm using Drupal 7.8, and I've tried the same thing I did with Drupal 6, making a custom layout for a node type.

I've copied node.tpl.php, and renamed it node-NAMEOFTHENODETYPE.tpl.php, altered the template, uploaded it to the theme folder.
Surprisingly, Drupal 7 doesn't take it: It shows the default node layout.

Can anyone tell me what I am doing wrong?

You mispelled the filename. Drupal 7 now uses double dashes (--); your file needs to be node--NAMEOFTHENODETYPE.tpl.php.


Facebook scraper ignores default language I have a Drupal 7 setup with an internationalized site. The default languages is English but the content is also available in German. However the site focuses on a German audience. As in Drupal you cannot switch the default languages without messing up all string translations, we have a custom language negotiation rule implemented (hook_language_negotiation_info()) that makes sure if no session or query parameter (like lang=en) is set, the site is shown in German. So, to make it short: If an user accesses our site like this:

http://www.example.com

it will be shown in German. Nevertheless Facebooks open graph scraper scraps the site always in English, as it would add programmatically lang=en to all URLs. How can that be? we have the following language specific meta tags:

<link href="https://www.example.com/node/581?lang=en" rel="alternate" hreflang="en" />
<link href="https://www.example.com/task/581" rel="alternate" hreflang="de" />
<meta property="og:locale" content="de_DE" />
<meta property="og:locale:alternate" content="en_US" />

Does anybody know, what I could do, to convince Facebook open graph scraper to scrape the German version as default?

Without knowing exactly how the following tags are generated I cannot provide the exact solution to your issue, but only to point out what causes the Facebook to grab EN version.

1. <link href="https://www.example.com/node/581?lang=en" rel="alternate"
> hreflang="en" />

2. <link href="https://www.example.com/task/581"
> rel="alternate" hreflang="de" />

Tags 1 & 2 have rel attribute set to alternative, which tells facebook that both links from tag 1 & 2 can be used for fetching info. Therefore it grabs the first one in line.

Each page should have rel="canonical" tag that will tell facebook and all other crawlers, that it is a primary url for that page that should be used for fetching info.

I do not know if you have a link tag with rel="canonical" in your source code, as you only copied a portion of your meta tags. I suggest you check if it is present, and what page version it points to. If it is not present, add it.

Also, meta tag og:url should point to the right version of the page.

<meta property="og:url" content="https://www.example.com/task/581" />

Test your tags by fetching new meta info via Facebook Open Graph Debugger.


Ckeditor changes  tags to  tag Trying to get a button working in content item but ckeditor won't let me.

I tried pasting in source. But when toggling back and forth bewteen source and rich text editor the html changes.

Goes from:

<button>click</button>

To

click

I've tried:

<button>click</button>

Not working either.

This never happened before, a settings thing?

For FILTER HTML go to:

/admin/config/content/formats/filtered_html

add <button> to the limit allowed HTML Tags list.

If you use FULL HTML the button should work.
If not try
go to:
/admin/config/content/ckeditor/edit/Advanced (for Filter HTML)
/admin/config/content/ckeditor/edit/Full (for Full HTML)
Then under Advanced Content Filter, select disabled.


How to filter a node view on a paragraph field I have a content type "Lunch" containing a paragraph type field named "Ingredients". This is a multiple values field which store a prapgraph type named "Ingedients" => Taxonomy term + Quantity
LUNCH
|- Ingredient1 (Term1 reference + quantity1)
|- Ingredient2 (Term2 reference + quantity2)
I have created a view displaying the tiles of my 3 encoded lunches. Until here, everything is fine.
Now, I would like to add an exposed filter to get all lunches congtaining a specific ingredient. For this I have added a relationship on the ingredient field:
Paragraph referenced from field_ingredients

Doing this is fine, because now, I can add an exposed filter using this relationship
AND
Doing this is bad, because as soon as I have added this relationship the number of rows in my view has been multiplcated by the number of ingredients... even if I check distinct in the SQL parameters
Any hint to solve this issue?
EDIT TO ADD: I could solve this by removing the duplicates in hook_views_pre_render but is it really the best thing to do?
REAL SOLUTION BASED ON prkos ANSWER:
1-In the advance>Other section I have enabled the aggregation
2-I have added my Ingredient field in the field section (exclude from display)
=>This is the taxonomy reference field of my Paragraphs field named "Ingedients". In other words, I have a paragraph type with 2 fields  (Ingredient and quantity) and I selected "Ingredient". Do not select the paragraph itself.
3-In the aggregation parameter of this added field, I selected  ID of the entity

Adding Relationships often causes duplicate rows in the results.

You can "remove" the duplicates using the Aggregation in Views (enable it under Advanced).

Then adjust the Aggregation settings for some Fields, specifically the Group column option. You may need to change it from Value to Entity ID or vice versa. The exact combination of settings depends on your particular case, I haven't tried it with Paragraphs.

When duplicates are introduced through Taxonomy reference field that is using a Relationship then all those Taxonomy fields need to have the Entity ID and not the Value.

If the field is a direct Entity Reference field and isn't using a Relatinship then again it needs to be Entity ID instead of, in this case, target_id.

Be careful with Sort criteria when using Aggregation, some of them can mess up the Aggregation. It's best to remove all Sort criteria while adjusting the Aggreation, then when you have it working add them and test that everything is still working as expected.

Some modules offer more advanced Aggregation settings, try looking into that if you need to, for example: Views Aggregator Plus,


File_load for image path errors when empty I need to print the URL of an image in a content type TPL file. I can do this with the following code:

<?php $file = file_load($node->FIELD_NAME['und'][0]['fid']); ?>
<?php print file_create_url($file->uri); ?>

However if the field is empty then I get errors on the screen. I tried only printing the URL if $file had a value:

<?php if (!empty($file)): ?>
  <?php print file_create_url($file->uri); ?>
<?php endif; ?>

However im still getting the errors if the field is empty. I understand that it is the first line of the code which creates the variable that is causing the issue. How can I rewrite this to not cause errors?

By the way im a themer not a back-end developer so if there is a more 'themer friendly' solution that would be my preference.

Found the answer here: http://www.drupalden.co.uk/rendering-drupal-7-fields-custom-node.tpl.php-templates

<?php
// field_my_image is the name of the image field

  // using field_get_items() you can get the field values (respecting multilingual setup)
  $field_my_image = field_get_items('node', $node, 'field_my_image');

  // after you have the values, you can get the image URL (you can use foreach here)
  $my_image_url = file_create_url($field_my_image[0]['uri']);

  print $my_image_url;
?>


How do I assign different colors to each serie of a Google bar chart I'm using Charts module to create some charts using the API. Depending on some variable i can create a pie chart or a column chart.

That variable is chart_type:

$chart_type = 'column';
$chart_type = 'pie';

This is the code I have:

$chart = array(
    '#type' => 'chart',
    '#title' => 'title',
    '#chart_type' => $chart_type,
    '#chart_library' => 'google',
    '#legend' => FALSE,
    '#tooltips' => TRUE,
    '#height' => 234,
    '#colors' => array('#006400', '#c11d0b'),
);

$chart['Status'] = array(
    '#type' => 'chart_data',
    '#title' => 'title',
    '#data' => array(500, 100),
    '#show_in_legend' => FALSE,
    '#show_labels' => FALSE,
);

$chart['xaxis'] = array(
    '#type' => 'chart_xaxis',
    '#labels' => array('Good', 'Bad'),
);

$my_chart['chart'] = $chart;

return drupal_render($my_chart);

When the chart is of type Pie, I can see the two colors (green and red) correctly assigned to the slices of the pie.
However, I can't assign the same principle to the column chart - in this case, both bars are green.

What I need is to have the colunn chart with the first bar green and the second one, red.

EDIT: Also, on the pie chart, I get two circles and I want to get rid of them. I thought it was a legend but it's not so... how can I remove them also?

It's hard to tell (without access to your site) what's causing your issue. But here is a working sample of a chart using the Charts API (disclosure: I'm a co-maintainer ...):

<?php
  echo '<p>&nbsp;</p>';
  $chart = array(
    '#type' => 'chart',
    '#chart_type' => 'column', // pie, bar, line, column, area, scatter
    '#chart_library' => 'google', // Allowed values: 'google' or 'highcharts'
    '#title' => t('Meals by store'),
   '#colors' => array('#006400', '#000064', '#640000', '#c11d0b'),
  );
  $chart['store1'] = array(
    '#type' => 'chart_data',
    '#title' => t('Store 1'),
    '#data' => array(16, 11, 13),
    '#suffix' => ' Meals',
  );
  $chart['store2'] = array(
    '#type' => 'chart_data',
    '#title' => t('Store 2'),
    '#data' => array(12, 14, 17),
    '#suffix' => ' Meals',
  );
  $chart['store3'] = array(
    '#type' => 'chart_data',
    '#title' => t('Store 3'),
    '#data' => array(9, NULL, NULL),
    '#suffix' => ' Meals',
  );
  $chart['store4'] = array(
    '#type' => 'chart_data',
    '#title' => t('Store 4'),
    '#data' => array(5, 10, 20),
    '#suffix' => ' Meals',
  );
  $chart['xaxis'] = array(
    '#type' => 'chart_xaxis',
    '#labels' => array('Breakfasts', 'Light Meals', 'Sandwiches'),
  );

  // dpm ($chart);

  $example['chart'] = $chart;

 return drupal_render($example);
?>

If you have the (dangerous) PHP filter enabled, just paste it all in the body of node, and see what happens (make sure you have a working internet connection if you use the Google library).

It should show 3 column charts (1 for each type of "meal"), with each chart having up to 4 columns (1 for each "store").

BTW, make sure you're using the most DEV version (I'm using Version: 7.x-2.0-rc1+5-dev).


Feeds module will not unpublish old feeds how can I have the Feed Importers, from the Feeds module, delete or remove feeds after it updates them with a new RSS feed.
Right now it will refresh feeds but not delete or unpublish feeds that are not in the xml file.

I am looking to solve the same problem. So far the best I have found is a patch for the Feeds module: http://drupal.org/node/1240366

EDIT: That was a poor answer, because I did not test it. Also there is a long discussion in the "Sync or Cache mode" issue: http://drupal.org/node/661314 . Posts #114 and #119 have the two leading solutions (and #114 is more sophisticated).


Drupal + Simpletest + Class Autoloading = FALSE? Just a quick question which I couldn't Google : is class autoloading not "enabled" when running tests using SimpleTest?

I'm using the Drupal SimpleTest module, and I'm trying to instantiate a class which I have defined in files[] (in the .info) file. However, I just keep getting a message saying that the class could not be found.

I assumed that all "autoloadable" files for the module I was testing would indeed be automatically loaded, but this seemed to be wrong.

I needed to add the following function to my testclass:

public function setUp() {
  parent::setUp('mta');
}

Please note that 'mta' is the module I'm testing, and which the "autoloadable" classes are defined for. I assume that if you need access to "autoloadable" classes defined for any other module, that you need to set up those modules too.


How do I modify the output of iframes generated by Media oEmbed module? I'm trying to add a title attribute to all iframes outputted by the D7 media_oembed module with Youtube videos, but can't find the write entry point for it. There aren't any templates with the raw structure to override.

Can someone point me to the right place please?

The HTML is being generated by the YouTube oEmbed API.

If you inspect the themes/media-oembed.tpl.php template & the theme preprocess include themes/media_oembed.theme.inc, you can see that  media_oembed_get_data() looks up the plugin which pulls the data from the API. In the returned data, the html element is used to fill the $content variable in the template.

The module provides a few different means to hook into retrieval/process/display of the data:

hook_media_oembed_request_alter($parameters, $plugin, $url) can be evoked to alter data before plugin retrieval.
hook_media_oembed_response_alter($embed) can be evoked to alter data after plugin retrieval.
hook_preprocess_media_oembed(&$variables) can be evoked before processing the template for display.

Whatever means you use, it looks like you'll need to manipulate the HTML string directly to add the title element to your output.


Creation of a Grid/Matrix using views in Drupal 7 Does anyone know of a good way to automate the creation of matrix/grids/tables like this?

Basically what I'm trying to accomplish is to create a grid that can show links to other nodes  based on an entity (or node) reference.

There could be many of these grids on the site so I'm trying to figure out an automated way to create them (i.e. go to a page like /grid/1/3 and the 1/3 tells the page what columns and rows to pull in - and then based on references how to fill the grid)

It's a little confusing to get across what I mean but hopefully it's understandable.

There is a module for that - if you are using Drupal 7 check this:
Views Responsive Grid


Output node reference field data in page.html.twig I have a homepage node-type in which I have an entity-reference field holding 3 references to 3 separate custom blocks.

The theme I'm working on requires that my 3 element reference field needs to be output in page.html.twig. I have overridden page.html.twig and I can see changes I have introduced once my caches are cleared.

My research led me to implementing a custom module to preprocess my homepage ouput and include the data I want printed from page--front.html.twig, code below:

function mymodule_preprocess_page(&$variables, $hook) {
    // $url_obj = Url::fromRoute('<front>');
    die('tested');
    dsm($variables);
    drupal_set_message('testing');
}

My problem is my preprocess function is not triggered. The module is enabled, and calling die() outside a function does "kill" the site, so the module file is recognized.

I would appreciate any help.

Module names are all lowercase or underscore. Your preprocess function name must start exactly with the same name as your module/theme. Never uppercase.

function mymodule_preprocess_page(&$variables) {
  ...
}

And there is no $hook parameter in this case, the _page function name suffix already declares this function as a specific hook only for the page hook type.


how to remove quicktabs extra url I have a quicktabs on my homepage. When the tabs are clicked the url of homepage changed to like this:

http://www.example.com/home?qt-homepage_tab_menu=0#qt-homepage_tab_menu
.
.
.
What should I do if I only want to have http://www.example.com when any tab is clicked?

Thank you!

I believe that could happen if you have a Javascript error on your page, or that you have Javascript disabled in your browser. For the former, open the error console (Ctrl+Shift+J in Firefox and Chrome) and try to figure out what might be causing it.


22762 rows in my session table. What does this mean for the site, and what should I do about it? Ok so the title is pretty self explanatory. There's thousands of rows in the session table. I see that the Persistent Login module is enabled. I don't know if this affects how the sessions are stored. Also, I note that 100+ users are quoted as being visitors at any one time, which seems very excessive for the user base and niche content of this site.

Please can someone advise the best course of action here? I assume I can truncate this table locally, but what's the long term action plan look like?

The long term action is to limit session lifetime.
Look for the following line in your settings.php:

ini_set('session.gc_maxlifetime',   200000);

This parameter sets session life time, after which session is marked as garbage and will be deleted by garbage collector.
Average session life time (not on drupal sites) is much less than 200000 seconds  - something between 15 minutes and half an hour (900-1800).
So, if you don't need long sessions, you can reduce ini_set value and thus get less sessions stored in the sessions table


Drupal 7 search through block content This is my problem:

I used views module to create several blocks of one content type and displayed those blocks in one basic page. My client would like to have that page included in search results when he searches for some word from those blocks.
Seems like Drupal's core search module indexes only content from pages, not content from displayed blocks.
Is there some module that I could use, which would index block's content too?

I don't know if it will help you, but the way I solved a similar problem was by using Google Search, which indexes the rendered page.


Programmatically uploading and validating a user_picture I use the following code to modify the image in the user_picture field of user with uid 42:
// Get user.
$user = \Drupal\user\Entity\User::load(42);

// Create file.
$file = file_save_data(
  file_get_contents('/tmp/image.jpg'),
  'public://pictures/image.jpg'
);

// Set file.
$user->set('user_picture', $file->id());

// Save user.
$user->save();

It works great, but it's very simplistic and doesn't do any of what has been configured in /admin/config/people/accounts/fields/user.user.user_picture, e.g:

Validate "Allowed file extensions".
Possibly downscale based on "Maximum image resolution".
Save image in the "File directory" location.
Validate "Maximum upload size".

Is there a way to somehow upload and set the file through what has been configured in the field?

You can access the values of the image field settings with:
$user->getFieldDefinition('user_picture')->getSettings();

Which will return an array, example:

You then can use file_save_upload
and you can pass to it for second param, an array containing all the validation functions

array $validators: (optional) An associative array of callback
functions used to validate the file. The keys are function names and
the values arrays of callback parameters which will be passed in after
the file entity. The functions should return an array of error
messages; an empty array indicates that the file passed validation.
The callback functions will be called in the order specified in the
array, then the hook hook_file_validate() will be invoked so other
modules can validate the new file.
 source: https://api.drupal.org/api/drupal/core%21modules%21file%21file.module/function/file_validate/8.9.x

Here are the validation functions you can use:

Source: https://api.drupal.org/api/drupal/core%21modules%21file%21file.module/8.9.x


Guide on How to Load CSS File Per Role I'm looking for the simplest solution to allow a custom CSS page to load per role. I have to the CSS pages done, but just need to load them and ensure they are only loaded based on user role.

I'm guessing it should be about three lines of PHP to go at the bottom of the template.php, but not sure what the code should be. Any advice?

Thanks.

With relation to the answer and my comment below, tried the beneath code unsuccessfully using the bamboo theme

function bamboo_preprocess_page(&$variables) {
  global $user;

  if (in_array('testtest', $user->roles)) {
    drupal_add_css(drupal_get_path('theme', 'bamboo') . '/roleedits.css');
  }
}

If my code wrong or is it a problem with the theme?

(for the record I did create a role called testtest.)

The error I get is:

Fatal error: Cannot redeclare bamboo_preprocess_page() (previously declared in E:\Test\sites\all\themes\bamboo\template.php:231) in E:\Test\sites\all\themes\bamboo\template.php on line 385

NOTE: Both the solution below work. I just accepted the one I used. However both have been tested and work fine, just the second solution offered me more flexibility to call roles again in future.

Add the next code to you template.php

/**
 * Implement hook_preprocess_page().
 */
function THEME_NAME_preprocess_page(&$variables) {
  global $user;

  if (in_array('DESIRED_ROLE', $user->roles)) {
    drupal_add_css(drupal_get_path('theme', 'THEME_NAME') . '/YOUR_CSS_NAME.css');
  }
}


How to have a field with a select list widget and custom list entries? In my content type there is a text field that is set using a list (combobox).

When adding new content, the list is displayed with static elements.

I would like to query an external site when the user adds content (or edits the page) and then build the list from the query result. The user can then select from these elements.

Is that possible?

For Drupal 8

Yes, is possible, but you will need to implement your own field type.

You should take a look into the Country module as you will need to implement the OptionsProviderInterface interface.

In the getPossibleOptions method, you will query the external site and get the possible options for your field.

For Drupal 7

You can always take a look inside the Examples module even for Drupal 8 you will find a very useful boilerplate code for your projects. If you want to check another example just go to the Countries module.


How can I do with Views and Drupal 7 what the Views Or module does in Drupal 6? I'm trying to find a way to do in Drupal 7 what the Views Or module does in Drupal 6.
I read that this module (or at least what it does) has been migrated to the core Views 3 module.

How can I do the same thing as on this picture (marked in yellow) within Drupal 7 Views 3?

In your views filter area it is possible, Click re arrange if existing filter there, other wise configure it on adding new.

In the following window you can configure the or or and, between fields and filter group


Hide or show fields based on whether the node is published I'm looking to show and hide form fields based on the current progress of a node using contributed modules like Workflow, Maestro or rules.

For example, I would like to show certain fields if a post is published and hide those same fields if it is in draft.  I would like to avoid writing a custom module if possible.

Is there a simple way to interact with the Drupal 7 FormAPI to show and hide fields based on the status of a node using Rules, Workflow, Maestro or other contributed modules?

Also, is there an easy way to modify 'select lists' produced with the FormAPI using any of the noted plugins?

You might be able to piece something together using Conditional Fields, but a custom module (using hook_form_alter()) would definitely be the recommended path here, because it sounds relatively custom.

Conditional fields are simply hidden using JS, while it sounds like you might need to make it so people can't access the fields (so, #access property = FALSE) on the edit form in certain situations.

Rules doesn't have much integration with content editing forms; but you could probably set some field to a different value if the status of a node is changed from draft to published, or something like that, which could trigger something with Conditional Fields... but I think doing it in a custom module would be better in this case, and would definitely be more robust.


How to use views replacement patterns while using the PHP filter? In views, when using the standard text formatter you can place replacement tokens such as [title] into the HTML code either in a rewrite or in this case global text for Drupal to render.

In this case I have a node field with the Machine Name field_story_url that is used within a view. Part of my PHP function requires me to define the content found in that field so I do $urlhere= '[field-story-url]';within a Global Text header using the PHP filter input.

But it does not work. I then did a simple <?php echo '[field-story-url]'; ?>to see if it would print the value and nothing either.

When I did the replacement using just HTML it worked. Anyone know what the issue may be?

Figured it out. When using replacement patterns within the PHP filter you simply use double quotation marks over single ones.

i.e: $urlhere= "[field_story_url]"; over $urlhere= '[field_story_url]';

Looks like the double quotes is what allows Drupal to see the replacement tokens outside of the PHP code.


Is Drupal suitable for that kind of ecommerce? I have to do website that sells webinars and I want to use D7 to this job. Unfortunately I have never done any Drupal ecommerce before.

I'll have to kind of users:

Teacher
Student

Payment method: PayPal only

Webinar content type:

Title
Description
Start date (every webinar length is 60 minutes)
Places
Price is the same of all webinars and is specified by Admin
Webinar booked at least 7 days before start costa less (discount and days limit  configurated via admin area)
If a webinar is cancelled need option to move the participants/users into a new webinar

User of role Teacher can add/edit/list his Webinars.

In addition Teacher can create group with fields:

Topic
Description
When Teacher is creating new webinar, he can specify group for this webinar (select list) (not mandatory)

Student (auth user) can buy single webinar or group. When buying group discount is bigger.

Every webinar can repeat and has multiple start date. Setting next start date must generate different ID for webinar for invoice

If do it by plain PHP database structure will look something like:

groups

id
topic
title

webinar

id
group_id
title
description
etc

webinar_date

id
invoice_id (maybe webinar id + webinar_date id)
webinar_id
date

Teacher can see list of his webinar with dates, so if webinar has two dates it must be visible in two times in list. Also info about free places of webinar must be and income from bookings of webinar. After choosing webinar Teacher can see list of all users that buy webinar 'ticket'.

The same is for admin but he can see all webinars of course.

Is this possible to create in Drupal without a lot of pain?

Which module are most suitable for this: Commerce or Ubercart?

Thanks in advance

Yes it is possible, most of which using Rules, Fields, Date and Views. I'd say that, due to the specificity around some features, Commerce would be best as it fully taps into the Entity API which makes developing a breeze.


Difference between views handler and views plugin? What are the main differences between view handlers and view plugins?

I checked the documentations for view handlers and view plugins, but I find them quite similar.

Can anyone show me what a view handler can do that a view plugin cannot?

The difference is summarized in the first sentence on About Views plugins:

  In Views, a plugin is a bit like a handler, but plugins are not directly responsible for building the query. Instead, they are objects that are used to display the view or make other modifications.

A view handler is implemented using a class derived from the views_handler class, which has methods to build the query, or to alter the result obtained from a query, such as:

views_handler::get_join()
views_handler::pre_query()
views_handler::sanitize_output()
views_handler::post_execute()
views_handler::placeholder()

On the other hand, the views_plugin class has only a method that is related to the query: views_plugin::query().


In a tableselect form element with '#js_select' => FALSE, how can I re-use the column header for a label? I have a pretty ordinary tableselect element that looks like so

$form['registration_table'] = array(
    '#title'=>"Register",
    '#type' => 'tableselect',
    '#header' => $header,
    '#options' => $enrollment_options,
    '#js_select' => FALSE,
    '#multiple' => TRUE,
);

What I would like is to be able to use the empty space which is reserved for the "select all" checkbox for a text label. I would like to indicate by the label what action the checkboxes represent. In this case they represent selecting a course to register for so I would like to add the label "Register" there. Any advice on how to do this?

For doing this you have to change the "theme_tableselect" core code. See this documentation code part. If you do not set "select all" then the header is assigned to null


how to make previously entered values appear for multistep forms after validation errors so evidently if I turn a form into a multistep form:

  if(!isset($form_state['storage']['step']))
    $form_state['storage']['step'] = 1;

and do form_set_error() in validate

when the validation error appears, the values that I previously put in would disappear.....

so If I enter a value into a textbox in a multistep form then hit continue then validation error appears, the textbox will now be empty instead of being filled with my previously entered values as it would happen normally

is there a way to prevent this from happening without manually reentering the default values for every form element?

fyi I'm using drupal 6

I was bitten by a similar case in a multistep form scenario, though in my case it was use of the "Previous" button that didn't preserve user entered values.

Initially I was under the impression that D7's form_builder() would automatically merge user data in $form_state['values'] back into the '#value' property of the form elements on previous step's subform, but this never happened!

After reading carefully through examples module, form_example/form_example_wizard.inc, I realized that I had to use:

'#default_value' => !empty($form_state['values']['my_elem']) ? $form_state['values']['my_elem'] : '',

on all form elements that I wanted to "remember" their user input!


Restrict vocabulary on entity_autocomplete form field targeting taxonomy terms I'm creating a form with an entity_autocomplete field targeting taxonomy terms, and I would like to restrict it to a certain vocabulary. Is there a way to do that with '#selection_settings'? I can't find any example.

This is the code I am using.

$form['p_cat_ac'] = array(
    '#type' => 'entity_autocomplete',
    '#title' => t('Product Category'),
    '#target_type' => 'taxonomy_term',
    '#selection_settings' => [
        'include_anonymous' => FALSE,
    ],
);

The vocabulary is the taxonomy term's bundle, so you just have to add a target_bundles array to the #selection_settings entry. In my case the desired vocabulary ID is 'category'.

$form['p_cat_ac'] = array(
    '#type' => 'entity_autocomplete',
    '#title' => t('Product Category'),
    '#target_type' => 'taxonomy_term',
    '#selection_settings' => [
        'include_anonymous' => FALSE,
        'target_bundles' => array('category'),
    ],
);


What other files belong in the root site folder? My employer maintains a server for several Drupal sites. They inherited these sites without having much expertise in Drupal. I'm more front end than back end so my knowledge of hosting is limited. My question relates to the folders that reside in the root folder alongside the Drupal site folders. I could tell that some folders didn't belong, such as 'backups' and 'libraries'. I moved those folders and there was no problem. (By the way I verified that some of these files could be called up in a browser.) There were two remaining folders I am not sure about. The 'logs' folder has server logs but the individual files cannot be called up in an anonymous browser. Does anybody know the rule as to where server log files belong and how to secure them? I do not see an htaccess file in this folder, BTW. The other questionable folder is a folder labelled 'internal', and it has database stuff in it, such as an 'aspnet_client' folder.  I'm afraid to just move this file even though the content is several years old with no recent changes.  That tells me it's not important, but I'm wondering if any server people can tell me this folder doesn't look right, it was probably stored there by mistake at one point as a backup.

Thanks in advance for your help.

The simple answer is: none. The public files folder is an area Drupal uses to store files. It shouldn't be manipulated manually or by non-Drupal processes (unless you're configuring an advanced workflow, really know what you're doing, and can accept the risk that Drupal could theoretically annihilate any "extra" files it finds as it has write perms).

If you're certain the folders you're talking about aren't managed by Drupal, and you don't need the contents, you can assume they're safe to delete.

Obviously you'll need to perform sanity checks to ensure other processes outside of Drupal don't rely on them first. Hopefully your infrastructure is documented (if not, now's the time to start)

FYI You can check whether individual files are managed by Drupal by interrogating the file_managed table.


Node ID is missing in contextual filters The node ID is missing in the view contextual filters.

How can I use the node ID as contextual filter?

In the screenshot you show, it's Identifiant (ID), the third rown of the Contenu category (Catégorie in the screenshot).

Since the context filters have a category, the node ID is simply called Identifier or ID. There isn't any possibility to confuse it with other IDs, like the user ID, because other IDs have a different category. You cannot even confuse it with the revision ID (Identifiant (ID) de révision) or the UUID (Identifiant universel unique (UUID)).


Image module custom image style changes image link I am using Drupal 7.32, and I enabled the Image module.

I have created a custom "Image Style" so that I could add Bootstrap 3 "img-responsive" class to my image in my view, but adding that custom style to the image field for my view causes Drupal to change the URL where the image is placed and then not resolve the image.

This is the "Image" styles user interface. Notice at the bottom I added my own custom style.

This is is my custom image style definition.

This is my Image field in my view. Here I set the Image style to my custom Image style that I created.

This is the view displaying the content for that view. It is not resolving the images because it is changing the title to http://localhost/system/files/styles/center_block_responsive_image/private/images_content/news/latin.america.night_.jpg?itok=1yvjqDtY. This would resolve but it is adding styles/center_block_responsive_image/private to the URL for the image, when the URL should be http://localhost/system/files/images_content/news/latin.america.night_.jpg?itok=1yvjqDtY.

The content type's image field saves the image to the private file system.
Does anyone know why the Image module would rewrite the image like this? I have a default image that I am using for each piece of content.

The image resolves for the default content type, despite the fact that it is also adding styles/center_blow_responsive_image/private to the URL, as in http://localhost/system/files/styles/center_block_responsive_image/private/default_images/elaw.jpg?itok=BpkGqQJ-.

If I change the "Image Style" on the view field back to "none" it retrieves the image just fine.

Does anyone know why the Image module is adding this extra text to the URL which causes it to not resolve properly?

I found a fix by adding

$conf['image_allow_insecure_derivatives'] = TRUE;

to my settings.php file

I found the solution from this drupal stack exchange posting:
Drupal 7.20 Image Styles return a url with Access Denied

I'll hold off on accepting my answer here as the accepted answer for a bit in case someone informs me that I should not be solving the problem this way.


Rules Fetch entity by property using fixed User Role Versions
Drupal 7
Rules 2.9
Problem
I am trying to loop through all users with a given role. I am trying to pull the users using the action "Fetch entity by property" with property "User Roles" But the value does not allow me to enter a static role. It forces me to select some available variable using tokens. If I enter a static value and save it returns a validation error.
How do I set the property to a static role?
Note the role is not the same as the user creating the node.
Rule
I would include a serialized copy of the rule but frankly none of the rest of the rule matters. Roughly:
Trigger: node create.
Condition: node is published.
Action: Grab all users with editor role.
Action: loop through all users and send e-mail or add to a nodequeue (havn't decided which yet).
More info
The documentation seems to indicate I should use "direct" input mode. However that option does not appear to be available on this form. Am I missing something? is this maybe a bug?

Answering my own quesiton. I guess I should have found this sooner. But writing it down here helped me process the vocabulary I needed to search for.

I do indeed need to switch to direct input mode. In fact if you switch to direct input mode it will give you a list of roles to select. However direct input mode is not available on initial creation.

To fix simply save as some value (I used site:user:role). Then edit the rule again and direct input will be available. It appears to be a bug listed here: https://www.drupal.org/node/2168961

Thanks and hope this helps someone else.


How to display fetched data in the form of html table? I have created a custom module & used below code to display data from Database. But I want to show that data in the form of html table. Please help.

<?php
function custom_table_menu(){
 $items = array();
 $items['custom_table'] = array(
  'title' => 'Custom Table',
  'page callback' => 'custom_table_page_display',
  'access callback' => TRUE,
);
 return $items;
}

function custom_table_page_display() {
$result = db_query('SELECT * FROM {users}');
  $records = $result->fetchAll();

  $content = '<pre>' . print_r($records, TRUE) . '</pre>';

  return $content;
}
?>

Try this example to output your data in table format with Pager (ie. table with page. 1,2,3.. )

function custom_table_page_display() {

  $header = array(
    array('data' => t('Name'), 'field' => 'id', 'sort' => 'desc'),
    array('data' => t('Address'), 'colspan' => 3),
  );

  $query = db_select('users', 'u');

  $query->fields('u', array('name','address'));  // select your required fields here

  $table_sort = $query->extend('TableSort') // Add table sort extender.

                      ->orderByHeader($header); // Add order by headers.

  $pager = $table_sort->extend('PagerDefault')

                      ->limit(20);  // here you can limit the number of data per page.

  $result = $pager->execute();

  $rows = array();
  foreach($result as $res) {
    $rows[] = array($res->id,
                    $res-> title,);
  }
  // If rows are not empty theme and display the rows.

  $output = '';

  if (!empty($rows)) {

    $output = theme('table', array('header' => $header, 'rows' => $rows, 'attributes' => array('id' => 'sort-table')));

    $output .= theme('pager');

  }

  else {

    $output .= t("No results found.");

  }

  return $output;

}


How to disable PHP files from being run in the sites/default/files directory? By default does drupal 7's sites/default/files directory disables running of PHP files?

By default, when you site is created a .htaccess files is put in your sites/default/files directory (or wherever your public files are) and your private directory (if defined).  See file_ensure_htaccess() and file_create_htaccess() for the details.

The first line of each should read

SetHandler Drupal_Security_Do_Not_Remove_See_SA_2006_006

This is an Apache directive that resets how it handles the files in that directory, and all subdirectories.  Basically, it resets the handler to a non-existent function, which prevents files from being executed.  See SA-2006-006 - Drupal Core - Execution of arbitrary files in certain Apache configurations security advisory for more info.  I have double checked this on a few of my servers, and this does prevent PHP from being executed.

If this line is missing, then you need to figure out what happened and how it was removed.

If this not preventing execution by Apache, then you need to look at your server configuration.  It is also conceivable that PHP may be executed here from the CLI via some server exploits.


Translating contextual filter nid value On a multilingual site, the function named language_negotiation_get_switch_links($type, $path) looks up the content translation and enables user to switch to parallel content if available.
What if the path comes from Views with contextual filter being the node ID? Say, in English it'd be en/news/197 but in German de/nachrichten/198. Drupal/Views tend to leave the contextual filter untouched and produces invalid criss-cross paths such as de/news/197. There seems to be no way to translated the value into one that belongs to a given translation set.

Is there? Or maybe I'm approaching the problem in a wrong way...

The key was using two functions: drupal_get_normal_path() and i18n_get_path_translations(). Inside hook_language_switch_links_alter() you can modify the href attribute of each language switcher.


Drupal Commerce Hook - Extra validation before adding to cart I was looking for a hook that will fire after a user hits the add to cart button.
The commerce api isn't very clear about this.

What I'm trying to is:
Add an extra validation for a customized product (date field).
So basically I want to interrupt the adding to the cart process and proceed if validation is ok, and lead the user back if not.

Thanks!

Seems like hook_commerce_cart_product_add is what you're after. I couldn't find any examples for preventing the line item being added to the cart but at the very least you should be able to use drupal_goto to interupt the process. You might also want to look at the Rules events\actions provided by Commerce.


Passing a single two word value into contextual filter that allows multiple values I have a contextual filter set up to allow multiple values, and it filters the view on the city. so if I pass in "new york", the view will look for "new,york" which will not return any results. If I pass in "new york,chattanooga" the view looks for "new york,chattanooga" which will give me the results from new york and chatanooga. Lastly, if I pass in "new york, "(notice the space), the view will give me the correct results.

Is there a way to get the view to not act this way? I.E. Allow me to do views_embed_view('places_to_stay', 'block', "new york");? Thanks!

in your case I think you need to separate values with plus-characters. so it would be:

views_embed_view('places_to_stay', 'block', "new york+chattanoog");

Because you have a single argument expecting multiple inputs.

in some other cases you might use the comma separator if you have multiple arguments each expecting a single inputs.


Facetapi: Rewrite facet machine names? I am working on a website with facetapi + search_api, with some facets for taxonomy term references.

One of my facets is getting the machine name field_xyz_parents_all or field_xyz:parents_all, which in the URL this becomes field_xyz%253Aparents_all.

I want this facet to replace the older facet with machine name field_xyz, so that old URLs still work. So I would like to change the machine name or url query key of the new facet.

Any idea how to do this?

One idea I have would be to implement hook_entity_property_info_alter() and define my own entity property with the desired machine name, overwriting the existing entity property field_xyz. I imagine this would work, but it somehow seems wrong, because in other places I might want to keep the original meaning of this property. Ideally I would only change the facet query key, not the property.

EDIT: The original intent I had with this was to change the facet alias used in the url. However, changing the question to clarify this would make it a "chameleon question". Hence, I don't.

For completeness: If what you need is to change the facet alias, not the machine name, then the FacetAPI Alias module seems to do exactly this.

If you also consider using facetapi_pretty_paths, this issue might be interesting: Is facetapi_alias compatible with facetapi_pretty_paths ? (compatible, overlapping functionality, compliment one another?)


Custom SQL: nodereference joins and latest VID I'm having a heck of a time constructing a custom SQL query.  The query has multiple nodereferences and needs to return the latest node revision.
I understand joins pretty well, but for some reason the added complexity of returning the latest revision is tripping me up.

I would prefer to go this route over creating views and executing them programmatically, just because of the complexity of the WHERE clauses.

I've tried translating the output of an equivalent View, but the prefixing that Views tacks on is making it a huge chore to comprehend.  My instinct is that it shouldn't need that many joins either.

Would love to see a generic structure that people might start with, or for conversation's sake here's a massively simplified version of what I'm working with.  This version is in a bit of flux, I think I have the latest revision covered but now person1Name, person2Name aren't returning anything.

SELECT event.nid AS eventnid,
       event.field_event_date_value AS date,

       event.field_event_person1_nid AS person1Nid,
       person1.field_person_name_value AS person1Name,

       event.field_event_person2_nid AS person2Nid,
       person2.field_person_name_value AS person2Name,
FROM {node} n

LEFT JOIN {content_type_event} event
    ON n.vid = event.vid

LEFT JOIN {node} refevent
    ON event.vid = refevent.nid

LEFT JOIN {content_type_person} person1
    ON refevent.vid = person1.nid

LEFT JOIN {content_type_person} person2
    ON refevent.vid = person2.nid

LEFT JOIN {node} refevent
    ON event.vid = refevent.nid

LEFT JOIN {content_type_person} person1
    ON refevent.vid = person1.nid

LEFT JOIN {content_type_person} person2
    ON refevent.vid = person2.nid

This looks wrong. Instead, you probably want to use event.field_event_person1_nid and 2 instead of refevent.vid. The additional join of node shouldn't be necessary, you already have node as the main table.

The query still returns something because you are using LEFT JOIN. Since I assume that these fields are required and/or you only want those which are filled, you should just use JOIN. LEFT JOIN means that the main table is returned even if there is no matching row in the joined table.

The same is true for the content_type_event table. No need for a LEFT JOIN. That is just what views does by default unless you specify that the relationship is required.


How can I determine which module is associated with a field plugin? I'd like to implement an entity hook, and act on all fields defined by Computed Field FieldType plugins.  So I either need a list of all FieldType plugins provided by the module or need to know which fields are associated with it in order to know which fields to work on (or avoid).  Is this possible?

I'd rather not hard-code the list of plugins (computed_string, computed_decimal, etc.) because new ones could be added later, and then the list would have to change.

And I can't use computed_* because another module, Computed Field Plugin, defines its own field type with that prefix, and I don't want to touch it.

I was expecting something like FieldDefinitionInterface::getDefiningModule(), but that doesn't seem to exist.

For those interested, I'm working on adding support for computed cardinality.

The answer to the question title should be straightforward. You can get the extension from plugins via getProvider(). So you could make a list of all FieldType plugins or get the provider of a specific field type directly from the plugin defintitions:

$module = \Drupal::service('plugin.manager.field.field_type')
  ->getDefinition($field_type)['provider'];

For field definitions this is a bit more complicated. Field storages have this method as well, but for configured fields it always returns the module field. This is not what you want. But there is a different place. When creating field storages the provider of the field type plugin is stored in the property module. So starting from FieldDefinitionInterface you should be able to get the module name:

$module = $field_definition->getFieldStorageDefinition()->get('module');


Clearing or changing styles with the TinyMCE WYSIWYG editor in Drupal 6 On the TinyMCE tool-bar you can select a style to apply to the selected text (from a list of CSS classes that you create). However if I want to change to a different style, when I select a new style form the drop-down list, it just adds another class so the text ends up with having multiple competing classes attached.

Is this the normal behaviour - does any one else get this?

Does ayone know if there is a way to clear all styles on the selected text?

Edit I'd thought that the optional Remove Format button (below) would do remove styles.

Actually, turns out it doesn't - not in the version I'm using, anyway.

So it seems re-clicking on the styles that is already selected in the dropdown is the only way to deselect them, short of writing a custom plugin.


how to call handler on every ajax request I have created a handler for every submit request using $form['#submit'][] = 'MYMODULE_form_submit_handler' now the problem is this doesnt works on Ajax submit, or page call backs functions. i want to log everything that is happening on every insert,update/delete in admin area
$form['button'] = array(
    '#type' => 'button',
    '#value' => t('Save'),
    '#attributes' => array(
        'onclick' => 'return false;',
        'class' => array('form-submit', 'rights-form-submit')
    ),
);

Where 'rights-form-submit' is a class that directs this button to AJAX call from javascript. i want to call hook on success / failure of request

Setting a form element to type button prevents submit handlers from being executed. You'll need to change the type to submit if you want your submit handlers to be called.


How can I redirect node page for a content type to custom URL? I need to redirect all the pages for a content type to a custom URL in Drupal 8.

I used to do this in Drupal 7 by implementing hook_init() with the function drupal_goto() or by using the Rules module. Unfortunately both hook_init() and drupal_goto() are removed in Drupal 8, and the Rules module is not stable yet, and I can't figure out how to do it in Drupal 8.

How can I achieve what I am trying to do?

Here is how I managed to solve this issue, based on the example in drupal.org/node/2013014:

I registered Event Subscriber in my_redirect_module.services.yml file:

   services:
     my_redirect_module_event_subscriber:
     class: Drupal\hbmsu_redirect\EventSubscriber\MyRedirectModuleSubscriber
     tags:
       - {name: event_subscriber}

and then in the file my_redirect_module/src/EventSubscriber/MyRedirectModuleSubscriber.php

I added this code:

  namespace Drupal\my_redirect_module\EventSubscriber;

  use Symfony\Component\HttpFoundation\RedirectResponse;
  use Symfony\Component\HttpKernel\KernelEvents;
  use Symfony\Component\HttpKernel\Event\GetResponseEvent;
  use Symfony\Component\EventDispatcher\EventSubscriberInterface;

  class MyRedirectModuleSubscriber implements EventSubscriberInterface {

      public function checkForRedirection(GetResponseEvent $event) {

          $baseUrl = $event->getRequest()->getBaseUrl();
          $attr = $event->getRequest()->attributes;
          if(null !== $attr &&
             null !== $attr->get('node') &&
             $attr->get('node')->get('type')->getString() == 'my_content_type') {
              $event->setResponse(new RedirectResponse($baseUrl.'/some_internal_url_path'));
          }
      }

      /**
       * {@inheritdoc}
       */
      static function getSubscribedEvents() {
          $events[KernelEvents::REQUEST][] = array('checkForRedirection');
          return $events;
      }

  }

in checkForRedirection function, I'm checking if the page is for a node with the content type my_content_type, then redirect to the page mywebsite.com/some_internal_url_path


Change article date format I'd like to change the date format that is used for articles in Drupal 8. It looks like it uses the Default medium date format by default. I added my own format at admin/config/regional/date-time, but I  can't find where to edit the format that articles use.

Is there a way to do this from the CMS or does this need to be done in code?

So after spending more time than I care to admit looking into this, I've come up with two solutions to this.

Solution 1

One way to do it is with the date function that darol100 mentioned in his answer. Modifying his example for my case, in my node--article.html.twig file, I changed:

{% trans %}Submitted by {{ author_name }} on {{ date }}{% endtrans %}

to

{% set createdDate = node.getCreatedTime|date('j F Y') %}
{% trans %}Submitted by {{ author_name }} on {{ createdDate }} {% endtrans %}

The advantage to this approach is that it's easy and quick. The disadvantage is I'm not using Drupal's built-in date format system.

Solution 2

In order to use Drupal's date format system, I first created my custom format at admin/config/regional/date-time. Then I edited node--article.html.twig as follows:

{% set createdDate = node.getCreatedTime|format_date('my_custom_format') %}
{% trans %}Submitted by {{ author_name }} on {{ createdDate }} {% endtrans %}

This assumes I named my custom format "My Custom Format", which results in the machine name my_custom_format.

While this solution requires an extra step, I feel it's the more Drupal way to do it.

I learned about it on this page about Drupal's Twig Filters.


JSON Menu Link Without Invoking Init Hooks? Our Drupal site utilizes a number of menu hooks to return JSON from an API we manage in a separate Web API. We also have a number of intensive tasks that happen on each page load via the hooks_init in several custom modules.

The issue we're facing is that the tasks in hook_init are only required for actual pages, and should not be executed when all we want is JSON output. Is there a way to ONLY execute the hook_menu endpoint, and no other Drupal code?

We have several pages that make 3-4 requests to Drupal JSON menu links, which means that we also run our unnecessary hook_init tasks 3-4 times as well -- plus once for the actual page request.

There must be a way to circumvent the usual Drupal pipeline to perform these actions?

Here is an example of one of our JSON menu hooks:

function membership_details()
{

    // Get membership details from API, and return as JSON
    $details =  sendCurlResponse(/* ENDPOINT */);
    drupal_json_output($details);
    drupal_exit();
}

hook_init() is invoked before the menu system deals with the request, and in the confines of a normal Drupal bootstrap, no, it's not possible to circumvent that workflow.

It's by design though, if you look at the docs:

  Perform setup tasks for non-cached page requests.

  This hook is run at the beginning of the page request. It is typically used to set up global parameters that are needed later in the request. When this hook is called, the theme and all modules are already loaded in memory.

Emphasis mine.

So for its intended use, hook_init should only set up variables that are required for the current request. Whether that be a request for HTML, JSON, or whatever else.

You have two pretty reasonable options as far as I can tell:

Augment the code you have in hook_init implementations to check whether it should be executed based on parameters from the request (accepted content type, file extension, whatever makes the most sense for you use case).
Move the logic in hook_init to another hook, one that's invoked later in the process (I can't really say which hook that would be without knowing what the code does)


Template for custom content type I created a module which creates a content type called equipment. Which includes multiple fields and a field collection. But now I want to style the template with those fields. As suggested from the HTML comments thanks to the Twig debugging, I created a file called node--equipment.html.twig which is located inside the templates folder of the module. Unfortunately this template won't show up, so it shows the default template.

Doesn't Drupal 8 recognize the Twig file? What is the reason for not showing the wanted template? How can I fix this?

To recognize a suggestion in a module, you need to explicitly specify it in hook_theme() of your module.

system_theme() for example has this:

// Normally theme suggestion templates are only picked up when they are in
// themes. We explicitly define theme suggestions here so that the block
// templates in core/modules/system/templates are picked up.
'block__system_branding_block' => array(
  'render element' => 'elements',
  'base hook' => 'block',
),

Copy the original definition and then change the key and set the base hook.


View calc and multiple field collection lines I came here because I have a problem with view calc module and several lines in my field collection. So first the result of my view look like this :

All this fields are in the same content type, and I put sum calculation on each fields. But it's seems the value of the field is multiplied by the count of lines in my field collections. So for the first sum(Montant HT) the calcul done is :

8600 + 51600 + (3101.26 * 5) + 2962.99 + (42000 * 3)

For the column paid sum I don't know how the sum is calculated I doesn't understand.

I tried to use distinct but it didn't work, so how can I found the right sum for all my column ??

Thanks

Finally, I found a way to make it work. Although, maybe it's not a good solution but it worked.
Here is steps:

Find file views_calc_table.inc in views_calc module directory.
Change if ($query_alias == 'unknown') { to if ($query_alias ==
'unknown' || $field->field_info['type'] == 'field_collection') { in
line 238 under function add_aggregation_fields(&$view)

Remind，never hack core!


Chosen library not working I installed chosen module and the library v1.8.3.

Jquery update is 1.10

Libraries is installed and enabled as well.

I get this error on the console when I try to use a select list with chosen:

Uncaught TypeError: this.selected_item.off is not a function

Does anyone know how to solve this?

I guess the Chosen library version 1.8.3 (released Jan on 22 2018) is a little bit too far ahead of the Chosen module version 7.x-2.1 (released on Mar 23 2017).

Replace the library by an older release (preferably version 1.1.0) and it should work.

From the Chosen module's README.txt:

-- INSTALLATION --

  1. Download the Chosen jQuery plugin
  (http://harvesthq.github.io/chosen/ version 1.1.0 is recommended)
  and extract the file under sites/all/libraries.
  2. ...


How to know Active sessions in Drupal? Is there any way to find my opened/active sessions and close them in Drupal?. Like in Gmail, If there already exists a session for the logged in user they can be notified like the follows and they can close all active sessions of them except the current session.

  open in 1 other location - Details

Similarly as an Admin I would like to view active sessions for all users. I know that all sessions are stored in sessions table. I can retrieve them by creating a custom module. But I wonder is there any module available for this

There exists a module for that called Active Sessions

Active Session is a module that allows a user to see if there is more than one session opened for their user and allows them (with permissions) to end other sessions belonging to their user. There is also an interface where a user with permissions can view all active sessions and close them.
Active Session creates a block that, by default, is placed in the footer of the page for users with 'view own sessions' or 'view all sessions' permissions to see and get more details about the sessions.

Images from module page


including new field to views_nivo_slider I created a slideshow using views_nivo_slider, with two fields, one content: image, and content: description. and I want the description field to be used as a description for the image in slide, but the problem is that description field doesnt work with nivo slider, it's not changing with the image, and I only have some static description fields.
thanks

The issue here is that the views_nivo_slider only accepts three values: an image, a link and a title, and therefore doesn't have anything inside it to display another field/description.

Now, if instead what you are saying is that the title isn't showing up with the image, then you need to go into Views' Row Style: Views Nivo Slider configuration and tell it what field you want to use for the title.  You do that by clicking on the wheel/gear widget thing to the right of that and then select from the menu.


Best option to extend user profile If I want to add a new tab in the user profile page, let's say /user/%user/resume, should I create a new node type and render it in this tab, or should I declare a table describing a résumé per user, develop add/edit/delete forms and render them in this tab ?

For now, I implemented the second options and I am wondering if it would be easier to do it with the Field API by mapping my SQL table to an entity so that I don't need to create all those add/edit/delete forms. So I have a page callback for /user/%user/resume selecting everything necessary in the resume table and rendering the selected informations with a template.

The sub-question would be : should I always map my SQL tables to entities to benefit the Field API functionalities ?

Thank you,

with Drupal you should never have to deal directly with tables and add/edit/delete forms again - Drupal does it all for you.
In your case you could either extend the user profile and add a "resume" field or you could add a "resume" content type and use the reference module to reference it to the user.


Add inline styles/JS from fields to My site contains nodes which require different styles (and the occasional inline JS script) and the ability to adjust these styles through the interface rather than via code. These styles are currently implemented via a Code-only text field using <style> tags, which is not ideal. However for systemic reasons I can't place these node-specific styles in individual libraries.

How can I extract the contents of specific code-only fields and reposition this content as inline styles in the <head> of the page? I understand that this is not the preferred Drupal way, however I need a solution.

You could do this with a preprocess function. The code here works for full views only (it won't work e.g. in a view of multiple teaser nodes).

function THEME_preprocess_html(array &$variables) {
  $router = \Drupal::routeMatch();
  $node = $router->getParameter('node');
  if (is_numeric($node)) {
    $node = \Drupal\node\Entity\Node::load($node);
  }
  if ($node instanceof \Drupal\node\NodeInterface) {
    $variables['node_object'] = $node;
  }
}

Now you can use {{ node_object }} in your html.twig.twig, e.g.:

<html>
<head>
  {% if node_object %}
    {% if not node_object.field_css.isEmpty %}
      <style>
        {{ node_object.field_css.value|raw }}
      </style>
    {% endif %}
    {% if not node_object.field_js.isEmpty %}
      <script>
        {{ node_object.field_js.value|raw }}
      </script>
    {% endif %}
  {% endif %}
  ...

And yes... don't try this at home kids ;-P


Token Value to insert URL of page into field I am trying to create a webform to appear at the end of all my site pages that asks if there is anything about the page that should be improved.  This is dumped straight into the page.  In order for this to make sense I need to be able to record the url the form was shown on.

I tried to dump these tokens into the default value for a field

%nid
%title

but they output the nid of the webform not the page it is dispayed as a block on.

If the user is logged in I can use

%server[SCRIPTNAME]

which works but almost all my users won't be logged in.

Is there a way I can get this information into a field on my form?   Otherwise my feedback for is useless.

you can use form alter .get the values from url put the values using form alter to default fields .


How do I construct an authenticated HTTP request in Postman? I have Drupal 7 installed locally on my computer with the domain set to http://drupal.local.

I am trying to prepare an external script in PHP or Python (or even in pure Bash using curl, if it does not require a lot of extra work), which will successfully execute an HTTP request by default available only for the logged in user.

To understand what such a HTTP request should look like, I am first trying to perform such a HTTP request using Postman, but all my attempts failed.

This is what I've done so far:

In the browser, I logged in as administrator of the Drupal 7 site
I opened the browser on http://drupal.local/en/node/add/article and I received status 200 (The page is displayed correctly in my browser.)
In Postman I set:

request method on: GET
URL: http://drupal.local/en/node/add/article
Headers: I set all headers identically to those in the browser including the current cookies containing the session key with its value

I don't have access to this page and I receive a 403 error

How do I construct an authenticated HTTP request in Postman that will work for Drupal 7?

You can make use of Token authentication but be careful:

From module description:

  Be careful with what paths you expose to Token Authentication, as it is effectively a very simple, very low security password mechanism. You can expose Administration pages through bad configuration.

Install / enable Token authentication Module.
Go to admin/config/services/tokenauth
Add the path you want to give access to with token.

in the example below i added all add content pages.
Go to admin/people edit the user you want to generate token.
Generate Token by clicking on Token authentication tab it will give a token for that user like ?token=tuvj7cMwauxStWGVQYfo.
Then you can use it with postman.

Note: it may not be the best way.


How to display a specific field instead of Title with Entity Reference I Have two entities.

**Students**
Title
Body

**Cours**
Title
Body
CoursRefNumber

I can associate many Cours for each students.
To do that, I create a Entity Reference on Cours for student.

When I create a new Student, I see al the Available Cours List.
Instead of showing Title In the Listbox, How can I display the CoursRefNumber .

Thanks a lot.

If you edit your entity reference field you'll see an "Entity Selection" fieldset section. There is a "Mode" field in there that defaults to "Simple" which just lists the entity titles.  You can change that to "Views" which lets you use a custom View to display the selection.

You'll want to create a View first. Just create the View to display the fields you want.  That could be the Cours Title and CoursRefNumber if you want.


How to get children and parent book pages I have nid of a book page. I need the nid of the parent and nid of all direct and indirect childs.

How to retrieve the parent and child IDs?

This is for Drupal 6 but might also apply to Drupal 7.
The hierarchy of a book is created with a menu. When you have the node object in $node you'll get the menu link id of the parent in $node->book['plid']. You can then load the corresonding node with menu_link_load().

As for the children you have to get the menu that represents the hierarchy of your book with menu_tree_all_data($node->book['menu_name']) and then go through that menu to fetch the links you need.


Rules Redirect User at Login by Role to URL not working I am trying to redirect any user with a particular Role at login to a URL.
I am using Backdrop (Drupal 7).
I have looked at most of the posts relating to this problem, and tried many of the examples but the redirect fails. There are no messages in the Logs, I have debugging on in Rules.
I have tried this which is from a post I found, and modified for my page redirection which works:

    { "rules_after_login_redirect_to_host_registration" : {
    "LABEL" : "After login redirect to Host Registration.",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "user_login" : [] },
    "IF" : [
      { "NOT text_matches" : {
          "text" : [ "site:current-page:path" ],
          "match" : "^user\/reset\/",
          "operation" : "regex"
        }
      }
    ],
    "DO" : [
      { "redirect" : { "url" : "webform\/host-registration" } },
      { "backdrop_message" : { "message" : "Redirecting to Host Registration" } }  ]
  }
}

However my Rule to Redirect a user at login with a Role of Host does not work:

{ "rules_redirect_role_host_to_selected_page" : {
    "LABEL" : "Redirect role Host to selected page",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "user_login" : [] },
    "IF" : [
      { "user_has_role" : { "account" : [ "account" ], "roles" : { "value" : { "host" : "host" } } } }
    ],
    "DO" : [ { "redirect" : { "url" : "webform\/host-registration" } } ]
  }
}

I am baffled. Why is the Role Condition not picked up?

Here is a working rule to redirect users to different URL's depending on user role, you will need Rules conditional module
to acomplish task, enjoy.

{ "rules_user_has_logged_in" : {
"LABEL" : "user has logged in, redirect based on role",
"PLUGIN" : "reaction rule",
"OWNER" : "rules",
"TAGS" : [ "redirect" ],
"REQUIRES" : [ "rules_conditional", "rules" ],
"ON" : { "user_login" : [] },
"DO" : [
  { "CONDITIONAL" : [
      {
        "IF" : { "user_has_role" : { "account" : [ "account" ], "roles" : { "value" : { "4" : "4" } } } },
        "DO" : [ { "redirect" : { "url" : "polizas\/todas" } } ]
      },
      {
        "ELSE IF" : { "user_has_role" : { "account" : [ "account" ], "roles" : { "value" : { "6" : "6" } } } },
        "DO" : [ { "redirect" : { "url" : "polizas\/todas" } } ]
      },
      {
        "ELSE IF" : { "user_has_role" : { "account" : [ "account" ], "roles" : { "value" : { "5" : "5" } } } },
        "DO" : [ { "redirect" : { "url" : "pagos" } } ]
      },
      {
        "ELSE IF" : { "user_has_role" : { "account" : [ "account" ], "roles" : { "value" : { "7" : "7" } } } },
        "DO" : [ { "redirect" : { "url" : "polizas" } } ]
      },
      {
        "ELSE IF" : { "user_has_role" : { "account" : [ "account" ], "roles" : { "value" : { "12" : "12" } } } },
        "DO" : [ { "redirect" : { "url" : "polizas\/todas", "destination" : "1" } } ]
      }
    ]
  }
]

}
}

and an img to see how my rule looks.


Metatag won't work for homepage? The Metatag Module inputs (Such as Description, Abstract, ETC, and that includes Page Title) won't trigger on the home page.

I already read in a forum thread that didn't give an in-program solution. I assume it's a solved problem, because it affects almost any site.

How can one solve it?

According to https://drupal.org/node/1848184#comment-6801690

  Check if you have the code for the main content on the homepage .tpl file:

  <?php print render($page['content']); ?>


How to redirect to a translatable page I have a bilingual site and I want to redirect to a custom page, which has two language versions, upon form submitting. This may be a pretty basic thing, but I am only starting to learn how to code for Drupal in PHP. This is what I tried:

$form_state['redirect'] = t('message-sent-successfully');

'message-sent-successfully' is the URL for the English version of the page. It has a different URL for the other language the site is using. In whatever language I submit the form, I get redirected to the above URL, i.e. the url doesn't get translated.

Install i18n and enable the Translation Redirect module within.

Install Globalredirect and go to admin/config/system/globalredirect and check "Language path checking".

You can then take the user to either source or translated node, and Globalredirect will take the user to the page which is in the currently active language.


Is it good to declare API details as constants I am writing a custom module for payments and using stripe payment method to accept payments on site.

i have a payment form on site and functions are written in above mentioned module.

right now my stripe api details are placed in a function and this function is called wherever i need to use them ( stripe publishable and private keys ) but i am not sure if i am doing it right because it might be not a safe approach to use api details directly in code

so i am thinking about re-writing the code to save the details in database ( using set_variable ) and then fetch them wherever they are needed.

can you help to figure out the most safe approach to save my details and use them.

another options is to declare them as constant at top of module but then they will be available globally that is also not secure.

I've seen both approaches, variables & constants, with storing API credentials. I've also seen private keys stored outside the webroot.

Security Concerns

In all these cases you have, roughly, the same level of security. An intruder needs to penetrate (code injection) and discover your credentials. You could argue that with constants or external files are more "secure" since an intruder is unlikely to know about those, whereas he will likely know the variables table will have many goodies in it, but as any security-minded person will tell you, security through obscurity just isn't security.

Anyone that has access to inject server-side code will eventually figure out how to grab everything if they're so motivated. Given that, your best bet for security is to prevent penetration in the first place.

Keep all your whole software stack (Drupal, contrib modules, web server, database, & OS) up to date.
Be proactive about monitoring any odd errors occurring in Drupal / web server logs.
Follow good programming practices (e.g. understand how to defend yourself against SQL injection, XSS, and other attacks)
Don't install modules / PHP libraries from an untrusted source
Keep up to date about any news with Drupal/PHP or any exploits related to your entire stack (e.g. drupal.org has security mailing list for recently discovered exploits)

Unless you're a high profile target, the most likely attacks you will see are script bots hitting you with well known exploits. As such, the above advice should keep you covered. Just keep in mind, the bigger you are the more time you should be investing into security.

Practical Concerns

With all that said, I'd say the only other difference between the different methods of securing credentials is usability. If these are credentials that a developer should only ever touch, constants/secure files should be fine. If these are credentials that can change (e.g. module reuse across many sites) and you want other non-developers to change them, then the variable approach is the way to go.


How to display different menu in a panel depending on node nr? I created a panel page. Say foopanel. This panel is displaying information based on the node nr. So in case of node nr 1 the url call will be: foopanel/1 (

I want to display a specific menu e.g menu-abc with node/1 and e.g menu-cde with node/2. So menu-xxx should be displayed in a block of foopanel.

How to implement this?

I see visibility rules in panels but do not see the nodeid. Should I do some php here? If so how should it be like?

I installed contexts but don 't see how I can manager this within a panel.

Every suggestion is very welcome to this. Thxs already.

Solved by using the following php code in the visibility rule:

return arg(1) == 1; for menu abc block
return arg(1) == 2; for menu cde block


Import a big website using Feeds XPath Parser I'm trying to import the content of a website with thousands of posts using Feeds and its related tools.
I will import the content by accessing a page that contains all the links.

I've tried importing the content using
http://premiumtemplate.org/kaboodle-premium-business-wordpress-theme.html
 as URL.

Below is the function I use:

Context: /
URL: //h:h2
title: //h:title
body: //*[@class="entry"]

I don't know what happens. It doesn't import anything, and I get the message "There is no new content."

Feeds is a very powerful module, and it is much more than a basic RSS aggregator.  Many people are beginning to leverage Feeds as a migration tool, and Feeds XPath Parser is emerging as a popular way to import static HTML documents.  I set up a quick parser to import this page, so hopefully the example will assist you with what you are trying to do.

First, it is important to enable the debugging options when using Feeds XPath Parser.  This will show you what text was matched by your various queries.

Second, the image below shows the Context and XPath queries I used to import this page.  The result is that it pulls the HTML title tag along with the content under an element containing the "question-page" class.

If you are looking to pull the header elements, I think you will have to explicitly use "h1", "h2", etc. in your XPath query, but I am not sure about this.  The downside of this approach is that you will have to have a source node for every page you are importing, or you will have to find a way to batch submit the import form either programmatically or through some automated tool such as Selenium, JMeter, Firefox Macro, etc.


The "entity_reference_revisions_entity_view" plugin does not exist This is related to Paragraphs module in Drupal 8.
I have enabled paragraphs module and Entity Reference Revisions module. Then I created a new paragraph type in Admin> Structure> Paragraph types. After that I added fields to the new paragraph type. After some configuration I tried to add the newly created paragraph type to a content type, in my case article.
But I got the following error:

There was a problem creating field Paragraphs: The "entity_reference_revisions_entity_view" plugin does not exist.

This is a persistent error. As I have rebuild the site from the scratch, and I am getting the same error.
I will appreciated a help.

This looks like a problem when installing the module.

Check this with drush.

drush ev "var_dump(array_keys(\Drupal::service('plugin.manager.field.formatter')->getDefinitions()))"

Acc. to the error message the plugin is missing. Now reinstall the module:

drush pmu entity_reference_revisions
drush en entity_reference_revisions

and check again:

drush ev "var_dump(array_keys(\Drupal::service('plugin.manager.field.formatter')->getDefinitions()))"

If the plugin is not discovered report any errors you see.

Only debug this on a test site with no field data in this field type.


hook_url_outbound_alter() not working I'm trying to rewrite the URL of a node. I have the following test code:

function mymodule_url_outbound_alter(&$path, &$options, $original_path) {

    if ($path == 'testpage') {
        $path = 'test-alias';
        $options['alias'] = $path;
    }
}

Which doesn't seem to do anything when I visit /testpage or /test-alias. It's definitely executing the code inside the if statement. Am I doing something wrong here?

I have previously implemented hook_url_inbound_alter(), which works perfectly and doesn't do anything on this particular page. I also use the Path module.

If you want to create an alias using hook_url_outbound_alter(), you need to implement also hook_url_inbound_alter(), since the former is for links output from Drupal, and the latter is for links received from Drupal. The former changes the path with its alias, while the latter changes the alias with the equivalent path.

Keep in mind that:

If you are not doing conditional replacements, then it is probably less performance-heavy to use the normal Drupal path aliases
Between the arguments taken from hook_url_outbound_alter(), $path is the path as already changed by the previously executed module, while $original_path is the path before being changed from any module

Also, $options['alias'] is really a boolean, not a string, which tells url() whenever the path being passed to the function is already a path alias. In the case it is, drupal_get_path_alias() will not be called.


Rename a taxonomy vocabulary during migration I'm working on a custom migration for taxonomy vocabulary and I was wondering if there is a way to rename a vocabulary during migration?
my d7 vocabulary name is staff and I wanted to be migrated to d8 as departments

This could be achieved by using static_map plugin:

plugin: static_map
  bypass: true
  map:
    staff: departments