How do I create a list with the previous and next referenced entities of the one being viewed?

A solution that comes to mind could include creating a block in a custom module and manually generate your pager-like unordered list. I wrote some quick code to show you how it can be done. I also added some comments in there to help you understand what I'm doing.

Notice, that this code is assembled in a hurry so you may find additional optimizations that you can perform in there.

/**
 * Implements hook_block_info().
 *
 * Declares your custom pager block.
 *
 */
function YOUR_MODULE_block_info() {
  $blocks = array();
  $blocks['parent_book'] = array(
    'info' => t('Parent Law'),
  );

  return $blocks;
}

/**
 * Implements hook_block_view().
 *
 * Renders the block. Calls the main rendering function.
 *
 */
function YOUR_MODULE_block_view($delta = '') {
  $block = array();
  switch ($delta) {
    case 'parent_book':
      $block['subject'] = '';
      $block['content'] = _YOUR_MODULE_parent_book_content_generator();
      break;
  }

  return $block;
}

/**
 * Helper function: renders the block's content.
 */
function _YOUR_MODULE_parent_book_content_generator() {
  // We'll need this to create the links to the articles.
  global $base_url;
  // Initialize the $output variable
  $output = '';
  // Checks if this is a node page.
  // No content type checking, you'll either have to add extra code
  // to narrow it down or use something like panels.
  if (arg(0) == 'node') {
    $book_chapter_nid = arg(1);
    if ($book_chapter_nid) {
      // Load the current chapter node object
      $book_chapter = node_load($book_chapter_nid);
      // Get the container book's nid and load its object.
      // If you have a multilingual site you'll have to pass the node's language in there
      $book_nid = $book_chapter->field_container_book[LANGUAGE_NONE][0]['target_id'];
      $book = node_load($book_nid);
      // Create a references array and walk through it to remove the intermediate arrays
      $references = $book->field_book_contained_chapter[LANGUAGE_NONE];
      array_walk($references, function(&$value, $key) {
        $value = array_shift($value);
      });
      // Setup the items that you want to display here
      $items_to_display = 5;
      // Find the current chapter's position in the array
      $current_chapter_position = array_search($book_chapter_nid, $references);
      // Crude method to get a maximum number of loops that will be needed
      $no_of_loops = (2*($items_to_display - 1)) + 1;
      // Initialize our final array
      $chapters_to_show = array();
      // Push the current chapter in the array
      array_push($chapters_to_show, $book_chapter_nid);
      // Index to stop adding items when we've reached our goal of items to display
      // Initialized to 1 since we've already added the current chapter
      $items_added = 1;
      // Loop a specific amount of times
      // Notice that we'll always break out of the loop before it ends
      // i.e. when the number of items added becomes equal to the number of items that we wanted to display
      for ($index = 1; $index <= $no_of_loops; $index++) {
        // The condition to add an item before our current chapter is the not-negative index
        if (($current_chapter_position - $index) >= 0) {
          // Previous chapters are added at the top of the array
          array_unshift($chapters_to_show, $references[$current_chapter_position - $index]);
          // Update index
          $items_added++;
        }
        // Check if we need to exit the loop right now.
        // This is needed for even amount of items to display
        if ($items_added >= $items_to_display) {
          break;
        }
        // The condition to add an item after our current chapter is if the array key exists in the $references array
        if (array_key_exists(($current_chapter_position + $index), $references)) {
          // Next chapters are added at the bottom of the array
          array_push($chapters_to_show, $references[$current_chapter_position + $index]);
          // Update index
          $items_added++;
        }
        // Check if need to exit the loop again.
        if ($items_added >= $items_to_display) {
          break;
        }
      }
      // Time to print our unordered list
      $output .= '
';
      // Loop through the array that we created and store the nid in $current_chapter variable
      foreach ($chapters_to_show as $current_chapter) {
        // Load the node since we need it to display the title
        // This: check_plain(db_result(db_query('SELECT title FROM {node} WHERE nid = %d',$nid)));
        // is also possible and more efficient than loading the entire node but revisions need to be taken
        // into account if it is used.
        $node = node_load($current_chapter);
        // Wrapper for the current list item
        $output .= '
';
        // If we are printing the current chapter, we don't want to print the link markup
        if ($current_chapter <> $book_chapter_nid) {
          $output .= '';
        }
        // The title needs to be printed in any case though
        $output .= $node->title;
        // Close the link markup if applicable
        if ($current_chapter <> $book_chapter_nid) {
          $output .= '';
        }
        // Close the list item markup
        $output .= '
';
      }
      // Close the unordered list markup
      $output .= '
';
    }
  }
  // Return our final input which will be stored in $block['content']
  return $output;
}


Does hook_node_submit() fire on feed import?

I believe hook_node_submit() only gets fired when submitting a node form. So the answer to your question is no.

I think you might be better off using hook_node_presave(). This hook is invoked from node_save() before the node is saved to the database.


Field template for display mode of referenced paragraph

Implement hook_theme_suggestions_alter like in the other answer and you can find everything you need in the $variables.

The following snippet will add the template suggestion for the view mode of the referenced paragraphs. Note that this will probably only make sense as long as you use only one paragraph type OR all multiple paragraph types have the same view mode configured.

/**
 * Implements hook_theme_suggestions_HOOK_alter().
 */
function MYMODULE_theme_suggestions_field_alter(array &$suggestions, array $variables) {

  $element = $variables['element'];

  if ($element['#field_type'] == 'entity_reference_revisions') {

    foreach ($element as $key => $value) {
      if (is_numeric($key) && isset($value['#paragraph'])) {

        $paragraph = $value;
        $suggestions[] = 'field__' . $element['#field_name'] . '__paragraph__' . $paragraph['#view_mode'];
      }
    };
  }
}

Seems you can implement that from you theme's *.theme file as well.

I guess the same logic works for any entity (node etc.) reference as well.


What is your way to get the fields information when using Services 3

As @Clive has suggested in comment its best to write your own service resource for this.

Approach 1:

But i wouldn't bother to programaticality supply the form field values anymore.  Reason being, its usually not cost-effective to spend enough hours trying to figure out every possible field type that has been implemented or may be implemented in the future.

Instead create an API documentation. The implementation details is the liberty of IPad / Android dudes. Make sure you enable version control over the docs and also maintain a well documented change logs.

Approach 2:

If you do want to supply the form field information via services.

Then create a resource action.

Something like www.mysite.com/your-endpoint-name/your-resource-name/get-form

This action should be responsible to provide the field details.

This could be done by calling drupal_get_form($form_id); and then passing the $form array through a function that would filter out lots of unnecessary data which drupal adds.

Please note that the main difference here is "We are removing unwanted data from the form definitions" instead of "adding necessary field data".  Thus it will help reducing missing fields that might be added later by some modules in to the form.

After you are done with removing you may add additinal information into the form array like API interface Version, timestamp, and some default values that maybe useful for the Ipad/android dudes.


Use hook_node_view and for $view_mode == teaser you can add your logic.

https://api.drupal.org/api/drupal/modules%21node%21node.api.php/function/hook_node_view/7


here it is, tried it with a custom content block and a views block

i executed the code in php/devel from devel_php module

$storage = \Drupal::entityTypeManager()->getStorage('entity_view_display');
foreach ($storage->loadMultiple() as $display) {
  foreach ($display->getSections() as $section) {
    foreach ($section->getComponents() as $component) {
      // Custom views block
      // $to_delete_plugin_id = 'views_block:my_news-block_1';
      // Custom block
      $to_delete_plugin_id = 'block_content:fb4ad848-0f3c-4296-a6ba-1a9da886335b';
      if ($component->getPluginId() == $to_delete_plugin_id) {
        $section->removeComponent($component->getUuid());
        $display->save();
      }
    }
  }
}

for a particular node :

// This can be adapted to be used for a set of nodes
$node = node_load(42);
$display = $node->layout_builder__layout;

foreach ($display->getSections() as $section) {
  foreach ($section->getComponents() as $component) {
    // Custom views block
    // $to_delete_plugin_id = 'views_block:my_news-block_1';
    // Custom block
    $to_delete_plugin_id = 'block_content:fb4ad848-0f3c-4296-a6ba-1a9da886335b';
    if ($component->getPluginId() == $to_delete_plugin_id) {
      $section->removeComponent($component->getUuid());
      $node->save();
    }
  }
}

Hope this helps :)


How to replace a Token in the PHP evaluation of a Rule?

I still don't know what went wrong, but I've solved the problem in an alternative way. Everything works fine when you follow the steps underneath.

Save the integers Old value and New value as variables.
Add a third variable Result. Thanks to step 1, one can use $old_value and $new_value in the PHP evalution of this variable. I've used this code:

if ($old_value > 5) {
  return 0;
}
else {
  return $new_value;
}

Convert Value to an integer Final value.
Award Final value Userpoints to the user of your choice.


Drupal JavaScript settings versus jQuery.data()

Personally, I used Drupal.settings as a read-only object for communicating settings and configuration information from PHP to JS.  Runtime state isn't appropriate here.

jQuery.data() should only really be used to pull out data attributes that you have set via PHP, and for setting data that is specific to that element-only.

Runtime logic and state should be stored in its own closure.  I use a variant of the Javascript Module Pattern, which I have adapted for Drupal.  Boilerplate looks like:

var FOO = (function(me, $, Drupal, undefined) {
    me.name = "FOO";

    // local properties

    var foo = null;
    var bar = null;

    // local functions

    function somethingAwesome () {
        console.log(me.name + '.' + arguments.callee.name + '()');
    }

    // global properties

    me.baz = null;

    // global functions

    me.somethingAwesomer () = function somethingAwesomer {
        console.log(me.name + '.' + arguments.callee.name + '()');
    };

    // Drupal

    function init (context, settings) {
        if (settings.foo) {
            console.log(me.name + '.' + arguments.callee.name + '()', $.fn.jquery);

            // do stuff
        }

        Drupal.behaviors[me.name] = undefined;
    };

    Drupal.behaviors[me.name] = {
        attach: init
    };

    return me;
}(FOO || {}, jQuery, Drupal));

I don't do a lot of true behaviors, though, hence making my initialization function a oneshot.


Modules to extend the Display Suite module?

I really like the combination of Display suite with Custom Formatters - http://drupal.org/project/custom_formatters & with the Omega Theme, with these tools you can almost entirely skip having to use tpl.php files to theme your site's layout and content.

