How to highlight search results views? I created a view to replace the search default of my website. So I explained the form in a block. Everything works fine, but I would like to highlight search terms in the results.

You can try to use the Highlight module. From its project page:

  Highlight the keywords from referrer search engine
  Highlight the keywords from local search

And I think that you should read this posts:

Highlight searched keyword using exposed filter views?
Add Keyword Highlighting using Search API in Drupal 7


Change date format in comments How can I change the date format in my comments?

Right now it looks like this:

  Sat, 09/01/2012 - 12:00

I want it to look like this:

  Saturday, September 1, 2012

I was able to achieve this in page.tpl.php in a section where I just display the date, but have no idea where to do this so it works for my comments too.

If you want to do it sitewide, you can edit the definitions at admin/config/regional/date-time/formats

You can also add your own formats there, and then use them in format_date() similar to what @Epok outlined.


Image-link to content works only on preview I have a view showing content of a specific content type. In the view, I show 2 links, linking back to the specific content. The first one is an image field and the second is the title field. Both links work on the preview but on the actual display only the title links to the content. The view is shown through a panel.

Views preview does not use templates from your theme. Expand Advanced on the right, and in Other section click Theme: Information. Find .tpl.php files that are bolded and may apply to your fields (are applied to them directly, or to their parents). Look for them in your theme's directory and search them for errors.

If that will not help, offending template comes from Panels, not Views themselves.


Updating to a newer dev version of a module using Drush (ignoring point/recommended releases, without trashing version control) [NB This question is off the back of, but separate/further to, an earlier question of mine, here.]

I've been using Drush a good while, but every so often I get stumped. At the moment, I'm really not sure how to go about this.

Scenario: currently, the site uses a dev release, dated way in the past. In the meantime, no point release has been created, but a newer dev release has. So we have something like:

Reroute Email           6.x-1.x-dev (2010-Sep-27)
Recommended version:    6.x-1.0 (2008-Jul-24)
Development version:    6.x-1.x-dev (2011-Feb-25)

Doing drush dl <module>-6.x-1.x-dev overwrites the existing  directory with the latest 1.x dev release. That's fine, but it trashes the .svn folder.

If I do drush upc <module>, it will download the point release (see edit below), which I don't want, but if I do drush upc <module>-6.x-1.x-dev, it just refreshes the update data and then tells me "Specified version already installed" on the relevant line on the output.

So how do I use drush to overwrite the old dev release, getting the new one in its place, without trashing the SVN folder?

EDIT: Actually, in this instance, drush upc <module> downloads the correct version, but I'm pretty sure if the point release was dated like 6.x-1.0 (2011-Jan-24) it would have gotten that one. Anyone want to clarify/correct?

I found your question just now because I had the exact same question. Didn't find an exact answer, but this worked for me:

#svn rm <module>
#svn commit -m"removing the module... whatever you want to write"
#drush dl <module>-6.x-2.x-dev
#svn add <module>

For some reason, not doing the commit between the rm and the dl caused a problem with svn. I do not know enough about svn to know why, but would be grateful if someone could elaborate!


Defaulting a value for a new boolean field added to an existing content type with content? We have a Drupal 8 site. For one of our features, I added a boolean field called 'Pinned' to a our Blog Post content type.

As I added the filed as a filter criteria to views, I noticed that, no matter what configuration I selected, Is equal to + True, Is equal to + False, Is not equal to + True, Is not equal to + False, my view preview, which had had results, suddenly gave no results. I thought surely one of these combinations must apply to at least one node.

I added the 'Pinned' field to the fields of the view to examine the values, and removed it from the filter criteria. It turns out that the field was technically NULL, from the join-- there was no record in node__field_pinned.field_pinned_value.

To further test, I edited one of our blog posts nodes. When I checked the 'Pinned' checkbox, the value in the view became 1. When I then unchecked the checkbox and saved the node, then value became 0.

Trying to think of ways to auto-populate the field, I made the 'Pinned' field required.

But, all that did was make it necessary to check the checkbox when editing or adding a Blog Post.

This didn't solve my problem, and seemed to make the field redundant anyway. You can't save the node without checking the checkbox; you have to check it.

Edit going off Grapple's answer, I found that if I changed the widget to "Check boxes/radio buttons" on the "Manage form display" page of the content type. This does allow you to set a default value, but it does not auto-populate existing node field values, nor does it auto-populate the form widget for existing nodes.

It only auto-populates the form for new nodes.

It seems like a boolean field with a checkbox widget is meant for situations where the user cannot advance without checking the box, such as accepting terms of service, etc.

As it is, it is difficult to use, because we have hundreds of Blog Posts, and it's pretty labor intensive to edit each one and check, then uncheck the box. We only want a few pinned posts, but we can't have views of unpinned posts being empty.

Is there a way I can add a Boolean field to a content type with existing nodes and have it auto-populate with values?

If the field has a default value configured, you may be able to cause the "Pinned" field to be populated by bulk editing the nodes from the content overview page, and toggling a different value like 'Published', 'Sticky', or 'Promoted to front page'.

For a programmatic solution, implement hook_post_update_NAME to load the necessary entities and update the new field with the required default value.


Display file description in view using Download Count I have created a view to display my most download files on the site and allow users to download them, to do this I am using the download_file and download_count modules.

The view should display a list of the most download attachment files on the site, I need to display the file name, a download link and then the file description.

When I try to insert the file description into the view I start running into problems, I am doing this by adding the field_attachments field (which is the field inside of my content type that the files are entered into).

When I add field_attachments all of the files associated with a files related node are displayed in the result, instead of what I expect which is just the single description for that file per row. This is probably an issue with relationships, does anyone know of a way to solve this?

I have figured it out, I had to add another relationship for the fields file id "field_attachments:fid" and then applied that relationship to all of the other fields.

Then I changed the aggregation settings for the attachment description field to group by 'fid' with 'display' and 'description' as additional grouping columns.

Now my view output only displays the matching description of the file in that row.


Entity Reference Views - Contextual Filters - Administrator override I have an Entity reference field View with contextual filter with Logged in user ID . The result of this view could be seen by the user only if he/she added some data. That is fine.

I would like to use the same Entity reference field View, so that administrator can view all the results without any restriction.

How can we achieve this.
Thanks for the help.

I'm not really sure why this works but anyways.. It seems to be what you want.
You'll need Views Contextual Filters OR.
In my test, I used the contextual filter for author UID. So your entity reference field would only shows nodes created by the current user.

In your view, add the Content: Author relationship (don't check required) and Content: Author uid contextual filter (provide default: current user).
Enable Contextual filters OR in Query settings under Advanced.
Add a second contextual filter for Content: Author uid (provide default: current user)
Under More at the bottom of the filter, click exclude.

When added this an entity reference field, normal users only see nodes they've created but as admin, I see every node on the site. Weird but it works.


Migrate WordPress blog to Drupal I'm migrating two blogs from WordPress to Drupal 7. How would one handle migrating user subscriptions from the WordPress blogs? I've already used the Migrate module and it looks like that only handles content.

You may try using WordPress Migrate which supports migrating WordPress blog exports (WXR format) into Drupal using Migrate module. Check also Migrate Extras which provides additional support for contrib modules.

For any other extra functionality which is not covered, you've to extend it by writing your own custom class. Check Migrate Example for example of migration data.

See also: What is the most reliable way to migrate a Wordpress site into Drupal?


Migrate part of a Drupal 6 installation to a new Drupal 7 installation I'm trying to migrate the users and the Forum nodes (including comments) from Drupal 6 Installation (current productive system) to a new Drupal 7 installation (staging system). I wanted to start from scratch with Drupal 7 so I did not go the upgrade way, but now I'm facing the problem that some data has to be migrated anyway.

I tried several Import/Export modules, but none really does what I want. Any ideas?

I might try the Migrate module.  It takes some coding but  but the documentation and example modules for it are very detailed and helpful. Basically you would create a migration class for the users (see BeerUserMigration) and a class for the forum nodes (see BeerNodeMigration).

One of the great things about this module is it creates a mapping between both data stores which allows you to rollback and re-run the migration until you get it right.


How do I override LoginTobbogan so that it redirects to Front Page on 403? We have a Commerce Kickstart 2 site using LoginToboggan.

What we want is this: if an anonymous visitor goes directly to a node which is unpublished we want them to be redirected to the front page.

We do NOT want them to get a 403 (Access Denied) or to see a login form ... which seem to be the only two options available.

I've tried using Rules, but unfortunately Logintoboggan seems to take precedence over Rules.

Is there a way to override Logintoboggan's 403 behaviour?

OR is there another login module we can use which allows for login by either user name OR e-mail address that doesn't hijack 403? (That's basically the only reason we're using LT--people have gotten used to using e-mail addy to login.)

Option 1: Use the CustomerError module

As per the "... is there another login module ..." part of your question, you may want to look at the CustomError module. Here is a quote about it (from its project page):

  ... allows the site admin to create custom error pages for HTTP status codes 403 (access denied) and 404 (not found), without the need to create nodes for each of them.

  Main features:

  Configurable page title and descriptions.
  There are no author and date/time headers as with normal nodes.
  Any HTML formatted text can be be put in the page body.
  The error pages are themable.
  Users who are not logged in and try to access an area that requires login will be redirected to the page they were trying to access after they login.
  Allows custom redirects for 404s.

More specific, related to the LoginToboggan module, this is how the CustomError module integrates with it (quote from its README.txt, bold markup added here):

  If this module is enabled, it can enhance CustomError's handling of
  access-denied messages, but you have to be careful to set them up to
  work together correctly.

  These two modules both attempt to take over handling of system 403
  ("access denied") messages, and can conflict. CustomError does it by
  asking you to go to "admin/config/system/site-information" and
  manually setting the "Default 403 (access denied) page" to
  "customerror/403", whereas LoginToboggan sets that same field to
  "toboggan/denied" automatically (overwriting any other value that
  was there), when you enable its "Present login form on access denied
  (403)".

  If you are using CustomError with LoginToboggan, you should allow
  LoginToboggan to perform this take-over (in other words, don't set
  the "Default 403 (access denied) page" to "customerror/403"). This
  way, if someone attempts to access a page that they don't have
  access to, LoginToboggan will first give them a chance to log in if
  they haven't yet. If they still don't have access to the page,
  CustomError then takes over from LoginToboggan (by overriding one of
  its theme functions), displaying its customisable messages for
  access-denied errors.

So using what is described in this last (bold) sentence, you may get it to work the way you'd want to (or at least come closer to the solution you're looking for).

