Disable pathauto for nodes created with migrate module I'm using migrate to import a bunch of nodes and I want to set the path alias during the migration. I am able to import the path alias just fine like so:

$this->addFieldMapping('path', 'url_alias');

When I look at the imported nodes I see the correct path in the path field, but the Generate automatic URL alias checkbox is still checked which means the setting is getting ignored.

How do I disable that setting on the node during migration?

You basically need to make sure the $node object is passed in with pathauto set to false when it is saved.

In your migration class:

function prepare(&$row) {
  $row->path['pathauto'] = 0;
}


How to create a query about users in a Drupal Commons group including their location (State)? I need to create a MySQL query that will allow me to view the users in a specific Drupal Commons group and include their USA State location. I would like to be able to export this to a CSV file.

Any help with this would be appreciated.

To create such query (and report) you may want to look at the Forena module. You would use its report writing features (such as its WYSIWYG report writer and/or it's query builder) to first create a report that fits your needs. The result of it could be a tabular output and/or graph. After the report content matches the specifications, you could save it as (e.g.) a CSV file.

Here is a quote from one of the Forena community docu pages, i.e. Reasons for considering Forena:

  Reports created by Forena (combined with SVGGraph and mPDF) can be
  saved (exported) as PDF documents with embedded graphs. Other
  supported formats for saving a report are CSV, XLS, DOC, HTML, etc.

Similar samples

Refer to this online example in the Forena demo site for a report that is fairly similar to the kind of (tabular) report you could (easily) create:

Using Forena's Query builder you would create the required SQL statement (if you'd rather want to write the SQL with your favorite SQL editor that's another option).
Using forena's WYSIWYG report writer you would develop your custom report (if you'd rather want to write that report with your favorite XHTML editor that's another option).

Some more details about the sample report mentioned above:

Use the "Parameters" pulldown option, to select any other state.
Note the PDF hyperlink: using that link, you'll get a PDF version of that report. When creating such report, you could as well ask for other (or additional) report export formats, one of them is CSV (or XLS, DOC, HTML, ...). This is how the CSV equivalent version of that sample report looks like.

The Master Summary with drill down sample report demonstrates how you can also "link" various reports together (while it also shows some of the charting features of Forena). Click on either any of those bars in the chart, or on the total-hyperlink in tabular report below the chart. Doing so will bring you to the report "for the selected state" (= the first sample report mentioned above).

Direct access to data blocks

All data blocks are accessible directly via their url also, provided you have permission to access that block. Here are a few samples of that, for the sample report located at /reports/sample.states:

in XML format (= demo with anonymous access).
in JSON format (= demo with anonymous access).
in XML format (= demo without anonymous access).
in JSON format (= demo without anonymous access).

More info about supported export formats

Refer to my answer to "How to add a link to the CSV download to my module page, for a report created with Forena?" for more details about supported export formats.

Video tutorials

The Forena Video demos and tutorials contain quite some links to live demos. They should help a lot to get you started.

Disclosure: I'm a co-maintainer of Forena.


How to create a form on settings o settings page In template.php file I am using the following code.
function MYTHEME_preprocess(&$variables, $hook) {
  $variables['socialmaintenaceurl'] = "https://twitter.com/test";
  $variables['maintenaceurltext'] = "Get the latest news on Twitter";
}

This is just for the maintenance page. I like to have two form elements on my settings page to manipulate these two values from the administrative area.
Could anyone show me what I can put in theme-settings.php?

My solution is for Drupal 7.

To add two textfields to the settings you have to implement the following hook:

function themename_form_system_theme_settings_alter(&$form, &$form_state) {

  $form['theme_settings']['socialmaintenaceurl'] = array(
    '#type' => 'textfield',
    '#title' => t('Social maintenance URL'),
    '#default_value' => theme_get_setting('socialmaintenaceurl'),
  );
  $form['theme_settings']['maintenaceurltext'] = array(
    '#type' => 'textfield',
    '#title' => t('Maintenance URL text'),
    '#default_value' => theme_get_setting('maintenaceurltext'),
  );
}

You have to replace themename in the function name with the name of the theme.
The declaration of the input elements is based on the Drupal 7 Form API (https://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7).

It is an array, which will be rendered according to the information you provide. Normally, keys starting with # are information to control the render process. For example: If you choose a different #type it gets a different widget/appearance in the form.

The $form['theme_settings'] should place the two new fields into the existing theme settings group.

If you want, you could ship default values for your two fields. You only need to add a few lines in you themes .info file:

settings[socialmaintenaceurl] = https://twitter.com/test
settings[maintenaceurltext] = Get the latest news on Twitter

I am not sure, if you need quotation marks around them, but I think in the .info file you dont need them.

To get these values in another file, you would need to use

theme_get_setting('maintenaceurltext')
theme_get_setting('socialmaintenaceurl').


Custom content types and fields: how do I set it up properly? I'm looking for a check-list style explanation of how I create this custom content type if possible.

I'm scraping data from an external website (it works flawlessly), I store it in my own database table (hook_schema(), etc.), and I display it in my config page as a table. The data gets re-scraped on cron using the queue API built into Drupal.

All this works fine. Now, my next step is to have this data turned into nodes as a custom content type. I will never need to create nodes of this content type by hand through the 'Add Content' menu because all the nodes should be generated by my module's scraping/parsing function, but the content should be searchable with Drupal's built in search. This is a bit more of a challenge. I have multiple fields (10-ish) I want to sort my data into, all different sections of the pages I'm scraping and I want to keep them separated properly so I can theme the content with a tpl file. The fields are all text, mostly HTML, some are titles/subtitles with no HTML, and a few Unix timestamps.

This has to all be done programmatically because this module might be deployed to other websites in the future, and this should not require configuring to work.

The first step is to create the content type and fields with the built-in UI of Drupal core. There are then several ways to export the configurations into code, but the simplest is probably Features, which will export a fully-functional module for you including all fields and content types you select.

To get your content into nodes of your content type, I'd suggest you create one node with the UI, use devel to look at the structure, then create the same object structure in code, which would look something like this:

$node = new StdClass;
$node->type = 'content_type;
$node->field_something = array(
  'und' => array(
    array(
      'value' => 'some value',
    ),
  ),
);
node_save($node);

Drupal's search defaults to searching nodes of all types, so that part should just work. Same with theming. You can use permissions (also exportable via Features) to remove the content type from the "Add content" list.


Set custom header text size for teasers I've created a frontpage which uses a the 34/33/34 panel layout and linked different contents to it (another pages). By checking the code using Firebug i see that teasers on this front page inherited the H2 class settings for header text, so they appear with the same text size just as they appear in full content view.

I'd like to customize the size of the header texts of the teasers on the front page. Any suggestion welcomed!

Thanks!

Just use CSS to alter the size of your H2 elements on the home page.

Replace in this code XX by the desired font-size, and it will apply to all h2 elements but only on the home page (body.front)

body.front h2 {
  font-size:XXpx;
}

Otherwise, learn CSS to understand how to select your specific elements.


How to know if a specific role can access a page? I have Drupal set up and some module enabled.
Specifically I have the translation_overview module installed.

Now I want to give a specific role access to those pages so they can see what needs to be translated.
So I gave them access to 'View translation overview assignments' but when I ask a person with this role if she can see it, she tells me she cannot.

I am an administrator, so I can obviously see everything in there.
But how can I see what other roles see?

You can make use of Masquerade module to switch users who belongs to different roles. This will help you see what other role users see.


do predicates in Ubercart really work? I´m trying to update a shipment cost for different zones of a country
(using predicates, conditional actions)

Using the trigger Getting shipping quote via Flat Rate
class uc_flatrate, activated , I´m trying to modify the rate..

Still the trigger doesn´t get called,
I tried to modify the objects with php , didn´t work ,
then i tried a simple test to display a message to the user, didn´t work..

then I tried to write a simple text into a file to see if the event gets called... didn´t work

How can I run a php script when I press calculate shipment cost? (or whenever the shipment cost is calculated) ?

To directly answer your question, yes, Predicates work. I use them extensively at a D6 Ubercart site of mine. Aside from that, my store is all digital goods, so no shipping.


Disable theme css via module I'm using Drupal 7.

I want to disable css defined by theme because I want to use my custom css that is defined by my custom module. What I mean is, I want to disable sites/all/themes/custom_theme/css/custom.css and use sites/all/modules/custom_module/css/custom.css instead.

Is there any way to do that?

Thanks!

Yes.

What you want is to include call drupal_add_css() for example:

drupal_add_css(drupal_get_path('module', 'your_module') . '/css/custom.css', array('group' => CSS_DEFAULT, 'every_page' => TRUE));

What that does is that it adds the css file on every page load. You can read more about adding css files here: https://api.drupal.org/api/drupal/includes%21common.inc/function/drupal_add_css/7

In your theme's .info file you will find a section describing where to find the css file e.g:

stylesheets[all][] = css/style.css

simply switch it off by placing a ; at the start of that line. This works particularly well if your theme is a subtheme, that is based off some other theme that you don't want to change directly in case you may need to upgrade it later.

Lastly, should you decide to remove the css file from your template.php file or module, you can do that via hook_css_alter()

for example:

function hook_css_alter (&$css) {

    if (isset ($css[path_to_theme() . '/css/custom.css'])) {
        unset ($css[path_to_theme() . '/css/custom.css']);
    }

}

Hope it helps.


Time localisation - "@count hour" (ago) instead of "1 hour"? Short story:

When Drupal 6 display time in format "x ago" (for example "3 hours ago"), there are two strings - for singular and plural. Singular string for hours is "1 hour", plural string is "@count hours". My question is - is this a bug? Shouldn't be there "@count hour"?

Long story:

Today, something strange happened to me. I went back to my site where I posted a comment yesterday around this time. However, in recent comments block, there was my comment marked as "1 hour 15 minutes ago" (in my language, not English - that's important!).

After I checked that time zone, server time and comment time are correct, I started debugging the Drupal. Finally, I found the culprit; it's the method format_interval(). At start of the method, there are strings definitions. For hour it's '1 hour|@count hours' - 1 hour for singular, @count hours for plural.

I found out that my comment was posted 21 hours ago and that locale_get_plural() function returned 0 - which is interpreted as singular.

And that's the problem - in my language we read "21 hour", NOT "21 hourS"! However, the count variable is not used, so for each numeric value read as singular (1, 21, 31, 41, ..., 91, 101, 121, 131, ...) (note: yeah, 11 is not singular in my language), the displayed value will be always 1!

I'm writing about hours, but this is same for all other values - years, weeks, minutes and seconds. Experimentally, I changed translation of "1 hour" to "@count hour" (in my language, not English) and the displayed time become correct. However, this is not clean solution, so my question is: is this a bug? If not, how should I solve this correctly?

Notes

I use Drupal 6
Happening on my machine (Xubuntu 14.04) and server (some Gentoo)
My language is Czech

The change you have made should work until you download and install an update to the drupal core language file.

The Drupal Localize site would allow you to download an check the latest versions of the  core language files to see if the bug also exists latest versions of 6, 7 and 8.

https://localize.drupal.org/translate/languages/cs

Perhaps you could sign up and posting a message into the Czech language forum on the localize site.  You can also find out more about contributing on the localize website.

https://localize.drupal.org


How can I clear the Varnish cache? We have installed node queue module on Pressflow 6 + Varnish. For clearing the varnish cache for node queues, we developed rules using the Rules, and Cache action modules. Whenever we update the content, it is reflecting for logged in users, but it is not reflecting for anonymous users.

Could you please suggest us for how to clear varnish cache with rules or any custom code?

The Cache Expiration module is designed to clear items from caches, including Varnish.

  This module acts as a grid to detect and act upon events that will expire URLs from caches like reverse proxy caches. The Cache Expiration module is a spinoff of the expiration code of the Boost expiration code so other modules can use it. This module stands on its own and does not use Boost in any way.


Integrating FBA (or Amazon MWS) with Ubercart I am going to be rebuilding an ecommerce site in Drupal 8 using Ubercart.  The site was originally built with Drupal 6 and Ubercart and had Amazon FWS integrated into the store.  Is there anything similar I can use for Drupal 8?  Basically the client needs FBA (fulfillment by Amazon) integrated into the site.

There's Commerce Amazon fulfillment if you're not wedded to Ubercart, but it needs porting to D8.


Flag- is there a way to allow users to only flag themselves? I'm on Drupal 7 with Flag 2.0 (beta9).  The flag module provides a checkbox option for user flags, Users may flag themselves.  However, I would like to allow users to only flag themselves.  In other words, I want to give each user an on/off switch as a flag, but each user should only be able to toggle the switch for herself.

What I am trying to do: I have some options users select at registration (are you interested in A?  B?  C?  etc.)  These are checkboxes.  I want to give users an easy way to change these options after registering.  If I send them to the edit account screen, they get the option to change their password, e-mail address, etc., which is too much.  I was thinking of using flags to do this (with a rule that triggers to Set a data value when the user is flagged/unflagged), but it is crucial that users only be able to change their own values.

Is there a way to use a node flag instead? Out of the box, there you can restrict it to a node type and also to content only owned by the user (or not).

So if you have the equivalent of a content profile set up in d7, you would be able to set it up so a flag was restricted to that type of content and only to the node owner, which might accomplish what you are after.


Create New User Display I am looking for a way to create new user Display.

When I go to Admin > Configuration > People > Acount Setting > Manage Dispaly

there are only three display modes: Default / Compact / User Account

How do I create a custom display mode?

See attached picture.

In drupal 8 you can easily create a new view mode via backoffice : Administration > Structure > Display modes > View > User
and click Add new User view mode.
To go further see documentation : https://www.drupal.org/docs/8/api/entity-api/display-modes-view-modes-and-form-modes


When altering the submit button, the form does not work We need a <button> instead of an input in our search-form. So I changed the markup accordingly using theme_form_alter:

function giga_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'search_block_form') {
    $form['search_block_form']['#title'] = t('Search'); // Change the text on the label element
    $form['search_block_form']['#title_display'] = 'invisible'; // Toggle label visibilty
    $form['search_block_form']['#size'] = 40;  // define size of the textfield
    $form['search_block_form']['#default_value'] = t('Search'); // Set a default value for the textfield
    $form['actions']['submit'] = array(
      '#type'   => 'markup',
      '#prefix' => '<button type="submit" class="btn btn-primary">',
      '#suffix' => '</button>',
      '#markup' => '<i class="icon-search icon-white"></i>'
    );
    $form['actions']['submit']['#executes_submit_callback'] = true;
    $form['actions']['#type'] = 'none';
    $form['#attributes']['class'][] = 'search-quick';

    // Alternative (HTML5) placeholder attribute instead of using the javascript
    $form['search_block_form']['#attributes']['placeholder'] = t('Search');
  }
}

However, I can submit the form, but the search won't be processed. The page reloads and I'm not redirect to the search results. However when I remove $form['actions']['submit'] = array([…]); it all works fine.

I'm not quite sure what's going on here.

I just had the same problem. All the needed was adding this.

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


How to achieve a particular layout (view within a view, custom template, or ____)? Say I had a site with travel destinations and I wanted to display a series of videos associated with each destination on a page below a description of the destination. The destinations and the videos each have their own node type.

Currently, the list of destinations is a view. Each video has a taxonomy term associated with it, that ties it to a particular destination. We use views arguments to pick up the taxonomy term from the URL and have the videos displayed in the side bar. However, we'd like to make it more clear that the videos are associated with a particular destination.

How can we best achieve the following layout?

+-----------------------------------------+
| +-------------------------------------+ |
| |                                     | |
| |               node 1                | |
| |                                     | |
| +-------------------------------------+ |
| +----------+ +----------+ +-----------+ |
| | video 1a | | video 1b | | video 1c  | |
| +----------+ +----------+ +-----------+ |
|                                         |
| +-------------------------------------+ |
| |                                     | |
| |               node 2                | |
| |                                     | |
| +-------------------------------------+ |
| +----------+ +----------+ +-----------+ |
| | video 2a | | video 2b | | video 2c  | |
| +----------+ +----------+ +-----------+ |
+-----------------------------------------+

p.s. - We're already using the Context module, if that helps at all (and consequently, we'd like to avoid installing Panels, since they serve similar purposes).

