How to theme view header Global: Text Area?

It seems the <p> tag is inserted on the Global: Text Area header, but not on the Global: Unfiltered text. In case it is acceptable for you to use this one, it might fix your issue.

(by the way, in version 8 of Views, the <p> tag is not inserted any more for the Global: Text Area header)


How can I prevent 'Error messages' to be shown to anonymous users?

Like @Screenack suggested.

Navigate to /admin/config/development/logging
Set the radio to None
Select Save Configuration

Please note that I recommend keeping the errors on locally and trying to fix them.


Adding the ICUTokenizerFactory to the text fieldtype solves the issue and the search ignores the diacritics.


Adding a taxonomy specific css file to certain pages

If you want to load certain CSS files based on taxonomy, maybe you could name your files according to taxonomy vocabularies. Just build the file name based on the vocabulary of a term.

$file = 'mymodule_taxonomy_' . $vocabulary . '.css';
drupal_add_css(drupal_get_path('module', 'mymodule') . '/' . $file);

If you have a node object you can use taxonomy_node_get_terms() to get the terms for a node and use this code to load a proper CSS file.
Then, with a vocabulary named cars you can name a CSS file mymodule_taxonomy_cars.css. That file can be loaded according to a vocabulary.


Coding a Load and delete Field Collection with Entity API

Please look into this links it will give your answers:

Example: Programmatically create and update field collection with Entity API

How to properly delete a field collection

Delete field content using entity metadata wrapper


You could create the effect you're after with some clever CSS applied to the default Views pager but it doesn't seem you're very proficient at CSS, and there is a way that may help you get further without coding.

Carousel Views Format through an additional module

There are some modules that you can use to change your Views Format to output views results in a way that resembles what you want, basically a carousel navigation for your views results:

jCarousel
Slick Carousel, Slick Views
Flex Slider

Better Pager through an additional module

If you don't think that the carousel solution is good for your case you can change the Pager directly with an additional module.

Pagerer is probably your best choice, but there are others if you want to search on your own and compare. Here is a tutorial about how to use it: How to Create Fancy Pagers in your Drupal Views with Pagerer.

Additional CSS

It's not clear which header and footer you're talking about - the HTML elements? This is CSS related and best solved by using Flexbox or Grid to get the layout with equal column heights but without limiting the column height so you're covered for all content "sizes".


Javascript file in theme does not get loaded

In drupal 8 my theme uses the file main.js. If my theme was called test I would add the file in this order.

File location:

test/js/main.js

In test.info.yml:

libraries:
  - test/global-js
  - test/global-css

In libraries.yml:

global-js:
  js:
    js/main.js: {}
global-css:
  css:
    theme:
      css/styles.css: {}

Remember your spacing in the .yml files (2 spaces).
also read adding stylesheets and javascript to a drupal 8 theme andCreating a drupal 8 sub-theme, or sub-theme of sub-theme

Happy Drupaling


I achieve it by adding brackets in ASCII code.


Need To Update One Entity Through Another

Okay figured it out. I needed to patch the Redhen module I'm using which was causing a Revision ID error. Im using the Relation, Rules Redhen modules together (and of course the Entity API). Here is the export of the Rule that did it:

{ "rules_update_employment_status" : {
"LABEL" : "Update Employment Status",
"PLUGIN" : "reaction rule",
"REQUIRES" : [ "rules", "relation" ],
"ON" : [ "relation_update" ],
"IF" : [
  { "entity_is_of_type" : { "entity" : [ "relation:endpoints:0" ], "type" : "redhen_contact" } },
  { "entity_has_field" : {
      "entity" : [ "relation:endpoints:0" ],
      "field" : "field_employment_status"
    }
  }
],
"DO" : [
  { "relation_rules_fetch_endpoint" : {
      "USING" : {
        "relation" : [ "relation" ],
        "entity_type" : "redhen_contact",
        "number" : "1"
      },
      "PROVIDE" : { "endpoint_fetched" : { "endpoint_fetched" : "Fetched Endpoint" } }
    }
  },
  { "data_set" : {
      "data" : [ "relation:endpoints:0:field-employment-status" ],
      "value" : "20"
    }
  },
  { "drupal_message" : { "message" : "[endpoint-fetched:full-name]\u0027s Employment Availability has been changed to [endpoint-fetched:field-employment-status]." } }
]
  }
}

This let me access whatever fields on the endpoint that I wanted then change them if I needed to.


Sadly that still doesn't work...  The problem is not that php, it calls the website only the first time.  The second time the button is broken.  It does not click, call Drupal or anything.  Also any buttons added to page with ajax do not work either, even though their pre-loaded counterparts work perfectly fine with jquery.


CKeditor not working for users only in forums

This looks like a javascript error. Have you tried installing the jquery_update module and evaluating what javascript libraries or drupal modules making use of Javascript are installed on the website and looking for conflicts between the modules.

What javascript file is producing the error. Using Chrome Developer Tools or Firebug for firefox and looking at the Console will give you the filename.


Render menu item children without being 'expanded'?

I was able to do this by adding a macro for children below the main one in my template.

{% macro menu_links(items, attributes, menu_level) %}
  {% import _self as menus %}
  {% if items %}

      {% for item in items %}
        {%
          set classes = [
            'global-top__utility-item',
            'js-utility-item',
            item.in_active_trail ? 'active-trail',
            item.below ? 'has-submenu'
          ]
        %}

          {% if item.url.options.attributes['data-icon'] is defined and item.url.options.attributes['data-icon'] is not empty %}
            <svg class="icon"><use xlink:href="/themes/custom/pncb/build/img/svg-sprite.svg#{{ item.url.options.attributes['data-icon'] }}"></use></svg>
          {% endif %}

          {{ link(item.title, item.url) }}
          {% if item.below %}
            {{ menus.submenu_links(item.below, attributes, menu_level + 1) }}
          {% endif %}

      {% endfor %}

  {% endif %}
{% endmacro %}

{% macro submenu_links(items, attributes, menu_level) %}
  {% import _self as menus %}

    {% for chunk in items|batch(7) %}

        {% for item in chunk %}

            {{ link(item.title, item.url) }}

        {% endfor %}

    {% endfor %}

{% endmacro %}

I split this out due to scoping, different markup for sub menu, and I needed to use the batch filter. Works great.


How do I order a search query by best match?

An entity query can't have arbitrary expressions added to it. To proceed with your current approach you'll need to execute a raw query against the database.

But to address your actual question, How to create search query in Drupal 8 order by best match, the answer is to use the Search API module:

  This module provides a framework for easily creating searches on any entity known to Drupal, using any kind of search engine. For site administrators, it is a great alternative to other search solutions, since it already incorporates facetting support and the ability to use the Views module for displaying search results, filters, etc. Also, with the Apache Solr integration, a high-performance search engine is available for this module.

In my experience the Solr integration is excellent, but if you don't have a Solr server handy, you can always fall back on the included database backend module. I would imagine that the results you get using search API will be better than any query you can put together yourself in any short amount of time.


Conditional views exposed filters (using Search api views)

There is a slight change in the code.May be this can help you.