Option 2: Retry with the Rules module

Your (failed) attempt to use the Rules module, might be because you have NOT used event "Drupal is initializing". You may want to retry, using this "Drupal is initializing" event. That might help to ensure that the rule gets trigger 'BEFORE Logintoboggan has a chance to take precedence' (so that you are NOT too late).

For a sample of a Rule (in export format) using this "Drupal is initializing", refer to my answer to the question "How to redirect user using Rules when user visits a link with view?".


Can't direct a domain to a working D7 test site I've created a D7.29 test site on godaddy's "deluxe classic hosting" plan at www.mybusiness.com/test  and it works great. The site structure is  root\mybusiness\test.      Now I've been trying to copy it to the root and direct a client's web domain to that copy and now all the user gets is the first page (very quickly I might add, like it was a static page) but all links that you click on or when trying to log in just result in "Internal Server Error..."

I then tried to direct the client's domain  www.hissite.com to the original test site's folder at root\mybusiness\test and all it results in is the same error, even after waiting an hour.

I then read about the settings.php option of   base_url = 'http://www.hissite.com';  so I enabled that and still get the same error.  What's wrong?  How come I can't just direct a domain to a working Drupal instance?

Any help would be greatly appreciated!!

Dave N

Fundamentally, there is absolutely no problem with pointing a domain to a functioning Drupal instance.  That being said, there are many other things that can be going on here.  Let's tackle a few of them.

First of all, when you change the DNS settings for a domain, it can take a day or more to fully propagate, due to the way different DNS servers cache their entries.  To make matters worse, the change can make it to you at a different time than someone else, which makes it difficult to detect what is going on.

If you want to see results immediately for testing, then you need to manually add an entry to your hosts file that points the domain name to the server that you want to see the results for.  In a Linux machine, the hosts file is /etc/hosts, and on a Windows machine, it is \Windows\System32\drivers\etc\hosts.  You add an entry just by adding a new line to the end of the file in the form of:

XXX.XXX.XXX.XXX www.hissite.com

where the XXXs are the IP address of the target server.  The change is instant when you save the hosts file (i.e. no need to restart).
$base_url is a setting that affects how Drupal creates URLs internally.  If the links that Drupal is creating look correct (e.g., www.hissite.com/node), then it is working correctly.
This could be a problem with clean urls.  If you go to www.hissite.com?q=user, and that works, but www.hissite.com/user does not, then the server is not correctly interpreting clean urls.  Your only options are to either enable clean urls or to choose a different host, since you likely don't have direct access to the server settings.  (Disclaimer: I haven't used GoDaddy's service, so I don't know the extent to which you can modify server settings.)  Basically, if the server is running Apache, then, in order for clean urls to work, Apache must be allowed to parse your .htaccess files, and it must have mod_rewrite enabled.
A final test would be to see if perhaps the .htaccess file is not being interpreted at all.  Try going to www.hissite.com/index.php?q=user.  If that works, but www.hissite.com/?q=user does not, then it is definitely a server setup issue, and I do not know if GoDaddy provides you with the tools to fix it.

Finally, I want to address your fundamental problem as I see it: you are using GoDaddy.  I'm slightly biased against them for various reasons, but mostly I think that you can have a better experience for roughly the same cost by setting up your own VPS somewhere.  I use DigitalOcean, and have for quite some time (I have no affiliation with them other than being a customer).  For the same cost of the GoDaddy deluxe hosting, you can have your own small VPS which can run several sites.  I do this with my personal site, http://cscrunch.com, as well as a handful of other, family sites.


Theming and designing css in Drupal 7 Ok, I know this is a general question, but I really looked information for a long time, and couldn't find helpful info that helped me.

I almost finish developing my community site in Drupal 7. Now I am starting to design it. I chose Zen theme, and created sub-theme.

Can you please recommend me about the best convenient method to implement CSS to DRUPAL site?

Thanks in advance

Well that's  very vast topic, however few things I would like to share with you are:

The best place to start can be the documentation of ZEN theme: https://drupal.org/node/193318. They are having pretty good maintained doc.
Must go through tutorial is drupal's theming guide: https://drupal.org/documentation/theme
To undertand the basics of theming: http://drupalize.me/videos/introduction-theming-basics-drupal-7
How to create the subtheme: here is official doc on how to create a sub-theme as per drupal standard.
Also there is one nice video tutorial on creating a sub-theme of Zen: http://www.youtube.com/watch?v=y-IXpbdgA3A
One good answer on creating a theme with drush command: How do I create a Zen's sub-theme using Drush?
Moving further you can check how do drupal process theme variables for templates: Setting up variables for use in a template (preprocess and process functions)
It would be good to learn few of the CSS frameworks: SASS framework, LESS framework

I tried to cover few of the quick points that striked me first, but anyways there is no limit of learning, so keep on exploring!!


How do I filter a view with a field on a group the current user is in? The site I'm working on will have many OG groups, each with a list of topics relevant to their members. I would like to show content to the logged in user that is about their group's relevant topics.

I started by creating a vocabulary (Topic) and two content types (Group and Post). Group and Post both have a term reference field that lists Topic terms (groups have topics that are relevant to the group, and posts have topics about which they're written).

How can I create a view that shows only posts with at least one Topic term in common with the logged in user's group's Topic list?

It looks like this may not be possible with the current stable release of OG (7.x-1.3). I think it would require at least the patch from issue #1341990 along with the patch from this comment on issue #1151648, but I'm completely new to Drupal so it's not unlikely that I'm missing something.


How to add Retargeting tag into each page? I am using drupal - 7.

I wanted to embed <script> tags for Retargeting tag into each page of the Website, between the <body> </body> tags.

I am new to Drupal. I am trying to create custom block module for this.

I have created custom module to place  tags into custom block. I am not sure what I have done is right or wrong. Can any one help me with this?

I just wanted to add script like this into each page for Retargeting tags for campaigns

<script async src="http://i.simpli.fi/dpx.js?cid=0&segment=Segment+Name&campaign_id=0"></script>

I have added script tag into my js file which I have called from .info file.
In my .info file I called;

scripts[] = MyCustomBlock.js

This is the code for my custom block module.

/**  * Implements hook_help().  *  * Displays help and module
information.  *  * @param path   *   Which path of the site we're
using to display help  * @param arg   *   Array that holds the current
path as returned from arg() function  */

function MyCustomBlock_help($path, $arg) {
  switch ($path) {
    case "admin/help#MyCustomBlock":
      return '<p>' . t("Displays links to nodes created on this date") . '</p>';
      break;
  }
}

/**
* Implements hook_block_info().
*/
/**  * Declaring the block  */
function MyCustomBlock_block_info() {
  $blocks['MyCustomBlock'] = array(
    // The name that will appear in the block list.
    'info' => t('MyCustomBlock'),
    // Default setting.
    'cache' => DRUPAL_CACHE_PER_ROLE,
  );
  return $blocks;
}

/**  * Preparing for a module configuration form  * Implements
hook_menu().  */

function MyCustomBlock_menu() {
  $items = array();

  $items['admin/config/content/MyCustomBlock'] = array(
    'title' => 'MyCustomBlock',
    'description' => 'Configuration for MyCustomBlock module',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('MyCustomBlock_form'),
    'access arguments' => array('access administration pages'),
    'type' => MENU_NORMAL_ITEM,
  );

  return $items;
}

/*  * Adding JavaScript from within a module  */

function MyCustomBlock_add_js($data = NULL, $options = NULL) {
    $javascript = &drupal_static(__FUNCTION__, array());
    $jquery_added = &drupal_static(__FUNCTION__ . ':jquery_added', FALSE);
}

I can see my block module in the /admin/modules section and I can enable my custom block module. But, I am not sure how to add that script into my module.

Thanks for the help!

drupal_add_js() doesn't support the async property (there is a patch however) but the simplest solution would be to just just add that line to your html.tpl.php as Geoff suggested.


How do I programmatically add a new language? I am using Drupal 8 on a multi-lingual site which uses Arabic and French.

I need to programmatically add a new language from a custom module. How can I do it?

You can use below way:

 \Drupal::service('module_installer')->install(['language']);
  $langcode = 'ca'; // get language from Your Form Input
    //print_r($langcode);
  $language = ConfigurableLanguage::createFromLangcode($langcode);
  $language->save();


How to add a correlated subquery expression in hook_views_query_alter? In hook_views_query_alter, how to add a condition which is a correlated subquery in which the value of the condition is an expression?

Given a view the produces this query:

SELECT node.nid, node.title, history.state
FROM node n
LEFT JOIN node_revision nr ON n.vid = nr.vid
INNER JOIN history h ON nr.vid = h.vid
WHERE (( (node.type IN ('blog')) ))

In order to show only the latest [state] for a given version (vid) of a node, we need to add this condition:

AND h.hid = (select max(hid) from history h2
where h2.nid = n.nid
and h2.vid = n.vid group by h.nid, h.vid)

So here's the statement we'd like to end up with after hook_views_query_alter:

SELECT node.nid, node.title, history.state
FROM node n
LEFT JOIN node_revision nr ON n.vid = nr.vid
INNER JOIN history h ON nr.vid = h.vid
WHERE (( (node.type IN ('blog')) ))
AND h.hid = (select max(hid) from history h2
where h2.nid = n.nid
and h2.vid = n.vid
group by h.nid, h.vid)

So we can see that our modified sql works, so here's our attempt (not working) to modify the statement on the fly:

function mymodule_views_query_alter($view, $query) {
  if ($view->name == 'my_view') {
  $expression = '(select max(hid) from
   workbench_moderation_node_history h
   where h.nid = node.nid
   and h.vid = node.vid
   group by h.nid, h.vid)';

  $condition = array();
  $condition['field'] = 'history.hid';
  $condition['value'][] = $expression;
$condition['operator'] = '=';
$query->where[1]['conditions'][] = $condition;
  }
}

This doesn't work (with or without the parenthesis) because the condition is an expression, not a value.  To validate that the syntax of adding a condition is correct, this will at least return results:

function mymodule_views_query_alter($view, $query) {
  if ($view->name == 'my_view') {
    $condition = array();
    $condition['field'] = 'history.hid';
    $condition['value'][] = '1';
    $condition['operator'] = '>';
    $query->where[1]['conditions'][] = $condition;
  }
}

How might we go about coding this constraint?