Also listed on the Display suite page you have Field Group - http://drupal.org/project/field_group & Rendable elemenets - http://drupal.org/project/rel However Rendable elements doesn't seem to work that well quite yet but it looks promising.


You can use a deriver class for this.

In your foo.links.menu.yml file

entity.node.canonical:
  deriver: '\Drupal\foo\Plugin\Deriver\FooMenuLinkDeriver'
  route_name: entity.node.canonical

In Drupal\foo\Plugin\Deriver\FooMenuLinkDeriver

class FooMenuLinkDeriver extends DeriverBase implements ContainerDeriverInterface {
  public function getDerivativeDefinitions($base) {
    $plugin_definitions = [];
    foreach (Node::loadMultiple() as $nid => $node) {
      $plugin_definitions[$nid] = $base;
      $plugin_definitions[$nid]['route_parameters']['node'] = $nid;
      $plugin_definitions[$nid]['title'] = $node->label();
    }
    return $plugin_definitions;
  }


How to add Wishlist/Add to Cart in all products shown in front page in drupal 7?

Install and enable the Commerce Wishlist module and in views add the Commerce Product: Add to Cart form field, then you can see Wishlist/AddToCart button. Also Enable the checkbox "Link products added to the cart from this display to the current path the customer is viewing where the View is rendered".

Don't forget to set permission and configuration.

  Features

  Provides an “Add to Wishlist” button on the display product node;
  Creates a customizable list with Views to display all products on the Wishlist – both as a page and as a block;
  Recognizes and stores product variations;
  Makes it possible for users to easily delete or switch products in their Wishlist to their Shopping Cart with the click of a button;


Show menu link as expanded when on node pages for a content type?

Menu Trail By Path modules does this is the node's paths are children of the parent.
http://drupal.org/project/menu_trail_by_path


Language switcher does not have current page query parameters

It seems that when I upgrade from 8.1.x (8.1.10) to 8.2.x (8.2.6) it fixes the problem. So it was a core bug.


How to create a Size field on Commerce product content fields?

I'd go for another solution/approach, as detailed below ...

Commerce Bulk Product Creation

You may want to use the Commerce Bulk Product Creation module. Excerpt from its project page:

  ... facilitates the creation of groups of related products in bulk. Product administrators can select a number of options for various fields, and a product will be created for all possible combinations of these values. Out of the box, only list fields are supported for this, but an API exists to enable other types of fields for 'combination creation'.

Attention: this module doesn't have an official release yet (only an RC6), though with over 1.200 reported installs, it seems it is pretty stable / trustworthy.

Commerce Backoffice

Another option is to use the Commerce Backoffice module, e.g. because of the auto creation of product display nodes. It provides the backoffice functionality present in Commerce Kickstart (V2), and contains these sub-modules:

Commerce Backoffice Product (commerce_backoffice_product).
Commerce Backoffice Order (commerce_backoffice_order).
Commerce Backoffice Content (commerce_backoffice_content).

This module (and a few dependencies) provides the rich store owner experience that has made Commerce Kickstart 2 so popular (and prevents that you have to install the entire Commerce Kickstart distribution). And there is a great video introduction about it also.

Note: if you use Commerce Backoffice, you most probably also want to use the Shiny administration theme, also used in Commerce Kickstart (V2).


Drupal 7 Commerce Price field not available to views

You should add Content: Product as a relation to this view. Then you'll have all the fields from the product available in the view.


How to implement a mysql date or datetime field correctly in hook_schema()?

You should provide a fallback type (varchar) for the case that the database is not mysql.

'pubblish_date' => array(
  'description' => t('The pubblish date for the single news'),
  'type' => 'varchar',
  'mysql_type' => 'datetime',
  'not null' => FALSE,
),
'unpublish_date' => array(
  'description' => t('The unpublish date for the single news'),
  'type' => 'varchar',
  'mysql_type' => 'datetime',
  'not null' => FALSE,
),

However, the messages you see come from the Schema module. This problem is already recorded as issue #468644.

The implementation of the mysql datetime in your schema is fine. You can safely ignore these messages.  I would say that these "advice messages" are caused by a bug in the Schema module.


How to show Users and Nodes in a single view?

One option is to add a user view as a footer to the node view. The footer can be configured to inherit the same contextual filters as the main view.

You can't get joint paging or joint filtering using this approach but it works in some scenarios.

I've also hacked into the views hooks before and manually created a db join but that is a nightmare to maintain so I wouldn't recommend it.


How to show a user's friends with only the Views and Flag module?

Step 1:

Use the Flag module to create a flag labeled "Friend" (or something like that). Here is such Flag definition (in export format) you could use for it (just import it in your own site):

$flags = array();
// Exported flag: "Friend".
$flags['friend'] = array (
  'entity_type' => 'user',
  'title' => 'Friend',
  'global' => '0',
  'types' =>
  array (
  ),
  'flag_short' => 'Friend',
  'flag_long' => 'Mark as friend',
  'flag_message' => 'User marked as friend',
  'unflag_short' => 'Unfriend',
  'unflag_long' => 'Remove as friend',
  'unflag_message' => 'User removed as friend',
  'unflag_denied_text' => '',
  'link_type' => 'toggle',
  'weight' => 0,
  'show_in_links' =>
  array (
    'full' => 'full',
  ),
  'show_as_field' => 0,
  'show_on_form' => 0,
  'access_author' => '',
  'show_contextual_link' => 0,
  'show_on_profile' => 1,
  'access_uid' => 'others',
  'api_version' => 3,
);
return $flags;

Step 2:

Use the Views module to create a view of users that flagged other users with that "Friend" flag.  Here is such view (in export format) you could use for it (just import it in your own site):

$view = new view();
$view->name = 'my_friends';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'users';
$view->human_name = 'My friends';
$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'] = 'Friends';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['access']['perm'] = 'access user profiles';
$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'] = 'table';
/* Relationship: Flags: friend */
$handler->display->display_options['relationships']['flag_content_rel']['id'] = 'flag_content_rel';
$handler->display->display_options['relationships']['flag_content_rel']['table'] = 'users';
$handler->display->display_options['relationships']['flag_content_rel']['field'] = 'flag_content_rel';
$handler->display->display_options['relationships']['flag_content_rel']['flag'] = 'friend';
/* Field: User: Name */
$handler->display->display_options['fields']['name']['id'] = 'name';
$handler->display->display_options['fields']['name']['table'] = 'users';
$handler->display->display_options['fields']['name']['field'] = 'name';
$handler->display->display_options['fields']['name']['alter']['word_boundary'] = FALSE;
$handler->display->display_options['fields']['name']['alter']['ellipsis'] = FALSE;
/* Field: User: Last login */
$handler->display->display_options['fields']['login']['id'] = 'login';
$handler->display->display_options['fields']['login']['table'] = 'users';
$handler->display->display_options['fields']['login']['field'] = 'login';
$handler->display->display_options['fields']['login']['date_format'] = 'long';
$handler->display->display_options['fields']['login']['second_date_format'] = 'long';
/* Field: User: Uid */
$handler->display->display_options['fields']['uid']['id'] = 'uid';
$handler->display->display_options['fields']['uid']['table'] = 'users';
$handler->display->display_options['fields']['uid']['field'] = 'uid';
/* Field: Flags: Flagged time */
$handler->display->display_options['fields']['timestamp']['id'] = 'timestamp';
$handler->display->display_options['fields']['timestamp']['table'] = 'flagging';
$handler->display->display_options['fields']['timestamp']['field'] = 'timestamp';
$handler->display->display_options['fields']['timestamp']['relationship'] = 'flag_content_rel';
$handler->display->display_options['fields']['timestamp']['date_format'] = 'long';
$handler->display->display_options['fields']['timestamp']['second_date_format'] = 'long';
/* Sort criterion: User: Created date */
$handler->display->display_options['sorts']['created']['id'] = 'created';
$handler->display->display_options['sorts']['created']['table'] = 'users';
$handler->display->display_options['sorts']['created']['field'] = 'created';
$handler->display->display_options['sorts']['created']['order'] = 'DESC';
/* Filter criterion: User: Active */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'users';
$handler->display->display_options['filters']['status']['field'] = 'status';
$handler->display->display_options['filters']['status']['value'] = '1';
$handler->display->display_options['filters']['status']['group'] = 1;
$handler->display->display_options['filters']['status']['expose']['operator'] = FALSE;

/* Display: Page */
$handler = $view->new_display('page', 'Page', 'page');
$handler->display->display_options['path'] = 'user/%/friends';
$handler->display->display_options['menu']['type'] = 'tab';
$handler->display->display_options['menu']['title'] = 'Friends';
$handler->display->display_options['menu']['description'] = 'Users marked as friends';
$handler->display->display_options['menu']['weight'] = '9';
$handler->display->display_options['menu']['name'] = 'user-menu';
$handler->display->display_options['menu']['context'] = 0;
$handler->display->display_options['menu']['context_only_inline'] = 0;

Result

After you enable the view, the result of it is that it'll show a tabular list of users, via path user/%/friends, and it will add a "Friends" tab on the user profile page (also).

Here is a sample of such table:

Name           ! Last login                  ! Uid
---------------+-----------------------------+----
Dries.Buytaert ! Monday, May 2, 2016 - 18:19 ! 19
Demo.User      ! Friday, May 6, 2016 - 12:16 ! 8


Fatal error: Call to undefined function context_get()

Try installing Context module and if this does not solve, also also try installing the spaces module.


What is the reason to define indexes in hook_schema?

MySQL Indexes
You can start by reading the MySQL reference.
You are right in saying that index is useful when you use a condition in your query. Deciding which fields to index is not as easy as it looks, though. There are pros and cons to each index, and it is not right to say that having an index always boosts overall performance at the expense of disk space.
Using index results in faster lookup of data when queries use the indexed columns in its conditions; however, large indexes can slow things down in cases of heavy inserts or updates to the table as any update to the rows result in updates to the index as well.
Therefore, you have to carefully decide if it is worth adding an index to the column even if you are going to use it in a query. In most cases it is.
On the next level, when you are using multi-column indexes, you have to be even more careful about the queries. Suppose you define:
CREATE TABLE test (
    id         INT NOT NULL,
    last_name  CHAR(30) NOT NULL,
    first_name CHAR(30) NOT NULL,
    PRIMARY KEY (id),
    INDEX name (last_name,first_name)
);

You might expect a query like this to use an index, but it won't.
SELECT * FROM test WHERE first_name = 'hw';

The reason is explained in the documentation:

The name index is an index over the last_name and first_name columns. The index can be used for lookups in queries that specify values in a known range for combinations of last_name and first_name values. It can also be used for queries that specify just a last_name value because that column is a leftmost prefix of the index (as described later in this section).

Drupal
As far as Drupal is concerned, it uses the Schema API to define those indexes. As you would see, these are common fields that are used in queries on the node table.


Insert data from sql file when call hook_schema on drupal 7

You can try this, hope it helps.

$db = new PDO($dsn, $user, $password);
$sql = file_get_contents('file.sql');
$qr = $db->exec($sql);

Otherwise try this, but i am also not aware of this correctly,

function my_module_install() {
  // Get the contents of the .sql file.
  $sql = file_get_contents(drupal_get_path('module', 'my_module') . '/module.sql');
  // Split into individual statements based on new lines.
  $statements = preg_split('/[\n\r]+/', $sql);
  foreach ($statements as $query) {
    db_query($query);
  }
}


Additional custom Omega breakpoint CSS files

I found out how to do it, you can do it like this in the template.php file of your theme

// Adds the Delta responsive stylesheets
$theme = alpha_get_theme();
$layouts = $theme->grids['alpha_default']['layouts'];
$keys = array_keys($layouts);
for ($i = 0; $i < 3; $i++) {
    drupal_add_css(drupal_get_path('theme', 'MYTHEME') . '/css/CUSTOM-' . $keys[$i] . '.css', array('group' => CSS_THEME, 'weight' => (120 - $i), 'media' => $layouts[$keys[$i]]['media']));
}

This will now look for your own CSS files called

/css/CUSTOM-narrow.css
/css/CUSTOM-normal.css
/css/CUSTOM-wide.css

And call them in the same way your other breakpoints are called, and if you're looking for the ability to add your own separate stylesheets separate to the normal ones, this'll do it.


After digging around some more I have found the solution. In your module you need to implement the hook_file_download() function. This function determines whether a user has the permission to view the file. It should look something similar to this:

function my_module_file_download($uri) {

  // Get the file record based on the URI. If not in the database just return.
  $files = file_load_multiple(array(), array('uri' => $uri));
  if (count($files)) {
    foreach ($files as $item) {
      // Since some database servers sometimes use a case-insensitive comparison
      // by default, double check that the filename is an exact match.
      if ($item->uri === $uri) {
        $file = $item;
        break;
      }
    }
  }

  if (!isset($file)) {
    return;
  }

  // Put your permission check code here.
  $can_access_file = check user permission function

  // When done perform the following code
  if ($can_access_file) {
    $headers = file_get_content_headers($file);
    return $headers;
  }
  return -1; // return that user does not have access
}

Hopefully this will help others with similar problems.


Help implementing Supersized.js in Drupal 7

There are a few issues here.

It's not in Drupal best practices to add a script to html.tpl.php
That being said, there are two ways to do it. (a) You can add it to your theme's .info file and call a .js file script from there (i.e. "scripts.js") in your theme folder, ideally in a "js" or "scripts" sub-folder if you need this site-wide (b)  If you don't need it site-wide or you can call it with drupal_add_js in your theme's template.php file to target only specific pages / paths
The way Javascript gets called has changed in Drupal 7

The main new thing is to include something like:

(function ($) {
//needed for drupal 7
Drupal.behaviors.myTheme = {
attach: function(context, settings) {
// end drupal 7 syntax

... at the top of your script.

so a clean version should work like so:

(function ($) {

//needed for drupal 7
Drupal.behaviors.myTheme = {
attach: function(context, settings) {
// end dtupal 7 syntax

            $.supersized({

                //Functionality
                slideshow               :   1,      //Slideshow on/off
                autoplay                :   1,      //Slideshow starts playing automatically
                start_slide             :   1,      //Start slide (0 is random)
                random                  :   0,      //Randomize slide order (Ignores start slide)
                slide_interval          :   3000,   //Length between transitions
                transition              :   1,      //0-None, 1-Fade, 2-Slide Top, 3-Slide Right, 4-Slide Bottom, 5-Slide Left, 6-Carousel Right, 7-Carousel Left
                transition_speed        :   500,    //Speed of transition
                new_window              :   1,      //Image links open in new window/tab
                pause_hover             :   0,      //Pause slideshow on hover
                keyboard_nav            :   1,      //Keyboard navigation on/off
                performance             :   1,      //0-Normal, 1-Hybrid speed/quality, 2-Optimizes image quality, 3-Optimizes transition speed // (Only works for Firefox/IE, not Webkit)
                image_protect           :   1,      //Disables image dragging and right click with Javascript
                image_path              :   'img/', //Default image path

                //Size & Position
                min_width               :   0,      //Min width allowed (in pixels)
                min_height              :   0,      //Min height allowed (in pixels)
                vertical_center         :   1,      //Vertically center background
                horizontal_center       :   1,      //Horizontally center background
                fit_portrait            :   1,      //Portrait images will not exceed browser height
                fit_landscape           :   0,      //Landscape images will not exceed browser width

                //Components
                navigation              :   1,      //Slideshow controls on/off
                thumbnail_navigation    :   1,      //Thumbnail navigation
                slide_counter           :   1,      //Display slide numbers
                slide_captions          :   1,      //Slide caption (Pull from "title" in slides array)
                slides                  :   [       //Slideshow Images
                                                    {image : 'http://buildinternet.s3.amazonaws.com/projects/supersized/3.1/slides/quietchaos-kitty.jpg', title : 'Quiet Chaos by Kitty Gallannaugh', url : 'http://www.nonsensesociety.com/2010/12/kitty-gallannaugh/'},
                                                    {image : 'http://buildinternet.s3.amazonaws.com/projects/supersized/3.1/slides/wanderers-kitty.jpg', title : 'Wanderers by Kitty Gallannaugh', url : 'http://www.nonsensesociety.com/2010/12/kitty-gallannaugh/'},
                                                    {image : 'http://buildinternet.s3.amazonaws.com/projects/supersized/3.1/slides/apple-kitty.jpg', title : 'Applewood by Kitty Gallannaugh', url : 'http://www.nonsensesociety.com/2010/12/kitty-gallannaugh/'}
                                            ]

            });

//ending drupal 7 specific calls / syntax
}};
}) (jQuery);


Is there a Rules Condition for 'is user:' or 'is root user'?

Sure there is such Rules Condition. As an example, have a look at the Rule I included in my answer to "How to stop a Views block from displaying to admins, such as user/1?".

The Rules Condition included that answer performs a Data Comparison to check if the value of site:current-user:uid is not equal to 1 (in your case you'd want to check if it is equal to 1).

Note: This specific Rules Condition comes in handy for anything you want to enforce (or prohibit?) for super user user/1 (which typically skips all permissions), similar to what the question was about in the linked question here.


contextual filters takes arguments from entities whether in the url or not

you could build the url and match arguments with url parts


How can I trace the source of a redirect error listed in Administration -> Reports?

If you know the name of the failing redirect URI (such as user/register), the best is to scan through your database and look for redirect entries, e.g. using drush:

drush sql-dump --ordered-dump | grep "user/register"

Alternatively add dd() (from Devel) into drupal_goto() and log the backtrace of each call into the file, e.g.

dd(debug_backtrace(FALSE, 5));

and check drupal_debug.txt in your tmp folder.

Another trick include using DTrace and hook into static probes (if your PHP supports that: php -i | grep dtrace), for example (after running the script):

sudo dtrace -qn 'php*:::function-entry { printf("%Y: PHP function-entry:\t%s%s%s() in %s:%d\n", walltimestamp, copyinstr(arg3), copyinstr(arg4), copyinstr(arg0), basename(copyinstr(arg1)), (int)arg2); }'

then you may grep it and look for specific functions such as drupal_goto, so you may append to above:

| grep -B5 drupal_goto > trace.txt

so this will log into file all calls to drupal_goto with 5 function calls before.

See also: How to generate the function stack trace of the last request made?


Enabling Views module causing cron to fail

Sounds like either:

You have two copies of the Views module enabled somehow.
You have a problem with your server configuration in relation to op-code caching.

Check your "system" table in the database with:

SELECT name, filename, status FROM system WHERE name = 'views';

Check the results are as expected for your install.

For the op-code cache issue, check this thread:

  Cannot redeclare class view, updating to PHP5.5

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

It may be a problem with using multiple op-code caching methods, or xcache conf issue.


Install media_youtube. Add a field to user profiles of this type.


The implementation should be placed into the file MODULENAME.rules.inc, which gets automatically included when the hook is invoked.


Disabling the Menu Token module, then deleting the corrupted link, and re-enabling the module did the trick.

Thanks.


The subtheme should inherit all of the basetheme files by default. So in theory you should be able to update the base bootstrap theme and your subtheme will gain all the benefits of those updates (Apart from things you're base theme has overwritten.)

E.g. if in bootstrap you have a page.tpl.php and you also have one in your subtheme then updating the bootstrap page.tpl.php won't have any effect as your subtheme has its own version of page.tpl.php

But anything that hasn't been overwritten/customised by your sub theme should be automatically be picked up by your subtheme. So you don't need to know what version your subtheme is, its effectly whatever the current bootstrap version is your subtheme is a ofshoot of that.


Permissions to create a database with drush command?

I don't think Drush has an option for this built into the site-install method but you might find something under the sql-sync method, which I think has an option to create a database.

I don't know if it's appropriate for your situation but you might want to look at the Drupal Quickstart: Pre-made Development environment; it has a bunch of custom Drush commands included, one of which will set up an entire site (vhost file, database, file permissions, etc.) in one line:

drush quickstart-create all --domain=example1.dev

I've copied this command out and hacked it to pieces, and now I can install a fully configured Drupal site on my local Mac machine with a single terminal line:

drush isosc --domain=example.dev

I would thoroughly recommend doing this; I couldn't live without it now


Hiding view filter option based on another filter selection

Run the check on page page load, not just on click:

 ... wrapped in the usual Drupal boilerplate

disableFilter($('#edit-field-agegroup-value-1'));

$('#edit-field-agegroup-value-1').click(function() {
    disableFilter($(this));
});

function disableFilter(element) {
    if( element.is(':checked')) {
        $("#edit-field-classroom-value-3").prop('disabled', true);
     } else {
        $("#edit-field-classroom-value-3").prop('disabled', false);
     }
}


How to make View setting changes happen simultaneously with deployment of a template

You can export a view, via the views interface or the Features module. Both will version control the view, updating the view but chaining/updating the code (if no alterations have been made in the UI).

What I usually do, is to use a script that

Updates the code on the
Reverts features
Clears cache
Runs cron

This is done calling drush commands and works very well for updating sites that doesn't rely heavily on cached data.


How to translate node programmatically with correct revision translation affected value?

I just ran into this and this prevented my translated revision also appearing as a revision of my original:
$langcode = 'fr';
$node->setRevisionTranslationAffected(FALSE);
$node->addTranslation($langcode, ['title' => $node->getTitle()])->save();


How to get child terms based on parent terms between two different taxonomies

You'll need to load your content's term references and then load those term entities so you can follow your chain of taxonomy terms. There's many ways to do that; taxonomy_term_load_multiple() is one such function.

$tids = array();

// @TODO: Use the $nid that corresponds with your node
// @TODO: Replace field_program & field_topic with your taxonomy ref field name
$node = node_load($nid);
foreach ($node->field_programs[LANGUAGE_NONE] as $term) {
  $tids[] = $term['tid'];
}
$programs = taxonomy_term_load_multiple($tids);

// @TODO: Iterate over $programs and retrieve
// topic tid references from $program->field_topic[LANGUAGE_NONE]


What are the replacement patterns or tokens for Profile2 URL of a particular user?

Try like this

First Install Pathauto Module.
Login in drupal as administrator, and goto Configuration. Under 'SEARCH AND METADATA' select 'URL aliases'.
Select 'Pattern' tab and goto 'USER PATHS' and click on 'REPLACEMENT PATTERNS' a list will appear.
Select 'Users' and again some more option will be displayed, select 'name' and the 'pattern for user account page paths should be displayed as '[user:name]' and save it.
In the same window 'Bulk update' tab and check mark the User Paths and click Update.

The following output will be http://example.com/username.


Adding JS to a page is really not that hard, even though you need to use php.

For normal JS files, you could do something like this

drupal_add_js($path_to_js)

Drupal has however registered jQuery UI into libraries making it easier to add both JS and CSS files for certain jQuery UI plugins. This can be done using

drupal_add_library($module, $library);

All the jQuery UI plugins exist in the system module, so you could do

drupal_add_library('system', 'ui');

or

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

Some of these plugins have dependencies because they use other plugins. Drupal handles this very cleverly and will included the components needed.

You can see the full list of jQuery plugins here. This is formatted as a PHP array, but generally the naming convention is ui.PLUGIN-NAME.

If you need to add the JS on every page you could simply add a preprocess page hook and add them there. This would look something like this in the template.php file.

function NAME_OF_THEME_preprocess_page(&$variables) {
  drupal_add_library('system', 'ui');
  drupal_add_library('system', 'ui.accordion');
  drupal_add_library('system', 'effects.highlight');
}


You need to use the EntityFieldQuery instead of the SelectQuery that db_select uses. You should do something like this:

$query = new EntityFieldQuery();
$result = $query
  ->entityCondition('entity_type', 'node', '=')
  ->entityCondition('bundle', 'slider', '=')
  ->fieldCondition('fieldname', 'tid', $tid)
  ->propertyOrderBy('changed', 'DESC')
  ->range(0, 4)
  ->addTag('node_access')
  ->execute();

The results will be an array of objects containing the nid and vid.

Read more about the fieldCondition


I faced the same problem, and I managed to solve it using merlinofchaos's suggestion. I used form_load_include() just after form_state initialization:

  $form_state = array(
    'title' => t('Add new deal'),
    'ajax' => TRUE,
    'node' => $node,
  );

  $form_state['build_info']['args'] = isset($form_state['build_info']['args']) ? $form_state['build_info']['args'] : array($node);
  form_load_include($form_state, 'inc', 'node', 'node.pages');


Feed importer: field collection processor settings

Finally got it to work!

Settings for Field collection processor

Do not update existing field collection item

Field name: (The machine-readable name of the field collection)

Host entity type: Profile

Is field: unchecked (FALSE)

Field/property name of Host entity GUID: pid

Identifier field name: pid

Mapping for Field collection processor

pid => Host Entity GUID

(and my other fields of course)

Note:

pid is the Profile ID.


how to custom position drupal login field

Go to "Blocks" under "Structure" (admin/structure/blocks if I'm not wrong). You'll find the "User Login" block and you can position it where you want, depending on the theme you have. It might be named "Sidebar" or "Sidebar Left (Right)" or "Sidebar First (Second)".


Can't find file to patch at input line 11, File to patch:?

The patch is trying to alter the install.php file that comes with Drupal, but it doesn't find it. That file is normally removed, once Drupal has been installed.

What the command line is prompting for is the name of the file to patch, in the case has been renamed, or moved in a different directory.

Keep in mind that the SimpleTest module should not be installed in a production server, but in a development site.


How to get notifications for unpublished content?

Part 1 - Notifications
Have a look at the Menu Badges module to add such notifications to any menu item and/or menu tab of your choice.
Here are some details about it (from its project page):

Provides a method for adding iOS-style badges to menu items. (see screenshot)

Adding Badges to Menus
Once enabled, go to Administration > Structure > Menus, and click "list links" next to the menu containing the target item. Click "edit" next to the item and select the badge to display with the Display Menu Badge select box.
Adding Badges to Tabs
For adding badges to menu tabs, there is a tab under Administration > Structure > Menus called "Tab Menu Badges". Search for the menu router path of the tab you want to alter, then select a badge from the corresponding select box.
Badge Types
The module includes five example badges, and new badges can be created easily with Views. Modules can also supply their own badges with a hook implementation. See the README.txt file for details.

Because of how it integrates with the Views module, you basically reduce the solution for any type of notification to something like "Just create an appropriate view of it".
Video tutorials:

Defining Menu Badges with Views in Drupal, from the module maintainer, which shows how to use it for a custom view with a menu tab "unpublished content" within admin/content.
Drupal 7 Menu Badges Module.

Part 2 - View unpublished content
You may want/have to combine this also with using the view_unpublished module. Some details from its project page:

This module allows you to grant access for specific user roles to view unpublished nodes of a specific type. Access control is quite granular in this regard.


Calculate difference between two dates in Webform

This is a bug in the Webform module. I created the below ticket to address this issue.

Improve Computed Twig element validation to support complex calculations


How to set up a repeated “field set” with unlimited time and event?

This is possible using the "double field" module (https://www.drupal.org/project/double_field) and using the "field permissions" module (https://www.drupal.org/project/field_permissions).

In the users' account settings add a double field, set it up as date/text combination, allow unlimited values. Use the field permissions setting to permit access to specific roles only.

This does't allow to use images to be used, unfortunately.

An alternative idea is using a paragraphs field (https://www.drupal.org/project/paragraphs), where you can define a paragraphs item with any fields you need. Again, set to unlimited allowed values and setting field permissions.


I don't think reCAPTCHA module provides front-end validation. Have you tried performing front-end validation using reCAPTCHA API? You could try something like this:

 $('form').submit(function () {
   if (!grecaptcha.getResponse()) {
     event.preventDefault();
     $('reCAPTCHA is invalid').insertAfter('.g-recaptcha');}
  });


How do I use the Save Draft module for a particular content type only?

Currently you have to install the 7.x-1.x-dev version to get settings per content type.

Once you install that version you can configure the settings on the node type settings form (eg. admin/structure/types/manage/article).


How to set order of Grouping Field in Format Settings

First, you can set the weight of the Project Type terms in the vocabulary.
Then you have to create the following relationship:

Entity Reference: Referenced Entity
A bridge to the Taxonomy term entity that is referenced via field_project_type

Then, add a Sort Criterion (first) Taxonomy term: Weight using the above relationship.


How do I add an additional submit handler in commerce checkout form?

What you are doing is correct.

The problem is that Drupal Commerce has defined the submit action on the buttons that is clicked, which will be used instead of the submit handlers defined on the form itself. So you need to add your submit handlers to the buttons (Cancel, Continue) that you want to use your submit function.

$form['buttons']['continue']['#submit'][]='c_coupon_review_submit';


File directory token - image field - node author

Have a look at this issue that explains why you cannot use node tokens in Views: https://www.drupal.org/node/1788414

  This is a limitation of Drupal core - it does not provide any node
  context for token replacement aside from the global tokens that are
  available. You will need a module like
  http://drupal.org/project/filefield_paths in order to use node tokens
  in the file upload directory tokens.

The File (Field) Paths module provides this functionality:

  The File (Field) Paths module extends the default functionality of
  Drupal's core File module, Image module and many other File upload
  modules, by adding the ability to use entity based tokens in
  destination paths and file names.

  In simple terms, File (Field) Paths allows you to automatically sort
  and rename your uploaded files using token based replacement patterns
  to maintain a nice clean filesystem.

That should allow you to use the node:author token.


How to make a CCK field appear as single-value on one Node Type, and multi-value on another Node Type?

You need to implement the hook_nodeapi and use the operation "presave"

Presave will have all the data submitted from the form and you can then alter it here just before it goes into the database.

If you have the devel module do a dpm($node); to see what data you are getting.

the important thing is that the field for multi values will be expecting an array so it may be as simple as grabbing the data from the form and adjusting it to pass it as an array.

EDIT

Aah ok validation....

I would probably turn off validation for that item by using the: '#element_validate' property, this way you can target validation for that specific element see the fapi docs on drupal.
http://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/6#element_validate


Bootstrap and require a method from a separate module

For this case you have to add one additional step to your bootstrap code.

Put $kernel->preHandle($request); right below the $kernel->boot();


How can I add a taxonomy-based view to a page?

Go edit the view that you created and hit add+ next to the view name and then block. By adding a block a new block will appear in the Structure-> Blocks Section and then you can place it anywhere you like.


Is there any way to use SQL Views in Drupal Views

I dont know your use-case. But look at new Raw SQL Query module, and see its attached screenshost(s) for how you define the SELECT queries and the report pages it generates:

  It builds "tables" (mysql views using "CREATE VIEW" statement) based
  on raw sql queries. I would say it is like a lightweight version of a
  materialized views approach. It uses Ctools to manage data storage and
  PHPExcel to export data into a Excel file :) After installation, go to
  admin/config/development/raw_sql_query Do not forget clean cache after
  you store a query.

It sounds like this module is caching the returned data (I'm not 100% sure). But that would be helpful since a mysql view is literally a SELECT query upon every access to the data.


7: Form API: managed_file: AJAX upload error "Undefined index ... in file_ajax_upload()"

You need to pass the parameters by reference if you want changes to persist outside the function scope:

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


REST API doesn't work with CURL because you don't send cookie after login. By default, Drupal 8 using HTTP Basic Authentication after the login user has a cookie. Browser (include postman) will store this cookie and send to the server any request. So It works normally.

If you want REST API working with CURL. You need to store cookie when request login, and send this cookie to check status login like this:

curl -c ~/cookie.txt
--header "Content-Type: application/json" \
--request POST \
--data '{"name":"admin", "pass":"admin"}'\
https://dfs3w.ply.st/user/login?_format=json

in line

-c ~/cookie.txt

mean that write cookie to file cookie.txt.

After login successfully, I will read cookie and send cookie to check status login:

curl -b ~/cookie.txt
--header "Content-Type: application/json" \
--header "X-CSRF-Token: -LSxwKsxEnupbeM4NANfV1JLtlGeqK0dRPxhRRSFvkU"\
--request GET \
https://dfs3w.ply.st/user/login_status?_format=json


AJAX form submit by clicking on any element with the #ajax property

Maybe this code:

$( "[type="checkbox"]' ).change(function() {
  $( "form" ).submit();
});

When a checkbox is change, it submits the form.


To keep this convo going even though I do not have a definitive answer...

I feel that is a pretty big question with a fair bit of config and templating even... So my short answer would be Views and/or Blocks. Depending on your needs maybe you could do just a views page with filters and relationships as you need populated with commerce entities and content types. Maybe you need views blocks, blocks, and content types with template files to render everything on the same page. My gut just tells me that's the pace to start. Views is Drupal cores way of bringing many things together.


I actually found the answer myself. Using the Better Exposed Filters module did the trick.

From the module's description:

  Provide instant feedback by updating the View using AJAX whenever an exposed filter is changed.


Why doesn't the "Edit" option always appear?

The user looking at the page the screenshot was taken on doesn't have the required level of access/permissions to edit those nodes.

There are many different ways that access/permissions can be configured to a single node, so you'll need to do some digging in your installation to find out whether it's simple core permissions, a contributed module, or a custom module that's causing the problem.


Arguably, a much more straightforward approach is to not muck with your user's group assignments at all and instead run drush as the web server user (ie: apache, www-data).

Use sudo:

sudo -u apache drush

or on debian/ubuntu:

sudo -u www-data drush

Create a command alias:

Then, to ensure that you always run drush like that, add an alias:

echo "alias drush='sudo -u apache drush'" >> ~/.bash_aliases

or on debian/ubuntu:

echo "alias drush='sudo -u www-data drush'" >> ~/.bash_aliases

Now when running any drush command, you'll be prompted for your password by sudo, and the command will run as the web server user. No more permissions problem reading and writing files.


How do I programatically get access to the file uploaded to a webform after a submission?

Well, as first posts go, it ended up as a "stupid" mistake on my end. The webfrom module is well documented and the solution was very straight forward. (In short I was pushing an array into the ->AddAtachment method in PHPMailer.) For reference to anyone else here is my working code:

[module_name]\src\Plugin\BusinessRulesAction\SMTPAuthEmail.php

namespace Drupal\[module_name]\Plugin\BusinessRulesAction;
use Drupal\[module_name]\Controller\[module_name]Controller;
use Drupal\business_rules\ActionInterface;
use Drupal\business_rules\Events\BusinessRulesEvent;
use Drupal\business_rules\ItemInterface;
use Drupal\business_rules\Plugin\BusinessRulesActionPlugin;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Render;
use Drupal\Core\File\FileSystem;
use Drupal\file\Entity\File;

class SMTPAuthEmail extends BusinessRulesActionPlugin {
    public function getSettingsForm(array &$form, FormStateInterface $form_state, ItemInterface $item) {
        //var_dump($item);
        $settings['email_settings'] = [
            '#type'          => 'fieldset',
            '#title'         => t('Email Settings'),
        ];
//this is just to show that I have a form for business rules that is being referenced later below.

    public function execute(ActionInterface $action, BusinessRulesEvent $event) {
    $send_email = new [module_name]Controller;
    $message = $action->getSettings();
    $css = file_get_contents(drupal_get_path('module', '[module_name]') . '/css/email.css');
    $entity_type = $event['entity']->getEntityTypeID();
    $node_storage = \Drupal::entityTypeManager()->getStorage($entity_type);
    $view_builder = \Drupal::entityTypeManager()->getViewBuilder($entity_type);
    $node = $node_storage->load($event['entity']->id());
    $build = $view_builder->view($node, 'table');
    $file_fields = $event['entity']->getWebform()->getElementsManagedFiles();
     if($file_fields){
        foreach ($file_fields as $file_field) {
            if (!empty($event['entity']->getData()[$file_field])) {
                $file_id = $event['entity']->getData()[$file_field];
                $file = \Drupal\file\Entity\File::load($file_id);
                $realpath = \Drupal::service('file_system')->realpath($file->getFileUri());
                $message['attachment'][] = $realpath;
            }
        }
    }
    $message['body'] = '<style>' . $css . '</style>' . render($build);
    $send_email->smtp_email($message);

}

[module_name]\src\Controller[ModuleName]Controller.php

class [ModuleName]Controller extends ControllerBase {

    public function smtp_email($data) {

        $mail = new PHPMailer();
        $mail->IsHTML(true);
        $mail->IsSMTP(); // enable SMTP
        $mail->SMTPDebug = 0; // debugging: 1 = errors and messages, 2 = messages only
        $mail->SMTPAuth = true; // authentication enabled
        if($data['tls']){
            $mail->SMTPSecure = 'tls'; // secure transfer enabled REQUIRED for Gmail
        }
        $mail->Host = $data['host'];
        $mail->Port = $data['port']; // or 587

        $mail->Username = $data['username'];
        $mail->Password = $data['password'];
        $mail->SetFrom($data['from']);
        $mail->Subject = $data['subject'];
        $mail->Body = $data['body'];
        if(isset($data['attachment'])) {
            foreach ($data['attachment'] as $attachment) {
                $mail->AddAttachment($attachment);
            }
        }
        foreach(explode(";",$data['to']) as $recipient) {
            $mail->AddAddress($recipient);
        }
        if(!$mail->Send()) {
            $message = "Mailer Error: " . $mail->ErrorInfo;
            $message_type = 'error';
        } else {
            $message =  "Message has been sent";
            $message_type = 'notice';
        }
        \Drupal::messenger()->addMessage(t($message), $message_type);
    }

}

I hope this helps someone!


With search_api_solr, how can I apply an significant field based boost when using solr 6.x?

None of the API function provided by Search API and Search API Solr Drupal work properly. You can either check solarium docs or switch back to Solr 5 or Solr 4. Boosts work properly with Solr 5.x. Data type indexed is also important. Try indexing it as Fulltext field.


You need to rewrite the output of the field and use PHP for the text string manipulations.

Two modules can help you do that. Note that you'll likely choose one of these two modules. they aren't dependent on each other. They can both help you get what you want in different ways.

Views PHP
Computed Field

You might need to turn the title off and create it instead in the View header using "Global: text" and turning tokens on their. The token for username (which is "[name]" will use the value from the written output you've used when defining the field.


Change views exposed filter value only on page reload

Just added a video link to show you : imgur.com/EmVha6e

You just need to add a conditional to check if it's not ajax

   $request = \Drupal::request();
   $is_ajax = $request->isXmlHttpRequest();
   if (!$is_ajax) {
     // code that sets the filter initial value
   }

Credit: How can I detect AJAX request inside Drupal?


Programmatically create a comment form for a node

FormBuilder::getForm() doesn't accept just an argument; after the first, the other arguments are:

  Any additional arguments are passed on to the functions called by \Drupal::formBuilder()->getForm(), including the unique form constructor function. For example, the node_edit form requires that a node object is passed in here when it is called. These are available to implementations of hook_form_alter() and hook_form_FORM_ID_alter() as the array $form_state->getBuildInfo()['args'].

So, \Drupal::formBuilder()->getForm('Drupal\comment\CommentForm', $node); would be perfectly fine. It's up to the form builder, using those arguments.


Provide the path as taxonomy/term/%
Install the pathauto module and override the path using the required patterns.


Drupal 8: Add custom class according to taxonomy in Views

You add taxonomy filed in view and Exclude from display this field.


Print User Registration Block Through template.php file

You won't need any alters. Just go to the template in which you want to place the registration form and add,

$form = drupal_get_form('user_register_form');
print drupal_render($form);

This will print the user registration form. It's always good to have a check for anonymous users as a wrapper of this output.

Edit #1 (After question update and comments)
I suppose you want to create a block that will appear in your "admin/structure/block" page and you can assign the block in any desired region? - Right? I don't think your question says the same but this can be done in the following way,

Create a hook_block_info() & hook_block_view()
In the hook_block_view() assign the "content" the following,

$form = drupal_get_form('user_register_form');
$block['content'] = drupal_render($form);

I hope this can solve your problem. I haven't tested this yet!


How do I use Url::setUnrouted() in a custom module?

Url::setUnrouted() is really an internal method used by the URL class.  It is used by the static constructor Url::fromUri() when the URI passed as argument isn't a route.

In general, you should create URL from one of the static constructor functions, and then use the public methods to change anything that you need.  And, paths in your own code should be set up as routes, whenever possible.

If you really need to create an unrouted URL to a static resource that can't be handled through other method (eg, JS and CSS should be handled using #attached), then you would do something like the following:

$url = Url::fromUri('base:some/path/foo.txt');


How to Get Custom Field Label Translation

You cannot use variables in t() function, it accepts only strings and placeholders with an array.

The i18n module has Field Translation module shipped with it, be sure you have enabled it as well.

There is also a good information on the following link about getting title fields translated as well.

Drupal 7 – Translate the title field label of content types


D7: Import localized menu programatically

You dont need to play directly with i18n. All you need is the correct configuration.
It also has a difference between translated and localized items. Translated items may point to different pages and may have different description (besides other customization). Localized item is the same item with just a different title on the menu for each language.

I think you want a translated item. Here is the recipe with some comments:

 <?php
 $menu_item = array(
    'link_title' => 'The menu link title',
    'menu_name'  => 'machine-name-of-the-menu', // It uses '-', not '_'
    'customized' => 1, // Must be 1 in order to not dispaly the link in any language
    'link_path'  => 'node/' . $node->nid, // menu_link_save() does not like aliases. Then 'nid' is used
    'language'  => 'en', // language is required in order to make the item translatable
  );
  $mlid = menu_link_save($menu_item); // You don't need to receive it in a variable
  $ml = menu_link_load($mlid); // I'm loading $mlid just to display the result and verify it
  print_r($ml); // Use print_r() only if you are testing on the block "Execute PHP"

I had a hard time to figure out the need of 'customized' and also the path alias issue.


Form selection with radios, ajax and taxonomy terms

I found a little solution by clearing the default value after output the form.
unset($form['step_2']['options']['type_2']['#default_value']);

But if the user goes back in the multistep form and comes to this point the default value isn`t set. It will not be recrate like the #options in the form array.


t() is a PHP function. You are looking for Drupal.t() which is the equivalent function Drupal makes available for JavaScript.

These are some example of how Drupal.t() and Drupal.formatPlural() can be used in JavaScript.

var comments = Drupal.t('Comments');
var commentsOnType = Drupal.t('Comments to @type posts', {'@type': typeName});
var commentCount = Drupal.formatPlural(count, '1 comment', '@count comments');
var commentCountOnType = Drupal.formatPlural(count, '1 comment on @type posts', '@count comments on @type posts', {'@type': typeName});

Notice what reported in Translating strings in JavaScript:

For performance reasons, Drupal caches the JavaScript files it has parsed. So, when you add or change strings in a JavaScript file, you have to clear the cache to have Drupal pick up the new strings and make them available for translation.
Automatic extraction does not work for packed JavaScript files. For this reason, module authors should only include unpacked versions of their JavaScript files. Drupal's JavaScript aggregator will create a packed version from these files anyway.

Just replace t() with Drupal.t(), and you are done.

var arrowimages = {
down: 'downarrowclass',
right: 'rightarrowclass'
};
var $mainNav = $('#navigation');
var $mainList = $mainNav.find('ul').eq(0);
var  optionsList = '<option value="" selected>'+ Drupal.t('Navigate...') + '</option>',
  $submenu = $mainList.find("ul").parent();

Your code also contains a syntax error: . is not the string concatenation operator, in JavaScript; JavaScript uses +, for that purpose.


Error When Create Drupal Commerce Product Display

This in a known bug, you should either start fresh or use the Commerce repair. The problem is most likely that a field that was expected wasn't installed properly. This could happen if you add hook_line_item_info to a module that's enabled.


Can't set view title in hook_views_views_pre_view

It's probably the Views module is calling drupal_set_title() right after invoking those hooks, so calling drupal_set_title() in those hook doesn't have the effect you are expecting. You could eventually use view::set_title in hook_views_pre_view() or hook_views_pre_render().

function mymodule_views_pre_view(&$view) {
  if ($view->name == 'the view you need to alter') {
    $view->set_title(t('New title'));
  }
}

You cannot assume those hooks are invoked when a view page is being rendered; it could be the view is embedded in a page for which the title change is not desired. This is similar as assuming hook_node_view() is being invoked when a node is rendered in its own page, and then calling drupal_goto() from that hook.


Renaming the label of the Title textfield

Go to Content type, you will have a list of content types of your site. Under Operations click on edit  for the content type you want to change the title.  Under Submission form  settings you can change the "Title field label"


How to make a popup appear on the side/bottom of the page instead of the center?

The Popup on Load module leverages the Colorbox module, and its jQuery plugin dependency, to style the pop up. The module allows for your own custom style which will let you adjust the popup position to where you want it. This is covered in its documentation.

  Add a custom Colorbox style to your theme

  The easiest way is to start with either the default style or one of
  the example styles included in the Colorbox JS library download.
  Simply copy the entire style folder to your theme and rename it to
  something logical like "mycolorbox". Inside that folder are both a
  .css and .js file, rename both of those as well to match your folder
  name: i.e. "colorbox_mycolorbox.css" and "colorbox_mycolorbox.js"

  Add entries in your theme's .info file for the Colorbox CSS/JS files:

stylesheets[all][] = mycolorbox/colorbox_mycolorbox.css
scripts[] = mycolorbox/colorbox_mycolorbox.js

  Go to "Configuration" » "Media" »
  "Colorbox" and select "None" under "Styles and Options". This will
  leave the styling of Colorbox up to your theme. Make any CSS
  adjustments to your "colorbox_mycolorbox.css" file.


Form returned from AJAX callback missing JS and CSS

I ended up loading the form with tabs in to my ajax-node div using the links api, but then within the form I made the submit button replace the form container.

My full solution:

/* Drupal caches all ids of form elements and when ajax request happen, this
 * results in the new form have id's appended with --2 --3 etc, so css breaks.
 * Unsetting this makes the ids always the same. Maybe hook_init is not the best
 * place for this, but for now it works.
 */
function mymodule_init() {
    if(isset($_POST['ajax_html_ids'])) {
        unset($_POST['ajax_html_ids']);
    }
}

function mymodule_form_{my_form_id}_alter(&$form, &$form_state, $form_id) {
    //only do the do if this is and ajax request
    if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
        $form['actions']['submit'] = array(
            '#type' => 'submit',
            '#value' => 'Save',
            '#ajax' => array(
                'wrapper' => 'my_form_id',
                'method' => 'replace',
                'callback' => 'mymodule_callback',
                'effect' => 'fade'
            ),
            '#submit' => array('node_form_submit'),
        );

        /* For some reason this _has_ to be in form_alter. Putting it in a submit
         * callback doesn't work. What this is doing is setting the changed time
         * of the form to be in the future, if we don't do this, when the form is
         * reloaded after a submit, it's not possible to submit the reloaded form
         * because Drupal thinks someone else has edited it (I think it checks
         * the last update time of the node VS this value). This adds a 5min window
         * where changes can still happen. It's not the best solution but I think
         * it will work.
         */
        $form['changed']['#default_value'] = time() + 300;
    }
}

function mymodule_callback(&$form, &$form_state) {
    $new_form = drupal_rebuild_form('my_form_id', $form_state, $form);
    $form_html = drupal_render($new_form);

    return $form_html;
}


Views- how can I hide one specific value of a series of checkboxes displayed in views?

You can remove it with jQuery. Find that element by the value and just do .remove().

Even though this is not the perfect solution, it needs least amount of time and you can use it in the short term.

[EDIT]

Check Views selective filters. They can limit the options only to the ones available in the results; all others will be hidden.


Generic field.html.twig template for a custom Entity

Add your own theme suggestion:
mymodule.module
/**
 * Implements hook_theme_suggestions_field_alter().
 */
function mymodule_theme_suggestions_field_alter(array &$suggestions, array $variables) {
  $element = $variables['element'];
  // place the least specific suggestion at the beginning of the array
  array_unshift($suggestions, 'field__' . $element['#entity_type']);

}


Which preprocess hook do I use to fire some HTML altering PHP?

you can use theme_preprocess_html(&$variables) OR my_module_preprocess_html(&$variables)

in $variables you will see $variables['classes_array']

if(in_array('class_name', $variables['classes_array'])) {

  //Do your changes

}

Hope this will help.


There are many possible ways to customize your front page content.

One of the easiest would be to create a view with page display and set the field order as you like and give a path to the view. Now you can change your frontpage to the path of this view (Configuration > Site Information - Default front page).

If you want to go with the standard front page and rearrange in the template as you described you could use drupal_is_front_page() to have different parts of the template for frontpage and other pages.


How to add time element to open date and close date when adding a quiz

You can convert it to an array using the php function substr

// lets assume $date = Array ('quiz_open' => '2016-05-12 21:17');

$year = substr($date['quiz_open'], 0, 4); // grabs 2016
$month = substr($date['quiz_open'], 5, 2); // grabs 05
$day = substr($date['quiz_open'], 8, 2); // grabs 12

$date = array ('quiz_close' => array (
                                'day' => $day,
                                'month' => $month,
                                'year' => $year,
                                     )
              );


Need to give a user "superadmin" status through database

How can I promote another user to superuser status through the
  database?

There's only one "superuser" or root user in Drupal. That user has uid 1

Perhaps you need to update that user's password.

In D6, using just SQL, you can go

UPDATE users SET pass = MD5('password') WHERE uid = 1;

and then login with that username and password.

Note, make sure that's ok with the current uid 1 user, if it's not you.


how to update a field created with field_create_instance

You can use a combination of field_info_instance() and field_update_instance():

// Load the instance
$instance = field_info_instance('user', $field_name, 'user');

// Make whatever changes you need to, e.g.
$instance['settings']['user_register_form'] = 0;

// And save it again
field_update_instance($instance);


How to Reload a Custom Drupal Theme (Without the Command Line)

The steps that so far work reliably for me with Drupal 8.9.1 to load a custom theme again without command-line access are:

Install and enable the Devel module. (You will only need to do this once.)
Put your site into maintenance mode.
Turn on Devel -> Settings -> Rebuild the theme registry on every page load.
Clear the caches.
Load the new copy of the theme from Appearance -> Install new theme -> Upload a module or theme archive to install.
Clear the caches.
Reload one of your pages to verify your theme changes.

The second "Clear the caches" (6) might be redundant.
So far, this has worked like a champ once I figured out all of the necessary steps.


Adding dynamic filter in module_invoke()

You want to use views_embed_view(), rather than module_invoke(), for this so you can pass the 'weekday' term as an argument to the view, such as in the following code:

print views_embed_view($view_name, $display_id, $argument);

There might be an easier way to do this in Drupal 7/Views by using contextual filters directly from the view itself; I'm not sure how you are planning on using jQuery to load each of these new blocks. Are you doing a load operation with the URL on each one? Is there any reason you need to use the # anchor attribute rather than a URL argument like http://www.example.com/place/Monday?

That could make it easier to set this up within views.


Which should I use and when: node_load() or entity_load()?

node_load is just a fancy wrapper for entity_load.

That is node_load calls node_load_multiple which is a wrapper for entity_load. This means that performance wise there isn't really much of a difference, which function you use, unless you have to load a lot of nodes.

node_load has many advantages over entity_load

It's simpler
It increases code readability
it returns the node object instead of an array with the node object(s)

So in all, node_load is a convenience that you always should use whenever possible, then resort to node_load_multiple for cases where you need to load many more nodes.

entity_load should be used for loading entities when you don't know the type, or have it stored in a variable, in which case you can do

entity_load($type, ...);


How can I manage a users collection of products?

Check out the Flag module.  You could create a product content type and then your users could flag which individual products they have.


How do I include a custom module translation?

Add interface translation project and interface translation server pattern definitions to custom_module.info.yml.
You can use a custom path for your translation po file by setting the interface translation server pattern to whatever you want.


How can I display the price field twice?

You should use Commerce Extra Price Formatters module.

Extra Price Formatters Implemented So Far

RRP / Your Price

Allows you to display the Retail Price and the User Price
for a product and optionally the amount the customer
will save.

Allows you to switch the display back to a single price if
there is no discount available on a particular product.
Formatted Price with Prefix and Suffix

Allows you to present a price in the style just £9.99 ex
VAT or only £9.99 for a limited time only.
Formatted Price with no decimal places

When you are selling items with whole unit prices, you
don't necessarily want to see £10.00. This formatter
lets you change the display to show £10. (use this with
care!)

There's a video demo here: http://www.youtube.com/watch?v=-WR3mKjou8M

Then you should add two price fields in your product content type. In your manage display tab you would be having a settings option to calculate your price excluding or including tax and other parameters and thus you can add two price fields.


What are the reasons that the "Show block on specific pages" settings wouldn't work?

It turns out that the issue was that there was, at some point, a theme with the same name but with different capitalization. It looks like this led to inconsistent results when looking up which blocks should be displayed and when. Once I removed all the entries in the block table to the old theme the problem was resolved.


How to use drupal_http_request for send data?

Your $url_login looks like the default URL scheme for a Ruby on Rails website that uses the devise login system. Here is a function I've used to login to a rails/devise backed web site.

/** Authenticate via Rails/Devise site */
function devise_login($email, $pass) {
   //Build up data to send to devise
   $data = array('user' => array('email' => $email, 'password'=>$pass));
   //Pull the url out of the drupal settings
   $url = variable_get('devise_authentication_url', '');
   if ($url != '') {
     $response = drupal_http_request($url, array(
       'method' => 'POST',
       'data' => json_encode($data),
       'max_redirects' => 0,
       'headers' => array('Content-Type' => 'application/json', 'Accept' => 'application/json'))
     );

     return = json_decode($response->data);
   }

   return FALSE;
}


There are some useful options, Please note that both Drupal Commerce and Ubercart have Marketplace modules which you could use in combination to achieve your desired functionalities:

A. Rooms helps with booking and room management, More info also available here

  Drupal Rooms is a booking and room management solution for hotels,
  vacation rentals and B&Bs.

  It allows an accommodation owner to:

Create rooms and assign availability (or on hold states) via a
calendar.
Manage pricing for rooms using calendars that allow to set pricing for entire seasons or just change it for specific dates.
Define optional add-ons for rooms. Charge either per-night or per-person. Handle children discounts. Create bookings and keep customer records.
Make rooms available for booking with a availability
search functionality and/or calendar - handling both immediate bookings and bookings following owner confirmation.
Search by Room Type.
Full integration with Commerce to manage payments, a range of different payment gateways, and a host of other e-commerce features.
Accept full or partial payments (deposits) using Commerce features.

B. Hotel Booking System For Ubercart

  The uc_hotel module is a hotel booking system for Drupal and Ubercart.

  It does not manage individual rooms, but rather lets you create room
  types, and set how many of each type are available for specific dates
  on the calendar. Each room type can be assigned a different rate, or
  be based off a single master rate and have a modifier applied to
  adjust that rate by a certain amount.

  You can vary the rate based on the number of adult and child
  occupants.

  The module also features an add-ons and upgrades sub module that
  allows you to bundle other date-based upgrades with the booking such
  as tennis lessons or spa treatments.

C. Open Hotel

  Open Hotel is a Drupal 7 Distribution that helps you create a full
  featured Hotel site with online booking and online availability.

Features

Online Availability
Online Booking
Multilingual
Photo Galleries
Responsive Design
Google Analytics E-Commerce Integrated
Free and Open-Source
Easy to integrate with any payments processor.
Search Engines Optimized


I've figured out the problem after lots of guessing. You'll need to use a contextual filter and use the hook_views_pre_view hook in a custom module to alter the $args variable.

function MODULENAME_views_pre_view($view, $display_id, &$args) {
    if ($view->id() === 'view_machine_name') {
        $args[0] = 'your value';
    }
}


Try to download it first and then install.

drupal module:download admin_toolbar
drupal module:install admin_toolbar


You could modify Best Responsive theme enlarging the page width. More precisely changing #wrap ID width from 960px to something bigger, like 1200px or a percentual value like 90%.

You can edit the style.css file and change the width from:

#wrap {
  width: 960px;
  margin: 0 auto;
  -moz-box-sizing: border-box;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
}

to:

#wrap {
  width: 90%;
  margin: 0 auto;
  -moz-box-sizing: border-box;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
}

You'll have to update some other elements width like #content and #sidebar using a percentual value and fix the sidebar background image.

Anyway the theme can easily be customized.

In this way the template is still responsive but on desktop the size is more wide.

I hope this will help.

Regards.


As far as the procedural method is concerned, you would use exactly the same method for a custom field as you would a contrib/core field.

Core field:

$node->body[LANGUAGE_NONE][0] = array(
  'value' = '
Some body text
',
  'format' => 'full_html',
);

Your custom field:

$node->field_whatever[LANGUAGE_NONE][0] = array(
  'esn_hex' => $some_val,
  'esn_dec' => $some_other_val,
  // etc...
);

To persist changes to both, use node_save() (or entity_save(), or whataver helper method the entity you're using provides).

node_save($node);

That's all you need to do. Manipulating the field tables manually is not recommended, as you bypass a lot of hooks that need to run, cache management, etc.

To use custom fields with an EntityMetadataWrapper, you need to go a bit further and describe the field and its columns to the entity module.

This involves adding property_type and property_callbacks to your field definition in hook_field_info(), and providing appropriate callbacks for those. There's a bit more information in this post


Although that limit appears sane to me, to adjust the maxlength, look at

commerce_line_item_field_widget_form

  $element['line_items'][$line_item_id]['quantity'] = array(
    '#type' => 'textfield',
    '#datatype' => 'integer',
    '#default_value' => $quantity,
    '#size' => 4,
    '#maxlength' => max(4, strlen($quantity)),
  );

You could use hook_field_widget_form_alter and adjust the #maxlength property there.


Twig/Drupal 8 custom cache context not working in node preprocess?

I finally found the solution. My scripts work pretty well, i just forgot one little thing about the cache modules Drupal enable by default in core.

I needed to disable "internal page cache" module and only keep "dynamic page cache" enabled. In fact "internal page cache" works for anonymous users only and caches the whole page in order to get better performance. It is therefore not possible to create dynamic parts and "max-age" or "cache context" doesn't work. So if you disable the module, drupal uses by default "dynamic page cache" and "max-age" or "cache context" will work then.

I hope this helps you.

More infos here :
http://wimleers.com/article/drupal-8-dynamic-page-cache


Why Drupal changes the module (system table) bootstrap value after i set it with an SQL query?

ok got it,

in system.module there is a function called _system_update_bootstrap_status()

this function changes bootstrap value to '1' for all modules that implement one (or more) of the hooks: 'boot', 'exit', 'watchdog', 'language_init'

so i just needed to implement an empty hook_boot() and my module is present in bootstrap.


The after_update case called is called after the user modifies his account from my understanding of hook_user.

So that would mean that the user account has been created and the user updates his profile such as changing user image or password etc., which would trigger update and after_update.

I guess when the user is created it is only normal that the insert is triggered. If you have customized the registration so that in course of the registration the user account has been created and while completion the account information is being modified by him the update and after_update would be triggered.

If you wish to get the uid of the user who's registered most recently I suggest you could implement hook_user with insert case and query the database to get the max(uid) which would be the recently added user's id, only making sure your module has a greater weight so that user module's insert of the user happens first and your retrieval of the uid follows it. Though my suggestion feels less than optimal I believe it would work.


You don't need entity_metadata_wrapper in this case.
You can get path of node using url() function.

$node = node_load($row->{$field->field_alias});
$nid = $node->nid;
$path_to_node = url("node/$nid");

And I agree with Елин Й's answer. You can use l() function. It already uses url() function. So you can build link with node pathauto alias using:

$node = node_load($row->{$field->field_alias});
print l(t('Go to Node'), 'node/' . $node->nid);


How do I programmatically delete an order?

Loading it like a normal entity did the trick.

How to load and delete commerce order programmatically

$ord_id=121;
$order = \Drupal::entityTypeManager()->getStorage('commerce_order')->load($ord_id);
$order->delete();

Here is the entire snippet on my ultimate goal which was deleting abandoned orders in the cart.
How to remove commerce orders automatically

How to delete ghost commerce registrations in cart

Custom cron to delete commerce orders programmatically

Load a view programmatically loop through values and delete orders

/**
 * Implements hook_cron().
 */
 function my_module_cron() {
   //load a view showing orders still in cart
   $view = \Drupal\views\Views::getView('commerce_carts');
   //the name of your display, i chose a simple rest display with the order_id field
   $view->setDisplay('rest_export_1');
   $view->execute();

   foreach($view->result as $row){
     //load the order
     $order = \Drupal::entityTypeManager()->getStorage('commerce_order')->load($row->order_id);
     $oid = $order->id();
     //delete the order
     $order->delete();
     //log to dblog
     \Drupal::logger('afc_commerce_registration')->notice('Clearing ghost registration, deleted: @oid.',
       array(
           '@oid' => $oid,
       ));
   }
 }

You can add the Created date field to the view, and test time values before deleting. In my case, it doesn't matter.

Thanks for the help everyone


Drupal 8 - Add custom HTML with script to embed on a page as block

You can use :

$build['test'] = [
  '#children' => $test_code,
];


Acquia Dev Desktop Redirects to Live Site

I encountered this problem tody, and it turns out that the securepages module causes it. After disable that module, everythin works.

Though, don't forget to enable the module before going online.


How to get Fixed Navigation when scrolling to the top

It turns out the answer is simple.  I just declare the javascript inside .info file.  And by using Drupal.behaiors I implement the jquery that target the navbar to fix upon scrolling.


How can we make the summary field auto expand on load?

You could do it with the Summary Options module.

This module provides site builders with additional options for the
'summary' field when using "Text Area with a Summary" widget.
Often, a summary or teaser field is used when displaying content in
views. Drupal already has built in support for a summary field,
however there is not much control of whether or not it is display, or
required.


How to allow registered users to enable / disable notifications for event nodes?

I would use the Flag module for this. It allows per user state toggling and integrates well with Views.

Create a Flag called notify.
Change the text that is shown to "Enable notifications" and "Disable notifications".
Use Rules and Views to send out your notifications.

For extra credit create a View that shows a User all of the nodes they are receiving notifications on.


Registration form to be submitted via ajax

You need the Ajax submit for any form module, here:

https://www.drupal.org/project/asaf


Beginner Drush question. Can't get Drush to do anything!

There is a known problem of using Drush with DevDesktop on MacOSX.

Quick fix

Instead of running drush like this:

$ drush status

Run it like this:

$ DEVDESKTOP_DRUPAL_SETTINGS_DIR="$HOME/.acquia/DevDesktop/DrupalSettings" drush status

Permanent fix

Everything is explained in this article:
http://btmash.com/article/2015-03-24/using-dev-desktop-composer-drush

Why is it happenenig?

Acquia DevDesktop keeps all credentials in a specific folder and let PHP have access to that location via a $_SERVER variable called $_SERVER['DEVDESKTOP_DRUPAL_SETTINGS_DIR']. This variable is provided by Apache and PHP only sees it is run by Apache. But when you use Drush, PHP is called directly and that variable does not exists anymore and Drush cannot find the database credentials.


#block-system-main-menu {
   float: left;
    top: 0;
    width: 100%;
}
#block-system-main-menu ul.menu
{
float: left; width: 100%;
}
#block-system-main-menu ul.menu li
{
float: left; width: 15%;
}

Use this css.it will help you

Simply put Your menu block above main page content block in same region and that menu will show above the rendered content or other option can be to change the order of the regions in the page.tpl.php file in your theme.


How to get an array of referenced entity ids from an entity reference field

As an alternative you can do it in one line with an array function instead of a loop:

$ids = array_column($entity->autoren->getValue(), 'target_id');

Edit: Use getValue() to only get the array of the field.


Is there a way to avoid anonymous user can see a node of a specific content type?

You can control the access to nodes in the hook hook_node_access():

mymodule.module:

use Drupal\node\NodeInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Access\AccessResult;

function mymodule_node_access(NodeInterface $node, $op, AccountInterface $account) {
  if ($account->isAnonymous() && $node->gettype() == 'article') {
    return AccessResult::forbidden()->cachePerPermissions();
  }
  return AccessResult::neutral()->cachePerPermissions();
}

This controls the direct access to the node, not the access in views. But this is what you probably want.


What is the difference between l() and url()?

l() creates a clickable link (an HTML anchor tag), while url() creates just a url. If you scroll down in the l() page you'll see the following source code:

  if ($use_theme) {
    return theme('link', array('text' => $text, 'path' => $path, 'options' => $options));
  }
  // The result of url() is a plain-text URL. Because we are using it here
  // in an HTML argument context, we need to encode it properly.
  return '' . ($options['html'] ? $text : check_plain($text)) . '';

theme_link() has a similar construction. So l() is using url() to construct the anchor.

So summarizing, the one is for clickable links, the other for plain (unclickable) url's.


Set default selected radio button on webform

There should be an option to set a default value when you go to edit that field in the webform. You have to set it to the "key" of the value you want selected by default. Your options should be listed as key|value under the field options.


Hook to log results of calls to drupal_mail() made by other modules?

The only way I can see is implementing hook_watchdog(), and look for a error message that matches "Error sending e-mail (from %from to %to)."

function mymodule_watchdog(array $log_entry) {
  if ($log_entry['message'] == 'Error sending e-mail (from %from to %to)') {
    // ...
  }
}

The alternative would be implementing a class that replaces DefaultMailSystem, which is a class implementing MailSystemInterface. To achieve this, it is enough to change the value of the mail_system Drupal variable.


how to add my custom template of heatbeat

I had the same problem and what you should do is replace

/**
 * Implement hook_ctools_plugin_api().
 *
 * This hook is needed to let ctools know about exportables.
 * @see heartbeat_og_ctools_plugin_api
 */
function love_ctools_plugin_api($module, $api) {
  if ($module == 'love' && $api == 'love') {
    return array('version' => 1);
  }
}

by

/**
 * Implement hook_ctools_plugin_api().
 *
 * This hook is needed to let ctools know about exportables.
 * @see heartbeat_og_ctools_plugin_api
 */
function love_ctools_plugin_api($module, $api) {
  if ($module == 'heartbeat' && $api == 'heartbeat') {
    return array('version' => 1);
  }
}

and after a cache flush, it should appear in heartbeat templates


How to change name of result of rest export?

The HTTP header Content-Disposition will suggest the filename the browser will save as. What's needed here is to make the REST export to add the HTTP header.

It turns out there's an existing issue for the CSV Serialization module. The current patch in the issue will take the last part of the URL after the slash and appends .csv to it (e.g. 2.csv in your example). You could modify the patch to use whatever filename you want to use for your CSV export.


Overwrite field description in an image widget

Using hook_field_widget_form_alter You can do this:

function MYMODULE_field_widget_form_alter(&$element, \Drupal\Core\Form\FormStateInterface $form_state, $context) {
  if ($context['field']['field_name'] == 'field_image_top') {
    // Loop through the element children (there will always be at least one).
    foreach (element_children($element) as $key => $child) {
      // Add the new process function to the element

      $element[$key]['#process'][] = 'MYMODULE_image_field_widget_process';
    }
  }
}

function MYMODULE_image_field_widget_process($element, \Drupal\Core\Form\FormStateInterface $form_state, $form) {
  // Change the title field label and description

 $element['title']['#description'] = 'SOME NEW DESCRIPTION HERE.';
 return $element;
}


Which module will allow me to see the two buttons "Customize this page" and "Change the layout"?

Panels and "Panels In-Place Editor" (sub-module of panels)


How do I programmatically render a view with contextual filters?

Basing on the code used by views_get_view_result(), I would use the following code, as code equivalent to the one you show in the question.

  $args = [$tid];
  $view = Views::getView('test_view');
  if (is_object($view)) {
    $view->setArguments($args);
    $view->setDisplay('block');
    $view->preExecute();
    $view->execute();
    $content = $view->buildRenderable('block', $args);
  }


Sending multiple attachment files by email

Try as $message['attachments'][] instead of $message['attachments']
example
$message['attachments'][] = $params['attachment2'];


How do I overwrite the particular webform submit event in template.php?

Try hook_form_alter() or hook_form_FORM_ID_alter(). This will help you to alter the array of the submission handlers and add a new submission handler.

function hook_form_alter(&$form, &$form_state, $form_id) {
  if($form_id == 'Your-Webform-ID') {
    $form['#submit'][] = 'custom_settings_form_submit';
  }
}

function custom_settings_form_submit($form, &$form_state) {
  // Your code here.
}


When a form has a validation error, the form is rebuilt from cache, meaning that the form function isn't invoked.

I could move the drupal_set_message call over to a #process or #preprocess function on the form itself or on one of the methods. These should be called again.

If the form is displayed with hook_menu you could also make a callback function which calls drupal_set_message and then fetches the form. There are a lot of ways to get around this.


As per your requirement it seems Activity module will suite you. But again this module is in Dev version for Drupal 7. So if you are ready to use Rules module then go ahead. Since you are only tracking the node create & edits then in Rules module you will get all the conditions and events.

But if you are also okay with developing custom module then I'd suggest to write a custom module and with all the HOOKs provided for nodes you can create the desired records and store those in a table. See the HOOKs for nodes here.

Let me know if I can assist you with creating a custom module.


Composer does not install Calendar Module

Is the module installing and working locally? I've had a similar issue with dev modules before. The problem is that they will ship with a .git directory and sometimes when I try to commit the module to my project's git repo it won't be committed because of the .git in the submodule. I bet if you navigate to the calendar directory on your server it will be empty.

A solution to this is to remove the .git directory from the submodule, e.g. /modules/contrib/calendar/.git before committing to your project's repo. If you've already committed, git will probably still try to ignore the directory after you remove the .git from the submodule, but you can remedy this by using git rm -r --cached modules/contrib/calendar (or whatever appropriate path). Then you can git add and git commit the submodule.


How to put the widget to rate nodes in a view next to title?

Since you're using the Rate module, you should configure Views as shown in this image:

So what you need to do, is to configure the field "Votes:Value". As you can see in my image above, within the Appearance Dropdown I selected Rate Widget (compact). if you only have "Rate Widget option or Default" (as in your comment, it's probably because you have not yet added the required Relationships to your view.

Relationships is a way to join tables from another module. To get you going with this also, have a look at the next image:

Some more details about the 3 (numbered) annotations I added in this image:

That's where you add the Relationship, in this case you need to select Content:Votes.
After you added that relationship, within Fields you can now add a new field Votes:Value (that is: because of the relationship that was added, you'll be able to select this specific field from the list of available fields when you try to add an extra field).
After you completed the previous step, automagically in the preview area you'll see a preview of the views results you'll get (don't bother too much about the theming of that preview at this time, what counts is that the result is correct).


Can I target a specific node type in page.tpl.php

As shown on Variable to check if the page is of some other Content Type, you can drop into template.php something like the following:

function THEMENAME_preprocess_page(&$variables, $hook) {
  $variables['print_extra_header'] = false;
  if (isset($variables['node']) && $variables['node']->type == 'product') {
    $variables['print_extra_header'] = true;
  }
}

then in your template, add in

<?php if ($print_extra_header) : ?>
THIS GETS PRINTED
 <?php endif; ?>

So effectively you're checking on the node type in a preprocess page, to pass a custom variable to the template for you to act on.