Pass variables from one preprocess function to another in .theme I am developing a theme in Drupal 8 and I have 2 twig files. One is page.html.twig and the other is status-messages.html.twig.

The problem is that status-messages has a variable named message_list (an array) but this variable is protected, so other files don't have access to it. I have tried to call this variable from theme_preprocess_page() like so  $variables['testvar'] = $variables['message_list']; with result of $variables['testvar'] = null.

In the next step I tried to copy the functionality of status-messages.html.twig from Drupal\Core\Render\Element\StatusMessages to mythemem.theme file, like so:

use Drupal\Core\Render\Element\StatusMessages;

function MYTHEME_preprocess_page(&$variables) {

  // Create Dynamic path for project root elements (in general files that are in our theme project)
  $variables['theme_path'] = base_path() . $variables['directory'];

  // this here gives us the array of renderMessages() but  '#message_list' has no data in it
  $variables['testvar'] = StatusMessages::renderMessages();
}

function mythemem_preprocess_status_messages(&$variables) {

  // this here dose gives the value but it can be accessed  only in status-messages.html.twig
  $variables['mymessages'][] = $variables['message_list'];

  // same as in mythemem_preprocess.page
  $variables['testvar'] = StatusMessages::renderMessages();
}

My aim here is to understand how to correctly use .theme files, how to pass protected variables from one preprocess function to another.

To be more clear I would like to know/understand how to get the same effect for my custom.html.twig file as it is here

To achieve this, I want to take $variables['message_list'] to process it as I want.

well after finking a lot about this problem, i realized that i don't wont to duplicate this variable at all.

lets start from beginning i wanted to copy the $variables['message_list'] from status-messages.html.twig to make my custom layout for different situation.

for example i wanted to have different layout/design of status message on  my custom login page and another layout/design for my custom register page. but now i understend that i can have this two in one place (in status-messages.html.twig) i can check if my URL is /login tean  with help of twig if condition i can render one layout and if  my URL is /register then i could have second layout! and in aver situation u would have default layout.

is that correct? how would you solve the problem if you ware in my place


Rendering nodes of a same content type in different templates My Client would like to have multiple templates for one content type. How to allow a user in Drupal to select a specific template when creating a node?

It seems you are looking for Template Picker module:

  Template picker gives content creators a list of templates to choose from as they create nodes.


Experience with Drupal 7 Install Profile "How to Write a Drupal 7 Installation Profile": http://drupal.org/node/1022020

Any experience with this (good or bad)?

The link above references the ability to create an installation profile. Question is, how much can it do?

The real objective is to be able to put everything into code (and version control) that defines the website; permissions, OG field group settings, you name it.
And then use that as a routine production path from dev, to stage, to production.

I've heard theory that this technique could be used to not only establish a site, also as a vehicle for migrating from the dev environment, to staging, to production.

Clearly, there is a benefit to be gained by an organization like Pressflow to be able to build a preconfigured base distribution. But, how viable is this technique for routine website updates and maintenance?

I have 1 site in production (re)built every academic quarter off of an installation profile. I have various sites in development I am building using installation profiles.

It's a PITA to try and include content into an install profile in my opinion. It seems to be a great way to code up the functionality of a website. But I still rely on a BASH build script and Drush to run additional import stuff -- and tools just as Migrate, Taxonomy_csvimport and backup migrate to move "content" around places.

I do like "building" the site codebase using an install profile and would recommend the Profiler module to help you along. You can do alot with install profiles.


Can I use entityreference module with my custom entity to display it? I've attached a new entityreference field to users that referenced my custom entity type, say it's called my_entity. When I dpm() the user or view the tokens, I can see my custom entity properties (id, name, etc) but when I view the user I do not see the field label or the entity label.

I threw a dpm($items) into hook_field_formatter_view() inside entityreference.module and
discovered that there are 0 items available to be displayed, but they are available in many other places! (as described above)

In hook_entity_info():