A simple solution would be to use node reference on the destination node which reference video nodes. Then it's just a matter of theming to convert the node references (node ids) to videos.


Disable Rule which is causing a redirect loop I have created a rule for logged in members that if they go to the home page it redirects them to a different page. The home page needs to be different for anonymous and authenticated users.

One problem is that my rule is not working. I have created a redirect loop by mistake. This means I can not get to the rules interface to disable the module. I know I could disable the rules module via drush however I will have the same problem when I turn it back on.

I had a quick look in db and see the rules_rules table. However the data is stored as a blob so I can not edit it. Except for deleting my rules what could I do to disable it?

You got a few options.

You can try to edit the data by deserializing it with PHP and try to get some meaning out of it. Most likely there is a status which is either 1 or 0.
You could delete the rule from the database entirely.
You can temporarily modify the rules_invoke_event (rules.module line 249 for 1.4), if you comment out the call_user_func_array call, no rule should be invoked on the site.

Either of these should work, personally I would go for the last one if I had write access to the rules files.


Displaying Database Data Within the Flow the Site I have a multi-page form that works fine in and of itself (pathfindertool.module). However, once a user clicks submit I want the page to display some records on the page. And it DOES display the records on the page, but NOT within the flow of the page. What I mean by that is, it just puts all the returned results in the top-left of the page in the browser window in  and not in a  tag in the #content area for example where content is supposed to go.

I tried to use javascript document.getelementbyid.innerhtml, calling that from my php and it just returns no results (well it returned them according to console but it didn't display them):

while ($row = $result->fetchAssoc()) {
    echo '';
  }
  }

I also tried doing drupal_add_js inside my .module file and can't get that to work either. Granted my coding here is pretty kloogy:

drupal_add_js('document.getelementbyId("pathfinder-primary-form").innerHTML = "', 'inline');

$title = $row['title'];

drupal_add_js('document.getelementbyId("pathfinder-primary-form").innerHTML = "', 'inline');

Surely this must be one of the most common workflows ever. What's the best practice for displaying data from a database in Drupal so that it displays within a specific  (ie. #main, or perhaps even the form container itself)?

Here's my pretty basic functioning code so far for displaying the results in my .module file:

if ($result) {
while ($row = $result->fetchAssoc()) {
    $title = $row['title'];
    echo '
' . $title. '
';

  }
  }

But of course it displays it in the top-left corner of the body in the browser window right above the Logo! O.O

What am I doing wrong and how can I fix it?

Drupal splits functionality (modules) and layout (themes) to keep everything maintainable.

Instead of echoing everything, you need to pass your output from your module to the theme.

First step is making a menu item. This will give you an url to work with: https://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook_menu/7

Basic example:

function pathfindertool_hook_menu() {
    $items['pathfinderurl'] = array(
      'page callback' => 'pathfindertool_page',
    );
    return $items;
}

The page callback point to a function that contains your logic. You can choose the function name, but it's advised to start with your module name.

function pathfindertool_page() {
  $output = '';
  drupal_add_js('document.getelementbyId("pathfinder-primary-form").innerHTML = "', 'inline');

  $title = $row['title'];

  drupal_add_js('document.getelementbyId("pathfinder-primary-form").innerHTML = "', 'inline');

  // Do whatever you did to fill result.
  if ($result) {
    while ($row = $result->fetchAssoc()) {
      $title = $row['title'];
      $output.= '<p>' . $title. '</p>';

    }
  }
  return $output;
}

Returning the output will make sure it will show in the right place. Never use echo or print, it will show up at the top.

You must always return something, even an empty string is ok, return NULL will result in a WSOD. That's why I always start my function with $output = '';


Site Configuration returns blank page I have just updated the Internationalization and language_dropdown modules successfully after Drupal asked me to. Having done that, the site configuration when clicked every time, returns blank page. Sometimes when I click it twice, it returns a screen with a table of PHP errors of the the l10n update. This is frustrating. I know that this is regarding the update I made. But a bit of searching indicated that this is because l10n_update is still available in beta3 form.

I would start by troubleshooting the horrid White Screen of Death.  Once you find the culprit module/file/function/setting this should be much easier to fix.

You may also want to scope out the Language Dropdown bug list, the i10n_update bug list and the i18n bug list.

If you will post back with details regarding the WSoD I'll do my best to update my answer.


