What tables should or could be migrated to InnoDB, and which should remain MyISAM?

You should convert all data to InnoDB to prevent table locking issues. However, here are somethings to think about:
FULLTEXT Indexing
At present, only MyISAM supports FULLTEXT indexing. FULLTEXT indexing for InnoDB is currently in the works for MySQL 5.6 but is not production-ready. If you have any Drupal tables that have FULLTEXT indexes, they cannot be converted to InnoDB at this time.
UPDATE on FULLTEXT Indexing
MySQL 5.6 is now GA (out for Production Use). Please try out FULLTEXT indexing in InnoDB.
To locate those tables that have a FULLTEXT index, run this query:
SELECT table_schema,table_name
FROM information_schema.statistics
WHERE index_type='FULLTEXT';

If no rows come back, convert all InnoDB tables to your heart's content. I wrote an earlier post on how to convert all MyISAM tables to InnoDB using only mysql.
MySQL Replication
If you have a read-heavy environment, reads can go faster in MyISAM if you do the following:

Setup Master/Slave Replication
Create one or more Read Slaves under the Master
Add --skip-innodb in /etc/my.cnf on all Slaves (converts tables to MyISAM when loading data into the Slave)
Change the row format of all MyISAM tables on every Slave to FIXED by this command: ALTER TABLE tblname ROW_FORMAT=FIXED;
I posted something on this in the DBA StackExchange
The book MySQL Database Design and Tuning recommends using ROW_FORMAT=FIXED on pages 72,73. This will internally convert all VARCHAR fields to CHAR. It will make the MyISAM table larger, but executed SELECTs against it will be much faster. I can personally attest to this. I once had a table that was 1.9GB. I changed the format with ALTER TABLE tblname ROW_FORMAT=FIXED. The table ended up 3.7GB. The speed of the SELECTs against it was 20-25% faster without improving or changing anything else.

The only headache with this is making your application aware of separate read slaves.
EPILOGUE
If you are looking at other benefits each storage engine has, check the DBA StackExchange:

Apr 14, 2011 : What are the main differences between InnoDB and MyISAM?
Sep 20, 2011 : Best of MyISAM and InnoDB
May 02, 2012 : Which mysql storage engine to choose?
May 03, 2012 : Which is faster, InnoDB or MyISAM?


How to update a field, after a view page is visited?

I end up use the hook hook_views_post_render() to update field value.


Recommended way to clone functionality to create a site in Drupal 8

If you want to just extract specific functionality, you need Features.

If you just want to clone an entire site, first you need to export the site config with drush. Then, you will need to wipe all UUIDs from config export files using a script, here is an example:

#!/bin/bash
FILES=/path/to/your-site/config/*
for f in $FILES
do
  echo "Processing $f file..."
  sed -i '' '/^uuid:/d' $f
done

From here, you can install a brand new Drupal 8 site, and then drop the config in and do a drush cmi to overwrite the entire config state to the one you exported.

I've used this method a few times to clone entire sites. You don't need to copy the database, in fact I would strongly advise against this.

If you wanted to make an install profile, you could do that too, and one route to doing that is to put your feature modules in a profile, include them as dependencies in the profile info file, and optionally add an installer script to configure the site a little further (default content?). But yeah, you will have to dive in a bit here.


Migrating site from MariaDB to MS SQL 2012

I recommend giving this tool a try. I have used it in the past (to do MSSQL -> MySQL) to setup a datasource for a legacy migration. In your case, you don't need a migration, you just need the db to be in MSSQL format. This is a great litmus test that might save you hours and hours of time.

https://dbconvert.com/mysql/mssql/

It's reasonably priced and worth a shot. If it works fine, you'll move right along.


How to contextual filter a view by a field value?

Create a block view of Show: content, in contextual filter add Country.

Add this to your view contextual filter:

  global $user; // gets current logged in user object

  if (isset($user->field_user_address[LANGUAGE_NONE][0]['country'])) {
    $user_country = $user->field_user_address[LANGUAGE_NONE][0]['country'];
    return $user_country;
  }


I'd recommend you do this via a form alter.  But that aside, the reason your code doesn't work is that you're not doing your comparison correctly.

if ($element['#attributes']['id'] = 'edit-profile-carer-field-profile-active-und') {

Should be:

if ($element['#attributes']['id'] == 'edit-profile-carer-field-profile-active-und') {

And you're also not setting the attribute correctly.  So the final function should be:

function mytheme_checkbox($variables) {
  $element = $variables ['element'];
  $element ['#attributes']['type'] = 'checkbox';
  element_set_attributes($element, array('id', 'name', '#return_value' => 'value'));

  // Unchecked checkbox has #value of integer 0.
  if (!empty($element ['#checked'])) {
    $element ['#attributes']['checked'] = 'checked';
  }

  //*******Added 3 lines below*******
  if ($element['#attributes']['id'] == 'edit-profile-carer-field-profile-active-und') {
      $element['#attributes']['data-toggle'] = 'toggle';
  }

  _form_set_class($element, array('form-checkbox'));

  return '<input' . drupal_attributes($element ['#attributes']) . ' />';
}


Banned IP address is still able to access the site

Turns out my host has me on a load balancer so the IP was masked by the load balancer. I had to look at the values inside the $_SERVER['HTTP_X_FORWARDED_FOR'] variable instead of $_SERVER['REMOTE_ADDR']

See more info here too: https://www.drupal.org/project/smart_ip/issues/1820048


How do I show/hide elements on a page using jquery?

the easiest way of adding custom javascript-snippets is to create a custom.js file in your themefolder and declare it in your theme.info file like scripts[] = custom.js. Add all your snippets there.

In your JS file you can hide the elements.
If you have multiple checkboxes create an array and hide them with a for each loop.

example

// create array with stuff you want to hide
    checkboxes = [
        '#checkbox1',
        '#checkbox2',
    ];

// Hide arrays
    for (i = 0; i < checkboxes.length; i++) {
        jQuery(checkboxes[i]).hide();
    }


Commerce cart form alter to do an availability check

I'm not sure what you're asking about quantity for, so I'm going to set that question aside and answer the broader question of confirming availability before purchase. In Drupal Commerce, the product pricing system serves a two-fold purpose:

Determine the price of a product for the current user.
Determine if the product is no longer purchasable.

While #1 is the most common use case, #2 even has some core representation: if you add a product to your cart and then disable that product as an administrator, the product will be removed from your cart thanks to a default product pricing rule that unsets the price of disabled products. We'll make this process more explicit in the next version of Drupal Commerce, but right now you should understand that if the unit price of a product line item is "unset" or set to a NULL (empty) value, the product will not be considered purchasable.

This will result in one of two behaviors:

For a product in the cart, it will be removed.
For an Add to Cart form, the Add to cart button will be changed to Product not available.

So, in your case, I'd just add a product pricing rule that performed the availability check. If the product is not available, the Add to Cart form will not allow the product to be purchased. If it was already in the cart, it would be removed, so you might use a separate rule to remove unavailable products from the cart and display a message informing the customer what happened. If they were on a checkout page, it would be user friendly to also send them back to the cart page.

Since I don't know how you're checking availability, I'll just add that if you can't do what you need through Rules directly, you can just whip up a simple custom condition to perform the check for ya. There should be plenty of examples in our code and elsewhere.


Yes it is possible to achieve this, You have to use views along with Scrollable Content

It provides a scrolling functionality for your content. Scrollable Content will give you a nice content slider preview of your site's nodes, and provides some display options.

  The basic use is via blocks page, you'll find a block called
  "Scrollable Content" and if you want more control & you know how to
  use Views, you should use the Views style for Scrollable Content.

or you can check Scrollable Views , I'm using this in my website, but it no longer supported.


Get only some fields with EntityFieldQuery?

Great question!

EntityFieldQuery  is truly good stuff,  but if you really want to get serious, you have to override the class in a custom module and add whatever behavior you need done in there.

I don't know your exact intentions, but I have referred myself to this article on the subject in the past.  Credits to Neil Hastings for this well written write-up.

Look for code examples a bit into the article for nice examples of overiding.

Hope that helps, happy coding!


PDOException: SQLSTATE[42S02]: Base table or view not found: 1146 Table

This error happened to me before, I don't really know why but the only solution that I can really tell you (and it worked for me) is to get some Database backup that you may have saved (from a past date) and export the schemas from the tables cambodia_ohchrProduction and revision_cambodia_ohchrProduction into your actual site .

Remember just the schemas of those 2 tables.

And that should work!


Which is the equivalent of php drupal format_interval for javascript?

Drupal doesn't implement a JS version of format_interval(); this is a rough (minimally tested) port:

Drupal.formatInterval = function(interval, granularity, langcode) {
  granularity = typeof granularity !== 'undefined' ? granularity : 2;
  langcode = typeof langcode !== 'undefined' ? langcode : null;

  var units = {
    '1 year|@count years': 31536000,
    '1 month|@count months': 2592000,
    '1 week|@count weeks': 604800,
    '1 day|@count days': 86400,
    '1 hour|@count hours': 3600,
    '1 min|@count min': 60,
    '1 sec|@count sec': 1
  },
  output = '';

  for (var key in units) {
    var keys = key.split('|');
    var value = units[key];
    if (interval >= value) {
      output += (output.length ? ' ' : '') + Drupal.formatPlural(Math.floor(interval / value), keys[0], keys[1], {}, { langcode: langcode });
      interval %= value;
      granularity--;
    }

    if (granularity == 0) {
      break;
    }
  }

  return output.length ? output : Drupal.t('0 sec', {}, { langcode: langcode });
}

Some random results using the above (they seem to match up to the PHP function as expected):

3643       => 1 hour 43 sec
92900      => 1 day 1 hour
2592000    => 1 month
9331200    => 3 months 2 weeks
297605232  => 9 years 5 months


How to get a field's value for all nodes in a content type?

In your case, you can probably simply query the field data table, with a condition on the entity type and bundle.

In any case, something like:

$field_name = 'FIELD_NAME';
$result = db_select("field_data_{$field_name}", 'f')
  ->fields('f', array('entity_id', "{$field_name}_value"))
  ->condition('entity_type', 'node')
  ->condition('bundle', 'article')
  ->condition('deleted', 0)
  ->range(0,10)
  ->execute();

foreach ($result as $row) {
  // drupal_set_message($row->field_name_value); // example
  drupal_set_message('<pre>'.print_r($row,1).'</pre>');
}

As an aside you might want to join on the node table to only select published content, but that's the gist of it.


Select entity to display using drop down list

Checkout the Entity reference module.

  Provides a field type that can reference arbitrary entities.


Filtering part of a multi-value field in a specific view

In order to have full power over the filtering and sort order of the field inside each item, the best solution appears to be a sub-view using the views_field_view module.

https://drupal.org/project/views_field_view

Create a view that only shows the desired field (without a page display)
Add a contextual filter for the entity ID to be displayed
Add this to the parent view, setting the contextual filter to the entity ID of the current item.


How to use owl carousel in custom module?

Assuming you've an array, you can print the array items one by one in wrapper
 tag, and apply Own Carousel to wrapper
 tag (check owl-demo class in example below). To do this in Drupal, you can process your array in your module to create HTML, and apply JS using drupal_add_js(). To print HTML you can either create a custom block and show on page or create custom page.

Implementing in Drupal with custom module:

function _owl_carousel_demo() {
  $array = array('User 1', 'User 2', 'User 3', 'User 4', 'User 5', 'User 6', 'User 7');
  $output = '
';
  foreach ($array as $value) {
    $output .= '

' . $value . '

';
  }
  $output .= '
';
  $output .= '

    Previous
    Next
    Autoplay
    Stop

';

  drupal_add_css('http://owlgraphic.com/owlcarousel/owl-carousel/owl.carousel.css', 'external');
  drupal_add_js('http://owlgraphic.com/owlcarousel/owl-carousel/owl.carousel.js', 'external');
  drupal_add_js('jQuery(document).ready(function() {
      var owl = jQuery("#owl-demo");
      owl.owlCarousel({
        items : 4,
      });
    });', 'inline');

  return $output;
}

Below example shows complete HTML:

    <link href="http://owlgraphic.com/owlcarousel/owl-carousel/owl.carousel.css" rel="stylesheet">
    <link href="http://owlgraphic.com/owlcarousel/owl-carousel/owl.theme.css" rel="stylesheet">

    <?php $array = array('User 1', 'User 2', 'User 3', 'User 4', 'User 5', 'User 6', 'User 7'); ?>

              <?php foreach ($array as $value) : ?>

<?php echo $value; ?>

              <?php endforeach; ?>

              Previous
              Next
              Autoplay
              Stop


How to render a field of a taxonomy term inside a view template?

This can be done entirely from within the Drupal UI.
If you already have access to the taxonomy term in the view, you can add the term entity directly.
This is what the core taxonomy term pages view does.
To see for yourself, go to /admin/structure/views/view/taxonomy_term on a standard Drupal 8/9 installation.
In the header, you will find Global rendered entity: Taxonomy term. If you click this to open up the settings, you will see that Drupal is loading the term based on the argument {{ raw_arguments.tid }}, which is provided by the Contextual Filter Content: Has term ID. (Check the settings there as well.)
For your own block, I would use this same technique.  You say you want to render the image, not necessarily the whole taxonomy term.  To do that, I would create a new View Mode for the term that only has the image and whatever else you want to display.
You can create a View Mode for a taxonomy term by going to the "Manage Display" page for the relevant taxonomy vocabulary.
Then, in Views, in the header where you are rendering the term entity, you can set the view mode to your new custom view mode.


Get error when displaying a token in a header view

I think you can do it without PHP code. Just enter "Subastes de !1".


Drupal Commerce or Ubercart to sell subscription for user (not for sell product)?

If you want to create a site like learning site. I think you can do this by using Course module.

  Create Drupal e-learning courses with any number of requirements for
  completion.

  There's a slideshow from Drupaldelphia and a video as well.


How to display (automatically in a field) all media that references this node?

Use the Views Reference Field module

When you've created your view, go to your node strcuture and create a field type using the module above. On node edit you then can select your banana view. This way your view is wrapped inside the same markup just like any other field of your node.


Alter a form's values on submission but before validate?

hook_form_alter() (or hook_form_FORM_ID_alter()) can be used to populate any field before rendering.


Create template suggestion for item-list.html.twig

I think it's better to use hook__theme_suggestions_HOOK_alter:

Something like this:

 /**
 * Implements hook__theme_suggestions_HOOK_alter().
 */