(function ($) {
  Drupal.behaviors.cdgi = {
    attach: function(context) {
     $(function () {
      $('#edit-field-level-of-telecommuting-1').click(function() {
        if ($(this).prop("checked")) {
          $('#edit-field-job-region-parents-all').hide();
        } else {
          $('#edit-field-job-region-parents-all').show();
        }
      });
     });
    }
  }
}(jQuery));`

check more info how to include js file


Secondary & Tertiary links next to Parent links

You can achieve this by using the module menu block. This module allows you to display certain levels of a menu considering the selected parent item.


I agree with @mradcliffe, that there is probably no simple way to reuse field widgets for normal form fields. The code of field widgets heavily depend on an underlying entity field.

I think the best solution is to create a mock custom entity. As you obviously don't need to store the result, otherwise you would already use an entity, you can set

"storage" = "Drupal\Core\Entity\ContentEntityNullStorage",

in the entity. Example for this is the core Contact Form, which needs very little code to implement fully customizable forms by reusing the form API for entity forms.


Such definitions can be placed in a local.settings.php file, alongside the generated settings.php.

You'll find an include statement at the bottom of the generated settings.php


Conflict between ajax callback and jQuery UI dialog

a simpler approach might be to include the form in a custom block, and set it's css to match the modal design you want but set the initial block display to none.  Then use an onclick to show the block using whatever transition you want


Is it possible to authenticate against LDAP server without creating a drupal user account

sorry, I guess you just can't do it that way.

everything you do in Drupal is tied to your user, even if said user is anonymous.

Drupal establishes a basic difference between logged and anonymous users, even if you give the latter every permission from the former.

hence an LDAP solution involves creating Drupal users for everyone, or else they don't get to do what registered users do.


Click event not always fireing in Drupal behaviors

See comments below...

      .on('submit', function(e){ // Not correct way of using submit.
                e.preventDefault();
                var $form = $(this); // You have already defined this global variable?

                $(function () { // you dont need to check if the document is ready, thats what behaviours are for.
                    $('#mymodule-form').submit(function () { // Why are you submitting again here?
                        if($(this).valid()) {
                            $submitButton.trigger('submitmyform'); // What are you trying to trigger?
// If the form is already submit, why are you doing anything with the submit button?
                        }
                    });
                });

            });

Try this...

var $form = $("#mymodule-form", context);

$form.submit(function(e){
  e.preventDefault();
    if($(this).valid()) {
       // Do something else...
    }
});

UPDATE

You are probably binding to the form before it exists. Bind the event to the document, and pass the form selector...

$(document).on('submit', '#mymodule-form', function(e){
    // Do something...
});


Is it possible to do a drush sql-sync of only certain tables?

YES
If you know which tables you want to transfer

--tables-list
A comma-separated list of tables to transfer. Optional.

If you know which tables you want to skip

--skip-tables-list
A comma-separated list of tables to exclude completely. Optional.

And here is how I know this:

$ drush help sql-sync
Copy and import source database to target database. Transfers via rsync.

Examples:
 drush sql-sync @prod @dev                 Copy the DB defined in sites/prod to the DB in sites/dev.

Arguments:
 from                                      Name of subdirectory within /sites or a site-alias.
 to                                        Name of subdirectory within /sites or a site-alias.

Options:
 --cache                                   Skip dump if result file exists and is less than "cache" hours old. Optional; default is 24 hours.
 --create-db                               Create a new database before importing the database dump on the target machine.
 --db-su=                            Account to use when creating a new database. Optional.
 --db-su-pw=                         Password for the "db-su" account. Optional.
 --dump-dir                                Directory to store sql dump files in when --source-dump or --target-dump are not used.  Takes precedence over --temp.
 --no-cache                                Do not cache the sql-dump file.
 --no-dump                                 Do not dump the sql database; always use an existing dump file.
 --no-ordered-dump                         Do not pass --ordered-dump to sql-dump.  sql-sync orders the dumpfile by default in order to increase the efficiency of rsync.
 --sanitize                                Obscure email addresses and reset passwords in the user table post-sync. Optional.
   --sanitize-password                     The password to assign to all accounts in the sanitization operation, or "no" to keep passwords unchanged.  Default is "password".
   --sanitize-email                        The pattern for test email addresses in the sanitization operation, or "no" to keep email addresses unchanged.  May contain replacement patterns %uid,
                                           %mail or %name.  Default is "user+%uid@localhost".
   --confirm-sanitizations                 Prompt yes/no after importing the database, but before running the sanitizations
 --skip-tables-key                         A key in the $skip_tables array. @see example.drushrc.php. Optional.
 --skip-tables-list                        A comma-separated list of tables to exclude completely. Optional.
 --source-database                         A key in the $db_url (D6) or $databases (D7+) array which provides the data.
 --source-db-url                           Database specification for source system to dump from.
 --source-dump                             Path to dump file. Optional; default is to create a temporary file.
 --source-remote-host                      Remote machine to run sql-dump file on. Optional; default is local machine.
 --source-remote-port                      Override sql database port number in source-db-url. Optional.
 --structure-tables-key                    A key in the $structure_tables array. @see example.drushrc.php. Optional.
 --structure-tables-list                   A comma-separated list of tables to include for structure, but not data. Optional.
 --tables-key                              A key in the $tables array. Optional.
 --tables-list                             A comma-separated list of tables to transfer. Optional.
 --target-database                         A key in the $db_url (D6) or $databases (D7+) array which shall receive the data.
 --target-db-url
 --target-dump
 --target-remote-host
 --target-remote-port
 --temp                                    Use a temporary file to hold dump files.  Implies --no-cache.


How to fetch submenu items for current page?

You are right it's a pretty common requirement. If you are not afraid of slight performance hit, you may use Menu Block module. It is able to provide you with submenu relative to your current path:

So if you’re only using your theme’s Main menu links feature, you can add and configure a “Main menu (levels 2+)” block. That block would appear once you were on one of the Main menu’s pages and would show the menu tree for the 2nd level (and deeper) of your Main menu and would expand as you traversed down the tree. You can also limit the depth of the menu’s tree (e.g. “Main menu (levels 2-3)”) and/or expand all the child sub-menus (e.g. “Main menu (expanded levels 2+)”).
Pretty simple, eh?

Of course it is a pretty big module, and it puts additional block layout between your menu and your display, so if it is too much of a performance hit, you can try to borrow some of it's code - it's GPL after all.


How do I add a variant programmatically?

You can try this:

I found how to store manually created variants in code for custom pages (e.g. '/node/%node/test')

function MODULE_default_page_manager_pages() {
  // Copy exported page code here.

  $pages['UNIQUE_PAGE_ID_HERE'] = $page;

  return $pages;
}

Putting everthing in a file called 'MODULE.pages_default.inc' in your MODULE's main folder, and link that file with my MODULE.module via

/**
 * Implement hook_ctools_plugin_api().
 *
 * If you do this, CTools will pick up default panels pages in
 * MODULE.pages_default.inc
 */
function MODULE_ctools_plugin_api($module, $api) {
  if ($module == 'page_manager' && $api == 'pages_default') {
    return array('version' => 1);
  }
}

Source: https://www.drupal.org/node/579036


Theme video-embed-iframe.html.twig by content type

That's not easily possible, not directly.

By default a media entity is going to be render cached on its own, that means the same media could be used in two different nodes with a different type and as long as they use the same view mode, it is only going to be built once. While you can get the current node easily on the detail page in preprocess and you could vary the rendered media by path, that will possibly result in a lot of variations and won't really work on views and other pages that display teasers of many nodes.

The easist way to achieve something like this would be to define two different view modes, use one from one node type and the second from the other.


Check Redirect 403 to User Login

  Redirect the HTTP 403 error page to the Drupal /user/login page with
  an optional message


You can try with below Jquery snippet.

(function ($) {
var cboxOptions = {
     width: '95%',
     height: '95%',
     maxWidth: '768px',
     maxHeight: '768px',
}

$('#colorbox').colorbox(cboxOptions);

$(window).resize(function(){
   $.colorbox.resize({
     width: window.innerWidth > parseInt(cboxOptions.maxWidth) ? cboxOptions.maxWidth : cboxOptions.width,
         height: window.innerHeight > parseInt(cboxOptions.maxHeight) ? cboxOptions.maxHeight : cboxOptions.height
   });
});


Reassign $view_mode using entity field passed to hook_entity_view_mode_alter()

I'm not sure exactly what's going on here, but looking at the documentation for hook_view_mode_alter, it looks like you're not resetting the view mode properly. It looks like you need to set it like:

/**
 * Implements hook_entity_view_mode_alter().
 */
function nfl_entity_view_mode_alter(&$view_mode, Drupal\Core\Entity\EntityInterface $entity, $context) {
  // Change the view mode to the value selected via radio button on the form.
  if ($entity->getEntityTypeId() == 'nfl_fact' ) {
    $view_mode = $entity->change_view->value;
  }
}


First put your text format to Plain Text mode and then paste your <iframe> code on the editor, now you switch back to "Full HTML" or "Filtered HTML" mode (for which your text editor is set to display).

Hope this is what you are looking for. Hope this helps. :)


You could use something like Computed Field for this or you can write your own custom module. You could hook into node save using hook_node_presave (since it acts on save and presave) and calculate the other 3 fields that you need to save. Either way should work pretty well. You would just use php date functions to calculate the new dates either way. There are a bunch of examples for computed field online and in their documentation you could use to draw inspiration from.


Features code changes overriding automatically

No, this is how Features work. If your feature is in Default state, code change will cause direct effect on the components (there are some exceptions when clear cache is required). This is actually one of the biggest points and benefits of features, you can easily deploy updated code without any further required action.

Maybe there is a problem with your workflow, you should create you features on you Dev environment (configurations etc), then export them and deploy to Stage/Prod. It is not a good practice to directly change the configuration of components on Stage/Prod environments, you should always do your changes on Dev, then recreate the feature and deploy.


How to add comment form to drupal pages not having node and content type?

Comments needs to be attached to a content. If you want to use built-in comments module, you need to:

Use "simple page" content type to create dummy nodes, or create similar one

it might be wise to strip your dummy content type from everything except title and comments
revoke edit and delete rights, no one should be able to do it

In your module's install file, make sure this content type is enabled and create a dummy node for each of pages you need comments on
Set node's paths to match paths of the pages, so people cannot access them directly
Setup Global Redirect or similar to always redirect from /node/$nid to path
In your module load node and pass it to theme so you could render comments in tpl.php file

That would be about it, if you need more details on any of these points, I guess it'll be worth a separate question.


How to remove a comment based on it's field value?

This code should work for you

function THEME_preprocess_node(&$variables) {
  global $language;
  foreach ($variables['content']['comments']['comments'] as $key => $comment) {
    if ($comment['field_language']['#items'][0]['value'] != $language->language) {
      unset($variables['content']['comments']['comments'][$key]);
    }
  }
}


How to know what is slowing down my drupal site

you can install devel module and enable show queries so you can look at what queries run your website.Find out havy query and try to optimize.


Content Type template override - Dash or Underscore?

If you look at theme_get_suggestions(), there is a comment:

// When we discover templates in @see drupal_find_theme_templates,
// hyphens (-) are converted to underscores (_) before the theme hook
// is registered. We do this because the hyphens used for delimiters
// in hook suggestions cannot be used in the function names of the
// associated preprocess functions. Any page templates designed to be used
// on paths that contain a hyphen are also registered with these hyphens
// converted to underscores so here we must convert any hyphens in path
// arguments to underscores here before fetching theme hook suggestions
// to ensure the templates are appropriately recognized.

If you look at a preprocess, like template_preprocess_node(), you will see things like:

$variables['theme_hook_suggestions'][] = 'node__' . $node->type;

This is using the machine name of the content type directly, which is underscored.

-- is a delimiter between things, underscores are used within a thing.


Create path alias for hook_menu URLS based on node information

For this I would use the pathauto module, which I am assuming you already have installed.

It provides a bunch of hooks to allow you to integrate with pathauto for your own needs.

For documentation, see the API.txt file in the pathauto module (from what I can tell though that file seems a little out of date).

You can look at working examples of its usage to give you an idea how to make your own.
To see these look in the pathauto.pathauto.inc file in the pathauto module.

Here is an example of what you might do (I haven't tested it but it should be close to what you need if it isn't exactly):

This is for the install file:

/**
 * Implements hook_install().
 */
function MODULENAME_install() {
  // Set the default value of the pathauto pattern.
  variable_set('pathauto_subsite_pattern', 'subsite/[node:title]');
}

/**
 * Implements hook_uninstall().
 */
function MODULENAME_uninstall() {
  // Remove the pathauto pattern.
  variable_del('pathauto_subsite_pattern');
}

This is for the module file (note you can move some of this out into an include file if you prefer):

/**
 * The internal path pattern for subsites.
 */
define('MODULENAME_SUBSITE_INTERNAL_PATH', 'subsite/template2/');

/**
 * Implements hook_path_alias_types().
 */
function MODULENAME_path_alias_types() {
  $objects = array();
  $objects[MODULENAME_SUBSITE_INTERNAL_PATH] = t('Subsites');
  return $objects;
}

/**
 * Implements hook_pathauto().
 */
function MODULENAME_pathauto($op) {
  switch ($op) {
    case 'settings':
      $settings = array();
      $settings['module'] = 'MODULENAME';
      $settings['token_type'] = 'node';
      $settings['groupheader'] = t('Subsite paths');
      $settings['patterndescr'] = t('Pattern for subsite');
      $settings['patterndefault'] = 'subsite/[node:title]';
      $settings['batch_update_callback'] = 'MODULENAME_subsite_pathauto_bulk_update_batch_process';
      return (object) $settings;
    default:
      break;
  }
}

/**
 * Batch processing callback; Generate aliases for subsites.
 */
function MODULENAME_subsite_pathauto_bulk_update_batch_process(&$context) {
  if (!isset($context['sandbox']['current'])) {
    $context['sandbox']['count'] = 0;
    $context['sandbox']['current'] = 0;
  }

  $query = db_select('node', 'n');
  $query->leftJoin('url_alias', 'ua', "CONCAT(MODULENAME_SUBSITE_INTERNAL_PATH, n.nid) = ua.source");
  $query->addField('n', 'nid');
  $query->isNull('ua.source');
  $query->condition('n.nid', $context['sandbox']['current'], '>');
  $query->orderBy('n.nid');
  $query->addTag('pathauto_bulk_update');
  $query->addMetaData('entity', 'node');

  // Get the total amount of items to process.
  if (!isset($context['sandbox']['total'])) {
    $context['sandbox']['total'] = $query->countQuery()->execute()->fetchField();

    // If there are no nodes to update, the stop immediately.
    if (!$context['sandbox']['total']) {
      $context['finished'] = 1;
      return;
    }
  }

  $query->range(0, 25);
  $nids = $query->execute()->fetchCol();

  MODULENAME_subsite_update_alias_multiple($nids, 'bulkupdate');
  $context['sandbox']['count'] += count($nids);
  $context['sandbox']['current'] = max($nids);
  $context['message'] = t('Updated subsute alias for node @nid.', array('@nid' => end($nids)));

  if ($context['sandbox']['count'] != $context['sandbox']['total']) {
    $context['finished'] = $context['sandbox']['count'] / $context['sandbox']['total'];
  }
}

/**
 * Update the subsite URL aliases for multiple nodes.
 *
 * @param $nids
 *   An array of node IDs.
 * @param $op
 *   Operation being performed on the nodes ('insert', 'update' or
 *   'bulkupdate').
 * @param $options
 *   An optional array of additional options.
 */
function MODULENAME_subsite_update_alias_multiple(array $nids, $op, array $options = array()) {
  $options += array('message' => FALSE);

  $nodes = node_load_multiple($nids);
  foreach ($nodes as $node) {
    MODULENAME_subsite_update_alias($node, $op, $options);
  }

  if (!empty($options['message'])) {
    drupal_set_message(format_plural(count($nids), 'Updated URL alias for 1 subsite.', 'Updated URL aliases for @count subsites.'));
  }
}

/**
 * Update the sibsite URL aliases for an individual node.
 *
 * @param $node
 *   A node object.
 * @param $op
 *   Operation being performed on the node ('insert', 'update' or 'bulkupdate').
 * @param $options
 *   An optional array of additional options.
 */
function MODULENAME_subsite_update_alias(stdClass $node, $op, array $options = array()) {
  // Skip processing if the subsite has no pattern.
  if (!pathauto_pattern_load_by_entity('subsite')) {
    return;
  }

  module_load_include('inc', 'pathauto');
  pathauto_create_alias('test', $op, MODULENAME_SUBSITE_INTERNAL_PATH . $node->nid, array('node' => $node));
}

/**
 * Implements hook_node_insert().
 */
function MODULENAME_node_insert($node) {
  // Insert subsite alias.
  MODULENAME_subsite_update_alias($node, 'insert');
}

/**
 * Implements hook_node_update().
 */
function MODULENAME_node_update($node) {
  // Update subsite alias.
  MODULENAME_subsite_update_alias($node, 'update');
}

/**
 * Implements hook_node_delete().
 */
function MODULENAME_node_delete($node) {
  // Delete subsite aliases.
  pathauto_path_delete_all(MODULENAME_SUBSITE_INTERNAL_PATH . $node->nid);
}

/**
 * Implements hook_node_operations().
 */
function MODULENAME_node_operations() {
  // This will add an operation to update subsite aliases to the content
  // administration page.
  $operations['MODULENAME_subsite_update_alias'] = array(
    'label' => t('Update subsite URL alias'),
    'callback' => 'MODULENAME_subsite_update_alias_multiple',
    'callback arguments' => array('bulkupdate', array('message' => TRUE)),
  );
  return $operations;
}

This will use a default path alias pattern of subsite/[node:title] but allow you to configure it on the path auto settings page.

It will update the alias when a node is added, edited or deleted.

It will allow bulk updating of path aliases via the bulk update area of the path auto settings pages.

It will allow bulk updating of aliases via the options on the content administration page.

It would be trivial to add a views bulk operations action too.


Is it normal that a site changes to maintenance mode during a module update?

It does look to be normal, yes. Drush's UpdateDBCommands::updateBatch, which is responsible for processing the updates, contains this:

batch_set($batch);

// See updateFinished() for the restore of maint mode.
$this->maintenanceModeOriginalState = \Drupal::service('state')->get('system.maintenance_mode');
\Drupal::service('state')->set('system.maintenance_mode', true);
drush_backend_batch_process();

The code deliberately sets maintenance mode to true before processing the batch, and then restores the original state when it's done.

Running drush help updb lists the following options:

--cache-clear[=CACHE-CLEAR] Clear caches upon completion. [default: "true"]
--entity-updates Run automatic entity schema updates at the end of any update hooks.
--post-updates[=POST-UPDATES] Run post updates after hook_update_n and entity updates. [default: "true"]
--no-cache-clear Negate --cache-clear option.
--no-post-updates Negate --post-updates option.

So there doesn't seem to be an obvious way to disable the behaviour. But if you're updating the database you probably don't want people to be able to access the site at the same time. There's a good explanation for that here.


thats right, consider creating a new entity and relate it through a user reference field, for these types of references, the "references module" is better than the "relations module".


Cardinality Violation during Views contextual filter setup, how to fix this?

Reading the instructions for multiple views contextual filter arguments you get the solution:

  Allow multiple values:
  If selected, users can enter multiple values in
  the form of 1+2+3 (for OR) or 1,2,3 (for AND).

So if you need an OR operator you should return a string of "1+2+3" and if you need an AND operator you should return a string of "1,2,3".

So don't return an array() but a string.


How to add new component type in webform?

I got answer for my question from this link, Hope this will help somebody who have same requirement.
follw this link.


How can I remove unwanted CSS found in the parent theme?

You can override it by adding a blank file with the same name in your theme (or you can add your own contents). Or, you can remove it altogether with libraries exclude: https://www.drupal.org/docs/theming-drupal/adding-stylesheets-css-and-javascript-js-to-a-drupal-theme#override-extend


You can probably add a validation pattern to the email address and block a list of email addresses for submitting the form. Or you need to create a custom module.


How to programmatically display a webform in a block based on user selection

You're very close - the return from hook_block_view() is an array with keys content and optionally subject. Your current code example:

$block['content'] = module_invoke('webform','block_view','client-block-N');

Produces the equivalent of:

$block['content'] = array(
  'subject' => ...,
  'content' => ...,
);

When you put that through drupal_render(), it gets angry (because subject isn't a render array but isn't prefixed by #).

You're probably looking for:

$block = module_invoke('webform','block_view','client-block-N');

Or simply:

return module_invoke('webform','block_view','client-block-N');

(once N is substituted for the node ID of the webform).


I guess the option you need is in the "Filter Criteria" section, in the dropdown next to the "Add" button. If you fold down that menu you will see the "And/Or, Rearrange" option in which you can create sets of conditions.


Get the before and after values of a node field

For new created nodes in hook_node_update you will never get any old values for any $node fields. Use node_load($node->nid) to load the previous instance of the $node and do any comparisons with it. You can also use $node->original to view the commited values to the database.


Table prefixes with db_select() in SimpleTest tests

Executing queries inside SimpleTest tests is not different from executing them in a module. The path.test file contains the following code, and it is executed without errors.

$forum_vid = db_query("SELECT vid FROM {taxonomy_vocabulary} WHERE module = 'forum'")->fetchField();
$tid = db_insert('taxonomy_term_data')
  ->fields(array(
    'name' => $this->randomName(),
    'vid' => $forum_vid,
  ))
  ->execute();


Drupal Views pager shows last page when higher pager value is entered manually instead of page not found

Found a way out!!..
I used theme_pager and global variable $pager_total

Here is the code

/**
 * Implements theme_pager
 */
function theme_pager($variables) {
  global $pager_total;
  if ($_GET['page'] > $pager_total[0]) {
    drupal_not_found();
    exit;
  }
}


How do I troubleshoot a node not appearing in workbench?

Absent the "right way to do it", what I've done is go ahead and given "Bypass Access Restriction" permissions to certain roles. That allows them to get their work done, but I would like to know what the correct thing here is.


Can I make the Omega theme to either be or not to be responsive depending on the capability of the device to properly scale the site

I'm pretty sure you can trigger contexts on specific devices using mobile tools, and you can probably turn Omega's responsiveness off with Delta.

I've never pulled such configuration, so please try out and give some feedback ;)


How can we make edit Body input area larger?

You can go to the content types (or paragraph type) Form display settings and set the number of rows. No dev needed:

e.g. /admin/structure/types/manage/content_type/form-display

Click on the gear in the right column
Click update
Click save at the bottom


The ajax callback is pointing to the wrong function, should be:
callback' => 'reloadOptions',

It's better to make it return just the field rather than the entire form
$form['field_author']['#prefix'] = '
';
$form['field_author']['#suffix'] = '
';

$form['field_author']['widget']['#ajax'] = [
  'callback' => 'reloadOptions',
  'wrapper' => 'author-ajax-wrapper',
  'event' => 'select2:opening',
];

Adjust the reloadOptions fuction, so it returns just the specific field
return $form['field_author'];


Site in offline mode, any way to debug how this happened?

Site offline is a matter of a global variable site_offline set to 1. Any call of variable_set('site_offline', '1') can also result to put site into offline mode.

Invalid database configuration can also results as site offline but it adds some error message.

Unauthorized access to DB can be used to manually alter record in variable table for the values as
variable.name='site_offline', variable.value='s:1:"1"'


Site turned to maintenance mode without changing any settings

Drupal will show a site as offline if it cannot connect to the database, so you may want to check that the database is up and running.


I have done something along these lines with custom blocks.  The basic approach is

Put everything you want in a menu, regardless of visibility
Make a custom block; make sure you don't cache it
In the render callback, get the menu $menu = menu_tree_all_data('menu-foo');
unset() any items in the $menu according to your visibility rules
Assign the items to $block['content']

Then you can assign the block to a region.


How to list articles by an author in a views?

In your case, i would create a Vocabulary "authors" and add them with a Auto Tag Widget to the Content Type. And add the Authors as a Taxonomy Tag. There are much more Handly then Text Fields.
Then you can easily Create a View with the author Tag. And much more, you can also add more fields to the Taxonomy such as author Picture and Author Description.


Views pager shows an incorrect current page

I ran into this issue for a view block when I had caching enabled on the view and block caching enabled under Performance. Try disabling the page caching under Performance.


Relate number of values to an integer field

You will probably have to setup some way of two step process to enable the reference between both nodes (maybe entityreference). The field you are using will have to be an unlimited multi value field.

with this peace of code you will be able to reduce the items of that field (including the add button). Feel free to provide any other logic for looking up the settings node / proding a default limit etc.

<?php
function mymodule_field_attach_form($entity_type, $entity, &$form, &$form_state, $langcode) {
  if ($entity_type == 'node' && $entity->type == 'my_content_type') {
    $multi_values = array();
    foreach ($form['field_myfield'][LANGUAGE_NONE] as $key => $value) {
      if (is_numeric($key)) {
        $multi_values[$key] = $value;
      }
    }

    if (count($multi_values) > 1) {
      $multi_value_keys = array_keys($multi_values);
      foreach ($multi_value_keys as $key) {
        unset($form['field_myfield'][LANGUAGE_NONE][$key]);
      }

      // get the count of the asociated node, maybe using entity reference?
      $settings_node = node_load($entity->field_settings_node[0][LANGUAGE_NONE]['target_id']);
      if ($settings_node) {
        $limit = $settings_node->field_limiting_field[LANGUAGE_NONE][0]['value']; // e.g. textfield..
        if ($limit) {
          $i = 0;
          // add all the fields that are allowed, cut of the once that are too much (and remove the add button)
          while ($i < $limit && $i < count($multi_values)) {
            $form['field_myfield'][LANGUAGE_NONE][$i] = array_shift($multi_values);
            $i++;
          }
        }
      }
    }
  }
}

You might also want to look at How to dynamically set the maximum cardinality for a multi value field? for another example (setting the access attribute for those fields)


How to display block to the nodes of specific content type?

In the block configuration page, select the content type like this picture:


your first host: '', (line 4) is empty, should be host: 'tapcreative.services',

In addition, you're using the wrong port, port 80 is for HTTP. You need to use the HTTPS port, 443.

Change line 8 from port: 80, to port: 443,


Commerce Feeds Node Parser Problem: product SKU "missing" from mappings causing empty product displays

Found a similar problem in one of the issues, switched the dev version which solved my problem.


How to change the value of a field in its preprocess method?

In Drupal 8 front page is a view called frontpage if the view is not modified it should show: "Content" by default (instead of fields).  If so the following can be applied to change each node title

function THEMENAME_preprocess_node(&$variables) {
  //for views that show: "Content" (not fields)
  if($variables["is_front"]){
    $variables["label"][0]["#context"]["value"] .= " end of title";
  }
}


Installing Drupal on an all-Nginx server - OOB or should you customize / replace any file?

Nginx doesn't support .htaccess files without an extension. You could install that extension, but most don't.

Drupal doesn't include sample rewrite config for Nginx, so there are a few extra steps when setting up the vhost, but nothing major. You'll also need to make sure FPM is set up and configured correctly, but that goes without saying when using PHP with nginx.

There's a pretty sensible looking sample config on the Nginx site itself:

server {
    server_name example.com;
    root /var/www/drupal8; ## <-- Your only path reference.

    location = /favicon.ico {
        log_not_found off;
        access_log off;
    }

    location = /robots.txt {
        allow all;
        log_not_found off;
        access_log off;
    }

    # Very rarely should these ever be accessed outside of your lan
    location ~* \.(txt|log)$ {
        allow 192.168.0.0/16;
        deny all;
    }

    location ~ \..*/.*\.php$ {
        return 403;
    }

    location ~ ^/sites/.*/private/ {
        return 403;
    }

    # Allow "Well-Known URIs" as per RFC 5785
    location ~* ^/.well-known/ {
        allow all;
    }

    # Block access to "hidden" files and directories whose names begin with a
    # period. This includes directories used by version control systems such
    # as Subversion or Git to store control files.
    location ~ (^|/)\. {
        return 403;
    }

    location / {
        # try_files $uri @rewrite; # For Drupal <= 6
        try_files $uri /index.php?$query_string; # For Drupal >= 7
    }

    location @rewrite {
        rewrite ^/(.*)$ /index.php?q=$1;
    }

    # Don't allow direct access to PHP files in the vendor directory.
    location ~ /vendor/.*\.php$ {
        deny all;
        return 404;
    }

    # In Drupal 8, we must also match new paths where the '.php' appears in
    # the middle, such as update.php/selection. The rule we use is strict,
    # and only allows this pattern with the update.php front controller.
    # This allows legacy path aliases in the form of
    # blog/index.php/legacy-path to continue to route to Drupal nodes. If
    # you do not have any paths like that, then you might prefer to use a
    # laxer rule, such as:
    #   location ~ \.php(/|$) {
    # The laxer rule will continue to work if Drupal uses this new URL
    # pattern with front controllers other than update.php in a future
    # release.
    location ~ '\.php$|^/update.php' {
        fastcgi_split_path_info ^(.+?\.php)(|/.*)$;
        # Security note: If you're running a version of PHP older than the
        # latest 5.3, you should have "cgi.fix_pathinfo = 0;" in php.ini.
        # See http://serverfault.com/q/627903/94922 for details.
        include fastcgi_params;
        # Block httpoxy attacks. See https://httpoxy.org/.
        fastcgi_param HTTP_PROXY "";
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_param PATH_INFO $fastcgi_path_info;
        fastcgi_intercept_errors on;
        # PHP 5 socket location.
        #fastcgi_pass unix:/var/run/php5-fpm.sock;
        # PHP 7 socket location.
        fastcgi_pass unix:/var/run/php/php7.0-fpm.sock;
    }

    # Fighting with Styles? This little gem is amazing.
    # location ~ ^/sites/.*/files/imagecache/ { # For Drupal <= 6
    location ~ ^/sites/.*/files/styles/ { # For Drupal >= 7
        try_files $uri @rewrite;
    }

    # Handle private files through Drupal.
    location ~ ^/system/files/ { # For Drupal >= 7
        try_files $uri /index.php?$query_string;
    }

    location ~* \.(js|css|png|jpg|jpeg|gif|ico)$ {
        expires max;
        log_not_found off;
    }
}


Clive's answer is right for Drupal 6.

For Drupal 7, you'd implement a Field. This field would provide the 64-field form to fill out, the way to display the info, and know how to query the external database. (Obviously there's some room for design improvement here.. I'm chunking all the different pieces into one meta-field, but you could split it out however you want.)

Then you go to admin/config/people/accounts/fields and add your field to the user account profile. When you add it, there will be an initial configuration page for that field instance, and you'd check 'Display on user registration form.'

Easy as pie, right? :-)

There's a generic field implementation example in the Examples project.


First ensure that your cache confiuration are working witout Memcache. Disable memcache modules and enable caching through  the UI or in settings.php

$conf['cache_lifetime'] = '1800';
$conf['cache'] = TRUE;

Then check the response headers for anonymous users and look for x-drupal-cache. If it is a hit then you have it working if it's a miss then you must investigate further. You can check the cache_page table in the database table to start with.

If DB caching is working, proceed and add the memache settings and enable the module. Memcache integration only divert db cache to memcache. Once you do this, truncate the cache_page table, then check it after visiting pages as anonymous user. You can also check Memcache statistics. If the table fills up then memcache is not working fine and we will need more info. You can use drush to check the settings. drush vget |grep cache and post back.

Lastly check cache settings at admin/performance/cache if it is set to external you need to change that to normal for Memcache to work.


How to export private images from Drupal

You can use file_create_url($uri) to create an externally accessible url for the file.

If used with private file mode files, you will need to implement hook_file_download

You might also be interested in the Services module, to expose an API for the files, which can provide authentication methods such as Drupal session and OAuth authentication.


Is it possible to display a Mailchimp campaign (the newsletter, not a link) from my Drupal 7 website?

Outside of linking or iframe embedding, there isn't a way of simply displaying the content as, say, a Drupal page. There is actually a reason for this.

First, the content of the email is already an entire webpage: it (should) have an <html> tag and it will likely have <head>, <style>, and <body> sections. So it actually makes plenty of sense to just include it as an iframe directly on a page since it will need it's own space to format the content properly.

But let's say you decide to use the /campaigns/content.format API call to grab the actual content of the campaign. You'd likely still need to strip away the CSS and other HTML from within the content to make it display within your page nicely.

And with regards to synchronization, it only syncs from Drupal to Mailchimp. You'd need some other way of grabbing those campaigns if you wanted to see them in Drupal. This is especially useful because Mailchimp is used by many who have a single account + multiple clients.


How to remove a value from URL parameter?

You need to get the value of the parameter, then check if the parameter contains the nid, then replace/remove the nid on your parameter from your url.

Use this code on your Views: PHP

<?php
$url = token_replace('[current-page:url]');
$venue =$_GET['field_product_venue'];
if (strpos($venue, $row->nid) !== false) {
$change= str_replace($row->nid .',', '', $venue);
$l = l( t('DELETE'), $url,  array('query' => array('field_product_venue'=>$change)  ));
echo $l;
}
?>


jquery hover function in views template (drupal 6)

The original issue was that you were targeting all play buttons at once with your JS, the second problem that came up in the comments below is that your play button is on top of your .imagecache object and your .play_button is taking away the mouse focus, thus firing "hover out"

Try this:

The downside to this, however, is that if you hover over the title on the right side (outside of the .imagecache) object, your still going to get the fade in/out effect triggered...

If that is not what you want then you could try altering the template:

<?php

print '
';

print '
';

print $fields['field_video_embed']->content;

$hover_play = l('', 'node/' . $row->nid, array('attributes' => array('class' => 'play_button', 'style' => 'display: none'), 'html' => true));

print $hover_play;

print '
';

print '
'. $fields['title']->content .'
';

print '
'; // vgrid

?>


Get taxonomy term ID from standard URL and then pass it to a View as a contextual filter

You do not have to write any code to achieve that.

Just go to the views edit page, add a contextual filter named as Has taxonomy term ID and select Provide default value, see screenshot for more options

However, you can also do it pragmatically

function HOOK_views_query_alter($view, $query) {
   $term = menu_get_object('taxonomy_term', 2);
   if ($term && $term->vocabulary_machine_name == 'VOCABULARY_NAME') {
     if ($view->name=='VIEWS_MACHINE_NAME') {
       $view->query->where['0']['conditions']['0']['value']= $term->tid;
     }
   }
}

I hope it helps.


How to add classes to every menu block placed within in a specific region?

you can augment the variables collection available to any twig file by tweaking the appropriate preprocess ... for example ... if you create the following function within your $THEME$.theme file:

function $THEME$_preprocess_block(&$variables) {
  $block_id = $variables['elements']['#id'];
  $block = \Drupal\block\Entity\Block::load($block_id);
  $variables['region'] = $block->getRegion();
}

you can then access the newly defined region variable from within:

{{ region }}

you could then add your desired classes to menus but only when they appear within a certain regions:

{% set classes = 'menu' ~ ((region == 'header') ? ' menu-header') %}
{% block content %}
    <nav {{ content_attributes.addClass(classes) }}>
        {{ content }}
    </nav>
{% endblock %}

that would add the class menu to all blocks and additionally would add the class menu-header to any block within the header region

hope that helps!


How do I get the taxonomy term ID from its name?

taxonomy_get_term_by_name() will do the trick:

$terms = taxonomy_get_term_by_name($row->field_term_name);
if (!empty($terms)) {
  $first_term = array_shift($terms);
  print $first_term->tid;
}


How can I aggregate information from about 30 Drupal sites in one place?

The Similar Module Review's Administration module wiki lists several options.

The following show some usage statistics, as well as Drupal core and module updates:

Droptor (Requires paid service for more than 1 site.)
Drupal Remote Dashboard
Network Manager (Drupal 7 version doesn't exist yet.)
Sentry Server (Drupal 7 version doesn't exist yet.)


OK, problem solved. Removing the features[] line from the theme info kind of reset the settings page. I also read this post about theme settings and providing default values. Problem solved, although I don't quite know why the features[] stuff affected the whole form. Will probably learn with time.


Create new child field collection programmatically

You try the code:

<?php
use Drupal\field_collection\Entity\FieldCollectionItem;
use Drupal\node\Entity\Node;

[.....]

  $node = Node::load(7);
  $field_collection_item = FieldCollectionItem::create(
    [
      'field_name' => 'field_test_student_info',
    ]
  );

  $field_collection_item->set('field_student_name', 'Student Name');

  $field_mark_collection = FieldCollectionItem::create(['field_name' => 'field_marks']);
  $field_mark_collection->set('field_english_marks', '1231');
  $field_mark_collection->set('field_history_marks', '123');
  $field_collection_item->field_marks[] = ['field_collection_item' => $field_mark_collection];
  $node->field_test_student_info = ['field_collection_item' => $field_collection_item];
  $field_collection_item->setHostEntity($node);
  $node->save();

You need create new collection field  FieldCollectionItem::create(['field_name' => 'field_marks'])

You can set value to the file child in field parent collection, it is same you when set value field collection in node, here you dont's need set setHostEntity, it will understand is the field_collection_item

As the code above I also checked it, and it worked.

You can refer to it here

Goodluck


Git showing every changed file not folders

The difference between showing the folder level for untracked files and the file level for tracked files is expected git behavior. This will always be the case. Once you add the folder (which adds all the files in it) each of the files is tracked by git and will be tracked individually. So, when you do a status, it SHOULD list each file separately. Yes, this is kind of annoying, but the general idea is that you'll add a folder and then commit that change. Once committed, you won't see each file unless is has been changed in some way.

As for fixing the situation, you probably haven't actually messed anything up; it's just tough to see that because there are so many new files in your index (a git term which you can research if you'd like more information).

If you'd like to undo it all, you can run the git reset command. In general, most things related to git can be demystified with a couple of Google searches. If you're new to git, I recommend the free Git Book.


Display decimal field without right side zeros

You can format the field from Manage Display as follow:

Go to manage display of the respective entity
Click on settings button of the field to do formatting
Change the value of Scale dropdown to zero
Click update
Click Save button at bottom


How do I show nodes/articles with specific taxonomy on a page?

You can use Views for building the output of the page and filtering according to the search query (that is called "exposed filter" in views).

To get familiar with Views and see all what you can do with them, check out Nodeone library of videos on Vimeo.


How to relate a complex field to another node

My solution to this is as follows:

I have basic content types of Player and Golf Course.
When I want to enter new scores, I first create a Round (which is another content
type with a node reference to a Golf Course and a date field).
Once the round is created I create Results (another content type which has
a relationship to a round and a player and an integer for the score).

This handles my data entry requirements even though the workflow is a bit of a kludge, but I can streamline that later I think. Now the next step will be using views to display my results but that will probably be another question :)


You need to add to your view the Contextual Filter: Content: NiD

Click Provide Default Value and select Content ID from URL


Why is css not working as expected with Omega

I think your CSS is incorrect. You wrote:

.menu ul li {/*stuff*/}

when I think it needs to be:

ul.menu li {/*stuff*/}

Is this correct?


There's definitely something wrong with your theme, or a custom/contrib module you've got installed. Required fields are always validated and checked for empty values; they just piggy-back off the FAPI #required property which I've never known not to work.

As far as debugging goes:

Check the context the registration form is being displayed in. If you're manually adding the registration form in your theme, and doing so in a template file, the problem is simply that the messages produced by the form builder are being built after $messages has already been outputted in page.tpl.php (ignore this one if the problem is happening on the main registration page).
Change the default theme back to Garland and see if the problem persists.
If it does, start methodically disabling contributed and custom modules to isolate the culprit. Start with custom modules, then dev/alpha/beta contrib modules (in that order), then the stable modules. Check the registration form each time you disable one.
To make sure there isn't some sort of conflict between your theme and a custom/contrib module, make sure you switch back to your custom theme before starting to disable modules.
If all else fails, install a fresh copy of Drupal as a test site, add a couple of required fields to the user entity, and check the registration form again. If it works, you know there's something definitely wrong with your main installation. If it doesn't (which is extremely unlikely), you know the problem is more sinister (i.e. it's a crazy problem with PHP/MySQL/your OS)


Drupal core language module, language switcher block

You can copy the core/modules/system/templates/links.html.twig into your theme's templates directory, call it links--language-block.html.twig  and in this file adjust the output from the default ul/li structure into a different html structure.

NOTE: there is already 3 maybe more modules that convert the language switcher to dropdown lang_dropdown, dropdown_language and bootstrap_languages.


Can Google Bot Crawl authenticated pages?

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.


Trigger Authcache Reload on Field Change for Drupal Commerce Products

Authcache comes with an integration module for the Cache Expiration project. See also the Authcache 2 tuning guide - integrate with Cache Expiration module.

It might get tricky to find all pages where a particular product/price is displayed due to the separation of products and display nodes in commerce. Depending on how frequent prices are changed, you might consider nuking the whole cache, e.g. using a combination of Rules and the Cache Actions module.


Search template suggestions from a module

Thanks to the comments from @AlexGill and @Beebee I was able to figure out what's the actual suggestion name for my template file. Here's how I solved it:

<?php

function history_search_theme()
{
    return array(
        'search_result__history_search' => array(
            'template' => 'search-result--history_search',
            'path' => drupal_get_path('module', 'history_search'),
            'base hook' => 'search_result',
        ),
    );
}


best way to restrict endpoints such as /node or /filter/tips

One way to restrict access to specific paths is to use the Custom Permissions module.

It allows you to create path based permissions at /admin/people/custom_permissions.

Then you can configure which roles have those custom permissions as you would any other permission at /admin/people/permissions.

I probably wouldn't use this solution if I had a very large number of paths to restrict but it's a very usable solution for a few pages, especially if you still want admins to be able to access them.

.htaccess restrictions are also possible if you want to go that way.
That would mean there would be no database load involved in restricting access, which might be a consideration for very high traffic sites but would generally be negligible for an average site.


When no terms are chosen as filters in a view all results are returned

So you want the inverse of a search? Or have I misunderstood?

If thats what you mean I think you can change that inside your view settings.

Go to Structure > Views > edit your view

Then select your filter criteria and edit it. I think you need to check the following check box.


drush sql-sync error: [mysqldump: command not found]

Looking at the drush github repo, mysqldump appears to be a
non-negotiable dependency. More broadly speaking, given it's
functionality, I'm unclear why it wouldn't be. So, yes, drush
requires mysqldump for mysql exports.
There's always another way, or expressed without my opinion; "yes." Whether it is a good practice to MacGyver such a solution depends on how much free time you have. There's an interesting php implementation of mysqldump discussed here, but here's where my caveat becomes more clear. Check out the commit activity page — not bad, but on the sparse side for a production solution for my tastes and capacity. So the answer may really depend on how much of this development your client is willing to absorb.

Personally, I'd either convince my sysadmin to allow mysqldump (something I haven't had to do in years) or move my site to a host that will provide such a basic service.

ps: I may be wrong but the Backup and Migrate may give you mysql export capability without mysqldump.


alterations in tpl file work, but not dpm();, dsm(); or drupal_set_message();

You have access to the entire Drupal bootstrap within template files. Template files are loading at the very end of a page request post bootstrap. If dpm() or dpr() is not working it is most likely because you are viewing the site as an anonymous user. The devel module by default does not allow access to it's functionality for anonymous users. Try logging in as admin and you should see the output of your devel module function calls.

As an F.Y.I. template files are not the typical place for a dpm() as you either need to know the variable you are after or put a get_defined_vars() calls inside it which can be quite heavy depending on where you are in stack. It is more common to use dpm()'s in template hooks such as:

template_preprocess_page()
template_preprocess_node()

function template_preprocess_page(&$vars) {
  dpm($vars);
}

Then you can see all the variables that are available to your template files.


Where to add "No results behaviour" to a view?

You can add "No Results Behavior" in view itself.

Then select Text area which will help you to add any custom text.
At last add your custom text and click on apply button.


Ability to separate between levels in vocabulary hierarchy

Yes, you could use a module like taxonomy_menu to show a list of taxonomy terms.

Alternatively, you could use a code solution like taxonomy_get_tree that allows selecting terms by parent tid and depth.


How to programmatically apply a fee/promotion?

After a lot of trial and error I thought of moving the code out of the form submit function and into an event subscription; in particular, i moved it to the commerce_order.order.paid event.
So I ended up with this in an existing event subscriber call back I already had:
  public function placeOrder($event) {
    $order = $event->getOrder();

    $fee = current(\Drupal\commerce_fee\Entity\Fee::loadMultiple());
    $price = $fee->getPlugin()->getConfiguration()['amount'];
    $splitter = \Drupal::getContainer()->get('commerce_order.price_splitter');
    $amounts = $splitter->split($order, new Price($price['number'], $price['currency_code']));
    foreach ($order->getItems() as $order_item) {
      $adjustments = $order_item->getAdjustments();
      $adjustments[] = new Adjustment([
        'type' => 'fee',
        'label' => $fee->getName(),
        'amount' => $amounts[$order_item->id()],
        'source_id' => $fee->id(),
      ]);
      $order_item->setAdjustments($adjustments);
      $order_item->save();
    }
  }

This code includes code to split the fee up among all the items; which may or may not be what you want (although doesn't seem like it could ever be a bad idea).


You are going to need to open phpmyadmin from your hosting, and look in the "block" table.

Look for the "main" block, and edit the status to "1" and the region to "content" (or whatever your main region is defined as in your themes .info file).
It seems strange that disabling the main content block would hide the login form though, I thought they were separate.


How to give default today date value in exposed filter?

Yes it is possible.

Choose the date field in Filter Criteria section in Views
On the RHS of your date filter settings, you will see a section to enter a default relative date (refer screenshot)
Choose 'Enter a relative date' & enter the relative date as 'today'
Apply the filter & Save the view


How to include data-url-encode data using drupal_http_request()?

--data-urlencode just appends ?foo=bar to the end of the URL (encoded of course); drupal_http_request() has no special handling for query strings, it parses them directly from the provided URL with parse_url().

That said, this would be functionally equivalent:

$data = drupal_http_build_query(array('include' => 'gator'));
$url = 'https://example.com/1/endpoint?' . $data;
drupal_http_request($url);

Request from Drupal:

GET /1/endpoint?include=gator HTTP/1.0
User-Agent: Drupal (+http://drupal.org/)
Host: example.com

Request from cURL:

GET /1/endpoint?include=gator HTTP/1.1
User-Agent: curl/7.30.0
Host: example.com


I don't think this is possible with an entity query directly, but you can alter entity queries after they are converted into select queries.

Add a tag to your entity query and then you can alter it there.

  $nids = \Drupal::entityQuery('node')
    ->condition('type', 'article')
    ->addTag('sort_by_random')
    ->execute();

Then add a query alter function to your custom module using the tag you added.  Drupal's select query even has a built in function to make a query sort on "RAND()":

function mymodule_query_sort_by_random_alter(\Drupal\Core\Database\Query\AlterableInterface $query) {
  $query->orderRandom();
}

If you're going to have to tag an entity query to alter it, and it's not essential that you use an entity query, you might want to just replace it with a select query.

$query = \Drupal::database()->select('node_field_data', 'n')
  ->fields('n', ['nid'])
  ->condition('type', 'article')
  ->range(0, 10)
  ->orderRandom();

$results = $query->execute()->fetchCol();

if (!empty($results)) {
  $nodes = \Drupal::entityTypeManager()->getStorage('node')->loadMultiple($results);
}


CSS/JS aggregation, huge number of files

As noted in the post you found:

  They will be deleted automatically 30 days (or whatever your
  drupal_stale_file_threshold variable is set to) after they were
  created via drupal_clear_css_cache() and drupal_clear_js_cache().

If you are going to have many thousands of users worrying about file system performance at this stage is likely getting ahead of yourself. Depending on your hosting setup you are more likely to run into other kinds of performance issues (PHP, database, fewer non-file caches, etc) before the file system becomes the bottleneck. You may indeed need to solve that problem eventually but it is unlikely to be the first challenge you need to overcome.


How do I display last five nodes, with the latest at the bottom using views?

I'm fairly certain that Views does not support this. It's a somewhat frequent request for listing comments as well, but you can't add sorting after filtering/paging.

The easiest way is to change the view template to output the rows in reverse order.


Can i use route ID for Link template 'edit-form' for entity type?

The tutorial is from 2014. Since then the link templates have changed from route to path. See change record:

Previous link template format

   links = {
     "canonical" = "entity.node.canonical",
     "edit-form" = "entity.node.edit_form",
     "delete-form" = "entity.node.delete_form",
   }

New link template format

After the change, the path is used.

   links = {
     "canonical" = "/node/{node}",
     "edit-form" = "/node/{node}/edit",
     "delete-form" = "/node/{node}/delete",
   }


How to get the URL for an image thumbnail

You need to use function image_style_url($style_name, $path) to obtain proper path in Drupal 7.20 and later. $path is a path to an original file. Preferably output normal path, and make it a thumbnail in proper .tpl.php file.

If you need to do it in place that does not accept php functions and cannot alter it in template, you can consider disabling itok token. To do so, add following line to your settings.php

$conf['image_allow_insecure_derivatives'] = TRUE;

Then you can simply add styles/thumbnail/public/ like Kevin says, and use path like example.com/sites/default/files/styles/thumbnail/public/myimage.jpg to get thumbnail of example.com/sites/default/files/myimage.jpg.


You can use something along the lines of this:

MYMODULE_views_pre_render(&$view) {

  if ($view->name=='NAMEOFTHEVIEW') {

    foreach($view->result as $r => $result) {
      // do whatever you want with each "row"
    }

  }

  // other views might go here

}

and this is certainly NOT a bad practice at all, and, at least IMHO, far superior to php fields in the view itself.


You can override the validateForm method in your own form class. Just declare a method like so:

public function validateForm(array &$form, FormStateInterface $form_state) {
  // Your custom validation code.
}

Since the Drupal\Core\Form\FormBase (parent of Drupal\Core\Entity\EntityForm) class has no validation, just a blank method, there is no need to call the parent method from your own class.


TinyMCE editor does not show buttons in bar

Did you enable some button /admin/config/content/wysiwyg/profile/yourprofile/edit ?

If yes, this can be caused by a javascript error. Do you see one in Firebug ?


Migrate Drupal locator content to Wordpress site

also saw your email...

The migrate module is very Drupal-centric. It runs on a Drupal site, and the primary (99.99%) use-case is to pull data into that Drupal site - all destination plugins I know of write to the local Drupal database. That being said, it would be entirely possible to write a destination plugin that pushed to an external destination - like, say, a WordPress database or a web service for creating content.

Personally, my only experience with WordPress is in importing content from WordPress exports (XML files) into Drupal, so I don't know how challenging pushing content to WordPress would be.


How do I create a table when a module is installed?

I see two problems with your hook_schema implementation.

You are missing a return statement at the end of your function to return the schema.
primary_key needs to be outside the fields array on the same level as the fields and the description.

/**
 * Implements hook_schema().
 */
function MYMODULE_schema() {
  $schema['post'] = [
    'description' => 'description pour la table post',
    'fields' => [
      'pid' => [
        'description' => 'post id',
        'type' => 'int',
        'not null' => TRUE,
      ],
      'title' => [
        'description' => 'title',
        'type' => 'varchar',
        'not null' => TRUE,
      ],
      'body' => [
        'description' => 'body',
        'type' => 'varchar',
        'not null' => TRUE,
      ],
      'created' => [
        'description' => 'created',
        'not null' => TRUE,
        'mysql_type' => 'timestamp',
      ],
    ],
    // primary_key needs to be outside the fields array.
    'primary key' => ['pid'],
  ];
  // Don't forget to return the schema.
  return $schema;
}


If an element is given #markup, the render process stops searching for nested elements. To accomplish what you need, just create a second child element with no #prefix or #suffix.

function make_array() {
  $items = port_view_get_block();
  $array = array(
    'container' => array(
      '#prefix' => '
',
      '#suffix' => '
',
      'markup' => array(
        '#markup' => 'This is inside the container div',
      ),
      'slider' => array(
        '#prefix' => '
',
        '#suffix' => '
',
        '#markup' => 'This is inside the slider div',
      ),
    ),
  );
  return $array;
}


Custom route using access check error with arguments

Digging deeper into what causes the error message brought me to the drupal docs about Parameter upcasting in routes. When passing entity parameters to an access check function you need to upcast your parameter and tell Drupal of which entity type your argument is. I.e. in my_mod.routing.yml add options and argument type:

mymod.add:
  path: '/mymod/add/{group}/{plugin_id}'
  defaults:
    _controller: '\Drupal\mymod\Controller\MymodController::addNews'
    _title: 'Add news'
  requirements:
    _group_content_create_access: 'TRUE'
  options:
    parameters:
      group:
        type: entity:group


Drupal 8 has a new versioning system, with the following format:

Major.minor.bugfix

Minor versions are expected every 6 months (8.1.0 was recently released), and will contain backwards compatible enhancements and new features, but will remain compatible with code written for earlier releases of the same major version.

So Drupal 8.1.x contains new features and API enhancements, but remains compatible with modules developed for 8.0.x.

This will allow Drupal to be more agile in future, and new features won't be limited to major releases, but compatibility with modules should be maintained.


Displaying the username of the user who created the node in the node template file

$node->name will get you the name of the author who submitted the node. It will return it as string, not as link to the user account.


Error: OAUTH2 SERVER LIBRARY Unavailable

I encountered the same problem, being new to Drupal 8 development, and this project currently lacking documentation for its use with Drupal 8, probably because it is currently only available through a "dev" edition.

The solution I used was to add the two oauth2-server-php Composer dependencies in the "composer.json" file at the root of the Drupal folder, which are currently:

"require": {
    "bshaffer/oauth2-server-php": "~1.7",
    "bshaffer/oauth2-server-httpfoundation-bridge": "~1.1"
}

Then install them with Composer by executing "composer install".

You can reach the project issue where I got help there: https://www.drupal.org/node/2897289#comment-12202222


Can't you use the "normal" upgrade scenario for FTP servers?
(I usume this still works btw. haven't tested it on d8 yet)
 - Download your intended version of devel from d.o.
 - Unpack the download
 - Upload to the server in place of the old devel module (so same paths,permissions,etc)
 - Run the "update.php" script to update the Database.(you need to be admin to do this, or change your settings.php to temp. allow anyone to do it).
 - Devel should be updated now.

according to the docs this should work see d.o. D8 Update a module


Paragraph migration for link field not working

I guess both icon_url and icon_type are fields of your paragraph entity.
Remove the leading blanks in front of the line

icon_url:

until it has the same indentation level as icon_type.

(Whitespaces are very important in YAML: Indenting something blanks makes it a child of a previous line with less blanks. In your example icon_url has 2 blanks and therefor it is a sub value of field icon_type. With only one blank [same as icon_type and all the other fields] it means that icon_url is a direct child of the global process [the one without blanks].)


How can I attach a phone number field to the user account and optionally validate it via SMS?

To address the modules mentioned:

This is a non-starter as it's a different use case from SMS number verification.
Here you'd have to build off the back the Twilio module. You could  modify user setting form twilio_user_settings_form() so that the callback twilio_user_settings_confirm_form_submit() is altered with your own custom callback that triggers a callback. Alternatively, you could evoke a hook_user_presave() as twilio_user_settings_confirm_form_submit calls user_save() with 'status' => TWILIO_USER_CONFIRMED, in the $edit array. In either case, you'd have to build/evoke your own custom rules event.
The SMS User module does provide verification for existing users. The form can be found under the path user/{UID}/edit/mobile. It triggers User validated SMS code event once the user has completed the verification process.

Given the above, both modules can achieve what you're looking for, it's just a matter of how much modification vs. what each service provides (Twilio vs. any other SMS Gateway provider).


Add a link in management menu for specific role

Shame on me ! The solution relied of course in a single line of my code, shared below in case it could help somebody.

I aimed to block many admin pages access, from which the admin path, in  a radical manner :

function vts_dashboard_menu_alter(&$items) {
   $items['admin']['access callback'] = 'vts_dashboard_admin_access_only';
  //more items ...
}
function vts_dashboard_admin_access_only() {
  global $user;
  if( !in_array('administrator', $user->roles)){
    return false;
  }
  return true;
}

But $items['admin']['access callback'] blocks also descendant menus items... commented out and all's fine again !

Be what it is, if any enlightened Drupal guru can tell me how to restrict access to foo path but no foo/bar, he'll receive all my consideration !


I would either add an image field directly to the line item type and expose it to the Add to Cart form (along with any other pertinent fields) or figure out some sort of entity reference scenario with an Inline Entity Form on the line item to show the entity add form in the Add to Cart form. Might be a bit general, but googling any of those topics will turn up more info.


Go to Solr Admin (usually http://localhost:8983/)

Go to Core Admin or your core selector and click Reload. When refreshed, you should see a green check mark on the "current" field. After this, your solr cache will be deleted and refreshed with new indexes.


retaining upload file information in form when validation fails on other fields

I believe using the File_Managed fieldtype will fix your problem. This Drupal FAPI field type uploads the file to a temp directory BEFORE the form is submitted, and so you can access the file during/after validation. You can see an example of it being applied in the "image_example.pages.inc" in the Examples module. Hope this helps.


Access denied to file in sites/all/default/files

Drupal.org has a great guide on permissions.

The TLDR; version.

You can change permissions by opening up your terminal and perform the following commmand:

(sudo) chmod <mode> <path>.

For more information about chmod, check the manpage. Or just perform:

chmod --help


You must have forget to render $tabs variable in your custom theme. You have to render it before you render your $content in page.tpl.php

Example from my page.tpl.php --

<?php if ($page['content']): ?>

        <?php if ($tabs): ?>

                <?php print render($tabs); ?>

        <?php endif; ?>
        <?php if ($title) : ?>

                <?php print $title; ?>

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

<?php endif; ?>

Structure your page.tpl.php like this by rendering $tabs variable before title, clear the cache & you will have tabs..


Drush core does not support upgrading from Drupal 6 to Drupal 7 with any of the built-in commands pm-update only supports minor updates.  You'll need the Drush Site Upgrade command to advance to the next major version.

Note that this command has not been tested on Windows; it would probably be safer to run the command in a Linux environment.  Use a virtual machine (e.g. virtualbox) if you do not have a dedicated Linux environment.

Doing a major upgrade from Drupal 6 to Drupal 7 is a serious endevour; the Drush site-upgrade command will help you walk through the process, but it does not do all of the work for you.  The process isn't too hard if it goes smoothly, but you may run into contrib bugs that complicate the process.  An alternative method to upgrade would be to just make an equivalent Drupal 7 site from scratch, and then use drupal-to-drupal migration to move your content over.

Finally, to answer your specific question, there are a number of ways to specify the Drupal site that you would like Drush to operate on, but the easiest and most straightforward way would be to cd to the directory that contains your settings.php file (often sites/default).  You will also need to set up an alias (for your target Drupal site) if you use the Drush site-upgrade command; see the file examples.aliases.drushrc.php for instructions on how to do that.


Add a hyperlink underneath the table of a Page View?

There's a few ways to do that.

Edit View
Click "Footer > Add"
Add your footer HTML as "Global: Text Area"

Another way is to add a block on that page under the view.

admin/structure/block/add
Set page visibility to only your View page path
Set region to "Content" below "Main page content"

If you want more control or placement, you can theme the View page

Edit the View
Click "Advanced > Theme > Information"
You would override the page level "views-view.tpl.php" template renamed to match your View (e.g views-view--my-view.tpl.php ) in your theme dir.


add function on date selected through date popup field

For Drupal 7, the datepicker is indeed likely to be the one from jQuery UI, and since you may not know in your own javascript if date pickers have been initialized yet, an easy way to trigger your "custom function" is to listen for selection on any date picker on the page.

  jQuery.datepicker.setDefaults({
    onSelect: function () {
      console.log('date selected');
    }
  });

Refer to the jQuery UI onSelect documentation for more information.


How do I create different landing pages?

You have to check this link for theming of different different page.


hook_menu access argument returns 3 instead of data

Your delivery callback is not right. The default delivery callback is drupal_deliver_html_page($page_callback_result).

From that page:

  $page_callback_result: The result of a page callback. Can be one of:

  NULL: to indicate no content.
  An integer menu status constant: to indicate an error condition.
  A string of HTML content.
  A renderable array of content.

So there is no such thing as $data['error']. You are probably encoding the error code 3.

In the default callback they catch integers as errors:

// Menu status constants are integers; page content is a string or array.
if (is_int($page_callback_result)) {
  ...
}

You might want to do the same:

function mymodule_json($data) {
  if (is_int($data)) {
    drupal_add_http_header('Status', '400 Bad Request');
  }

  echo drupal_json_output($data);
}


How to empty the cart automatically before adding a new item to the cart?

You can clear the cart using the following function

uc_cart_empty(uc_cart_get_id());

Use the above function in your module when you want clear cart.
To empty the cart automatically before adding a new item to the cart call the function in hook_add_to_cart().

eg:

function MODULE_NAME__add_to_cart($nid, $qty, $data) {
  uc_cart_empty(uc_cart_get_id());
  drupal_set_message("Previous item cleared");
}


my urls are not replacing spaces with hyphens

It's because you haven't updated the paths yet. So you need to go to the BULK UPDATE tab

Select CONTENT Paths and click on update.


One method of doing this is to override theme_menu_link() in your template.php file. Specifically, we will be looking for the "My account" link and changing that the text to the username and adding the image.

Add the following to your template.php in your Omega subtheme:

function OMEGASUBTHEME_menu_link(array $variables) {
  global $user;
  $element = $variables['element'];
  $sub_menu = '';

  if ($element['#below']) {
    $sub_menu = drupal_render($element['#below']);
  }
  $title = '';
  // Check if the user is logged in, that you are in the correct menu,
  // and that you have the right menu item
  if ($user->uid != 0 && $element['#theme'] == 'menu_link__user_menu' && $element['#title'] == t('My account')) {
    $element['#title'] = $user->name;
    // Add 'html' = TRUE to the link options
    $element['#localized_options']['html'] = TRUE;
    // Load the user picture file information; Unnecessary if you use theme_user_picture()
    $fid = $user->picture;
    $file = file_load($fid);
    // I found it necessary to use theme_image_style() instead of theme_user_picture()
    // because I didn't want any extra html, just the image.
    $title = theme('image_style', array('style_name' => 'thumbnail', 'path' => $file->uri, 'alt' => $element['#title'], 'title' => $element['#title'])) . $element['#title'];
  } else {
    $title = $element['#title'];
  }
  $output = l($title, $element['#href'], $element['#localized_options']);
  return '
' . $output . $sub_menu . "
\n";
}

This produces the following html for the menu item in question (my thumbnail image style is set to scale and crop 28 x 28):

username

The rest is just css and possibly javascript.


Drupal 7 LoginToboggan username or email or custom field

You can do that by using this contrib module: https://www.drupal.org/project/login_custom_field

It will allow you to log in using a (custom user field and password) along side with (username and password). Also, you can enable LoginToboggan module to allow using (email and password) as a 3rd option.


show all the blocks added to the particular page?

The simple answer is that there isn't such a page. But you can go to the block administration page and see a list of all blocks for the given theme. If there is a 'configure' link for the block, it's a block that was created through the admin interface, so you can go through them to try to find the block in question.

The other thing you can do is examine the HTML to find the HTML id for the block. This will give you an indication of which block it has been added to, or if it was even added through a block or not.


On a Drupal user application form, is it possible for the user to lookup existing users?

Yes it is possible but would require some custom code.

Assuming you already have a form element where your autocomplete search would take place, in a hook_form_alter() or hook_form_FORM_ID_alter() you could use something like:

  // Add ajax autocomplete.
  $form['name_of_your_text_element']['#attached']['js'][] = 'misc/autocomplete.js';
  $form['name_of_your_text_element']['#autocomplete_path'] = 'ctools/autocomplete/user';

Note that you will probably need to adjust some permissions in order to allow anonymous users to see your users' information. Check /admin/people/permissions if you need to fine-tune something there.

You also need to have the ctools module enabled in order to use this functionality.


According to Get the user IP address and Symfony HttpFoundation you can get visitor IP by

first add use Symfony\Component\HttpFoundation; then

 \Drupal::request()->getClientIp()


media_gallery images are not opening with proper size

For the images to be of same size on every refreshing of page:-

you need to define the image style as per your requirement by Configuration > Media: Image Styles
Add the new style by giving it a name
Add the effect you want to give
Click on Add button and add the corresponding properties.
Update the style
Finally when uploading the images,choose the image style for the image ,this would result in the constant size of the image throughout instead of the variable size of the image.


Trying to get COUNT(*) from custom content type with EntityFieldQuery

You can use EntityFieldQuery::count(), as reported in the documentation for EntityFieldQuery::execute().

  [The result is] Either a number if count() was called or an array of associative arrays of stub entities.

The code you should use is similar to the following one:

$query = new EntityFieldQuery;

$count = $query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'employees')
  ->propertyCondition('status', 1) // Getting published nodes only.
  ->count()
  ->execute();

To filter the result by the content type, you need to use EntityFieldQuery::entityCondition('bundle', $content_type).
For conditions on fields, you should use EntityFieldQuery::fieldCondition().


When you make a change to a view in the UI and click "save" before the preview has finished loading, you'll get this error. It's simply because you've made a 2nd request to the server while the ajax request to load the preview is still running.

You can either wait for the preview "loading" icon to finish before you save the view, or you can ignore it :)


Views: Use default value from URL for contextual filter, THEN show all if default value empty?

Even faster:
PHP is not even needed to just display all values...

Under "When the filter value IS available or a default is provided
Tick "Specify validation criteria" Choose 'Basic validation'
Under "Action to take if filter value does not validate", choose "Display all values"


Taxes is not shown in the cart. Using Drupal Commerce module

Drupal commerce will by default not show taxes on the cart, the cart is more simple minded with focus on products. The review and checkout pages, will however have taxes displayed by default.

The shopping cart is based on views, so it's pretty easy to change how the order total is displayed. Instead of using Commerce Line Item: Line item summary area handler you should instead use the Commerce Order: Total


Help with wrapping character with CSS span using Jquery

Two things I can think of that could possibly cause the problem:

Your code runs before the document is fully loaded. To fix it try wrapping the function call inside $(document).ready:

$(document).ready(function() {
  $('div').wrapInTag({
    words: ['™'],
    tag: '<span class="trademark">'
  });
});

The CSS style are being overridden. Quickfix would be to add !important at the end.

.trademark {
  font-size: 9px !important;
  vertical-align: top !important;
}


It has been solved using.

function  hook_install(){

db_query("CREATE PROCEDURE xyz()

BEGIN
    set @num := 0, @termid := 0;
    ......................................");


Allow only lowest taxonomy terms to assign to nodes

Hierarchical Select.

  Hierarchical Select has the ability to save the entire lineage of a
  selection or only the "deepest" selection. You can configure it to
  force the user to make a selection as deep as possible in the tree, or
  allow the user to select an item anywhere in the tree. Levels can be
  labeled, you can configure limit the number of items that can be
  selected, configure a title for the dropbox, choose a site-wide
  animation delay, and so on. You can even create new items and levels
  through Hierarchical Select!


Checking which radio button was clicked on a cck form using Javascript or Jquery

If you want to have an 'other' type of field you could use: http://drupal.org/project/select_or_other

I maintain custom code to achieve what you want (on very long fake multistep forms) and don't recommend this, it quickly becomes very unmanageable.


How to refresh a coded block when a flag is clicked in it?

The easiest way would be to use the module Block Refresh. With this module you can set up any block to be reloaded both manually and by an interval. For your use case you would chose the first option, here is an example form the block configuration page:

You will see now a refresh button on blocks title, which could be hidden by the following CSS:

.block-refresh-button {
    display:none;
}

and then triggered by clicking the flag:

$(".flag").click(function() {
    $(".block-refresh-button").each(function() {
        $(this).click();
    });
});

I did not test the code.


What are some ways to implement a hierarchical taxonomy page structure?

Drupal taxonomy was born for these needs.

And Views is perfect if you need simple filters.

If it's a high volume of pages and search functionality is going to be important, you can integrate it with Apache Solr and use Facets to filter. What better example than drupal.org


What is the most robust way to assert for a validation error?

Since you are talking of custom validation, if the code is using form_set_error() or form_error(), then there should not be any problem, if the test code and the form validation handler use the same string (which is passed / not passed to t() in both the cases).

Keep in mind that the modules enabled during a test execution are Drupal core modules enabled from the profile used for the tests, or modules explicitly enabled from the test class. The error message output from your form validation handler is not altered, if the modules enabled from the test class don't alter it.

An alternative method of checking if a validation handler returned an error would be setting a global variable, for example; that is something Drupal does, but only from a module that is used only for testing, not a module that is normally executed. For example, entity_crud_hook_test_comment_delete() (the implementation of hook_comment_delete() done from the Entity CRUD Hooks Test module) uses a session variable that is set when the hook is invoked.
Notice that this is what Drupal normally does to verify a hook is effectively invoked when it should. When you need to verify if a form validation handler returned an error, I would rather use the method you are using, since:

It doesn't require the form validation handler to know if it is being executed during test, or not
It doesn't require the use of a test module

There are some cases where a module needs to be created with the only purpose of testing something, but that is not generally the case of verifying a form validation handler effectively returns an error when it should.


Batch API passing data to finished function

First, make sure you set the finished process in your batch process.

$batch = array(
      'title' => t('Merging content ...'),
      'operations' => array(
         array('batch_import_import', array($col1, $col2),  //Note we pass 2 variables here.
       ),
      'finished' => 'batch_import_finished', // set this!
      'init_message' => t('Connectng to the base site ...'),
      'progress_message' => t('Processed @current out of @total.'),
      'error_message' => t('An error occurred during processing'),
      'progressive' => FALSE
    );
...
batch_set('admin/content');

Then, in your worker function, you can take the last argument passed to it as $context.

For an example, from above example above, your worker function should be something like this:

function batch_import_import($col1, $col2, &$context) {
  //do the stuff.
  if (!isset($context['results']['created'], $context['results']['updated'])) {
    $context['results']['created'] = 0;
    $context['results']['updated'] = 0;
  }
  $context['results']['created']++; // is_new == TRUE or some logic.
  $context['results']['updated']++; // add some logic to determine created or updated.
}

and then in the finish function, you get $context['results'] as the second argument.

batch_import_finished($success, $results, $operations) {
   if ($success) {
     $message = t('Nodes created: @count', array('@count' => $results['created'])).'<br />';
     $message .= t('Nodes updated: @count', array('@count' => $results['updated']));
   }
   else {
     $message = t('some errors');
   }

  drupal_set_message($message);
}

I have also corrected the $message as you can use t() function here.
Note that you pass $context by reference.
See batch_api examples for more information. This is just some code copied from a module I was developing the other day.

In the finished function, $operations contain unprocessed items.


Your First argument must be a variable. The file_move() documentation says:

  $source: Either a string specifying the file location of the original file or an object containing a 'filepath' property. This parameter is passed by reference and will contain the resulting destination filename in case of success.


How do I create a variable that my page.tpl.php file can access?

In Drupal theming, template preprocess functions are the functions that prepare the variables that can be used in a certain template. Template preprocess functions are executed one after another and they pass around an array with all variables. You can add your own in your theme's template.php, in the form of function THEMENAME_preprocess_TEMPLATENAME(&$variables) { // Your code here. }.

If you're adding a value to a node object in a hook_node_load implementation, that probably looks something like this:

function mymodule_node_load($nodes, $types) {
  foreach ($nodes as $node) {
    $node->myvariable = 'somevalue';
  }
}

Now you want to access $node->myvariable in your page.tpl.php. For this, you don't even need to write a preprocess function, because Drupal already adds the current node object to the variables by default. (This happens in template_prepocess_page.) This means that you can simply add this to your page.tpl.php:

<?php if ($node->myvariable): ?>
  <div class="myvariable">
    <?php print $node->myvariable; ?>
  </div>
<?php endif; ?>


Twig is in Drupal 8 core, but you can use it in Drupal 7.
Check out this sandbox that provides twig as a theme engine.


As @kiamlaluno mentioned in the comment, neither the token API in core nor the token.module replaces tokens in node bodies.

For that, you need a module like Token Filter.


Make top level terms un-selectable in hierarchical taxonomy?

Using  Hierarchical Select module you can do that and configure it to Force the user to choose a term from deepest level, see the below screenshot.

and also take a look at this Taxonomy Term Reference Tree Widget module, I think it have the option to select only child term and I'm not sure about this module.


You can easily do this with the Conditional Fields module.

  Conditional Fields allows you to manage sets of dependencies between fields. When a field is “dependent”, it will only be available for editing and displayed if the state of the “dependee” field matches the right condition.
  When editing a node (or any other entity type that supports fields, like users and categories), the dependent fields are dynamically modified with the States API.


You have a separate submodule for using Hierarchical Select with menus, the same as for taxonomy terms.

So, for taxonomy terms you have Hierarchical Select Content Taxonomy submodule (hs_taxonomy), and for menus you have Hierarchical Select Menu (hs_menu) submodule, which you should use in your case.

Click on 'Show config' links on the demo page you have mentioned to see the details.


Module dependency can be defined as follows.

If a module A requires that module B to be enabled before the module A is enabled then, module A is dependent on module B.

In other words, if module A uses some of the functions that are available or defined in module B then it becomes mandatory to enable module B prior to enabling of module A, as not doing so may result in a "call to undefined function error"

Dependencies are very useful as it may save lot of your development time by allowing you to use functions that are already available in other modules, instead of rewriting the function in your module.

A module's dependencies are mentioned in the module's .info file. Following is an example from the forum module

name = Forum
description = Provides discussion forums.
dependencies[] = taxonomy
dependencies[] = comment
package = Core
version = VERSION
core = 7.x
files[] = forum.test
configure = admin/structure/forum
stylesheets[all][] = forum.css

The lines :

dependencies[] = taxonomy
dependencies[] = comment

declare or make the forum modules to be dependent on the 'taxonomy' and 'comment' modules. We can also say that the 'taxonomy' and 'comment' modules are the dependencies for the forum module.

In your module A you can add dependencies for module B and module C by adding the following lines in the a.info file of your module A .

dependencies[] = b
dependencies[] = c