This doesn't answer the question as stated, but provides a very simple approach to get at the result using Views without implementing hook_views_query_alter.

The example provided is for workbench_moderation, although the principle applies in other scenarios as well:

Creating a new Workbench view showing recently updated content and its state


Is there a way to check if a custom form element exists in application Suppose i am building a custom form element with

  hook_element_info()

Is there a way , in another module,to check this element's existence before inserting it to a form?

You can invoke the hook yourself to check for the existence of a specific element type:

if (in_array('some_element_key', array_keys(module_invoke_all('element_info')))) {
  // The element type exists.
}


Include specific stylesheet for specific language? I have the following stylesheets:

stylesheets[all][] = AAA.css
stylesheets[all][] = BBB.css
stylesheets[all][] = CCC.css
stylesheets[all][] = chinese.css

AAA, BBB and CCC are fine. They should show for all languages. But I need english.css to ONLY show if the language code of the current page being viewed is:

cn-zh
tw-zh

The language code is retrieved from the i18n module:

$language = i18n_language();
$languageCode = $language->language;

How can I include this stylesheet for this case?

So you will probably need to remove the style sheet from your info file and add it in a pre-processor.

I normally don't recommend using pre-processor functions but this is kind of the ideal exception to that rule. Checkout template_preprocess_html. In that hook you can pull the active language setting and conditionally add the language specific css file with drupal_add_css

function mytheme_preprocess_html()
{
  // Don't remember the code for this but you can figure that out.
  $language = getLanguage()

  if ($language == 'chinese_traditional')
  {
    drupal_add_css(drupal_get_path('theme', 'mytheme') . '/chinese.css');
  }
}

If the get language function uses a database call it would be better to do this in a custom module. DB calls in the theme are pretty much always a bad idea. You would in that case use the same code in hook_preprocess_page. At least that is what I was always told to do.


Drupal 2 blocks same form function with different output not working I have dynamically created some blocks depending on how many entries I have in the database:

    function my_module_block_info() {
        $result_set = db_select('my_products', 'products')
            ->fields('products', array('pid', 'name'))
            ->execute();

        $blocks = array();

        foreach($result_set as $product) {
            $blocks['my_product_' . $product->pid] = array(
              'info' => ('My Product ' . $product->name)
            );
        }

        return $blocks;
    }

    function my_module_block_view($delta = '') {
        $pieces = explode('_', $delta);
        $pid = $pieces[2];
        $product = db_select('my_products', 'products')
            ->fields('products')
            ->condition('products.pid', $pid, '=')
            ->execute()
            ->fetchObject();

        $block['subject'] = $product->name;
        $block['content'] = my_module_block_content($product);
        return $block;
    }

function my_module_block_content(&$product) {
    $form = drupal_get_form('my_module_block_form', $product);

    $output = '<p>' . $product->price . '</p>';

    $output .= drupal_render($form);

    return $output;
}

function my_module_block_form($form, &$formstate, $product) {
    $form['submit_product] = array(
      '#type' => 'image_button',
      '#button_type' => 'submit',
      '#src' => base_path() . path_to_theme() . '/images/buy.gif',
    );
    $form['product_name'] = array(
      '#type' => 'hidden',
      '#value' => $product->name,
);
    return $form;
}

My problem is that when I have 2 blocks with different products on one page, the submit function for the second block displayed has the value of $form['product_name']['#value'] equal to the first block, which is an entirely different product. What am I doing wrong?

I would suggest to prefix the form array with your product ID (I guess $product->pid or something like this) :

function my_module_block_form($form, &$formstate, $product) {
    $form[$product->pid]['submit_product] = array(
      '#type' => 'image_button',
      '#button_type' => 'submit',
      '#src' => base_path() . path_to_theme() . '/images/buy.gif',
    );
    $form[$product->pid]['product_name'] = array(
      '#type' => 'hidden',
      '#value' => $product->name,
    );
    return $form;
}

Then the fields shouldn't be overwritten.


Quick edit many SKU fields in Drupal Commerce Is there a way to quickly edit many SKU fields in Drupal Commerce? I have the Back Office quick edit and its great for price or stock control, I have also tried editable views but it seems that the SKU field can only be edited by accessing a full edit of the individual product. With 500+ products this could take quite a while. We have a seperate database external to Drupal where the product ids don't correspond to the SKU but would like to make that happen so in the future we could use feeds to import price changes, product title changes etc.

An alternative way of doing this is as follows:

Create a view for the products including SKU & Product Id (assigned by drupal commerce)
Export the view into a csv using the views_data_export module.
Amend your SKUs in the csv file using any text editor. This should make it easier to amend.
Create a feeds importer, with settings "Update existing commerce products", and using the "Product Id" as unique key (instead of SKU).
Load the amended csv to update the SKUs in the database.


Robust handling of the pager in an Ajax controlled View, when URI is shared with another user? I have a gallery content type, it references a number of images. When viewing gallery content, a View renders a gallery image, and a pager set to display a single item at a time allows the user to go back and forth with a link that will change the url.

As a user, I can now copy the URL and send it to someone else, who will see exactly the same image.

Problems show up however, when we decide to load only the new image, instead of the whole page, with JS. Since we no longer change the url, the JS-using user will remain at page=0 all the time, and can no longer share this URL as intended.

I have two suggestions of my own, but I haven't implemented either yet, and would love to hear either comments on those, different answers, or just votes on whichever answer you think is the best.

With Javascript, I could manipulate the # value of the URL without triggering a page reload. Using this, a custom Javascript pager could be implemented, that will override the ?page value with any #page value instead. Unfortunately that would mean loading two images. This way, paging with JS will update the #page value, and this url can then shared and get the intended behavior.


Field collection translation structure: entity translation vs. node-type translation I have a site with field collections and the entity_translation module that saves field collections after the following format:

When I save a new translation via the edit page, Drupal adds a new parent field collection row in field_data_field_parent_fc (en, en-gb, en-au). Each parent field collection points to a different text field (en -> 100, en-gb -> 101, en-au -> 102, etc.)

This is want I want to happen. There should be one row in field_data_field_parent_fc, containing language und, which points to a single text field (100). Then in the text field table, there should be a translation for en, en-gb, and en-au.

What I want is something akin to entity translation as opposed to node translation. Is there a setting for this, within the entity_translation module or otherwise?

It turned out that while I had field collections enabled in /admin/config/regional/entity_translation, the language must be set to "Language neutral" for field collections. This creates a single "und" row, and the child text fields can have their own entries for language.

Also, make sure the "Field Translation" setting is disabled for field collections under /admin/structure/types/manage/{your_content_type}/fields/{your field collection field}. This way, the field collections won't be translated, but the underlying text fields will be.


Single view on multiple pages 1) I created a content type Portfolio-Item. In this type a text field Project-Url was defined.

2) I created a view containing a gallery using jQFX module displaying content of Portofolio-Item elements which where published.

I wan't to add this view to different pages containing different projects portfolios.

a) Is it possible to add a "filter criteria" or "contextual filter" that would compere the Project-Url field with page URL and filter available Portfolio-Item's to display only proper one's. ?

b) Is there any easy way to achieve this?

c) Can contextual filter's be used with regular expressions?

I would recommend you to use a Viewfield or the EVA Module. With both of them you can attach a view to an entity and add arguments. I personally prefer EVA to do stuff like this. Very handy and allows you to use the same in different contexts without exposing it to the site admin directly.


commerce kickstart - how to edit a view ? the link is missing I am really clueless why the edit link of the view is gone in Drupal Commerce, even Drupal 6 used it before.

Where is the edit link?

It is available if you enable the "Contextual Links" module.


Loading a specific node revision for view I am trying to load a specific revision for viewing by the end user. Drupal 7.

I have the following in my .module ;

function mymodule_node_load($nodes, $types) {
  if ($nodes[821]->vid != 5928) {
    $nodes[821] = node_load(821, 5928);
  }
}

function mymodule_node_view($node, $view_mode, $langcode) {
   $node = node_load(821, 5928);
}

If I dpm/var_dump the node after doing this, its perfect and is the correct revision but when it comes to rendering, the page chooses the older revision. So something is happening between these functions and the page rendering. What is it? And how can I stop it?

Thanks in advance, much appreciated.

EDIT Anybody know if there is a hook load order chart somewhere? That would be super handy.

EDIT #2 It seems that even the node.tpl.php has the correct revision but what is displayed is not the correct revision ... See image (body['und'][0]['value'] != what is displayed.)

EDIT #3 Ok, so I worked out how to do it (code below) its an awful solution and its because of this that I am going to have a look at the Workbench module because I think it might just do what I need. Thanks for all the help!

/**
 * Implements hook_node_view_alter().
 */
function mymodule_node_view_alter(&$build) {
  $latest_revision = _get_latest_published_revision($build['#node']);

  if ($latest_revision) {
    $build['#node'] = node_load($build['#node']->nid, $latest_revision);
    node_build_content($build['#node']);

    $build['body'] = $build['#node']->content['body'];
  }
}

I think you have misunderstood the usage and intent of hook_node_load. What you do is changing the revision ID (vid) after the node has been fully loaded. Same for hook_node_view(), you are not supposed to replace $node in there, but add additional content to render to $node->content.


What is the use of sync directory? I see in Drupal documentation about Configuration Management it is adviced to change the location of the sync directory in a production environnement.

But I can't find an explanation about the actual use of this directory. For what does Drupal use it ? (I expect a more accurate answer than "synchronizing", which I can formulate myself but is not very helping...)

And why is it unadvised to keep this directory accessible from the web ? What could be the consequences ?

It's where Drupal exports configuration (YAML files) to, and reads configuration from (for example using drush config-export and drush config-import respectively). The term "synchronising" refers to Drupal comparing the contents of those files to the site's active configuration, and applying any config that's changed.

You want to keep that folder out of the public web server for at least 2 reasons:

Those files could potentially contain sensitive data
You're potentially exposing the structure and configuration of your site to the world. Those details could be advantageous to an attacker.

Best to err on the side of caution and keep them away from prying eyes.


How to add up rows in a view? I would like to show a "cumulative total" of nodes by date. For example, it should look like this:

date number total
1/1  1      1
1/2  3      4
1/3  2      6
1/4  4      10

I've tried views_php without luck:

Have you tried the Views Calc module? I think you will get what you want from it. Here is an excerpt about it from the module's project page:

