Views Load More: Showing X number of item initially

Well you could use this workaround.

Have a view with the initial 3 (#1-3). Then add another view below it with an offset of 3, so it shows #4-6. Thus, it will load 3 rows at a time.

You could just show the views back to back on the page or you could use the Insert View module, and have it load the #1-3 view at the header of the 2nd view.


How do I correctly add cache information for breadcrumb parts?

Look at \Drupal\book\BookBreadcrumbBuilder::build() for an example. You'll want to add the cacheability metadata (or at minimum the cache tags) of the node/menu item John Doe.

So:

$breadcrumb->addCacheableDependency($entity);

You could have easily figured this out yourself: you're building a \Drupal\Core\Breadcrumb\Breadcrumb object… which implements RefinableCacheableDependencyInterface, and that interface lists all things related to cacheability.

I highly recommend you read https://www.drupal.org/developing/api/8/cache and all documentation it points to.


Displaying Line Item Fields in a View (SQL Error)

I was running into the same problem too. You have to create the relationship "Commerce Line Item: Order ID" and display the field "Commerce Order: Order ID" to get around the mysql error.

You can get the view by importing the following code:

    $view = new view();
    $view->name = 'commerce_line_items';
    $view->description = '';
    $view->tag = 'default';
    $view->base_table = 'commerce_line_item';
    $view->human_name = 'Commerce Line Items';
    $view->core = 7;
    $view->api_version = '3.0';
    $view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

    /* Display: Master */
    $handler = $view->new_display('default', 'Master', 'default');
    $handler->display->display_options['title'] = 'Commerce Line Items';
    $handler->display->display_options['use_more_always'] = FALSE;
    $handler->display->display_options['access']['type'] = 'none';
    $handler->display->display_options['cache']['type'] = 'none';
    $handler->display->display_options['query']['type'] = 'views_query';
    $handler->display->display_options['exposed_form']['type'] = 'basic';
    $handler->display->display_options['pager']['type'] = 'full';
    $handler->display->display_options['pager']['options']['items_per_page'] = '10';
    $handler->display->display_options['style_plugin'] = 'default';
    $handler->display->display_options['row_plugin'] = 'fields';
    /* Relationship: Commerce Line Item: Order ID */
    $handler->display->display_options['relationships']['order_id']['id'] = 'order_id';
    $handler->display->display_options['relationships']['order_id']['table'] = 'commerce_line_item';
    $handler->display->display_options['relationships']['order_id']['field'] = 'order_id';
    /* Field: Commerce Line Item: Line item ID */
    $handler->display->display_options['fields']['line_item_id']['id'] = 'line_item_id';
    $handler->display->display_options['fields']['line_item_id']['table'] = 'commerce_line_item';
    $handler->display->display_options['fields']['line_item_id']['field'] = 'line_item_id';
    /* Field: Commerce Order: Order ID */
    $handler->display->display_options['fields']['order_id_1']['id'] = 'order_id_1';
    $handler->display->display_options['fields']['order_id_1']['table'] = 'commerce_order';
    $handler->display->display_options['fields']['order_id_1']['field'] = 'order_id';
    $handler->display->display_options['fields']['order_id_1']['relationship'] = 'order_id';
    $handler->display->display_options['fields']['order_id_1']['link_to_order'] = 'customer';


How to navigate the URL after booking page

You should use form state to do redirects since users are interacting with forms. header is not really want you want and neither is drupal_goto.

The class(es) should return either a success/fail style response to the caller (in form submit) and based on that, you should handle the response and redirect with form_state redirect. The only job of your booking class should be to create a booking, it does not need to handle redirects or worry about any of that logic.

Also, no, absolutely don't do redirects from hook_init.

Vanilla example:

function myform_submit($form, &$form_state) {
  $book = new MyBookingClass();
  $form_data = $form_state['values'];

  // createBooking() returns either TRUE or FALSE

  if ($book->createBooking($form_state['values'])) {
    $form_state['redirect'] = '/booking-confirm';
  } else {
    // There was some sort of error.
    $form_state['redirect'] = '/booking-error';
  }
}


How do I take out the caching and bandwidth optimizations sections out of the performance window for a user?

You can use the #access property to do this.  You would just need to wrap things up in your own logic.

/**
 * Implements hook_form_FORM_ID_alter().
 */
function MYMODULE_form_system_performance_settings_alter(&$form, $form_state) {
  if (user_cant_access_this_stuff()) {
    $form['caching']['#access'] = FALSE;
    $form['bandwidth_optimization']['#access'] = FALSE;
  }
}

I am not 100% sure on those $form elements (this was taken from something similar I have on a site), so you may need to dpm() the $form.


How do I hide the link to the RSS feed on the term page?

Under "Structure", "Views", open the "Taxonomy term" view, on the Feed display, under Feed settings set Attach to to none.


Prevent Development modules from being added to configuration management

From Dave Reid on Twitter

Ignoring Development Modules

If you have a certain list of modules that should only be enabled on the development or staging server, then this may be done with the built-in --skip-modules option in the config-export and config-import commands.

For example, if you want to enable the 'devel' module on development systems, but not on production server, you could define the following configuration settings in your drushrc.php file:

# $command_specific['config-export']['skip-modules'] = array('devel');
# $command_specific['config-import']['skip-modules'] = array('devel');

You may then use drush pm-enable to enable the devel module on the development machine, and subsequent imports of the configuration data will not cause it to be disabled again. Similarly, if you make changes to configuration on the development environment and export them, then the devel module will not be listed in the exports.

http://www.drush.org/en/master/config-exporting/#ignoring-development-modules


Video.module: Rendering playablefiles programmatically

There are a few things that could do with attention...

A foreach statement needs an as keyword to keep a reference to the current object in the iteration (the docs explain it better than that, it's worth having a read). This error should throw an exception.
From the looks of the array each 'playablefile' is an object (not an array) so you need to access its members with -> not []. If the interpreter makes it this far this should also throw an exception.
You can also make use of the API and make your code language safe using the field_get_items() function

The resulting code should be:

$field_items = field_get_items('node', $node, 'field_video');
foreach ($field_items[0]['playablefiles'] as $file) {
  echo $file->uri;
}


How do I set the title tag for the maintenance page?

TEMPLATE_preprocess_maintenance_page changes only variables for maintenance-page.html.twig. But <title> is outputted in html.html.twig, so you have to choose another preprocessor template_preprocess_html. So you can use this code(don't forget to clean cache after it):

function mytheme_preprocess_html(&$variables) {
  $maintenance_mode = \Drupal::state()->get('system.maintenance_mode');
  if (!empty($maintenance_mode)) {
    $variables['head_title'] = (string)t('My Custom Maintenance Title');
  }
}


Rules- How can I copy the formatted text in one field to another?

I figured it out-- I needed to add :value after the body field, since the field value contains the summary, text format, and text value.

So for example, instead of profile:field-myfield, use profile:field-myfield:value.


Depending on your display requirements, you might be able to use a table format.  When using a table format, you have the option to set columns to "sortable".

Format section:

Sorting settings:


Remove login confirmation message programmatically

You can add a custom module hook to alter the login process and unset the messages. If you look at core's user.module you can see the various points where you can hook into the login functions.

This is one option (I think there are several and you may need to adjust based on your site's settings) You should be able to do something along these lines:

function YOURMODULE_user_login(&$edit, $account) {
  if ($account->uid) {
     if (isset($_SESSION['messages']['status'])) {
       unset($_SESSION['messages']['status']);
     }
  }
}


How to place all form buttons on top of the page, before the form, in all forms?

You can do that using hook_form_alter() and setting the weight of $form['actions'] to a very small negative number.  Note that this applies only those buttons wrapped in $form['actions']. For other buttons that they aren't, you should add them manually.

function YOURMODULE_form_alter(&$form, &$form_state) {
  $form['actions']['#weight'] = -1000;
  // a button that is not wrapped in actions.
  // assuming it's id is 'submit'
  $form['submit']['#weight'] = -1000;
}


How to define multiple file downloads for a single library in drush make

You are close, you should use destination instead:

libraries[jquery-json-min][download][type] = "file"
libraries[jquery-json-min][download][url] = "http://jquery-json.googlecode.com/files/jquery.json-2.3.min.js"
libraries[jquery-json-min][download][sha1] = "2a4615b93c65dd50f92117c570121035a0327fee"
libraries[jquery-json-min][destination] = "libraries/jquery-json"


Is there a non-WYSIWYG-module that lets me use Media ver. 2 images with multiple image styles?

As I can see Entity Image Style can be used with the Field collection module to achieve this task. However the Entity Image Style module is not yet a stable module. As per the logic this should achieve your goal.

Other resources:
Formatter Field module


How to run drush tests from the command line?

The test-run command was removed from Drush; the recommendation now is to simply run the scripts/run-tests.sh script in Drupal folder directly.

See: Running tests through command-line.


Do I have to create a module for just one _alter function?

No...

All alter hooks are also run for themes, so you don't have to create a module.

e.g.

function MYTHEME_entity_info_alter(&$info) {
  // ...
}


table styles not applied by bootstrap sub-theme

leymannx suggested twig debugging, which was super helpful. The solution I came up with was to copy the core/modules/forum/templates/forum-list.html.twig file into mytheme/templates and then modify it to take the table theming elements from the system/table.html.twig file in bootstrap.
Here's the end result:
{#
/**
 * @file
 * Default theme implementation to display a list of forums and containers.
 *
 * Available variables:
 * - forums: A collection of forums and containers to display. It is keyed to
 *   the numeric IDs of all child forums and containers. Each forum in forums
 *   contains:
 *   - is_container: A flag indicating if the forum can contain other
 *     forums. Otherwise, the forum can only contain topics.
 *   - depth: How deep the forum is in the current hierarchy.
 *   - zebra: 'even' or 'odd', used for row class.
 *   - icon_class: 'default' or 'new', used for forum icon class.
 *   - icon_title: Text alternative for the forum icon.
 *   - name: The name of the forum.
 *   - link: The URL to link to this forum.
 *   - description: The description field for the forum, containing:
 *     - value: The descriptive text for the forum.
 *   - new_topics: A flag indicating if the forum contains unread posts.
 *   - new_url: A URL to the forum's unread posts.
 *   - new_text: Text for the above URL, which tells how many new posts.
 *   - old_topics: A count of posts that have already been read.
 *   - num_posts: The total number of posts in the forum.
 *   - last_reply: Text representing the last time a forum was posted or
 *     commented in.
 * - forum_id: Forum ID for the current forum. Parent to all items within the
 *   forums array.
 *
 * @see template_preprocess_forum_list()
 *
 * @ingroup themeable
 */
#}
{% if responsive %}

{% endif %}
{%
  set classes = [
    'table',
    bordered ? 'table-bordered',
    condensed ? 'table-condensed',
    hover ? 'table-hover',
    striped ? 'table-striped',
    sticky ? 'sticky-enabled',
  ]
%}

      {{ 'Forum'|t }}
      {{ 'Topics'|t }}
      {{ 'Posts'|t }}
      {{ 'Last post'|t }}

  {% for child_id, forum in forums %}

        {#
          Enclose the contents of this cell with X divs, where X is the
          depth this forum resides at. This will allow us to use CSS
          left-margin for indenting.
        #}
        {% if forum.depth > 0 %}{% for i in 1..forum.depth %}
{% endfor %}{% endif %}

            {{ forum.icon_title }}

{{ forum.label }}

          {% if forum.description.value %}

{{ forum.description.value }}

          {% endif %}
        {% if forum.depth > 0 %}{% for i in 1..forum.depth %}
{% endfor %}{% endif %}

      {% if forum.is_container == false %}

          {{ forum.num_topics }}
          {% if forum.new_topics == true %}

            {{ forum.new_text }}
          {% endif %}

        {{ forum.num_posts }}
        {{ forum.last_reply }}
      {% endif %}

  {% endfor %}

{% if responsive %}

{% endif %}

The table now seems to render sensibly;


Please check the below format:

function mymodule_form_alter(&$form, $form_state, $form_id) {
  if ($form_id === 'form_id_goes_here') {
    // Code here
    $form['#submit'][] = '_mymodule_test_registration_submit';
  }
}

function _mymodule_test_registration_submit($form, &$form_state) {
  // Code here
  $form_state['redirect'] = 'path1/path2/mypage';
}


I needed to overide a function in my template.php in my theme:

function blogbuzz_views_bulk_operations_fields_action_form($form) {
  $output = '';
  $access = user_access('Use PHP input for field settings (dangerous - grant with care)');
  if ($access && $form['#settings']['php_code']) {
    $output .= t('
Using the Code widget

Will override the value specified in the Field widget.

Should include &lt;?php ?&gt; delimiters.

If in doubt, refer to devel.module \'Dev load\' tab on a content page to figure out the expected format.

', array('@link_devel' => 'http://www.drupal.org/project/devel')
    );
  }
}


Redirect anonymous users to the register page

You should take a look at the Rules module and setup a rules that redirects anonumoys users to the user/register page.


Drupal to Salesforce - Check if record exists before create

I have solved this myself utilizing the hooks provided in the Salesforce Suite module. I wrote details about it in a 2 part blog post.

Customize Syncing Between Drupal Commerce and Salesforce – Part 1


What is the difference between core.entity_form_mode and core.entity_form_display?

entity_form_mode would be the form mode (/admin/structure/display-modes/form)

37 - Form mode foo available for use on node entities (shows as
content on the link above)
38 - Form mode register available on
user entities.

entity_form_display is the configuration for that mode on a specific bundle - how the fields are arranged (/admin/structure/types/manage/book/form-display/{form_mode}) - in your case form_mode would be foo.

36 - Form display settings for the default display on the book bundle (content type) of the node entity.

The reason 36 is default is because you have arranged your form display (/admin/structure/types/manage/book/form-display) but you haven't enabled your foo mode.

At the bottom of that page is a fieldset called "Custom display settings". Expand that and you can enable your foo display for that content type.

In the picture, I have a created a form mode called Inline Entity Form, yours should say foo


Countries Additional Data Tokens not working

It apperas to be a known issue with some of the country metadata so the current solution is to use the following slightly different continent token:[node:field-prgm-country:continent]/[node:field-prgm-country]/[node:title]


Group search results by content type and limit count

You can increase the page limit by apache solr hook

function custom_apachesolr_query_alter($query) {
  if(strpos($_SERVER['REQUEST_URI'],'/bundle/') == false)
    {
  $query->replaceParam('rows', '400'); // Note that high value increases response time
  }
}


Mail subject and body remain empty using mailManager

Remove the empty array tag from body as below.

$message['body'] = $params['message'];


You can do it easily directly in the configuration page of block by adding <none> in the title field setting.


How to develop a page which displays data from more than one content type/table

As mentioned by the commenters to your question, use the Views module. Here's some documentation to get you started.

In general, it is an enhanced query/list/menu builder, with which you can build most of your site's general pages, blocks and lists.

You can join multiple tables (or content types) in any way Drupal's structure lets you, and output the results as

a table of columns and rows (one record per row),
a grid with multi records per row,
short lists used to make menus,
and so much more.

Views should be in any newb tool chest of modules (opinion). It's invaluable for examining your site content, and in learning Drupal's content relationships (after you get beyond it's learning curve). It's now even in Drupal 8 core.


Views contextual filter - related nodes as an offset from a node's creation date

I think in this case you can use panels for that
In views create a content pane

Then add contextual filter based on Created Date
and in "PANE SETTINGS" click on "Argument input" and use this Settings :

this will export the node's created date from it and pass it through arguments to views.

this will give you an Panel's pane , to add it to your view you can use Page manager module .


Since you've got each employee in his/her own node, you can use views to show pages or blocks/panels with all employees (or certain employees depending on the filters you set on the view).


admin toolbar not showing sub-navi in Firefox any more

It was a bug in the admin menu module. I think it was fixed in the latest stable version (if not in stable, then in dev). Try updating to the latest stable version of admin menu (currently 7.x-3.0-rc5).


I can't imagine why your site is crashing using the two functions you link to (Drupal calls them both internally so it certainly shouldn't be), but you can use the following custom query to grab that data directly from the database:

$query = db_select('block', 'b')
  ->condition('theme', $your_theme_name)
  ->condition('status', 1)
  ->condition('region', -1, '<>');

$query->addExpression("CONCAT(module, '_', delta)", 'delta');

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

// $deltas now contains a list of deltas for all enabled blocks in the provided theme


Restricting view of nodes on taxonomy aggregation pages?

You're looking for hook_node_access_records:

http://api.drupal.org/api/drupal/modules%21node%21node.api.php/function/hook_node_access_records/7


Yes, that's correct.

Once you've added the file, clear the caches and the new template will take effect.


Why am I getting empty input value on expose filter $form_state variables for taxonomy?

Apply little trick and my issue solved.
Used default taxonomy search and hide it.

(function($) {

Drupal.behaviors.tushar_1 = {
  attach: function (context, settings) {
    $('#edit-shs-term-node-tid-depth').change(function(){
      var eid = $('#edit-shs-term-node-tid-depth').val();
      $('#edit-tid ').val(eid);
    });
  }
};

})(jQuery);

Solved my issue.


How to count the number of anonymous users that are currently using the site?

The admin_menu module does this, and provides this function:

/**
 * Counts how many users are active on the site.
 *
 * Counts how many users have sessions which have been active since the
 * specified time. Can count either anonymous sessions or authenticated
 * sessions.
 *
 * @param $timestamp
 *   A Unix timestamp. Users who have been active since this time will be
 *   counted. The default is 0, which counts all existing sessions.
 * @param $anonymous
 *   TRUE counts only anonymous users. FALSE counts only authenticated users.
 *
 * @return
 *   The number of users with sessions.
 *
 * @todo There are mostly no anonymous sessions anymore. Split this into a
 *   separate module providing proper user statistics.
 */
function admin_menu_session_count($timestamp = 0, $anonymous = TRUE) {
  $query = db_select('sessions');
  $query->addExpression('COUNT(sid)', 'count');
  $query->condition('timestamp', $timestamp, '>=');
  $query->condition('uid', 0, $anonymous ? '=' : '>');
  return $query->execute()->fetchField();
}

It returns the count of users who have been active in the past (default) 15 minutes like this:

    function admin_menu_get_user_count() {
      $interval   = REQUEST_TIME - variable_get('user_block_seconds_online', 900);
      $count_anon = admin_menu_session_count($interval, TRUE);
      $count_auth = admin_menu_session_count($interval, FALSE);

      return t('@count-anon / @count-auth', array('@count-anon' => $count_anon, '@count-auth' => $count_auth));
}


The php file of the form is in a subfolder, but the class name in getForm() does not reflect this.

Change the location of the php file from

custom_module/src/Form/UserType/UserType.php

to

custom_module/src/Form/UserType.php

and

namespace Drupal\custom_module\Form\UserType;

to

namespace Drupal\custom_module\Form;


How to get count on how many times a term is used on a node

Here's the query you're going for.

SELECT count(*) AS count, tid FROM taxonomy_index GROUP BY tid ORDER BY count DESC LIMIT 100;

You'll need to use AddExpression to get the count in there.

$query = $this->database->select('taxonomy_index', 'ti');
$query->addField('ti', 'tid', 'tid');

$query->addExpression("count(*)", 'count');
$query->groupBy('ti.tid');
$query->orderBy('count', 'DESC');
$query->range(0, 50);

$data = $raw_data = $query->execute()->fetchAll();

Here's how you might convert the data to a render array:

$term_storage = \Drupal::entityTypeManager()->getStorage('taxonomy_term');

$build = [];
foreach ($data as $count_group) {
  $term = $term_storage->load($count_group->tid);
  $label = $term->label();
  $link = $term->toLink();
  $link->setText($this->t($label . ' (' . $count_group->count . ')'));
  $build[] = $link->toRenderable();
}

return $build;


Alter a query using hook_views_query_alter() to filter a view by month

I managed to get my code working, if anyone is stucked at the same point, you have to use addWhereExpression instead of addWhere.  Here's what it looks like overall.

function HOOK_views_query_alter(ViewExecutable $view, QueryPluginBase $query){
    if($view->id() == 'calendar'){
        $definition = array(
            'table' => 'node__field_precise_date',
            'field' => 'entity_id',
            'left_table' => 'node_field_data',
            'left_field' => 'nid',
            'extra' => [ // These are extra conditions views adds by default, I just copied them so it looks like any filter.
                0 =>[
                    'field' => 'deleted',
                    'value' => 0
                ],
                1 => [
                    'left_field' => 'langcode',
                'field' => 'langcode'
                ]
            ]
        );
        $join = Views::pluginManager('join')->createInstance('standard', $definition);

        $query->addRelationship('node__field_precise_date', $join, 'node_field_data');
        // ouptuts "LEFT JOIN {node__field_precise_date} node__field_precise_date ON node_field_data.nid = node__field_precise_date.entity_id AND (node__field_precise_date.deleted = '0' AND node__field_precise_date.langcode = node_field_data.langcode)"

        $date_format = $query->getDateFormat("node__field_precise_date.field_precise_date_value", "m")." = :value";
        $query->addWhereExpression(2, $date_format, [":value" => 12]); // Where 12 is the month I need.
    }
}

I'm still opened to better ideas so feel free to share them !


How do I add a Javascript library to a field formatter?

In your formatter's viewElements

public function viewElements(FieldItemListInterface $items, $langcode) {
$elements = [];
foreach ($items as $delta => $item) {
  $elements[$delta] = array(
    '#theme' => 'theme_name_if_any',
    '#variablenametobepassed' => $this->viewValue($item) * 20, // any other preprocessing
    '#attached' => array('library'=> array('module_name/library_name')),
  );
}

return $elements;
}


How can I format a cell to not wrap in a themed table with the Antonelli/Bartik theme?

one way would be setting the min-width in the css to some value.
this would ensure no matter what device it is being viewed it will set this minimum width.
google up for sum css trick.


Interface translation - Body, Title built-in interface

If having it only in Dutch is enough for you, you could change it to Dutch directly in the Edit content type form; go to Admin -> Content -> Content types, select edit for the one you want to change. You can set a title and body label in the "Submission form settings" fieldset.

There is a bug report open for this, see http://drupal.org/node/1016006.

I also found some reports that this should work now with multiple languages, with i18n: http://drupal.org/node/149349#comment-1135605.


I have a site that is translated in English and French - can't change "Home" link in menu

Most likely, the "Home" menu link is coming from the UI text in Drupal Core.

You should be able to enable the "Interface Translation (locale)" module and then obtain .po or .pot files for the respective language (as described on the Drupal.org internationalization page).

Refer to https://www.drupal.org/node/1814954 for information about editing the .po/.pot files and https://www.drupal.org/node/314231 for info about obtaining them.


How to display a author picture in comment form?

I don't think you need to do coding for your requirement. You can take help from this documentation for same - https://drupal.org/node/22271. It says for D7 :

Enable user pictures for Drupal 7

Navigate to Configuration > People > Account settings.
In the Personalization settings, select Enable user pictures.
For Picture directory type pictures
Under Picture display style, select thumbnail (you can change the size settings
Click "Save configuration".

Next, ensure your user pictures display in your theme. These are enabled by default in Bartik, the default theme of Drupal 7 , so you may have to check this with any new theme you add.

Go to Appearance and click "Settings" for the theme you have enabled as default.
In the Toggle display settings, select User pictures in posts and/or User pictures in comments.
Click "Save configuration".

If your theme doesn't support user pictures, then you should look for bartik & apply same structure for TPL.


Remove default › between breadcrumbs in panels breadcrumbs

If you have your own custom theme (or a sub-theme you can edit), you can override theme_breadcrumb(). Actually I'm not sure this is completely supported by panels_breadcrumbs but I assume it is.

THEMENAME_breadcrumb() {
  $breadcrumb = $variables['breadcrumb'];

  if (!empty($breadcrumb)) {
    // Provide a navigational heading to give context for breadcrumb links to
    // screen-reader users. Make the heading invisible with .element-invisible.
    $output = '
' . t('You are here') . '
';

    $output .= '
' . implode(' CUSTOM SEPARATOR ', $breadcrumb) . '
';
    return $output;
  }
}

EDIT:
Alternatively, there are other breadcrumb-customizing modules that allow to specify a custom separator between the breadcrumb items.


You probably have a content access module (e.g. Content Access) installed that's conflicting with the default access settings.


cck fieldgroup tabs appear but all fields in one tab

Check the permissions to ensure the fields are available to the anonymous users.


Google Map will not show on new ajax page load

You can do it this way:

var success = Drupal.ajax.prototype.success;

Drupal.ajax.prototype.success = function(xmlhttprequest, options) {
    success.apply(this, arguments);
    initialize();
}

This will call initialize (make a note about your init function - it' called initialiSe) just after successful Drupal.ajax call.

Using this code

success.apply(this, arguments)

we ensuring ourselves that nothing interrupt normal behaviour of the original handler.


Drupal, like most Content Management Systems, has security systems in place to filter most javascript during submission so site members can’t do ugly things via scripting. In most cases, that’s a good thing. When you’re scratching your head trying to figure out a way around it, not so much.

You can hard-code a script into the template, if you need it on all the pages and it works. But just adding a a single, inline javascript into a Drupal node is not as easy as it seems.

There may well be a prettier way to do this, but here is a quick way out in case you need it:

First,  put the script on your server, someplace it’s easy to find. I usually have a  “scripts” folder in my sites/all folder.

Second, when do your post, set your input filter to PHP

Third, do a php include where you’d like to place the script. Something like this:

<?php include('sites/all/scripts/my_javascript.js'); ?>

And there you go. Inline javascript. I guess in the most common scenarios Drupal is used for, having <script> available without filtering would be very foolish security wise. Unfiltered js in a webform makes for a very insecure setup.


Replacement pattern for one value of a multivalue field in views

I had a similar problem, although not exactly the same.  Here's what worked for me:
 1. Enable the module entity_token which is a sub-module of Entity.
 2. Use field-tagging:0 (with a dash not an underscore).  Depending on exactly what you are trying to do, you may need a further parameter such as field-tagging:0:url.

It seems that field_tagging and field-tagging are two different things.  The first one doesn't accept :0.


How to render alt and title texts of image file entities using a theme function

The logic is pretty easy, you can just preprocess theme_image():

function MYTHEME_preprocess_image(&$vars) {
  $vars['attributes']['alt'] = 'alt';
  $vars['attributes']['title'] = 'title';
}

If you're using any of the standard image display formatters they'll eventually be passed through theme_image() so that should work for all fields.

I'd strongly advise you consider not doing this though. The point of an alt tag is to describe the image to parties who can't interpret it in its original form (visually impaired people, robots, text only browsers, search engines, etc)

By setting the alt for every image to the same string, you're making your site quite inaccessible to those groups of visitors. And since Google and others assign a reasonable weight to alt text, you won't be doing your SEO any favours either.


The drush command 'sql dump' could not be found

The actual command is sql-dump not sql dump

drush -v sql-dump --result-file=DrupalBackups/nameofsqldb5.sql

From drush help:

  sql-dump              Exports the Drupal DB as SQL using mysqldump or
  equivalent.


Lightest setup to sell only digital content with no physical products?

You could get by using Drupal Commerce with just the core modules, some custom Rules, and your preferred payment gateway module. The modules and features you pointed to (shipping, inventory, etc.) and the ones you didn't point out have nothing to do with Drupal Commerce itself. They're all optional contributed modules and don't have to be added if you don't need them.

It's possible you saw a demo site running Commerce Kickstart 2.x. That is a distribution of Drupal that includes Drupal Commerce and a wide variety of contributed modules to make it function more like a robust eCommerce application out of the box. At its core, Drupal Commerce is much lighter weight, and I think you'll find its compatibility with Rules combined with the Content Access / Access Control List modules to be very helpful in selling access to digital content on your site.


Set a date field equal to "current time" + "5 minutes" using tokens

I can't think of a solution with just tokens. Here is a quick and dirty solution without tokens

Setup your Article datetime field so that has a default relative time of +5 minutes

You can hide this field with css so the user will not change it or you can do it in a hook_form_alter function in your MODULENAME.module file

// adjust node_article_form for your content type
if($form_id == 'node_article_form'  || $form_id == "node_article_edit_form"){
  $form["field_article_datetime"]['widget'][0]['value']['#attributes']['readonly'] = 'readonly';
}

Of course if a user takes much time to fill the form the set datetime might not reflect exactly the NODE CREATION TIME +5 minutes (as a datetime is set on form creation time)

If the above is not good enough you can probably use hook_entity_presave to adjust the time to be EXACTLY the creation time +5 minutes.

function MODULENAME_entity_presave(Drupal\Core\Entity\EntityInterface $entity) {
  // adjust article to reflect your content type
  if ($entity->bundle() == "article" && $entity->isNew()) {
    $created = $entity->created->value;
    date_default_timezone_set('GMT');
    $createdadd5 = date('Y-m-d\TH:i:s', $created + 5 * 60);
    $entity->field_article_datetime->value = $createdadd5;
  }
}

NOTE: if you want to update the timer even on node update you can just delete the && $entity->isNew() part.


location ~ \.pdf$ {
  try_files $uri =404;
}


When creating a content type programmatically, is there a way to disable promoting to the front page by default?

Whether nodes of a particular content type are promoted to the front page by default is stored in the Drupal array variable node_options_{content type name}:

$node_options = variable_get('node_options_{content type name}', array());
$promote_key = array_search('promote', $node_options);
if ($promote_key !== false) {
  unset($node_options[$promote_key]);
  variable_set('node_options_{content type name}', $node_options);
}


Drupal 8, use variable defined from custom form in custom template twig

Like javascript you need to use bracket notation to get hash key variables:

{{ element['#foo'].key_a }}


In Drupal 7, you can add a CSS class to the <body> tag for your book. For nodes, you have the class added by default. For example page-node-2056, for the /node/2056 path.

For Book nodes, you might add the book ID inside your template.php theme file, in the theme_preprocess_html function:

function MYTHEME_preprocess_html(&$vars) {
  // If on an individual node page, add the book ID to body classes.
  if ($node = menu_get_object()) {
    if (isset($node->book['bid'])) {
      $vars['classes_array'][] = drupal_html_class('book-id-' . $node->book['bid']);
    }
  }
}

You can then take the ID for each book and add all the style definitions in a single CSS file. Something like the following:

.book-id-xxx {
  /* Style for book xxx. */
}
.book-id-yyy {
  /* Syle for book yyy. */
}
... and so on

Would it make sense for what you need?


Blocking JS from being executed more than once

I adjusted your code to match the one from the docs.

MYMODULE/js/myscripts.js:

(function ($, Drupal) {
  Drupal.behaviors.myModuleBehavior = {
    attach: function (context, settings) {

      $('.block-facets-ajax', context).once('myModuleBehavior').each(function () {
        // Apply the myModuleBehavior effect to the elements only once.
        $(this).wrapAll('

');
      });

    }
  };
})(jQuery, Drupal);

To get that working properly you also need to require core/jquery.once for this script.

MYMODULE.libraries.yml:

myscripts:
  version: VERSION
  js:
    js/myscripts.js: {}
  dependencies:
    - core/jquery
    - core/jquery.once


Programmatically add a taxonomy term to an existing content type

You should check out the Views Bulk Operations (VBO) module. It allows you to create a View to generate a list of target nodes (or other things like Users) and perform an action on each of those nodes. One fo the available actions is modifying the taxonomy terms used on these nodes. This is actually the exact example used in the documentation for VBO on d.o. It seems like this is exactly what you're looking to do, just not actually programmatically. Maybe that's ok... but if not, you can create this VBO and then execute it programmatically using views_bulk_operations_execute.


You might want to go about this in a different way, like adding a views handler to the module, but I took the question as how to get data from "uc_crowdfunding_products" table into Views. It also seems like the tables mentioned had Node IDs so I made a relationship there. You were pretty close with your code.

Before getting too fancy with relationships and joins, make sure the following basic code works. It adds the ability to list the target field from the products table and some field from the features table with any node associated with them. You'll want to add the node revisions tables if you have revisions on your site. You can also look at the Data project to give you an idea of how to adopt database tables into Drupal.

/**
 * @file
 * Views hooks for UC crowdfunding projects.
 */

/**
 * Implements hook_views_data().
 */
function uc_crowdfunding_views_data() {
  $data['uc_crowdfunding_products'] = array(
    'table' => array(
      'group' => 'Crowdfunding',
      'base' => array(
        'field' => 'nid',
        'title' => t('Crowdfunding Products'),
        'help' => t('Data for each crowdfunding product.'),
        ),
      'join' => array(
        'node' => array(
        'left_field' => 'nid',
        'field' => 'nid',
         ),
      ),
    ),
  );

  $data['uc_crowdfunding_products']['nid'] = array(
    'title' => t('Example content'),
    'help' => t('Some example content that references a node.'),
    'relationship' => array(
      'base' => 'node',
      'field' => 'nid',
      'handler' => 'views_handler_relationship',
      'label' => t('Example node'),
    ),
  );

  $data['uc_crowdfunding_products']['target'] = array(
    'title' => t('Crowdfunding Target'),
    'help' => t('Just a numeric field.'),
    'field' => array(
      'handler' => 'views_handler_field_numeric',
      'click sortable' => TRUE,
    ),
    'filter' => array(
      'handler' => 'views_handler_filter_numeric',
    ),
    'sort' => array(
      'handler' => 'views_handler_sort',
    ),
  );

  $data['uc_product_features'] = array(
    'table' => array(
      'group' => 'Crowdfunding',
      'base' => array(
        'field' => 'nid',
        'title' => t('Crowdfunding something'),
        'help' => t('Data for each crowdfunding product.'),
        ),
      'join' => array(
        'node' => array(
        'left_field' => 'nid',
        'field' => 'nid',
         ),
      ),
    ),
  );

  $data['uc_product_features']['nid'] = array(
    'title' => t('Example content'),
    'help' => t('Some example content that references a node.'),
    'relationship' => array(
      'base' => 'node',
      'field' => 'nid',
      'handler' => 'views_handler_relationship',
      'label' => t('Example node'),
    ),
  );

  $data['uc_product_features']['some_field'] = array(
    'title' => t('Crowdfunding field'),
    'help' => t('Just a numeric field.'),
    'field' => array(
      'handler' => 'views_handler_field_numeric',
      'click sortable' => TRUE,
    ),
    'filter' => array(
      'handler' => 'views_handler_filter_numeric',
    ),
    'sort' => array(
      'handler' => 'views_handler_sort',
    ),
  );

  return $data;
}


How to hide a form element having a certain class in ajax callback in form?

AJAX Commands are supposed to be returned in the callback function, not printed. Also, you have to give a CSS valid selector.

Try this:

function _change_table_product_type(&$form,&$form_state){
  $commands = array();
  $product_type = $form_state['values']['field_product_type_select']['und'][0]['value'];
  drupal_set_message($product_type);
  $commands[] = ajax_command_invoke('.display-' . $product_type, 'show');

  return array('#type' => 'ajax', '#commands' => $commands);

}

You can show the actual selector that code generates and test it in the JavaScript console. Just type:

 jQuery('CSS_SELECTOR').show();

If element is shown your CSS selector code is right.


How to add a heading at the top of node/add or node/edit?

If you mean to change the title of the page you can do this. This will make all node add form titles "Create new [content type]" instead of "Create [content type]".
It doesn't change the edit form because it doesn't make sense to put "new" in the title there because it is not new content, you are editing existing content.

Create a new custom module that implement this:

/**
 * Implements hook_form_BASE_FORM_ID_alter().
 */
function MODULE_NAME_form_node_form_alter(&$form, &$form_state, $form_id) {
  // For the node add form.
  if (!$form['nid']['#value']) {
    // Add "new" to the page title.
    $node_types = node_type_get_names();
    drupal_set_title(t('Create new @type', array('@type' => $node_types[$form['#node']->type])));
  }
}


solved it using below code:

$file = \Drupal\file\Entity\File::load($content->resumefid);
$filelink = file_create_url($file->getFileUri());

$url = Url::fromUri($filelink);
$external_link = \Drupal::l(t('Download Resume'), $url);

  $rows[] = array(
    'data' => array(
      \Drupal::l($id, $editUrl),
      $content->name.' '.$content->lname,$content->number,$external_link,
      \Drupal::l('Delete', $deleteUrl)
    ),


'Edit' tab does not appear on user's account page?

Oceanescence, some times people have disabled or moved the tabs block. If you are using a custom theme try switching to Bartik and see if it pops up.

If not try digging into the permissions. Just log in as Admin 1 and see if the tabs show up.


The rule isn't running because of my fault in the parameter settings the parameter commerce_customer is giving problems, I get an error that says: "Missing configuration for parameter commerce_customer".
How can I get to this information in my component?

It looks like you have a mismatch in the variables of your rules component (which has 3 of them) and the rule which invokes that rules component (which only passes a value for the first variable selected_line_item).
Here is what I suggest you try to get the 2 remaining variables for your rules component fixed:

commerce_order: in your rule (which invokes the rules component), add the value of it as your 2nd variable (to actually pass that value to your rules component). For sure you have a token available to actually pass it (= commerce-order), since your rule already refers to commerce-order:commerce-line-items also (which you would not be able to do if you wouldn't have commerce-order).

commerce_customer: just remove (delete) that as your 3rd variable in your rules component. It seems you don't need to "pass" that as a variable, as per the (2nd) entity_fetch included in your rules component. Whereas this (2nd) entity_fetch will return you that entity_fetched (BTW, a terribly bad name IMO, consider changing that to something more meaningful like fetched_user, or even better fetched_customer).
Whatever you end up using (i.e. entity_fetched, fetched_user, or fetched_customer) that's what you can then use within the body of your eMail (any of the tokens related to it).


How to achieve the use exposure filter of views, head Title Update？

1) Add Taxonomy term: Name as a field

Check Exclude from display
Uncheck Link this field to its taxonomy term page

2) Click on Title: and put [name]


How to display blogs related to particular taxonomy term name

You don't need a contextual filter for this. The only thing you need is an exposed filter of the taxonomy you created. You can then use Better Exposed Filters to create links instead of a select list or checkboxes.


The way to achieve that was adding a relationship for the referenced entity (authors in my case). As a result, all the fields from the referenced entity become available in the current content type.

After adding a relationship, I created and exposed filter for author's name and in the "Relationship" drop-down in the filter settings selected the newly created relationship.


Just as structured programming revolutionized system building, modern web sites have strived for a conceptual structure. Today we try as far as possible to separate information, process and presentation. Think of the three as a venn diagram of overlapping circles: content, function, and theme.

Images and text are information, and the core and modules necessary to work with them are function.

The theme is the look and feel, the overlap is your information architecture. In Drupal, you can retain the same function and information, and completely change the presentation by changing the theme.

Think of it as structured programming taken to the next level.


Drush installation - setting symlink to /usr/local/bin/drush is a must?

This may not answer the question directly, but a preferred and much simpler way to install Drush, is to install it through the Composer.

Installing Composer

See Composer's website for greater detail.

curl -sS https://getcomposer.org/installer | php
# If the above code fails, use this one.
# php -r "readfile('https://getcomposer.org/installer');" | php
sed -i '1i export PATH="$HOME/.composer/vendor/bin:$PATH"' $HOME/.bashrc source $HOME/.bashrc

Installing Drush

See Drush instructions on GitHub for greater detail.

To install Drush 6:

composer global require drush/drush:6.*

Or to install Drush 7:

composer global require drush/drush:dev-master

Update

Per @leekit, he was able to solve his original issue by substituting the symbolic link with export PATH="$PATH:/path/to/drush:/usr/local/bin". For that and other alternatives, refer to step 3 of Install - Manual, on Drush instructions on GitHub.


For a list with checkboxes I suggest looking at this issue about using Views Bulk Operations.


Role weight is only used for some lists in the backend. It has no effect on the permissions that a user has.

The permissions or a user are always the sum of all permissions of all roles that he has, you can not remove permissions with roles.

All "users" either have the anonymous (when they're not a user, basically) or the authenticated user role. You can give anonymous users more permissions than authenticated users. But you can never remove any permission granted by the authenticated user role through another role.

This doesn't answer your question but considering the above, I don't think  you are asking the right question. Whatever problem you are trying to solve exactly, setting role weights is not the answer ;) If this is not enough to solve your problem, then try explain the actual problem that you are trying to solve.

Edit:

Anyway, to actually set the role weight in e.g. hook_install(), you can do this:

$role = \Drupal\user\entity\Role::load('anonymous');
$role->setWeight(0);
$role->save();

Again, keep in mind that this has no effect on the permissions a user has, it just affects how the roles are listed on the role and permission administration pages.


Force View to be displayed only in a specific domain

One solution would be to use hook_preprocess_html()

function MYTHEME_preprocess_html(&$variables) {
  global $_domain;
  if (arg(0) == 'myViewPath' && $_domain['subdomain'] != 'blog.example.com') {
    drupal_goto('http://blog.example.com/myViewPath', array(), 301);
  }
}

Note that the global $_domain variable is provided by the Domain Access module.

Alternatively, in a custom module you could use hook_boot()

function MYMODULE_boot() {
  if (arg(0) == 'myViewPath' && $_SERVER['HTTP_HOST'] != 'blog.example.com') {
    exit(header('Location: http://blog.example.com/myViewPath', TRUE, 301));
  }
}


How do I submit call handler on radio button selection?

This should do it:

$(function() {
  $('input[type="radio"]').on('change', function() {
    $(this).parents('form').submit();
  });
});

You might want to qualify the selector for $('input[type="radio"]') to the scope of the form you're working with, else if you include this in a JavaScript file that's accessed on many different pages, you'll definitely run into problems!

Demo:  http://plnkr.co/edit/8448bjiywnVtbT3CV6s6?p=info


Testing if email was sent in Kernel test

Look at core tests that utilize email. For example:

MailCaptureTest::testMailSend()
EmailActionTest::testEmailAction()

The tests demonstrate ways to inspect the plugin.manager.mail service for signs that mail was successfully sent.


Drupal has specific functions that can help with communicating with a web service, and handling JSON input.
Drupal 7 has the following functions:

drupal_http_request() is the function to make a HTTP request to a remote site, and it handles GET, POST, PUT or any other HTTP requests; it also handles redirects.
drupal_http_build_query() transform an array in an rawurlencode()-d string.
drupal_json_decode() decodes a JSON string in PHP code.
drupal_json_encode() encode a PHP variable into a string that is handled by JSON.

With those functions you can write your own custom module to make requests to a site implementing a web service.

If there are some restrictions about the number of requests that can be done to the web server, you can use the Drupal functions to cache the result obtained from the web server:

cache_get(), to get the data saved in the cache
cache_set(), to save the data in the cache

To notice that Drupal supports more than one cache bin, and modules can use their own cache bins, when necessary.
Drupal supports also cache items that are automatically removed at the successive cache swipe (see the description for the CACHE_TEMPORARY constant). Implementing hook_flush_caches(), the modules allow to the administrator users to clean the cache used by the module when the "Clear" button on the "Performance" page is clicked, or any times a module calls drupal_flush_all_caches().

In Drupal 7, cache data for frequently used data are associated with a static variable handled with drupal_static(). When the data is really frequently used when outputting the same page, code similar to the following one is used:

  // Use the advanced drupal_static() pattern, since this is called very often.
  static $drupal_static_fast;
  if (!isset($drupal_static_fast)) {
    $drupal_static_fast['implementations'] = &drupal_static(__FUNCTION__);
  }
  $implementations = &$drupal_static_fast['implementations'];

  // …

  // Fetch implementations from cache.
  if (empty($implementations)) {
    $implementations = cache_get('module_implements', 'cache_bootstrap');
    if ($implementations === FALSE) {
      $implementations = array();
    }
    else {
      $implementations = $implementations->data;
    }
  }

The code is part of module_implements().


BlockContent::load for addtoany_block returns null

The addtoany_block is not a block content, but it's a plugin block.
So if you want to get the its build programmatically you should:
1. Get the block configuration (addtoany_block settings).
2. Create an instance of the block.
3. Get the build.

Try the following:

// Block manager.
$block_manager = \Drupal::service('plugin.manager.block');
// Load Block settings / Settings.
$addtoany_config = \Drupal::config('addtoany.settings')->getRawData();
/** @var \Drupal\addtoany\Plugin\Block\AddToAnyBlock $plugin_block */
$addtoany_block = $block_manager->createInstance('addtoany_block', $addtoany_config);
// Get Block build.
$build = $addtoany_block->build();


Implement javascript inside body, error: jQuery is not defined

In Drupal 8 it is not a good idea at all. You must define a library and put your js in a seperate file.

Here is a link to how to do it

Libraries in Drupal 8

Then if you want to write jquery you just need to add a dependency on core/jquery, also explained on the link.

If you want to attach a library to a twig function, you can do like this:

{# In a Twig template we attach the library. #}
{{ attach_library('modulename/libraryname') }}


To set a Date Field via REST in Drupal 8, you can do this:

// Build the JSON payload.
var node = {
  "type":[{"target_id":"article"}],
  "title":[{"value":"Hello World"}],
  "field_start":[{"value":"2017-07-21T18:11:11"}]
};

// Then POST the payload to Drupal...
$http.post('https://example.com/entity/node', node);


How to show available drush commands per module with a drush command?

You can use the --filter feature of Drush. For example, you can use drush --filter=features to get all the commands available from the Features module, or drush --filter=views to get all the Drush commands available from the Views module.

You could then also pipe that output into a file if you wanted (e.g. drush --filter=views > views_drush_commands.txt).

You can find the docs on the Drush homepage.


Apply hook_menu to all nodes except node593

You're probably overthinking it; making that decision in the page callback seems like the easiest solution:

function MYMODULE_menu_alter(&$items) {
  $items['node/%node']['page callback'] = 'MYMODULE_node_page';
}

function MYMODULE_node_page($node) {
  if ($node->nid == 593) {
    return node_page_view($node);
  }
  else {
    // ...
  }
}


You could do this using three views.

Make the center part of the screen a view which uses a URL argument to know which node to pull the image/video from.
Make the listing of possible photos a view. Make each link to view #1 and passes in the node id.
Make the listing of possible videos a view. Make each link to view #2 and passes in the node id.

To put all three views on one page you have several options. You could use the module Panels or make each view a block and put them into different regions.


How to show specific views for certain combinations of taxonomy terms?

In a custom module you could implement the hook hook_views_pre_view()

e.g.

function my_module_views_pre_view(&$view, &$display_id, &$args) {

    if ($view->name == 'the_view') {
        // if url matches certain pattern
        $view->set_display('your display');
    }

}


Node export import into different node numbers

Node ID numbers is an auto-incremented field in the database that is global for the entire Drupal installation. Attempting to replicate the exact Node ID in Drupal can be difficult and cause serious problems if handled incorrectly.

If your issue is URLs, one option is to make a 301 alias for the old URLs to the new URLs. There are modules to easily create the redirects like the Redirect module.

If you must maintain the ID numbers then the solution will have to be custom migration code. The migration process will recreate the nodes in the new site and account for any node deletions.


Self-hosted development and deployment control panel - does this exist?

Aegir in and of itself is definitely the route I would recommend.

If you want a complete server + Aegir solution (and are willing to consider a LEMP stack), Barracuda-Octopus-Aegir (BOA) is fantastic (and highly maintained).


How to import decimal fields using Feeds?

It could be that the there is an issue with how it's interpreting the value especially if you are in a non-English context. For example, in Drupal's terms if you have a decimal value it's formatted like so "7.6". If you are trying to import a decimal value formatted with "7,6" it may have an issue.

If it is a bug, you could try and import and use a module like Feeds Tamper to rewrite that field output so that Drupal will import it.

I just tested myself and it imports fine using English decimal notation.


How to open Bootstrap Photo Gallery on page load?

Add your gallery into model window then used #modelid in then then gallery is automatically load when your page is loaded.

<script type="text/javascript">
    $(window).load(function(){
        $('#myModal').modal('show');
    });
</script>


What entity type should I choose for a comment type?

That depends to which entity you want to attach those comments. If the new comment type is for content types (node bundles), select the according type. (I assume it's one of the the last three list entries given in your screenshot.)


How to add user role as a class while rendering a username

You need to preprocess the theme function, and add to the attributes array or link options, depending on context. Currently you're overriding the theme function and reducing its output to an empty string.

function MYTHEME_preprocess_username(&$vars) {
  foreach($vars['account']->roles as $role) {
    if (isset($variables['link_path'])) {
      $vars['link_options']['attributes']['class'][] = 'role-' . drupal_html_class($role);
    }
    else {
      $vars['attributes_array']['class'][] = 'role-' . drupal_html_class($role);
    }
  }
}


Clean URLs work*, but not when I submit forms?

I think you need to enable Apache's rewrite module using a2enmod rewrite or with sudo if you get permission errors and added the Apache directive AllowOverride All for VirtualHost.


Placing Drupal core/modules code outside public_html

There is some work being done to move as much of core out of DOCROOT, but this is complicated by assets that need to be web accessible, mainly JS, CSS, and images.  So, moving core/modules outside DOCROOT is tough because many of those have all three.

Current thinking is to place the vendor directory outside of DOCROOT to help reduce attack surface area.  Since using composer for all site building is also essentially a best practice now, the drupal-composer/drupal-project template does this, and also will place modules, themes, libraries, and other Drupal stuff in the proper place, while keeping vendor non-web accessible, as it contains the non-Drupal specific dependencies.


combining drupal commerce product display page with checkout page

You can't get to checkout pages without products in your cart ( try visiting /checkout with an empty cart). At least, not without extensive hacks.

I'd recommend keeping the catalogue browse / add to cart separate from the checkout process.

If suitable, you can redirect straight to checkout with a Rule after the product is added to the cart, for user detail input and order completion.


How to temporarily replace Drupal with static HTML pages?

Drupal only kicks in when a file does not exist. So if you create HTML files at the same path where a Drupal page existed, the HTML file will be shown, and Drupal will not be instantiated.

Example: You have a path named /node/4.

If you create a folder in your webroot named 'node', and a file named 4, it will be picked up instead of Drupal being instantiated, even if Drupal exists in the webroot. You may need to do some work to set the headers of the file as text/html though, since there is no file extension on the file to tell the processor that it's an HTML file.


Deleting nodes did not remove the node-related menus

These Q/A may be helpful for you:
Delete all nodes of a given content type
How to bulk delete content of a given type?
According to the first Q/A, the Delete all module is worth to try.

You could also try mass delete node. The function node_delete() is safe to call. It has a call to node_delete_multiple() which deletes all related components of a node, such as entities, files, revisions, history, etc.

[UPDATE]
If you already deleted your nodes, but node-related menus are still there, you could also try out menu_rebuild() to rebuild your navigation menus. Check this answer. You could also add menu_rebuild() at the end of the script of mass delete node I mentioned above.

OR

If you know menu IDs, you can remove each of them using menu_link_delete().


echo() doesn't output anything for anonymous users

Drupal have much better tools for debugging than echo. You can sent a message to the watchdog log with the watchdog function. And if you install the devel module you get a few more funcions like dpm() to easily send messages or dd() to write onto the drupal debug log.


Earliest hook to generate content during user registration

You can use hook_user_insert(), it should be early enough for you.

Technically speaking, hook_user_presave() is the first hook called from user_save() (even before the user is written to the database), but according to the documentation it is "primarily intended for modules that want to store properties in the serialized {users}.data column". More importantly, it is also invoked when a user account is updated, so that wouldn't fit your use case.


Allow CSS styling in node filtered HTML view?

I recommend using the WYSIWYG Filter module.
In the "HTML elements and attributes" textarea there is a list of allowed HTML tags. 'ol' should be present. If it is, add '[class|style]' to it which will make it look like this:

ol[class|style]

Or, you can add @[class|style] to the list to enable the style and class attributes on all allowed html tags.


How do I create a total blank page without any header and footer?

You can make a copy of page.tpl.php in your theme and rename it according to the Template Suggestions for Drupal 6.

Your theme should be in a directory like site/all/themes or sites/default/themes.

So if you wanted a custom page.tpl.php for http://yoursite.com/path/to/override, your file name will end up being something like page--path-to-override.tpl.php.


How do I import product category based on taxonomy vocabulary?

You probably need to add your taxonomy vocabulary field to the product display.


If you are focusing on the problem of data overflow from the views table, CSS could solve the issue.

For example if you write a code similar to this:

...

...

The only factor that is missing and could prevent the overflow is:

width: 100%;

Often you need to set the height of Content as well. If the height attribute is not set, the div will grow vertically as tall as it needs to. You may also try using a FixedHeightContainer


Changing the default imagefield formatter for a node field

Go into the admin for the content type in question and look at the display fields, eg, admin/content/node-type/THISCONTENTTYPE/display and change up the field you want.  You can select any imagecache preset you have defined on your system along with a number of other options.


How to set up a trial-based account for users on an ubercart site?

Create 2 user roles: Trial Seller and Seller.
Create a Rule.

Event: "Drupal is initializing"
Condition: User has role -> "Trial seller"
Action: php that will hide (disable) the add to cart button. You have to use the hook_form_alter function (or similar) like described here: https://drupal.org/node/773312#comment-7425408

The second question is another seperate task.

Create a Rule:

Event: "Drupal is initializing"
Conditions: User is of role "Trial Seller" AND not "Seller" AND php "(Current_date_time - Account_Created_Date) > 30*24*60*60" (to see if the time from the user account date until now is more than 30 days, time in seconds) AND he has paid
Action: Remove user role -> "Trial Seller"

There is also the module Role_Expire that may help you.


Commerce payment for Rooms reserveration only after the order is confirmed

Maybe you want to look at the Easy Booking distribution, to check if there is anything in it similar to what you're looking for (specific to the way this distribution uses Rooms and Drupal Commerce). If you find something, it is just a matter of reusing what's appropriate in your own site.
Here are some more details about this distribution (quotes from its project page):

... to set up a website, that will suit all your needs in managing your own hotel, inn or hostel online.
It gives a set of options for visitors to make room reservations, contact hotel administration or just follow hotel’s newsletter to be aware of all special offers and discounts.
Easy booking profile is powered by Drupal Rooms and Drupal Commerce - widely used and popular contributed decisions, which means active maintaining and timely technical support.


It depends how the links have been created.

If the links were added using a field, eg using the file module, then you could look to that module for it's theme functions, and create your own replacement theme function in your module or theme.

If (just reread your question) the links are included in the body (or other textarea field) of your site's nodes, then you would have to rely on an input filter to alter them before displaying the field. You could look to a module like ELF, for how this can be accomplished using an input filter, or 'External Links' for an example using javascript.


Disable sticky table headers for field collection?

One line of CSS will do it:

table.sticky-header { display: none !important; }

Answer found here.


How Not To Update Existing Taxonomy Terms At Migration

If found the solution, if the term exists return false from prepareRow($row) and the term won't be updated or migrated again. like this:

public function prepareRow($row) {
  if (parent::prepareRow($row) === FALSE) {
    return FALSE;
  }
  $term_name = $row->name;
  $query_checking_if_term_exist = db_select('taxonomy_term_data', 'ttd')
    ->condition('ttd.name', $term_name)
    ->condition('ttd.vid', '2')
    ->fields('ttd', array('name'))
    ->execute()->fetchAll();
  if(!empty($query_checking_if_term_exist)) {
    return FALSE;
  }

}


We ended up going the route of a custom field collection table module combined with batch processing.  The problem was the standard Drupal way of adding rows using ajax.  Instead we created the rows dynamically using Javascript to duplicate the last row and all associated features tied to each field.  We then used a batch process to save the data.  This resolved the issue of the server timing out with lots of rows.


Custom theme css separate from editor css

First, let me add that the answer that I am about to give is the way I would handle it. This could be done in many ways.

Create a separate stylesheet for your text styling (we usually call it style-type.css) and place it somewhere appropriate in your theme (for example /sites/all/themes/your_theme/css/style-type.css), also use this file for your front-end. Only add styling in this stylesheet for textual styling, so for h1, h2, strong, em, etc...

Then use the admin/config/content/wysiwyg admin page to define the CSS in the appropriate format. We mostly don't use the replacement patterns (like %b) and simply fill in the path relative to your Drupal install (of course, the patterns could be applicable in your case): /sites/all/themes/your_theme/css/style-type.css. Make sure Define CSS is the active option above the path.

If you need extra styling for stuff like highlighted text, simply make sure you have that styling in your style-type.css. For example .highlighted { color: yellow; }. And then define it in the CSS Class textarea as follows:

Highlighted=highlighted

Then also make sure you've got the plugin Styles enabled. This will give you a dropdown list on the WYSIWYG editor which allows you to add styling that you defined to texts.


How do I retrieve an entity from an entity reference

Entities part:

I think (as much you showed) your entity definition is wrong:

Entity names should be always SINGULAR: Chemical, Element, Chemical Formula
Your Chemical Formula should have the ability to hold reference to MULTIPLE elements (H20 for example, has H and O elements). Which means you won't able to store this information in this entity table, but you will have to create an external table to hold this information. You can find example for this in core entities (like taxonomy_terms, if I remember good).
If you make this changes right, you won't have query anything, since the referenced entity ids (elements, chemical) will be present in your entity.
You only have to load via EntityTypeManager.

Final hint again: always examine core / contrib entities. Node, Taxonomy terms are pretty good examples.


Drupal views contextual filter: use last argument as filter value

One solution would be hook_views_pre_view()

function MYMODULE_views_pre_view(&$view, &$display_id, &$args) {
    if ($view->name == 'view_machine_name' && $display_id == 'my_display_id') {
        $args = array(end($args));
    }
}

For a view with one contextual filter this would always set the argument to the last argument from the URL.


"drush sql-sync" failing with Illegal string offset 'site' backend.inc:1030

I had same issue and fixed it by specifying the %drush-script path for my remote machine alias. Just ssh into your remote machine and run "drush status" to find the correct "Drush script" path and put it in under path-aliases array. So it would look like this:

'path-aliases' => array(
  '%drush-script' => '/{your_path}/drush.php',
)


How do I get the current node from a Block module?

The Book module implements a block that needs to access to the currently viewed node, and it uses the following code, in BookNavigationBlock::build().

if ($node = $this->requestStack->getCurrentRequest()->get('node')) {
  $current_bid = empty($node->book['bid']) ? 0 : $node->book['bid'];
}

$this->requestStack is initialized from the following code.

  public function __construct(array $configuration, $plugin_id, $plugin_definition, RequestStack $request_stack, BookManagerInterface $book_manager, EntityStorageInterface $node_storage) {
    parent::__construct($configuration, $plugin_id, $plugin_definition);

    $this->requestStack = $request_stack;
    $this->bookManager = $book_manager;
    $this->nodeStorage = $node_storage;
  }

  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static(
    $configuration,
    $plugin_id,
    $plugin_definition,
    $container->get('request_stack'),
    $container->get('book.manager'),
    $container->get('entity.manager')->getStorage('node')
    );
  }

The code is essentially like the one you are using, but it seems that in your case, a module is messing up with what $container->get('request_stack')->getCurrentRequest()->get('node') is returning.

As workaround, if you find in which cases it happens, you could override BlockBase::blockAccess() to avoid your build() method is called in those cases.


Replace 'page' twig template for controller/url

Just create new twig template in the template folder of your theme page--your-url.html.twig and clear the cache.


Tracking User's Location at a certain point

You can append a different query string to each click, which will allow you to track each one individually. Lets say your "Start Timer" is at mysite.com/start_timer (using ajax). You can create several url's with a query string that lead to the buttons. Ex:

mysite.com/start_timer (using Ajax)

mysite.com/end_timer (using Ajax)

Then you can use Google Analitics Event Tracking Module which will do your work for tracking easily.

Enjoy !


Buttons get longer when pressed if using AJAX

I suspect it's the trobber, you know the little .gif image showing an ajax loading.

You can fix it via css, but to find out the class/id to edit, i had to break the ajax and force it to never complete the load, so i had time to inspect the markup with firebug.

check this discussion:

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


How to change view mode of view row using hook_views_pre_render?

I was able to change the view mode in the hook_views_pre_execute() hook. I believe _views_pre_render() is too late.

function custom_module_views_pre_execute(ViewExecutable $view) {
  // Some logic to determine view mode...

  $view->rowPlugin->options['view_mode'] = 'list';
}


How to change views exposed filter default value

in template.php:

function MY_THEME_form_views_exposed_form_alter(&$form, &$form_state) {
  // dpm($form);
  if ($form['#id'] == 'MY_EXPOSED_FORM_ID') {
    // Modifications go here.
    // example: (change the field name to yours)
    // $form['field_adv_cat_1_tid']['#default_value'] = 'All';
  }
}

then clear the cache.


Elysia cron Execution time vs Shutdown time

The documentation surrounding that variable is pretty much non-existent. This is how it's calculated, in elysia_cron_completed():

time() - $cron_completed_time

Where $cron_completed_time is a global, presumably a timestamp indicating exactly when an associated cron job ended.

I'm afraid you'll need to infer exactly what that timestamp is from the above; I think it refers to the gap between when a cron job was completed, and the time it was logged in the database.


How to add custom class in custom module?

you can try code :

  $url = Url::fromRoute('entity.node.canonical', ['node' => $previous_next['next'],'an'=>'left']);
  $url->setOptions([
      'attributes' => [
          'class' => ['ajax-link custom-class']
      ],
  ]);

  $build['prevnext_next'] = [
      '#type' => 'link',
      '#title' => t('Next'),
      '#url' =>  $url,
  ];


Moving PayPal Payment iFrame to Checkout page

This actually just isn't possible. The iframe depends on having a completed order object, which you can't possibly have (or know for certain) if it's on the same page as fields placed to collect user input to complete that order. The same is true for all redirect, tokenized, or iframe based payment solutions.


Redirect to a specific page in ajax callback

I had the same problem. You should try this:

ctools_include('ajax');
ctools_add_js('ajax-responder');
$commands[] = ctools_ajax_command_redirect('login');
return array('#type' => 'ajax', '#commands' => $commands);


How to list only the latest revision of all nodes in a view?

In the view you should have it sort by revision id (vid) descending, then use Views Group By to group by node id (nid).


Does node_save create all fields associated with a custom content type automatically?

You can happily omit the empty ones, there's no problem. When consulting the newly created node, node_load() will retrieve all the attached field and build the correct object.


Drush includes a sample php.ini file (there's an online copy here) with instructions on how to override your the php.ini file that Apache uses.

Just copy the contents of the example file into one of the three locations listed in the sample file and save the new file as php.ini. I would recommend using either option except for your Drush installation as this will require you to re-create a php.ini every time you update Drush.

Running drush status shows you which PHP configuration file it is using in case you're unsure if your changes took effect.


logging into development instance of Drupal

You can try login with https://drushcommands.com/drush-8x/user/user-login/

drush uli admin

Which will give you a login link for user admin

If you invoke it without a username it gives you a login link for user 1

drush uli


How to redirect a newly registered user to a custom URL after signing up?

Consider using the Rules module to do this.

Here is how such (fairly basic) rule would look like, based on your extra comment in my answer (= new users that register do NOT need admin approval):

Event: After saving a new user account.
Condition: None
Action: Page redirect (with value = Node/35 in your case).

The above is just a basic rule. You might want to enhance it in various ways. E.g. add a 2nd action to the very same rule to just set a special welcome message (near the top of the main content of your pages).


There's a few issues confused into here based on the original question. I'll try to take these one at a time:

1 Is RSS the same as HTML?

No, these are different markup languages. RSS is a dialect of XML designed for syndicating content from podcasts, blogs, etc, etc. HTML is a web page specific markup format. In your question you mentioned that firebug is showing a <pre> tag in RSS feed, but this is impossible because <pre> is HTML only, and will never appear as RSS.

2 How can I style an RSS feed?

Typically, you don't need (or want) to do this. RSS Readers typically apply formatting to your RSS content, and if you change the formatting this could get confusing and ugly for your end users. Just as there are many browsers for HTML, there are many RSS REaders for RSS including iTunes, online services, Mozilla Thunderbird and hundreds of others. So, I recommend NOT styling your RSS feed.

However, if you need to style an RSS feed you can do using regular CSS by adding this tag to beginning of your RSS feed:

<?xml-stylesheet type="text/css" href="http://example.com/rss.css" ?>

Then you would need to create a css file called rss.css in the appropriate place on your server. Here's a great article that goes more in depth on this:
http://www.petefreitag.com/item/208.cfm

3 How do I get Drupal to modify my RSS feed to include CSS?

This is really a great question, and a lot of people struggle with this. What makes this hard is that in Drupal 6 and 7 only HTML can be "themed", so many of the normal hooks that work on nodes which appear as HTML do not work on RSS feeds. What's also really anooying is that Drupal will escape all your HTML markup and put it inside your RSS feed, making your RSS feed nearly unreadable.

If it doesn't exist already, create a new folder called template inside your theme folder. Add a new file inside that folder called views-view-rss.tpl.php. This file will affect all your RSS feeds. Add this code inside views-view-rss.tpl.php:

<?php
/**
 * @file
 * Default template for feed displays that use the RSS style.
 *
 * @ingroup views_templates
 */
?>
<?php print "<?xml"; ?> version="1.0" encoding="utf-8" <?php print "?>"; ?>
<?php print "<?xml"; ?> type="text/css" href="http://example.com/rss.css" <?php print "?>"; ?>
<rss version="2.0" xml:base="<?php print $link; ?>"<?php print $namespaces; ?>>
  <channel>
    <title><?php print $title; ?></title>
    <link><?php print $link; ?></link>
    <description><?php print $node->body['und'][0]['value']?></description>
    <language><?php print $langcode; ?></language>
    <?php print $channel_elements; ?>
    <?php print $items; ?>
  </channel>
</rss>

For more details on this: https://drupal.org/node/1884558

4 How do I remove a specific tag from my RSS feed?

It depends on where the tag is appearing in your view. I assume it's showing up inside <item> tag somewhere. In the file you created earlier, change:

    <?php print $items; ?>

to:

    <?php print str_ireplace(array('<pre>','</pre>'), '', $items); ?>

Make sure to clear the cache.


I think the classes should be added in the attributes array:

 $button['my_tickets'] =array(
    '#type'       => 'link',
    '#title'      => t('My tickets'),
    '#href' => '',
    '#attributes' => array('class' => array('btn', 'btn-default')),
    '#id' => '',
    '#options' => array(
      'html' => true,
    )
  );


<?php

$field = $view->result;
?>

<?php

    foreach($field as $obj){

     $url = drupal_lookup_path('alias', 'taxonomy/term/'. $obj->tid);

?>

    <a href="<?php echo $url;?>">

<?php echo $obj->taxonomy_term_data_name;?>

        <img src="http://faliam.com/demo/sites/default/files/styles/catalogueimage/public/catalogue/<?php echo $obj->_field_data['tid']['entity']->field_illustration['und'][0]['filename'];  ?>" alt="" height="300" width="368">

<?php

}

?>


When this happened to one of my sites, I corrected it by upgrading to the latest version of the galleria library. There also might be an issue with your css. Several hints to track the problem down can be found here.


You can add new "template suggestions" using a preprocess function. Here's an article with more details.

Here's another example, but for different templates based on the vocabulary, rather than the term.


How to know that the node of a specific type is being viewed for the first time?

Used the core statistics module.

and then on node view used the function statistics_get() function and then check it the total count is less than 1.


Why field is double when I print it in node.tpl.php

Try wrapping the field in the hide function.

hide($content['field_like']);

Do this after you have output your field but before you call render($content).

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


how to pass a parameter to a route of type _entity_form

With the help of 4k4 who have all the credit for this answer, I have created a controler which, in turn, build my register form (I no longer need to extend the register form).
Before building the form, the controller must create a user and assign the role (coming from the parameter).

Here is the code

1-Create the route with rid as the parameter and a _controler key:

my_module.register:
  path: '/register/{rid}'
  defaults:
    _controller: '\Drupal\my_module\Controller\RegisterByRoleController::content'
    _title: 'Register by role'
  requirements:
    _permission: 'access content'

2-Create the controller with rid as the parameter (src/Controller/...):

    public function content($rid=null) {

      $user_with_role = \Drupal\user\Entity\User::create();
      $roles = Role::loadMultiple();
      if ($rid && isset($roles[$rid])){
          $user_with_role->addRole($rid);
      }else{
          throw new \Symfony\Component\HttpKernel\Exception\NotFoundHttpException();
      }

      $form = \Drupal::entityTypeManager()
      ->getFormObject('user', 'register')
      ->setEntity($user_with_role);

      $form_build=\Drupal::formBuilder()->getForm($form);

      //here is the trick I used to check the role
      $form_build['account']['roles'][$rid]['#checked']=TRUE;
      return $form_build;
  }

Everything works well: the form is displayed, the rid is transmitted to the controller but the is still a problem:

The "transmitted" role's checkbox is not checked in the register form!

Any Hint?

I answer myself: it seems there is no way to achieve this "automatically", I will have to check "myself" the check boxes... see the last comment here: Default value for form entity

This is why is have added this line in the code $form_build['account']['roles'][$rid]['#checked']=TRUE;


Create Group permission to grant view of all group content

As per their documentation "The permission layers explained" it should work like this:

  I want my site admins to be able to administer all groups without having to join them.

  Assign them a global role, e.g.: "Site admin", and then assign the "Administer group" >permission to the matching advanced outsider role in the group type configuration >section. Anyone with the "Site admin" role set to their account will be able to >administer all groups they are not a member of.


How might a user configure which video is shown on page without editing the page?

Step 1

Create a content type: e.g. "Home Page Video".
Add fields: YouTube, text area, image, etc. Basically all the fields you would want to structure that "section" on the home page.
Give permissions for the fields with field permissions (additional security measure, you'll see why later)

Step 2

Create a few nodes for "Home Page Video"
Set your view modes

Step 3

Create a View to show only "Home Page Video" content.
Choose Bootstrap Grid (Views Bootstrap module and Bootstrap Field
Group module) and add fields
OR
Choose unformatted list: Rendered
entity and a View Mode
Set a filter: "promoted to front page"
Set a Pager: Display a specified number of items and choose 1, More
link: no
Set a sort criteria: "Content: Updated date" (The date the content
was last updated.) and set it to "descending"
Create a pane view from this view.
Save

Step 4

Enable: System - page_manager - node_edit - Node add/edit form -
/node/%node/edit
Create a new variant of node_edit template in Page Manager
Selection rule: Node being edited is bundle "Home Page Video"
Selection rule: Logged in user has one of "my user role"
Content: Add the form fields you want this user to edit AND add the
base form (General Form) in order to get the submit button. If you
have set certain fields to be required on your Home Page Video
content type, they will show in the base form UNLESS you add them in
through the cog wheel "Add content" and choose FORM and then choose
the specific form field that is required. Like that you have the
ability to choose where that field goes in your edit form layout.
More control.
Save

Step 5

Add your pane view of "Home Page Video" to your Home Page Page Variant at the position where you want it to show up on your Home Page.
In order for your pane view to show up, you might have to clear the cache. If you use Drush, simply type: drush cc all
Go look again for that pane view and add it.
Save

Et voilá.
No need for a custom module. Permissions are dealt with by the 'selection rules' in your node_edit page variant.


How to trim a rendered item before and after specific symbols

A tip from a friend got it working. Here the solution.

<?php foreach ($items as $delta => $item) : ?>
    <?php
     $file_extension = substr(render($item) , strrpos(render($item) , '.') +1);
     print basename(render($item), '.'.$file_extension);
    ?>
     </p>
<?php endforeach; ?>


Add external CSS file with custom backend setting

hook_library_info_build() would be the right hook to add dynamic library definitions (definitions that depend on any run-time information) but it needs to be implemented by a module, as its documentation page says.

  Modules may implement this hook to add dynamic library definitions. Static libraries, which do not depend on any runtime information, should be declared in a modulename.libraries.yml file instead.

hook_library_info_alter() can be implemented by either a module or a theme.

  Allows modules and themes to change libraries' definitions; mostly used to update a library to a newer version, while ensuring backward compatibility. In general, such manipulations should only be done to extend the library's functionality in a backward-compatible way, to avoid breaking other modules and themes that may be using the library.

If there are default values you can use (for example, using a local CSS file that is then replaced from hook_library_info_alter() basing on run-time information), you can put those default values in the .libraries.yml file, and use hook_library_info_alter() to alter them.


You should be able to go into the Edit Content type form simply turn on comments.  Are you sure the option is not there?


Drupal Commerce: line_item field in user profile?

Yes, I would not use a line item reference field outside of the order entity type. You might try using an entity reference field instead with the inline entity form module for line item creation / editing.


Display status message after submitting modal popup form

After redirection the \Drupal::messenger() may not work. So try with the Drupal OpenModalDialogCommand
use Drupal\Core\Ajax\OpenModalDialogCommand;

/**
* {@inheritdoc}
*/
  public function submitForm(array &$form, FormStateInterface $form_state){

    $entry_entity = \Drupal::entityTypeManager()->getStorage('entry')->load($entry_id);
    $entry_entity->delete();

    $response = new AjaxResponse();
    $response->addCommand(new OpenModalDialogCommand("Success", 'Entity deleted.', ['width' => 800]));
    return $response;
  }


How to solve claimitem() in batch process?

Add the 'file' key in your batch:

  file: Path to the file containing the definitions of the 'operations'
  and 'finished' functions, for instance if they don't reside in the
  main .module file. The path should be relative to base_path(), and
  thus should be built using drupal_get_path().

$batch = array(
  'title' => t('Started Importing node Data.'),
  'error_message' => t('Error!'), //Error Message
  'finished' => 'node_data_import_batch_finished',
  'file' => drupal_get_path('module', 'YOUR_MODULE_NAME') . '/YOUR_MODULE_NAME.module',
);


How do I redirect users visiting a path matching a regular expression?

In Drupal 8 you use an event subscriber for this. You subscribe to a REQUEST kernel event, get the original url from the request, apply a regular expression and if this finds a replacement set the new url as a 301 redirect response.

mymodule/src/EventSubscriber/RedirectSubscriber.php

<?php

namespace Drupal\mymodule\EventSubscriber;

use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\EventDispatcher\Event;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Drupal\Core\Routing\TrustedRedirectResponse;
use Symfony\Component\HttpKernel\KernelEvents;

class RedirectSubscriber implements EventSubscriberInterface {

  public function redirectIndexPHP(GetResponseEvent $event) {
    $old_url = $event->getRequest()->getUri();
    $new_url = preg_replace('|/index.php|', '', $old_url, 1, $count);
    if ($count > 0) {
      $response = new TrustedRedirectResponse($new_url, 301);
      $event->setResponse($response);
    }
  }

  static function getSubscribedEvents() {
    $events[KernelEvents::REQUEST][] = array('redirectIndexPHP', 39);
    return $events;
  }

}

mymodule/mymodule.services.yml

services:
  mymodule.redirect:
    class: Drupal\mymodule\EventSubscriber\RedirectSubscriber
    arguments: []
    tags:
      - { name: event_subscriber }


How add a custom page template for an article node

Refer this url http://drupalknowledge.blogspot.in/2012/01/different-page-template-for-different.html

You can print  $vars['node'] variable and get the particular node path to give different template.

I hope this will help you.


Submission handler for the user registration form doesn't work

In hook_form_alter use foloowing code

function MODULENAME_form_alter(&$form, $form_state, $form_id) {
if($form_id == 'user_register_form'){
    $form['#submit'][] = 'module_custom_form_submit';
   }
}

after that use

function module_custom_form_submit($form, &$form_state) {
    // Do whatever you want.
}


Backup and Migrate exclusion recommendations?

I have following tables to exclude data (not to exclude the table altogether):

all cache_* tables
ctools_views_cache
ctools_object_cache
flood
history
queue
semaphore
watchdog
search_index

Usually search_index saves a lot of database size.


You can change this be enabling the Taxonomy Term View (I suggest cloning it in case you mess something up) and then you can change the view to suit your needs.


How do I add a date field that can be filtered by a relative value?

I've found the solution. (Doh!)

It turns out that there is a module named Date Views that comes as part of the Date package.  If you enable this, the filter criterion screen changes, and you can use relative operators.


If you just need the functionality, you can try MultiBlock to see if it fits your needs:

"Each block has a 1:1 relationship with its region, weight, visibility (and other) settings. This means that it is impossible to have blocks in multiple regions or to have blocks that have different settings on different pages. MultiBlock module solves this problem by allowing you to create multiple Block Instances of already existing blocks."

However, you question is about being able to accomplish building a module that manages this. So, yes, I recently did something similar. I needed a homepage with blocks displaying a list of articles, each one with custom options (e.g. different categories, with / without images, etc.) and also in different regions across the site. I created one module, and then instead of having each block with a harcoded-fixed name, I generate the block's names ($delta) dynamically, like this:

function MY_BLOCK_block_info() {
  // Instead of having a static number of blocks, let's choose how many
  // we want, via the administration.
  $blocks_qty = variable_get('MY_BLOCK_blocks_qty');
  for($i = 1; $i <= $blocks_qty; $i++) {
    $blocks['MY_BLOCK-' . $i] = array(
      'info' => t('My block ' . $i),
      'cache' => DRUPAL_CACHE_PER_ROLE,
      'region' => BLOCK_REGION_NONE,
    );
  }
  return $blocks;
}

Then you will have different names for each block (MY_BLOCK-1, MY_BLOCK-2, etc). So you can individually configure them like this:

function MY_BLOCK_block_configure($delta = '') {
  $form = array();
  $parts = explode('-', $delta);
  $block_number = $parts[1];

  // Your form here...
  $form['MY_BLOCK_' . $block_number . '_title'] = array( ...

So, in the general Configuration page you get to choose how many blocks you want to generate. And then, in the individual block's configuration page you choose the individual block's settings.


How can I make a node like template for a vocabulary?

Enable the Taxonomy term Views if you haven't already, and look into theme suggestions there.

It seems you have views-view--taxonomy-term--page.tpl.php available where you can add some logic that would apply to only a certain Vocabulary.

You can also Clone the Taxonomy term Views twice, Filter to only certain Vocabulary in one Views, and to all the rest in the other Views, then use the template in the first Views for special styles.

You can use the Taxonomy Views Integrator module to assign different Views to output different term pages.


Which is the difference between the Full content and the Default mode?

The argument for EntityViewBuilderInterface is $view_mode.

View displays and view modes are not the same thing.

view_mode can basically be anything you want, you can even make up them on the fly.

What the field formatter/widget system then does is look up if there is a form/view display with for that view mode. If that is the case, that is used.  If not, then it falls back to default.

The view/form modes that you set up in the UI are basically only there to tell field UI that it can create form/view displays for them (the checkboxes at the bottom of the default display page). They are never used at runtime.

So, when you are going to node/1, there is by default no display for full, so it falls back to default. Whereas teaser does have one, so it uses different things. However, you can also enable a form display for full and then it will no longer use default.


node_type is set in node_preprocess_html() from the Node module.

/**
 * Implements hook_preprocess_HOOK() for HTML document templates.
 */
function node_preprocess_html(&$variables) {
  // If on an individual node page, add the node type to body classes.
  if (($node = \Drupal::routeMatch()->getParameter('node')) && $node instanceof NodeInterface) {
    $variables['node_type'] = $node->getType();
  }
}


Additional filter for (image)fields to filter node display

I'm not sure if it quite meets 100% of your requirements, but you might want to take a look at the Display Suite module. It lets you customize multiple displays per node type, each of which can be configured to display different fields.


I think you are making it sound more complicated than it actually is. (smile)

As explained here, you may consider simply registering  your custom stylesheet in your theme's .info file:

stylesheets[all][] = nice-menu-custom.css.

Once that is done, you have the benefit that your custom style-sheet will be loaded with all other application's css and js files,  and be optimised by Drupal (when you change your dev settings to prod settings).

You understand that you can then overide any nice menu selector in your stylesheet, as long as your stylesheet loads last it should do the trick. If you want to "delete" an unwanted style, do not hack nice-menu.css, add an empty matching selector selector in your style-sheet.

THen, last but not least you can confirm your custom styles are being loaded by looking through any browser's inspector applet or script viewer, or even view source. Whatever.  In dev mode (no caching, no script compression) you should see the changes without needing to drush cc on your instance.

Hope this helps, good luck


jQuery length of object to determine existence gives error?

if (pid.length)

causes a reference error in your script if pid is undefined.  So, if you don't know that pid exists ahead of time, then you have to check to see if that object is valid before trying to reference properties on it.

FYI, you could probably just use:

if (pid)

because that would protect you from pid being undefined or an empty string.

It has been raised in comments that maybe you're actually just trying to test for the existence of a DOM object, not the attribute.  If that's the case, then you should just be doing this:

if ($('input[name="product_id"]').length)

which tells you if the selector matched any DOM objects.


Where does the value of entity come from in a field of a content type?

It's literally magic (well, PHP magic methods anyway).

FieldItemBase implements __get(), which will respond to any property on the object (existing or not):

public function __get($name) {
  // There is either a property object or a plain value - possibly for a
  // not-defined property. If we have a plain value, directly return it.
  if (isset($this->properties[$name])) {
    return $this->properties[$name]->getValue();
  }
  elseif (isset($this->values[$name])) {
    return $this->values[$name];
  }
}

And the image field type extends the entity reference field type, which maintains an entity property (see EntityReferenceItem::propertyDefinitions).

So when you request the non-existent entity property on the field class, FieldItemBase hooks it up for you via the $properties array, and you get an entity back.


Make Commerce Kickstart home page show up at a different URL

The front page on Commerce Kickstart is node. The content is defined via blocks. So if you want to change the front page to another page, you could create a page and set it as the front page in the admin. None of the blocks should show up. If you want to make the contents of the current node page visible on a new or custom page, then you'll need to change the block configuration of all of the blocks that are currently visible on node and configure them to show up on another page.


Why would piece of content of each content type be migrated but their text formats wrong?

You need to map the body format.

This is from 6 years ago, but reposting in case mikeryan does not see this question.

  if the format is part of the source data (i.e., it varies from node
  to node), you can make use of the source_field feature:

$this->addFieldMapping('body', 'body')
     ->arguments(array('format' => array('source_field' => 'body_format'));

Where body_format is the value from the source db I believe.

It has been a loooong time since I have done a 6 to 7 migration.

This post might also be of use if you are using migrate_d2d.


You need to create an input filter that uses the GMAP filter before it can work : Go to Administer > Site Configuration > Input format > Add Input Format and select the gmap filter in the filters list