The menu block is defined in the core module system.

Here you can see how the menu tree is set when creating the object:

core/modules/system/src/Plugin/Block/SystemMenuBlockTest.php:

namespace Drupal\system\Plugin\Block;

use Drupal\Core\Block\BlockBase;
use Drupal\Core\Cache\Cache;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Menu\MenuActiveTrailInterface;
use Drupal\Core\Menu\MenuLinkTreeInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Provides a generic Menu block.
 *
 * @Block(
 *   id = "system_menu_block",
 *   admin_label = @Translation("Menu"),
 *   category = @Translation("Menus"),
 *   deriver = "Drupal\system\Plugin\Derivative\SystemMenuBlock"
 * )
 */
class SystemMenuBlock extends BlockBase implements ContainerFactoryPluginInterface {

  /**
   * The menu link tree service.
   *
   * @var \Drupal\Core\Menu\MenuLinkTreeInterface
   */
  protected $menuTree;
  ...
  public function __construct(array $configuration, $plugin_id, $plugin_definition, MenuLinkTreeInterface $menu_tree, MenuActiveTrailInterface $menu_active_trail) {
    parent::__construct($configuration, $plugin_id, $plugin_definition);
    $this->menuTree = $menu_tree;
    $this->menuActiveTrail = $menu_active_trail;
  }

How to use your own menu tree in a menu block you can see in this test:

core/modules/system/src/Tests/Block/SystemMenuBlockTest.php

Example from SystemMenuBlockTest.php. A menu that was created before is put in a block config:

$block = Block::create(array(
      'plugin' => 'system_menu_block:' . $this->menu->id(),
      'region' => 'footer',
      'id' => 'machinename',
      'theme' => 'stark',
    ));


Link to content within node, from CKEditor WYSIWYG

There's an option, under "Url Substitution" for linkit Media matchers that allows exactly this, but for Media entities. It should be fairly straightforward to create a new plugin using Drupal\linkit\Plugin\Linkit\Substitution\Media as a reference. (You should just have to update the plugin definition annotation as well as the getUrl() and isApplicable() methods. Then you can exclude your Document content type from any previous linkit matcher and add a new linkit matcher to your profile that uses your new plugin for Url Substitution type to link to Documents.


Use drush to sync core &/or modules directory only

To sync contrib:

drush rsync @mysite.com.live:%modules @mysite.com.dev:%modules

%modules will be rewritten to sites/all/modules.

Drush does not have a path alias for the core modules folder, but you could do this:

[REDACTED]

The answer I gave before only sync'ed the core modules folder; what you really want is all of core, minus any sites or contrib modules.  To do that, use the following rsync command:

drush rsync @mysite.com.live @mysite.com.dev --exclude="sites/*"

To sync core and contrib together:

drush rsync @mysite.com.live @mysite.com.dev --include="sites/all" --exclude="sites/*"

Add '-s' prior to the rsync to run in simulated mode (i.e. drush -s rsync ...); if you do this, Drush will print out the rsync command that it would run for those parameters without actually executing it.

Update:

Yes, the rsync command shown in the question will sync the entire Drupal root.  If you want to sync only the sites folder for one particular Drupal site, you could try this:

drush rsync @mysite.com.live:%site @mysite.com.dev:%site

At this point, you might be tempted to chain together all of the commands shown above, and drop it into a script to sync everything that one site needs to run. If that's your intention, you might want to try the following variant, which rsync's everything except the other multisites:

drush --exclude-other-sites rsync @mysite.com.live @mysite.com.dev

Again, run with -s to see what it's going to do with that command.


Part 1: Review the definition of your field

Assuming that all of the faculty members have an account on your site (as you confirmed in one of your comments), I recommend to replace the implementation of that field_advisor_-field. I.e. delete that field in your timeclock content type, and add a more appropriate field that looks like so:

Field Name = Anything you want, say with a machine name like field_timeclock_reviewer
Field Type = Entity Reference, with Target type = user and Number of values = 1 (pick any of the other options to define this field as you see fit).

By using this field, you don't have to maintain the data of that field as in your example with john@email.com|Doe, John (instead you take advantage of the already administered userids and their corresponding eMail IDs).

Note: to limit the list of users that can be referenced to only those users with a specific role (like "faculty"), you should use Views "Entity selection mode" for your entity reference field in the Entity Reference widget. But before you can select the appropriate "View" to do so, you should create a view (with the Views module) to create a list of all users with that specific role.

Part 2: Rule to send the eMail

After you adapted the setup of your field as described above, it is straight forward to write a rule for the Rules module to send such eMail that you're looking for.

Here is a sample of such rule (in Rules export format), which will send such eMail to the userid selected via the field field_blog_reviewer (= a field I added to my "Blog" content type that is defined as an entity reference to a 'user'), and this whenever a new node of content type "Blog" is saved:

{ "rules_notify_reviewer_about_outstanding_approval" : {
    "LABEL" : "Notify reviewer about outstanding approval",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "node_insert--blog" : { "bundle" : "blog" } },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_blog_reviewer" } }
    ],
    "DO" : [
      { "mail" : {
          "to" : "[node:field-blog-reviewer]",
          "subject" : "Blog Post waiting your approval",
          "message" : "[node:author] has submitted a new Blog post waiting your approval.\r\n\r\nYou can review it at: [node:edit-url].",
          "language" : [ "" ]
        }
      }
    ]
  }
}

If in the above exported rule you'd change "blog" to "timeclock" (before importing this rule in your environment), and after you also add that extra user_has_role condition (as in your question), you should be pretty close to getting it to work (with an eMail that is similar to what you wanted it to be).


You would use the database abstraction layer.

$query = \Drupal::database()->select('node', 'n');
$query->addField('n', 'nid');
$query->condition('n.type', 'blablabla');
$results = $query->execute();

As for executing the query, you can also fetch results in various ways.

Examples:

$query = \Drupal::database()->select('node', 'n');
$query->addField('n', 'nid');
$query->condition('n.type', 'blablabla');
$results = $query->execute()->fetchAll();

$query = \Drupal::database()->select('node', 'n');
$query->addField('n', 'nid');
$query->condition('n.type', 'blablabla');
$results = $query->execute()->fetchAllAssoc('nid');

If you are within a class, you should inject the appropriate classes in your constructor instead of use the static Drupal container. But since you are in a preprocess function, \Drupal::database() is fine.

From core/lib/Drupal.php:

 /**
   * Returns the current primary database.
   *
   * @return \Drupal\Core\Database\Connection
   *   The current active database's master connection.
   */
  public static function database() {
    return static::getContainer()->get('database');
  }

Depending on your use case(s), you can also leverage EntityQuery:

$query = \Drupal::entityQuery('node');
$query->condition('type', 'blablabla');
$results = $query->execute();

Please note that you may want to use node_field_data table instead of node, but your query is pretty generic so it is hard to tell without a better query.

Example, get all nodes of type that are published:

$query = \Drupal::database()->select('node_field_data', 'nfd');
$query->addField('nfd', 'nid');
$query->condition('nfd.type', 'blablabla');
$query->condition('nfd.status', 1);
$results = $query->execute();

Or:

$query = \Drupal::entityQuery('node');
$query->condition('type', 'blablabla');
$query->condition('status', 1);
$results = $query->execute();


How to have no more than 20 Entity references to another content type?

You should select unlimited as possible relations. Then, using a custom module, you can alter the node edit form to don't allow more than 20 items.

To do this, implement hook form alter:

function mymodule_form_node_form_alter(&$form, &$form_state, $form_id) {
  // do magic.
}

Inside you have to:

Check the if the relations field has 20 item; if yes
delete the element widget that adds another one (so user don't get confused because it seems more items can be added).
Add a new validate handler to check related items are less than
21.


In drupal 7 how to add a link to a node which creates another node related to the previous being visible only if a user has not yet done so?

I can see couple of ways to do it.

1) add the module http://drupal.org/project/node_limit

2) Create a menu with node/add/contentA

3) add this block to the node of the type content A

4) to do the third step you would need to add alias to the content A nodes by following method

Setup a URL alias pattern for content A
Click on Configuration in the admin menu, and look for "URL Aliases".
One of the tabs is called "Patterns" - this is where you can adjust the automatic URL alias settings for your content. In the "Content Paths" section you'll see the default is set to "content[node:title]" -- just below that you'll want to set "Pattern for all Blog entry paths" to "contenta/[node:title]" and save your new configuration. This means all of your future Content A content will have URLs like: http://yoursite.com/contenta/your-contenta-title.

(Thanks to Jonathan Webb http://www.drupalgardens.com/content/block-not-showing)

That should do it.

This assumes that the user can only add one node.

EDIT : An update with the requirement mentioned in the comment

Instead of step 1 and 2 do the following

1) Enable php filter

2) Create a view of the type block with just one field may be nid of the node. Remove the label. Rewrite the out put to some thing like  so that nothing is displayed.

3) Add contextual filter of the type content:author and select provide default value and from the drop down select User ID from logged in user

4) In the header section add a field of the type gloal:textarea click on "Display even if view has no result" so that it would be displayed even if there is no result.

5) Select PHP code as the filter and paste the following code with the changes that suite your requirement such as changing the url to the one that adds your content type.

<?php
  $view = views_get_current_view();

   if (!count($view->result))
   {
       print "Add Node";
   }
?>

Follow step 3 and 4 to add the block to the node.


browscap.ini is not configured in php.ini


How to display the pager on top and bottom of a custom search results page?

You could use CSS

.[wrapping-div-class] { position: relative; }
.[wrapping-div-class] .pager { position: absolute; top: 0px; }


Can you make a "feature request" over on drupal.org about this?
https://drupal.org/node/add/project-issue/responsive_menus

It doesn't have a way to do anything other than the left-side vertical menu currently.  I'd like the Google Nexus style to be able to use the top horizontal area as well.


Creating multiple custom blocks in drupal 8

Thank you very much Shawn.

It was the @Block annotation. I was using same id for both the blocks.

/**
  * @Block(
  *   id = "show_state",
  *   admin_label = @Translation("Show State"),
  *   category = @Translation("POP")
  * )
  */


How do I set a validation error on a component inside a composite component?

The element name "sample_details][date_sampled]" specified in the first parameter of setByErrorName is not correct.

It should be

// $key = your multi field array key eg 0,1,2,3
$formState->setErrorByName('sample_details][items][' . $key . '][_item_][date_sampled', $this->t('must not have a sample date in the future.'));