... adds simple calculations to a views table. Requires the Views module.
You can SUM, AVERAGE, COUNT, MIN, MAX, or AVG selected columns. A plug in theme makes the view look more spreadsheet-like (right justifies numeric fields, shades calculated columns and rows, and underlines calculated rows).


How to create programmatically multiple URL alias of same taxonomy term? I have category cars and I want to create its URL alias according to the region like if the user location is Australia than URL will mysite/australia/cars similar if the user location is USA than URL will be mysite/usa/cars.

Can you please anyone tell how can I achieve this kind of functionality?

Thanks in Advance.

If you use pathauto module:

You can use hook_pathauto_alias_alter  like the following:

/**
 * Implements hook_pathauto_alias_alter().
 */
function YourModuleName_pathauto_alias_alter(&$alias, array &$context) {
  // Change tags here by your term name
  if ($context['module'] == 'taxonomy_term' && isset($context['type']) && $context['type'] == 'tags'){
   // Get the current user the location for example australia
    $user_location = 'australia';
    // Change the alias to be
    $alias = $user_location. '/cars/[term:name]';
  }
}


Display a message is not giving result? I like to show a message on 1 page of my website after login. Therefore I made a rule. To determine the mobile device I use module : mobile_detect.
I installed the corresponding library. Checking the status is saying it is available.

They module readme shows the example code:

$detect = mobile_detect_get_object();
$is_mobile = $detect->isMobile();

So when I rewrite this in a message with php eval like this:

#
<?php
$detect = mobile_detect_get_object();
$is_mobile = $detect->isMobile();
print ($is_mobile);
?>
#

So the result should be : #TRUE# or #FALSE# but I get back # #.

What can I do to solve this?

According to PHP manual

  A boolean TRUE value is converted to the string "1". Boolean FALSE is converted to "" (the empty string). This allows conversion back and forth between boolean and string values.

You can use below code instead

print ($is_mobile ? "TRUE" : "FALSE");


drupal 7 hidden views blocks when node references value is empty I created Expert and Review content types, both have a node reference field related each other.

Expert
    - title
    - field_expert_reviews(node reference)

Review
    - title
    - field_review_expert(node reference)

I follow this tutorial create a block show expert's review in the side bar. But I found that when the field_expert_reviews is empty, the block doesn't hidden. How to hidden the block when the node reference field is empty?

You need to add a Filter Criteria which validates to "Is not empty (NOT NULL)" on the field which should not be empty.


How to access files from a custom block without code I've created a custom block in D8 via the UI. Is there any way to reference the files path in order to use images in the block without having to create a module?

I might be misunderstanding, but in a custom block you should be able to use standard img tags to display an image you've uploaded to your site.


Stop registration form from sending mails I want to stop the registration form from sending "email activated" email to users, is there a way to stop them?

Google is your friend, a search for "drupal 7 user registration email settings" produced:

User: access and management settings

configure user registration, user email, and user picture settings on the Account settings page:

Administer > Configuration > People > Account settings) in Drupal 7, and (Administer > Settings > User) in previous versions.


paypal no shipping address on file Problem statement: When users pay for an order at paypal, in almost 50% cases(for both verified and unverified paypal users) the transaction slip(for business account) does show shipping address(confirmed address), but for other 50% users it is saying "We have no shipping address on file" even if users enter shipping details on paypal review page.

Using Paypal Express Checkout payment Method.

Currently we are passing NOSHIPPING=1

What should be the parameter for NOSHIPPING ? What could be the problem ?
Please help.

try not passing that parameter at all
Here is an excerpt from the PayPal's Express Checkout Integration guide  about Shipping address:

Suppressing the Buyer's Shipping Address
You can suppress the display of the buyer's shipping address on the
PayPal pages. You might want to do this in these cases:

You are selling a product or service that does not require shipping.
You prefer to handle addresses completely on your own and do not want
to let buyers choose from their PayPal address book.

To suppress the display of the buyer's shipping address, set the NOSHIPPING parameter to 1
in the call to SetExpressCheckout. No shipping address displays
on Express Checkout pages.

Hope this helps.


Drupal doesn't detect my MySQL installation Does Drupal 7 use some special libraries for MySQL?
I tried to install the 7.8 version, and the only option for the database I have is "SQLite."

I am running Drupal 6 on the same server, and it works fine.
I am using PHP 5.2.8, and MySQL 5.1.38.

Do I need any additional library?

You need to have the PDO driver for MySQL installed for Drupal 7. This is indeed different from Drupal 6. Instructions are at http://drupal.org/requirements/pdo. I hope those instructions are sufficient for you.


How can I move custom panels content from a panel to a mini panel (using Features)? I have created a large number of new custom content pieces with a rather complicated configuration for visibility settings, etc.

However, I now need to re-use this custom content across a large number of panels (originally, I had thought I would only need it for one panel).  So, I want to move the custom content to a mini-panel.

Is there a way to move this content from the panel to the mini panel instead of re-creating it manually?  I am managing deployment through the Features module, so all of my panels and mini panels are already in code.  However, I opened up myfeature.pages_default.inc and there is a huge amount of code; I wasn't able to find the positioning information for the panels/mini-panels.

I ended up just doing it manually.  Though it took some time, I was unable to find a faster solution.


Where do I add a jQuery UI in Drupal 7? I have a view where I want to use the jQuery UI slider.
For the moment, I've just put the following in my template.php:

drupal_add_library('system', 'ui.slider');

This doesn't feel right.

Is there a better place to put something like that, or at least do a check so it only get loaded when it is needed?

Ok, you can use preprocess functions for views.

Drupal 6 - Add Javascript to a View
Programmatically set a css class of a view
Using views preprocesses to add css and js to a view


Type hinting - which is better, UserInterface or AccountInterface? Recently I've finally begun shifting my focus from D7 to D8, and I'm converting a site over to D8. In D7, I type-hinted my account objects as \stdClass, since they were not members of any class. However in D8, they are now members of the User class.

That said, I'm finding in some code on the net that people are typehinting as Drupal\Core\Session\AccountInterface, and in other places as Drupal\user\UserInterface. How should we be determining which one to use for our typehints, and what is the difference between the two types of objects?

UserInterface extends ContentEntityInterface, EntityChangedInterface, and AccountInterface. This means there are methods an object implementing UserInterface needs to have but objects implementing AccountInterface don't need to have. For example, there is UserInterface::hasRole(), but AccountInterface::getRoles(); in the first case, there is a helper method allowing to check the object has a specific role, while in the second case you would need to write your code for that, getting the list of the roles with AccountInterface::getRoles().
Which hint should be used is given from the documentation. For example, hook_user_logout() gets an object implementing \Drupal\Core\Session\AccountProxyInterface, since it gets the object returned from Drupal::currentUser(). See user_logout(), the function invoking hook_user_logout().
  $user = \Drupal::currentUser();

  \Drupal::logger('user')->notice('Session closed for %name.', array('%name' => $user->getAccountName()));

  \Drupal::moduleHandler()->invokeAll('user_logout', array($user));

Sometime the documentation for a hook doesn't show a specific hint, such as in the case of hook_user_login(). In this case, it could help to see which hint is used from the implementations of that hook, for example system_user_login(), which uses UserInterface as hint for its argument.
When you aren't sure about the correct interface implemented by the object passed to a function (including a hook), use the most generic one as hint. In the case you describe, that would be AccountInterface.


i18n, path alias doesn't work I set path auto alias of content type page to:

  [language]/[title-raw]

I am using Content Translation module.

I created english version of selected page.
Alias was generated ok.

But even if I am admin, I have 404 when I want to view this page.

Could somebody give me any advice?

EDIT

I change pathauto alias setting to

  [title-raw]

still 404.

If I use raw address of page (node/232) it works.

EDIT 2