<?php
return array('my_entity' => array(
  'label' => t('My Entity'),
  'controller class' => 'MyEntityController',
  'base table' => 'my_entity',
  'uri callback' => 'my_entity_uri',
  'load hook' => 'my_entity_load',
  'fieldable' => FALSE,
  'label callback' => 'my_entity_label',
  'entity keys' => array(
    'id' => 'id',
    'label' => 'name',
  ),
);
?>

I tried just setting the entity keys['label'] to the schema field, which is supposed to be adequate to set the label, but I also tried 'label callback' and even setting up the bundle info, which is not necessary for my entity.

I've also tried adding the property into hook_entity_property_info() in the hope that it would be "made aware" to other modules, but no luck:

<?php
return array('my_entity' => array(
  'properties' => array(
    'name' => array(
      'label' => 'Name',
      'type' => 'text',
      'schema field' => 'name',
    ),
  ),
);
?>

Any ideas?

I figured this one out. Entityreference runs entity_access() before returning $items:

$items[$id][$delta]['access'] = entity_access('view', $field['settings']['target_type'], $target_entities[$item['target_id']]);

To get this working, you need to set the 'access callback' property in hook_entity_info(), which is an extended property that is checked by entity.module, not by core's entity functionality. So, for example:

<?php
return array('my_entity' => array(
  'label' => t('My Entity'),
  'controller class' => 'MyEntityController',
  'base table' => 'my_entity',
  'uri callback' => 'my_entity_uri',
  'load hook' => 'my_entity_load',
  'fieldable' => FALSE,
  'label callback' => 'my_entity_label',
  'access callback' => 'my_access_check',
  'entity keys' => array(
    'id' => 'id',
    'label' => 'name',
  ),
);

function my_access_check($op, $entity, $account, $entity_type) {
  // ...do something
  return TRUE;
}
?>


Can I migrate content to non drupal sites I've been reading up on Drupal migration module recently and it seems like very powerful tool. That's why I was wondering is it possible to make migrations like Wordpress -> Joomla with Drupal only as intermediary between those two.

I tried to find some answers to this question but so far I've found only X -> drupal migration

It's probably better to try to go directly from one system into another. Placing Drupal in the middle is likely to add complexity to your migration strategy. But hey, if you find that it solves some issues that your migrations face, then I see no reason why it can't be done.


Creating a menu while categorizing my products Hello I am developing an e-commerce website with drupal commerce(commerce kickstart) everything seems great.I have imported my products and I have tested it and I made my catalog like the video on vimeo that it is posted http://vimeo.com/22748684.

But I would like to make this catalog as a drop down menu.I mean I want to a menu with jquery  that it will replace this catalog and the user for example can see a subcategory cars and can choose Toyota, BMW, some other with tyres like my products on the catalog.

How can I do this?

You can use Superfish to replace the default main menu that comes with commerce kickstart, however you use it at a cost since this jquery drop down menus are usually not optimized for mobile, although superfish provides some optimizations (most in a beta state right now).

Anyway if you need a big dropdown menu your alternatives are short, and Superfish provides minimal mobile browser support if used with a responsive theme (auto-resize and support for touch devices).


Join a custom table on a View I need to join a custom table custom_table on a View my_view.

I have a module created called join_table

The nid is the referential id (the nid is what ties the two table to the view).

Then, I need to take the info the column price in custom_table and be able to display using my Views template.

I'm completely lost.

Example:

/**
 * Implements hook_views_api()
 * @file modulename.module
 */
function modulename_views_api() {
  return array('api' => 2);
}

/**
 * Implements hook_views_data()
 * @file modulename.views.inc
 */
function modulename_views_data() {
  $data['custom_table']['table']['join']['node'] = array(
    'left_field' => 'nid',
    'field' => 'nid',
  );

  $data['custom_table']['price'] = array(
    'title'  => 'Title',
    'help'   => 'Help',
    'group'  => t('Node'),
    'field'  => array('handler' => 'views_handler_field'),
    'sort'   => array('handler' => 'views_handler_sort'),
    'filter' => array('handler' => 'views_handler_filter_string'),
  );

  return $data;
}

Read more info in oficial manual Describing tables to Views


Error generating image, no error log I am new to Drupal, I am trying to move an existing site from serverA to serverB.

When I visit

http://serverB/sites/default/files/styles/thumbnail/public/publications/43026/cover.jpg

I get Error generating image.

I am using Drupal 7.22, on an ubuntu server, PHP Version 5.4.9, have php5-gd and mod_rewrite installed and activated. Error log of apache server is empty. I also have the following directories created.

mkdir -p /var/www/sites/all/files/styles/thumbnail
mkdir -p /var/www/sites/default/files/styles/thumbnail
chmod 777 /var/www/sites/all/files/styles -R
chmod 777 /var/www/sites/default/files/styles -R

How can I fix/find the source of this problem. Where should I look for some useful error logs.

Problem is - you are trying to generate styled image, but you do not provide security token. In Drupal 7.20 and later security token is required so images are only generated when Drupal site itself tries to use them. To turn it off, just add the following line to your settings.php file:

$conf['image_allow_insecure_derivatives'] = TRUE;

Solution taken from this answer and 7.20 release notes.


How to update locale after editing a .po file? I edited a .po file in profiles/l10n_install/translations/ but after this the pages of the site are not updated.

How to update the site after editing a .po file?

Just Import your file from config menu then translate interface import
admin/config/regional/translate/import
and then import your file


Programmatically printing a block So far I have been using this code, which works fine to print third-party module blocks.

<?php
    $block = module_invoke('views', 'block_view', 'og_members-block_1');
    print render($block);
?>

However, now I am trying to print a block that lives within my theme folder and I can't seem to figure out how to do that. How can I achieve this?

There is a way to programmatically print a block in a tpl file.

For 'module' defined blocks you can use block_load() see: block_load op api.drupal.org

If you have a block defined through the block interface, it is called a custom block you can use block_custom_block_get($bid) see: block_custom_block_get() on api.drupal.org

$block = block_custom_block_get(1);
$content = $block['body'];


Add reverse IN clause to db API I need to add IN clause while implementing hook_views_pre_execute

But it's not the regular IN added like the next line

  {table1}.col1 IN (val1, val2)

$query->condition('author', array($user->uid), 'IN');

Wanted to add reverse

  {val} IN ({table1}.col1, {table2}.col2)

$query->condition($user->uid, array(pm_message.author, pm_index.recipient), 'IN');

But the query takes the fields as values not column names

Is it possible to be added in drupal

Simply I need to get messages where the user is the author or the reciever in privatemsg

That's (arguably) non-standard, so you'll need a where.

For example,

$query = db_select('foo');
$query->where(':val IN ({table1}.col1, {table2}.col2)', array(':val' => $user->uid));

will get you

SELECT
FROM
{foo} foo
WHERE  (:val IN ({table1}.col1, {table2}.col2))

(with :val replaced by $user->uid).


Applying a condition/reaction context to all themes I use Drupal 7.43 with Context to hide the sidebar regions in certain content-types so that their nodes will have full-width (at least in desktop mode).

This is a good way to hide sidebars programmaitcaly, and not by CSS (which may cause clashes with other CSS rules and maybe also JavaScript).

My problem:

If I change my theme, I need to reapply each condition-reaction I've created to regions in the new theme. For example, I need to pick the existing name of my sidebar region each time anew.

Do you think there's a better approach to auto-hide ANY sidebar region on certain Pages or Nodes?

You could do this through a very simple custom module. This way hiding the region will work with any theme, as long as it has the same name of the region you are trying to hide.

Here's the code that would go into your sample.info file:

name = Module name
description = Module description
package = Custom
core = 7.x
version = 7.x-1.0

Create sample.module file and add the following code:

function sample_page_alter(&$page) {
  // Fetch the node object.
  $node = menu_get_object();
  // Perform some checks to make sure this is the page we want to alter.
  if (
    // We are on node page.
    $node &&
    // Check if the node if of type you want to have 100% wide layout.
    $node->type == 'page' &&
    // This will exclude local node tasks, such as edit, delete and revision.
    !arg(2)
  ) {
    // Unset the region you want to hide.
    unset($page['sidebar_first']);
  }
}

Update

You asked for a wildcard that would work across multiple themes.

First off - the sidebar_first and sidebar_second are somewhat standard names for left/right sidebars in Drupal themes. Most of the themes will name sidebars the same way.

However, for the sake of answering the question, here's how you'd "scan" for all regions that contain for example the word "sidebar":

function sample_page_alter(&$page) {
  // Fetch the node object.
  $node = menu_get_object();
  // Perform some checks to make sure this is the page we want to alter.
  if (
    // We are on node page.
    $node &&
    // Check if the node if of type you want to have 100% wide layout.
    $node->type == 'page' &&
    // This will exclude local node tasks, such as edit, delete and revision.
    !arg(2)
  ) {
    // Unset the sidebar regions.
    //
    // We will loop through the elements and check if they are set and contain
    // the word "sidebar".
    foreach (element_children($page) as $region_name) {
      if (strpos($region_name, 'sidebar') !== FALSE && !empty($page[$region_name])) {
        unset($page[$region_name]);
      }
    }
  }
}

Notes

Do take into consideration that the above approach will just prevent the region from being printed on the screen. This means that if you have complex blocks, they will still be rendered and take server resources.
You can replace all instances of sample with whatever else you want to call your module.

For more information, check out the following:

hook_page_alter()
menu_get_object()
path_is_admin()
current_path()
element_children()

Hope this helps.


Is it possible to create in Drupal a multiple pages on single page Please check screenshot , without moving to any new URl when i click on Q&A it shows at right side the result even i can edit and save without going to new URL, everything happens on same page
Is it possible in Drupal to do that

Of course it's possible, with or without Drupal. Here is the second link from google: Ajaxify Drupal with JQuery Ajax

  Ajax links API module help you to load any content to a specified DIV or ajaxify whole drupal site, using JQuery Ajax. This module will also load JS for Ajax-loaded content by using Drupal.attachBehaviors(). In case you dont want to load js or css, you can alter tpl for path/node type.


What are the URLs for devel generated images in CCK fields? I generated a few nodes with Devel. When I do a krumo($node), the CCK field consisting of an image, does not have a filename. $field_name['und'][0][filename] is a string of 0 characters. I only get this: $field_name['und'][0]['uri'] = public:///garbledImageName.tmp.png. How do I use this? What function does Drupal use, to convert this public:/// URI into a complete image path? And in the future, can I count on custom created modules to also have the 'uri' value?

Drupal uses the file_create_url() function for this:

  Creates a web-accessible URL for a stream to an external or local file.

Code example:

$url = file_create_url($field_name['und'][0]['uri']);


Swiftmailer module installation fails although the swiftmailer external library is installed I am trying to install the Swiftmailer module on Drupal 8, but I get the following error.

  Swift Mailer requires the external Swift Mailer library. The recommended way of solving this dependency is using the Composer Manager module.

The steps I took are the following.

I installed the Libraries and Mail System modules
I installed the Swiftmailer external library, by running composer require swiftmailer/swiftmailer:"~5.4.5" from sites/all/libraries (inside the Drupal root directory)
I uploaded and uncompressed swiftmailer-8.x-1.0-beta2.tar.gz at $DRUPAL_ROOT/modules/. The installation seemed to be successful, afterwards I got a vendor/swiftmailer/swiftmailer directory under sites/all/libraries.
I tried to install the Swiftmailer module with drush en swiftmailer and through the admin UI.

I have also tried the second step from other locations (for example $DRUPAL_ROOT/libraries), with the same result. Note that the Composer Manager module seems to be obsolete and not needed, according to latest information found in Drupal forums/sites.

How do I install the Swiftmailer module?

That's 7.x/outdated information unfortunately.

You should use composer to manage your Drupal 8 site, using the drupal-project starting point: https://github.com/drupal-composer/drupal-project. It will be a bit of work to switch an existing site to that but after that, installing swiftmailer including all its dependencies will be as easy as running composer require drupal/swiftmailer. That will automatically include all dependencies.


How to style a byline field in an article content type? There might be a simple answer to this but it's driving me crazy. I'm working on a template for an article node and I want the byline to display this way:

  By Author Name

I don't want to change the field label in the web form, so I just want the "By" to be inserted through the node template. No matter what CSS styling I use, the byline field always displays like this:

  By
  Author Name

Is there a way to get the label and field to show up inline?

Here's the PHP I'm using in the template:

<div class="newsbyline">
  <?php print t('By'); ?> <?php print render($content['field_newsbyline']); ?>
</div>

Setting the "newsbyline" <div> to inline doesn't seem to be working.

It would be helpful to see the markup that surrounds the newsbyline field. I'm guessing there's a div or some other element around field_newsbyline that's a block element by default. If you change the CSS for that element to display: inline that may solve the problem.

Alternatively, if the above code is in your node template, you could adjust the markup in the field template instead:

Copying field.tpl.php from the base theme you're using or from Drupal core's /modules/field/theme/ into your theme
Rename it field--field-newsbyline.tpl.php (assuming field_newsbyline is the machine name of your field)
Edit that template to add <?php print t('By'); ?> in the appropriate spot.

By making the change in the field template, you should be able to get your code inside the wrapper div, rather than having it outside.


Force users to always log in and show no content I am using Drupal 7.31 and I installed the MD Alpine theme. I have a site which loads a video on the front page. I want to hide this front page. When users come to my site, I want they are redirected to the login form.

I tried changing the home page to /user and that was a huge mistake. I did manage to undo this. I also went into the permissions and removed any permission for the anonymous user, including the permission to view published content.

I know I have seen this question before, and it seems like there might be a module that can fix that. I am willing to make some configuration change.

On the Structure > Blocks page, configure the Main Content block.  Within the Roles section, check Authenticated User.

Move the User Login block in the Content region.  This allows the Login screen to appear even if they are not logged in.

If you want to redirect them to the login page, you can install the Rules module and create a rule that whenever an anonymous user loads a page, and the page path is not user*, then redirect them to /user.


How to return a missing field as null with db_select union? I have a db_select union of two tables where some of the columns are different. I would like to select a column that is only in one of the tables. The standard SQL way of doing this seems to set the column as null for the table where the field missing. Is there a way of doing this with db_select? db_query?

Standard SQL way:

select id, name, date, null as userid, 'A' as recordtype from table1
union all
select id, name, null /*as date*/, userid, 'B' as recordtype from table2

What I'm trying to do:

$table_one = db_select('t_one', 'to')->fields('to', array('ID', 'NAME'));
$table_two = db_select('t_two', 'tw')->fields('tw', array('ID', 'NAME', 'new_field_not_in_first_table'));
$s_query = Database::getConnection()
        ->select($table_one->union($table_two), 't')
        ->fields('t', array('ID', 'NAME', 'new_field_not_in_first_table'));

I tried adding 'NULL as new_field_not_in_first_table' in the first table but no luck.
Thanks for your time!

I used the addField function to explicitely declare the NULL aliased columns for the UNION. It worked!
Check the following snippet:

$table_one = db_select('users', 't_o');
$table_one->addField('t_o', 'uid', 'id');
$table_one->addField('t_o', 'name');
$table_one->addField(NULL, 'null', 'weight');
$table_one->addField('t_o','mail');

$table_two = db_select('taxonomy_term_data"', 'tw');
$table_two->addfield('tw', 'tid', 'id');
$table_two->addfield('tw', 'name');
$table_two->addfield('tw', 'weight');
$table_two->addField(NULL, 'null', 'mail');

$s_query = db_select($table_one->union($table_two), 't')
    ->fields('t', array('id', 'name', 'weight', 'mail'));

And this generates this kind of SQL:

SELECT t.id AS id, t.name AS name, t.weight AS weight, t.mail AS mail
FROM
  (SELECT t_o.uid AS id, t_o.name AS name, null AS weight, t_o.mail AS mail
   FROM {users} t_o
   UNION
   SELECT tw.tid AS id, tw.name AS name, tw.weight AS weight, null AS mail
   FROM {taxonomy_term_data} tw)

Hope this solves your problem!


create list of  content titles at end of each articles I want create block, view first articles as full node and others just view titles at the end of first articles.

for instace:  when create content type like 'opinion' and show 10 articles on every page, how view first articles (newest) as full node and 9 articles just view titles.

I used drupal 6

Best Regards

Create a views display in which you'll show complete node and add an attachment to display which'll show the titles of all the other nodes.


Add arguments to core search Is it possible to add arguments from $_GET to the core search?
For example:

search/term1/mystring

This search page should show results that have the "term1" term. Like views, but I've to add this function to core search :)

certainly possible.

http://api.drupal.org/api/drupal/modules!search!search.api.php/function/hook_search_preprocess/7

Check out that function.


Error :Missing non existing module In my Drupal 7-configuration, i'm getting this error:

The following module is missing from the file system: imagcache_actions. For information about how to fix this, see the documentation page. bootstrap.inc:1138

The tips on https://www.drupal.org/node/2487215 didn't help.
also imagcache_actions is not to find in the database.

Any hints?

This issue is already fixed by Drupal community. Please check this imagecache_actions.

Its a typo issue and it exists in:

.../imagecache_actions/canvasactions/imagecache_canvasactions.module


Send email notification to node author with Rules I am trying to notify the node author of a new comment on their node.

Using Drupal 8.3

Created new reaction rule.

Send to:  comment.entity_id.entity.uid.entity.mail.value

email address is not being picked up

I get this email from system:

A message that you sent contained no recipient addresses, and therefore no
delivery could be attempted.

This worked.

As a workaround, you can use the data selection string as a token in the direct input textarea.

Switch to data selection and get your string, in my case content_moderation_state.uid.entity.mail.value

Switch to the direct input mode and paste the string with double braces {{content_moderation_state.uid.entity.mail.value}} to use the token replacement API.

As described here: https://www.drupal.org/project/rules/issues/2799569#comment-12376804


Subscriptions in Commerce Stripe I use the Commerce Stripe module to make charges on my website, but I need to be able to subscribe through Stripe, and I have no idea how to do it. The charges I make and without problem but I would need someone to show me the way on how to change the charge to subscription through Commerce Stripe. Thank you.

You can not change existing charge to subscription. It is not a trivial task, but doable by using such modules as Commerce Recurring or  Commerce License and Commerce License Billing.


What is the difference between implementing hook_url_inbound_alter() and hook_url_outbound_alter(), and using a path alias? In Drupal 7, a module could implement hook_url_inbound_alter() and hook_url_outbound_alter() to rewrite URLs used in Drupal. The same effect could be obtained with path aliases. The only difference is that for path aliases that are someway dynamic, you would need a module that adds a path alias every time there is the need. That is what the Pathauto module does.

Is there any difference between the two approaches (implementing those hooks, and using path aliases)? Is there any reason to prefer one approach to the other one?
Is there any performance difference between the two approaches?

The only difference I can see is that with those hooks there could not be the need of accessing the database (depending on how the hooks are implemented). Is that the only difference, or are there more differences?

Using hook_url_outbound_alter() has some potential performance issues because it is executed by every single URL on a page via the url() function. This means a module could implement hook_url_outbound_alter() with some complex and slow code that is called 100's of times per page.

Also hook_url_outbound_alter() allows a link's $options, including its query string, to be altered, which is impossible to do to path aliases and a very useful feature. For example, I have altered internal RSS URLs to point to their respective Feedburner and iTunes URLs.

Conceptually, the Path module should be calling the hook_url_*_alter() hooks but it is probably slightly faster to have the drupal_get_path_alias() calls directly in url().

My personal conclusion is when possible use the built-in path system, but for most special circumstances you will have to use the hook_url_*_alter() hooks.


how to display an image in theme using img tag? I need to display an image in the page footer using  tag. In my page.tpl.php I have following block:

<?php print t('Copyright'); ?> &copy; <?php echo date("Y"); ?>

I can`t use print $logo since I can use another image for the logo.

add image in this way,

<img src="/sites/all/themes/mytheme/images/logo.png" />


How to obtain Drupal session cookie via an XMLRPC request? I would like to implement single sign-on to Drupal and other site (not PHP) via xmlrpc.

Is there a way to make an xmlrpc call with user name & password and in return obtain information on success of authentication and the session cookie - so that we could set the cookie and log in to both sites at once?

The Services module does this. See its user.login service. Core Drupal does not offer this service via XML-RPC.


How can I disable single option of checkboxes in drupal 8 I am using domain access module in Drupal 8. I want to disable one option/site in domain access settings in node edit page . I am trying to disable through hook_node_form_alter. Following is my array in node form alter

Array
(

[widget] => Array
    (
        [#title] => Domain Access
        [#description] => stdClass Object
            (
                [__CLASS__] => Drupal\Core\Field\FieldFilteredMarkup
                [string] => Select the affiliate domain(s) for this content
            )

        [#field_parents] => Array
            (
            )

        [#required] => 1
        [#delta] => 0
        [#weight] => 0
        [#element_validate] => Array
            (
                [0] => Array
                    (
                        [0] => Drupal\Core\Field\Plugin\Field\FieldWidget\OptionsButtonsWidget
                        [1] => validateElement
                    )

            )

        [#key_column] => target_id
        [#type] => checkboxes
        [#default_value] => Array
            (
                [0] => site1
                [1] => site3
            )

        [#options] => Array
            (
                [master] => stdClass Object
                    (
                        [__CLASS__] => Drupal\Core\Field\FieldFilteredMarkup
                        [string] => Master
                    )

                [site1] => stdClass Object
                    (
                        [__CLASS__] => Drupal\Core\Field\FieldFilteredMarkup
                        [string] => Site 1
                    )

                [site2] => stdClass Object
                    (
                        [__CLASS__] => Drupal\Core\Field\FieldFilteredMarkup
                        [string] => Site 2
                    )

                [site3] => stdClass Object
                    (
                        [__CLASS__] => Drupal\Core\Field\FieldFilteredMarkup
                        [string] => Site 3
                    )

                [site4] => stdClass Object
                    (
                        [__CLASS__] => Drupal\Core\Field\FieldFilteredMarkup
                        [string] => Site 4
                    )

            )

)

You can use Form Options Attributes module.

Then in form alter add below code

  $form['field_domain_access] ['widget'] ['#options_attributes']
  ['your_option_key']  = ['disabled' => 'disabled'] ;


Detection of form refresh and callback! How is it possible to detect if the page, in which the form is, is refreshed and to detect if only the form is refreshed?

I tell you the whole thing: I'm building a module. The form in this module has ajax-ed elements. When the form is first loaded (or when the page containing the form is refreshed) a database query is executed (filling up the form), that is the thing i want. But when an ajax-ed element is triggered the query is executed again, and i don't want that.

How is it possible to stop the execution of this query when an ajax callback is executed?
The form is in an .inc file and called by the .module file via drupal_get_form().

You can use $form_state['triggering_element'] to find out if and by which element a form was submitted.

That said, I am not sure if what you want to do is possible. When rebuilding the form, you will have to provide all valid form elements and options for them again.

If that query is slow, you might be able to use the caching system instead (That is, unless these options are personalized for the current user).

But maybe I didn't exactly get what you meant, so try it..


Move label to RIGHT of checkbox in Webforms When setting the label to "inline", Webforms will place the label to the left of my checkbox. Is there any way I can move it to the right?

Here's what it looks like right now, I want the label to be to the RIGHT of the box.

thanks

Drupal is spitting out the markup as [title][field] and what you want is [field][title] so to accomplish this you need to override Drupal's default theme implementation of your field. To do this copy example.com/modules/field/theme/field.tpl.php to your theme template folder(if one does not already exist in there ...sites/all/themes/my_theme/templates) and modify the template file to your desired markup.
When naming your template file you can restrict it to the webform fields, Drupal will use the most specific template it finds in the following order:

field--field-name--content-type.tpl.php
field--content-type.tpl.php
field--field-name.tpl.php
field--field-type.tpl.php
field.tpl.php (in your theme)
field.tpl.php (in drupal's field module)

Take a look at this link, Drupal documentation on field.tpl.php

Hope this helps.


How to restrict user posting a node in certain circumstances I've created a new user role (country_admin) and I have created a field for these users called user_country. This can be set when registering a user to UK or USA.

I have created a taxonomy 'Countries' and have added UK and USA as terms. I have also created a term reference on my articles so that articles can be assigned to a country.

The functionality I require is that only the user who has UK in the user_country field can post an article with the term set to UK.

I am looking at hook_node_access_records() and hook_node_grants() and have got the functionality working so UK users can only VIEW or UPDATE UK articles using this, however, in hook_node_grants() there doesn't seem to be an "ADD" operation.

How would I do this?

Current hook_node_grants() below

/**
* Implements hook_node_grants().
*/
function curator_scraper_node_grants($account, $op) {
    if ($op == 'view') {
        if (array_key_exists(DRUPAL_AUTHENTICATED_RID, $account->roles)) {

            //Let's get the country id the user is linked with
            $uid = $account->uid;
            $user = user_load($uid);
            $country = $user->field_user_country['und'][0];

            $grants[MYMODULE_REALM] = array(
                MYMODULE_GRANT_ID_PUBLIC, // Allow public data
                $country, // this should be users' country link
            );
        }
        else {
            // this is an anonymous user, give them the 'public' grant ID
            // that allows them access to public nodes
            $grants[MYMODULE_REALM] = array(
                MYMODULE_GRANT_ID_PUBLIC,
            );
        }
    }
    if ($op == 'update'){
        //We can grant update permissions here similar to the above
        // but where is $op == "add"???
    }
    return $grants;

}

You can use the Node access user reference module:

  Gives content access permissions to users for content that references
  the users with User reference or Entity reference.

  This is great if you want your content authors to be able to choose
  additional authors, or choose who can view their content, as well as
  being able to display the list of authors or viewers within your
  content, or in views displays.


How to modify a view's empty text to show a different message depending the user viewing it I have created a view displaying a user's blog entries. In view's empty text i have put the simple php code showing below
    You have not created any blog entries.
    You can create a
Now i want to modify it to implement the following scenario.
1. When a user visit his/her profile page the above empty text should be appear. 2. If a user visit an another user profile page then i want the empty text to have the following value
        [username of the user that own's the profile page] hasn't created any blog entries.
Can anyone help me to achieve this? Thanks in advance.

Do you have the php filter input format turned on for your site? You can do this by adding the following code into your empty text field with the input format 'php code' enabled:

//get the current $user object to determine the logged in user's id
global $user;

//now load the user id from the profile page into another object by pulling it from path
$usertmp = user_load(array('uid' => arg(1)));

if ($user->uid == $usertmp->uid) {
     //we're on the logged in user's page
     print "You need to write more stories..";
} else {
     print $usertmp->name." needs to write more stories.. ";
}


How to pass query parameter in form submit? I have a form :

function buildForm(array $form, FormStateInterface $form_state) {
    $form['edit'] = array(
          '#type' => 'textfield',
    );
    $form['submit'] = array(
          '#type' => 'submit',
          '#value' => t('Go'),
          //'#markup' => "
Go
",
        );
    return $form;
}

Now I want is; when I submit form,$form_state->getValue('edit'); should get appended as a query parameter in form route.

Let's say my form route is:

mymodule.admin_page:
  path: '/mypage'
  defaults:
    _form: '\Drupal\mymodule\Form\myform'

And when I hit submit button of form, the route should get changed to /mypage?word=$form_state->getValue('edit').

I tried below approach, but it is throwing error:

Created 1 more route with a parameter:

mymodule.word:
  path: '/mypage/{word}'
  defaults:
    _controller: '\Drupal\mymodule\Controller\AdminController::myfunction'

And in my form submit function,

function submitForm(array &$form, FormStateInterface $form_state) {

    $data = $form_state->getValue('edit');
    $url = Url::fromRoute('mymodule.word',['word'=>$data]);
    $form_state->setRedirectUrl($url);
   }

But when I hit submit button, it is giving me error,

  Uncaught PHP Exception
  Symfony\Component\Routing\Exception\MissingMandatoryParametersException:
  "Some mandatory parameters are missing"

Stick with your original route definition:

mymodule.word:
  path: '/mypage'
  defaults:
    _controller: '\Drupal\mymodule\Controller\AdminController::myfunction'

Then set your submit handler to this:

function submitForm(array &$form, FormStateInterface $form_state) {

  $data = $form_state->getValue('edit');
  $url = Url::fromRoute('mymodule.word', [], ['query' => ['word' => $data]]);
  $form_state->setRedirectUrl($url);
}


How to desactivate jquery_update logic for the homepage The objective of this is to remove all legacy javascript files from the homepage except for the new javascript files I specifically want to load.

Here is how I remove all the Javascript files I don't need:

function phptemplate_preprocess_page(&$vars) {
    $template_files = $vars['template_files'];
    $scripts = drupal_add_js();

    if (in_array('page-front', $template_files === true) {
        // Here I unset all the javascripts that I don't want to be loaded in the homepage
        unset($scripts['theme']['themes/"theme_name"/js/jquery.jcarousel.min.js']);
        ...
        // Once cleaned up all unncessary javascripts, I load them into $var['scripts']
        $var['scripts'] = drupal_get_js('header', $scripts);
    }
}

This works fine, however it only works when the jQuery Update module is desactivated. If the jQuery Update module is active, somehow it overseeds this logic and all the javascript files are loaded anyways.

I don't want to use the jQuery Update logic in the homepage, but I'm affraid that if I disable this module, I can provoke negative side effects in the other pages of the website.

Conclusion: I want to desactivate jQuery Update logic for handling javascript files but only for the homepage.

Any other alternative solution / conclusion to this problem is also welcome.

The reason why your theme_preprocess_page function isn't working, is because the jQuery update module uses a clever implementation of hook_theme_registry_alter to ensure it's implementation of hook_preprocess_page is called last.

What I recommend you do is create a new module and implement your own hook_theme_registry_alter and hook_preprocess_page functions. See a simple example below which has taken some code snippets from the jquery update module:

function mymodule_theme_registry_alter(&$theme_registry) {

  if (isset($theme_registry['page'])) {
    if (count($theme_registry['page']['preprocess functions']) > 0) {
      if ($key = array_search('mymodule_preprocess_page', $theme_registry['page']['preprocess functions'])) {
        unset($theme_registry['page']['preprocess functions'][$key]);
      }
    }

    // Now tack it on at the end so it runs after everything else.
    $theme_registry['page']['preprocess functions'][] = 'mymodule_preprocess_page';
  }
}

This hook implementation tells Drupal to invoke our custom hook_preprocess_page function after all other modules have run their hooks.

Then we need to define our own custom implementation of hook_preprocess_page which will alter the scripts included on the front page:

function mymodule_preprocess_page(&$vars) {

  // Only do this for pages that have JavaScript on them.
  if (!empty($vars['scripts'])) {

    $template_files = $vars['template_files'];
    $scripts = drupal_add_js();

    if (in_array('page-front', $template_files === TRUE)) {
      // Here I unset all the javascripts that I don't want to be loaded in the homepage
      unset($scripts['theme']['themes/"theme_name"/js/jquery.jcarousel.min.js']);
      // Once cleaned up all unncessary javascripts, I load them into $var['scripts']
      $vars['scripts'] = drupal_get_js('header', $scripts);
    }
  }
}

Using this approach in your own custom module will make sure that any alterations you want to make to your javascript includes will happen very last.

Good luck! :)


Difference between router path and link path? I have recently started looking into the drupal menu system. I am not able to understand the difference between a router_path and the link_path. Both point to the same location in my installation.

Pro Drupal Development, Second Edition describes them as:

  menu_links.link_path is the Drupal path or external path this link
  points to.

  menu_links.router_path is for links corresponding to a Drupal path
  (0 means external), this connects the link to a menu_router.path for
  joins.


Get Media entity field values in custom validation handler I am trying to put a custom validation on node form which has paragraph attached to it. The problem is I am not getting paragraph field values available in form_state of my validation handler.

I just see the delta of entites when I do a debug on form_state

As in the screenshot field_asset the entity_reference_revision referencing a media entity, I only see two entities attached in form_state in custom submit handler on node_form but how can I get value of those refernced entities?

Update: I realised it was not paragraph entity but media entity.

Digging the form_state I found the user submitted values for embedded media entites lies at form state storage. My validation code now looks like

/**
 * Implememts hook_form_alter().
 */
function mymodulename_form_alter(&$form, \Drupal \Core\Form\FormStateInterface $form_state, $form_id) {
  $operative_form = array(
    'my_node_add_form',
    'my_node_edit_form'
  );
  if (!in_array($form_id, $operative_form)) {
    return;
  }
  $form['#validate'][] = '_mymodulename_validate_element_node_form';
}

/**
 * Custom validation handler for EDP.
 */
function _mymodulename_validate_element_node_form($form, $form_state) {
  $form_storage = $form_state->getStorage();
  $form_storage_embed_entities = $form_storage['inline_entity_form'];
  foreach ($form_storage_embed_entities as $key => $value) {
    $media_entities = $value['entities'];
    foreach ($media_entities as $media_entity) {
      if ($media_entity['entity'] instanceof \Drupal\Core\Entity\EntityInterface) {
        if ($media_entity['entity']->getEntityTypeId() == 'media') {
          $asset_type[$media_entity['entity']->field_asset_type->value] = $media_entity['entity']->field_asset_type->value;
        }
      }
      if (count($asset_type) > 1) {
        // early bail.
        break;
      }
    }
    // Validation condition goes here.
    if ($validation_condition) {
      $form_state->setErrorByName('field_asset', t('Did you try turning it on and off.'));
    }
  }
}


How do I add shipping costs to orders? I have a really complex set of shipping rules

I have three product types

Product type A with a rate of £1 per product
Product type B with a rate of £2 per product
Product type C with a rate of £3 per product

A customer can add any combination of products into their cart so

2 x Product type A
1 x Product type B
1 x Product type C

I have created rules to loop through commerce_line_items and get the individual shipping costs for product types based upon a field in the commerce_product entity and I have got it so it calculates quantity times shipping cost.

What I do not know and cannot work out is how I then add these shipping costs back to the order, there seems to be no way to set the value of a shipping service.

Also I do not know how to parse the line items for each product type and calculate the shipping costs based upon each product type. So I need a condition check on the product type of each line item in the order to obtain the product type and then do the calculations based upon the correct shipping rate and quantity.

Any advice would be fully appreciated.

Edit the Reaction Rule "Collect rates: Flat Rate" and add conditions if you wish, so that it only applies to certain Product Types, or to an Order whose total is over a certain amount, for example. (Note that because you are using Conditional Rules you could also put such logic in the Action of your shipping pricing rule [see below])
Create a Shipping Service for your Flat Rate Shipping Method. For example, "My Basic Shipping." Give it a base rate - can be $0, or whatever.
Create a shipping pricing Rule that applies shipping charges to Products through the Service you just created. You can use conditionals in the Rule to apply the shipping based on SKU, Product Type, price, or whatever. You can use extra modules to base it on size and weight, day of the month, whatever.

Here's an example of a Price Calculation Rule. My Shipping Service is called 'swag shipping' and the Rule adds to the shipping cost based on the country:

{ "rules_ship_s_store_shipping_surcharge_by_country" : {
"LABEL" : "Ship\u0027s Store: Shipping Surcharge by Country",
"PLUGIN" : "reaction rule",
"OWNER" : "rules",
"TAGS" : [ "Commerce Checkout" ],
"REQUIRES" : [
  "rules",
  "commerce_order",
  "rules_conditional",
  "commerce_line_item",
  "commerce_shipping"
],
"ON" : { "commerce_shipping_calculate_rate" : [  ] },
"IF" : [
  { "data_is" : { "data" : [ "commerce-line-item:type" ], "value" : "shipping" } },
  { "data_is" : {
      "data" : [ "commerce-line-item:commerce-shipping-service" ],
      "value" : "swag_shipping"
    }
  },
  { "entity_has_field" : {
      "entity" : [ "commerce-line-item:order" ],
      "field" : "commerce_customer_shipping"
    }
  },
  { "NOT commerce_order_compare_address" : {
      "commerce_order" : [ "commerce-line-item:order" ],
      "address_field" : "commerce_customer_shipping|commerce_customer_address",
      "address_component" : "country",
      "value" : "US"
    }
  }
],
"DO" : [
  { "CONDITIONAL" : [
      {
        "IF" : { "commerce_order_compare_address" : {
            "commerce_order" : [ "commerce-line-item:order" ],
            "address_field" : "commerce_customer_shipping|commerce_customer_address",
            "address_component" : "country",
            "operator" : "is one of",
            "value" : "CA\u000D\u000AMX"
          }
        },
        "DO" : [
          { "commerce_line_item_unit_price_amount" : {
              "commerce_line_item" : [ "commerce_line_item" ],
              "amount" : "1000",
              "component_name" : "flat_rate_swag_shipping",
              "round_mode" : "1"
            }
          }
        ]
      },
      { "ELSE" : [
          { "commerce_line_item_unit_price_amount" : {
              "commerce_line_item" : [ "commerce_line_item" ],
              "amount" : "1500",
              "component_name" : "flat_rate_swag_shipping",
              "round_mode" : "1"
            }
          }
        ]
      }
    ]
  }
]

}
}

IMPORTANT NOTE: You may have trouble after you get your shipping working, to display your shipping line items in your Order display, for example in the Order acknowledgment e-mail that comes by default with Commerce. You need to make some rather complicated configuration changes to get this to work. Please see the article How to display all Drupal Commerce line items using a token if you get that far.


How to split node fields into view blocks I am using Omega, and I want to assign fields for a node type to regions of a template.  I created a view, with a page (to get a URL) and block views with fields. I then assigned the blocks of fields to their regions to only display for that node type.  It's not working.  I have a contextual filter for NID, and if not found, to default to the Content ID in the URL.

I feel like this should work, but I'm missing something.


"render ($user_profile)" in user-profile.tpl.php = no output Following the discussion in http://api.drupal.org/api/drupal/modules--user--user-profile.tpl.php/7 I created a user-profile.tpl.php file in my theme directory, but the code

<div class="profile"<?php print $attributes; ?>>
  <?php print render($user_profile); print ("you are here"); ?>
</div>

prints the "you are here" but not the $user_profile array. Any suggestions as to what I might be doing wrong?

Try installing and enabling the devel module, then edit it so that it reads

<div class="profile"<?php print $attributes; ?>>
  <?php krumo($user_profile); ?>
  <?php print render($user_profile); ?>
</div>

That will show you what the data actually looks like...


Change the text on the message which is displayed after the user registration I am looking for a way to replace the text in this message which appears on the website after a new account if created.

  Thank you for applying for an account. Your account is currently
  pending approval by the site administrator. In the meantime, a welcome
  message with further instructions has been sent to your e-mail
  address.

Has anyone managed to change this successfully?

Thanks!
Anton.

Goto Admin -> Configuration -> Account Setting -> Change the messages.
OR
You can implement through Rules module.

Send mail after creating new user a/c

Usage :

Goto Admin -> Configuration -> Rule

Click on 'Add new  rule'

Enter Name & Select React on event : After Saving a new user a/c & SAVE

Click on Add Condition & select Send Mail.

Click on Data Selector button & Enter Data Selector : account:mail

Enter Subject & Message & Save


Display terms, username and user picture in a view block I created a new view block and it appears in Article - Content type; In these block I want to display the author's user picture, author's username, post date, category, tags, and comment count.

I succeeded to display user picture, username, but the post date, category, tags, and comment count are from the other article (the first or the last article written by the same author).

I used a few relationships and contextual filters, without success.

Example

I have an article with title "One two three", category numerals, tags "one, two, three, numeral". When someone reads these article, I want that block to show these values:

Category: numerals
Tags: one, two, three, numeral
username
user picture

Is it possible to display all these things in one view?

There was a recent answer very much along these lines here that recommended the module Author Pane.  This module is extensible with hooks; might be the easier way for you to go as well.

  Author Pane is a block of information about a given user, like those typically found on a forum post, but can be used in other places as well. From core, it collects the user picture, name, join date, online status, contact link, and profile information. In addition, any module or theme can feed it more information via the preprocess system. All of this information is then gathered and displayed using a template file.


hook_libraries_info() doesn't work I have a custom almost empty module where I'm tring to insert a js file using hook_libraries_info(). But when I load the home I don't see my script inserted. It works when I use a simple drupal_add_js.
What I'm doing wrong? I've seen other examples like masonry and nivo-slider and those are similar. Do I need to init somehow? I'm new at module development, so probably is something simple.

DETAILS
Libraries module is enabled:
-  Libraries    7.x-2.1

The location of the library folder is this:
- sites/all/libraries/test/test.js

test.module

<?php
//drupal_add_js('sites/all/libraries/test/test.js'); when uncommented it works

/**
 * Implements hook_libraries_info().
 */
function test_libraries_info() {  // it never works
  $libraries['test'] = array(
    'name' => 'Test',
    'vendor url' => 'http://www.example.com/',
    'download url' => 'http://www.example.com/',
    'files' => array(
      'js' => array(
        'test.js',
      ),
    ),

  );
  return $libraries;
}

hook_libraries_info(), documented in libraries.api.php, is just a hook that informs the Libraries API module of any existing external library. Its purpose is not loading those libraries when a Drupal page is shown; for that, the module needs to call libraries_load() (defined in libraries.module) when necessary.

libraries_load_files() is the function that actually load in the page the CSS and Javascript files, respectively with drupal_add_css() and drupal_add_js().

  // Load both the JavaScript and the CSS files.
  // The parameters for drupal_add_js() and drupal_add_css() require special
  // handling.
  // @see drupal_process_attached()
  foreach (array('js', 'css') as $type) {
    if (!empty($library['files'][$type])) {
      foreach ($library['files'][$type] as $data => $options) {
        // If the value is not an array, it's a filename and passed as first
        // (and only) argument.
        if (!is_array($options)) {
          $data = $options;
          $options = array();
        }
        // In some cases, the first parameter ($data) is an array. Arrays can't
        // be passed as keys in PHP, so we have to get $data from the value
        // array.
        if (is_numeric($data)) {
          $data = $options['data'];
          unset($options['data']);
        }
        // Prepend the library path to the file name.
        $data = "$path/$data";
        // Apply the default group if the group isn't explicitly given.
        if (!isset($options['group'])) {
          $options['group'] = ($type == 'js') ? JS_DEFAULT : CSS_DEFAULT;
        }
        call_user_func('drupal_add_' . $type, $data, $options);
        $count++;
      }
    }
  }


Display latest three news on a custom template I'm building a custom theme and I would like to display last three inserted news (i.e. nodes with content type = News) on the bottom of the home page from inside the home page template.

Something like this:

+-------------------------------+
| +---------------------------+ |
| |                           | |
| |          Slides           | |
| |                           | |
| +---------------------------+ |
|                               |
| +---------------------------+ |
| |                           | |
| |           Page            | |
| |           Body            | |
| |                           | |
| |                           | |
| +---------------------------+ |
|                               |
| +-------+ +-------+ +-------+ |
| | Last  | |Second | | Third | |
| | News  | | Last  | | Last  | |
| |       | | News  | | News  | |
| +-------+ +-------+ +-------+ |
+-------------------------------+

I created a content type named Home page, with fields for manage slides and the page body, then I created a new content (a new node) of type Home page.

Inside my custom theme I created a template file named node--home-page.html.twig and inside it I can handle the Home page's fields (slides and body) and how to render them inside the page.

After that I created another content type News and I added some content of such type.

Now I would like to display latest news inside the homepage template as in the figure above. What is the better/simplest way to do it?

I'm thinking to load latest news in some hook_preprocess_HOOK function (using the EntityFieldQuery object) then add them inside a variable for the Twig template. Inside the template I will perform a for loop rendering latest news at the page's bottom. Is this a good way to do it or I'm completely out of the way?

EDIT

Correction: I would like to display latest news between slides and body, in this way:

+-------------------------------+
| +---------------------------+ |
| |                           | |
| |          Slides           | |
| |                           | |
| +---------------------------+ |
|                               |
| +-------+ +-------+ +-------+ |
| | Last  | |Second | | Third | |
| | News  | | Last  | | Last  | |
| |       | | News  | | News  | |
| +-------+ +-------+ +-------+ |
|                               |
| +---------------------------+ |
| |                           | |
| |           Page            | |
| |           Body            | |
| |                           | |
| |                           | |
| +---------------------------+ |
+-------------------------------+

Where slides and body are two fields of the Home page content type.

I used the Twig Tweak module and I embedded a custom view, showing latest news, inside my Twig template with:

{{ drupal_view('view_name') }}


Adding a class to a menu item where the class name is set in the node I want to add a field to a content type where the editor can select a class name from a drop down or simply enter a class name into a text field. I want this class name to then be added to the menu item's li tag.

The purpose is so that the editor can select an icon (based on Font awesome) when they are authoring a page of content.

The class should be added on the content authoring page, and not via a secondary step by editing the menu item itself from the menu manager. Note, I'm also using taxonomy menu to build the links.

Any suggestions would be appreciated.

How comfortable are you with code?

This sounds like a job for hook_preprecess() inside template.php to get the value of drop down field and store it to something like $var['my_class_to_insert']=. Then inside of whatever.tpl.php used for this situation, have
Content goes here
. See https://stackoverflow.com/questions/8124089/ for how to get the value of a field in the template.php file.

The drawbacks to this second approach is that you are coupling functionality to the theme layer and adding to "Drupal's Div Soup."

Or I'd look at two other modules before you open up a code editor. You could try to use logic in the Context Module

  Context allows you to manage contextual conditions and reactions for
  different portions of your site. You can think of each context as
  representing a "section" of your site. For each context, you can
  choose the conditions that trigger this context to be active and
  choose different aspects of Drupal that should react to this active
  context.

And Rules may help out...

  The Rules module allows site administrators to define conditionally
  executed actions based on occurring events (known as reactive or ECA
  rules). It's a replacement with more features for the trigger module
  in core and the successor of the Drupal 5 workflow-ng module.

Rules and Context also have a world of other modules that add additional pieces of functionality.


Drupal queue processing at cron run I use ultimate cron to fill in a queue with some nids.

To add the items in the queue, I use something like:

$queue = DrupalQueue::get('my_queue');
foreach($urls as $nid=>$url){
  sleep(1);
  $response = drupal_http_request($url,array('timeout'=>3,'method'=>'head'));
  if($response->code=='404'){
    $queue->createItem(array('nid' => $nid));
  }

This works OK.

When the time comes, another cron job is executed that deletes those nodes. This is done like:

$queue = DrupalQueue::get('my_queue');
for($i=0; $i<$queue->numberOfItems(); $i++){
  $item = $queue->claimitem();
  node_delete($item->data['nid']);
  $queue->deleteItem($item);
}

This is not working OK; there is a small issue: Everytime the second job runs, only half of the items in the queue are processed (deleted). If there are 3000 items in the queue, only 1500 are deleted. If there are 1500 items, only 750 are deleted and so on.

Why is that? Is there a way to control it?

So you have 2 queues walking all over eachother. The timeout value is how long the item is Leased to have work done upon it. The lease-time does not guarantee your processing will finish it time. A Leased item will not be able to be deleted until its lease has expired.

So you should analyze the tasks being run and adjust your timeout to be larger than the longest processing time you have recorded as occurring. I typically do a 2x or 10x as much Lease-time as my longest evaluated processing time. Once an item has completed processing its Lease is expired (so over guessing doesn't really hurt you here).

Alternatively, instead of having 2 queues you could do all this with 1 queue. To try to get around contention. You could insert into a single queue all your NIDs with an additional value of task; and at the end of that queue append a new list of NIDs with an additional flag value of delete or purge. Adjust your worker function to examine a NID and the action to perform on the NID; task or delete.

For example your createItem could look like:

// Add all NIDs for task to be performed.
$queue->createItem(array('nid' => $nid, 'action' => 'do-task'));
// in the same list later on queue the same NIDs to be deleted.
// by setting a huuuuge lease time you will never accidently purge an
// uncompleted task.
$queue->createItem(array('nid' => $nid, 'action' => 'do-delete'));

You may find working with a single queue -- easier than juggling 2 queues.


Is there any way to connect to a second (MySQL) database in a Kernel Base test? Right now I have configured this environment variable in my phpunit.xml to connect to a Drupal database in a SQLite file:

<env name="SIMPLETEST_DB" value="sqlite://localhost//Users/jepster/Dev/my-project/project/docroot/sites/default/files/db.sqlite"/>

This works fine. But can I also connect to a second database like I am doing in the settings.php?

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

Currently my Kernel Base Test fails with the following error:

  The specified database connection is not defined: second-database

That's because I want to connect to my database from a service constructor:

  public function __construct() {
    $this->database = Database::getConnection('default','second-database');
  }

I have been digging in the Drupal core Kernel Base Tests ("core" folder), but I could not find a way there.

I have figured it out. The setUp() method in my Kernel Base Test must look like that:

/**
 * {@inheritdoc}
 */
protected function setUp() {
    parent::setUp();

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


Commerce add to cart form combined products: how to change default product How can I set for example the mp3 as first item?
Now it takes the products (product reference) from a product display node and display it in order of product creation.

In this example the "CD" was created before "MP3", but I want to be able to always display MP3 before CD.

I use a view with an add to cart field and the option "Attempt to combine like products on the same line item in the cart." checked.

Solution in my case (thanks Ryan Szrama!):

function mymodule_commerce_product_reference_default_delta_alter(&$delta, $products) {
foreach ($products as $key => $product) {
    if ($product->type == 'audio' && $product->field_audio_medium[LANGUAGE_NONE][0]['value'] == 'mp3') {
        $delta = $key;
    } elseif ($product->type == 'video' && $product->field_video_medium[LANGUAGE_NONE][0]['value'] == 'mp4') {
        $delta = $key;
    }
}

}

That checkbox you've mentioned is irrelevant, if I understand your request properly. The Add to Cart form assumes whichever product you reference first is the default product when it first builds the form (i.e. it has a product reference field value delta of 0).


How do I force Breadcrumb to use a menu other than Main Menu? I am trying to force breadcrumb to follow the structure of a menu other than Main Menu.

I have configured the content type to use the new menu to add links, which are displayed correctly in the sidebar menu. However breadcrumb just displays Home > (current_page).

Where is this configured? Is it hard coded?

Any advice appreciated.

Cheers
Paul

Menu Breadcrumb

By default, Drupal will use the Navigation menu for the breadcrumb. This module allows you to use the menu the current page belongs to for the breadcrumb.

As an added bonus, it also allows you to Append the page title to the breadcrumb (either as a clickable url or not) and hide the breadcrumb if it only contains the link to the front page.


Get custom field of node in frontend as its type I have a requirement in drupal. In this i have a content type 'sports' and created some custom fields of type dropdown, checkbox and file.

I want to get the custom field with its type as html in front end.

Example In dropdown i have

<select>
<options value="15">Cricket</options>
<options value="16">Football</options>
<options value="16">Basketball</options>
</select>

I want the same in frontend to display as html

Finally i found what i want actually in front end.

The below code displays the form that it has on backend.

This form is for 'sports' content type. This wil bring all fields with its widget wherever we calling.

module_load_include('inc', 'node', 'node.pages');
$form = node_add('sports');
print drupal_render($form);


Adding a block to the page but not declaring it in hook_block_info() I have inherited some code from a contractor. This code adds a block to page_content but it is not defined in hook_block_info().

We then have the following code:

/**
 * Implements hook_block_view().
 */
function erepair_blocks_block_view($delta = '') {
  $block = array();
  switch ($delta) {
    ...
    case 'page_content':
      $block['content'] = page_content();
      break;
    ...
  }
  return $block;
}

This block is then displaying on some certain pages but I can't work out how.

So I have looked into the database and have found an entry for the block in the table.

It is safe to presume that they have either:

executed some sql to add the block (but did not do it in an install file)
had an entry in hook_block_info() added the block to the page then deleted the deceleration in hook_block_info()

I imagine what ever they have done is not best practice. Is there anything else they could have done (we are not using features).

The block may be positioned using the Context module, or via custom code in about a million places. What you can do is temporarily modify the template_preprocess_block() function in block.module, identify the block you're looking for by looking at the data in $variables['block'], and then looking at the output of debug_backtrace() to see the callstack and find the place the block is coming from.


Submit webform via POST on restful API I'm trying to submit JSON data directly to a webform through some restful resource. My thought was to create a webform, enable webform_service, and then post directly to the endpoint. This lead me to try something like this:

curl -vv -X POST -H "Content-Type: application/json" -d '{"title":"Contact Us", "submitted[contact_fullname]": "my name", "submitted[contact_email]": "test@example.com", "submitted[contact_message]": "test message"}' http://localhost/api/contact_us.json

But this does not work. In fact without the "title" value I get "title field is required", which seems to be trying to create a new webform, and in fact if I provide a title, a new webform is, in fact, created. But this is not what I'm looking to do - I'm trying to submit a new entry into the existing webform.

I thought that perhaps there's a different resource that I should be submitting form data to:

curl -vv -X POST -d 'submitted[contact_fullname]=sundartest&submitted[contact_email]=test@lp.com&submitted[contact_message]=test_message' http://ike.localhost/api/contact_emc.submission

But obviously this is wrong and I'm just guessing!

Any pointers on how I can accomplish this?

https://stackoverflow.com/users/763010/tyler-frankenstein created a grate article that can be found here

you might also find https://stackoverflow.com/questions/10428014/steps-to-make-a-mobile-application-using-drupal-as-a-back-end-or-service/13662041#13662041 useful it has links to articles that describe services in full.

I'd also advise a couple plugins
Firefox: poster
Chrome: postman

http://drupal.org/node/1795770 might be more applicable it's how to login, post a comment, and loggout from curl hope it helps.


How to uncache jsonapi? As usual, I am debugging something and this time, it's jsonapi. I already have $settings['cache']['bins']['render'] = 'cache.backend.null'; and $settings['cache']['bins']['dynamic_page_cache'] = 'cache.backend.null'; this works for HTML, how do you force JSONAPI to not cache?

This is due to the internal page cache and Internal dynamic page cache, Drupal will heavily cache all GET requests, so what you are missing is

$settings['cache']['bins']['page'] = 'cache.backend.null';

as the 3rd bin to clear but this won't work due to dynamic cache, so can you either manually purge the entire Drupal cache or set a timestamp into your URL so you can bypass caching for development.

node/1?_format=json&time=123456789


Append query parameter to module's javascript based on custom field on page I am new to Drupal development.

I am currently working on maintaining a Drupal module that was developed by a past colleague.

What I want to do is have an available field where a user can enter in an integer which corresponds to a JS query parameter that will be added to one of the module's script upon page load.

I am wondering if it is possible to add a custom field type that users can add through the Drupal UI to their content (nodes), and then check for the existence of this field and append it to the script?

I have found this tutorial helpful in adding custom fields through my module. However, it doesn't provide any links to documentation that specifies what values I can/should put on dependencies, module, along with other parameters. Also after quite a bit of Google searching, and a bit of combing through Drupal docs, I ended up with nothing.

Further, I believe that I am more or less on the right track in using the hook_page_attachments_alter function to check against fields and conditionally load JS scripts. Although, I don't believe that the $page array passed through this hook supplies node fields.

Currently the module is loading the custom JS like so:

  function my_module_page_attachments_alter(&$page) {

    $page['#attached']['library'][] = 'my_module/script';

  }

Obviously it is loading it through libraries, which would make appending a custom query string parameter difficult. Maybe there is a better way?

You probably want to approach this through hook_ENTITY_TYPE_view(). It's easy enough to get the current node in the page attachments hook, but as you only need to take action when a node is being viewed, using the more specific hook seems appropriate.

A basic example:

function my_module_node_view(array &$build, \Drupal\Core\Entity\EntityInterface $entity, \Drupal\Core\Entity\Display\EntityViewDisplayInterface $display, $view_mode) {
  if ($view_mode == 'full' && $entity->getType() == 'foo' && $entity->hasField('field_bar')) {
    if ( ($val = $entity->field_bar->value) ) {
      $build['#attached']['library'][] = 'my_module/script';
      $build['#attached']['drupalSettings']['my_module']['script']['bar'] = $val;
    }
  }
}

The settings you add to the #attached array will be available in JS after a change to your libraries yml file to add a dependency:

script:
  js:
    ...
  dependencies:
    ...
    - core/drupalSettings

The value will be available in the JS var drupalSettings.my_module.script.bar.


How to preprocess Bootstrap region I am using Panels Bootstrap Layouts. I insert bootstrap_twocol_stacked into the $content region.

I'd like to be able to access regions of that Bootstrap layout (Top, Left, Right, Bottom) in my page.tpl.php template to restructure the HTML code, but I only seem to have an access to the content. $page['content']['system_main']['content']['#markup'] variable when run e.g.

function theme_preprocess_page(&$variables) {
  dpm($variables);
}

only contains rendered HTML code and does not give me option to access Bootstrap data as array, like $page['content']['***']['top'].

I tried to look for a preprocess hook (probably one of the panels module function), but could not figure out which one.

Any hints?

What I am trying to do is to move the bootstrap region to the same hierarchy level in the page.tpl.php as other page regions, see the image below.

Here the solution, if somebody is interested:

create new section in your theme, call it e.g. bottom-section and use this preprocess hook to move the content of the bottom pane to bottom-section section

function theme_preprocess_panels_pane(&$variables) {
  if ($variables['pane']->panel == 'bottom') {
    // Move to a region
    drupal_add_region_content('bottom-section', $variables['content']['#markup']);
    // Delete the pane from the panel
    $variables = array();
  }
}


Do entities need to have URIs? I am trying to figure out the best way to manage some data. I don't want it to be accessible like nodes through any kind of URI. I know that, when entities are defined, I have to provide a URI callback. Is this callback necessary?

I mostly want to use entities because the API makes it easy (and standard) to work with data.

You don't have to define a uri/URL callback.
Defining one won't make your entities visible to users, you have to create a menu callback to make them visible.


Remove 'Switch to plain text editor' in CKEdtior Where do I disable the switch to plain text editor link from the CKEditor. I checked the settings and I don't find anything that support this.

I tried to disable it with display:none; through CSS but it wont respond to it. Here is the code

Switch to plain text editor

I both tried with the id tag and the class to disable it but it dosen't work.

.ckeditor_links a {
display: none;
}

does not work :(

Any suggestions?

You do not need to use CSS. There is an option within the CKEditor profile.

Go to Configuration > Content Authoring > CKEditor then select edit next to the profile you want to effect. This way you can also limit this too certain users.

Then select editor appearance and scroll down to "Show the disable/enable rich text editor toggle" then select hide and save the profile.


Ajax error while uploading or removing file through managed file I am getting following error while using managed file through my custom form.

  "An Ajax HTTP request terminated abnormally."

Also, I updated my jquery version to latest using jquery_update module. Still no any benefit.

Any idea on how to solve it?

EDIT:

Code

  $form['path_image'] = array(
    '#title' => t('Image'),
    '#type' => 'managed_file',
    '#description' => t('The uploaded image will be displayed on the page unless it is marked as "removed".'),
    '#default_value' => $current_image,
    '#upload_location' => 'public://subpage_banner/',
  );

MaxRequestLen sometimes gets lowered as a result of server/module updates. Also, adding modules that add to the request length can also introduce this problem. This is why disabling modules can sometimes "fix" the problem.

See http://drupal.org/node/1015938#comment-7412202 for a solution that involves updating your vhost file, eg:

<IfModule mod_fcgid.c>
  # 50MB
  MaxRequestLen 52430000
</IfModule>

Or try switching from FastCGI to mod_php or php-fpm (if you're using FastCGI).


how to set complete site background to a color or image? I used this:
wrapper    { background-color:yellow; }
but I want really everything in the background to get colored. how to?
Code above just makes the wrapper background change.

Try applying same for body tag !

body {
      background: yellow;
    }


Multi Page Selection VBO Is there a way to achieve multi-page selection. Everytime I go to the next page, my selection gets lost. Any chance to keep my selection over multiple pages?

There is a patch for same feature https://www.drupal.org/node/1207348


Rendering renderable arrays in an item_list I'm struggling to get a render-array constructed, and I think it's because of how theme_item_list works. I would be grateful if anyone could help find the problem (or tell me to implement it without item_list!)

  The context: This function is called from my module's
  hook_block_view() to render the content of the block. The module is
  an example module showing how to use a new API. I hope nothing of that
  is needed to answer this point, except that these calls are not made
  from a theme.

The code I have is:

function example_render() {
  $block = array();

/* fill $providers[] ... */

  $items = array();
  foreach ($providers as $metric => $provider) {
    $value = $provider['value'];
    $class_link = $provider['name'];
    $name_link = $provider['name'];

    // Construct a renderable array wrapper for the template invocation.
    $items[$metric] = array(
      '#type' => 'container',
      '#attributes' => array('class' => array('provider')),
      'info' => array(
        'providername' => array(
          '#prefix' => '',
          '#markup' => $name_link,
          '#suffix' => '',
        ),
        'providervalue' => array(
          '#prefix' => '',
          '#markup' => $value,
          '#suffix' => '',
        ),
        'metricname' => array(
          '#prefix' => '',
          '#markup' => $class_link,
          '#suffix' => '',
        ),
      ),
    );
  }

  // Finally, bring it all together.. a container with the via text then a list
  // of the providers.
  $block['content'] = array(
    '#type' => 'container',
    '#attributes' => array('class' => array('example')),
    'ttl_text' => array(
      '#prefix' => '
',
      '#markup' => $record['title'],
      '#suffix' => '
',
    ),
    'via_text' => array(
      '#prefix' => '',
      '#markup' => $via_text,
      '#suffix' => '',
    ),
    'metrics' => array(
      '#items' => $items,
      '#theme' => 'item_list',
      '#attributes' => array(
        'class' => 'providers-list',
      ),
    ),
  );
  return $block;
}

and this is what I get when run with 9 items in the list:

A bacterial sulfonolipid triggers multicellular development in the closest living relatives of animals
via Lagotto article information courtesy of Lagotto

not very inspiring!

The three 'Array' under 'info' in the html here obviously correspond to the providername/providervalue/metricname arrays in the code i.e. the $items array isn't being interpreted as a render array at all.

How can I make this work?

According to https://api.drupal.org/api/drupal/includes!theme.inc/function/theme_item_list/7 theme_item_list is looking for data key so your list item should look like this:

// Construct a renderable array wrapper for the template invocation.
$tmp = array(
  '#type' => 'container',
  '#attributes' => array('class' => array('provider')),
  'providername' => array(
    '#prefix' => '',
    '#type' => 'markup',
    '#markup' => $name_link,
    '#suffix' => '',
  ),
  'providervalue' => array(
    '#prefix' => '',
    '#type' => 'markup',
    '#markup' => $value,
    '#suffix' => '',
  ),
  'metricname' => array(
    '#prefix' => '',
    '#type' => 'markup',
    '#markup' => $class_link,
    '#suffix' => '',
  ),
);
$items[$metric]['data'] = drupal_render($tmp);

That should give you single element:

test1test1test1


Contextual filter doesn't work with the name of the entity reference, it only works with its ID why is the contextual filter below only working the the id of the entity reference ID? I would to search by name like by "Oceanography" or "Ecology and Evolution", but i'm not sure how. If i add a relationship the contextual filter doesn't even work with the ID number. Please help. Thanks in advace.

Like Drupal 7 this configuration should work for you :

But for some reason it doesn't work, so your alternative is Views Taxonomy Term Name Depth module if you are working with Drupal 8.6 or higher version:``

Install and enable the module.
Add contextual filter Content: Has taxonomy term name with Depth

Save your changes.


Can I use the prepopulate module on an entityreference field in an entityform? It may be wishful dreaming, but it would be sweet if I could pull this off.  I've been banging my head against it for a while now.

Has anyone done this before?

I actually did this on a project recently.

You can use Entity Reference Prepopulate. It's nice because you can make the field disabled if it's populated, all handled through the UI.

The alternative would be to just write a little bit of JS that disables the field on the node edit form if the value isn't empty.


Upon clicking save, how do I stop the node from inserting? Upon saving a new node, I need to check against a function, if its field value is available. If not, I need to prevent the node from saving.

function mymodule_node_insert($node) {
    $uniqueName = $node->field_name['und'][0['value'];
    if (checkIfAvailable($uniqueName) == FALSE) { die; }
}

function checkIfAvailable($uniqueName) {
    return FALSE;
}

I would probably just use Unique field, as all of the legwork is done.

This module performs additional validation when a node is created or
updated by a user to require that a node's title, author, language,
and CCK fields are unique within a given context.

If you really want it in code though, I'd take a look through the source of this module and see how it adds the extra validation.
I know you said you'd prefer it in code, but I've left this here just in case it benefits anyone with the same question as you :-)


Update values using AJAX in field widget form Similar questions:

Ajax wrapper replacement on a field widget form

how to create an AJAX field widget

Problem:

Get FIELD_NAME and DELTA in AJAX callback function? (See below)

What is done:

Change value of a textfield  in a widget form (see here) upon value change (jQuery event .change()) of another textfield in widget form.

Code Sample:

in hook_widget_form:

// Changes of this field fire the AJAX event
$element['value'] = ...
$element['value']['#ajax'] = array(
                    'callback' => 'some_ajax_callback',
                    'wrapper' => 'location-div',
                    'method' => 'replace',
                    'effect' => 'fade'
            );
// This field is updated upon AJAX call
$element['location'] = ...
// Here is where the actual change occurs
if(!empty($form_state['values'][$field['field_name']]['und'][$delta]['value'])) {
            $element['location']['#value'] = ...;
        }

in some_ajax_callback:

function some_ajax_callback ($form, $form_state) {
  // Where do I get FIELD_NAME, and DELTA?
  return $field[FIELD_NAME]['und'][DELTA]['location'];
}

What happens?

As it is mentioned here #default_value is not populated using AJAX so according to this #value should be used instead.

The problem is how to get FIELD_NAME and DELTA in AJAX callback function? (See above)

UPDATE (NOT WORKING!)

I managed to figure out a workaround to make this work as following:

Item to be updated receives an ID composed of field_name and delta (e.g. location-div-myfield-0 (this is necessary if multiple instances of the same field are on the same page)
Save field name (here myfield) and delta (here 0) in $field_state (in hook_field_widget_form)
Read the saved values from $field_state in ajax callback (here some_ajax_callback) and return the desired form element.

This however works if there is only one instance of the field in the form, otherwise the values in $form_state are always those of last instance.

Possible solution

Using the triggering_element of $form_state in some_ajax_callback all necessary info can be derived:

function some_ajax_callback ($form, $form_state)
{
    // This contains info about triggering element
    // Index 0 = field name, 1 = language, 2 = delta, 3 = element name
    $element = $form_state['triggering_element']['#parents'];
    $delta = $element[2];
    $field_name = $element[0];
    ...
}

I generally do something like this:

function gft_enable_display_callback($form, $form_state) {
  // Get the array parents of the triggering element
  $parents = $form_state['triggering_element']['#array_parents'];
  // Pop off the triggering element as we usualy want the one above it
  array_pop($parents);
  // Get the element from the nested array
  $element = drupal_array_get_nested_value($form, $parents);

  return $element; // or we can return $element['someotherfield']
}

We can also use the drupal_array_get_nested_value to retrieve values from form_state['values'] as needed.


How to add a specific menu item in Panels? I am using Drupal 7. I made use of panels to partition the look of a page. I would like to know whether it is possible to add "A specific menu item" in the panels? I have used node templates to generate this page. I have 6 menu items(main menu), i want only one of them to be present in the panels.

Thanks in advance.

To the best of my knowledge, Panels can only interact which whole menues.

One option is using Menu block to slice a menu into pieces, exposed as blocks. I don't think menu blocks however can pick one item, though I haven't looked at all the advanced options.

If you just want a single menu item, can you just emulate the markup?


How to display the survey results created with the Webform module? Does anybody know how to display the survey results created with the Webform module?

I have created a survey using the grid field and it works great. I want to be able to display the accumulated results (using my CSS styling) on the same page the survey question appears. Is there a way to do this?

If you want to create charts from the survey results of the Webform module, there are 2 alternatives to pick from:

Webform Charts (used in about 400 sites), to display Webform results in a graphical manner using a charting library.
Webform Chart (used in about 220 sites), which integrates with the "Analysis" tab of a Webform (created with the Webform module) to provide charts for each individual component's analytical data.

The Drupal 7 version of both modules, requires the Charts module (dependency).


Textarea for Drupal 8 text fields content types Currently there is no option to select textarea as a widget for a long text field in a content type. What solutions are there? And why was this removed as this was in core Drupal 7.

A long textfield is a textarea by default, there's no need to explicity configure it as such. For example here I created a textfield with label "Text" as plain, long:

And this is how it looks in the node/add page:


How to display a warning message I have a form with a required checkbox.

If the box is not checked and I confirm my form, I receive a warning with Chrome (see the screenshot).

How to display a warning message in drupal ?

In my module, I add code to display a Drupal warning. Why is not it displayed ?

<?php

namespace Drupal\commerce_agree_cgv\Plugin\Commerce\CheckoutPane;

use Drupal\Component\Serialization\Json;
use Drupal\Core\Form\FormStateInterface;
use Drupal\commerce_checkout\Plugin\Commerce\CheckoutPane\CheckoutPaneBase;
use Drupal\commerce_checkout\Plugin\Commerce\CheckoutPane\CheckoutPaneInterface;
use Drupal\Core\Link;
use Drupal\Core\Url;

/**
 * Provides the completion message pane.
 *
 * @CommerceCheckoutPane(
 *   id = "agree_cgv",
 *   label = @Translation("Agree CGV"),
 *   default_step = "review",
 * )
 */
class AgreeCGV extends CheckoutPaneBase implements CheckoutPaneInterface {

  /**
   * {@inheritdoc}
   */
  public function submitConfigurationForm(array &$form, FormStateInterface $form_state) {
    parent::submitConfigurationForm($form, $form_state);

    if (!$form_state->getErrors()) {
      $values = $form_state->getValue($form['#parents']);
      $this->t('You must agree with the terms before continuing.');
    }
  }

  /**
   * {@inheritdoc}
   */
  public function buildPaneForm(array $pane_form, FormStateInterface $form_state, array &$complete_form) {
    $store_name = $this->order->getStore()->getName();
    $store_id = $this->order->getStoreId();
    $pane_form['#attached']['library'][] = 'core/drupal.dialog.ajax';
    $attributes = [
      'attributes' => [
        'modal-title' => $this->t('Terms and conditions'),
        'class' => 'use-ajax',
        'data-dialog-type' => 'modal',
        'data-dialog-options' => Json::encode([
          'width' => auto,
        ]),
      ],
    ];
    $link = Link::fromTextAndUrl(
      $this->t('the general terms and conditions of the store "@store_name"', ['@store_name' => $store_name]),
      Url::fromUri("internal:/store/$store_id/cgv", $attributes)
    )->toString();
    $pane_form['cgv'] = [
      '#type' => 'checkbox',
      '#default_value' => FALSE,
      '#title' => $this->t('I have read and accept @cgv.', ['@cgv' => $link]),
      '#required' => TRUE,
      '#weight' => $this->getWeight(),
    ];
    return $pane_form;
  }

  /**
   * {@inheritdoc}
   */
  public function validatePaneForm(array &$pane_form, FormStateInterface $form_state, array &$complete_form) {
    $values = $form_state->getValue($pane_form['#parents']);
    if (!$values['cgv']) {
      $form_state->setError($pane_form, $this->t('You must agree with the terms before continuing.'));
    }
  }

}

That’s the browser validation message appearing. If you want to show Drupal messages only, you need to set the no-validate attribute on the form tag itself so browsers ignore it. Drupal will still run validation on submission.


Alter existing route to a different route for a specific content type node using RouteSubscriber I want to modify node edit of a specific content type node to a different route .

Eg : suppose i have a node edit page route as entity.node.edit_form (core feature) . And now i want to change this route to custom_module.edit_form when taking the node to edit .

I refered This  which explains altering the existing route to a different route . It only says to route to a different url . It may not work in my case as node edit form will contain node id as parameter . Its not mentioning how routes can be placed in $route->setPath() though .

For eg:
In custom_module/src/Routing/RouteSubscriber.php

/**
   * {@inheritdoc}
   */
  protected function alterRoutes(RouteCollection $collection) {
    // Change path '/user/login' to '/login'.
    if ($route = $collection->get('user.login')) {
      $route->setPath('/login');
    }
    // Always deny access to '/user/logout'.
    // Note that the second parameter of setRequirement() is a string.
    if ($route = $collection->get('user.logout')) {
      $route->setRequirement('_access', 'FALSE');
    }
  }

How can i do this ?

You need to change the _controller for the route, check this code:

<?php

namespace Drupal\drush_help\Routing;

use Drupal\Core\Routing\RouteSubscriberBase;
use Symfony\Component\Routing\RouteCollection;

/**
 * Listens to the dynamic route events.
 */
class RouteSubscriber extends RouteSubscriberBase {

  /**
   * {@inheritdoc}
   */
  protected function alterRoutes(RouteCollection $collection) {
    // Change the controller for the help page.
    if ($route = $collection->get('help.page')) {
      $route->setDefault('_controller', '\Drupal\drush_help\Controller\HelpController::helpPage');
    }
  }

}

In this case the route is altered to replace the Drupal help page for a custom controller.

If you want to see this in action go to check the code of the Drush Help module.

Disclosure: I'm the maintainer of the module Drush Help.


How to render a template in a module controller? I want to render a custom template in a module controller but I don't know how. How do I achieve this?

You need to let Drupal know about the theme, and then you can leverage it in the controller code. The template needs to be in the folder my_module/templates.

my_module.module

function my_module_theme() {
  $theme['template_name'] = [
    'render element' => 'build',
    'template' => 'template_file_name',//This is only needed if you need a different template file name than the array key above, 'template_name'.
  ];

  //override existing template for this module
  $theme['html__my_module__template_file_name'] = [
    'template' => 'html--my_module--template_file_name',
  ];
  return $theme;
}

src/Controller/MyModuleController.php

public function index() {
  $build['#theme'] = 'template_name';
  //populate your build renderable array..
  return $build;
}


How can I make sure a javascript cookie is set before page load? I am setting a simple javascript cookie and checking it before firing a jquery ui dialog

(function ($) {
  Drupal.behaviors.setPopupConfig = {
   attach: function (context, settings) {
   if ($.cookie('modalServed') == null) {
    $.cookie('modalServed', 'yes');
    // build and show the dialog

I am adding the javascript with drupal_add_js in a hook_entity_load() in a module. In testing I've noticed that if I have a link element in the modal with a destination set to another place in the site with a potential modal dialog, the second dialog will fire before the cookie is set in the browser, which is not the intended behavior. I've tried adding weight and scope options to the drupal_add_js call, but it doesn't solve the problem. Is there another way to make sure the modal js only fires after the cookie is set?

The solution in this case was to set a path on the jquery.cookie

$.cookie('modalServed', 'yes', {path: '/'});


entity export not serializing node I am trying to use entity export to move existing entitys from a live to dev site. I tried the code below and it returned NULL int(1)
However, when I did a dump of the $node object, it did dump the object correctly, so I know that the entity exists

$query = new EntityFieldQuery();
$query
  ->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'events')
  ->propertyCondition('status', 1)
  ->propertyOrderBy('created', 'DESC');
$result = $query->execute();

$nids = array_keys($result['node']);
//var_dump($nids, 1);
$node = node_load($nids[0]);
var_dump($node,1);

//dpm(entity_get_info());
$entity  = entity_export('node', $node);
var_dump($entity,1);

The entity_export function comes with the following caveat:

  Note: Currently, this only works for entity types provided with the entity CRUD API.

This means that if your entity type does not come with this, a call to entity_export() will return NULL.

This seems to be the case with node.

I am not sure, but I think the core team never got around to adding CRUD API to core entities.

If you inspect a node entity with dpm(), there is nothing. If you do:

 debug($node->delete, 'node->delete');

it prints NULL.


Printing a drupal 7 user field into a link Ok so my goal here is to allow users to link there social media profiles onto their user pages. So i tried to print the field within an href statement so it would come out as a link.
For example if the value for the field link is http://www.google.com, then it should output the text link with a link to google when clicked.

But it doesnt, it instead outputs the value for the field_link and links it to

Heres what i attempted at:

<a href="<?php print render($user_profile['field_link']); ?>">Link

Any help is appreciated!

Edit:
Ok so this is what it outputs:

But i only want the web address
Please Help!!

Use the Link field Module:

  The link module can be count to the top 50 modules in Drupal
  installations and provides a standard custom content field for links.
  With this module links can be added easily to any content types and
  profiles and include advanced validating and different ways of storing
  internal or external links and URLs. It also supports additional link
  text title, site wide tokens for titles and title attributes, target
  attributes, css class attribution, static repeating values, input
  conversion, and many more.

Or better, yet do a search for drupal social media for a number of different modules to do exactly this.


Are there plugins available for an "improved" Find Content admin interface? One of our clients has a lot of content over a number of languages and has expressed that they don't really like the Filter/Sort options available on the Find Content page.

Are there any plugins available that present this information in a different manner...maybe something like Windows Explorer?

Have you tried VBO module? that, allows you create custom admin interface.