How to save single value from a select field? I have webform module with multiselect field (Checkbox) User can select all the three.

  PR|Print Required
  DP|Digital Print Required
  TP|Print has been taken

If user selects the last option then, only that option must be saved after submitting even if the other options are selected. If other two options are selected then as usual those options should be saved.

In General,
If the user selects the first two options, it should accept the first two options. If user selects third option, then it should save the third option not other two options(If user selects). Example: If user selects all three options, then it should save only the last option.If user selects the last option i.e., Print has been taken, then it should save that irrespective of other selections.

I would use jQuery to deactivate and uncheck the other two checkboxes when the third has been checked. If they uncheck the third, they will all become active.

Your Drupal form will look something like this:

    <input type="checkbox" class="form-checkbox" value="pr" name="field_terms[und][pr]" id="edit-field-terms-und-pr">  Print Required

    <input type="checkbox" class="form-checkbox" value="dp" name="field_terms[und][dp]" id="edit-field-terms-und-dp">  Digital Print Required

    <input type="checkbox" class="form-checkbox" value="tp" name="field_terms[und][tp]" id="edit-field-terms-und-tp">  Print has been taken

jQuery code would be something like this:

(function($) {
$(document).ready(function() {

    $("#edit-field-terms-und-tp").click(function() {
        if($(this).is(':checked')) {
            $('#edit-field-terms-und-pr, #edit-field-terms-und-dp').attr('disabled', true).prop('checked', false );
        } else {
            $('#edit-field-terms-und-pr, #edit-field-terms-und-dp').removeAttr('disabled');
        }
    });

});
})(jQuery);

Haven't tested it, but it should work.


Can Google Bot Crawl authenticated pages? I am using Organic Groups and most of the pages i.e Discussions and related pages are only accessible to an authenticated user, can google bot crawl all these pages as well or is thrown a 403 error ?

Drupal will send a 403 response for any protected pages to any user agent, including the Googlebot, unless that user agent has been authenticated by Drupal and has a valid session cookie.

If your pages are only accessible by users with the "authenticated user" role, Google will not be able to crawl them.


How do I use hook_search_api_solr_search_results_alter() to alter search results? I want to alter the results of a Drupal 8.x search_api_solr search using hook_search_api_solr_search_results():
function sbn_search_api_solr_search_results_alter(\Drupal\search_api\Query\ResultSetInterface $result_set,
                                                     \Drupal\search_api\Query\QueryInterface $query,
                                                       \Solarium\QueryType\Select\Result\Result $result) {
 $resultset_data = $result->getData();
  // Get docs in response results
  $results = $resultset_data['response']['docs'];
  foreach ($results as $id => &$item) {
    // get the doc and array id
  }
}

I know that the docs I seek are in the search results:
dsm($result);