After recreate page, alias works ok (:

In the Workflow settings of the type page you should choose Multilingual support: enabled or eabled with translation if you want to have the page in 4 different versions on their own.

If you simply choose enabled you can e.g. make as many path aliases as languages are active for one and the same page. If you choose "with translation" you can make translation nodes after creating the page. There is also a rules integration, that makes you all translation nodes automatically.

If you enable Multilingual support you will see in pathauto autmoatic section, that you can choose a path for every enabled language. The prefix you shouldn't use, because itis handled by drupal and/or modules itself. You can change the behaviour in the languages menu under site configuration.


Use Views to delete a record from the database I have created a view that displays userpoints info. What I need is to create a link that will delete or reset individual records.

Userpoints can not be deleted, at least not through the UI.

Instead, you need to create a reverting transaction that removes the points that the other transaction added, or the other way round.

The only thing that you can currently do out of the box is building a link that points to the add points form with the username pre-filled, by using that as a token in views. Then you just need to add the points and save.

Everything else currently requires custom code, by e.g. writing a custom action.

Userpoints 7.x-2.x will allow this using bulk operations and better rules integration, but there is currently not much progress on that branch. As in, pretty much none.


How to disallow one domain path in robots.txt without any modules? How to disallow one domain path in robots.txt? (there is a module which allows to do that but it is better to avoid it because of performance issues)
For example, onedomain.com/path1/* must be disallowed. Is it right to type like this in robots.txt (there is another domain twodomain.com for the same website):

Disallow: onedomain.com/path1/*

Twodomain path must be allowed to be crawled and Onedomain path must be disallowed to be crawled (both of them are pointing to the same path).

I don't have enough reputation to comment, so I'll just throw this out:

You can test the user agent and the URL in settings.php. Then, if it matches the crawler bot and the /path1/* criteria, you  could do a 301 Permanent Redirect for that URL within your settings.php file. Here is how:

  header('HTTP/1.0 301 Moved Permanently');
  header('Location: ' . $base_url . $redirect_path );
  exit();

where $base_url is "Twodomain" and $redirect_path is "/path1/URLfromtest"


How to programmatically set Webform field value with custom submit? I try to update an hidden field value with my custom submit, but it doesn't work, my new value are not saved.

With :  $form_state->setValue('token_uid', $token_uid);

  function MODULE_form_alter(&$form, FormStateInterface $form_state, $form_id) {

    if ($form_id == 'webform_submission_creation_compte_add_form' || $form_id == 'webform_submission_creation_compte_test_form') {

      foreach (array_keys($form['actions']) as $action) {
        //attention en multi step : wizard_next
        if ($action != 'wizard_next' && $action != 'preview' && isset($form['actions'][$action]['#type']) && $form['actions'][$action]['#type'] === 'submit') {
          $form['actions'][$action]['#submit'][] = '_MODULE_creation_compte_submit';
        }
      }
      if (isset($form['#validate'])) {
        $form['#validate'][]  =  '_MODULE_creation_compte_validate';
      }
    }
  }

My custom submit function :

function _MODULE_creation_compte_submit(array &$form, FormStateInterface $form_state) {
    global $base_url;
    $data               = array();
    $user_id_created    = null;

    //Info account
    $account_name       = $form_state->getValue('nom');
    $account_username   = $form_state->getValue('username');
    $account_first_name = $form_state->getValue('prenom');
    $account_mail       = $form_state->getValue('email');
    $account_password   = $form_state->getValue('mot_de_passe');
    $account_phone      = $form_state->getValue('telephone');

    if (!empty($account_username) && !empty($account_password) && !empty($account_mail)) {

        $account_username   = strtolower(str_replace(' ', '', $account_username)).'_'.rand(0,1000);

        $user_created       = User::create([
          'name'                  => $account_username,
          'pass'                  => $account_password,
          'mail'                  => $account_mail,
          'field_user_nom'        => $account_name,
          'field_user_prenom'     => $account_first_name,
          'field_user_telephone'  => $account_phone['phone'],
          'status'                => 0,
          'init'                  => $account_mail,
          'created'               => time(),
          'changed'               => time(),
          'login'                 => 0,
          'access'                => 0,
        ]);
        $user_created->save();
        $user_id_created = $user_created->id();
        $token_uid       =  $base_url . '/user/' . $user_id_created;

       //==> Value is not saved after submit
        $form_state->setValue('token_uid', $token_uid);

    }
}

The solution with hook_ENTITY_TYPE_presave :

use Drupal\webform\WebformSubmissionInterface;

 function MODULE_webform_submission_presave(WebformSubmissionInterface $webform_submission){
    global $base_url;
    $user_id_created    = null;

    //Info account
    $account_name       = $webform_submission->getElementData('nom');
    $account_username   = $webform_submission->getElementData('username');
    $account_first_name = $webform_submission->getElementData('prenom');
    $account_mail       = $webform_submission->getElementData('email');
    $account_password   = $webform_submission->getElementData('mot_de_passe');
    $account_phone      = $webform_submission->getElementData('telephone');

    if (!empty($account_username) && !empty($account_password) && !empty($account_mail)) {

      $account_username   = strtolower(str_replace(' ', '', $account_username)).'_'.rand(0,1000);

      $user_created       = User::create([
        'name'                  => $account_username,
        'pass'                  => $account_password,
        'mail'                  => $account_mail,
        'field_user_nom'        => $account_name,
        'field_user_prenom'     => $account_first_name,
        'field_user_telephone'  => $account_phone['phone'],
        'status'                => 0,
        'init'                  => $account_mail,
        'created'               => time(),
        'changed'               => time(),
        'login'                 => 0,
        'access'                => 0,
      ]);
      $user_created->save();
      $user_id_created = $user_created->id();
      $token_uid       =  $base_url .'/user/' . $user_id_created;
      $webform_submission->setElementData('token_uid', $token_uid);
    }
  }


How to add css immediately (display:none) to a block created through hook? I created a block through drupal hook_block_info (and hook_block_view, but this doesn't really matter)

function mymodule_block_info() {
  $blocks['menu_mobile'] = array(
    'info' => t('Mobile Menu'),
    );
  return $blocks;
}

I need it to be hidden initially and then to show on webpage resize/mobile.
I did this by applying a display:none to css and the media rule

@media screen and (max-width: 768px)

It works. Almost Perfectly. The problem is that, at the very beginning of webpage loading, the block is visible and, for maybe a second, it shows on its webpage, then the display:none does its work hiding it. It is annoying. I saw here some properties of the array to be returned by the hook, but none really fits my case. For example, enabling/disabling hides the block, but i don't really know how or when to show it again.

https://api.drupal.org/api/drupal/modules%21block%21block.api.php/function/hook_block_info/7

So, how i can have the block initially hidden, or fasten the display:none (that is contained in the style.css of my custom theme)?

A block can have a content element when created in code. This content element can be raw HTML or a drupal render array. If you use raw HTML for your block you can just put <style type="text/css">#your-block-id { display: none;}</style> directly into your block output.

Or if you use a render array you can do something similar with the #attached key on the render array. This is outlined in the API usage of drupal.org and a comment provides an example:

$block['content'] = array(
  '#markup' => mymodule_testblock_content(),
  '#attached' => array(
      'css' => array(
        drupal_get_path('module', 'mymodule') . '/css/mymodule.css',
      ),
      'js' => array(
        drupal_get_path('module', 'mymodule') . '/js/mymodule.js',
    ),
  ),
);

Obviously the render array approach is a cleaner, more elegant solution. You can even have the CSS inline when using #attached.


Is there a way to edit/write templates from the user interface? One of the UI/UX issues with Drupal is that theme templates are not editable from within the interface. Even for devs who know what they are doing this is awkward time consuming distraction needing FTP and other software outside of Drupal to create/remaster themes or put in a little logic . While knowing that the ability to edit tpl.php templates from the UI can potentially create security issues, still it seems to me that showing the template code and ability to re-write templates within the interface is lacking in Drupal 7.

Css can be writen to files (from themes and modules ie administratiom theme and css editor) so why not templates?

Can it be done?

As far as I know, the best you could do in Drupal from the admin side is alter the layout using Display Suite, Panels, and to some extent, Field Groups (Bootstrap Field Group can come in handy). Advanced functionality will still require code access (i.e. adding custom layouts and layout CSS). That's usually what you end up doing with templates most of the time, just moving things around.

It's rare that you edit the widgets and field outputs (you write formatters for those, which then can be changed via admin once installed). Also, editing widgets using templates instead of formatters is a maintenance nightmare and full of surprises.

  Even for devs who know what they are doing

Devs who know what they're doing store changes in version control, and therefore code. ;)


How to enable tokens for custom entity? I had the impression that in Drupal 8 all entity tokens are provided automatically since it uses the new field structure but I don't see anything available for my entity.

Do I need to enable something in the annotation or did I get it wrong and tokens have to be provided manually like in D7?

I had the impression that in Drupal 8 all entity tokens are provided
  automatically since it uses the new field structure but I don't see
  anything available for my entity.

That impression is wrong. Drupal (core) doesn't provide any generic tokens for entities, all that are in core are hardcoded.

Now, token.module, just like in D7, provides some tokens for configurable fields. Simply because the existing functionality was ported to D8. It is possible to extend that to all fields and it shouldn't even be that hard. In fact, there's an explicit check that ignores anythig that's not a configurable field, so we just have to remove that and see what happens.


File field breaks AJAX form in Drupal 7 form API This is a really strange one, I've created a custom form using the multi step form method. So there are various AJAX calls to handler functions that return certain sections of the form back to containers and replace the HTML.

My form works great has a lot of complexity to it and the speed is fantastic. A recent addition to said form is to be able to upload a PDF, simple I thought! Added my manged_file field and all looked great. However I'd missed that now my page was reloading, AJAX requests were no longer in the Firebug console and instead seemed to be in the POST somehow. I don't fully understand how the AJAX is still working but it is slower that's for sure!

This is a problem I think we could live with a bit of slowness but then I noticed on a full form submission it was breaking a second form outside of this form. Basically it's too big of an issue to live with now.

I've tried a few things, one a standard file field, two a markup field with a raw

<input type="file" />

just to see what happened and I experienced the exact same issue as using the form API. This confirms to me that this is not caused by some added javascript from Drupal but a problem with the input itself.

So my question is why does a file field break the AJAX in my form?

Rather awkwardly I can't just paste all my code here as the data is protected and technically not my property. I'm not sure it's needed but I've thrown together a quick bit of code that should demonstrate my issue.

function vv_test_menu(){
    $items = array();
    $items['vvtest'] = array(
        'page callback' => 'vv_test_page',
        'access arguments' => array('access content'),
        'page arguments' => array(false),
        'description' => t('Test page for code.'),
        'type' => MENU_CALLBACK,
    );
    return $items;
}

function vv_test_page(){
    $content = 'This demonstrates the file field breaking the AJAX.';
    $content .= render(drupal_get_form('vv_test_form'));
    return $content;
}

function vv_test_form($form, &$form_state){
    $form['#tree'] = TRUE;
    $form['#prefix'] = '
';
    $form['#suffix'] = '
';

    $form['job_number'] = array(
        '#type' => 'textfield',
        '#title' => t('Job number'),
        '#required' => TRUE
    );

    if($form_state['triggering_element']['#ajax']['callback'] == t('vv_test_call')){
        $form['result'] = array(
            '#markup' => '
You entered: '.print_r($form_state['values']['job_number'], true).'
'
        );
    }

    // - Comment this field in and out to see the problem
    $form['pdf'] = array(
        '#type' => 'file',
        '#title' => t('A file field')
    );

    $form['sync'] = array(
        '#type' => 'button',
        '#name' => 'sync',
        '#value' => t('Sync'),
        '#ajax' => array(
            'callback' => 'vv_test_call',
            'wrapper' => 'container'
        )
    );

    return $form;
}

function vv_test_call($form, &$form_state){
    $form_state['rebuild'] = FALSE;
    return $form;
}

I experienced the exact same: Drupal 7, custom AJAX form, multiple pages, all working fine. After adding a managed file field it broke the AJAX functionality. Or that was what it looked like...

The past couple of days I spent quite some time digging around misc/drupal.js, misc/ajax.js and modules/file/file.js to turn the managed file field into a single customizable "Select & upload file" button with client side file size validation and auto submit functionality.

After reading your question and remark about that the problem even occurred when manually inserting a plain non Form API file field it dawned to me that I read the following in misc/ajax.js > Drupal.ajax.prototype.beforeSend:

  For forms with file inputs, the jQuery Form plugin uses the browser's normal form submission mechanism, but captures the response in a hidden IFRAME.

I tested this on the dev site and it appeared that AJAX only "broke" after visiting a form page which contained a plain file field. Though the requests felt less snappy and in Chrome and Firefox loading throbbers appear in the browser tabs and the status bar showed a new page was being requested, it seemed to not harm my forms.

But the jQuery Form plugin for Drupal 7.28 has version number 2.52, see misc/jquery.form.js. The jQuery update module 7.x-2.4 ships with path/to/jquery_update/replace/misc/jquery.form.min.js with version number 2.69, though the latest version is 3.51, see http://malsup.com/jquery/form/#download. This latest version appears to use another technique for file uploads which feels like AJAX (or maybe ís using AJAX), see http://malsup.com/jquery/form/#file-upload. I tried this version on the dev site and so far with success!

Download the latest version to your module or theme and use ie. hook_js_alter() to replace the old script for the new one. I implemented this hook for the site's theme:

/**
 * Implements hook_js_alter().
 */
function YOURTHEME_js_alter(&$js) {
  // Define path to old jQuery Form plugin, alter to your needs.
  $old_path = drupal_get_path('module', 'jquery_update') . '/replace/misc/jquery.form.min.js';

  // The script does not get loaded on every page, so check the $js array.
  if (isset($js[$old_path])) {
    // Define path to newer jQuery Form plugin, alter to your needs.
    $new_path = drupal_get_path('theme', 'YOURTHEME') . '/js/jquery.form.min.js';

    // Copy data from old javascript to new and remove old javascript.
    $js[$new_path] = $js[$old_path];
    unset($js[$old_path]);

    // Set new path as data property and alter version number.
    $js[$new_path]['data'] = $new_path;
    $js[$new_path]['version'] = '3.51.0';
  }
}

Or see how jquery_update_library_alter() did it and apply this method to your module.


How to find which module is causing PHP warning In the Recent log messages I get this message repeated many times:

  Warning: array_flip(): Can only flip STRING and INTEGER values! i
  DrupalDefaultEntityController->cacheGet() (rad 388 av
  C:\wamp\www\includes\entity.inc).

I assume that the problem lies within one of the modules I have installed, but after spending the whole day trying to narrow down which module is causing the problem, without luck, I post this question. I have read other answers that relates to the same log message, but they did not help me.

Anyone that can explain how to get more info out of that warning?

Best way is probably to use a debugguer like xdebug and watch the callstack in your IDE before your warning.

If you cannot, use debug_print_backtrace() or debug_backtrace(), locate your warning and you will see all the calls before it happens.

Here is an exemple you have to adapt (or not) : set_error_handler()


How to tell Drupal to look for templates in module directory? I'd like to provide template implementation in my module and allow themes to override it. Basically, I add a suggestion by this simplified code:

function attach_preprocess_node(&$vars) {
  $vars['theme_hook_suggestions'][] = 'node__test';
}

(I don't want to use hook_theme to add a new theme because I want to reuse preprocess node functions. The theme name are awkward but I don't want to write node_attach_% to avoid confusion with node type.)

Then I use hook_theme_registry_alter() to add module path:

function attach_theme_registry_alter(&$theme_registry) {
  $path = drupal_get_path('module', 'attach') . '/themes';
  $theme_registry_copy = $theme_registry;
  _theme_process_registry($theme_registry_copy, 'phptemplate', 'theme_engine', 'node', drupal_get_path('module', 'node'));
  $theme_registry += array_diff_key($theme_registry_copy, $theme_registry);
  if (!isset($theme_registry['node']['theme paths'])) {
    $theme_registry['node']['theme paths'] = array();
  }
  if (!isset($theme_registry['node']['theme paths'])) {
    $first_element = array_shift($theme_registry['node']['theme paths']);
    if ($first_element) {
      array_unshift($theme_registry['node']['theme paths'], $first_element, $path);
    }
    else {
      array_unshift($theme_registry['node']['theme paths'], $path);
    }
  }
}

However it does not work. That means: the file themes/node--super.tpl.php is not used. It is used only if I copied it to the theme folder.

Maybe this one works:

/**
 * Implements hook_theme().
 */
function MODULE_theme($existing, $type, $theme, $path) {
  return array (
    'node__CONTENTTYPE' => array (
      'variables' => array( . . . ),
      'template' => 'node--CONTENTTYPE' ,
      'base hook' => 'node',
      'path' => drupal_get_path('module', 'MODULE'),
    ),
  );
}

Important here is the key 'base hook'.


Can't disable module when it defines an field type used by a custom entity I have created a module that creates a custom entity (using hook_entity_info etc.), defines a field type (using hook_field_schema and hook_field_info), and then creates an instance of the field type with my custom entity (using field_create_field and then field_create_instance).

This all works great until I try to uninstall the module and am told "Drupal (Field type(s) in use".

Whilst this is true they won't be in use once the module is uninstalled!

Short of going into the DB and starting to delete rows out of the field_config and field_config_instance table how do I get round this problem?

Here I am creating the field instance in hook_enable:

function emtr_enable() {

    field_cache_clear();
    field_associate_fields('emtr');

    if(field_info_field('emtr_denominations')) return;

    $field = array(
        'field_name' => 'emtr_denominations',
        'type' => 'field_emtr_denominations',
        'cardinality' => FIELD_CARDINALITY_UNLIMITED,
        'translatable' => FALSE,
    );
    field_create_field($field);

    $instance = array(
        'field_name' => 'emtr_denominations',
        'entity_type' => 'emtr_safe_check',
        'bundle' => 'emtr_safe_check',
        'label' => 'Denominations',
        'required' => false,
        'widget' => array(
            'type' => 'number'
        ),
        'settings' => array(
            'target_type' => 'emtr_safe_check',
            'handler_settings' => array('target_bundles' => NULL),
        ),
        'display' => array(
            'default' => array('label' => 'inline', 'type' => 'number_integer'),
        ),
    );
    field_create_instance($instance);
}

And here is my uninstall hook:

function emtr_uninstall() {
    if ($instance = field_info_instance('emtr_safe_check', 'emtr_denominations', 'emtr_safe_check')) {
        field_delete_instance($instance);
    }
    if (field_info_field('emtr_denominations')) {
        field_delete_field('emtr_denominations');
    }
    field_purge_batch(100);
}

And hook_field_schema:

/**
 * Implements hook_field_schema
 */
function emtr_field_schema($field) {

    $columns = array(
        'denomination_value' => array(
            'type' => 'int',
            'not null' => FALSE,
        ),
        'denomination_tid' => array(
            'type' => 'int',
            'not null' => TRUE,
            'default' => 0,
        ),
    );
    $indexes = array(
        'denomination_tid' => array('denomination_tid'),
    );
    return array(
        'columns' => $columns,
        'indexes' => $indexes,
    );
}

Just in case my hook_field_info and hook_entity_info are in a pastebin here.

So as Clive suggested I solved this by creating a helper module called emtr_fields.

The emtr_fields module creates the entity and has the field schema.

Then the main emtr module creates the field and it's instance.

To remove all of this again first the emtr module has to be disable AND uninstalled (it has to be uninstalled as the field and it's instance is deleted in hook_uninstall), and then the emtr_field module can be disabled and uninstalled.

I also found some documentation on this on drupal.org here:

Module cannot be disabled because Drupal claim "Field type(s) in use"

Moving field(s) definitions into a separate module of a installed module.

Field types should be defined by one module and implemented by a separate module.


How to boost relevance of Search API solr with the value of a certain field? I am using Search API solr on my site. To get better search results I would like to boost the relevance by the value of a certain numeric field.
Say, all items have a field A, which is numeric. Now I want to boost the relevance of those itemes by the value of field a, so that, if As value is higher the relevance of the item becomes higher too.
I have absolutely no idea how to do this. Maybe with

hook_search_api_solr_query_alter()

But I did not find documentation how to use it. Please hint me in the right direction.

hook_apachesolr_query_alter($query) alter the query after it's prepared and cached.

As per example given in documentation which I found, you can use this hook in similar way to other query_alter hook. E.g -

function hook_apachesolr_query_alter($query) {
  //Adding one more filter.
  $query->addFilter("is_uid", 1);

  // Only search titles.
  $query->replaceParam('qf', 'label');
}

Find the documentation by clicking on the mentioned hook name by me.

EDITED--

Sorry for giving example of other hook of apache solr module. You can find documentation of your hook here hook_search_api_solr_query_alter().

You can find a small snippet for example of this hook like --

function hook_search_api_solr_query_alter(array &$call_args, SearchApiQueryInterface $query) {
  if ($query->getOption('foobar')) {
    $call_args['params']['foo'] = 'bar';
  }
}

Eric has wrote a nice article with example of this hook.


Display thumbnailPhoto from Active Directory - Open atrium and LDAP modelude I am using Open Atrium for my intranet. I got LDAP module installed, the server is configured, same as User, Authentication, and Authorization.
The communication with my Active Directory is successful, I have all my fields and properties populated correctly, but THUMBNAILPHOTO

Do I need to configure something else?? What I am missing? My active Directory uses CodeTwo.

Thanks,

Sofia

You need to configure your ldap server

  Go to admin/config/people/ldap/servers
  Click edit
  Go to "LDAP User to Drupal User Relationship" tab
  Under "Thumbnail attribute" add "thumbnailphoto" (without quotes)
  Save your settings

Now your ldap server is configured to automatically copy user thumbnail from ldap (Active Directory) to Drupal.


How can I upload files with the form element type file? I want to upload a file and I have to use form element type as 'file'. In submit function I am not able to get any proper data related to the file which I am uploading. SO Can anyone please help me to resolve this. Please find the below code:
public function buildForm(array $form, FormStateInterface $form_state) {
  $form['test_CERTIFICATE'] = [
    '#type' => 'file',
    '#title' => $this->t('Certificate'),
    '#description' => $this->t('Your Certificate (.pem file)').': '.\Drupal::state()->get('test_CERTIFICATE_NAME'),
  ];

  return parent::buildForm($form, $form_state);
}

Submit function:
public function submitForm(array &$form, FormStateInterface $form_state) {
  parent::submitForm($form, $form_state);

  $validators = array('file_validate_extensions' => array('pem'));
  $files = file_save_upload('test_CERTIFICATE', $validators, 'public://certfiles', FILE_EXISTS_REPLACE);
  $file = File::load($files[0]);
  if ($file) {
    kint($files); exit;
    // here control is not coming
    $file->setPermanent();
    $file->save();
  }
}

I had the same problem with the file form element. Solved this by using managed_file and providing the upload location and validators in the form element:

$form['test_CERTIFICATE'] = [
  '#type' => 'managed_file',
  '#title' => $this->t('Certificate'),
  '#upload_location' => 'private://certfiles',
  '#upload_validators' => [
    'file_validate_extensions' => ['pem'],
  ],
];

Then in submit:

use Drupal\file\Entity\File;

$form_file = $form_state->getValue('test_CERTIFICATE', 0);
if (isset($form_file[0]) && !empty($form_file[0])) {
  $file = File::load($form_file[0]);
  $file->setPermanent();
  $file->save();
}


Edit meta tags per entity via field or entity property? Is there a way in Drupal 8 to override the global meta tags at the entity (node) level when adding or editing content? I thought the option previously existed in 7.x, but I am not seeing it in 8.x.

If not, is there a way to alter the meta tags when preprocessing a node to inject them based on node fields in code?

Yes, there is.

All you need to do is add the Meta tags field to the node types where you want to have this.


How to migrate users and keep their IDs unchanged? I'm trying to use migrate_d2d, via the UI, to migrate a site from D6 to D7.  I need to preserve user UID's in the migration.  I'm finding the documentation confusing..

Given this in the UI...

What do I need to do to import the users?

Here is the solution (see image)

Uncheck DNM in 'Option:...' row
Enter 1 as default value
Save
Edit again
A new row will appear for 'Existing user ID'
Select Source field, i.e uid.
Save

This works...


Show a menu item as expanded if on a certain node type I have a News menu item, which then has children. I need it to be expanded if it is on a news article page, but not expanded on other certain pages.

I'm not sure which hook to use. i've played around with menu_link_alter but i can't figure out how to choose the item i'm on in order to process it. Maybe this isn't the correct way.

Any ideas please?

I would go with the context module.

You can set a context to be active whenever a certain content type is shown, in this case, an 'Article'.

You can then set the reaction to 'menu' and choose an item which will get an active trail. You can then target using CSS or more likely, it's probably already expanded.

https://drupal.org/project/context


Bootstrap.inc error appearing on website When I go to my database website at kctd.org/community, I get this error:

  Fatal error: require_once() [function.require]: Failed opening required '/home/kctd/public_html/community/sites/all/modules/views/modules/translation/views_handler_filter_node_language.inc' (include_path='.:/usr/lib/php:/usr/local/lib/php') in /home/kctd/public_html/community/includes/bootstrap.inc on line 3069

I have no idea what that means. The last action I did was extending the result of my view filter to include user's email. When I clicked save, this popped up. I cannot log in to even switch to maintenance mode.

What can I do?

The problem seems to be that views_handler_filter_node_language.inc was moved from views/modules/translation to views/modules/locale. I guess you have updated the views module but not rebuilt you registry.
You should be able to solve this by flushing the cache. Here's a issue, addressing the same problem.

Notice that whenever you update a module you should also call the update script located at example.com/update.php.

To flush the cache using drush use the following syntax: drush cc all.

You could also try to clear the cache_bootstrap table using:

mysql -uusername -ppassword -hhostname database -e"DELETE FROM cache_bootstrap WHERE cid='system_list';"`

or

drush sql-query "DELETE FROM cache_bootstrap WHERE cid='system_list';"

Backup your database before trying the above

If you still have trouble, you could also try to disable the views module using something like this:

mysql -uusername -ppassword -hhostname database -e"UPDATE system SET status='0' WHERE name='views';"

or

drush dis views

You might need to clear the cache as in the previous step for this to take effect.

Here you can find more information about disabling a module manually: Disabling modules manually in the database


Referencing logged user and node relations. I am trying to solve a problem with no luck:

I have 4 objects in Drupal:

-Company user (role company)
-Mod user (role moderator)
-Node Project
-Node Person (not a user entity)

Company user can add/edit/delete own Project nodes.
Mod user can a/e/d  own Person nodes.

I would love to accomplish next:

Mod can reference (add) Persons to Projects.
Example : Person A, Person B,... (both owned by Mod1 user) can be referenced (added) to Project 1, Project 2, etc. (or unreferenced/removed).

I imagine this as M:N relation, with two extra attributes - status (value 0-5) and author/createdBy (logged Mod1 user) to prevent mod users from editing/viewing others relation entities.

Next level is creating this by Rules module and Rules link module.

Lets have a View with Projects

clicking on a project should display a project page with list of
referenced and unreferenced Persons owned by logged-in Mod user.
Persons list should be clickable (rules link) for adding/removing reference
from actualy displayed project.

I had some progress with field collection module - was able to create relation entities with status, but cannot made it with Rules - dont know how to send two parameters in rule link (project id, person id) and create project page with persons lists (maybe as view blocks with contextual filters?)

Thank for any help, or idea.

I dont use Rules Link alot, I have used Rules Link Event and Rules. Anyways this issue queue item for Rules Link describes how to setup Parameters for a Rules Link:

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

From the issue:

  For your example, add the product sku field to your view and pass the
  token for that in the views rules link field settings under:
  Additional parameters for the rules link

  Edit the rules link component, click the configure rules tab, under
  settings, add the additional parameter. I assume it could be string,
  integer or whatever that matches your sku. The view is going to pass
  that parameter as a variable to use in the rules link component rules
  so you can do whatever you want with it from there.

The issue queue explains adding 1 parameter. but it does sound like it supports additional parameters to send to Rules, so just assure your View is passing 2 parameters instead of just the 1 in the Additional Parameters.


In a drupal commerce, how to use the same picture for every size attribute I have a dresses drupal commerce. I have 45 dresses in différents colors and size.

My problem is that I have the same picture for every size.

My product variation is composed of a sku,price,color,size,image.

As You can see , I have the image in the product variation. Mean that I need to reselect the image for every color,size variations.

Any Idea on how could I do this?

Thanks

If you're using commerce feeds, just use the same url to the same image on your server; or manually upload the same image for each!


How to override code of module in custom module? I am using Content Taxonomy module and trying to override some code, when I tried to modify in my custom module then the module functions also keeps running. And by modifying module file my purpose get solved but is there any way to do it in my custom module, please suggest:

CODE NEED TO MODIFIED:

/**
 * Form element validate handler for taxonomy term autocomplete element, which denies any new terms.
 */
function content_taxonomy_autocomplete_validate_deny_new_terms($element, &$form_state, $form) {
  $values = $form_state['values'];
  foreach ($element['#array_parents'] as $parent) {
    $values = $values[$parent];
  }
  foreach ($values as $delta => $value) {
    if ($value['tid'] == 'autocreate') {
      form_error($element, t('%name: new terms are not allowed. Please choose from the given list.', array('%name' => $element['#title'])));
    }
  }
}

DOING LIKE BELOW:

function custom_overrides_field_attach_form($entity_type, $entity, &$form, &$form_state, $langcode) {
  // Add validation function to taxonomy_autocompletes, if necessary.
  $instances = field_info_instances($form['#entity_type'], $form['#bundle']);
  foreach ($instances as $instance) {
    if (($instance['widget']['type'] == 'taxonomy_autocomplete' || $instance['widget']['type'] == 'autocomplete_deluxe_taxonomy')
      && isset($form[$instance['field_name']])
      && isset($instance['widget']['settings']['content_taxonomy_autocomplete_new_terms'])) {

      // Use the language that is used in this form (which doesn't necessarily
      // be the default language in $langcode).
      $lang_key = $form[$instance['field_name']]['#language'];
      if ($instance['widget']['settings']['content_taxonomy_autocomplete_new_terms'] == 'moderate') {
        $form[$instance['field_name']][$lang_key]['#element_validate'][] = 'content_taxonomy_autocomplete_validate_moderate_new_terms';
      }
      else if ($instance['widget']['settings']['content_taxonomy_autocomplete_new_terms'] == 'deny') {
        $form[$instance['field_name']][$lang_key]['#element_validate'][] = 'custom_content_taxonomy_autocomplete_validate_deny_new_terms';
        var_dump($form[$instance['field_name']]);
      }
    }
  }
}

/**
 * Form element validate handler for taxonomy term autocomplete element, which denies any new terms.
 */
function custom_content_taxonomy_autocomplete_validate_deny_new_terms($element, &$form_state, $form) {
  global $user;
       if($element['#title'] == "Topic"){
          if (!$user->uid) {
                $values = $form_state['values'];
                foreach ($element['#array_parents'] as $parent) {
                  $values = $values[$parent];
                }
                foreach ($values as $delta => $value) {
                  if ($value['tid'] == 'autocreate') {
                     form_error($element, t('%name: new terms are not allowed. Please choose from the given list.', array('%name' => $element['#title'])));
                  }
                }
            }
      }else{
            $values = $form_state['values'];
            foreach ($element['#array_parents'] as $parent) {
              $values = $values[$parent];
            }
            foreach ($values as $delta => $value) {
              if ($value['tid'] == 'autocreate') {
                form_error($element, t('%name: new terms are not allowed. Please choose from the given list.', array('%name' => $element['#title'])));
              }
            }
      }
 }

By Doing this now I have my custom validator running and my custom module weight is 1000 and contrib module weight is 0 but still its not working because I think second validator function as shown below in output of var_dump need to be unset by some way:

'#element_validate' =>
        array (size=3)
          0 => string 'taxonomy_autocomplete_validate' (length=30)
          1 => string 'content_taxonomy_autocomplete_validate_deny_new_terms' (length=53)
          2 => string 'custom_content_taxonomy_autocomplete_validate_deny_new_terms' (length=60)

You can use  hook_field_attach_form(). function much like it has been done in content_taxonomy_autocomplete module and replace the validate function to the one you want.

function MODULENAME_field_attach_form($entity_type, $entity, &$form, &$form_state, $langcode) {
 // Add validation function to taxonomy_autocompletes, if necessary.
  $instances = field_info_instances($form['#entity_type'], $form['#bundle']);
  foreach ($instances as $instance) {
    if (($instance['widget']['type'] == 'taxonomy_autocomplete' || $instance['widget']['type'] == 'autocomplete_deluxe_taxonomy')
      && isset($form[$instance['field_name']])
      && isset($instance['widget']['settings']['content_taxonomy_autocomplete_new_terms'])) {

      // Use the language that is used in this form (which doesn't necessarily
      // be the default language in $langcode).
      $lang_key = $form[$instance['field_name']]['#language'];
      if ($instance['widget']['settings']['content_taxonomy_autocomplete_new_terms'] == 'moderate') {
        $form[$instance['field_name']][$lang_key]['#element_validate'][] = 'content_taxonomy_autocomplete_validate_moderate_new_terms';
      }
      else if ($instance['widget']['settings']['content_taxonomy_autocomplete_new_terms'] == 'deny') {
        $form[$instance['field_name']][$lang_key]['#element_validate'][] = 'YOUR_NEW_VALIDATOR_NAME';
      }
    }
  }

}

// add your validater function here


Behat test fails, unable to find Username field using @javascript My Behat test fails as soon as I add @javascript

Error:

Form field with id|name|label|value|placeholder "Username" not found.

When I remove @javascript, test is passed without any error.

Given I am logged in as a user with the Administrator role

To test the Drupal 8 image_field I need @javascript

Behat.yml:

default:
  autoload:
    '': '%paths.base%/tests/behat/bootstrap'
  suites:
    default:
      paths:
        - '%paths.base%/tests/behat/default'
      contexts:
        - Drupal\DrupalExtension\Context\DrupalContext
        - Drupal\DrupalExtension\Context\DrushContext
        - Drupal\DrupalExtension\Context\MessageContext
        - Drupal\DrupalExtension\Context\MinkContext
        - MyServices\EntityContext
        - FailureContext
        - MyServices\LinkContext
        - My\MenuContext
  extensions:
    Bex\Behat\ScreenshotExtension:
      image_drivers:
        local:
          screenshot_directory: /[SHARED_FOLDER]/screenshots
    Behat\MinkExtension:
      goutte: ~
      base_url: "http://dev.mysite.com"
      files_path: '%paths.base%/tests/behat/files/'
      javascript_session: selenium2
      browser_name: chrome
      selenium2:
        wd_host: "http://localhost:4444/wd/hub"
        capabilities:
          # required by mink-extension 2.3
          marionette: null
          browserName: chrome
          browser: chrome
          version: 63
    Drupal\DrupalExtension:
      blackbox: ~
      api_driver: 'drupal'
      drupal:
        drupal_root: '%paths.base%/public'
      text:
        username_field: "Username"
        password_field: "Password"
        log_in: "Log in"
        log_out: "Log out"
      selectors:
        message_selector: '.messages'
        error_message_selector: '.messages--error'
        success_message_selector: '.messages--status'
        warning_message_selector: '.messages--warning'
        logged_in_selector: '.user-logged-in'
        login_form_selector: '#user-login-form'
      region_map:
        comments: '.comments'
        "main navigation": '#block-my-theme-main-navigation'
        "local tasks": '.block--local-tasks-block'
        "main content": '.block--system-main-block'
        "highlights": '.c-highlights__list'

ci:
  extensions:
    Bex\Behat\ScreenshotExtension:
      image_drivers:
        local:
          screenshot_directory: /tmp/artifacts/screenshots
    Behat\MinkExtension:
      base_url: http://localhost

I bet you are either one:

Testing against a non-English site.
Having BigPipe enabled.
Missed to tag that scenario with @api.
Misconfigured Selenium.

To solve 1. you need to put the non-English strings into your behat.yml like so:
Drupal\DrupalExtension:
  text:
    log_out: "Sign out"
    log_in: "Sign in"
    password_field: "Enter your password"
    username_field: "Username"

@see docs Override text strings.

To solve 2. which can occur when BigPipe somehow changes the markup in an undesired way, you can try out the patch at https://github.com/jhedstrom/drupalextension/pull/325.patch.
@see pull request Big pipe compatibility follow-up

To solve 3. simply add an @api tag to your scenario.

To solve 4. you must point wd_host to http://dev.mysite.com:4444/wd/hub, since your base_url is http://dev.mysite.com.
wd_host: "http://dev.mysite.com:4444/wd/hub"


Enable a button block programmatically? How do I enable a button block programmatically?

I've tried:

function openid_connect_block_info() {
  $blocks['openid_connect_login'] = array(
      'info' => t('Login Using PixelPin'),
      'cache' => DRUPAL_CACHE_PER_ROLE | DRUPAL_CACHE_PER_PAGE,
      'visibility' => 1,
      'region' => 'content',
      'pages' => 'user',
  );
  return $blocks;
}

Setting a block region doesn't work unless you set status to 1, and clearing your cache of course.


How do I override the HTML output of a theme function? Let say we have theme function in module A theme_super_a(), this function returning some HTML. I want to write function in my own module (let's call it B) where I can get output of theme_super_a() manipulate it and return back to Drupal theme system. How can I do it?

Notice that I'm not interested in overriding whole theme with hook_theme_registry_alter(&$theme_registry).

You will need to override the whole theme function in your own module.
Because the override is done from a module level, not the theme, you will probably need hook_theme_registry_alter to change the theme function settings for that specific hook_theme component.


During which bootstrap phase hook_exit & hook_boot will be invoked? Project Documentation says.. Both are invoked even for cached page views. hook_boot says

  This hook is run at the beginning of the page request. It is typically
  used to set up global parameters that are needed later in the request.

  Only use this hook if your code must run even for cached page views.
  This hook is called before the theme, modules, or most include files
  are loaded into memory. It happens while Drupal is still in bootstrap
  mode.

hook_exit says...

  Perform cleanup tasks.

  This hook is run at the end of most regular page requests. It is often
  used for page logging and specialized cleanup. This hook MUST NOT
  print anything because by the time it runs the response is already
  sent to the browser.

  Only use this hook if your code must run even for cached page views.
  If you have code which must run once on all non-cached pages, use
  hook_init() instead. That is the usual case. If you implement this
  hook and see an error like 'Call to undefined function', it is likely
  that you are depending on the presence of a module which has not been
  loaded yet. It is not loaded because Drupal is still in bootstrap
  mode.

Interested to know during which bootstrap phases hook_boot & hook_exit getting invoked so that it will be helpful in cases where above hooks can be used....

hook_boot is getting invoked during fifth phase which is DRUPAL_BOOTSTRAP_PAGE_HEADER which set up the page header... This is for non cached pages..

/**
 * Invokes hook_boot(), initializes locking system, and sends HTTP headers.
 */
function _drupal_bootstrap_page_header() {
  bootstrap_invoke_all('boot');

  if (!drupal_is_cli()) {
    ob_start();
    drupal_page_header();
  }
}

For Cached pages both gets executed at Second Phase of Bootstrap which is DRUPAL_BOOTSTRAP_PAGE_CACHE with little difference...

  // If the skipping of the bootstrap hooks is not enforced, call
  // hook_boot.
  if (variable_get('page_cache_invoke_hooks', TRUE)) {
    bootstrap_invoke_all('boot');
  }
  drupal_serve_page_from_cache($cache);
  // If the skipping of the bootstrap hooks is not enforced, call
  // hook_exit.
  if (variable_get('page_cache_invoke_hooks', TRUE)) {
    bootstrap_invoke_all('exit');
  }

what make difference between these hooks is

  drupal_serve_page_from_cache($cache);

Which tells hook_boot and hook_exit is used before and after page requests for tasks like setup and cleanup respectively..

hook_exit also called in common.inc what makes difference is,  Invoke during DRUPAL_BOOTSTRAP_PAGE_CACHE phase applies where cached page requests are served..  In common.inc hook_exit is called for non cached pages..

function drupal_page_footer() {
  global $user;

  module_invoke_all('exit');

  // Commit the user session, if needed.
  drupal_session_commit();

  if (variable_get('cache', 0) && ($cache = drupal_page_set_cache())) {
    drupal_serve_page_from_cache($cache);
  }
  else {
    ob_flush();
  }

  _registry_check_code(REGISTRY_WRITE_LOOKUP_CACHE);
  drupal_cache_system_paths();
  module_implements_write_cache();
  system_run_automated_cron();
}

Above confirms even for non cached requests hook_exit is invoked..


How to update the blocks db-table correctly I wrote a module that comes with a default_view (a block view). The corresponding block is not automatically listed inside the blocks db-table, even after a cache clearing, but it is shown after I visit admin/build/block. My problem is that I have a hook_update_N(), which is going to update the blocks table (the configuration of this specific block); if it's not there, it can't be updated.

When I use _block_rehash('MYTHEME') the table is updated, not only for MYTHEME (ZEN-subtheme) but also for the Minelli theme. Is there another way of "updating" the blocks-table? What exactly is going on, when admin/build/block is visited?

Edit: I just noticed that Pro Drupal Devel (2. Ed.) states, at page 218, to use a Insert INTO query and do it "by hand." I think thats what I'm going to do now.

Use INSERT INTO. I've spent hours and hours using block_rehash and variants to no effect.


Displaying parent nodes with child nodes - nested views, hard coding, or other approach? I have a parent content type which is categorized with a taxonomy term. Then there are child nodes to the parent. When someone clicks on a category, I want them to see a table basically. It would be of the form:

  Parent1
  Description

    Child1
      Description

    Child2
      Description

  Parent2
  etc

Seems out of the box I can't get Views to behave that way, so I was thinking I would have one view that is for the Parents, and another for children of a parent, and then somehow (via Display Suite for instance) have the page display the views one after another. Though I suspect that way of thinking is counter to what drupal is all about, so I am really trying to harnass the power of drupal to make that happen, as opposed to writing a custom module (though in the end I think such a custom module would be easier than Views, but I want to max out my understanding of Views before I go that route).

That said, how would you go about creating the Views and then controlling the display in Display Suite?

EDIT: So I figured out the SQL query that would return the results how I want them. Basically something like this

SELECT n.title, d.field_description_value, n.nid, l.field_lesson_target_id from drupal_node n

JOIN drupal_field_data_field_description AS d ON d.entity_id = n.nid

JOIN drupal_taxonomy_index AS t ON t.nid = n.nid

LEFT JOIN drupal_field_data_field_lesson AS l ON l.entity_id = n.nid

ORDER BY COALESCE(l.field_lesson_target_id, n.nid), l.field_lesson_target_id, n.nid

I made sqlfiddle

So I guess it comes down to whether Views is able to produce such queries.

Per the creator, the answer is in the comments with some additional documentation here: http://drupaleasy.com/blogs/ultimike/2009/02/displaying-hierarchical-content


Convert tpl template to twig template I have file tpl in drupal 7 like this:

<div class="<?php print $classes; ?>" <?php { print $attributes; } ?>>
    <?php
    $content_section = '
';
    foreach($columns as $key => $column) {
      $content_section .= render($column);
    }
    $content_section .='
';
    if(isset($customHTML)){
      $customHTML = str_replace('[content]', $content_section, $customHTML);
      print $customHTML;
    }
    else {
      print $content_section;
    }?>

I want convert two twig template. But i have problem with function render() and str_replace(). I know in twig have function replace. But don't know how to convert to twig.

In Drupal 8 you can use the drupal |render twig filter:

{{ myvar|render }}

Replace might be used as:

{% set customHTML = customHTML|replace({'[content]': content_section}) %}

having the variables all ready.

To convert your whole template to twig have a look at loops, also.