You can find out the exact element name by two methods:

$formState->getUserInput() will give you the exact array pattern to use for setting error by name.
Inspect the element from the browser and use the value of name attribute.


Rules Looping for Multiple User References

You could write you're own condition. See http://drupal.org/node/298486.


Drupal Commerce - Reference Product in another product

What you are looking for is bundling of products.

Take a look at Commerce Product Bundle Module

The project page says

  You can define products that consists of other products. They are all
  combined in one add to cart form. The form works like the core add to
  cart form with all the fancy selection and ajax magic. So the
  customers can make their selections as usual. The difference is, that
  the products from mulitple reference fields were presented on one add
  to cart form.


Using EntityFieldQuery with Address Field

Although Addressfield can be extended, the standard columns like zip code are normal field columns and live in field storage (see addressfield_field_schema()).

In your case you want the postal_code column:

$query  =  new EntityFieldQuery();

$entities  =  $query->entityCondition( 'entity_type', 'node' )
  ->propertyCondition( 'status', 1)
  ->propertyCondition( 'type', 'consumer_store' )
  ->fieldCondition( 'field_postal_address', 'postal_code', $postal_codes )
  ->execute();


In D8 believe you need to wrap your code around this tags in order for Drupal to recognize it.

(function ($, Drupal, window) {

 // code goes here

})(jQuery, Drupal, window);

So try

(function ($, Drupal, window) {
   $(window).on("scroll", function() {
     if ($(this).scrollTop() > 50) {
       document.getElementById("logo").style.width = '150px';
       document.getElementById("logo").style.marginTop = '0px';
     } else {
       document.getElementById("logo").style.width = '300px';
       document.getElementById("logo").style.marginTop = '20px';
     }
   });
})(jQuery, Drupal, window);


There is no way to achieve that without coding, you have to create your own module, which will create this token (implementing hook_token_info and hook_tokens) - see example here - http://www.taggartjensen.com/code-snip/drupal-7-create-custom-token-module.

EDIT: I created a simple module out of this - Token Menu Render.


How can I translate string templates in Metatag module?

Basic internationalization support can be found in the i18n module:

  All default configurations may be translated using the
  Internationalization (i18n) module. The custom strings that are
  assigned to e.g. the "Global: Front page" configuration will show up
  in the Translate Interface admin page
  (admin/config/regional/translate/translate) and may be customized per
  language.

There exists at least 1 ongoing issue in Review still with Views, Panels and other 3rd party contrib modules and the metatags module.


How does Feed import get a list of the CSV fields to map to content type fields?

https://www.isovera.com/blog/using-feeds-module-bulk-import-drupal-7

This is what I used...worked like a charm...you simply need to map field names from CSV file to node fields...

Alex


I inherited this site.

In the Panels Page Manager, rules were set up for "node/#."
Therefore, any new node was printing blocks as a sidebar because of those set rules. I reconfigured those rules, and the problem has been fixed.


Link to content in views doesn't translated to fr

One way to solve this would be to construct the "Link to content" field on your own, using Views. You will need to:

Add 2 fields to your view:

a "Content: Node ID (Node ID)" field
a "Content: Translation language (Translation language)" field.

Exclude the "Content: Node ID" field from display.
Rewrite the "Content: Translation Language" field as a custom link.
The text in the "Rewriting" would look something like this:
Link path: {{ langcode_value }}/node/{{ nid }}

Hope this helps!


You would use the PHP Filter, but I would highly recommend AGAINST it as it doesn't restrict anything, and with it, your users could enter things far more "exciting" than just echo statements...


Prevent directory permissions of sites/default from being protected in a local environment?

If you are on Drupal 8, you can configure settings.php to include a settings.local.php with a simple environment check (to ensure you are running a local env).

In that file, you can add this:

$settings['skip_permissions_hardening'] = TRUE;

This will allow you to open and write to settings.php without it being locked back down.


Storing Credit Card Information for later use

The most secure place to store credit card numbers will be on a third party service designed to securely retain that data. These service providers are PCI Level 1 compliant with code and systems in place to prevent the unwanted or unexpected exposure of sensitive card data.

Many payment gateways support such "card on file" functionality, where they allow you to process an authorization or capture for a credit card and provide you with a token to perform follow-up transactions using that same card data. Such a transaction is generally referred to as a "reference transaction", with example implementations being PayPal's reference transactions, Authorize.Net's Customer Information Manager (CIM), or CyberSource's Managed Billing / subscriptions.

The name and price of these services will vary from payment gateway to payment gateway, but they will always require a similar point of integration in Drupal - a way to retain a payment token and process that reference transaction at a later date; typically you want some sort of customer interface as well, allowing customers to update their information or reuse a credit card on a later order.

To solve the Drupal integration, we created the Commerce Card on File module, which does all this and more within Drupal Commerce. It works through payment method callbacks, allowing any payment method module to implement the callbacks to integrate reference transactions through its payment gateway's API. Obviously, not every payment gateway under the sun is supported, so be sure to check the documentation to find out if yours is supported.

And as the comments on your original question indicate - you should never be in the business of storing card data in your site, which was unfortunately easy to do in Ubercart. Multiple times now I've been part of rescuing sites that incorrectly used the UC Recurring module to retain credit card data in plaintext in the database for later processing. Do not do this - ever.