function MYTHEME_theme_suggestions_item_list_alter(&$suggestions, $variables) {
  $suggestions[] = 'item_list__' . str_replace('-','_',$variables["attributes"]["id"]);
}

Just make sure that in your suggestions name you use _ instead of -, otherwise you will get suggestions in the debug, but Drupal won't use it.


How to remove a stylesheet provided by a contrib module?

I think using hook_css_alter() in a custom module/theme would be the easiest solution:

function MYMODULE_css_alter(&$css) {
  // Get the path to the module
  $path = drupal_get_path('module', 'field_group');

  // Remove the unneeded files from the css array
  unset($css[$path . '/field_group.css']);
  unset($css[$path . '/field_group.field_ui.css']);
}

There are also other CSS files in the Field Group module:

horizontal-tabs/horizontal-tabs.css
multipage/multipage.css

In case you're look to remove absolutely all the CSS that Field Group introduces.


I don't think feeds supports that out of the box, but there's a patch for it that is reported to work.


node has term - show all parents of this term

Although you're looking for a Views solution, if you were to do it custom, e.g with hook_block_info you could use taxonomy_get_parents

Just mentioning in case others looking for that.


view inside a view with different arguments

I can't immediately think of a simple solution to this problem, but I also don't have VFV installed anywhere, so I can't play around with it at the moment.

What I would probably have done, is created a ctools content type, called both of the views, and manually rendered through a specific template afterwards. This solution however is non-trivial, so perhaps you will need to search for a different one.

See What are Ctools plugin (content type, access, etc), and how does one create them? for info on implementing ctools content types.

Example of adding a specific template on top: Correct way to render a modules output through a template?


What is the best way to add the latest version of jQuery to a theme?

In my opinion the best solution is to replace drupal jQuery with the latest jQuery only on the pages where you really need it. If you go on with newest jQuery many of drupal out of the box functionality will be broken.

You can remove native jquery like in the code snippet below only on certain pages that meet your conditions:

function MYTHEME_preprocess_page(&$variables, $arg, $delta) {
  if(YOUR CONDITION HERE) {
    $scripts = drupal_add_js();
    unset($scripts['core']['PATH TO DRUPAL JQUERY']);
    $variables['scripts'] = drupal_get_js('header', $scripts);
  }
}

to add your newest jquery file you can use drupal_add_js('path to yor newest jquery') function.


Using Drush without local copy of Drupal, only calling site aliases - No site aliases found

If your Drush 9 alias file is remoteproject.site.yml, and it has keys like live:, then your alias should be @remoteproject.live.

If you have multiple remote sites, do not put them in the same .yml file in Drush 9. Make one file per site, e.g. remotesite1.site.yml, remotesite2.site.yml and so on.

Use ./vendor/bin/drush sa to see the list of aliases found by Drush.


This is a common issue in the Drush queue on drupal.org and the consensus is that its related to your version of PHP that runs in client mode versus the version running on your web server, ex. http://drupal.org/node/1402120 or http://drupal.org/node/436968. Of course, some of these were related to PHP 5 vs PHP 4 issues and you're just one version behind on the client but it may help to alias your php version as explained here:

echo 'export PATH="$HOME/packages/bin:$PATH"' > .bash_profile
mkdir -p packages/bin
ln -s /usr/local/php5/bin/php packages/bin/php

Patrick Kenny is right though that this parse error won't affect your upgrade in the end.


How to redirect to user organic group on login

Since you are using code to do this you should be able to use og_get_groups_by_user to return that information. This will return all groups of either the active user or the $account object that you pass to the function.

You can also use Rules to do this without code pretty easily. There is a rule export on this page to help get started if you want to go that way.

Just to add: the place you are looking for the og group should be under og_membership I think, not og_user_nodes but that's off the top of my head :)


How to remove unwanted div from view rendered block?

Is the view empty? AFAIK that's the div where the view results should be (may somebody correct me if I'm wrong).

And here's some info in general about what this class is all about: https://www.drupal.org/node/2573529


Commerce Pricing Rules Not Applying During Checkout

The problem was the Rules 2.8 regression resolved by Commerce 1.11.


How to export custom entity using Features?

Follow https://www.drupal.org/node/1021526 for detailed instructions.


How to output multiple files url entities on twig?

You can try to loop over the field items:

{% for item in node.field_upload_file %}
  Download File
{% endfor %}


How do I optimize a Views "execute_count_query"?

As long as you know the query you want use in its place, you can override the count query for a view fairly easily. There are probably other places to do it but I found hook_views_pre_execute() to work pretty well:

function MYMODULE_views_pre_execute($view) {
  if ($view->name == 'view_name' && $view->current_display == 'page') {
    $new_count_query = db_select('some_table', 't')
      ->fields('t', array('id'))
      ->condition('some_field', 'some_condition');

    $view->build_info['count_query'] = $new_count_query;
  }
}

Views will convert the above query into a COUNT(*) at some point further down the line.


here is an example of pulling all the terms in a vocabulary