returns
stdClass Object
(
    [__CLASS__] => Solarium\QueryType\Select\Result\Result
    [numfound:protected] => 5
    [maxscore:protected] => 1.8644972
    [nextcursormark:protected] =>
    [documents:protected] => Array
        (
            [0] => stdClass Object
                (
                    [__CLASS__] => Solarium\QueryType\Select\Result\Document
                    [fields:protected] => Array
                        (
                            [ss_search_api_id] => entity:node/47:en
                            [ss_search_api_language] => en
                            [score] => 1.8644972
                        )

 ...
    [data:protected] => Array
        (
            [response] => Array
                (
                    [numFound] => 5
                    [start] => 0
                    [maxScore] => 1.8644972
                    [docs] => Array
                        (
                            [0] => Array
                                (
                                    [ss_search_api_id] => entity:node/47:en
                                    [ss_search_api_language] => en
                                    [score] => 1.8644972
                                )

                            [1] => Array
                                (
                                    [ss_search_api_id] => entity:file/85:en
                                    [ss_search_api_language] => en
                                    [score] => 1.784599
                                )

Let's say that the doc in question that I want to remove from $result object is:
$resultset_data['response']['docs'][$id]

How do I alter the $result object to remove this doc from results?  Every attempt I have made to access the $result object as an array has resulted in these types of errors:

Error: Cannot use object of type Solarium\QueryType\Select\Result\Result as array

Error: Cannot access protected property Solarium\QueryType\Select\Result\Result::$response

Any suggestions or documentation on this would be highly appreciated.

I have installed search_api, search_api_solr and search_api_attachments.  The View that I am reading with the hook is a Solr indexed view returning solr index extracts.

I discovered this was how to read the result rows:

  $result_items = $result_set->getResultItems();
  // Iterate through doc ids
  foreach ($result_items as $docid => $value) {
    // process info from $docid and/or $value
  }

$docid will be the Solr document id, i.e.: entity:node/47:en

In my case, all the information I need, entity type and entity id, are in the document id.

If I want to remove the result row:

unset($result_items[$docid]);

And at the end of the hook:

$result_set->setResultItems($result_items);


Why doesn't my text filter strip out the tags I don't want? I thought I understood text filters, but it appears I don't.

I am using a filter on my node's "body" field that is supposed to restrict tags. I have entered the allowed HTML tags as

<em> <strong> <cite> <blockquote> <code> <ul> <ol> <li> <dl> <dt> <dd> <br>

Yet in my WYSIWYG editor I can switch to source view and save text that includes  (or worse, ) tags.

Why aren't these tags stripped out when the node is saved?

Okay, I've found my own answer. The problem was with my understanding of how text filters work. Text is saved into the database with no changes, and filters are only applied when the text is output.

When using Entity Metadata Wrappers, as I am, when you get $wrapper->body->value(), it gives you an array with several elements. One is the "value", which is the raw, unfiltered text. Another is the "safe_value", which has had filters applied.

So in my case I needed to use the "safe_value" when displaying the text. Makes sense once you understand it!


Views field rearrange I am using Field group module for creating fieldset in content type.

Can I have similar features while rearranging the fields selected in views.

You can try using module Field group views

Project page says

  Provides a view format for Field group.

  In other words, a field group can be displayed using a view. One
  possible usecase would be to generate a table using fields as columns.


variable_del wildcard when uninstalling a module I have lot of variables created in a module. Is there any wildcard when deleting variables using variable_del.

Ex1: variable_del($key . '_campaign_text_*');
Ex2: variable_del($key . '_campaign_text_%');

Will any of these workout?

You can try db_delete but handle with caution.

Example :

db_delete('variable')
->condition('name', '_campaign_text_%','LIKE')
->execute();
cache_clear_all('variables', 'cache_bootstrap');


How to use SQL clause GROUP BY? I am using Drupal 8 and want to use custom query to get details like below:

$db = \Drupal::database();
$query = $db->select('sinica_grade_summary','sgs');
$query->fields('sgs', ['id', 'coursename', 'average', 'grade', 'term', 'schoolname']);
$query->condition('sgs.uid', $id, '=');
$query->groupBy("sgs.coursename");

Getting this error :

Drupal\Core\Database\DatabaseExceptionWrapper: SQLSTATE[42000]: Syntax error or access violation: 1055 'lmhd8.sgs.id' isn't in GROUP BY: SELECT sgs.id AS id, sgs.coursename AS coursename, sgs.average AS average, sgs.grade AS grade, sgs.term AS term, sgs.schoolname AS schoolname, COUNT(sgs.id) AS count FROM {sinica_grade_summary} sgs WHERE (sgs.uid = :db_condition_placeholder_0) GROUP BY sgs.coursename ORDER BY id DESC LIMIT 11 OFFSET 0; Array ( [:db_condition_placeholder_0] => 28 ) in Drupal\resume\Controller\ResumeController->sinica_academic_detail()

I used mariadb10, there is no sql_mode been used

mysql  Ver 15.1 Distrib 10.1.13-MariaDB, for osx10.11 (x86_64) using readline 5.1

MariaDB [(none)]> SELECT REPLACE(@@SQL_MODE, ',', '\n');
+--------------------------------------------+
| REPLACE(@@SQL_MODE, ',', '\n')             |
+--------------------------------------------+
| NO_AUTO_CREATE_USER
  NO_ENGINE_SUBSTITUTION |
+--------------------------------------------+

Here is table structure

    CREATE TABLE `sinica_grade_summary` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `uid` int(10) unsigned NOT NULL,
  `studentid` int(10) DEFAULT NULL,
  `courseid` int(10) DEFAULT NULL,
  `leadcourseid` int(11) DEFAULT NULL COMMENT '对应 courseid 关系',
  `coursename` varchar(64) DEFAULT NULL,
  `teacher` varchar(64) DEFAULT NULL,
  `teacher_email` varchar(32) DEFAULT NULL,
  `average` varchar(64) DEFAULT NULL,
  `grade` varchar(64) DEFAULT NULL,
  `status` varchar(64) DEFAULT NULL,
  `createtime` int(11) DEFAULT NULL,
  `markingperiodid` int(11) DEFAULT NULL,
  `durationid` int(11) DEFAULT NULL,
  `term` varchar(64) DEFAULT NULL,
  `gradelevel` varchar(32) DEFAULT NULL,
  `schoolname` varchar(64) DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `sinica_uid` (`uid`),
  KEY `sinica_term` (`term`) USING BTREE,
  KEY `sinica_subject` (`coursename`)
) ENGINE=InnoDB AUTO_INCREMENT=623 DEFAULT CHARSET=utf8mb4 COMMENT='The data table for user entities.';

How to fix this problem?

You can do this to make it work:

$db = \Drupal::database();
$query = $db->select('sinica_grade_summary','sgs');
$query->fields('sgs', ['coursename']);
$query->condition('sgs.uid', $id, '=');
$query->groupBy("sgs.coursename");


Error message - Trying to get property of non-object i'm getting a notice

  Error message - Trying to get property of non-object

here's my function:

<?php
function func()
{
        $node = menu_get_object();
        global $user;
        if ($node->type == 'hall' &&
            in_array('instructor', array_values($user->roles)))
        {
            return " hall-instructor ";
        }
}
?>

You need to check what node_get_object() returns since it could not return an object. This is particularly true when the user is not watching a node page, but even in the case the viewed page is a node one, the function could not return an object. This is why Drupal code always check the returned value.

function book_page_alter(&$page) {
  if (($node = menu_get_object()) && !empty($node->book['bid'])) {
    $active_menus = menu_get_active_menu_names();
    $active_menus[] = $node->book['menu_name'];
    menu_set_active_menu_names($active_menus);
  }
}

// template_preprocess_page()
if ($node = menu_get_object()) {
  $variables['node'] = $node;
}

// template_preprocess_html()
// If on an individual node page, add the node type to body classes.
if ($node = menu_get_object()) {
  $variables['classes_array'][] = drupal_html_class('node-type-' . $node->type);
}


drupal 7 views horizontal align not working in grid? First time ever had this problem with views not rendering images to horizontal align in grid.

I have the Views module version 7.x-3.5 installed on Drupal 7.18.

I actually realized it is aligning for immediate view of links, but not within the view after clicking a link. How do I make all images horizontal align?

You can horizontally align things with CSS

e.g

.container{
  text-align:center;
}

You can also align using a margin or padding.

In your case:

.view-galleryofimages .views-view-grid {
  margin:0 auto;
}

Should suffice.

See this summary for more info: CSS Horizontal Align


How to modify contents of drupal select form element based on what was selected in a preceeding select element First off, I am not a Javascript guru so this may be easy to acccomplish but I just don't know how.

Here is my situation: I have created a form in Drupal 7 and I have two dropdown select box in that form. I would like to change the possible selections in the second dropdown based upon what the user has selected in the first drop down.

Is there a way to add a change listener in Drupal so as to trigger an ajax update of the form?

Thanks.

You can create it with built-in Ajax Framework (you don't need to use javascript). Here is a nice example (and I'll include the code here):

function sandbox_ajax_dropdown($form, &$form_state) {
  $form['sandbox_ajax_dropdown']['province'] = array(
    '#title' => t('Province'),
    '#type' => 'select',
    '#options' => _load_province(),
    '#ajax' => array(
      'event'=>'change',
      'callback' =>'sandbox_ajax_dropdown_city',
      'wrapper' => 'city-wrapper',
    ),
  );

 $form['sandbox_ajax_dropdown']['wrapper'] = array(
    '#prefix' => '
',
    '#suffix' => '
',
  );

  $options = array('- Select city -');
  if (isset($form_state['values']['province'])) {
    $options = _load_city($form_state['values']['province']);
  }

  $form['sandbox_ajax_dropdown']['wrapper']['city'] = array(
    '#title' => t('City'),
    '#type' => 'select',
    '#options' => $options,
  );

  $form["sandbox_ajax_dropdown"]["submit"] = array(
    "#value"  => t("Submit"),
    "#type"   => "submit",
    "#submit" => array("sandbox_ajax_dropdown_submit"),
  );

  return $form;
}

function sandbox_ajax_dropdown_city($form, $form_state) {
  return $form['sandbox_ajax_dropdown']['wrapper'];
}

function sandbox_ajax_dropdown_city($form, $form_state) {
  return $form['sandbox_ajax_dropdown']['wrapper'];
}

function _load_province() {
  $province = array('- Select province -');
  $query = db_select("sandbox_province", "a");
  $query->fields("a", array('id', 'name'));
  $query->condition("a.status", 1);
  $query->orderBy("a.name");
  $result = $query->execute();

  while($row = $result->fetchObject()){
    $province[$row->id] = $row->name;
  }

  return $province;
}

function _load_city($province_id) {
  $city = array('- Select city -');
  $query = db_select("sandbox_city", "a");
  $query->fields("a", array('id', 'name'));
  $query->condition("a.status", 1);
  $query->condition("a.province_id", $province_id);
  $query->orderBy("a.name");
  $result = $query->execute();

  while($row = $result->fetchObject()){
    $city[$row->id] = $row->name;
  }

  return $city;
}

And also take a look at Examples module.


Can I use the CTools modal functionality under HTTPS adn Display Suite? The client for a new project wants their content to display in a modal overlay.  From my research so far, it seems using ctools is the way to go.

My question is, some of this content will be product displays (using Drupal Commerce).  Will there be a conflict with the AJAX functionality while the pages are HTTPS?  I'm also using Display Suite to lay out the content.  Is anyone familiar with any issues that may arise while using ctools' modal functionality with Display Suite?

HTTPS should just work, or I would say there's a bug in ctools.

I haven't used DS much, so can't really comment, but DS handles View modes, and I would expect all ctools modules to deal nicely with those.


What does vetted role mean? I just read in drupal.org site this comment:

A user who doesn't have the vetted role cannot become the only
maintainer, or the project maintainer, of a project that opted into
security coverage, in the same way a user without the vetted role
cannot take over a project that opted into security coverage.

I tried to found what is this on the site without luck and I really don't have an idea.
Does somebody know what means vetted role in drupal.org?

In order for a Drupal contributed module to be eligible to be tagged as a security monitored project, one or more of the maintainers have to be 'vetted'.
Here is the main Drupal security policy on this.  See the "Which Projects are covered" section.  There is a link in this to the process of becoming 'vetted'.
Basically, you submit a Drupal.org project to a queue.  Eventually, security community members will review it for use of best security practices, code quality, and some other stuff.  If approved, the maintainer becomes 'vetted'.  Unfortunately, this process can take a long time to happen.
Once you have a project approved and are 'vetted', any other projects you maintain can be labeled as covered by the security community.


How to show field collection items with comma separated in views? I have profile type programmer. This profile type having a field 'field_collection' type named language.

In the field collection we have two fields

Language
Year of experience

Now I am going to create a view that will show all the users associated with that profile type(programmer). I want to add an field(language) in that view which will have all the languages with comma separated.

NOTE : I don't want to show 'year of experience' in the field, just want to show the 'language' only.
Ex : C++, PHP, JavaScript

The basic setting for fields with multiple values actually has that as default. When you are adding the field into your view click on the multiple field settings tab and it will show you the functions to do just this.


How to list duplicate nodes, with views, based on compared fields with links I'm trying to create a list with duplicate nodes, so i can delete those.
I'm not coder and I have already tried the module "remove duplicates" without success, so i have to use views with vbo module.

The field i have to compare nodes, contains a link.
If the same link is in more than one node, i need it to be listed.

I have turned aggreation on.
I have one field, displaying a link.
I have created a filter, pointing at the above field with link,  with "count" and set it to "show only greater than 1" acording to other similar questions on how to list duplicate  titles.

Unfortunately this does nothing for me. As soon as i turn on the filter, there is no output.

Can you tell me what I'm missing here ?
Sorry for the poor english.

There isn't an easy, non-coder based way to do that with views. You could however create a view with the link field visible, and as a sort parameter as well. That way identical field values would show up next to one another. It'd be then the process of selecting the duplicate node (I'd suggest deleting the one with the higher nid) and deleting it.

Let me know if that makes any sense at all, or if you need a 5 minute proof of concept demo.


return other indexed fields using SearchApiQuery($index) I created an index that indexes taxonomy terms.
I indexed the term name + field_skill type text.
The current result shows only the term id + score.

I want to show also the field_skill.

 $term = 'drupal';

 // Select an index.
 $index = search_api_index_load("terms");
 $query = new SearchApiQuery($index);

 // Conditions.
 $query->condition('name', $term, '=');
 // $query->condition('language', $language->language, '=');

 // Fetch results.
 $results = $query->execute()['results'];
 dpm($results); // returns only ids and score I want to return other indexed fields

If you are using Solr, on server configuration (admin/config/search/search_api/server/YOUR_SERVER_NAME/edit), under "Advanced" fieldset, you should enable the "Retrieve result data from Solr" option:


hook_form_FORMID_alter not working function send_xml_form_user_profile_form_alter(&$form, &$form_state){
    $form["#submit"][] = 'send_xml_edit_account_submit_function';
    drupal_set_message('
' . print_r($form['#submit'], TRUE) . '
');
}

function send_xml_edit_account_submit_function($form, &$form_state) {
    drupal_set_message(t("ahoy"));
}

the modules name is send_xml.module.

this code drupal_set_message('
' . print_r($form['#submit'], TRUE) . '
'); displays

Array
(
     [0] => user_profile_form_submit
     [1] => send_xml_edit_account_submit_function
)

but this code drupal_set_message(t("ahoy")); isnt displaying...

anyone ring a bell?

it's quite annoying to have problems which you cant find the reason why... does anyone experience this before? if yes, would please so kind to share your solutions to me. thank you very much! :)

Can you try

function send_xml_form_user_profile_form_alter(&$form, &$form_state, $form_id){
    $form['actions']['submit']['#submit'][] = 'send_xml_edit_account_submit_function';
    drupal_set_message('<pre>' . print_r($form['#submit'], TRUE) . '</pre>');
}

Try clearing Drupal cache before you see the changes..


Change routing behaviour for non-existent entities For my custom entity type called item, I would like to set up routes such that the path:

/item/{item}

views the entity as normal, if it exists
if it doesn't exists, redirects to the create form

The default Entity controllers create a 404 response. How can I change that behaviour?

Currently, the routes are generated through the entity's annotation (via DefaultHtmlRouteProvider):

* links = {
*   "canonical" = "/item/{item}"
*   ...
* }

Yes, routing is one way to do this. Extend the entity view controller, where you call (1) the parent method to view the entity or (2) redirect to the create form. Change the route so that it points to the new controller and remove the options for type casting and converting the entity parameter. You have then to load the entity in the controller by hand, because the controller gets only the raw parameter (the entity id), but you need to check if the entity exists anyway to decide if you need to redirect. You can change the route by extending DefaultHtmlRouteProvider or in a RouteSubscriber. You might also need to move the access check from the route to the controller after the entity is loaded.

There are more ways to do this, you could redirect in a request subscriber where you check if the entity exists before routing or you could redirect in an exception subscriber after a 404 is raised.

The last option is possibly easier to implement, because then you don't need to think about routing and access checking and simply react on a 404 caused by your specific entity route.


How do I create a file download popup form? I am new to drupal, and I want to create a popup form with with form fields for name and email, and a buttom to download and to close the popup.

When users click on the download link, the popup form appears; users enter their name and email address; once the data have been validated, the users can download the file, and see how many users downloaded it.

How can I achieve this.

Email Download does just what you want.

  A tiny module to make downloads only available to people who submit their email address to the site in case the site creator doesn't want visitors to be required to create an account. The email is checked for validity and a cookie with a hard to guess authentication string is stored in a browser cookie. The next time (and of course this first time) the user makes a download, the cookie is checked and the user can proceed. This of course requires cookies to be on on the client side.


How do I check which of my installed modules is unsupported? When I go to admin/modules, I get this scary warning:

  The installed version of at least one of your modules or themes is no
  longer supported. Upgrading or disabling is strongly recommended. See
  the project homepage for more details. See the available updates page
  for more information and to install your missing updates.

That sounds like something I'd like to fix!  So I click the "available updates" link, but that page tells me:

  All of your projects are up to date.

Hmmm.  I tried checking for updates with Drush (drush up) but Drush doesn't find any updates either.  How can I find which modules installed in my site are unsupported?

As stated here, you need to go to admin/reports/updates rather than admin/reports/updates/update to see which module is having the problem.


Access custom billing field in rules using Commerce I have added the field field_e_mail to the Billing profile type in Commerce and would like to use this for sending an confirmation email to the customer (customers never log in). However, I can't for the life of me get hold of the field in rules. I've tried to use Entity has field in different ways, but I still can't get it to work.

What can I do to get the field_e_mail field from Billing into rules and use it for sending a confirmation email?

This is where I am at the moment (test@test.com is just a placeholder where I'd like to put the field_e_mail value):

{ "commerce_checkout_checkout_send_order_activation" : {
"LABEL" : "Send an order notification e-mail (cloned)",
"PLUGIN" : "reaction rule",
"WEIGHT" : "4",
"OWNER" : "rules",
"TAGS" : [ "Commerce Checkout" ],
"REQUIRES" : [ "rules", "commerce_checkout" ],
"ON" : { "commerce_checkout_complete" : [] },
"IF" : [
  { "entity_has_field" : { "entity" : [ "commerce-order" ], "field" : "commerce_customer_billing" } },
  { "entity_has_field" : {
      "entity" : [ "commerce-order:commerce-customer-billing" ],
      "field" : "field_e_mail"
    }
  }
],
"DO" : [
  { "mail" : {
      "to" : "test@test.com",
      "subject" : "Order [commerce-order:order-number] at [site:name] test",
      "message" : "hello.",
      "from" : "no-reply@test.com",
      "language" : [ "commerce-order:state" ]
    }
  }
]

}
}

If you have added the e-mail field on the commerce profile type as you said, you should access is via the profile type as well. (It is not a property of the commerce order.)

Normally, the commerce profiles are already available when the commerce order is loaded. But you might not recognize them as such. Nothing indicates it it a profile.

For instance I have access to these profiles:

And then you can use a condition like this:

  { "entity_has_field" : {
      "entity" : [ "commerce-order:commerce-customer-quotation" ],
      "field" : "commerce_customer_address"
    }
  }


admin/people/permissions no access I can not access admin/people/permissions, even the link to permissions in the backend-menu is not visible. But I am logged in as admin! So what can be the problem here?

Your administrative role probably lacks the "administer permissions" permission.

If you have Drush installed:

$ drush role-add-perm 'administrator' 'administer permissions'

You may also want to make sure your site still defines the 'administrator' role, since occasionally developers may manually delete the default roles from the DB (really not a good idea unless you know what you're doing). If you can't view available roles you can run this Drush command:

$ drush role-list

If it's not there, then you may have to create a new role to replace the admin role that was deleted and assign the role to yourself, and give your new role the 'administer permissions' permission:

$ drush role-create 'administrator'
$ drush user-add-role 'administrator' 'your username'
$ drush role-add-perm 'administrator' 'administer permissions'

If for some reason you don't have terminal access to your server, then you may need to download and enable the Devel module and PHP filter, then write a script that you can paste and run in /devel/php, but that should really be your last resort. https://drupal.stackexchange.com/a/56495/72084

p.s.: I believe Drupal gives user 1 the administrator role and completely unrestricted access by default. So if you are logged in as someone other than user 1, and/or if the administrator role has been deleted, that may explain how this problem came about. https://www.drupaleasy.com/quicktips/beginner-tip-what-special-about-drupal-user-1


Display view on all page routes I would like to display a multi value media field and its file type and size in a content type and display it in a table layout. I thought using a view would be the best way to pull the media file type and file size and any references it has using views relations.

The view uses Relations to get the media type and size and uses a Contextual filter - Content ID from URL. Now I am printing the display in a node template like this using Twig tweak.

{{ drupal_view('materials', 'block_1') }}

The table and media values display fine when published on route entity.node.canonical.

But the media values do not display on other routes and tabs like /latest routename entity.node.latest_version and /full routename entity.node.preview. The table markup displays but not the media values inside. I have tried printing the view using the drupal_block method and had the same results.

The content id is missing from your function call you have to add it like this

{{ drupal_view('who_s_new', 'block_1', arg_1, arg_2, arg_3) }}

or you can render your view in custom block and add it in every page via 'block layout'

https://www.webwash.net/programmatically-create-block-drupal-8/

$view = views_get_view('view_name');
$view->set_display('view_block_name');
$view->set_arguments(array($tid));
// change the amount of items to show
$view->set_items_per_page(4);
$view->pre_execute();
$view->execute();
$view->render();


Changing column names for CSV export in Webform results download page This should be very basic. Unfortunately I couldn't find any page that provides specific instructions on how to do this. If anyone can point me in the right direction, much obliged.
Basically I just need to automatically rearrange and change the names of a few columns when I go to the submissions results download page in Webforms. That way, when I export in CSV, I get the column names I want instead of the ones I created in the actual webform.
I'm aware you can do this via a view, but I would like more specific instructions... Anyone know of any guide that can point me in a right direction?
Thanks.

If you want to change the column title of an exported element, the simplest solution is to specify an 'Admin title' via the element edit form's 'Advanced' tab under the 'Administration' detail widget.


hook_file_download not triggered I set the private file system to /system/files/export , I create a file in private directory programmatically and it not belong to any field ,and show link to user , I implement Hook_file_download , I want check some condition in it but when user click on link to download the file created in private path it return me Forbidden and mymodule_file_download not tirggered ( I put some code to it , even die but never called).
I clear cache but noting changes,
the link that showed for user is http://localhost/mytestdrupal/system/files/export/Export-couponcards-1393307265.csv
where is problem?

Part of my code to create file in submit

function mymodule_export_form_submit($form, $form_state) {
    $temp1 = variable_get('file_private_path');
    if (!file_prepare_directory($temp1, FILE_CREATE_DIRECTORY)) {
        drupal_set_message(t('Problem in write file in directory'), 'error');
        return;
    }
    $filename = 'Export-file'. '.csv';
    $filepath = $temp1 . '/' . $filename;
    $df = fopen($filepath, 'w');
    if (!$df) {
        drupal_set_message(t('Can not write file in') . $filepath, 'error');
        return;
    }
            fputcsv($df, array('code', 'name'));
            fputcsv($df, array('test','test'));

    fclose($df);
    $path = file_create_url($filepath);
    drupal_set_message(t('Export done. ') . '' . t('Download export file') . '');
}

hook_file_download working perfectly, List of steps which worked for me

I made File System to Private
Created a File Field in Article Content Type and marked it as Private In Settings
Uploaded a PDF File
Link to file is something link below

http://example.com/d7/system/files/**.pdf

Created a custom module with hook_file_download, When ever i access above URL and visit any page i can see drupal set message "Hi"

function drup_custom_file_download($uri) {
  drupal_set_message("Hi");
}


Is it possible to build a site without Users and Node? It's hard for me to imagine any site that could be built without the Users and Node modules.  Having them as modules makes it possible to replace them with alternatives, I suppose, but they are so fundamental to how Drupal works that I would suspect that anyone who wants different behavior would probably just skip Drupal altogether, since replacing these might break most of the other modules you might use.

Is it possible to build a Drupal site without Node and Users?  Has it actually been done, or is it just a theoretical possibility?

With Drupal 7 and a reasonable amount of effort, I don't actually believe it's possible.

Drupal 8 however will further decouple the modules, so that you can (hopefully) truly build a site without it.

A good use case for disabling User, is as a security hardening mechanism. Have your production site completely disallow logging in by not having the module, and push content from an internal stage environment instead with the help of something like Deploy.

A good use case for disabling Node could be a file handling API. One would need the file entity, but then only communicate with the world through a REST based API. No nodes (or even theme) needed.


Display only selected term from content type in Views maybe this is duplicate but I cant find solution and answer for this one, maybe its so basic buy I need little  help about.

I have content type with:
 1. Title
 2. Body
 3. Category
(Category field is Vocabulary check box with two taxonomy terms called
 1. Yes
 2. No

So I have contents some are with selected yes and some one are selected with no, I want to create a view and display only with the selected (Yes) contents. Any idea how should I do it. Thank you for reading this.

Under your Views,

Add filter criteria > Has taxonomy term > apply

Vocabulary: your vocabulary in question > Apply

Is one of: Yes > Reduce duplicates > Apply

Save your Views.

HTH


jQuery slideshow behaving oddly in Drupal I have a jQuery slideshow that worked fine when it was running in a site built with standalone PHP files, but now that I've rebuilt the site in Drupal, it has a problem. The slideshow is running in the header of this page:

http://oaklandoctopus.org

There are five images in the slideshow, the first of which is selected randomly. The first time the script loops back to the beginning, the first image does not appear. Then, on subsequent loops, everything is fine. Here is the jQuery script:

var x = Math.floor(Math.random() * $(".home-page-header-images .view-content .header-slideshow-image").length);
$(".home-page-header-images .view-content .header-slideshow-image:eq(" + x + ")").addClass("active").css({opacity: 1.0});

    setInterval(homepageSlideshow, 4000);

    function homepageSlideshow() {
        var activeImg = $(".header-slideshow-image.active");
        var nextImg = activeImg.next(".header-slideshow-image");
        console.log($(".header-slideshow-image:first"));
        if (nextImg.length == 0) {
            nextImg = $(".header-slideshow-image:first");
            }
        nextImg.addClass("next").animate({opacity: 1.0}, 1000, function() {
            activeImg.removeClass("active").css({opacity: 0.0});
            nextImg.removeClass("next").addClass("active");
        });
    }

Here is the relevant CSS:

.home-page-header-images .header-slideshow-image, #footer-slideshow .header-slideshow-image {
opacity: 0;
position: absolute;
z-index: 0;
/* Early IE */
filter: alpha(opacity=0);
}

.home-page-header-images .header-slideshow-image.active, #footer-slideshow .header-slideshow-image.active {
z-index: 1;
display: block;
}

.home-page-header-images .header-slideshow-image.next, #footer-slideshow .header-slideshow-image.next {
z-index: 2;
display: block;
}

I am so thoroughly stumped its not even funny. Any help is greatly appreciated. Happy to provide any additional information. I'm relatively new to Drupal theme development, just FYI.

This because you have two slider block in your durpal website. The second one is hidden in the footer section. Block id is : block-multiblock-7.

Both of these block are having same DOM structure, so in the following scenario your slider will break.

Breaking Scenario:
Main slider -> 5th Image is active.
Footer Slider -> 3th Image is active

Then your condition fails:

if (nextImg.length == 0) {
            nextImg = $(".header-slideshow-image:first");
            }

Hope you are clear with my point.

Thanks


VotingApi / Fivestar rating Player per Game Can not figure how this works, and hope is doable.

I'd like to add a feature using the fivestar module but I could not figure it out myself. The work may simply require configuring the module correctly or make code changes.

I create a new node with "game" content type for each game.
I add the team squad (list of players) for that game. Each player is a separate node, with "player" content type.
I would like each player to be voted per game and display the score of the player for that game only. This is where I'm stuck, I could not display player votes per game.

Thanks

You can set up an intermediary content type containing two reference fields and a fivestar field. One reference field references the game, the other references the player. Then use views as a block with a contextual filter to display the fivestar and the player info on the game node.


Form submit with radio in table has data in form_state['input'] and not in form_state['values'] While developing a form for Drupal 7, I need a few radio groups, placed inside a table (one radio group per table row). The radios are defined as '#type' => 'radio' (not radios) and grouped together using the same name attribute per group. Nevertheless, when the form is submitted, the radio selections are not in the $form_state['values'] array, but in $form_state['input'].

As you can see from the screenshots, all data is stored in input, with the radios being outside the 'undefined' array, even though I placed them in $form['undefined'][$key][x]. In values only the select and textfield data is retained.

Any ideas? It's been two days now that I'm trying to resolve this :(
Thank you in advance.

function game_insert_form($form, &$form_state) {
  dpm($form_state, 'form_state');

  $test_data = array(
    '2' => 'Alfa',
    '4' => 'Beta',
    '6' => 'Gamma',
    '8' => 'Delta',
  );

  $header = array(
      t('Name'),
      array('data' => t('Existing'), 'colspan' => 2),
      array('data' => t('New'), 'colspan' => 2),
  );
  $form['undefined'] = array(
      '#tree' => TRUE,
      '#theme' => 'table',
      '#header' => $header,
      '#rows' => array(),
  );
  foreach ($test_data as $key => $data) {
    // Label
    $label = array('#markup' => $data);
    $children = array(&$label);
    $row = array(array('data' => &$label));
    unset($label);
    // radio 0
    $radio0 = array(
      '#type' => 'radio',
      '#return_value' => 0,
      '#value' => 0,
      '#name' => 'undefined-' . $key . '-radio',
    );
    $children['radio0'] = &$radio0;
    $row[] = array('data' => &$radio0);
    // dropdown
    $select = array(
      '#type' => 'select',
      '#options' => array(0 => 'Zero', 1 => 'One'),
      /*'#states' => array(
        'enabled' => array(
          ':input[name="undefined-' . $key . '-radio"]' => array('value' => 0),
        ),
        'required' => array(
          ':input[name="undefined-' . $key . '-radio"]' => array('value' => 0),
        ),
      ),*/
    );
    $children['select'] = &$select;
    $row[] = array('data' => &$select);
    // radio 1
    $radio1 = array(
      '#type' => 'radio',
      '#return_value' => 1,
      '#value' => 0,
      '#name' => 'undefined-' . $key . '-radio',
    );
    $children['radio1'] = &$radio1;
    $row[] = array('data' => &$radio1);
    // textfield
    $textfield = array(
      '#type' => 'textfield',
      '#maxlength' => 40,
      '#size'=> 40,
    );
    $children['textfield'] = &$textfield;
    $row[] = array('data' => &$textfield);

    $form['undefined'][$key] = $children;
    $form['undefined']['#rows'][] = $row;
    unset($radio0);
    unset($select);
    unset($radio1);
    unset($textfield);
  }
  $form['next'] = array(
    '#type' => 'submit',
    '#value' => t('Test'),
    '#weight' => 0,
    '#name' => 'test',
  );
  return $form;
}

function game_insert_form_submit($form, &$form_state) {
  dpm($form_state, 'submit: form_state');
}

At last I managed to find the answer (after a lot of experimentation). The following code works fine for me. I am not sure if everything is needed, but I won't touch it as long as it works.

Pay attetion that I use an associative array for the #rows array, in order to be able to find the correct row without keeping track of indexes.
The most bizzare part is that I had to add $form[$key]['#type'] = 'value'; to hold the selected value.
The '#name' => $key, is obviously used to group the radios
together per row.
The '#id' => drupal_html_id($key . '[' . $item . ']'), was also
added, but I'm not sure if it's needed.

Obviously one does not need to use a seperate column for the label, but I display it this way because in my code I use drop downs and other controls instead of the labels shown here.

Here is the code:

function game_test_form($form, &$form_state) {
  dpm($form_state, 'form_state');
  $test_data = array(
    'alfa' => array(1, 2, 3),
    'beta' => array(1, 2, 3),
  );
  $header = array(
      t('Name'),
      array('data' => t('First'), 'colspan' => 2),
      array('data' => t('Second'), 'colspan' => 2),
      array('data' => t('Third'), 'colspan' => 2),
  );
  $form['undefined'] = array(
    '#tree' => TRUE,
    '#theme' => 'table',
    '#header' => $header,
    '#rows' => array(
      // The keys here are used later on for the correct #row insertion
      'alfa' => array('title' => t('Alfa')),
      'beta' => array('title' => t('Beta')),
    ),
    '#prefix' => '
',
    '#suffix' => '
',
  );
  $table = &$form['undefined'];
  foreach ($test_data as $key => $data) {
    // This stores the value in the $form_state['values']. It must be outside the table.
    $form[$key]['#type'] = 'value';
    foreach($data as $item) {
      $element = array(
        '#type' => 'radio',
        // this value will be assigned to the $form_state['values'][$key]
        '#return_value' => $item,
        '#default_value' => isset($form_state['values'][$key]) ? $form_state['values'][$key] : 0,
        // Radio group stored in input[#name] with the selected radio's #return_value as value
        '#name' => $key,
        '#id' => drupal_html_id($key . '[' . $item . ']'),
      );
      // Attach the radio to the logical tree, so as to be included in $form_state['values']
      $table[$key][$item] = &$element;
      // Attach the radio to the render tree, so as to be rendered.
      $table['#rows'][$key][] = array('data' => &$element);
      unset($element);
      // Attach its label to the render tree, so as to be rendered.
      $table['#rows'][$key][] = array('data' => array('#markup' => 'Label ' . $item));
    }
  }
  $form['next'] = array(
    '#type' => 'submit',
    '#value' => t('Test'),
    '#weight' => 0,
    '#name' => 'test',
  );
  return $form;
}
function game_test_form_submit($form, &$form_state) {
  dpm($form_state, 'submit: form_state');
  $form_state['rebuild'] = TRUE;
}


Best practices when choosing a method of displaying content? This is a little broad, but I have a specific example. I'm new to Drupal, with a WordPress background. I'm getting some of the core Drupal concepts down, but I'm left with some questions.

How do I know what method of displaying content is best for a situation? For example, I'm running Ubercart. I would like to display a single featured product on the home page. As far as I'm aware, I can't use a block because I'm not sure if I can pull node data into that. I could hard code it in the template file, maybe? Can I use a view?

Is there somewhere in the documentation where this concept is spelled out?

Thank you for the help.

You want to display a single, featured product on the homepage. I would try using Views to create a Block which you can then include in the Content region on the homepage.

In Views, set the criteria, so you're pulling the appropriate content type. Perhaps you have some kind of "featured" or "sticky" flag. Add that to your criteria as well. Then if you want to restrict it further by taxonomy or sort it by most recently added and restrict the view to a single item, you can do that (see Pager settings; click "Display all items" and adjust settings).

Typically, Views is used to create a Page or a Block. Have yours output a block, then at sitedomain.com/admin/structure/block, locate the new Block and add it to the page wherever you want it.


Change the front page based in the screen size of the visitor? I use the Omega theme to make a site responsive.
I need to change the Front Page of the site based in the screen size of the visitor.

The idea is to hide a front page which include a flash movie on mobiles devices.

Then:

if the user screen is small than 740px then the front page is: no-flash-page
if the user screen is bigger than 740px then the front page is: flash-page

Can I do this using the Omega theme setting? Maybe with Delta and Context?

The responsiveness of Omega uses CSS3 Media Queries, which are totally client side.  The other thing to think about is that with true responsive design, the viewport of the client can change while viewing a single page, and the page should adapt.  For example, you can load a page in Chrome, and resize the browser window, and go through the narrow/normal/wide changes and see how responsive your site is.

My suggestion is to make your front page so you employ Progressive Enhancement and not Graceful Degredation.  Design the page so that it works well for users without Flash or Javascript, and make it responsive.  Then, when the page loads, have some JS that checks the browser width, and then use SWFObject to add in the Flash content using the dynamic method.  Depedning on your situation, you may want to add in some min-width and/or display: none on the Flash <div> in the narrow/normal/wide sheets to handle viewport changes.


Override a template for only one route I want override the region default template. I did that with a hook theme from my module.
I want override the region custom template but only for the front page. How can I do that?

You need to implement hook_theme_suggestions_HOOK_alter() in your theme.
For siderbar_first region it would look like follows:

/**
 * Implements hook_theme_suggestions_HOOK_alter().
 */
function THEMENAME_theme_suggestions_region_alter(&$suggestions, $vars) {
  if ($vars['elements']['#region'] == 'sidebar_first' && Drupal::service('path.matcher')->isFrontPage()) {
    $suggestions[] = 'region__sidebar_first__front';
  }
}

Now region--sidebar-first--front.html.twig can be used for theming sidebar on the front page.


Module that provides Rules action to create node? Is an Action to create a node available in any module? I tried searching but couldn't find it. I was hoping something as basic as a node create action would be available.

In Rules 2.x on Drupal 7, there is a "Create entity" action built-in to the Rules module itself.  You can use this action to create a node (Content), which is one type of entity.


How to print out search results I created a custom searchpage.tpl.php to print out search form and search results using the following code:

<?php
print drupal_get_form('search_form');
?>

<div class="search-result <?php print $search_zebra; ?>">

    <a href="<?php print $url; ?>"><?php print $title; ?>

    <?php if ($snippet) : ?>

<?php print $snippet; ?>

    <?php endif; ?>

It shows the search form correctly and when I search a phrase, URL changes to http://domain.com/search/node/phrase
But it doesn't show the search results, How can I make it work please?

Here's the solution:

<div class="searchblock">
<?php
print drupal_get_form('search_form');
?>
</div>

<?php
$keys = arg(2);
print search_data($keys, $type = 'node');
?>
</div>


Set multiple domain for one language I am running a d6 website with i18n and I have multiple domain on it working very fine. Now I want to add another domain but for an existing language so what is the best solution for that.

In fact, this additionnal domain is for the mobile version of the website and because menus depends on language domain selection, I cant' get my menus using the mobile domain but the default domain, that's why I want to add another language but I can't :)

Maybe there is a simpler solution?

Thanks

I would rewrite second language domain to the "primary" one in settings.php
Something like

if ($_SERVER['HTTP_HOST'] == 'newlang.example.com') {
  $_SERVER['HTTP_HOST'] = 'lang.example.com';
}


Uninstalled fb module, but page still pings fb connect for every pageload I uninstalled the fb module and all its submodules from my site and deleted /sites/all/modules/fb folder completely. But for every pageload, the site still calls for these files:

http://connect.facebook.net/en_US/all.js
and a few others.

I want them removed as these slow down my pages completely. I have nothing other than a facebook like button on my homepage, and this was added with sexybookmarks. Any help?

It was added by the facebook share button added by sexybookmarks, Disabling that removed the files as well.


What is the difference between normal filter and contextual filter in views? I am using Drupal 7.34. I have used Views module many time but I don't know difference between normal filter and contextual filter. So can you tell me What is the difference between normal filter and contextual filter in Views?

In simplified language to understand.

Normal Filter: Normal filter takes the fixed data from the available data. For example, you have created a views with Content: Title which will show all the title of nodes available on the site. But if you provide the Filter: Content type(Articles), then it will show only the Node title of Articles. Hence here filter, filters all data and gives only data which belong to Articles.  So this is the Normal filter.

Contextual Filter: Now, Sometimes, you do not have the fixed filter value, suppose, Logged-in-user, value available in URL, Author name of currently loaded page. So, this kind of filter values are dynamic and keep changing, so Contextual filter provides the way to solve this. To visualize this you can see the following UI image of contextual filter. Which has mainly two section.

1. WHEN THE FILTER VALUE IS NOT AVAILABLE

2. WHEN THE FILTER VALUE IS AVAILABLE OR DEFAULT IS PROVIDED.

Now, in the first option WHEN THE FILTER VALUE IS NOT AVAILABLE itself defines what is Contextual filter is- So, Contextual filter SAYS to you,
"I can fetch value from following listed areas(as you can see in image), you select from  where shall I fetch. And I will take it as Filter value."

Example to understand Contextual filter:
Now your site has the Taxonomy terms- BMW, AUDI, HONDA.
So, in fixed value filter you can take only one value. But, what you will do when that value is keep on changing based on browsing.

So, suppose, I select contextual filter and select Taxonomy term ID from URL So, if URL will have BMW is will take BMW as filter, If URL will have AUDI it will take AUDI as filter value. So, filter value keep on changing here, hence Contextual filter provides the way for this.


How to compare before and after state in whatever_submit($form, &$form_state) In a custom module, I have a form allowing some Create/Update/Delete data in a specific table of the database.
In the submit part of the code, I'd like to compare 'before' state (what was displayed to the user) to 'after' state (what he has actually entered) in order to properly update the database: create what has been added, update what has been changed and delete what has been removed.
How can I do that?
By the way, the site is running Drupal 6.37.

First of all: You should migrate to Drupal 7 or 8. Drupal 6 is no longer supported as of Feb 24th, 2016.
If migration is not possible, perform security updates. The latest version of Drupal 6 is 6.38 released on 24 February 2016. Have you also heard about the Drupal 6 LTS initiative? I highly recommend reading the details https://www.drupal.org/project/d6lts, https://github.com/d6lts/drupal.

Answering your question, the simplest thing would be to pass the object with the data in the form:

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

$form['some_field'] = array(
  '#default_value' => $my_object->some_field,
  '#type' => 'textfield',
);

Then in the submit handler you can compare values:

if ($form_state['values']['my_object']->some_field != $form_state['values']['some_field']) {
  // Value of some_field has changed!
}


Checking if personal contact form exists I am using a custom user-profile.tpl and I want to add a 'contact user' link to the viewed users personal contact page.

How can I check that the user in question has a contact page enabled? Is there a variable I can look at, or maybe a db query that can be run?

I am not using tabs on the user profile page.

Thanks,
Paul.

This is taken from contact.module:

function _contact_personal_tab_access($account) {
  global $user;

***snip***

  // If the requested user has disabled their contact form, or this preference
  // has not yet been saved, do not allow users to contact them.
  if (empty($account->data['contact'])) {
    return FALSE;
  }

***snip***

  return user_access('access user contact forms');
}

You should be able to see in the user object whether or not they have they are allowing people to contact them. This will also be empty if they don't have a contact form.


How do I find the hooks used by this module? How can I find out what hooks are available in the Entity Clone module? I want to modify the entity after it is cloned to change its author and workflow state.

As @Kevin says, modules should have a modulename.api.php file with examples that implement hooks that the module provides.

When this file is not available you can search for the code that creates a hook in Drupal.

Drupal 8

Look for following functions of the ModuleHandlerInterface, usually implemented by the ModuleHandler class:

invokeAll
alter

Using grep it's easy; just go to the module's root directory and execute:

 grep '\->invokeAll(\|\->alter(' * -r

This command looks for the strings ->invokeAll (creates regular hooks) and ->alter (creates alter hooks).

For example, if you use this grep command with core's module User you get:

src/Entity/User.php:    \Drupal::moduleHandler()->alter('user_format_name', $name, $this);
user.module:  \Drupal::moduleHandler()->invokeAll('user_login', array($account));
user.module:    \Drupal::moduleHandler()->invokeAll('user_cancel', array($edit, $account, $method));
user.module:  \Drupal::moduleHandler()->alter('user_cancel_methods', $methods);
user.module:  \Drupal::moduleHandler()->invokeAll('user_logout', array($user));

So, this module creates the following hooks:

hook_user_format_name_alter
hook_user_login
hook_user_logout
hook_user_cancel
hook_user_cancel_methods_alter

Drupal 7

Same procedure, but in this case you have to look for the functions module_invoke_all() and drupal_alter().

grep 'module_invoke_all\|drupal_alter' * -r

Keep in mind that this method is not 100% reliable, as some modules use their own hook creation implementation (I've seen this in Drupal 7 mainly), but it's a good starting point if the said modulename.api.php file is missing.

Entity Clone

Unfortunately Entity Clone doesn't create any hook, and the command yields no results.

invoke

There are certain hooks that are only invoked in a particular module, see ModuleHandler::invoke and module_invoke. As they only affects certain modules they are less used than regular ones (they are some kind of internal use hooks).


How to implement admin verification for selected user profile fields? After the user fills the registration form, if the profile is appropriate, the administrator user approves it, and the profile goes live; if it is not appropriate, the administrator user will reject it, but the user still has the chance to proceed with changing the picture and content until it is appropriate. The administrator user will then review for the second time to be sure everything is fine, and the profile will go live.

How can I achieve this?

Step 1: Create a designated role

Create a role like (say) "Member", and use this role within Drupal's Permission system to disallow access to anything on your website for users who do not (yet) have access to this "Member" role. Make sure that for profiles that did not go live yet, you do not grant access to this role.

Step 2: Activate user accounts after registration

When a new registration request arrives, check if it satisfies some minimal requirements to have the account's status be changed to "active" (you don't want to do so for e.g. spammers).

If the request does satisfy your requirements, the administrator just grants the Member role (and is finished with this registration request review).

But if it doesn't satisfy your requirements yet, then the administrator should NOT (repeat NOT) grant the designated role from Step 1. To allow the admin to indicate "I reject", use the Flag module so that the admin can flag such user. Since flags are entities (fieldable), you could also add a (text?) field to have the admin add some kind of "reject reasons". Such flagging could then result in sending an eMail to the registered (not approved yet) user to ask for appropriate changes by the registered user.

Step 3: Wait for the user to apply account updates

After the user (who does not yet have the "Member" role applied new updates to relevant profile fields, send an appropriate eMail to the administrator to request a new profile review. To do so, use the Rules module with a custom rule that looks similar to this one (in Rules export format):

{ "rules_notify_admin_about_selected_profile_updates" : {
    "LABEL" : "Notify admin about selected profile updates",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "user_update" : [] },
    "IF" : [
      { "entity_is_of_type" : { "entity" : [ "site:current-user" ], "type" : "user" } },
      { "NOT user_has_role" : {
          "account" : [ "site:current-user" ],
          "roles" : { "value" : { "4" : "4" } }
        }
      },
      { "data_is" : { "data" : [ "account:uid" ], "value" : [ "site:current-user:uid" ] } },
      { "NOT data_is" : {
          "data" : [ "account-unchanged:field-to-be-approved" ],
          "value" : [ "account:field-to-be-approved" ]
        }
      }
    ],
    "DO" : [
      { "drupal_message" : { "message" : "Thanks for updating your account, the site administrator will soon review your updates." } },
      { "mail" : {
          "to" : [ "site:mail" ],
          "subject" : "Updated profile needs your review",
          "message" : "Please review the updates to the profile of user [account:name], located at [account:url].",
          "language" : [ "" ]
        }
      }
    ]
  }
}

Some more details about the magic in the above rule (use the Rules UI to import it in your own site, after you applied relevant changes like the field name):

Rules Event: After updating an account
Rules Conditions:

An entity of type "user" is updated.
The account being updated is from the currently logged in user.
The user does NOT have the role with ID=4 (which is assumed to match the Member role, adapt this ID to fit your needs).
The actual profile field is "some" field you want to monitor / review / approve. In this case I used a field with machine name field_to_be_approved (adapt to fit your own needs, and add similar conditions if you want to check other fields also).

Rules Actions:

Show an informational message to the user who performed these updates (though only if all Rules Conditions are satisfied).
Send an appropriate eMail to the site admin (adapt the content of it to fit your needs).

Step 4:

You may want to add an extra Rules Action in the previous step to unflag the user again. So that the administrator can fag the user again if after updating the profile the administrator still rejects (by repeating from Step 2). However I recommend to NOT add such extra step, so that the administrator can still see the "reject reason" (from Step 2). And if a 2nd reject is needed, all it takes for the admin is to (a) unflag the user and (b) right away flags the user again, but now possibly with a new reject reason. True, an extra click for the administrator, but the advantage is that the prior reject reason (if used) did not automatically get deleted.

At the point where the updates are OK, just have your admin grant access to this role for any registered user as soon as "the profile goes live". A possible way to further automate this is to create another rule which automagically grants the Member role after the admin "unflags" the user (= removes the flag set in Step 2). If you wonder how to do so, use this link ...

Bonus:

The above approach, with some minor variations, could also be used to catch users who after their account got verified, update their profiles in a way that would not have been allowed when they first registered.


How to use the Rules module for assigning a role during user registration based on a select field option? I need to assign a role to user based on select field at the time of registration.

I have added a field in user registration form (ex: school checkbox) . When user click on school I need to assign a school role to user . otherwise default user role assign by drupal. For this I tried to create role but its not working.

{ "rules_user_reg" : {
    "LABEL" : "user reg",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "user_insert" : [] },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "account" ], "field" : "field_selector" } }
    ],
    "DO" : [
      { "data_set" : { "data" : [ "account:roles" ], "value" : { "value" : { "6" : "6" } } } }
    ]
  }
}

You need to add a Rules Condition (after the one you already have) to check the value of field_selector.

With that your Rules Action should work. Though you also may want to add the Conditional Rules module to implement the "otherwise" part of your question.


Create a view of all nodes that have the same value for a specified field as the current node So I have an event, which has a field called 'field_location'. I want to create a view on the event page where all other events are listed with the same location. In this case location is a node reference to a node (with content type 'location').

How can I dynamically filter all my event nodes on 'location value of the current event'?
I tried this with contextual filters but here it only checks the field you use, in this case 'field_location', with the content id of the url.

I already tried this but without success.

I get zero results.

Use Page manager and panels and add the view as a content pane. Then, pass the node's field's value as an argument to the pane(s) on the panel and you should be good to go.


regex works in PHP fiddle but not in Drupal I am having a problem getting some regex to work in Drupal. The below regex works fine:

<?php
 $test = "1111~~test1<>2222~~test2<>3333~~test3<>44444~~test4<>11112~~test5";
 $regex = '/~~(.*?)(<>|$)/';
 $matches = array();
 preg_match_all($regex,$test,$matches);
 $test = implode(', ', $matches[1]);
 print_r($test);
?>

But when I try to use this to parse the contents of $items[0]["#markup"] in my field file it does not work, even though the content of that field are the same (look at it through print_r). This code works inside the tpl file, but as soon as I replace $test with $items[0]["#markup"] it stops working, does anyone know why this could happen?

EDIT: I think part of the issue is that regex in Drupal may not work with <> tags?

Thanks

Yep, the issue was I couldn't use the <> symbols. Have to use &lt and &gt instead.


How to send an email to an author on a specific date using date field specified in a node? In my content I have one date field which is entered by the author, who fills that as future estimate date like  tomorrow or after 1 month. Depending on that estimated date, on that day mail should trigger.

Example: my date field is "weaning date" which the author will fill at as after one month on that day should trigger a mail.

You might use the Rules Scheduler module (included with Rules) for this. The following tutorial explains a case similar to yours: http://www.webwash.net/tutorials/how-send-follow-emails-using-rules-scheduler-drupal-7

In short, you would need to:

create a "send email" component that sends an email with a user as
parameter
create a rule triggered when a node of your content type is
modified
set the action for that rule to an "scheduled component
evaluation" that uses the "send email" component you created.
in the "scheduled evaluation date" of the action you need to press the "switch to data selection" button, and then to select the date field of your node from the dropdown menu.

Note that the scheduled component evaluation is triggered by cron. You need to make sure that cron is configured correctly in your site.

Hope that helps,


Display a certain page in a view Here is what I'm trying to do is display a certain page in a view instead of all of the basic pages.
How would I go about doing that?

If you want to change what is shown on the site front page you can do that under Configure > System > Site information.
Enter node/[number] into the Default front page field (replace the [number] with the node ID of the content you want to appear on the front page).

If you want to change Content Views to show only a particular node add the Filter Content: Nid with the Operator set to Is equal to and enter your node ID number in the Value field.
This will show only the one node information on that Views.


Panes' Title translation I need to translate the Label of the panes in a page. For example, Title and Body are not translated in my pages.

Note: I do not mean the content of panes! I only mean their label! Which is generally called TITLE.

Sounds like i18n_panels would be overkill. You can do it like this:

/**
 * Preprocess panels panes to translate their title.
 */
function MY_THEME_preprocess_panels_pane(&$variables) {
  $pane_config = $variables['pane']->configuration;
  if (!empty($pane_config['override_title'])) {
    // Translate pane title via t().
    $variables['title'] = t($pane_config['override_title_text']);
  }
}

Or, if appropriate, just:

/**
 * Preprocess panels panes to translate their title.
 */
function MY_MODULE_preprocess_panels_pane(&$variables) {
  $variables['title'] = t($variables['title']);
}

The first will process the title only if defined in the pane settings as a title override. The second will translate the title regardless of whether it's the override title or original title from elsewhere.

Tested under Drupal 7, the same or similar approach would probably work for Drupal 8.


Views: Display Total number of products in commerce kickstart shopping cart I'm using menu badges to display the total number of products in the commerce kickstart shopping cart. However I cannot simple use aggregation to count the total number or products using line item ID because I need to multiply it by the quantity, and add it to the total.
Since the shopping cart already displays the total number of items, I though it would have been easy to do some reverse engineering but I couldn't find it.

In menu badges module check line no 335 code

/**
 * Drupal Commcerce cart items count callback.
 * @param array $arguments
 */
function menu_badges_commerce_cart_item_count() {
  global $user;

  if (module_exists('commerce_cart') && $order = commerce_cart_order_load($user->uid)) {
    // Count the number of product line items on the order.
    $wrapper = entity_metadata_wrapper('commerce_order', $order);
    $quantity = commerce_line_items_quantity($wrapper->commerce_line_items, commerce_product_line_item_types());
    if ($quantity > 0) {
      return $quantity;
    }
  }
  return NULL;
}

You can get total quantity using below code also...

  global $user;
  $order = commerce_cart_order_load($user->uid);
  $wrapper = entity_metadata_wrapper('commerce_order', $order);
  $quantity_total = 0;
  foreach ($wrapper->commerce_line_items as $delta => $line_item_wrapper) {
    $quantity = $line_item_wrapper->quantity->value();
    $quantity_total = $quantity_total + $quantity;
  }

Commerce modules does not provide view handler for Quantity Total.. If you are interested you can create one and share it with community.. Other wise you can use views php module to achieve same...


How to put a Slider widget into the Better Exposed Filters for Ubercart price and other product features? How to put a Slider widget into the Better exposed filters and product search result view in Drupal 7 for Ubercart price and other product features?

I have developed an ecommerce shop, and need to a add slider widget to search products.

Jquery UI and most of its widgets are embedded with D7 core, in misc/ui folder. First add these lines to your theme template file (sites/all/themes/YOUR_THEME/template.php) :

/**
 * Implements template_preprocess_views_view().
 */
function YOUR_THEME_preprocess_views_view(&$vars) {//replace YOUR_THEME by your theme name
  $view = $vars['view'];
  switch($view->name) {
    case 'YOUR_VIEW' : //replace YOUR_VIEW by your view name

      drupal_add_library('system','ui.slider');
      drupal_add_css('/misc/ui/jquery.ui.slider.css');
      break;
  }
}

Don't forget to clear cache.

Your filter must be compatible with is between, lower, greater operators. This is fine for  numeric fields. In the filter setup, set it as exposed and choose "is between" operator.

Last, in views advanced settings, in the BEF setup screen, select Jquery ui slider for your filter and adjust other settings like range at convenience.

EDIT

To answer your comments, don't edit Bartik or other core files.
You can easily create a subtheme as following :

Create the folder: /sites/all/themes/vassia
Create the file /sites/all/themes/vassia/vassia.info
put this code in vassia.info

name = vassia
description = my first subtheme
core = 7.x
base theme = bartik

stylesheets[all][] = css/vassia.css
stylesheets[all][] = css/colors.css

regions[header] = Header
regions[help] = Help
regions[page_top] = Page top
regions[page_bottom] = Page bottom
regions[highlighted] = Highlighted

regions[featured] = Featured
regions[content] = Content
regions[sidebar_first] = Sidebar first
regions[sidebar_second] = Sidebar second

regions[triptych_first] = Triptych first
regions[triptych_middle] = Triptych middle
regions[triptych_last] = Triptych last

regions[footer_firstcolumn] = Footer first column
regions[footer_secondcolumn] = Footer second column
regions[footer_thirdcolumn] = Footer third column
regions[footer_fourthcolumn] = Footer fourth column
regions[footer] = Footer

settings[shortcut_module_link] = 0

Create a file named: /sites/all/themes/vassia/css/vassia.css for your future css custom
If you need colors features, copy the file /themes/bartik/css/colors.css to /sites/all/themes/vassia/css/colors.css and copy the folder and its contents /themes/bartik/color/ to /sites/all/themes/vassia/color/
Go to the the Administration > Appearance page to enable your new subtheme called Vassia

Everything is very well explained in Creating a subtheme DO page. Now the slider part

Create a file /sites/all/themes/vassia/template.php
Write exactly this code in your template.php file :

<?php
/**
 * Implements template_preprocess_views_view().
 */
function vassia_preprocess_views_view(&$vars) {
  $view = $vars['view'];
  switch($view->name) {
    case 'productviewwithsliders' :

      drupal_add_library('system','ui.slider');
      drupal_add_css('/misc/ui/jquery.ui.slider.css');
      break;
  }
}

Double check the view name. Clear all caches

Enjoy