We use a module called IMCE (https://drupal.org/project/imce) to upload images/files via ckeditor. Works really well and has a nice interface.


How can I insert a comment form into my view?

What I know? That you can use the view.tpl.php file and add:

<?php
print drupal_render(drupal_get_form("comment_node_**content_type_machine_name**_form", (object) array('nid' => **$node->nid**)));
?>

Change the bold according to your node object and the content type machine readable name.

I think this link can help you too. and I suggest to check hook_views_pre_render Here which can do it but I didn't try it before.


What is the best way to generate node(book) to ePub?

I know this answer is dead simple, but have you tried EPUB Export module?

  This project builds content objects from drupal and bundles them into an
  EPUB 3.0 document. Currently it will export a rendered entity seperate of all
  of the page markup and gather all the referenced resources within the content
  and bundle those into one EPUB document.

I tested it on a clean install and it appears to work as advertised.


Enabling "entity translation" disables term translation in Drupal (name and description)

Ad documented on the Entity Translation project page: "Title module allows to replace entity labels with fields to make them translatable." With the Title module you are able to replace the non-Field title and description properties taxonomy terms with Fields translatable with Entity Translation.


What is the template name for www.mysite.com/user/login

page--user--login.tpl.php   ... if you create one, make sure you flush your cache!

Also, check out this module:
https://drupal.org/project/devel_themer

It'll help you determine these sorts of things, just don't leave it running after you're done development!


Display youtube video using Media Oembed in the node

First of all i got all the default displays in my drupal site using the function : field_info_formatter_types().Since media is a file entity, the formatter should be file rendered.Then i had to give the file view mode in the settings array to show the way i wanted it.I created a custom view mode called article_page(machine name) and added oembed formatter.Here is the final code.

$row[$field_name][] = field_view_field('field_collection_item', $entity, $field_name,
            $display = array('type' => 'file_rendered','settings'=>array('file_view_mode' => 'article_page')), $langcode = NULL);


When is the available 'language: English French...' link displayed under translatable content?

I'm guessing this is your other question!

I'm not exactly sure but I just did this from scratch on my Drupal test site and found it to work.

Modules - The only module I have enabled is Multilingual content
Content Type - Edit - Publishing options - Enabled, with translation
Content Type - Edit - Multilingual settings - Nothing selected except 'Normal'
Regional and language - Languages - Multiple languages enabled
Regional and language - Multilingual settings - Node Options - Hide content translation links is not checked

i18n can definitely be uncooperative...


Pass positional arguments to drush via drushrc.php?

Alas, there is no command-specific argument feature in Drush.  You can't even use a pre-command hook to fill in the arguments, as Drush will check for required arguments before calling any command hooks.

Another option would be to define a shell alias, and define your argument there:

$options['shell-aliases']['myis'] = 'site-install xyzzy';

Then you can use this as drush myis [other options], and your profile name will be inserted.


Is there a way to hide the Apply button on an Exposed Contextual Filter?

This is a standard feature. Go to the "Exposed Form" settings on your view and click "Settings" next to "Exposed form styles". I don't remember the correct name of the option but i think you get it when you're there.


How can I setup automatic subpages for existing pages using a view with a contextual filter that uses the URL to determine the filter value?

After much trial and error, I found a solution that seems to work for me.

The first thing I had to do was switch from using a "provide default filter value" to specifying custom validation criteria via PHP:

$normalPath = drupal_get_normal_path('expertise/' . $argument);
$urlPieces = explode('/', $normalPath);

if(!isset($urlPieces[1]))
{
    return false;
}

$nodeId = $urlPieces[1];
$node = node_load($nodeId);

if(!empty($node))
{
    switch($node->type)
    {
        case 'area_of_expertise':
            $handler->argument = $node->nid;
            return true;
    }
}

return false;

Thanks to Cameron for the bits about $argument and $handler->argument.

Once I figured out how to use argument to generate the URL which then allowed me to look-up the node ID, I was able to reuse most of the code that I had before in the "Provide Default Value" section.

The next issue was the breadcrumbs. Before I did anything extra, the breadcrumbs were showing as Home >   > Staff. I ended up having to create a new menu item called Staff in the main menu that was a child of Pathology. So then the breadcrumbs showed as Home > Pathology > Staff > Staff which is still not what I wanted.

I found out that views likes to add each contextual filter as a breadcrumb so that you can navigate up and get less and less granular. Normally this would be a nice feature, but I couldn't see any way to turn it off.

So I found a post that detailed how to remove the breadcrumbs which I tried to implement via hook_preprocess_page. This ended up not affecting the breadcrumbs at all because the views module was altering the breadcrumbs after that hook was being run.

Then I found another post that detailed how to affect the breadcrumbs after the view was ready to be rendered using hook_views_pre_render.

So I have the following code as my hook:

function MODULE_views_pre_render(&$vars)
{
    $page = menu_get_item();

    if(($page['page_callback'] == 'views_page') && ($page['page_arguments'][0] == 'staff_cross_reference'))
    {
        $breadcrumbs = drupal_get_breadcrumb();
        array_pop($breadcrumbs);
        drupal_set_breadcrumb($breadcrumbs);
    }
}

And now my breadcrumbs look like Home > Pathology > Staff which is exactly what I want!


Synchronize data between 2 sites dynamically

You need to work on the database a little bit.

I think it is impossible to make it work if you just write php. Because it will generate a lot of database login errors.

There might be a lot of ways to do that, but the only way I know is to:
First, Combine two database into one, two different databases with two different prefix.
Second, delete all the attributes you want to synchronize in the second database.
Third, link the synchronized field in the second database to the first database, you can do this in the settings.php in the second drupal site.

But there might be some dependency problems when you do step 2. Don't forget to backup at first.

This link might be helpful How to connect to multiple databases within Drupal


Page not found error when using plus"+" sign in the url alias

Drupal url do not accept the + sign, so it will convert the url into "space" so that only i t return page not found value.
Please remove the + sign from url.


Two Views with autocomplete filters display no result

The link provided by  WaQaR Ali solved the problem.

  The problem lies in the fact that two form-fields get the same ID.
  Placing this code in a hook_form_FORM_ID_alter():

<?php
 $form['title']['#id'] = 'form-text-' . rand(0,100);
?>

Thank you Ali!


Is there a function to return all the multisite names?

Okay, this is what I am using for now in a drushrc.php file. If you can improve upon this please post a new answer. Thanks

// Gets a list of all directories in /sites.
$sites = glob(drush_locate_root() . '/sites/*', GLOB_ONLYDIR);
// Strips the absolute path except for the last name.
$sites = array_map('basename', $sites);
// Removes the 'all' folder.
$sites = array_diff($sites, array('all'));


How to hide and/or prevent access to fields in a form,  such as group_audience for organic groups

Edit:

Ok I figured it out.  Put this in your custom module:

function example_form_alter(&$form, &$form_state, $form_id) {
    if($form_id == 'story_node_form') {
        $form['title']['#value'] = 'hot stuff';
        $form['title']['#access'] = FALSE;

    }
}

This will set the title of the story node to 'hot stuff' and it will NOT be render on the page because #access = FALSE;

You can add more granularity control inside hook_form_alter()
like

  global $user;

  // Check to see if $user has does not have the administrator role.
  if (!in_array('administrator', array_values($user->roles))) {
    $form['title']['#access'] = FALSE;
  }

This works for Drupal 6 & 7.

Old Answer (ignore):

Its been awhile since I did something like this,  so I may have it wrong.
If you set the  [#value] of a form item,  it will not be visible on the form.

I did this in Drupal 6,  hook_form_alter() in a custom module.  I don't know if it will work in Drupal 7 and I don't know if you can do it in a preprocess function


How can I create a programmatic Search API query which uses a date field

Try

$myQuery->condition('field_application_end_date:value', '1411084800', '=');

Search API stores the dates as timestamps, so you're right there, but you forgot the 'value' after the field. If you want to use the 'to' date, use 'value2'.


Get programmatically value of sub field collection item of a field collection

I think this should be structured properly. It should give you access to each book on each library item.

$node_wrapper = entity_metadata_wrapper('node', $node);
$libraries = $node_wrapper->field_library->value();
foreach($libraries as $library){
  $library_wrapper = entity_metadata_wrapper('field_collection_item', $library);
  $books = $library_wrapper->field_book->value();
  foreach($books as $book){
    $book_wrapper = entity_metadata_wrapper('field_collection_item', $book);
    $title = $book_wrapper->field_title->value();
  }
}


CCK Field Table in Database and Content Type

Assuming you're using CCK with Drupal 6 here...

Unless a field is set to multiple cardinality, or is attached to more than one content type, there won't be a table created for it. Instead, a new column will be created for it in the CCK table for that content type.

For example, if you have a content type called 'page' with a number field called 'field_number', with single cardinality and only attached to the 'page' type, there will be a column called field_number_value in the content_type_page table; that's where the data is stored.


I found solution.
In the file

  modal_forms.pages.inc

inside the function modal_forms_view_webform($js = NULL, $node) place $form_state['rebuild'] = TRUE; after $output = ctools_modal_form_wrapper('webform_client_form_' . $node->nid, $form_state);

Then modal form will save data only once.


Your best option would be to use the combination of Filefield Sources and IMCE, but unfortunately, the first isn't ready for D7 yet.


In Drupal 7 you could set the $base_url='https://example.com'; in /sites/default/settings.php.

For Drupal 8 it looks like $base_url has been removed in favor of trusted domain patterns which are protocol agnostic. Using .htaccess rules seems to be the recommended approach.

In .htaccess below RewriteEngine on

  # Redirect to HTTPS
  RewriteCond %{HTTPS} off
  RewriteCond %{HTTP:X-Forwarded-Proto} !https
  RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

That's from this page: https://www.drupal.org/https-information


How to share user and user profile in a multisite environment?

Edit settings.php -> $databases

$databases['default']['default'] = array(
  'database' => 'my_db',
  'username' => 'user',
  'password' => 'pass',
  'host' => 'example',
  'prefix' => array(
    'default'   => '',
    'users'     => 'shared_db_',
    'sessions'  => 'shared_db_',
    'role'      => 'shared_db_',
    'authmap'   => 'shared_db_',
  ),
  'collation' => 'utf8_general_ci',
);

Add any other tables as required in prefix array.
Have a look at settings.php as well it has lots of documentation on all these.


How to conditionally hide a space in a rules action if the first token is empty?

If I was to implement this, I'd create a special (tiny) Rules Component as a kind of helper function, and use that in your existing rule also. The clue of that Rules Component is the (not often used) "Provided" facility for one of its parameters. More details below ...

Part 1: Create a Rules Component

Create a new Rules Component that looks like so (in Rules Export format):

{ "rules_create_email_body_prefix" : {
    "LABEL" : "Create eMail body prefix",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : {
      "title_value" : { "label" : "Title value", "type" : "text" },
      "prefix_value" : { "label" : "Prefix value", "type" : "text", "parameter" : false }
    },
    "IF" : [ { "NOT data_is_empty" : { "data" : [ "title-value" ] } } ],
    "DO" : [
      { "data_set" : { "data" : [ "prefix-value" ], "value" : "[title-value:value] " } }
    ],
    "PROVIDES VARIABLES" : [ "prefix_value" ]
  }
}

Some details about the above Rules Component:

It uses 2 parameters:

it accepts title_value as an input parameter (Usage = Parameter).
it provides prefix_value as output of it (Usage = Provided).

The logic of this Rules Component is like so:

Rules Condition: verify that the value of title_value is NOT empty.
Rules Action: set the value of prefix_value equal to the value provided via title_value, and follow it by a space (note!).

Part 2: Integrate the Rules Component in your existing rule

Here is an updated version of your rule (also in rules export format).

{ "rules_mail_confirmation_with_optional_prefix" : {
    "LABEL" : "Mail Confirmation with optional prefix",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "webform_rules" ],
    "ON" : { "webform_rules_submit" : [] },
    "IF" : [
      { "node_is_of_type" : { "node" : [ "node" ], "type" : { "value" : { "contact" : "contact" } } } },
      { "node_is_webform" : { "node" : [ "node" ] } }
    ],
    "DO" : [
      { "component_rules_create_email_body_prefix" : {
          "USING" : { "title_value" : "[data:title-value-raw]" },
          "PROVIDE" : { "prefix_value" : { "prefix_value" : "Prefix value" } }
        }
      },
      { "mail" : {
          "to" : "[data:email-value]",
          "subject" : "Confirmation",
          "message" : "[prefix-value][data:name-value-raw],\r\n\r\n",
          "from" : "[site:mail]",
          "language" : [ "" ]
        }
      }
    ]
  }
}

These are the changes I applied (as compared to your rule):

Rename the rule (to not override your own rule).
Add a Rules Action (as the first one) to invoke the newly created Rules Component (whereas the value [data:title-value-raw] is passed to the title_value parameter).
Adapt the message body of the eMail, to now use the prefix_value as provided by the Rules Component. To be complete: if the Rules Condition in the Rules Component is NOT satisfied, the value of prefix_value is empty, otherwise the Rules Component will assign a value is equal to title_value followed by a space.

Notes:

The exported rule as included in the 1st revision of your question, contains some errors/challenges, i.e:

It contains a syntax error, the comma at the end of your 2nd Rules Condition should not be there (only after I removed that comma I was able to import your rule ...).
Something doesn't seem right in the [data:[data:title-value-raw]] token you included, pretty sure it should be [data:title-value-raw], as confirmed somehow also in the edit you applied in revision 6 of your question.
IMO there is no need for "PHP" (as shown within "REQUIRES" in your exported rule ...), as confirmed somehow also in the edit you applied in revision 6 of your question.


What will be my function name in template.php for particular .tpl.php

You need to use theme_preprocess_node function in template to add variables..

/**
 * Override or insert variables into the node templates.
 *
 * @param $variables
 *   An array of variables to pass to the theme template.
 * @param $hook
 *   The name of the template being rendered ("node" in this case.)
 */

function YOURTHEME_preprocess_node(&$variables, $hook) {

  // define $node object, so it's be easier to use it
  $node = $variables['node'];

  // add variables to node--nameofnodetype.tpl.php file
  if ($node->type == 'product'){

      // $variables: an array with variables
      // you need to add one, so just define it
      $variables['my_variable'] = 'whatever';

  }
}

In your node--product.tpl.php file:

// check if your new variable exist
print $my_variable;


Include content of subdomain inside a block or view?

I think I got the answer on this.

I've created a new block, added this:

<?php print file_get_contents("http://sub.homepage.com/"); ?>

Remember textformat should be PHP.

And it worked. It now shows my subdomain inside my template.


How to fix incorrect forum post count when using internalization and locale?

Look at advanced_forum_statistics_topics (check your advanced_forum version)

return db_result(db_query('SELECT COUNT(DISTINCT(nid)) FROM {forum}'));

You can use preprocess forum_statistics and instead of advanced_forum_statistics_topics(); use your own function to select only nids which relate to the current language.


Create a view/list of pages made with Panels

Try www.yoursite.com/admin/structure/pages

This lists all the system generated & custom panel pages that exist.


Of course, you can use a feature like a "normal" module.

Feature use .module file only for include a file, so after this include you could add your custom code.
And obviously you can add more files, directories, etc.

It's a great way to avoid to create too many modules.


You could create a hidden redirect URL element, which is then used as the confirmation redirect URL.  The hidden redirect URL element can be populated using the 'Default webform submission data.'


Disabling text field for all users / roles

I don't know why would you need to disable any fields in the first place (that's not turns out from your post), but if you need 5 voting field, you could easily create it:

You may need just a part of them or all of them:

Creating a custom Field


putting the most visited content in a block

You could use the Drupal Most Popular module

  Showcase the most popular content across your Drupal website and
  engage your audience. Ready to Use

  The module is pre-packaged with several services including:

  Drupal - Most Viewed pages (using Statistics module) Drupal - Most
  Commented pages (from simple database query) Google Analytics - Most
  Viewed pages AddThis.com - Most Shared pages Disqus.com - Most
  Commented pages The system defines Drupal hooks to allow new services
  to be created, which can pull data from third party providers or
  internally from Drupal.  The system also provides an API to help
  service plugins normalize their results and exclude certain pages, as
  configured by the administrator.

or another module that you can use and its so easy is Radioactivity and there is a good video tutorial here


How to change the link in the view by content type?

yes you can add the Link field by add a module called link module which will add a type called link in the add field drop down. for that you will need to install Link module

Hope this will help :)


Reset boost cache in a busy site without crash

Here is the script that does the job:

<?php

/* function to list all relevant HTML files in a given directory */
function ListIn($dir, $prefix = '') {
  $dir = rtrim($dir, '\\/');
  $result = array();

    foreach (scandir($dir) as $f) {
      if ($f !== '.' and $f !== '..') {
        if (is_dir("$dir/$f")) {
          $result = array_merge($result, ListIn("$dir/$f", "$prefix$f/"));
        } else {
          if (stripos($f,".gz") === FALSE) {
            $result[] = $prefix.$f;
          }
        }
      }
    }

  return $result;
}

/* main function */
function go() {
  $isToNotify = false;
  // get all relevant HTML files, recursively
  $files = ListIn('/var/www/drupal_site/cache/normal/my.domain.com','');
  foreach($files as $file) {
    // save filename for later
    $filename = str_replace("_.html","",$file);
    // normalize path to file
    $file = "/var/www/drupal_site/cache/normal/my.domain.com/" . $file;
    echo "\n************************************\n\nChecking $file" . "...\n\n";
    // get HTML from file into string variable
    $html = file_get_contents($file);
    // create DOM object for easy parsing
    $dom = new DOMDocument;
    $dom->loadHTML($html);
    // get all <link> tags
    $links = $dom->getElementsByTagName("link");
    foreach($links as $link) {
      $css = $link->getAttribute('href');
      $css = str_replace("http://my.domain.com","",$css);
      // find only the relevant tags with the CSS file
      if (stripos($css,"css_") !== FALSE) {
        // normalize path to CSS file
        $path = "/var/www/drupal_site" .$css;
        // check if CSS exists
        if (file_exists($path)) {
          echo "The file $path exists\n";
          // no need to do anything else
        }
        else {
          echo "The file $path does not exist\n";
          // set notification ON
          $isToNotify = true;
          // delete HTML with links to not existing CSS file
          unlink("/var/www/drupal_site/cache/normal/my.domain.com/$filename"."_.html");
          unlink("/var/www/drupal_site/cache/normal/my.domain.com/$filename"."_.html.gz");
          // GET the HTML from scratch so Boost will re-cache it
          echo file_get_contents("http://my.domain.com/$filename");
          echo "Adding log entry...\n";
          // log activity
          $content = "\n\n".(date("Y-m-d H:i:s"))."\n    Refreshed HTML: my.domain.com/".$filename."\n    CSS file which was not found: ".$css;
          file_put_contents("/root/scripts/logs/monitorCSS.log",$content,FILE_APPEND);
          echo "Going to sleep for a while ZzZzZz...\n";
          // sleep for a while to avoid bombardment of the server by this script
          sleep(20); // in seconds
          // go to next file - no need to refresh same file more than once (if more than one CSS file was not-found in HTML)
          break;
        }
      }
    }
  }
  if ($isToNotify) {
    // send email notification if needed (we found some missing CSS files)
    mail('my@email.address', 'Monitor CSS Notification', wordwrap("Some missing CSS files discovered - see log file for more info...", 70));
  }
}

// call main function
go();
?>


Updating content to remove it from the front page shows it as being 'New'

You should "uncheck" the checkbox "promoted to the frontpage" (which is shown when you 'edit' such nodes). That way it will not be shown on the frontpage anymore.


How do I preserve GIF animation with the image field and image styles?

It is possible, there already is some discussion:

Pure PHP with imageMagick - https://stackoverflow.com/questions/718491/resize-animated-gif-file-without-destroying-animation
Drupal discussion - https://drupal.org/node/1115658
Issue for ImageMagick module with patch - https://drupal.org/node/1802534 - several users claim that it is working.


How to obtain a list of the submodules of a module using Drush?

This information is available via the pm-projectinfo command:

$ drush pm-projectinfo views
 Name         :  Views (views)
 Version      :  7.x-3.13
 Extensions   :  views
                 views_test
                 views_ui

This command is available in Drush 8, and was first introduced in this PR.  It is also available in Drush Extras for older versions of Drush.


Services Module Unable To Update User Fields

Way 1:

Yes, you need to send the current password to update the user email that is default Drupal user account configuration, and the default user update enpoint exposed by services programmtically submit the same user profile form, which triggers all the validation your form has. In order to send the current password your request load may look like

{
    "current_pass": "onso",
    "mail": "test@example.com"
}

Way 2:

If you don't want to provide current password, you can consider using No Current Password module, but remember that it will remove the current password field from the form UI as well.

Way 3:

Expose custom endpoint to update user email. Make sure you have authentication on your endpoint.


I think your looking for node_save. You can node_load your node and make changes to the object and then use node_save to save the changes.


Changing a menu link used in the sitemap module but not in main nav

{{ something.content }} is a render array, you can't do a string replace on an array. But you can store the computed string output of the render array, and do a string replace on the rendered output:

{# compute the output of the render array and store it #}
{% set rendered_html_string = item.content|render %}

{# do the replacement #}
{% set modified_string = rendered_html_string|replace('seachtext', 'replacetext') %}

{# print the modified string #}
{{ modified_html_string }}


How to get drupal 7 default file upload directory?

This information is saved in Drupal's variables table. Use the variable_get function to get this information, passing in the name of the correct variable:

Public Filesystem Location: variable_get('file_public_path', conf_path() . '/files');
Private Filesystem Location: variable_get('file_private_path');

If you want the temporary upload directory use variable_get('file_temporary_path'); If you want to determine the system specific upload directory, regardless of the actual site configuration use the file_directory_temp function.

variable_get('file_public_path', conf_path() . '/files'); will pull the default path for you in case it has not been modified or explicitly set by the site administrator.


Display content reference with another content

Create a view with title list in Task content type, in this create a Contextual filters with field_project. Take the filter value from url arguments.


How do I retrieve un-submitted values from a form and pass to another module?

First, you shouldn't have to modify the page callback from the user references module. Instead, use hook_form_alter() (or hook_form_FORM_ID_alter()) to change the #autocomlete_path attribute of the user reference text box to point to you're callback instead. That way you aren't modifying the module's stuff and you have the option of using the default implementation somewhere else. This is generally a better option than modifying another module's menu items.

For your particular use case, you'll do what you actually suggested; use the AJAX properties on the team fields to make the information available to the autocomplete callback. In practice it's slightly more complex than that, but you've already got the right idea. There's an article on Active LAMP that does pretty much the same thing.

First let's see about your custom autocomplete callback. You need to know which teams (Team X and Team Y as you put it) to filter by and what string to search for. In the following code, you first create a menu item for your callback, then define the actual autocomplete callback. The menu item uses two wild cards in the path to provide the ids for Team X and Team Y to the callback. You do not need to specify a wildcard for the search string, Drupal will handle that for you. In your callback, use the id information to narrow your user query results.

function trim_users_menu() {
  $item['trim-users/autocomplete/%/%'] = array(
    'page callback' => 'trim_users_autocomplete_callback',
    'page arguments' => array(2, 3),
    'type' => MENU_CALLBACK,
  );
  return $item;
}

function trim_users_autocomplete_callback($x, $y, $string) {
  // Here, use the query you altered for finding the correct users.
  $query = <youre altered query>;
  // Now, return the available User options.
  // Taken from user_reference_autocomlete, minus the hyperlink removal.
  $matches = array();
  foreach ($query->fetchAll() as $row) {
    $matches[$row['title'] . " [uid:$id]"] = '
' . $suggestion . '
';
  }

  // return for JS
  drupal_json_output($matches);
}

Now you need to alter the form to make the user reference field use this custom autocomplete callback. The url you use for the user reference field's #autocomplete_path will follow the pattern of the menu item you create. Suppose you want to filter the users to Team X, with id 1, and Team Y, with id 2. You're path will be trim-users/autocomplete/1/2. To get  team ids for the path, you use #ajax['callback'] settings on the Team fields to respond to change events. For example, set the #ajax['callback'] property to trim_users_team_selected. When the Team field value changes, Drupal will rebuild the form then run your #ajax['callback'] to update the form on the client. So, inhook_form_alter()`, check if the team fields have a value, and if they do use it to build the autocomplete callback path you assign to the user reference field.

function trim_users_form_alter(&$form, &$form_state) {
  // Check if it's the correct form, or use hook_form_FORM_ID_alter instead.
  ...

  // Check the $form_state to see if there's a value for the Team fields
  if (isset($form_state['input']['field_name']['#value']) {
    // Get the value of the field and use it in the autocomplete callback path
    ...
  }
  ...
}

// Return the User Reference field element from the rebuilt form. This will
// replace the existing field element on the client.
function trim_users_team_selected($form, $form_state) {
  return $form['user_reference_field'];
}

There's a few other things you have to do, like set the #ajax['wrapper'] property, but that's all part of using #ajax['callback'] so I'm not going to get into that here. This should at least get you on your way, you just need to figure out the specifics of retrieving and setting the form field values.


Is there a way to disallow the node/* path for anonymous users?

You can give permission to particular node using hook_permission().

function your_module_name_permission() {
  return array(
    'access your modulename module' => array(
      'title' => t('Access your modulename module'),
      'description' => t('Allows access to your modulename module'),
      'restrict access' => TRUE
    ),
  );
}

and then go to permission section under people menu. and uncheck above created permission for anonymous user.


Command "generate:module" is not a valid command name

I have faced the same problem this works 100 %  :

open the shell and  cd to projectFolder
run this command :

   composer require drupal/console:~1.0 --prefer-dist --optimize-autoloader

then run this command :

   composer update drupal/console --with-dependencies

run drupal list command again, and you'll find the list of all commands.

! this steps must be repeated with each project.


Using a sweet alert with preventDefault()

I solved this, just in case anybody else comes across it.

Drupal uses a variable called $op == "Update", which is an attribute on the Submit .  When you use preventDefault() this is removed from the Form Data.

The solution is to add this to the sweetalert callback function when they confirm to delete or whatever your use case is.

          formE.off('submit');
          var input = $("<input>").attr("type", "hidden").attr("name", "op").val("Update");
          formE.append(input);
          formE.submit();

Drupal now gets that so hits the form_submit function.


how can i define a maintenance template within a custom module?

drupal_get_http_header() should be treated as deprecated.

See https://www.drupal.org/node/1969270#comment-7609337

I think your approach is good, but for a little more coverage of 404/403 pages we came up with a more extendable approach, also theres a bit more room for customization in the backend within the modules settings page.

We did this by using the customerror module in conjunction with a theme function and a few overriding template files.

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

After installing, add this to your template.php file's theme_preprocess_page function. Example;

function YOURTHEME_preprocess_page(&$variables) {

  $alias_parts = explode('/', drupal_get_path_alias());

  if (count($alias_parts) && $alias_parts[0] == 'customerror') {
    if ($alias_parts[1] == '403') {
      $variables['theme_hook_suggestions'][] = 'page__forbidden';
    }
    if ($alias_parts[1] == '404') {
      $variables['theme_hook_suggestions'][] = 'page__not_found';
    }
  }

  <other code goes here>

}

Then in your templates folder add your custom templates (just like your page.tpl.php file);

page--forbidden.tpl.php
page--not-found.tpl.php

Clear your cache, hit one of those pages (you can test them by going to);

[yoursite]/customerror/403
[yoursite]/customerror/404

As for your maintenance page, all you need to do is create a
maintenance-page.tpl.php file and toss that in your templates folder.


Paging issue in views when implements node access

hook_node_access() doesn't really do any access checks on node listings or views.

To get this to work you should look into implementing hook_node_grants() and hook_node_access_records()

That logic will be included in your views query so you could get rid of hook_views_post_execute()


How can I show a view in panel with argument in drupal 7

In order to use "contextual filters" for a view within a panel, you need to change the style of the panel. It seems that even though they are called contextual filters, they expect an argument. Make sure you have the view panes enabled in modules and create the same view with the style of view pane. You will then get an additional menu called "pane settings". One of the settings is "argument input", select "from context" and the required context, and it should work fine. This was something I was really stuck on till  found this solution.

also, if you are trying to pass a taxonomy term, you have to make sure it is formatted correctly to use in the filter. See this post for details

Views contextual filters taxonomy name


Use this for errors:

/**
 * Implements hook_rest_server_execute_errors_alter().
 *
 * Reformat error output.
 */
function up_coaching_rest_rest_server_execute_errors_alter(&$error_alter_array, $controller, $arguments) {
  $error_alter_array['body_data'] = array(
    'success' => FALSE,
    'error' => $error_alter_array['body_data'],
  );
}

For success output you need clone needed resources from user resource definition.


Changing the $base_url variable by no means makes drupal look through every bit of text in the system checking for href's.  So, if you put in

 <a href="/company/.....

it is going to use it exactly as is because it has no idea to do anything else.  It will, however, be more than glad to put it in front of a path if you use some of its built in functions, for example:

 <?php print l('Foo Bar Baz', 'company/foo/bar/baz'); ?>

will create a link to /company/foo/bar/baz if $base_url is not set, or if it is set to drupal, to /drupal/company/foo/bar/baz.

So, to your problem.  Have you tried Views' Output as a link instead of creating the <a> ... </a> code yourself in Rewrite the output of this field?  That should put that $base_url in there automagically if in the Link path: you enter company/[nid][path] (or whatever tokens you need as you use several different ones in your question).


I solved this as follows:

install react-app-rewired:  npm i --D react-app-rewired --
this is important so you don't try to load react more than once
change package.json so build executes react-app-rewired build -- full instructions here: https://github.com/timarney/react-app-rewired
Pick a spot in your Drupal install for your react app  -- I chose sites/all/react, it seemed right to me
load react into your template using the CDN links https://reactjs.org/docs/cdn-links.html
update package.json with homepage for your app to reflect where you are saving it for example: "homepage": "/sites/all/libraries/myapp/",
build your react app and copy the contents of the build folder to the location you chose for storing your app
build a simple module to load your app as a block (code below)
add the block to your page however you see fit

/* Adds the block to the block menu */
function my_app_block_info() {
  $blocks['my_react_app'] = array( //a new array for each new app
    'info' => t('My React App'),
    'cache' => DRUPAL_NO_CACHE,
  );

  return $blocks;
}

/* set the content for the block */

function my_app_block_view($delta = '') {
  $block = array();
  switch ($delta) {
    case 'my_react_app': //a new case for each new app
        $block['content'] = file_get_contents(libraries_get_path('appfolder').'/index.html');

        break;
     }
  return $block;
}

 /*
   file_get_contents loads the index.html page that loads
   the react app don't use libraries_get_path if you saved your app
   somewhere else
 */


Ok, I made it work by the answer from this post:
How can I programmatically display a block?

And rendered it by adding this in hook_form_alter:

if ($form_id == 'node_article_edit_form') {
  ... code from the other post here ...
  $block = $plugin_block->build();
  $form['checkmark_block'] = $block;
}

And then in the twig file:

{{ form.checkmark_block }}

I find it way to difficult for a small task like this, and annoying to spend so much time on it, but one hopefully learns by it.


Use JSON instead HTML for access denied on some custom paths

Drupal returns the 404 in the format requested, so adding the query string ?_format=json to the request should return a JSON response under any circumstances. If Drupal doesn't detect the format it uses HTML by default. You could either help Drupal detecting the format in a request subscriber or implement an exception subscriber to return JSON exceptions similar to ExceptionJsonSubscriber::on4xx for your API paths.


Override container.html.twig template for a specific context

I just did this a month ago for the same reason:

/**
 * Implements hook_theme_suggestions_container_alter().
 */
function mytheme_theme_suggestions_container_alter(&$suggestions, array $variables) {
  $element = $variables['element'];

  if (isset($element['#type']) && $element['#type'] == 'view') {
    $suggestions[] = 'container__' . $element['#name'];
    $suggestions[] = 'container__' . $element['#name'] . '__' . $element['#display_id'];
  }

  if (isset($element['#type']) && $element['#type'] == 'container' && isset($element['children']['#type'])) {
    $suggestions[] = 'container__' . $element['children']['#type'];
  }
}

This will work for Views and general types. It is coming up blank because you need to handle it a little differently depending on whats being rendered.

Then in my twig file I am just doing:

{{ children }}

because I didn't want wrapping divs.


AJAX error when ctools_modal_command_dismiss() is called

You are doing it wrong, ctools modal works a little bit different. Better do it like this:

remove #ajax property from form submit button, let it work as usual:

...
$form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Submit'),
  );
...

define submit callback as usual:

function pay_rise_modal_email_share_form_submit($form, &$form_state) {
  $values['message'] = $form_state['values']['body'];
  drupal_mail('pay_rise', 'share', $form_state['values']['recipient'], 'en', array('values' => $values));
}

build modal callback:

function myCallback($js = NULL) {
  if (!$js) {
    drupal_access_denied();
    drupal_exit();
  }

  ctools_include('modal');
  ctools_include('ajax');

  $form_state = array(
    'title' => t('My modal title'),
    'ajax' => TRUE,
    'build_info' => array(
      'args' => array(),
    ),
  );

  $commands = ctools_modal_form_wrapper('pay_rise_modal_email_share_form', $form_state);

  if (!empty($form_state['executed'])) {
    $commands = array();
    $commands[] = ctools_modal_command_dismiss();
  }

  print ajax_render($commands);
  drupal_exit();
}

ctools itself handles ajax submission.. That's it.


Special code for .htaccess and robots.txt files

It looks like the most important bit they want you to put in .htaccess is this:

SetEnvIfNoCase User-Agent "^SemrushBot" bad_user
SetEnvIfNoCase User-Agent "^DotBot" bad_user
SetEnvIfNoCase User-Agent "^AhrefsBot" bad_user
Deny from env=bad_user

They should probably go inside the <IfModule mod_rewrite.c> block in your .htaccess file, just after RewriteBase / (whether it's commented out or not).
This RewriteBase / line shouldn't cause any problems, if your drupal site is not in a subdirectory (e.g. your index.php file shouldn't be in a sub-folder of your webroot like http://domain.com/drupal/index.php)

The Options +FollowSymLinks shouldn't need to be included twice if it's already there.


Need to create a RedHen Contact for each Drupal User

Rules might be the quickest way to achieve this.

You could have one that on user create, generate a new contact for that user, and a separate rule that after a user updates their information update their contact.

According to RedHen documentation, they have direct rules support so this seems like an easy addition.


Separate permissions for administering user configuration and administering users

One method is to create a new permission

function MYMODULE_permission() {
  return array(
    'administer user configuration' => array(
      'title' => t('Administer User Configuration')
    )
  );
}

and then re-assign the pages under 'admin/config/people' to that permission:

function MYMODULE_menu_alter(&$items) {
  foreach ($items as $path => &$item) {
    if (strpos($path, 'admin/config/people') === 0) {
      $item['access callback'] = 'user_access';
      $item['access arguments'] = array('administer user configuration');
    }
  }
}

Then the user role in question can have the 'Administer users' permission, but not have access to the admin/people/config pages.

This feels messy at best though.


May be you have miss something.

For Gmap on Drupal site there are many ways to implement.

You can try this approch:

Put whole the code in any block with full text format.
Place that block in a specific region.
Set visiblity of that bock as per your requirment.

Implementation code be like this


When you added field_file in views as a field you should set the Formatter to URL to file instead of Generic file.


How to add CSS and JS files on node pages from theme's template.php

Since you want your CSS and JavaScript when displaying a node, you can add the files it in the preprocess function for the node template. Also, as stated in their documentation, when adding a file, the first argument for drupal_add_css() and drupal_add_js() is the path the CSS/JavaScript file relative to the base_path(). You can use drupal_get_path('theme', 'THEME') to get the path of your theme relative to the base path.

function THEME_preprocess_node(&$variables) {
  if ($variables['view_mode'] == 'full') {
    $node =& $variables['node'];
    if ($node->type == 'sales_team_page') {
      $path = drupal_get_path('theme', 'THEME');
      drupal_add_css($path . '/misc/jquery.fancybox-1.3.4.css');
      drupal_add_js($path . '/misc/jquery.mousewheel-3.0.4.pack.js', array('type' => 'file', 'scope' => 'header'));
      drupal_add_js($path . '/misc/jquery.fancybox-1.3.4.pack.js', array('type' => 'file', 'scope' => 'header'));
      drupal_add_js($path . '/misc/jquery.fancybox-calls.js', array('type' => 'file', 'scope' => 'header'));
    }
  }
}

Also, doing $node = node_load(arg(1)); to load the currently viewed node is unsafe and wrong. If you have a non node page at whatever/42 but have an existing sales_team_page node with nid = 42, you will load this node and add your CSS and JavaScript files even if the user is not viewing the node.


Drush make, git repository checkout specific subdirectory

The [subtree] only works if the download is an archive.
See Project download options page for drush 7.x.


You can consider using Panels module to override the user page.

UPDATE:

You must be knowing default user page has path of form 'user/[uid]'. Now to replace that with our new panels page, visit this link: "admin/structure/pages".

There, you can enable "user_view".

Now when you edit that, you choose layout and content (add the fields). Then when you visit user page at user/[uid], the new layout will take effect.


Cannot import Paragraph based Feature into new site

My best answer to this question is: Features is awesome but a little buggy, or seemingly so, due to field and field storage dependencies. The best solution I have found in Drupal using features and all these export issues is to create a content type where you create ALL your field base instances. I always call mine xxxFields. Then in all other content types, always add an "existing" field. really all this is doing is helping with user error. I have used features from 7 and now into 8, and I find that most issues arise through configuration of numerous content types which share fields, which creates dependency issues when trying to export features modules.

I believe your specific issue may be that that module is trying to create itself but has a dependency for a field base and field storage configuration that was created in another content type.


Import LinkedIn data (profile information) to user profile in drupal

That module is the only LinkedIn-specific module that does that; LinkedIn Company API Suite is for company (not individual) accounts and flux LinkedIn API integrates with LinkedIn, but it does not provide any other functionality.

For quick Drupal profile creation, you're better off using one of the many social media login modules that supports LinkedIn (e.g. HybridAuth, Janrain, etc.)


Problem with trailing slash and global redirect

if you are looking to redirect your users site or visitors to the right language you can do this without global redirect module
to do that

install [Localization update][1] , [variable][2] , [Internationalization],
after install modules active Locale , Localization update , Internationalization , Variable
go to Configuration > Languages > detection and selection
the 1st option URL u can choose between (Path prefix or domain)
the 2nd option is Browser and here u can Determine the language from the browser's language settings. if your browser's visitor is English he will go to English site ....
the 3rd option is User in this option the site Follow the user's language preference.

that's all


Perhaps the Drupal Restaurant Distribution is what you need, and if not it should at least give you some ideas.

It contains a number of modules, including on for reservations which I assume will do all you need, and more.

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

From the feature list:

  Reservation System - Manage your reservations easily from one
  dashboard. View all reservations for today, this week or this month.


Where to add track_changes option in migrate_d2d class

It seems you want to synchronize sites.
http://timonweb.com/using-hash-value-trackchanges-to-detect-source-data-changes-in-migrate-for-drupal-7
If you follow on this example you have mentioned above, Filter nodes by the update time these are changed after you deployed at last. You use MigrateSourceSQL. So you able modify a query.

If you want to synchronize sites, use the module: services or feeds.


You should do

$query->fields('n')->fields('prospekt');

See the documentation for more info.

Note that querying field tables this way is not recommended as the tables are created dynamically. You should only fetch field data via APIs.


How can I implement a RESTful API in Drupal?

For a REST API implementation on Drupal, use the Services module.

  A standardized solution of integrating external applications with Drupal. Service callbacks may be used with multiple interfaces like REST, XMLRPC, JSON, JSON-RPC, SOAP, AMF, etc. This allows a Drupal site to provide web services via multiple interfaces while using the same callback code.


Adding like condition to db_select for section of string

as it is trying to find pages that only contain 'Meetings' in their title.

Not quite - it's trying to find titles that end with the string "Meetings".

For a full wildcard match, the percent needs to be at both ends:

$query->condition('n.title', '%' . db_like($string) . '%', 'LIKE');


How to automatically assign a role based on email address domain?

Yes you could create your own (custom) Rules Condition. But in this case I don't think that's needed. The clue to what you're asking for, is a Rules Condition which is a "text comparison".

In that comparison, you use a regular expression to indicate "the email address should end with "@examplecompany.com".

For an example rule which also uses such RegEx-expressions, refer to the answer to "How to use the Rules module to perform a simple anti-spam validation using specific keywords?".

Be aware: I'm not a RegEx expert ..., but here a few dozens of similar examples using a RegEx ...

However, I predict you'll have multiple domains/roles to be processed. So the real Rules fun starts when this (typical) question arises: "I need to add something like a Rules Condition inside the Rules Actions, how can I do that?"

To resolve this typical question, there are basically 2 approaches (that I am aware of):

Use the Conditional Rules module. For an example using the Conditional Rules module (for which there is not a lot of docu available), refer to my answer to the question "How to prevent a node being saved when using the Rules module?".
Rework the relevant part of your Rules Action(s) into performing a Rules Component. Because in a Rules Component, it is possible to also add Rules Conditions.


I assume you're using the visible state?

The code that is responsible for doing this is in states.js:

$(document).bind('state:visible', function(e) {
    if (e.trigger) {
      $(e.target).closest('.form-item, .form-submit, .form-wrapper')[e.value ? 'show' : 'hide']();
    }
  });

As you can see, it calls show/hide without any configurable parameters, which means that it can't be easily changed.

However, the comment above that block is interesting:

/**
 * Global state change handlers. These are bound to "document" to cover all
 * elements whose state changes. Events sent to elements within the page
 * bubble up to these handlers. We use this system so that themes and modules
 * can override these state change handlers for particular parts of a page.
 */

If I understand this correctly, you can override the event handler for your specific page element, e.g. the form or even single form elements, by adding something like this:

$('form.your-form-class').bind('state:visible', function(e) {
  if (e.trigger) {
    $(e.target).closest('.form-item, .form-submit, .form-wrapper')[e.value ? 'slideDown' : 'slideUp']();
  }
});

I guess you will need to return FALSE to prevent that the event bubbles up further in the DOM tree.


In your tpl.php file only have the following

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

If you want to style it you can wrap divs around.

Then add a rel="lightframe" attribute in your link that will trigger lightbox.

Link


How can I change active theme for specific paths or inside module?

There are several modules you could use besides themekey:

Sections
Theme Rules (There is a 7.x branch, you'll probably need to check it out with Git)
Theme per path

Some of those are more focused for your task and don't have the overhead Themekey has (although it is a good module, just a bit heavy perhaps).


Flexslider view preview working but not on actual page

In the config of the 'jquery update' module, select 'Default (Provided by Drupal)' in both of the drop-downs.
i.e. 'Default jquery Version' and 'Default jquery Version for administrative pages'


PCI compliance with authorize.net payment- Drupal7.x

It's pretty easy to implement Authorize.net PHP SDK for this purpose. I also had started with Webform Pay (6.x) but it was not reliable in the fact that if a payment failed, or you wanted to do different form widgets (radio, select, text) to represent dollar value, it wasn't very feasible.

I wound up creating my own module that implements specialized Form API fields (CC number, CC date, CC cvv): https://www.drupal.org/project/creditfield

If you are comfortable with Form API, it is very easy to construct simple payment forms (simple donations, bill pay), and then handle the payment submission in your form submit handler. This module makes it possible to create one or more standard forms with Form API without having to implement the same validations all the time on the credit card fields.

I never had a need to store any data locally, not even the user information. If the payment did not succeed, the error was caught and logged and the user was asked to try again. If it succeeded, all of the submitted information was visible in the Authorize.net transaction logs. Check the SDK payload information to see what is available. It's been a while since I have done one, but you could use the card authorization method to create a transaction to be validated, and then perform the transaction.

For other methods, like off-site payment on a service like Authorize.net, you will probably need the applicable walkthrough. It also looks like the Webform Pay module has been abandoned with no stable Drupal 7 release, so this could be a good opportunity to roll up your sleeves and learn Form API + menu routes.

https://developer.authorize.net/api/reference/index.html#payment-transactions


Location Proximity Search using db_select in Custom Module

Thanks to @joemurray for pointing me in the right direction. This is my function to grab the closest nid to my target nodes lat, long.

/**
 *
 * Load the nid we are interested in for this report taken from the page we are on.
 * [http://funkjedi.com/technology/308-search-using-geolocation-data-in-mysql/][1]
 */
function _load_proximity_nids($lat, $lon) {
  $nids = array();

  // in Miles
  $radius = 25;

  // Constants related to the surface of the Earth
  $earths_radius = 3958.9394;
  $surface_distance_coeffient = 69.174;

  // Spherical Law of Cosines
  $distance_formula = "$earths_radius * ACOS( SIN(RADIANS(latitude)) * SIN(RADIANS($lat)) + COS(RADIANS(longitude - $lon)) * COS(RADIANS(latitude)) * COS(RADIANS($lat)) )";

  // Create a bounding box to reduce the scope of our search
  $lng_b1 = $lon - $radius / abs(cos(deg2rad($lat)) * $surface_distance_coeffient);
  $lng_b2 = $lon + $radius / abs(cos(deg2rad($lat)) * $surface_distance_coeffient);
  $lat_b1 = $lat - $radius / $surface_distance_coeffient;
  $lat_b2 = $lat + $radius / $surface_distance_coeffient;

  // Construct our sql statement
  $results = db_query('SELECT node.title AS node_title, node.nid AS nid, node.status AS status, node.type AS type, (' . $distance_formula . ') AS distance
FROM
{node} node
LEFT JOIN {location_instance} location_instance ON node.vid = location_instance.vid
LEFT JOIN {location} location ON location_instance.lid = location.lid
WHERE (location.latitude BETWEEN ' . $lat_b1 . ' AND ' . $lat_b2 . ') AND (location.longitude BETWEEN ' . $lng_b1 . ' AND ' . $lng_b2 . ') HAVING distance < :radius
AND (node.status = 1)
AND node.type = :type
ORDER BY distance ASC',
  array(
    ':type' => 'weather_reports',
    ':radius' => $radius)
  );

  foreach ($results as $result) {
    $nids[] = $result->nid;
  }

  return $nids;
}


How to add field update your password in drupal webform?

Webform Password Field

  This module allows you to add a password component to a webform. It
  doesn't validate the password in any way.


Use db_select with multiple conditions of which one needs to apply

Syntax for db_or :

$or = db_or();
$or->condition();
$or->condition();
$query->condition($or);

For More Information


Is it possible to create an iCal stream from Open Atrium's calendar feature? If so, how?

I ended up making the feed in a custom module using the iCalCreator library. I did like this approach because I was able to be very selective with the events to include in the feed which was a requirement and the iCalCreator library was VERY easy to work with :D


Add classes to quick tabs and nested tabs within quick tabs

Have you read this issue. Try to apply the patch by using git apply command line :

$ git apply --directory=path/to/module-dir/ add-custom-class-656330-6.patch

If you don't use git, add this line in the theme_qt_quicktabs_tabset function near the line 589 on the quicktabs.module file and the function will become :

<?php
function theme_qt_quicktabs_tabset($vars) {
   if ($key == $vars['tabset']['#options']['active']) {
     $item['class'] = array('active');
   }
   $item['class'][] = drupal_html_class($tab['#title']);# new line added by the patch
   $item['data'] = drupal_render($tab);
   $variables['items'][] = $item;
 }
?>

of course WITHOUT the <?php ?> tags

After that you have the title in class attributes :

Example :

tab title => given tab title
automatic tab class => given_tab_title

Wish helps :)


How to get field collection value in tpl file in drupal 7?

Use entity_load('field_collection_item', array($item_id)) or field_collection_field_get_entity($item)

Sample

$node = node_load($id);
$items = field_get_items('node', $node, 'field_fc');
foreach ($items as $item) {
$fc_value = field_collection_field_get_entity($item);
// Do something.
}

For reference link 1, link 2


How can I use Drush in a project installed with Composer?

Basically, you need to follow steps on http://docs.drush.org/en/master/install and get Drush installed globally. It's possible to invoke Drush installed within Composer context together with Drupal 8 indicating the exact path something like /path-to-website-home/vendor/bin/drush. However, if you want Drush available anywhere in the system then get Drush Launcher installed.

Here is direct quote from http://docs.drush.org/en/master/install:

  Optional. To be able to call drush from anywhere, install the Drush
  Launcher. That is a small program which listens on your $PATH and
  hands control to a site-local Drush that is in the /vendor directory
  of your Composer project. If you skip this step, run Drush from Drupal
  root via ../vendor/bin/drush. In that case Drush's bash integration
  and custom prompt won't work.

You might also want to read How to get Drush to work with Composer and What is the right way of installing Drupal 8?


Automatic alias overriding manual alias on each edit

Go to admin/build/path/pathauto on your site, open the 'General settings' fieldset and select 'Do nothing. Leave the old alias intact.' as update action. That should be all.


For Drupal 8 You have to use Toogle Editable Fields https://www.drupal.org/project/toggle_editable_fields


How to determine if a View display is being used in a site?

If this is in Drupal 8, you can export all config and search for the display id in both code and config and you should be able to find if it is being used anywhere.


For those that are not familiar with Omega theme, it will be hard to help you without more information like a link or your HTML and CSS code. However, you may look up the CSS float property to achieve what you want.


You'll need to get and install the Full Package here: http://ckeditor.com/download

Then the missing buttons will show up.


Change Sent By in Drupal 6 Webform Module?

Depending on the Webform version, you can accomplish this  in one of two ways:

Webform 2

When you edit the webform, look under Webform mail settings for E-mail from address. As long as you have an email field attached to the webform, you can select that field under the Component option.

Webform 3

Click on the E-mails task underneath the Webform tab when viewing a webform node. Within the E-mail header details fieldset, you'll see an option to change the E-mail from address.

The one caveat: Drupal sets the Sender:, Errors-To:, and Return-Path: headers to the site's email address. You can, however, change these headers using hook_mail_alter().

If you wanted to make sure the email field is set to user's email address (for a logged in user), you should've noticed the User email as default checkbox in the email field's settings, which will accomplish this and will work with the setting I mentioned above.


Simple way to change messages after node creation

You can do it through Rules

Create a new rule configuration and set the event to Node | After saving new content.

Add a condition, Node | Content is of type and set CONTENT TYPES to Article, as shown in the following screenshot:

Add an Action and select System | Show a message on the site

By using the Action, After saving new content, we're asking Rules to react on content creation. This means that the rule will fire every time a new content has been created in the system. By using Conditions, we can tell Rules to only fire the action if the created content type is Article (or any other content type). In the MESSAGE field, we've used REPLACEMENT PATTERNS to insert chunks of data from the objects available in our current rule configuration.


Theme suggestions not working for custom templates

Have you tried making the template name and pattern in the hook_theme implementation uppercase like this:

  'template' => 'MYMODULE-theme',
  'pattern' => 'MYMODULE_theme__',

You can also try to remove the pattern completely. It doesn't seem to be necessary at least in the example use case.

Preprocess functions for theme suggestions doesn't work in Drupal 7, and that's why you are manually calling them in your preprocess function. They are being added to the array so they are called but they are not in the correct format so that theme system could handle  them.


Seems like you are messing up with Multiselect and Improved multiselect modules.

Navigate to [your-site]/admin/config/user-interface/improved_multi_select and disable Improved multiselect settings as below.


Drupal 6: only displaying select vocabularies?

Assuming that the row style of your view is "Fields", add a "Taxonomy: All terms" field to your view. On that field's settings form, you will see a "Limit terms by vocabulary" checkbox. Select it and choose the vocabulary you want to show.


How to set up a date field based scheduled newsletter with Simplenews?

You could schedule a rule when the content type with the date field is generated.  You'd need to create a rule component that sends the email you want.  Schedule the component on content creation with the date field as the execution time.

I'm using this mechanism to delay some heartbeat activities on my site.  Works a treat.


Theme generic file link in node template

You can function theme_file_link() , you can change the file link title before html rendered for file link in your custom themes templete.php file.


The issue you have is with the module Internal Page Cache for anonymous users. You have several options:

If you want to serve for anonymous users a newly built page on each request the same way as for logged in users, then uninstall the Internal Page Cache module. The dynamic page cache will still cache pages, but does respect the cache contexts and max-age you set on the page elements.

Performance wise it is not a good idea to do this, so it might be better to configure a max-age for the Internal Page Cache, see this answer https://drupal.stackexchange.com/a/196557/47547, where you use an event subscriber to set an Expires time in the response.

If this is only for Views, another option is to modify the route definition of the view by setting a no_cache option, see this answer https://drupal.stackexchange.com/a/230242/47547

In all cases you need to configure /admin/config/development/performance for external caches like the browser cache.


How to programmatically create forums and containers (not forum topics)?

I think I got it.. not in some fields, not (directly) in some DB table.. the difference between forum and containers is in the variables:

$containers = variable_get('forum_containers', array());
$containers[] = 14;
variable_set('forum_containers', $containers);


How to set jquery datapicker options from within Drupal?

Your are working within a Drupal behavior that could be reapplied several times on the DOM tree, in order to avoid processing the same element several times you should limit the $($selector) call to the passed-ind `context and use a marker CSS class for already processed class. Something like

$('.selector:not(.only-monday-processed)').addClass('only-monday-processe').doSomethingwithTheElements();

To defines then set the datepicker options from Drupal server-side PHP, you need to store the selector(s) and options in the settings object received by your behavior attach function using the drupal_add_js() function or the #attached property of your form/render array element. Then your function can use the selector to apply the option to the element. Something like

In your module code, store the selector and options in settings:

drupal_add_js(array('myModule' => array('.selector' => array('showWeek' => TRUE))), 'setting');

In your JavaScript, for each stored selector, apply the datepicker options:

(function ($) {
  Drupal.behaviors.only_monday = {
    attach: function (context, settings) {
      var selector;
      if (typeof settings.myModule === 'object') {
        for (selector in settings.myModule) {
          if (settings.myModule.hasOwnProperty(selector)) {
            $(selector, context).filter(':not(.only-monday-processed)')
              .addClass('only-monday-processe')
              .datepicker('option', settings.myModule[selector]);
          }
        }
      }
    }
    // ...
  };
}(jQuery));


Yes, what you are seeing is the render cache. If you are developing a theme, you likely want to disable render caching and enable twig debug. See sites/example.settings.local.php for instructions on how to do that.

That said, breadcrumbs, like almost everything else, is a block now. Blocks are configuration. If you don't want a block, just remove that block in the UI. If you just remove it in the template, Drupal still needs to load and prepare that block for rendering as it cannot know the template doesn't print it.

And if you don't display the region (you always display regions with 0-N blocks, not directly blocks in page template), you should also not define it as an available region so that the user/site admin knows that he can't place blocks there.


Sometimes shipping and/or billing address is missing

I've had similar problems before, never did get to the bottom of it. I think it's related to the Commerce Addressbook module and the way it copies profiles but time ran out before I could confirm.

As a rather hacky (but effective) workaround I used the following to make sure the profile had been copied:

function MYMODULE_form_commerce_checkout_form_checkout_alter(&$form, &$form_state, $form_id) {
  $form['buttons']['continue']['#submit'][] = 'MYMODULE_commerce_checkout_form_submit';
}

function MYMODULE_commerce_checkout_form_submit($form, &$form_state) {
  // If the copy address checkbox is selected.
  if ($form_state['values']['customer_profile_shipping']['commerce_customer_profile_copy']) {
    $order_wrapper = entity_metadata_wrapper('commerce_order', $form_state['order']);
    $shipping_address = $order_wrapper->commerce_customer_shipping->commerce_customer_address->raw();
    $billing_address = $order_wrapper->commerce_customer_billing->commerce_customer_address->raw();

    // If the shipping and billing address aren't the same then we need to fix it.
    if ($shipping_address != $billing_address) {
      $order_wrapper->commerce_customer_shipping->commerce_customer_address = $billing_address;
      $order_wrapper->commerce_customer_shipping->save();
    }
  }
}

It may or may not work as-is, but even if not it might provide a starting point for debugging.


Adding a new column to users table: db_drop_field errror

There is the difference between hook_schema() and hook_schema_alter(): The first is used to create a database table when a module is installed, but the second is not used to alter an existing database table when a module is installed. hook_schema_alter() is used to alter the values returned from hook_schema() to let other modules know an existing database table (created from a module) has been altered (from another module).

What you need to to is:

Implement hook_schema_alter() to make public the changes you made to a database table created from another module
Make the changes in that database table, in hook_install() or hook_update_N()

The reason you need to alter what returned from hook_schema() is that there are functions that write on the database which use the information returned from hook_schema(), in primis drupal_write_record().

  $schema = drupal_get_schema($table);
  if (empty($schema)) {
    return FALSE;
  }

  $object = (object) $record;
  $fields = array();

  // Go through the schema to determine fields to write.
  foreach ($schema ['fields'] as $field => $info) {
    if ($info ['type'] == 'serial') {
      // Skip serial types if we are updating.
      if (!empty($primary_keys)) {
        continue;
      }
      // Track serial field so we can helpfully populate them after the query.
      // NOTE: Each table should come with one serial field only.
      $serial = $field;
    }

    // …
  }

Without hook_schema_alter(), which is invoked from drupal_get_schema(), such functions would not be able to correctly write on the database tables.


How a module can override theme suggestion?

This code works for me:

function MYMODULE_theme_registry_alter(&$theme_registry) {
  $mod_path = drupal_get_path('module', 'MYMODULE');

  $theme_registry_copy = $theme_registry;       // munge on a copy
  _theme_process_registry($theme_registry_copy, 'phptemplate', 'theme_engine', 'pow', $mod_path);
  $theme_registry += array_diff_key($theme_registry_copy, $theme_registry);

  $hooks = array('node');
  foreach ($hooks as $h) {
    if (!isset($theme_registry[$h]['theme paths'])) {
      $theme_registry[$h]['theme paths'] = array();
    }
    _MYMODULE_insert_after_first_element($theme_registry[$h]['theme paths'], $mod_path);
  }
}

function _MYMODULE_insert_after_first_element(&$a, $element) {
  if(is_array($a)) {
    $first_element = array_shift($a);
    if ($first_element) {
      array_unshift($a, $first_element, $element);
    }
    else {
      array_unshift($a, $element);
    }
  }
}

function MYMODULE_preprocess_node(&$vars) {
  if ($vars['view_mode'] == 'attach') {
    $vars['theme_hook_suggestions'][] = 'node__attach';
  }
}

I know you've seen nearly that exact code before from looking at your other question, but there are a couple of changes from the code in the article. It should work after clearing the caches (just once!)

Using the above I added a file called node--attach.tpl.php to my module folder, cleared the caches again, and the output from that template file was shown for the node.

Then I added node--attach.tpl.php to my theme folder, cleared the caches again, and the output from the new template file was shown.


The cache is used only when the input format is enabled to use it; this means that none of the input filters that are used by the input format disable the cache.

The code of check_markup(), which the function that is called when an input format needs to be applied to a text, contain the following code.

$cache = $cache && !empty($format->cache);
$cache_id = '';
if ($cache) {
  $cache_id = $format->format . ':' . $langcode . ':' . hash('sha256', $text);
  if ($cached = cache_get($cache_id, 'cache_filter')) {
    return $cached->data;
  }
}

$cache is a parameter passed to the function, and $format is the variable containing the value returned by filter_format_load(); if $format->cache is FALSE, the filter cache will not be used.

In the case of the body content of a node, the function that is used to sanitize the body content (and the content of other fields) is _text_sanitize(), which invokes check_markup() without to use the fourth parameter ($cache), which by default is FALSE. This means that, whatever the filter is set to use the cache or not, the cache will not be used.

function _text_sanitize($instance, $langcode, $item, $column) {
  // If the value uses a cacheable text format, text_field_load() precomputes
  // the sanitized string.
  if (isset($item["safe_$column"])) {
    return $item["safe_$column"];
  }
  return $instance['settings']['text_processing'] ? check_markup($item[$column], $item['format'], $langcode) : check_plain($item[$column]);
}

This is different from what done by user_comment_view() (the implementation of hook_comment_view() that is used to filter out the signature of the user who wrote the comment), which passes the fourth parameter to check_markup(), setting it to TRUE.

function user_comment_view($comment) {
  if (variable_get('user_signatures', 0) && !empty($comment->signature)) {
    // @todo This alters and replaces the original object value, so a
    //   hypothetical process of loading, viewing, and saving will hijack the
    //   stored data. Consider renaming to $comment->signature_safe or similar
    //   here and elsewhere in Drupal 8.
    $comment->signature = check_markup($comment->signature, $comment->signature_format, '', TRUE);
  }
  else {
    $comment->signature = '';
  }
}


How do I programmatically update the allowed values of a list field?

You can't do this in a form alter hook, because the entity field validation will fail.

You have to add a function to the field settings. This is not in the field UI, so you have to export the configuration and change the field in field.storage.node.field_time_zone.yml:

type: list_string
settings:
  allowed_values: {  }
  allowed_values_function: 'mymodule_allowed_values_function'

Reimport the configuration. Then you can implement this function in mymodule.module to set the options dynamically:

use Drupal\Core\Entity\ContentEntityInterface;
use Drupal\field\Entity\FieldStorageConfig;

  function mymodule_allowed_values_function(FieldStorageConfig $definition, ContentEntityInterface $entity = NULL, $cacheable) {
    $options = [
      ...
    ];
    return $options;
  }

See https://chromatichq.com/blog/dynamic-default-and-allowed-values-list-fields-drupal-8

For the question added later:

How can I set allowed value options to a field of type text(list) and save it accordingly?

The question originally was what to do with the code which doesn't work in form alter, where you can place it instead.

If you mean with this question you have a static allowed value list, then you can copy and paste the list in the field settings UI and save it:

And now it is stored in the mentioned yaml file of the exported configuration here:

  allowed_values: {  }


How to build an Isolated Drupal instance for testing

You could just use different git branches to isolate your code tests.

git checkout -b iss_tst1
<make changes>
git add <changes>
git commit -m "my new changes" <changes>

git checkout -b iss_tst2
<make changes>
git add <changes>
git commit -m "other new independent changes" <changes>

Then you should be able to run independent tests on each branch.


Just move your entire Drupal root somewhere else, and put something else in its place (with a "Be Right Back"-message) while the upgrade goes on.

For instance, if your Drupal root is /var/www/html, prepare a directory named /var/www/brb and put a static index.html-file in it with your BRB message.

Then execute the following pair of commands:

mv /var/www/html /var/www/pending_upgrade
mv /var/www/brb /var/www/html

Now, make sure that your ftp job puts the files in below /var/www/pending_upgrade.

When done, restore your site with the following pair of commands:

mv /var/www/html /var/www/brb
mv /var/www/pending_upgrade /var/www/html

The above assumes that you have CLI access.  If you don't, most ftp tools have built-in commands to move directories around.


What am I doing wrong in my theme that's breaking CAPTCHA?

I found the conflicting template inside USWDS base theme. For anyone else having this problem, you must alter this template:
/themes/contrib/uswds_base/templates/form/details.html.twig

You can either wholesale replace with the same template from Bartik's classy template (or similar), or else custom rewrite it using the working template from Bartik and customizing it to what you need. I needed to rip out the ul/li based markup that USWDS imposed, but still keep the classes and accessibility markup.
In case it helps anyone else, here's what I ended up using:

  {%- if title -%}
    {%
      set summary_classes = [
        required ? 'js-form-required',
        required ? 'form-required',
      'usa-accordion__button',
      ]
    %}

    <button type="button" aria-expanded="true" aria-controls="{{ attributes.id }}-content"{{ summary_attributes.addClass(summary_classes) }}>{{ title }}</button>
  {%- endif -%}

    {% if errors %}

        {{ errors }}

    {% endif %}
    {%- if description -%}

{{ description }}

    {%- endif -%}
    {%- if children -%}
      {{ children }}
    {%- endif -%}
    {%- if value -%}
      {{ value }}
    {%- endif -%}


I has just found a solution for it. Perhaps, somebody can find more pretty realisation.

So, first step:
Lets your 'hook_node_view' in custom module call early than webform 'hook_node_view', you can do it through hook_module_implements_alter() something like it:

function YOUR_MODULE_module_implements_alter(&$implementations, $hook) {
  if ($hook == 'node_view') {
    if(isset($implementations['YOUR_MODULE'])){
      $group = $implementations[YOUR_MODULE];
      unset($implementations[YOUR_MODULE]);
      $implementations = array_merge(array(YOUR_MODULE => $group), $implementations);
    }
  }
}

Second step:
Remove unnecessary webform components from node object.

function YOUR_MODULE_node_view($node, $view_mode) {
  if (isset($node->webform['components']) && YOUR_CONDITION) {
    foreach ($node->webform['components'] as $key => $component) {
      if ($component['page_num'] == 2) {
        unset($node->webform['components'][$key]);
      }
    }
  }
}


How to show a title-link in a view for authorized and hide it for unauthorized users?

You can implement template_preprocess_views_view_field function in your module and rewrite output for this field for anonymous users.

/**
 * Implements hook_preprocess_views_view_field().
 */
 function mymodule_preprocess_views_view_field(&$vars) {
   switch ($vars['view']->name) {
     case 'my_view_name':
       if ($vars['field']->options['id'] == 'my_field_name') {
         if (user_is_anonymous()) {
           $vars['output'] = strip_tags($vars['output']);
         }
       }
       break;
   }
 }


Is this snippet modification correct? (php snippet in a drupal commerce rule)

You can add your PHP code in action of some rules. For this you will have to enable core PHP filter module.
Once you enable it, you go to ADD ACTION in rules and you will find a option "Execute custom PHP code". If the variable you are suppose to use is available there for using with the PHP code then it will work without any problem..

As per your requirement, if you do this by simple small module then also it will work fine as you just have to put this hook in your .module file, declare the module in .info file & enable it....I am suggesting using module as I see you are already checking your condition in code...