$vid = taxonomy_vocabulary_machine_name_load("catalog")->vid;
//print($vid) . PHP_EOL; prints the vocab ID
$terms = taxonomy_get_tree($vid);
//print($terms) . PHP_EOL; prints "Array" if a vocab was grabbed
foreach ($terms as $term) {
   print($term->name) . PHP_EOL;
}


I guess hook_form_alter is not the right place to set attributes. But I may be wrong. What surely works is to set attributes in a preprocess function.

The following snippet adds the form ID as CSS class to every form. You could easily wrap some if-request around this to only fire on certain forms checking for $variables['element']['#form_id'].

/**
 * Implements hook_preprocess_HOOK().
 */
function MYTHEME_preprocess_form(&$variables) {

  // Add form ID as class to form attributes.
  $variables['attributes']['class'][] = 'form';
  $variables['attributes']['class'][] = 'form-' . str_replace('_', '-', $variables['element']['#form_id']);
}


I'm pretty sure the values stored using the date attribute are unaltered and just passed on in an array. So the question would be if the user submits the date for UTC or his/her timezone. I would say the latter ;-)

I'm no expert on date settings and timezones, but had seen this question before on stackoverflow, so taking that into account I assume you can do this:

global $user;
$datefields = $form_state['values']['submitted_date'];
$submittedDate = "{$datefields['year']}-{$datefields['month']}-{$datefields['day']}";
$timezone = $user->timezone;
$newdate = new DateTime($submittedDate, new DateTimeZone($timezone));
$unixts = $newdate->getTimestamp();

This would require the user to have set his/her timezone accurately in the account settings.


How can you display document file sizes next to a media link button?

function HOOK_preprocess_file_link(&$variables) {
  if (isset($variables['file'])) {
    $variables['fileLinkDisplay'] = [
      'fileSize' => $variables['file']
        ->getSize(),
      'fileSizeFormatted' => format_size($variables['file']
        ->getSize()),
    ];
  }
}

{{ fileLinkDisplay.fileSize }}and {{ fileLinkDisplay.fileSizeFormatted }} will be available in your template.

PS: if it works then you can more filter to restrict to the content type and field you want applied for.

Additionally, there is a module that show the size https://www.drupal.org/project/field_formatter_file_size

  Field Formatter File Size is a field formatter to display the file
  size.


How can I print a block (the language switcher) without the block-related classes?

Digging locale_block_view() out of locale.module:

/**
 * Implements hook_block_view().
 *
 * Displays a language switcher. Only show if we have at least two languages.
 */
function locale_block_view($type) {
  if (drupal_multilingual()) {
    $path = drupal_is_front_page() ? '<front>' : $_GET['q'];
    $links = language_negotiation_get_switch_links($type, $path);

    if (isset($links->links)) {
      drupal_add_css(drupal_get_path('module', 'locale') . '/locale.css');
      $class = "language-switcher-{$links->provider}";
      $variables = array('links' => $links->links, 'attributes' => array('class' => array($class)));
      $block['content'] = theme('links__locale_block', $variables);
      $block['subject'] = t('Languages');
      return $block;
    }
  }
}

shows that it is "just" theming up some links.  So, you have a couple options here that may work depending on what exact divs/CSS you want/don't want:

Override theme_links() to use "links__local_block" and wrap it in some divs that you can apply CSS to.
Stuff all the guts above in a custom module's block_view() so you can override its block CSS.
Add different or additional classes to the $variables[class'] array,
Include, or override in your theme, a different locale.css file,
Override the block.tpl.php for this specific block, eg, block--locale.tpl.php (see: http://drupal.org/node/1089656) (copy it out of .../modules/block/block.tpl.php and into your theme and change the classes)


How to set default role as 'Member' in drupal 7?

Use Auto Assign Role module to set a default role at the time of user registration.

You can also use registration_role module to fulfill your requirement.


hide field based on its value or value of another hidden field

You can give a try to this module: https://www.drupal.org/project/ffc


Is it possible to implement date field as one select list?

I would recommend replacing the date field with text box and add a date pop to allow certain dates. This could be easily done by hook_form_alter in your custom module. See below:

    /**
     * Implements hook_form_alter().
     */
    function yourmodule_form_alter(&$form, $form_state, $form_id) {
      switch($form_id) {
        case 'your_form_id':
          $form['yourfield']['#type'] = 'date_popup';
          $form['yourfield']['#date_format'] = 'd/m/Y';
          $form['yourfield']['#datepicker_options'] = array('minDate' => '-15D', 'maxDate' => '-1D');
          $form['yourfield']['#readonly'] = TRUE;
          break;
      }
    }

You will need the Date  module enabled before you can use this.
Let me know how you go..


How do I make custom entity create new revision by default?

Normally the default value is stored in bundle configurations. If you have no bundles then override getNewRevisionDefault() of your content entity form:

class MyEntityForm extends ContentEntityForm {

  protected function getNewRevisionDefault() {
    return TRUE;
  }

}

This class should already exist when you've generated the entity with Drush/Console. Check in the entity annotations that the class is used as form handler.


Is it possible to combine two different Template.php functions?

You can do all of this inside the views_pre_render

function mytheme_views_pre_render(&$view) {

  if ($view->name == 'my_view_name' && $view->current_display == 'block_1') {
    if ($node = menu_get_object()) { // gets current page node object
      $field_name_val = $node->field_name[LANGUAGE_NONE][0]['value']; // get field value
      if ($field_name_val == 'option 1') {
        // your empty view code conditional goes here
        // if($view->result...
      }
    }
  }

}

You can find out the current_display name look here


It's impossible to troubleshoot this remotely but there are a couple of things you can try to get connected to your source DB.

In your group's shared_configuration.source config you can manually add a database key with the same DB setting array properties that the migration module also looks for. For example:

shared_configuration:
 source:
   key: database_key
    database:
      driver: mysql
      username: user
      password: pass
      ...

Use the migrate update module to template out an initial working migration config rather than manually add your source DB. For example, run: drush migrate:upgrade --legacy-db-key database_key ....


How to programmatically get the NID of the current node

Assuming your code is running for a node page, the methods I see used most often in core/contrib modules are either using menu_get_object() or arg():

if ($node = menu_get_object()) {
  // Get the nid
  $nid = $node->nid;
}

or

if (arg(0) == 'node' && is_numeric(arg(1))) {
  // Get the nid
  $nid = arg(1);

  // Load the node if you need to
  $node = node_load($nid);
}

I personally prefer the first method (even though assignment in condition isn't considered a good idea by some people), but both are perfectly valid.


You can trigger Ajax in custom javascript. See How to Trigger Existing, Non-Form Ajax from JavaScript Event
In your case an Ajax dialog:
var ajaxSettings = {
  url: '/node/1',
  dialogType: 'modal',
  dialog: { width: 400 },
};
var myAjaxObject = Drupal.ajax(ajaxSettings);
myAjaxObject.execute();


How to get nodes that do not belong to a particular user role

Nodes are only associated with author's nids (not user roles)

Thus you should do a query first to get the userids that match your selected user roles.  Then use that array to filter out nodes with authors that belong to those user ids.


How does the #submit property works with #ajax?

I don't think its good idea to handle form submission using the submit_form function in case of AJAX form. All the form submission logic should be handled in AJAX callback only.
https://drupalabc.xyz/question/how-handle-form-submission-using-ajax-drupal-8

The following link has a running example of AJAX form submission in Drupal 8. I hope this helps.
Thanks.


Calling a module function name in Ajax URL

You have to create own endpoint and call post on it. For example create menu element using hook_menu:

$items['my-module-ajax-endpoint'] = array(
   'page callback' => 'my_module_ajax_callback',
   'delivery callback' => 'ajax_deliver',
   'access arguments' => array('access content'),
   'type' => MENU_CALLBACK,
);

And now post to it.


try this in the form

$custom_table = _table_maps();

$form['some_information'] = array(
  '#markup' => $custom_table,
  '#prefix' => '
',
  '#suffix' => '
',
);


How can I allow users to receive e-mails whenever I update my blog in Drupal 7?

This can be acquired easily. I can give you some steps to follow.

There are actually at least 2 ways to achieve that

A. Using Triggers (core module)

First activate the core module Triggers. This will provide you basic triggers (in your case UPDATE trigger) and actions to run when condition is met.
Go to Admin > Configuration > Actions then CREATE AN ADVANCED ACTION, then select: Send e-mail. In the recipient field you need to select a proper token provided by simplenews module to match all the registered users. (make sure you also have Token module installed)
Go to Admin > Structure > Triggers, then Node tab. Choose the third: TRIGGER: AFTER SAVING UPDATED CONTENT.

If you need more control then implement the hook

function YOURMODULE_trigger_info_alter(&$triggers) {
 //Here dpm($triggers) to see where is your update trigger and do the changes.
}
?>

B. Using Rules (contrib module)
Basic the same thing. If you get stuck follow these steps on a similar issue
on this blog:
http://adellefrank.com/blog/how-to-email-notifications-comments-drupal7


Display entity as options_select multi-select

The options_select widget will automatically be multi-select if the cardinality of the field is multiple. Make sure your field is created as such, e.g.

use Drupal\Core\Field\FieldStorageDefinitionInterface;

...

$fields['foo'] = BaseFieldDefinition::create('entity_reference')
  ...
  ->setCardinality(FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED)
  ->setDisplayOptions('form', [
    'type' => 'options_select',
    'weight' => 0,
    'settings' => [],
  ])
  ...

Incidentally, options_select has no settings, so you can provide an empty array instead of the autocomplete settings you're currently using.


Mark a location on a map (Google Maps/OpenLayers) on a node creation or edit page - but with which module?

I had a good experience with Geolocation Field.

I used this module on dealing website to show location of store. It lets you mark location via node creation/edition form and have display formatter to rendering the address as PNG or Google map.

It was simple and good enough.


A better option might be to use valid_email_address() to keep it all Drupal friendly :)

  Verifies the syntax of the given e-mail address.

  See RFC 5322 for details.

Example:

if (valid_email_address($email) != TRUE) {
  $errors[] = 'Please enter valid email';
}


Which version of drush? https://github.com/drush-ops/drush#drush-versions has a nice table, but in short you need the master branch from github if you want to work with Drupal 8.


Toolbar to insert HTML tags while editing content

After asking on #drupal on irc.freenode.org, I was looking for the BUEditor module that does just that, specifically looking at its native support for HTML tags:

Screenshot (using BBCode)


The array returned from hook_menu() is cached, and each implementation of hook_menu() is only invoked when the cache is cleared, which what happens, for example, when a module is disabled/enabled.

If the users are redirected to a different node depending on the currently set language, then the code should be similar to the following one.

function mymodule_menu() {
  $item['mymodule_path'] = array(
    'title' => 'Contact Us',
    'page callback' => 'mymodule_redirect',
    'access callback' => TRUE,
    'menu_name' => 'main-menu',
    'type' => MENU_NORMAL_ITEM,
  );

  return $items;
}

function mymodule_redirect() {
  global $language;

  switch ($language->language) {
    case 'en':
      $goto = 'node/285';
      break;

    case 'pl':
      $goto = 'node/286';
      break;

    // ...
  }

  if (isset($goto)) {
    drupal_goto($goto);
  }
}

The alternative would be:

Create a link through the user interface (admin/structure/menu/manage/main-menu/add)

Use the following code to alter where the link takes

function mymodule_menu_link_alter(&$item) {
  if ($item['module'] == 'menu' && $item['link_title'] == t('Contact us')) {
    $item['options']['alter'] = TRUE;
  }
}

function mymodule_translated_menu_link_alter(&$item, $map) {
  global $language;

  if ($item['module'] == 'menu' && $item['link_title'] == t('Contact us')) {
    switch ($language->language) {
      case 'pl':
        $item['link_path'] = 'node/286';
        break;

      // ...
    }
  }
}

The first hook is necessary, or hook_translated_menu_link_alter() is not invoked.

The module could also programmatically add the link to the main menu. In this case, the code I would implement is similar to the following one.

function mymodule_enable() {
  $item = array(
    'link_path' => 'node/285',
    'link_title' => t('Contact us'),
    'menu_name' => 'main-menu',
    'mlid' => 0,
    'plid' => 0,
    'module' => 'mymodule',
  );

  menu_link_save($item);
}

function mymodule_menu_link_alter(&$item) {
  if ($item['module'] == 'mymodule' && $item['link_title'] == t('Contact us')) {
    $item['options']['alter'] = TRUE;
  }
}

function mymodule_translated_menu_link_alter(&$item, $map) {
  global $language;

  if ($item['module'] == 'mymodule' && $item['link_title'] == t('Contact us')) {
    switch ($language->language) {
      case 'pl':
        $item['link_path'] = 'node/286';
        break;

      // ...
    }
  }
}


You need to add a new field to the view, and choose the "Global" filter from the available drop down.

Then choose the "Global: View result counter" type:

That wiill give you a counter as a field which you can put into whichever column in the table is appropriate for what you need.


Commerce Kickstart 2 Collection - Displaying too much information

I was able to finally fix this. I fixed this issue by going into Content Types, and just adjusted the Manage Display setting under Product List.


Is there a module that saves the node while you are creating it?

Looks like you need the Autosave module. Here is an excerpt from its project page:

The Autosave module automatically saves a snapshot of your content type form using AJAX. If the user's browser or machine dies while editing a node; the edits will be presented to the user the next time they return to the node. The user may toggle back and forth between the last saved version and the version with the edits that were lost and select which of these they would like to continue with.
How often a form is autosaved as well as which content types to enable autosave for are admin configurable.


How do I override /theme/custom twig in my module to render input fields?

Found the answer after some intensive searching and looking at Drupal From API: Create a twig file for the theme, I called it custom-input.html.twig and place it in your custom_module templates folder. Then you tell Drupal about it using hook_theme() function:

function custom_module_theme($existing, $type, $theme, $path) {
  return array(
    'custom_input' => array(
      'render element' => 'element',
    ),
  );
}

Lastly, in the buildForm function you say what theme will render the element like below:

public function buildForm(array $form, FormStateInterface $form_state) {

  $form['name'] = array(
    '#type' => 'textfield',
    '#title' => $this->t('Name'),
    '#title_display' => 'invisible',
    '#required' => TRUE,
    '#theme' => 'custom_input'
  );

  $form['#theme'] = 'custom_form';

  return $form;
}

This will tell Drupal to render the form input elements using the custom twig file you created.


How to create a catalog site with views and taxonomy?

Have a look at either of these modules, both have an official D7 version (quotes included are from their project pages):

Taxonomy Menu Block

  Taxonomy Menu Block allows you to make blocks containing unordered lists that represent the structure of your vocabularies, creating a menu out of your taxonomies (without using Drupal's menu system).

  Taxonomy Menu Block combines the idea of Taxonomy menu with the workings of Menu block:

  Make multiple menus per vocabulary.
  "Split" the taxonomy into different menus.
  This allows, for example, the creation of one menu with only the top items (parents) of a vocabulary and another menu with only the sub-items (children).
  Make a menu out of a specific branch of your vocabulary only.
  Follow the active trail, also for nodes coupled to a term with a term reference field.

  Taxonomy Menu Block also comes with its own theme function and a few hooks (see the .api.php file) that allows you to alter the generated data to your needs.

Taxonomy Block

  This module displays a list of taxonomy terms in a block from a single vocabulary.


Looking for multi step form in Drupal that can also show submissions in Admin

You can use Webform module and Webform steps module to visualize the steps.

The process is as follows:

Create Webform put some fields organized in Fieldsets if you like.
To make new page insert pagebreak

.

If you want more customization you can follow this tutorial for creating your own module for that.


The functionality you're looking for doesn't exist at the moment. I'd describe it as wanting line item field value changes to trigger a refresh of the Add to Cart form and the injected product fields. You can follow this feature request, though I'm not sure it's likely to be addressed soon:

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


It doesn't work without public_html symlink

Solved it!
Thanks to @sonfd for making me think more about the composer installation. Look what I found in there:
"extra": {
  "installer-paths": {
    "public_html": [
      "type:drupal-core"
    ]
  }
},

I changed that from public_html to web and it works. Damn.


How to show kint debug info from a module on a page?

Try to take a look at this site it has a lot if useful information, print variables using kint.

They say that if you want to output in the message area then you shall use, ksm().


ajax pager working depends on if js file is loaded in module .info file

It is the Drupal behavior JS code copied form your blog post.

(function ($) {
  Drupal.behaviors.addCtoolsModalClass = {
    attach: function (context) {
        $('#modalContent .pagination ul li a').addClass('ctools-use-modal');
        $('#modalContent .pagination ul li a').addClass('ctools-modal-imgsearch-modal-style');
    }
  }
})(jQuery);

The most meaningful thing I can find here is the class name ctools-use-modal. Obviously, this class name is used for ctools module. So I search this class name and find below snippet from js/modal.js in ctools module (version 7.x-1.9).

  Drupal.behaviors.ZZCToolsModal = {
    attach: function(context) {

      $('area.ctools-use-modal, a.ctools-use-modal', context).once('ctools-use-modal', function() {
        var $this = $(this);
        $this.click(Drupal.CTools.Modal.clickAjaxLink);

Now we have the full picture.

In your JavaScript code, you want to add a class name which is required for Ctools JavaScript code. AJAX does not work because the Ctools JavaScript code is run before adding the class name, so Drupal.CTools.Modal.clickAjaxLink never bind to the link.

Yu can fix it by manually run the attach behavior again after adding classname.

Solution

(function ($) {
  Drupal.behaviors.addCtoolsModalClass = {
    attach: function (context) {
        $('#modalContent .pagination ul li a', context)
          .addClass('ctools-use-modal')
          .addClass('ctools-modal-imgsearch-modal-style');

        Drupal.behaviors.ZZCToolsModal.attach(context);
    }
  }
})(jQuery);

Note: since all the code inside Drupal.behaviors.addCtoolsModalClass is wrapped with jQuery.fn.once, which means every code inside is only be implemented once if the selector finds the element. So you don't need to worry about binding the same event twice.


We can do it like this...

$form['my_date'] = array(
  '#type' => 'date',
  '#date_format' => 'd-m-y',
  '#default_value' => format_date($primary_start1, 'custom', $format),
  '#date_type' => DATE_DATETIME,
  '#date_timezone' => date_default_timezone(),
  '#date_format' => 'm/d/Y',
  '#size' => 20,
  '#access' => TRUE,
  '#after_build' => array("custom_range_date")
);

using '#after_build' => array("custom_range_date")

function custom_range_date($form_element, &$form_state){
    // We unset the current values
    unset($form_element['year']['#options']);

    // Now we set the range we want
    $max_age = date('Y') - 100; // 100 years ago
    $min_age = date('Y') - 7; // 7 years ago

    // Now we populate the array
    $form_element['year']['#options'] = array();
    foreach (range($max_age, $min_age) as $year){
        $form_element['year']['#options'][$year] = $year;
    }

    // We return our modified element
    return $form_element;
}

SEE: https://www.drupal.org/node/1165138


Change the bulk operations confirmation page

I assume that the entities are nodes, although the code can be easily adapted to any entity.

/**
 * Implements hook_form_alter.
 */
function my_module_form_alter(&$form, $form_state, $form_id) {

  if ($form_id == 'views_form_ADMIN_VIEW_MACHINE_NAME_system_1' && $form_state['step']== 'views_bulk_operations_confirm_form') {
    $items = array();
    $entity_type = 'node';
    $ids = $form_state['selection'];
    $entities = entity_load($entity_type, $ids);
    foreach ($entities as $entity) {
    $data = 'Title: '. $entity->title . '
Created: ' . date('d/m/Y', $entity->created) . '';
    $items[] = array(
    'data' => $data,
    'class' => array('item-class'),
    );
  }
    $title = '
' . t('Nodes List:') . '
';
    $type = 'ul';
    $attributes = array('class' => 'list-class-one list-class-two');
    $list = theme_item_list(array('items' => $items, 'title' => $title, 'type' => $type, 'attributes' => $attributes)); // Create the list.
    $form['description']['#markup'] = $list;
  }
}


Is it possible to automatically delete image files that have been uploaded when a node is not saved?

That would be difficult to accomplish automatically, since as you pointed out, these nodes / profiles are not saved and therefore the data isn't loaded into Drupal 7's file management table. Drupal 7 will automatically delete all files it is tracking in the file management table when the node is deleted.

Another way to approach this then is to try and detect any files in your target folder (ex. 'files/') that do not have a corresponding data entry in the database and then delete those. Here is a script from Caribbean New Media that does just this task (and even cleans up image styles):

  The script will scan through your chosen directory (and
  subdirectories), for every file found, it will endeavour to
  cross-reference that file within your chosen table.
       If the file doesn't exist in the tables, it will delete the original file and all it's generated image style files you have
  defined.

Definitely should be carefully configured and tested in a safe development environment before moving to your production site, but once running correctly, you can set this up in a cron job to at least have it run every few days / week to clean up orphaned uploads.


Is it possible to include a forward slash in a route dynamic property?

I tested this out, and it doesn't work in Drupal 8, unfortunately.

mymodule.test:
  path: '/mymodule/{testparam}'
  defaults:
    _controller: '\Drupal\mymodule\Controller\TestController::build'
    _title: 'Variable Parameter'
  requirements:
    _permission: 'access content'
    testparam: .+

It picks up the route with "/mymodule/hello", but not "/mymodule/hello/world".

There's some more discussion of this here:
Slashes in single route parameter or other ways to handle a menu tail with dynamic number of params

It looks like there's a solution, but it's pretty heavy handed.


Email send action fails: Cron has been running for more than an hour and is most likely stuck

I think that your PHP configuration is not letting cron finish. Turn off poormanscron, then delete your cron entries in your MySQL database:

DELETE FROM `variable` WHERE name = 'cron_semaphore';
DELETE FROM `variable` WHERE name = 'cron_last';

Then go to admin/reports/status and click on your PHP version to see the output of phpinfo(). What is the max execution time? What is the memory limit? You'll want to change those values to higher numbers, then verify that they are indeed different on this page, then run cron manually at admin/reports/status.

To change these 2 values in PHP, create (or edit) php.ini in the webroot of your site and add (or modify):

max_execution_time = 300
memory_limit = 256M

Obviously feel free to try whatever numbers you'd like here. Ideally you don't want to leave the memory limit very high if you don't need to.


Is the AJAX from image fields and multi-line fields breaking my JavaScript?

Would this have something to do with Drupal 8's AJAX updating those
  fields?

Yes, you need to add

Drupal.behaviors

In order for your Drupal JS code to be able to run after AJAX.

  using the functionality of Drupal.behaviors and once(). If used
  properly this will ensure that your code runs both on normal page
  loads and when data is loaded by AJAX (or BigPipe!)

  Any object defined as a property of Drupal.behaviors will get its
  attach() method called when the DOM has loaded both initially and
  after any AJAX calls.

I suggest you read the Javascript API Overview.

Alternatively, If you don't want to use Drupal.behaviors, I believe if you change all the .addEventListener to .on that will also do.


How do I filter by date is null in a View

I do not know the answer, but did a quick Google: https://www.drupal.org/node/2107633
I would recommend you ask the question on the Drupal Stack Exchange site https://drupal.stackexchange.com/ as it is more of a Drupal than a CiviCRM question.


Try putting js code using Drupal Behaviours

(function($, Drupal)
{
  Drupal.behaviors.animation = {
    attach:function()
    {
      if ( $(window).width() > 960) {

      function fadeOutFunc() {
        $('.image-list .bottom').delay(1000).fadeOut(500, function() {
          $('.image-list .bottom').delay(1000).fadeIn(500,fadeOutFunc);
        });
    }

    fadeOutFunc();
    }
  };
}(jQuery, Drupal));


How to check if block is empty in page.html.twig

You could preprocess your template

function mytheme_preprocess_page(&$variables) {
  $block = \Drupal\block\Entity\Block::load('leftblock');
  if ($block) {
    $variables['leftblock'] = \Drupal::entityTypeManager()
      ->getViewBuilder('block')
      ->view($block);
  }
  $block = \Drupal\block\Entity\Block::load('rightblock');
  if ($block) {
    $variables['rightblock'] = \Drupal::entityTypeManager()
      ->getViewBuilder('block')
      ->view($block);
  }
}

Than you can do this in your template

{% if rightblock or leftblock %}

{{ 'Block title'|t }}

{% endif %}

  {{ leftblock }}
  {{ rightblock }}


Passing arguments with special characters

For Drupal 7, use drupal_get_query_parameters().

https://api.drupal.org/api/drupal/includes%21common.inc/function/drupal_get_query_parameters/7.x


Change the page view to a block view and add the block to the nodes in the content region.


Drupal Commerce - (free) Shipping , Pickup option , Order Comment?

Install https://www.drupal.org/project/commerce_flat_rate
Go to "admin/commerce/config/shipping/methods" and create following flat rate services

Pickup at store (0 $)
Free shipping (0 $)
Shipping (x $)

Configure the last 2 flat services (free shipping / shipping) by clicking "configure component"

Free shipping rate -> add condition "Order amount comparison" >= 25 $
Shipping -> add same condition, but check "negate"

Now picking up at store will always show up, the other 2 depending the order amount.

For the textfields, you can put that in the shipping profile for the customer.


Template file not recognized when moved to module theme folder

Try using 'template' => 'subfolder/mycustommodule-example-form'.


As I still ran into a lot of 403 errors, I'll summarize my overall solution (Drupal 8.0.1).
Setup and configuration
Enable all core web services modules (HAL, HTTP Basic Authentication, RESTful Web Services, Serialization). Enable the relevant permissions of RESTful Web Services and for creating the relevant Nodes.
Get a CSRF token
GET http://your-drupal8/rest/session/token
POST to create a new node
POST http://your-drupal8/entity/node?_format=hal+json
Note that the URL for POST seems to be /entity/node rather than /node.
Headers
Authorization: Basic QWRt...
X-CSRF-Token: zCf...

Data
{
"title": [
  { "value": "atest2" }
],
"type": [
  { "target_id": "article" }
],
"_links": {
  "type": { "href": "http://your-drupal8/rest/type/node/article" }
}
}


What happens to URL alias when a node is unpublished?

Nothing happens and nothing should.

An alias only exists on the URL level. It simply aliases "/blog/2018-01-23/my-awesome-article" to "/node/27", does a lookup for what when a request is coming in and that's it. After that, the routing and entity (access) systems are taking over to figure out what to display and who is allowed to see it.

If you unpublished node 27, then it still exists and admins can still access it, using that alias. In theory, it wouldn't even care if node 27 is deleted, it would still de-alias it to "/node/27" and then the routing system would return a 404 page as there is no node 27 anymore. This actually doesn't happen with nodes because there is code that listens on nodes being deleted and deletes aliases pointing to them as well.

It also doesn't matter if you use a manual alias or generated one using pathauto, that only differs while saving the node and telling pathauto if it should generate one dynamically or not.

But that's actually not your question, because what you're really asking is how  google updates its index when you unpublish content. And what you describe is exactly what should happen, eventually google will re-index your content, see that it no longer exists and removes it from its index. There isn't really anything else you can do directly. You could use a sitemap.xml to tell Google index your content more or less frequently but that's about it.


How to avoid missing status for Workflow access module permission just after node creation?

Just had the same problem for me, but for a custom hook_node_access_records().

For me the solution to implement the hook_node_grants(). and clear the cache.

Once you use the hook_node_access_records, you have to implement the hook_node_grants.


How to invoke autodialog module close method in autodialog.js file using ajax_command_invoke

Finally I made it work.

Instead of using asaf module (This module is used to AJAX-ify form submissions) - not aware of this one, just notice it appending its own ajax class. thought that autodialog already made the submit button ajaxified. In combo with autodialog I make my form api submit button ajaxified.

here's my working code

Form submit buttons.

  $form['closed'] = array(
    '#type' => 'submit',
    '#value' => 'Closed',
    '#attributes' => array('class' => array('btn btn-block btn-default btn-sm')),
    '#ajax' => array(
      'callback' => 'ajax_example_submit',
    ),
  );

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => 'Save Changes',
    '#ajax' => array(
      'callback' => 'ajax_example_submit',
    ),
  );

Ajax callback

function ajax_example_submit($form, &$form_state) {
  $commands = array();
  switch($form_state['clicked_button']['#value']) {
    case 'Closed':
      $commands[] = ajax_command_invoke('.autodialog-content', 'dialog', array('close'));
      break;
    case 'Save Changes':
      drupal_set_message('Saved Changes');
      $commands[] = ajax_command_invoke('.autodialog-content', 'dialog', array('close'));
      break;
  }
  return array('#type' => 'ajax', '#commands' => $commands);
}


Drupal won't validate required field when disabled

According to the API docs of _form_builder_handle_input_element disabled fields are ignored, you can try using #access instead.

You can try adding your own handler after that of prepopulate and check if a (valid) value is entered, if not redirect the user or display a message

function MY_MODULE_form_alter(&$form, $form_state, $form_id) {
  $form['#after_build'][] = 'MY_MODULE_prepopulate_after_build';
}

function MY_MODULE_prepopulate_after_build($form, &$form_state) {
  // check #value
  if (empty($form['field_to_set'][0]['#value'])) {
    drupal_set_message ('You altered the URL', 'error');
    drupal_goto ();
  }
  // if #value is set, set #default_value as well
  if (empty($form['field_to_set']['und']['#default_value'])) {
    $form['field_to_set']['und']['#default_value'] = $form['field_to_set']['und']['#value']
  }
  return $form;
}


Check for IE8 in theme_preprocess_page function

No there is no reliable way to detect browsers. Furthermore, you should not check browser compatibility from the server-side.

You have a few alternatives:

In your module or theme, add IE-specific styles (hide the SVG, show an image instead, likewise). This is well covered in the handbook page.
If you do not need to add the stylesheet to every page, then you can add the stylesheet in your preprocess hook (#attached is recommended. See this and this.)
Javascript workaround. Again, checking the user agent is not that easy and fool-proof. You can check SVG compatibility either by using a library available, or just by trying to create an SVG element and see if it work. This and this covers it well.


Subscribe all users to Simplenews Newsletter

Figured it out.

Go to Mysql and output the user_field-data table as a csv. Delete all
the columns except the user emails.
Copy all the user emails to the clipboard.
Go to Admin  People  Simplenews

You will see options to Mass Subscribe.
Paste the emails on the form. Select the newsletter and wait for a
while.

If you have a long email list break it down in 500 or 1000 records at a time or the server may time out.


Generate Rate widget for specific user based on UID

What i understand that you want to display that Current logged in user Content ratings. for that you can use the (Votes) Votes: Current user (True) for filter

and if you want to display all the voted content User-wise than you can Make a relation with (Votes) Votes: User and remove the (Votes) Votes: Current user (True) as the following image.


Arrange formatted fields in Views row using a template

I had a similar issue recently and this is what I did.

Let's say for the sake of argument that we have 6 fields: A to F. I wanted to wrap A-C in a layer eg "col-1" and D-F in a second layer eg "col-2". I overrided the field templates (views-view-fields--field-*.tpl.php) for A, C, D, F as such:

Added a
 element in A, without a matching closing tag
.
Added a
 element in D, without a matching closing tag
.
Added the respective closing tags
 i n C and F.

This may show some error or warning in your IDE, but the rendered HTML should be ok as long as the order of the fields in the views allows it (eg don't re-arrange D to be above C).


Is there a way to determine what is powering the content behind a URL?

You could try looking in the menu_router table, where the path column contains values like node/%/revisions/view. Also, the url_alias table has a source column (to check against the menu_router table) and the alias defining a path like /my-url.

I also use TextWrangler and PHPStorm to inspect my code. You could try to search.


Views Data Export Module hide button when unfiltered

You have a number of options, you can apply a default views filter that is applied on page load through the view settings.

You can also use javascript to test if all the filters are on "All" then hide the button with CSS


I don't think there is separate file for Blog content type. Because for Blog default node.tpl.php is called. If you want to create tpl file for blog, straight away copy file from node.tpl.php and create a tpl like node--blog.tpl.php.

And if you want to create page tpl for blog content type then you can create

page--blog.tpl.php

And you have to add some PHP code in template.php file in THEMENAME_preprocess_page() function

if( !empty($vars['node'])){
    $vars['theme_hook_suggestions'][] = 'page__'. $vars['node']->type;
  }


Include the user history visibility settings in a feature

If you've added a custom visibility option to User accounts. You'll need to figure out a way to export it to code. if they are just Fields then they should show up under export options for Fields when building a feature.

If on the other hand you've created a custom tab of sorts on the User Accounts page and have a bit of code managing some settings there -- you need to inform Drupal of those pieces of custom data.

Features Extras supports exporting visibility settings for blocks, and blocks in general.

  To export a block, install FE Block, edit your block, give it a
  "machine name," export it with Features. You can export block settings
  (region settings, visibility settings, ...) of any block, and the
  content of blocks created with the Block module from Drupal core.

I recommend looking at that module and seeing how they export these settings. If I had to guess I'd say they use the Ctools Export API. There is a drupal handbook page on how to get started exporting configuration for your module.


How to close login-popup after successful login

The user login form is the one returned from user_login(), or user_login_block(). In both the cases, user_login_submit() is the form submission handler that is invoked for the login form.

Adding a form submission handler that is executed after user_login_submit() would be possible to set a Drupal variable.

function mymodule_form_user_login_form(&$form, &$form_state) {
  $form['#submit'][] = 'mymodule_login_submit';
}

function mymodule_login_submit($form, &$form_state) {
  global $user;

  variable_set('mymodule_user_logged_in', (integer) !empty($user));
}

The addon could then periodically ping a URL handled from the module, which would return the value of "mymodule_user_logged_in," and close the window when its value is not 0.
The code I wrote here is not optimized, and it serves only as example of what is possible to do.

To allow to the added form submission handler to be called after the submission handler added by user.module, the weight of the module should be changed to a value that is different from the default module weight, in hook_install() or hook_update_N().

function mymodule_install() {
  db_update('system')
    ->fields(array('weight' => 10))
    ->condition('name', 'mymodule')
    ->execute();
}


How to fetch a single value with an entity metadata wrapper?

Well you could use:

$node = node_load($nid);
$wrapper = entity_metadata_wrapper('node', $node);
$title = $wrapper->title->value();

But if that's literally all you need to get from the node, an EntityMetadataWrapper is overkill in my opinion. Just use:

$node = node_load($nid);
$title = $node->title;


How to create custom field in ubercart 3.x checkout page?

I found the Extra Fields Checkout Pane module.

  This module allows an administrator to define additional (billing and shipping) address fields as well as custom order fields in Ubercart e-commerce suite. These fields will be available during checkout process and in order handling pages.
  This module has been developed and tested with Ubercart 2.6.


You should create a views display of type "Content pane".

Then ideally configure it to take arguments from context, and specify that the view requires a node id (or whatever you actually need). This will make the view much smarter, for example allowing Panels to hide the view from the UI all together when on a non node page.

Then add the new content panes to the page. You should be asked for which node you want to use as the source for the nid. Usually there will only be one, and you can continue without changing any settings.

And your view will now show up.


We added a filter to drop the languages that did not have translations from the language switcher.  Here's the code from that:

/**
 * Implements hook_block_view_BASE_BLOCK_ID_alter().
 */
function mymodule_block_view_language_block_alter(array &$build, BlockPluginInterface $block) {
  $build['#pre_render'][] = '_mymodule_language_block_prerender';
}

FYI - Used pre_render because I was removing links from the [content][[#links] element.


Just merge like:

function mytheme_theme($existing, $type, $theme, $path) {
  $items = array();
    $items['user_register_form'] = array(
    'render element' => 'form',
    'path' => drupal_get_path('theme', 'mytheme') . '/templates',
    'template' => 'user-register-form',
    'preprocess functions' => array(
       'mytheme_preprocess_user_register_form'
    ),
   );
   $items['comment_form'] = array(
    'render element' => 'form',
    ),
   );
 return $items;
}


Editing time for pages in google analytics?

Ok - you want to use Google Analytics custom variables for this and a bit of javascript (though will try and make this as Drupaly as possible). For the timer, you can write javascript/jQuery code to start a timer on the window.load() event and then attach it to the submit button on your particular form. Number of examples of javascript timers, I found this example that looked promising.

Key thing to get this data to your google analytics account is to add a google analytics push event (see documentation above) so your code would look something like this (rough psuedo code)

$(document).ready(function() {

   function StartTimer() { some timer function ... }

   function StopTimer() { some timer stop function ... return $time; }

   startTimer();

   $("#id-for-form-submit-button").click(
       $timeValue = StopTimer();
       _gaq.push(['_setCustomVar',
          1, // This custom var is set to slot #1.  Required parameter.
          'Editor Time', // Category Name. Required Parameter
          $timeValue,  // This value of the custom variable.  Required.
          3  // Sets the scope to page-level.  Optional parameter.
      ]);

});

Finally, you need to attach your javascript to your form (the drupaly part). I use this quick code snippet (from switchbackcms) as a good way to avoid losing the javascript if the user reloads the form:

function hook_form_alter(&$form, $form_state, $form_id){
  if($form_id == 'form_in_question'){
     $form['some_element']['#after_build'] = array('_load_my_javascript);
   }
}

function _load_my_javascript($element){
    drupal_add_js(
      drupal_get_path('module', 'my_module')
        . '/track_editors.js');
return($element);
}


You could in fact develop your own module to do the above - for example, set a value attached to each user account of number of 'drips' left, which is then decremented by each pageview/similar, and then the total is refreshed at the start of the next billing period, for example by using a scheduled task implemented via the cron system.


Features conflicts when field bases are used by other feature

Say you have two Features, and one field that is used in both Features, then you only need to export the field base ONCE.

This is why I generally have a "controller" Feature that contains field bases, update hooks etc, and then for every other Feature I export the field instance, and then add a dependency on my controller feature.

Basically, you are right - you don't need to export the field bases every time, just export them once and then add dependencies.


Using CCK Date with Date Repeat on Calendar

Here is a very recent issue thread that seems to match your problem:

http://drupal.org/node/1014664

The issue is very recent and it looks like a working patch has been rolled into the newest version of the module, so a quick update of the Date module, (specifically the Date-Repeat submodule) should fix you up.


Image Widget Crop

Provides an interface for using the features of the Crop API. Module
is still under heavy development.

Posted by woprrr


How do you change the css of node editing forms?

Arggh -- finally found it.  I'm running a modified version version of Bartik for my site theme, and Seven came along as the admin/overlay theme.  I can put changes into /themes/seven/style.css, and they work.  It all makes sense now, I guess.  Thanks for the pointers.


Use multiple email addresses on contact form

Despite being an old post, I think it warrants an answer for those sites still operating on Drupal 7 or even Drupal 8.  Rather than use the built-in Contact form, I recommend using the Webform module.  Below is a description of how it can be used for a contact form of this nature, with Drupal 7 specific screenshots.

If you setup your contact form using the Webform module, you can setup distinct emails, one for each purpose.  In both cases, the "from" setting can be set to one unique site email address, a preset/predefined email address in the configuration, or one email address from the form itself.


I assume you're using postgres instead of mysql, AFAIK postgres doesn't support REGEXP.

As an alternative you can look at atrium_folders but it has not as many features as filedepot and it needs open atrium.


The answer is :

$user=user_load($uid);
$username=$user->name;


How can I add styles attribute to Global Custom field markup?

Drupal 8 views will strip away any markup it thinks it is dangerous

you have to rely on a custom theme solution here is a general overview of how this can be done

if you don't have a custom theme you have to create one (more info)
Enable Twig debugging (more info)
Inspect your page in browser to find the appropriate templates to override.  In the html comments you will find which .twig template is responsible to output a specific piece of html markup  (More info)
Copy required template into your CUSTOM_THEME/theme folder
Add or modify the markup in the twig template

Alternatively you might want to give https://www.drupal.org/project/viewscss a try which promises to allow viewscss but it does not have a stable release.


How to inculde 3d parrty libraries into your module?

suggestion:

in MyAction.php add:

require_once DRUPAL_ROOT . '/modules/my_project/src/libs/mylibs/src/ClassWhichINeed.php';


How DO I store/retrieve data and display them in templates?

One way to achieve this is using preprocess function. In your theme's '.theme' file, write a preprocess function. Example:
In bartik.theme

function bartik_preprocess_html__node__28(&$vars) {

$nids = \Drupal::entityQuery('node')
        ->condition('type','article','=')
        ->condition('status',1,'=')
        -> execute();
$nodes = \Drupal::entityTypeManager()->getStorage('node')->loadMultiple($nids);
foreach ($nodes as $key => $value) {
$title = $value->title->value;

}
$vars['title'] = $title;

}

(node__28 is any node page where you want to see all results, I made this basic page)

Now in html--node--28.html.twig template, retrieve title of content type = article

{{ title }}


hide the webform after submission in webform 3.0

Do you want to allow users to submit it just once ?
If so have a look at node/123/webform/configure (where 123 is your form node id), there's a "Submission limit" option. If you choose "1" and "ever" then the form will be hidden with the following message: You have already submitted this form. View your previous submissions".

If you want to redirect your user to another page after submission, you can use the redirect option in the settings page.

Does this answer your question ? Can you elaborate it a little more if it doesn't answer it ?


How do you create a make file and minify it for pdf.js?

How do you accomplish this from a Windows machine?

No, you can't run make command in Windows; maybe you want to check cygwin.

  Does it require the web server to be a linux machine?

Final .js file can be placed anywhere, Windows or Linux. You need a Linux machine to create it.

  Does this require SSH'ing into the remote host?

If you want run make command in your server, you need ssh-ing.


Is it bad practice to add markup to title or label fields?

That'll work, but best practice is to theme it. The following answer describes how to theme a custom block: https://drupal.stackexchange.com/a/39270/23063


Find matching fields between content types and create new nodes

You need the below rule to fire when the client's content type is saved.. And all relevant fields must exist in BOTH content types. It will talk your clients answers, feed them through a VBO, get the company NIDs that match and then loop through them to create Partner Details nodes.

First, you need to have Views Bulk Operations (VBO) which will give a new rule action.. "Load a list of entity IDs from a VBO View". In this action, you can specify a VBO view and a list of arguments (taxonomy tids etc.) to send to the view using replacement patterns. The list of returned IDs is what you will use to create your "partner details".
You need to create the VBO view by adding "Bulk operations: Content (Content)" as a field in a new view. The arguments sent from the rules action can be picked up by contextual filters using the "Provide Default: Raw Value from URL" setting. If I remember correctly, the first argument starts with path component 2.
The results of the VBO should be limited to those nodes that match the arguments. Now we have a list in rules that we can use Loop to go over.
Depending on needs, you can just create the new entities and reference the client and company nodes or do a two way reference so that the client and company nodes also reference each partner detail node.

The above is will do the taxonomy fine but for the integers, it's a bit more complicated since the contextual filter must match perfectly. For this, you can use the contextual filter: Global Null (which won't limit the results) and use Views Argument Substitutions to take the value from the contextual filter and use it in your views filters (the regular ones on the left). * *  *!2 * * * (no spaces) if your global: null is the second contextual filter.

This is pretty limited but it could work. If you need it to only be 50-100 employees for example,  on the company content type, have minimum and maximum integer fields and use "greater than" and "less than" filters in VBO view.

You should do quite a lot of testing on the VBO preview to make sure things work as expected. I really believe this is the only way to do this without writing a nasty amount of custom code. Good luck!


In Drupal 7 Commerce, where do you send an order completion confirmation email to administrators or store owners?

I guess this is available in the rules provided by the drupal commerce at (admin/commerce/config/checkout/rules):

admin -> commerce -> config -> checkout -> rules -> "Send an order notification e-mail"

Configuration of recipient email address including the admin address you want the order confirmation sent to can be done at this place.

Also you can check the doc for commerce order mail: https://drupal.org/node/2061215


How to retroactively apply Mollom spam filtering?

Not currently. See http://drupal.org/node/734476 for the feature request in the Mollom issue queue.


Disable caching for custom block for anonymous users

The problem is, you don't render the block in a normal way and Display Suite is obviously not able to retrieve the plugin cache metadata.

Most times it is a better option to include the cache metadata in the render array together with the data it depends on:

public function build() {
  $build = [];
  $request = \Drupal::request();
  $mode = $request->query->get('mode');
  $build['mode'] = [
    '#markup' => t('The query argument is mode=@mode.', ['@mode' => $mode]),
  ];
  $build['#cache']['contexts'][] = 'url.query_args:mode';
  return $build;
}

Then the cache metadata can bubble up, no matter where and how this block content is embedded.


Do you always need to search on multiple terms at the same time? And how do you want to search, via an exposed filter or with query parameters?

In both cases you need to add references to the vocabularies A and B.

If you want to search through an exposed filter, you can add the term name fields (with relation to the references) to the normal filter and just expose them. I'm not sure, but I think there is a way to combine this with global text search.

If you want to work with query parameters you need contextual filters. Just add a term name for both vocabularies and let them match the value of the query parameters. You can specify what results must be shown if the parameter value is 'all' for example.

I don't think you need the or operator because you mentioned you want to match on both terms at the same time. However, if you want to match on multiple combinations you might want to check this module. I haven't tested it myself, but it really saves you some time if it works. The or operator is not native in contextual filters.

Good luck! Contextual filters and references can be a real pain in the ...


One way is to define your own form and add it to a block in the panel.

After that, you save the value to the user account in the form submit handler.

Background:

Form generation summary

Relevant hooks:

hook_block_info ( define form in a block )
hook_block_view ( return $block['content'] = drupal_get_form('my_module_user_notify_form'); )

and some custom functions you'll need.

my_module_user_notify_form ( return form array )
my_module_user_notify_form_submit ( save to user )

If you use something like Profile2, you could also just embed the relevant user profile form in the block. It would then handle the form build and processing for you.


If you set the
"Minimum amount of items" and
"Number of empty items" to the same number the add more won't appear.

Here is a screenshot

Here is the YAML source for basic multiple text field

textfield:
  '#type': textfield
  '#title': textfield
  '#multiple': 5
  '#multiple__min_items': '5'
  '#multiple__empty_items': '5'

Here is the YAML source for multiple custom composite

custom_composite:
  '#type': custom_composite
  '#title': custom_composite
  '#multiple': 5
  '#multiple__min_items': '5'
  '#multiple__empty_items': '5'
  '#multiple__sorting': false
  '#multiple__operations': false
  '#element':
    textfield:
      '#type': textfield
      '#title': textfield
    select:
      '#type': select
      '#options': days
      '#title': select


get the permission must the user have to access to the 'Access denied ' page

The only answer I can think of is to roll this functionality yourself with some coding in a custom module.

You probably want to use Chain Menu Access and the drupal API function user_role_permissions.

You can use the chain menu access api to put a fired-last menu access check that does some comparisons over previous access checks and Roles:

<?php
  chain_menu_access_chain($menu, 'an/existing/path', '_mymodule_new_access_callback_check_permissions_to_roles');
?>

Then use the drupal api user_role_permissions to see what Role has X permission that was failed in a parent-chained access callback. You could store that for example in the users $_SESSION data. Then write a custom 404 page that shows them purchase options.


Image style don't create thumb image and it get error "Division by zero"

It would appear that your image toolkit is not working properly. On the status page (admin/reports/status) are there any errors, etc.?


In Views Use this code in "Rewrite the output of this field"

[title]

You can also set the width and height of the popup window, see the read-me file in Lightbox2  module folder.

hope you will get idea from the above!!


How to limit the number of nodes created using the Feeds module?

You'll also need to clear your caches after setting $conf['feeds_process_limit'] = 50;.

Alternatively, if you are just looking for a quick limiter (during development of a custom importer, for example) this trick worked for me:
Limit number of feed items to import ($conf['feeds_process_limit'] not working) (an active issue in the Feeds issue queue).


Are regions and features automatically created when creating a sub subtheme?

Yes, you will enherit everything unless you modify the page.tpl.php file located in /sites/all/themes/yourtheme/template folder.

The page.tpl.php file contains all block regions. Thus, you should modify this file if you want to add, remove, or move regions.

If you want to resize or theme a region, it's all css. As you will see in page.tpl.php, the regions will have a div class or id.


How to clear form element values after validation error

Have you looked at unsetValue()?

Example usage:

public function validateForm(array &$form, FormStateInterface $form_state) {
  ...
  if (!$authorized) {

    $this->messenger->addError($this->t('An error occurred.'));

    $form_state->unsetValue('name');

   }
 }

From the doc:

  Removes a specific key from the submitted form values.

  @param string|array $key
  Values are stored as a multi-dimensional associative array. If $key is a string, it will use unset($values[$key]). If $key is an array, each element of the array will be used as a nested key. If $key = array('foo', 'bar') it will use unset($values['foo']['bar']).


It is possible to have an action for the condition rules?

Events, conditions and actions are bound together in a Rule. So to match them up you need to define them in your Rule. I am assuming you want to create a Rule programmatically to go along with your hooks?

You can define events, conditions and actions, as you say with hook_rules_event_info(), hook_rules_condition_info() and hook_rules_action_info(), but to create a default Rule, you'll need to use hook_default_rules_configuration(). It is recommended you put the hook implementation in MODULE.rules_defaults.inc to optimize the memory footprint.

For further details on how to use the hook, see Default rules in the Site Building Guide, and look at the default Rules the module provides.

Personally I would recommend that you build your Rule through the UI and featurise, or export it as a Rules string and then import it like so:

function MYMODULE_default_rules_configuration() {
  $items['test_rule'] = entity_import('rules_config', 'EXPORT STRING HERE');
  return $items;
}

That will save you a lot of pain.


you can configure your Solr Server under the following URL:

http://my.drupal-domain.com/admin/config/search/search_api/server/apache_solr/edit


Node theme template override isn't working

Devel got disabled somehow breaking the page when calling dpm.
Re-enabling fixed all.


Use order number instead of order id in Drupal Commerce checkout URLs

Thanks @bob!

Just a bit of background:  I'm dealing with a 3rd party order fulfillment company who provides me with an API to generate orders in their Magento system after orders are created in my Drupal Commerce system.  The 3rd party passes back the order number from the Magento API, which I store as $order->field_vendor_order_number in Drupal Commerce.  Later I actually replace the Drupal Commerce $order->order_number with the custom field I created to temporarily hold the 3rd party's order number. I do this after successfully processing the customer's payment, so unfortunately all the checkout pages leading up to the "thank you" page still have the internal commerce order_id in the url because the order hasn't been created in the 3rd party's system yet, and therefore I don't have the proper order number that I want to show the customer yet.

Here are the rules, actions, and callbacks that send an order to the 3rd party and save the order number they respond with as the new Drupal Commerce order_number:

/**
 * Implements hook_default_rules_configuration().
 */
function example_store_default_rules_configuration() {
  $rules = array();

  /**
   * Add a reaction rule to send the order to 3rd party for fulfillment upon checkout completion.
   */
  $rule = rules_reaction_rule();

  $rule->label = t('Send Order for Fulfillment');
  $rule->tags = array('Example Store');
  $rule->active = TRUE;

  $rule
    ->event('commerce_checkout_complete')
    ->action('example_store_send_order_for_fulfillment', array(
      'commerce_order:select' => 'commerce-order',
    ));

  $rule->weight = 1;

  $rules['example_store_send_order_for_fulfillment_rule'] = $rule;

  /**
   * Add a reaction rule to update the order number to the one assigned by 3rd party fulfillment upon checkout completion.
   */
  $rule = rules_reaction_rule();

  $rule->label = t('Assign Fulfillment Order Number');
  $rule->tags = array('Example Store');
  $rule->active = TRUE;

  $rule
    ->event('commerce_checkout_complete')
    ->action('example_store_assign_fulfillment_order_number', array(
      'commerce_order:select' => 'commerce-order',
    ));

  $rule->weight = 2;

  $rules['example_store_assign_fulfillment_order_number_rule'] = $rule;

  return $rules;
}

/**
 * Implements hook_rules_action_info().
 */
function example_store_rules_action_info() {
  $actions = array();

  $actions['example_store_send_order_for_fulfillment'] = array(
    'label' => t('Send Order for Fulfillment'),
    'parameter' => array(
      'commerce_order' => array(
        'type' => 'commerce_order',
        'label' => t('Order to send for fulfillment'),
      ),
    ),
    'group' => t('Example Store'),
    'callbacks' => array(
      'execute' => 'example_store_send_order_for_fulfillment_callback',
    ),
  );

  $actions['example_store_assign_fulfillment_order_number'] = array(
    'label' => t('Assign Fulfillment Order Number'),
    'parameter' => array(
      'commerce_order' => array(
        'type' => 'commerce_order',
        'label' => t('Order to assign a new fulfillment order number'),
      ),
    ),
    'group' => t('Example Store'),
    'callbacks' => array(
      'execute' => 'example_store_assign_fulfillment_order_number_callback',
    ),
  );

  return $actions;
}

/**
 * Callback for rules action to send the order for fulfillment to 3rd party API and process the response
 * Save the 3rd party order number into a custom field on the order entity
 */
function example_store_send_order_for_fulfillment_callback($order) {
  include_once DRUPAL_ROOT . '/services/ExampleStoreService.php';
  $objExampleStoreService = new ExampleStoreService();
  $arrResponse = $objExampleStoreService->SendOrder($order);

  if ($arrResponse['status'] === 'success') {
    $order->field_vendor_order_number['und'][0]['value'] = $arrResponse['order_number'];
    $order->log = 'Order Number from 3rd party is: '.$order->field_vendor_order_number['und'][0]['value'];
    $order->revision = TRUE;
    commerce_order_save($order);
  }
}

/**
 * Callback for rules action to assign the new order number received from 3rd party fulfillment
 * Take the order number stored in the custom field and actually save it as the order entity's order_number
 */
function example_store_assign_fulfillment_order_number_callback($order) {
  if (isset($order->field_vendor_order_number['und'][0]['value']) && !empty($order->field_vendor_order_number['und'][0]['value'])) {
    $order->order_number = $order->field_vendor_order_number['und'][0]['value'];
    $order->log = 'Order Number '.$order->order_number.' saved.';
    $order->revision = TRUE;
    commerce_order_save($order);
  }
}

However instead of going to the default "Checkout Complete" page, I created a rule that reacts to the checkout_complete event by redirecting to "store/order/[commerce-order:order-number]".  Notice it has a weight of 10, to ensure it's the last thing I want to do when reacting to the checkout_complete event.

{ "rules_redirect_to_custom_checkout_complete_page" : {
    "LABEL" : "Redirect to custom checkout complete page",
    "PLUGIN" : "reaction rule",
    "WEIGHT" : "10",
    "TAGS" : [ "Commerce Checkout", "Example Store" ],
    "REQUIRES" : [ "php", "rules", "commerce_checkout" ],
    "ON" : [ "commerce_checkout_complete" ],
    "DO" : [
      { "redirect" : { "url" : "store\/order\/[commerce-order:order-number]\/" } }
    ]
  }
}

I added a hook_menu entry for this, which accepts the order_number instead of the internal commerce order_id as an url argument:

/**
 * Implements hook_menu().
 */
function example_store_menu() {

  $items['store/order/%'] = array(
    'page callback'   => '_example_store_order_view',
    'page arguments'  => array(2),
    'access callback' => TRUE,
    'type'            => MENU_CALLBACK,
  );

  return $items;
}

/**
 * Custom page callback for store/order/%
 * @param  string $order_number - order number from 3rd party fulfillment api
 * @return array - order as renderable array
 */
function _example_store_order_view($order_number) {
  if (!empty($order_number)) {
    $order = commerce_order_load_by_number($order_number);
  }

  if (!empty($order)) {
    $entity_view = entity_view('commerce_order', array($order->order_id => $order), 'customer', NULL, TRUE);
    return theme('example_store_order_complete_thank_you', array('entity_view' => $entity_view));
  }
  else {
    drupal_set_message(t("No order was found for order number ". $order_number . ". Please check your order number to make sure it is correct."), 'error');
    drupal_goto('store');
  }
}

And a custom hook_theme entry to handle the template for this custom "Order Complete Thank You" page, which mainly just displays the rendered order entity.  If you have any Google Analytics e-commerce tracking code, this is the template in which you'd want to place those scripts. I'm not displaying it in this stripped down example, but I rigged mine up to only render those scripts on the first visit of this page, that was if the customer refreshes the thank you page, Google Analytics won't see duplicate tracking.

/**
 * Implements hook_theme().
 */
function example_store_theme($existing, $type, $theme, $path) {
  $module_path = drupal_get_path('module', 'example_store');
  return array(
    'example_store_order_complete_thank_you' => array(
      'variables' => array(
        'entity_view' => NULL,
      ),
      'template' => 'example-store-order-complete-thank-you',
      'path' => $module_path.'/templates',
    ),
  );
}

Contents of example-store-order-complete-thank-you.tpl.php:

//Render the order entity
print render($entity_view);


How to programmatically use the "between" operator in Drupal Views

I believe you are using hook_views_query_alter. So see the example to add OR in condition. Check out code :

$this->query->add_where(
  $this->options['group'],
    db_or()
      ->condition($field, array(0, 100), 'BETWEEN')
      ->condition($field, array(150, 200), 'BETWEEN')
  );


What do you have the "sort" criteria set to? Also, I find the default Views grid-view to be quite awful. I use the Views Fixed Grid module for any grid views. It will give you better output and greater control in my humble opinion.