How to use _user_mail_notify with a defined language

I finally understood and overcome the issue, in order to send emails in a different (enabled) language multilingual features must be enabled for the emails.

To enable the multilingual features there are just few steps:

The module "User mail translation" has to be enabled
From the Variable configuration (admin/config/regional/i18n/variable) you have to select the tab "User emails" and then check the email types you want available in a different language
From the account setting page (admin/config/people/accounts) then you select the language (in the very first box of the page) and add the translation for the related email templates (just scroll down)

After this 3 steps you will be able to send emails in all the enabled (and translated) languages in your site.


You could craft a variable that holds all entity fields with respect to their order and formatter settings.

/**
 * Implements hook_theme().
 */
function sponsor_theme() {
  return [
    'sponsor' => [
      'render element' => 'elements',
    ],
  ];
}

/**
 * Prepares variables for sponsor templates.
 */
function template_preprocess_sponsor(&$variables) {
  // Helpful $content variable for templates.
  $variables['content'] = [];
  foreach (Element::children($variables['elements']) as $key) {
    $variables['content'][$key] = $variables['elements'][$key];
  }
}

This approach is used by core entities (node, user, comment etc).


As I also stated in my comment, try to give a real network path. For example if the shared folder Z: is mapped to \\server\folder, the real network path of the file would be:

  file:///\\server\folder\popular-documents\how-to-use-pc.docx

UPDATE:

According to Link module page:

  Filter allowed protocols module This module allows you to change the default protocols that are set by Drupal to include new protocols like skype. The default protocols, for reference, are 'ftp', 'http', 'https', 'irc', 'mailto', 'news', 'nntp', 'rtsp', 'sftp', 'ssh', 'tel', 'telnet', and 'webcal'.

You can try this module to include 'file://' protocol.


I can't show the body content with full HTML

The error message you see (Full HTML: Missing filter. All text is removed.) means that one of the filters you selected on admin/config/content/formats/manage/full_html is missing; this usually happens when you uninstall the module implementing it. As explained in Missing filters result in Exception when the format is used, in those cases, Drupal doesn't show the text using the input format containing the missing filter.

That is not a problem. Just go to admin/config/content/formats/manage/full_html and save; the reference to the missing filter will be removed, and you will be able to see the body text again. In fact, the form builder for the input format form contains the following code. (See FilterFormatFormBase::form().)

  // Create filter plugin instances for all available filters, including both
  // enabled/configured ones as well as new and not yet unconfigured ones.
  $filters = $format->filters();
  foreach ($filters as $filter_id => $filter) {
    // When a filter is missing, it is replaced by the null filter. Remove it
    // here, so that saving the form will remove the missing filter.
    if ($filter instanceof FilterNull) {
      drupal_set_message($this->t('The %filter filter is missing, and will be removed once this format is saved.', array('%filter' => $filter_id)), 'warning');
      $filters->removeInstanceID($filter_id);
    }
  }

The message clearly says The filter is missing, and will be removed once this format is saved. So, saving should fix the issue.
If this doesn't work, remove another filter from the input format, save, re-add the same filter you removed, and save again. At least, this should clear the eventual cache Drupal uses for filters or input formats.


Creating smaller menus from chunks of a bigger menu

What you are describing is the primary feature provided by the Menu block module.


Can a Webform display the last submitted version of instead of creating a new submission

Yes!!! Just go to Webform: Submissions: Settings and check off 'Limit total to one submission' per user or per submission.


What to do when Drupal views module doesn't output what you want?

Is there a way to write the view code manually or something like that?

You could easily setup a menu route and controller (or page callback in D7) to serve the same purpose. The controller would execute the query (provided by you) and return the results / page output as a renderable array.

However, there are many variables in between, so it would be hard to provide all the code.

Here is a walkthrough for D7 to starting to code your own route and callback: https://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook_menu/7.x

Here is one for D8:
https://www.drupal.org/docs/8/api/routing-system/introductory-drupal-8-routes-and-controllers-example

It would be a good opportunity to learn how to extend Drupal and 'take control' when you don't get the result you want with Views, or, just to have more control in general.


I ended up running two global drush installs as explained here.

I needed to make to use same versions of Drush 9 both globally and on the site-specific installs to not get any errors. Now both Drush 8 and Drush 9 seem to run smoothly alongside each-other.


How to create a commenting system for ECK entities, similar to node comments as exposed field under the body?

As an alternative to the Comments Entity module, and the bug you reported about it, you may want to give the Reply module a try. Some more details about this module, from its project page:

Reply is a D7 answer to entity comments.
Reply is basically a fieldable entity so you can create a 'review', 'comment', 'forum post' or whatever you like by creating bundles and attaching fields to them. Such bundles can be attached to any fieldable entity by 'reply field'.
You can set access for reading and writing, position the form to the same page as entity or to a custom page, allow or deny replying to replies(= no hierarchy), choose threaded or flatted list. Such settings can be set for bundle, field, instance and entity with build-in inheritance which makes if a four level hierarchy settings system.
Most common usage of this module is comment replacement and reviews.

Even though this module only has an alfa release for D7 (as compared to a beta release for the Comments Entity module), the issue queue statistics seem to be more healthy:

Reply:  66 open, 166 total (about 40% open issues).
Comments Entity:  10 open, 10 total (= 100% open issues).


Avoid a revision is automatically published

Please have a look at Revisioning module, this is probably what you are looking for.
There is simpler module Revision Moderation, but it has no D7 version


Views Day of Week provides a simple filter plugin for Views 3 to enable filtering content that should be visible based on the current day of the week.

  Example: With this module you can select that some content should be
  visible only on Mondays, some on Tuesdays and Thursdays and some only
  on Fridays.


Best method of changing content of one field based on whether another exists

look in to https://api.drupal.org/api/drupal/modules%21node%21node.api.php/function/hook_node_view/7.x

In Drupal 7 yes you can do this in the template file for the content type, -> unless you are changing themes lots perhaps the "custom logic" in the  theme file is the quickest win.


There is the Boxes module. Which supports in-place editing.

  Boxes module is a reimplementation of the custom blocks (boxes) that
  the core block module provides. It is a proof of concept for what a
  re-worked block module could do.

  The module assumes that custom blocks are configuration, and not
  content. This means that it is a reasonable action to ask for all
  blocks at one time, this is in fact exactly what the core block module
  does.

  Boxes provides an inline interface for editing blocks, allowing you to
  change the contents of blocks without going to an admin page.

  Boxes provides exportables for its blocks via the (required) Chaos
  tools module. This allows modules to provide blocks in code that can
  be overwritten in the UI.

  Chaos tools is required to use Boxes.

Be sure to look at the module page for full information.


Import Drupal Database, Excluding Database Connection Parameters

I've actually never heard of database settings being stored in the database. Are you sure you aren't updating your site's settings.php-file as well?

Do you have different database prefixes?

Could it be related to some stale cache?


Best practice for avoiding module / theme / profile name clashes?

In my office we usually have a site key that gets used for most things.

Client: Acme Company & Co
Key: acme
Site Folder: /path/to/WebServer/sites/acme
Custom Modules: acme_tweaks, acme_forms, acme_blocks, acme_settings
Theme: acme_theme
Repo: acme.git
etc...

For code that we re-use from site to site, we ensure that it's generalized and client ambiguous and then add it to some common modules that are part of our default module set - such as:

theme_tweaks
template_suggestions

Our rule is that unless it can be applied to all our client sites (at least moving forward) then it shouldn't go in theme_tweaks but in acme_tweaks etc.


Drupal multi-site subdomain and subpath going to same site

You can configure your desired structure/aliasing by creating the sites.php file in the sites directory. See the example.sites.php file in the same directory for extensive documentation on this topic.

So, for your use case:

$sites['foo.example.com'] = 'foo';
$sites['example.com.foo'] = 'foo';

When visiting foo.example.com or example.com/foo, Drupal will return the "website" located at sites/foo. (However, instead of foo usually the name of the (sub)direcotry is one of these aliases).

About running into any issues, the one thing that comes into my mind is that search engines seem to appreciate unique content. It is considered bad practice if your (public) content can be accessed by multiple web addresses (therefore generally it is recommended to set up 301 redirects, however, not sure if this is the right place to discuss this topic since it is not specific to Drupal).


Multiple buttons to link to different page and different query

Use the following code:

function sample_menu() {
  // This is a default option, without argument.
  $items['upcoming_games'] = array(
    'title' => 'Upcoming Games',
    'page callback' => 'my_page',
    'page arguments' => array(),
    'access callback' => TRUE,
  );
  // This is for any other date.
  $items['upcoming_games/%'] = array(
    'title' => 'Upcoming Games',
    'page callback' => 'my_page',
    'page arguments' => array(1),
    'access callback' => TRUE,
  );

  return $items;
}

function my_page($date = NULL) {
  // If the $date has not been defined, it means that the user is trying to see
  // today's games.
  if (!$date) {
    // Redirect to today's date.
    drupal_goto('upcoming_games/' . format_date(REQUEST_TIME, 'custom', 'Y-m-d'));
  }
  // Otherwise, check the date. The strtotime() function is just as an example.
  else {
    $date = strtotime($date);
  }
  // Continue the operation.
  // ...
  return 'Upcoming games for ' . format_date($date, 'custom', 'Y-m-d');
}


Language switcher block is different on remote site

Possible reason:

Maybe you are not in the same page.
You dont have the same configuration

Solution:
We suggest you add your own custom class or container div. And from these, add the correct CSS.


Whenever I edit/update a node all the page caches for anonymous user are lost

Whenever I edit a node all my page caches are cleared.

As per the design : This behavior is intended behavior and works as per the design. If you look at the node_form_submit() node submit handler function within the node module you will notice that there is a cache_clear_all() As the comment in the line above the function call reads it clears the page and blocks cache as expected.

Reason for clearing all the caches: When a node is created/updated there can be many pages in the site which are dependent on the current node in question. It is next to impossible/very difficult identify all the dependencies and clear the caches only for those pages. For this particular reason, to make sure that no stale data is served to the end user drupal by default clears all the caches.

Work Around :

Approach 1 : Since node_form_submit is form submit handler you could just implement a hook_form_alter() and change the submit handler to your own function which can omit cache_clear_all() function call.

Approach 2 : Set Minimum Cache Life Time to a high value. (By doing this you are asking Drupal not to clear caches if they are not older than the specified Minimum Cache Life time. So now if you edit a node, the changes will not be visible immediately. Your changes will only be visible when time elapsed is greater than Minimum Cache Life time and next general cache wipe has occured.)

Once you have set the Minimum Cache Life Time you can use Expire module to implement your custom logic for Invalidating a cache. You can have settings such that whenever a node is edited drupal can clear the cache for that particular page and all the listing pages.

EDIT(After @MPDs comment) : If you are using a reverse proxy server then you might need to consider setting the Expiration of cached pages to an appropriate value and probably consider using purge module.

Futher Reading : Difference between Minimum Cache Lifetime and Expiration of Cached Pages value.


What is the path for form elements which are ajax-enabled

foreach (element_children($form['alternatives']) as $delta) {
  $form['alternatives'][$delta]['advanced']['#access'] = FALSE;
}

Something like this.


As the error message says, this is not supported. There is no API that will do it for you.

There was a similar question recently but I can't find it right now, just this one: How do I change the type of a field attached to a content entity?

In short, you have two options:

Create a new field, write a script to move over all your data, then delete the old field.
Manually alter the database schema and low-level config data as well as the data that Drupal has stored about the field type and its schema. This is by far the more complicated option.


Is there a way to add a Captcha to Ubercart?

I am assuming you are talking about the add to cart form. Please share on what page or place you need captcha?

If you cannot find a module, then you need to do exactly what the captcha module does,

Write hook_fomr_FORM_ID_alter for the form for which you need to add the captcha.
Look for articles online explaining how to add captcha programmatically on a form in Drupal, ex: How do I add reCaptcha to a custom form?, https://www.drupal.org/node/743056.
Enable your custom module containing this code, and the captcha module.

You should have your captcha on ubercart's add to cart or any other form with a submit button.


How to read testbot feedback / get more info

If you click the colored patch result (above), you will get to a detailed page. On the top of that page there is a link 'View results on dispatcher'. That will get you to the test. Then go to the 'Console output' (on the left) (direct link).

The actual error appears to be:

  13:56:12 PHP Fatal error:  Class
  'PhpOffice\PhpSpreadsheet\Worksheet\Worksheet' not found in
  /var/www/html/modules/contrib/migrate_spreadsheet/tests/src/Unit/SpreadsheetIteratorTest.php
  on line 187


Node Acess User Reference and Organic Groups permissions

Nevermind, http://drupal.org/node/1171834#comment-6019078 answers it.


Creating a dynamic contextual filter list

I have personally done the contextual filter part of it and can confirm it works very well and is easy to setup.

Simply add a contextual filter for "Content: Created year" and "Content: Created month" and then set the Path of the view to "/articles". I use basic validation for the contextual filters and have also setup something for no results so the users aren't presented with a blank page.

I'm not quite sure what you're asking for with the other part of the question.

I think the easiest way of going about this is to create a separate Views block and add a field that contains the post date. You can then use a custom Date format to display the post dates the way you want them. "F, Y" should do it.

Turn on Aggregation and make sure it's grouping the results together and you should be good to go. You can now use the rewrite as link to accomplish what you need. You may need to add a couple of other hidden fields to get all the parameters you need.

UPDATE: I realized there is a problem here. Views aggregation works on the raw SQL data only which is what I think your original problem was. This means that group by date doesn't actually work as you mentioned earlier. There are a couple solutions I came across http://drupal.org/node/388140, http://drupal.org/project/views_date_format_sql, and http://groups.drupal.org/node/40356.


For this one - I am going to adjust the size via css in each of the views.  Would still like to know if the above is possible, but this will resolve my current issues


How to make a single query with multiple records

This works for me.

$result2 = db_query("SELECT fci.* FROM {node} AS fci LEFT JOIN {node_access} AS fdfp ON fci.nid = fdfp.nid where fci.nid IN(SELECT replace(source, 'node/', '') as source FROM {url_alias}  where source like 'node/%') AND fdfp.nid IS NULL");
foreach ($result2 as $record2) {
  echo '<pre>';
  print_r($record2);
}


Isn't it possible to have multiple buttons  along with a submit button?

Jaypan gave me the answer.

  Required checks happen irregardless of validation - they happen before any other validation even occurs.
  You cannot skip the default _validation() function, it is always executed
  When you choose limit_validation_errors(), anything that is not part of that array is not submitted.

  As such, you will want to explicitly declare your submit and validate functions for the original submit button, and leave the second button as-is, using the default submit and validate functions:

function some_form($form, &$form_state) {
  // Form definition not shown.
  $form['submit1'] = array(
    '#type' => 'submit',
    '#value' => t('Submit 1'),
    '#validate' => array('my_explicit_validate'),
    '#submit' => array('my_explicit_submit'),
  );

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

  return $form;
}

// my_form_validate is not created, since we don't want to validate the second submit button, but we do want the submit function.
function my_form_submit($form, &$form_state) {
  // You need to check which submit button was pushed, as this function
  // will be run for both buttons, but you only want do something if it was the
  // secondbutton.
  if($form_state['values']['op'] == $form_state['values']['submit2']) {
    // Second submit button's submit function.
  }
}

function my_explicit_validate($form, &$form_state) {
  // Validation for the first submit button.
}

function my_explicit_submit($form, &$form_state) {
  // First submit button's submit function.
}

  To deal with your required issue, you will need to not set #required => TRUE for the elements, and check them manually in your validation function (the function explicitly declared for the first button). If you want to have the required marks, I think you can manually add them to the element title, or you can override the theme function for those elements and manually add them there.


After any AJAX form event, all Entity Reference Fields are blank

I finally solved this.

There is a patch here... https://www.drupal.org/files/issues/entityreference-use-tokens-2010898-126.patch That allows you to use tokens in the Entity Reference Fields "Pass argument to view" field.

The problem was that after AJAX, the view I was using for the Entity Reference was losing its contextual filter argument. This patch, and the use of the token fixes the problem nicely.


You need to add Forum Containers, and then place the Forums in the appropriate container. Topics are then added into the Forums from the add content or Forums page. So basically you need to plan the hierarchical structure that your forums will take beforehand.

For more forum features look at Adding functionality to your forum with contribs

Tutorial : 203: Creating and Managing Forums in Drupal 7


Drupal menu callback create node permissions

Don't use access arguments. Use user_is_logged_in() as access callback.


I don't think you can migrate like that.  I am pretty sure the database creation during installation process is different if you're using postgres.


drupal_set_message is visible only to those with permissions for the operation?

No, it doesn't. It means that if you want to get the list of the messages set from other modules, you just call the function without any argument; this is what drupal_get_messages() does to get the list of messages set by the modules.

function drupal_get_messages($type = NULL, $clear_queue = TRUE) {
  if ($messages = drupal_set_message()) {
    if ($type) {
      // …
    }
    // …
  }
  // …
}

If the message should be visible to users with a specific role, it is the caller that needs to first check the user's permissions with user_access() as in the following code, executed from comment_form_submit():

  if (!user_access('administer comments')) {
    drupal_set_message(t('Your comment has been queued for review by site administrators and will be published after approval.'));
  }

This doesn't need to be done in a form submission handler, if who uses the form is already restricted to who has that permission.


How do I display images from a field in a View as grid?

You can edit image field in view and uncheck "Display all values in the same row" checkbox under "MULTIPLE FIELD SETTINGS" fieldset. This will tell view to render each image in node as single row. See screenshot below for field settings:


Yes, you can use a contextual filter on a node nid.  For its value, select a default argument (since a block won't have it) and then select node id from url.  Then also click on exclude the argument.  This will create a contextual filter that excludes the node on the page from the View.


How can I prevent users from entering invalid e-mail addresses at registration?

Drupal validates the email since Drupal 5; since Drupal 7, valid_email_address() (the function used to validate the email entered during registration, or when editing a user account) calls filter_var().
The code used to validate the email address doesn't check if the domain exists, the username doesn't contain typos, or the domain has an active email server. While it would be possible to check if the domain has an email server by looking at its MX records with checkdnsrr(), it would be more difficult to verify if the username is correct, as most of the SMTP hosts doesn't return a useful value for the VRFY command (which means they always return ERROR, or OK).

Notice that the documentation for getmxrr() contains the following note.

  This function should not be used for the purposes of address verification. Only the mailexchangers found in DNS are returned, however, according to RFC 2821 when no mail exchangers are listed, $hostname itself should be used as the only mail exchanger with a priority of 0.

I would rather do as @Letharion suggested, and implement hook_cron() to get ride of those accounts created by users who didn't type their email correctly. For Drupal 7, I would use the following code.

function mymodule_cron_queue_info() {
  $queues['mymodule_delete_users'] = array(
    'worker callback' => 'user_delete_user',
    'time' => 30,
  );

  return $queues;
}

function mymodule_cron() {
  $query = new EntityFieldQuery();

  $query->entityCondition('entity_type', 'user')
    ->entityCondition('entity_id', 1, '>')
    ->propertyCondition('access', 0)
    ->propertyCondition('created', REQUEST_TIME - MYMODULE_DELAY, '<')
    ->addTag('DANGEROUS_ACCESS_CHECK_OPT_OUT');

  $result = $query->execute();

  if (isset($result['user'])) {
    $queue = DrupalQueue::get('mymodule_delete_users');
    foreach (array_keys($result['user']) as $uid) {
      $queue->createItem($uid);
    }
  }
}

The module should define the constant MYMODULE_DELAY, and set it to an appropriate value.


There doesn't seem to be a "custom ruleset" module on Drupal.org, but I'd simply use the Rules module, together with the Webform Rules module, as further explained below.

Step 1 - Create a basic eMail about the submitted Webform

Have a look at this example rule (in Rules export format):

{ "rules_process_submitted_webform" : {
    "LABEL" : "Process submitted webform",
    "PLUGIN" : "reaction rule",
    "ACTIVE" : false,
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "webform_rules" ],
    "ON" : { "webform_rules_submit" : [] },
    "IF" : [
      { "data_is" : { "data" : [ "form-id" ], "value" : "2" } },
      { "user_has_role" : {
          "account" : [ "site:current-user" ],
          "roles" : { "value" : { "2" : "2" } }
        }
      }
    ],
    "DO" : [
      { "mail" : {
          "to" : "[site:mail]",
          "subject" : "A new webform submission has occured",
          "message" : "A new webform submission has occured (with form-id \u0022[form-id:value]\u0022). It was submitted by the user with id = [user:id], name = [user:name] and eMail Id = [user:mail] ...",
          "language" : [ "" ]
        }
      }
    ]
  }
}

Some details about the above rule:

Rules Event: After a webform has been submitted
Rules Conditions:

Form-id has value "2" (change to whatever form-id to fit your case).
User submitting the form is logged in.

Rules Action: Sent an eMail.

Not sure if it is the case for you, but if the user who submitted the form is authenticated (not anonymous), then you do already have access to a limited set of tokens related to the user who submitted the webform, such as [user:id], [user:name] and [user:mail]. If the user is anonymous, just omit that condition, and don't refer to those tokens in the eMail being created.

Step 2 - Include data from the submitted Webform data in your eMail

You do have access to all labels and all values of any field of a Webform, ie:

[data:MachineFieldName-title] contains the Label of a field with machine name MachineFieldName.
[data:MachineFieldName-value] contains the Value of a field with machine name MachineFieldName

For way more details on this, and a prototype rule about this, refer to the answer to "How to create a node from a Webform using rules?":

the 1st attempt relates to using "Entity has field" (which doesn't work for Webform).
the 2nd attempt explains what to do in case of Webform.

And while the above is a good start, it may still not be sufficient to achieve your goal. I.e. if you want to use specific data from the submitted webform. However, you can use a technique similar to what is described in my answer to "How to do a data comparison to submitted webform data when using the Rules module?". For short:

Add an extra Rules Action to Add a variable, with a value assigned to it equal to your [data:SomeField-value-raw] (and with an appropriate data type). I'm assuming a field in your webform has a machine name like SomeField (adapt to fit your machine name).
In your subsequent Rules Actions you can refer to the value of this variable you just added (that's the clue!).

Step 3 - Cover all possible variations of the Webform data

To make this work for each of the 4 (or 5?) conferences, you basically have 2 options:

Duplicate this rule for each possible form id (or form component value if all conferences are covered via a single form) you want to process this way. E.g 1 such rule for each conference.
Use the Conditional Rules module if you want to have a single (consolidated) rule for all conferences to be processed.

Here is an example rule (in Rules export format), which uses the Conditional Rules module:

{ "rules_process_submitted_webform_based_on_a_component_value" : {
    "LABEL" : "Process submitted webform based on a component value",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "rules_conditional", "webform_rules" ],
    "ON" : { "webform_rules_submit" : [] },
    "IF" : [
      { "data_is" : { "data" : [ "form-id" ], "value" : "2" } }
    ],
    "DO" : [
      { "variable_add" : {
          "USING" : { "type" : "text", "value" : "[data:somefield-value-raw]" },
          "PROVIDE" : { "variable_added" : { "submitted_form_component_value" : "Submitted form component value" } }
        }
      },
      { "SWITCH" : {
          "USING" : { "data" : [ "submitted-form-component-value" ] },
          "DO" : [
            { "CASE" : {
                "USING" : { "value" : "1" },
                "DO" : [ { "drupal_message" : { "message" : "Webform Option 1 was selected" } } ]
              }
            },
            { "CASE" : {
                "USING" : { "value" : "2" },
                "DO" : [ { "drupal_message" : { "message" : "Webform Option 2 was selected" } } ]
              }
            },
            { "CASE" : {
                "USING" : { "value" : "3" },
                "DO" : [ { "drupal_message" : { "message" : "Webform Option 3 was selected" } } ]
              }
            },
            { "DEFAULT CASE" : [
                { "drupal_message" : { "message" : "Webform Option selected was different from 1, 2 and 3" } }
              ]
            }
          ]
        }
      }
    ]
  }
}

Some details about the above rule:

Rules Event: After a webform has been submitted
Rules Condition: Form-id has value "2" (change to whatever form-id to fit your case).
Rules Actions:

Add an extra Rules Action to Add a variable, with a value assigned to it equal to your [data:SomeField-value-raw] (and with an appropriate data type). I'm assuming a field in your webform has a machine name like SomeField (adapt to fit your machine name).
Show a message on the site (depending on the value of the variable that was added via the prior Rules Action).

What is left to do to further tune the above Rules example to fit your needs:

Replace the "Show a message on a site" by an appropriate eMail to be created (for each "case").
And for each of those eMails just indicate which eMail Ids should receive that eMail.

Voilà

PS: forget about your "custom ruleset module", no more need for it to solve this challenge.


You can search for examples for each of your questions with "backwards views" and "sibling views". In short:
Show children on parent page
Create a Views that lists Children, then add the Entity reference field as the Contextual filter (not Content ID). Configure it to Provide default value Content ID from URL.
No Relationships needed in this solution. Place the Block on Parent pages and don't forget to configure the Block contextual option, it won't work without it.
Show siblings on child page
Create a Views that lists Children. This time you'll need 2 Relationships and 1 Contextual filter, all sequentially linked.
The first Relationship is for your ER field (the Field on Child that references a Parent), this one introduces the Parent info.
The second Relationship is the "backwards" Relationship for the same field, it is named a bit differently that the "forwards" one. Make the second Relationship use the first Relationship. This will trace path "backwards" from Parent to all their Children.
Add the Content ID Contextual filter and make it use the second Relationship. Configure it to Provide default value Content ID from URL. This will tell Views which Child's page you're currently viewing and will match to the Parent and then Parent's children.
Exclude current Child from Views
Your current Child will also be listed in Views because it satisfies the same condition! (It's also Parent's Child, just like other Siblings.)
You can exclude it by adding the second Contextual Content ID Filter that doesn't use any Relationships, Provides default value Content ID from URL, but under the last section More also check Exclude.


How to set static field on Display Suite

Add a code field to Display Suite. In that code field you add your html (with token support if token is installed). Then just place the code field in the display tab for the content type.

Tutorial here.


How do I set field mapping in the Feeds module for Drupal 8?

First, select a target to map to.

This will result into a list of sources to appear. Select one of these sources.

Notes:

The UI for CSV parser is still incomplete. See https://www.drupal.org/node/2669974
If the sources list does not appear after selecting a target, you may be facing javascript issues. In this case, check with a debugger which scripts fails. In D7, the jQuery Update module (or how that modules was configured) sometimes was the culprit.
If there are no targets appearing, try to rebuild caches.
Currently there is a bug with updating items if the target 'Feeds item' is not in the list. Be sure to map to that target if you not only want to insert new items, but also update existing ones. See https://www.drupal.org/node/2857692.


Theming a views field output using views-view-fields.html.twig

You need to refer documentation for the working with twig template. Here you can use conditional twig :

Twig: {% if field.[field_name].content is not empty %} field.[field_name].content {% endif %}


New custom content type: place image above body

On Drupal 7, you can change the placement of the image from within the interface by navigating to Structures-> Content Types-> Name of your content type and then clicking Manage Display.  Drag the image above the body to show it first.


Add 2 flag fields of 2 types of flag to views field

You may be able to do this with native views.

Using field rewriting in views you can insert values into field display originating from other fields in the same row if they are ordered to appear above it. You can also use a "Global: Custom Text" field and add values and HTML to construct complex output.

Add the fields you want to be displayed as part of the rewritten/global field should be ordered to appear above it by clicking the reorder button and using the handle bars to drag fields up and down.

Those fields you want to merge should be set to exclude from display.

Those hidden fields will be available as a token value you will be able to use elsewhere in the view row in the global custom text field, or combined field.


I guess you're talking about tabs

As it is written on the page :

  The tabs module integrates the jQuery UI tabs plugin, providing client-side interactive tabs. This is a helper module. It doesn't do anything on its own. Rather, it is used by other modules that provide tabs.

If you are not a coder, don't use this module.
If there is not any module that ask you to install this module, don't use this module.

If you want some tabs to break long pages into smaller ones, have a look on paging module.

If you just want to add some tabs like "Views," "Edit," etc on nodes, this is handled by core code; have a look to the API, especially hook_menu().


Most performant way to check if a user is referenced in any node of a specified type?

I suggest you NOT to worry about performance until it's not a real issue. That doesn't mean of course you can write any silly things you want to.
The code snippet you posted is just fine. You are using the Drupal API, which is a good thing to do.

If you really want to speed up things, to make it for example with ONE query (instead of two) you can use:

\Drupal::database()->select("..."); // With a proper dependency injection

About how to write queries in Drupal connection class there is a lot of good tutorials. If you wouldn't find one, please let me know.

However, I only would use this, if it's a REALY performance issue. It's never a good thing "having a knowledge" in your production code about your table schemes. Always start with EntityTypeManager or entityQuery (as you did).


Is there a way to add the comment section to the node edit page?

Take a look at this for setting up a custom edit template if you don't want it site wide: http://www.nybergtechnology.com/blog/2013/11/11/how-create-edit-tpl-node-type-drupal-7

then you should be able to add:

<?php print render($content['links']); ?>  // only if you want the links to show

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

to the bottom, to produce the comments. (I didn't test this, so it may be gibberish)


Disable transition effect field slideshow

Set "Transition speed" to 0 (zero) and it won't have any transition effect, just the direct change of image.

If you want to stop automatic changing of images, set "Timeout" to 0 (zero).


How to use subquery in views where clause

Just ran into the same question, here is what I found:

You can add a sub query to your view using the hook_views_query_alter hook in a custom module (documentation). Inside the module you should add something like the following:

function your_module_views_query_alter(&$view, &$query) {
  if ( $view->current_display == '[display in question]'){
    $query->add_where_expression([group], [sub query]);
  }
}

documentation for $query->add_where_expression.  You can add whatever where clause you need using this function.

hook_views_query_alter should go in your_module.views.inc.  Make sure you declare hook_views_api in your_module.module, otherwise views wont know to look for the file. For example:

function your_module_views_api() { // declare your views api # here
  return array(
    'api' => 3,
  );
}


Views: Highlight today's post based on previously referenced node

From what I understand your page view only displays a single (the last one) weekly node that in turn displays the fields with references. If this assumption is correct, what you can do (and what I would do in this case) is to create a node--weekly.tpl.php file in your theme folder based on node.tpl.php. Here you will be able to get the current day of the week in PHP. Based on that, use render() to display the reference fields in the order you wish, while adding the required html and css classes to make the current day highlighted.

More information about theming individual content types can be found here: https://www.drupal.org/node/17565

I don't know what's your experience with theming, but if you need help with the actual template, let me know.

[later edit]
You can of course use a separate display suite template if you don't wish to override the general template of the weekly node. It's the same principle, but instead of having a node--weekly.tpl.php, you will have something like this: https://www.drupal.org/node/1098068 I think that the custom display suite layout involves a bit more work, but I may be wrong. Depending on your particular use case and how do you plan to display the "weekly" nodes across your website (e.g. if you will always have the same template or use multiple ways of displaying it), then you can choose one approach over the other. Both of them can help you accomplish what you need.


Simplenews logs out when sending test newsletter

I found out that the problem occurs when I use custom .tpl.php templates. I deleted the statistics module and .tpl.php files from my theme's folder. So, I am using the default .tpl.php files provided by Simplenews and it works.

Now, I need to figure out why I can't use custom template files.


Feature with Content Types is not reverted

Please check whether there are two copies mistakenly placed inside drupal modules. Just recreate the feature with a new name and a version number. Download new feature then disable current feature and remove module completely from source. Then make sure the feature is completely removed and not appearing in the module list. Then add new feature and see.


Form textfield on-click remove default values

What do you mean for "default value"? Do you need to save this value or just to use it as a placeholder?

In this case you can obtain the goal without javascript:

$form['Package']['FirstName'] = array(
  '#type' => 'textfield',
  '#maxlength'=> 255,
  '#required' => TRUE,
  '#attributes' => array(
    'placeholder' => t('First Name'),
  ),
);


How to cancel user accounts without e-mail confirmation?

Please use this code snippet it works for me

 function simple_pass_reset_form_user_cancel_form_alter(&$form, &$form_state, $form_id) {
  //  dsm($form);
  $form['actions']['submit']['#submit'][] = 'simple_pass_reset_user_cancel_form_submit';
}

function simple_pass_reset_user_cancel_form_submit(&$form, &$form_state) {
  $uid = $form['uid']['#value'];
  // exit;
  $user = \Drupal::currentUser();
  if (!$user->hasPermission('administer users') && $uid == $user->id()) {
    // Hide "A confirmation request to cancel your account has been sent to your email address."
    $messages = drupal_get_messages('status', FALSE);
    if (!empty($messages['status'])) {
      unset($_SESSION['messages']['status']);
    }

    // Cancel the account, from user_cancel_confirm()
    user_cancel($form_state->getValues(), $uid, $form_state->getValue('user_cancel_method'));

    // Since user_cancel() is not invoked via Form API, batch processing needs
    // to be invoked manually and will redirect to the front page after
    // completion.
//You need to run batch process
    $batch = &batch_get();
    $batch['progressive'] = FALSE;
    batch_process('');
  }
}


Stop caching for a specific node type Drupal 7

See if http://drupal.org/project/cacheexclude can do it for you. If not you need to create a module that will implement hook_init. Inside of that hook you need to load the node from arg() from there see if the node is of a certian type; if it is disable the page cache.

<?php
  // Get the current active node object if present.
  $node = menu_get_object();
  if (!empty($node) && !empty($node->type) && $node->type == 'page') {
    drupal_page_is_cacheable(FALSE);
  }
?>


How to render an entire page from external php page?

drupal_deliver_html_page() is never called directly; you should eventually call drupal_deliver_page(). It also seem you are calling the function with the wrong argument, since drupal_deliver_html_page() doesn't get a path as argument, but the result obtained by a page callback.

The correct code would be the following one.

define('DRUPAL_ROOT', '/home/quickstart/websites/custom.dev');

require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
menu_execute_active_handler('user');

Since that is just the index.php code just slightly modified, I don't see any reason not to use http://example.com/user directly. A custom PHP file like that should be used to perform specific tasks, like in the case of cron.php.

define('DRUPAL_ROOT', getcwd());

include_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

if (!isset($_GET['cron_key']) || variable_get('cron_key', 'drupal') != $_GET['cron_key']) {
  watchdog('cron', 'Cron could not run because an invalid key was used.', array(), WATCHDOG_NOTICE);
  drupal_access_denied();
}
elseif (variable_get('maintenance_mode', 0)) {
  watchdog('cron', 'Cron could not run because the site is in maintenance mode.', array(), WATCHDOG_NOTICE);
  drupal_access_denied();
}
else {
  drupal_cron_run();
}

Normally, you don't need to use a similar file, and you should handle it through a normal menu callback; this even more true when you need to just shown a specific page as you are doing.

Keep in mind that Drupal 8 doesn't use anymore the cron.php file; cron tasks are handled through a menu callback too.


How do I restrict uploaded images to a specific aspect ratio?

My advice would be to implement a custom file validator.

To see how these are used when saving files, you can check out file_save_upload. For an example implementation that is very close to what you want to achieve, check out file_validate_image_resolution.

My super quick attempt at this

/**
 * Validates an image upload as having a particular aspect ratio
 *
 * @param $file
 *   - the uploaded file
 * @param $aspect_ratio
 *   - the apect ratio in the format [WIDTH]:[HEIGHT]. E.g. '3:2'
 */
function file_validate_image_aspect(stdClass $file, $aspect_ratio = 0) {
  $errors = array();

  // Check first that the file is an image.
  if ($info = image_get_info($file->uri)) {
    if ($aspect_ratio) {
      // Check that it is smaller than the given dimensions.
      list($width, $height) = explode(':', $aspect_ratio);
      if ($width * $info['height'] != $height * $info['width']) {
        $errors[] = t('The image is the wrong aspect ratio; the aspect ratio needed is %ratio.', array('%ratio' => $aspect_ratio));
      }
    }
  }

  return $errors;
}


How to change link to a node's path in Views conditionally

You could add a blog_url field which you hide in a form alter and  programmatically set when the form is submitted. If the blog is remote, you set it to the value of the link field. If it's local, you set it to the value of the node. You can then use this field in Views (just include the Title field and use 'Link this field' to link it to the value of blog_url). Something along the lines of:

/**
 * Implements hook_form_alter().
 */
function mymodule_form_alter(&$form, $form_state, $form_id) {
  if ($form_id == 'school_blog_node_form') {
    $form['field_blog_url']['#access'] = FALSE;
    $form['#validate'][] = 'mymodule_validate_school_blog_form';
  }
}

/**
 * Validate handler for school_blog edit form.
 */
function mymodule_validate_school_blog_form($form, &$form_state) {
  if ($form_state['values']['field_blog_is_hosted'] == 'local') {
    $form_state['values']['field_blog_url'] = 'node/' . $form['nid'];
  }
  else {
    $form_state['values']['field_blog_url'] = $form_state['values']['field_blog_remote_url'];
  }
}


Possible to add a organic group role programmatically?

It seems that hook_og_default_roles() will only assign the role to new group members. The role must first exist in the roles table. You can do this by creating it in the OG UI or by using og_role_create() and og_role_save () as above.


Add unlimited field collections in a from of drupal

This is a working code that can be placed directly into your form function. Please see the comments too.

$node = new stdClass();
// Replace the value to the content type's machine name where you have added
// the field collection field
$node->type = 'CONTENT_TYPE';

// Prepare the field collection display array
$form['field_collection_display'] = array();

// Get the field collection field's info/structure and return it to the given variable
// w/c in our case is $form['field_collection_display']
field_attach_form('node', $node, $form['field_collection_display'], $form_state, NULL, array(
  'field_name' => 'FIELD_COLLECTION_FIELD_NAME'
));

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

return $form;

For the "Add another item" display, when you go the the field collection's content manage field settings page it says that the button will only display when it's set to 'Unlimited' w/c isn't your requirement. So you would need to add custom validations to this.

Since this is also custom coding, if you're having a hard time manipulating the field I would also recommend looking at doing the "field collection" functionality by yourself. This is the link https://api.drupal.org/api/examples/form_example!form_example.module/group/form_example/7. You could go to the form_example_tutorial_9 directly if you want.


Use a twig template instead of a render array in a custom module admin page

The back-end theme automatically switches by path. So if your route's path begins with /admin it will show the page in the admin theme.

MYMODULE.MYPAGE:
  path: '/admin/config/MYPAGE'
  defaults:
    _form: '\Drupal\MYMODULE\Form\MYFORM'
    _title: 'MYTITLE'
  requirements:
    _permission: 'administer site configuration'

To render a form inside your own template you could simply register a new theme implementation inside MYMODULE/MYMODULE.module.

/**
 * Implements hook_theme().
 */
function MYMODULE_theme($existing, $type, $theme, $path) {

  return [
    'MYNAME' => [
      'render element' => 'form',
      'template'       => 'MYTEMPLATE',
    ],
  ];
}

And in the form you set this as the form's #theme.

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

And in the MYMODULE/templates/MYTEMPLATE.html.tiwg template you print it like so:

<div class="foo bar">
  {{ form }}
</div>

Any additional library also can simply be #attached directly to the form.

$form['#attached']['library'][] = 'MYMODULE/MYLIBRARY';

Read More

[drupal.org] Create custom twig templates for custom module.


Placing a drupal menu on an external site

Yes, it is possible.
In your drupal website:

Render the main menu block on a custom made (module) page for example /main-menu-external
Strip all the sections but the content section, so that no header, footer, ... is rendered, only the menu.
With context load a blank theme on the page "main-menu-external"
At this point "main-menu-external" will be a blanco page with only the main menu rendered on it AND will use a different theme from the rest of your website so you can configure it for that page only.

In your /members website:

Just put an <iframe> with source "yourdrupalwebsite.be/main-menu-external"

Et voila, there is your drupal menu on an external website :)


imagecache_actions module implements this for D7 (brand new, in 7.x-1.x-dev only yet). It is based on a feature request for D8: #1403962. The dev version also implements a rudimentary export/import to copy between different systems (or the issue queue) without a need for features.


When does Views check node_access permissions?

Views adds the node_access tag to it's queries, which allows the implementation of hook_query_TAG_alter in the node module to intercept the query and the joins needed to respect node access grants.

The "Disable SQL re-writing" checkbox in the Query options under the advanced settings for the view can disable this behaviour.


In views, how can you link "read more" to the webform submission?

I believe the link should be node/%nid/submission/%sid/view.

Where %sid is the webform submission id.


How can I restrict a Flat Rate to a single product SKU?

It really depends on the context of the event. If that event is receiving an order by default, then your conditions either need to be based on the order (such as "Order contains a particular product") or you'd need to loop over commerce-order:commerce-line-items and evaluate line item based conditions via custom Rules components.

I'd give that condition I mention above a shot before trying anything more complicated, though.


How to translate menus that are made in views?

I would recommend you to not generate menu items with views. Just give it a path and create menu items manually which point to the appropriate path. If you need to have a speaking URL, create URL-Aliases for it in each language. This does the trick, usually.


You can use Views Reference module that will give you a cck to choose from selected views. This will use with each type of content.

For a same view in all content of content type you will need to create a template file node--type.tpl.php and paste your code to include the view.


Setting error text in Commerce Alter Form Module

I guess you can obtain the field value using this.

if ( $form_state['values']['field_i_have_read_and_i_agree_to'] == 0 ) {
  //or use this in if statement $form_state['values']['customer_profile_billing']['field_i_have_read_and_i_agree_to']

      form_set_error('field_i_have_read_and_i_agree_to', t('You forgot to check the required checkbox.Please try again.'));
    }

You shouldn't include ['customer_profile_billing'] unless you have set the #tree to TRUE.


can we use one argument for two contextual filters

You should be able to set "WHEN THE FILTER VALUE IS NOT AVAILABLE" on the contextual filter to "Provide Default Value" and set "Type" to "Raw value from URL" and set the Path component, in case of example provided in your question, Path component 0 is location-map and Path component 1 is region-or-type-field-here


You may try to use Get JWT on Login module that I have created for the same purpose.


How to use Rules for sending an email to all users with same field value in some select list?

Without knowing anything about your entity & field setup I can't give you an exact rules that will work however it is possible and I can give you a pseudo rule:

Install the rules bonus pack module.
Install the rules conditional module (I think you need this but I'm not actually looking at a site to confirm).
Create a view that lists all users with a contextual filter of the state field. - So when you call the view with a specific state you get all users who have selected that state.
Event: Before user profile is saved.
Action: Rules bonus pack action "Load a user list with Views". Use the user email list view from earlier and pass in the value of the state from the new user object (from after the edit).
Action: Loop through the user list you loaded from the view.
Action: In the user list loop send an email to the loop user object.

This will also send an email to the user who is actually changing their profile. if you want to exclude them you can either add more conditions in the rule to check against the edited user object or you can add another contextual filter to the view for uid, check the box in that contextual field to exclude that user from the results and then also pass in the uid as a contextual filter in the rule.

I would do that latter because it is a less complex rule and I would assume it would use less resources to run.


You can use hook_page_alter() to do this. For example, if you wanted to remove the system navigation block from the "sidebar_first" region, you would do something like this:

function MYMODULE_page_alter(&$page) {
  if ($my_condition) {
    $region_name = 'sidebar_first';
    $block_name = 'system_navigation';

    if (isset($page[$region_name][$block_name])) {
      $page[$region_name][$block_name]['#access'] = FALSE;
    }
  }
}


Setting a Warning message in the Page.tpl.php file

If you want to use Drupal's message system, and you want to do this at the theme-level, as opposed to writing a module, you would enter the code

drupal_set_message(t('Don\'t panic!'), 'warning');

into your theme's template.php file as a preprocess function.  For instance, if you wanted to display this message on all content of the type 'page'

function YOURTHEME_preprocess_node(&$variables) {
 if ($variables['node']->type = 'page') {
  drupal_set_message(t('Don\'t panic!'), 'warning');
 }
}

It should then automatically show up in the $messages area whenever someone visits a 'page' content type.

Note: You might also need to flush your theme cache after making these changes.


There isn't, but since users are entities, and taxonomy term references are fields, you can use an EntityFieldQuery to get this data. You could even wrap it in a function to make your life very easy:

function taxonomy_select_users($term_id) {
  $query = new EntityFieldQuery;
  $query->entityCondition('entity_type', 'user')
    ->fieldCondition('field_taxonomy_term_field', 'tid', $term_id);

  $results = $query->execute();

  if (isset($results['user'])) {
    return user_load_multiple(array_keys($results['user']));
  }

  return FALSE;
}


Reload only the content area of a website while the sidebars remain static

Yes, it's possible to update the content area without updating the sidebars using Ajax or Ahah. There are multiple modules for implementing ajax functionality in various parts of Drupal:

Views Load More
Ajax pages
Views
jQuery AJAX Load
etc.

It will depend on the specific requirements of your site and its content as to which method would make the most sense.

Besides Ajax modules, another more advanced option is an idea often referred to as "Headless Drupal" in which you use Drupal as a backend in conjunction with a dynamic front-end framework like Angular or Backbone.

If you're just getting started with Drupal though, I would encourage you to get a bit of experience building simple Drupal sites before getting too focused on Ajax functionality. If you're not already familiar with Javascript, you'll likely end up being somewhat limited in terms of what you can do with the out-of-the-box functionality available from community contributed modules.


Installing and Running Drupal in Subfolder - Beginner

I have read "How to get Drupal 7 installed in a sub-folder / sub-directory properly?" already - i'm having a difficult time deciphering what steps to take from this post.

Your problem is not a Drupal problem. It is a file permissions problem. It is probably caused by you using ftp to create the sub-direactory to hold Drupal.

  but im only getting 404/page not found error messages when i navigate to this URL.

This means that the the directory you've created with ftp, and/or the files you've uploaded in that directory is not readable by the webserver user.

If you have access to the command line interface (CLI), you may need to use chown to make sure the Drupal directory and files are owned by the webserver user, or at least use chmod to make sure they're readable by the webserver user.

However, since you use ftp, I assume that you have not CLI access to your installation? In that case, you need to contact customer support at your hosting provider to learn what tools exist to change the read permissions of files and directories to be readable by the webserver user.

  this post lost me at " I already modified the .htaccess in the parent drupal installation to ignore the sub-folder and i also set the $base_url in the sub-directory drupal installation."

That is just noise in the question.  You need to read the upvoted answer to that question for the solution.

In fact, you should ignore all the stuff about modifying .htaccess in the duplicate issue.  I am no idea why the person who wrote it believes this is relevant. Each Drupal installation has its own .htaccess in its own directory, and the one that comes with Drupal is fine provided you do a clean install. The simple fact is that there is nothing special about installing Drupal in a subfolder.  You need to get the directory and file permissions correct tho' - and using ftp to set things up may have caused the permissions to be wrong.


How can I make an order generated through Services invoke hooks or checkout complete?

So, for anyone looking for a solution, here is what I did after asking for help in IRC #drupal-commerce:

Don't use the order status, don't use a checkout-status. Use something (an entity) as a trigger that is necessary for creating the order. I picked the last action provided via .json-file, POSTing a line-item. As soon as this is known by Drupal, all corresponding rules start their work, and some hooks respectively.

Sidenote: I learned something else also and wished to have been pointed to that earlier: Next time I will not use the above mentioned modules again. They're buggy and obsolete in D8 anyway since the concurring RESTws module became part of core.


The Cache-Control header which mod_expires sets tells the browser when a set of cached content should expire and be redownloaded. If you are interested in learning more about how that header works, read http://blog.httpwatch.com/2007/12/10/two-simple-rules-for-http-caching/ it explains it really well. Browsers do not ignore this setting. But if you "shift reload" or do something which forces the browser to ignore the cache and redownload anyways you'll ignore it.

A common approach for this is to implement a timestamp based update for CSS/JS. For example you have the following stylesheet link

<link rel="stylesheet" type="text/css" media="all" href="style.css">

You would append a last changes tag to it, something like

<link rel="stylesheet" type="text/css" media="all" href="style.css?c=20131001">

and then you can just auto increment this every time you change the css. This will force ALL browsers to redownload, but won't destroy the cache benefits.


How to transfer Userpoints between users?

Module Userpoints Donation has to be used.


CKEditor automatically making new paragraphs

Out of the box, the CKEditor configuration does a <p> on enter and a <br> on shift + enter.

If you wish to change this, you can visit admin/settings/ckeditor/edit/[profile], and scroll down to the "Cleanup and output" section.


How to customize the admin toolbar in Drupal 7?

Take a look at the Quickbar module.This is a simple administration toolbar. It allows you to take any menu and assign it to a role. This menu will be displayed at the top of your page as an administration toolbar.

You could also look at the Manager module. It includes the Manager's Bar. An admin-bar designed for users that aren't familiar with Drupal. It is like the default "Navigation" menu, when we cut off everything that doesn't matter to this users, and it looks like some known admin-bar-modules, like Admin Menu, but a lot more simple.


Missing filter and sort criteria from views

I was running through that tutorial the other day too...

You need to add a relationship to the user (in the "Advanced" fieldset of your View), then the User: filters will appear.

I think the Field:... criteria are now called Content:....

I got the tutorial content working fine in quite a short space of time and if memory serves these are the only things that were different from what was stated in the video. The video uses a beta/RC version of views whereas it's now in full release, so there will be a few differences.


Try this code. I'm using it with backup and migrate module

$module = 'backup_migrate';
$key = microtime();
$language = language_default();
$params = array();
$params['attachments'][] = array(
  'filepath' => $attachment->path,
  'filecontent' => 'My attachment.',
  'filename' => $attachment->filename,
  'filemime' => 'text/plain',
);

$from = $mail->from;

$send = FALSE;
$message = drupal_mail($module, $key, $to, $language, $params, $from, $send);

$message['subject'] = t('Database backup from !site: !file', array('!site' => variable_get('site_name', 'drupal'), '!file' => $attachment->filename));
$message['body'] = t('Database backup attached.') ."\n\n";

// Retrieve the responsible implementation for this message.
$system = drupal_mail_system($module, $key);

// Format the message body.
$message = $system->format($message);

// Send e-mail.
$message['result'] = $system->mail($message);


how to add color field after Commerce Fancy Attributes has been installed?

You should create a simple "text field".


How to: Multilingual site with one front page that makes user choose a language first

You can create a custom block to display the language enable into site and a link to respective page of particular language.

To display the custom block in home page, you can use panels, create different template for the home page (page--front.tpl.php).


Why does drupal_set_message function encode all html tags?

The messages added with drupal_set_message() are rendered in the page.tpl.php template file of the theme, if the file it is using one; otherwise, they are rendered through the template file defined from the System module.

By default, the System module and the core themes use the following code to print them.

<?php print $messages; ?>

There could be some HTML markup to wrap them, as in the Bartik theme, but that should not have the effect you are seeing.

  <?php if ($messages): ?>

      <?php print $messages; ?>

  <?php endif; ?>

The way those messages are printed has not been changed from recent updates to Drupal core, so I would check the used theme and any installed (and enabled) modules to find out what is happening.

Apart from looking the page.tpl.php template file used from your theme, you should check the implementation of theme_status_messages() (which is normally called from template_preprocess_page()) done from the theme you are using, any preprocess function for theme_status_messages() (hook_preprocess_status_messages()), and any preprocess function used for the page.tpl.php template file (hook_preprocess_page()). Keep in mind that preprocess functions can be implemented by any module, or the theme used for the rendered page.

As side note, it is usually better to use t() and its placeholders, with drupal_set_message().

drupal_set_message(t("!important. This not.", array('!important' => 'This is important')));

If you don't need to translate the message (e.g. because it is a debugging message), you could use [format_string()][5].

drupal_set_message(format_string("!important. This not.", array('!important' => 'This is important')));


Display Count of associated nodes as "more" in Calendar View?

In your calendar view you can select format>Settings: Too many items to "Hide all add link to day" and it will show the totals for that day.


Programatically accessing block settings

Sure, block_load gives you the contents of the whole row from the block table:

$block = block_load('module', 'delta');

$region = $block->region;
$weight = $block->weight;
$custom = $block->custom;
$visibility = $block->visibility;
$pages = $block->pages;
$title = $block->title;

And so on.


Get default min and max default values in views exposed filter form element

function MYTHEME_preprocess_input(&$variables) {
  if (isset($variables['element']['#default_value'])){
    $variables['attributes']['data-default-value'] = $variables['element']['#default_value'];
  }
}


How to remove Upload picture lable from registration page?

Something similar to this should work. Use form id alter hook to remove the label from image field.

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

 // Search for the field you want to alter

 // unset the label using $form['search_image_field_name'] or remove the label using empty string for that form field.
}


How to determine if loading a form or submitting a form in hook_form_alter?

When there is no user input the form is loading for the first time and it is not submitting.

Additionally you can check the entity whether it is new, if you don't want this condition to be true when the form is loading for an existing node:

if (!$form_state->getUserInput() && $form_state->getFormObject()->getEntity()->isNew()) {
  // first load of the form
}


Node edit form with embedded form not executing custom submit handler

I came across https://www.drupal.org/forum/support/module-development-and-code-questions/2015-09-03/put-a-custom-form-inside-node-form which, while old, claims that what I wanted to do is not possible. To get this to function the way I wanted I:

Attached a JS event handler to the embedded form submit buttons that performed .preventDefault()
This handler then .ajax'd a custom route that I created.
In the Controller for that route, I had to perform all the primary operations for submitting the form and return markup back to the .ajax call.


If you are using Stable like theme you can see that the field is wrapped around a div tag.
You can rewrite field.html.twig with your theme suggestions and edit the markup.


What's the usage difference between element_validate and validate hook?

@Haider Ali with #element_validate, we can add our own custom validation functions to a field or we can pass the validation functions provided by Drupal, e.g., element_validate_integer_positive(), element_validate_number(), etc.

This #element_validate works only on the field we added it to.

When we want to add custom validation to multiple fields, we add it in form validate hook, so that we do not need to add separate function to each field and call multiple validate functions.


Drupal views override stopped working for no reason

I have not experienced this, but have a theory.  The default views that come with the module can be restored to their original condition so your problem may relate to the "special' nature of these views.  Try cloning the view and making your modifications to the clone.


You will be best using hook_form_alter().

You can edit the registration form & user edit form and change the type in a custom module.

function register_form_alter(&$form, &$form_state, $form_id) {
  if ( $form_id= 'user_register_form') {
    $form['user-register-form']['roles'] = array(
      '#type' => 'radios'
      // …
    );
  }
}


Where is the group of a fields group stored in datababase (to get it programatically)?

I have never used field_group module, but your approach seems wrong, looking in the database doesn't help often.
I suggest you should install the module devel, turn it on.
Then use the function dsm() to see the content of your node/form that you are in.
If I assume you are in the hook_form_submit() to process something, dsm($form_state), if you are in another hook with a node as parameter of your hook, just dsm($node), you might find what you are looking for.

Cheers


How to allow users to rotate a picture upon upload?

I've been fighting this issue for some hours now and have something that seems to work for me. It's not extensively tested yet, though.

My setup:

ImageMagick instead of GD as Image Toolkit (because GD strips EXIF data)
Imagecache Autorotate, part of [Imagecache Actions](Imagecache Autorotate) that provides an Image Action that automatically rotates pictures according to their EXIF orientation
EPSA Crop module: EPSA crop was the only cropping module that allowed me to use its after the Autorotate action in my image style preset (I tried at least with manualcrop, imagefield_crop, simplecrop)

In my image style I use the following actions:

Autorotate Autorotate image based on its EXIF data
EPSA Image Crop, 150x150 (with Aspect Ratio of one, as the resulting image has a square AR)
Scale and Crop, 150x150, scale and crop it even if it wasn't manually cropped.

Only drawback so far:
EPSA Crop doesn't show you the cropped image on the thumbnail of the edit page, so users might be confused if their cropping was successful after all.

Hope this helps others saving some hours of research.


How do I find or set the apropriate form for base scheme fields?

You can always create a field with the desired settings in the field, widget and formatter settings in the UI. Then export the configuratio and use the settings from there. The field settings are in two files:

field.storage.entity_type.yourname.yml
field.field.entity_type.bundle.yourname.yml

For base fields, you can merge the settings together into a single array.


limit access to some configuration pages (manage display and manage fields)

I would probably go into one of my custom modules and:

invoke a hook_permission() with my new needed permission (administer display and fields) that will be granted only to admin.

Then invoke hook_menu_alter() to alter the access control on the menu path the taxonomy module creates.

This way on install admin will be granted automatically the permission and only the roles granted this permission will be able to access that page.


Remove status messages from content output?

at /admin/structure/block, you can find the block "Status Messages" and move it to the "- None-" region, or another region of your choosing.


This worked for me. Incase there was no translation node, I send the user to the homepage.

$tpath = translation_path_get_translations($_GET['q']);
if ($language->language == 'en') {
    if (array_key_exists('fr', $tpath)) {
        $tlink = "Français";
    } else {
        $tlink = "Français";
    }
} else {
    if (array_key_exists('en', $tpath)) {
        $tlink = "English";
    } else {
        $tlink = "English";
    }
}

print $tlink;


How to import node view count with Feeds and Statistics module?

This isn't currently a feature of the feeds module. You could write a module that implements hook_feeds_after_save() to create the needed database records.


General Approach in Zen-Theming: 3 different fixed-width layouts based on viewport-size

Zen 5 has mobile/responsive built-in, and it works really well. I found the conversion from Zen 3 fixed to Zen 5-Responsive fairly easy, and I went with the dev version (Jan 2013). As suggested, you could take out all the sidebars, but they don't really get in the way.

I had to spend some time learning responsive images, in particular responsive background images.


How to use kpr() or dsm() when i am not logged in

You need to grant the Access developer information permission to the anonymous user role.

Be sure to revoke it again before releasing the site, it's an easy way to leak sensitive information.


Why is the Pressflow Last-Modified header not like plain Drupal?

Drupal 6 sets the Last-Modified header with

header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");

That was changed to

$default_headers = array(
  'Expires' => 'Sun, 19 Nov 1978 05:00:00 GMT',
  'Last-Modified' => gmdate(DATE_RFC1123, REQUEST_TIME),

during the development of drupal7. Pressflow has backported the patch from drupal7 in 2009. That's the reason of the difference. As for the possible impact of this, in fact it can have bad effects on caching. At least squid 3.1.10 prints a warning about the header and refuses to store the page in cache

cannot parse hdr field: 'Last-Modified: Tue, 12 Feb 2013 14:35:43 +0000'
[snip]...[/snip]
refreshIsCachable() returned non-cacheable..

Switching to the "GMT" version resolves the issue with squid.

rfc2616 (HTTP/1.1: Protocol Parameters:) specifies that "Last-Modified" header value can conform to rfc1123 (which looks OK with +0000) but all the examples use "GMT".

I think it'll be better to create a bug report in drupal issue tracker and see what the developers answer.


Managing large volume of content in tree hierarchy

Good strategy is to utilize Workbench and create sections from your menu.

So you would have your main menu, lets say 3-4 levels deep and mimic those in Taxonomy. Its easier to create taxonomy first as there is a module that will create menu from taxonomy.

So you create your taxonomy that has your structure going 3-4 levels deep. Then create a menu from it.

Install Workbench and Workbench Access and Moderation modules.

Configure Access to use Taxonomy for section assignment and then configure URL parameters to pull from Taxonomy as this will take care of your URL and breadcrumbs. Use Custom Breadcrumb module to generate breadcrumbs if you need them.

Then on each content type add a new filed for Sections which will pull from your taxonomy. So when adding content you select where in the tree it should live.

For example you are adding "Help" node which needs to live in About Us > Services  and About Us and Services are in the menu. Help does not need to be in menu but needs to follow the About Us > Services > Help path.

By using Workbench modules you can easily achieve that. In a sense your taxonomy acts as buckets into which content is placed. This drives URL, Breadcrumbs as well as left or right nav menu if you need one using Menu Block.

So to summarize the steps:

Create taxonomy of the items you want to be in menu.
Create menu from taxonomy using Taxonomy 2 Menu module.
Install Workbench suite of modules.
Configure workbench access to pull from Taxonomy.
Adjust content types to add a fields for Taxonomy selection, make it only 1 as you don't want multiple paths for nodes.
Configure URL Patterns to pull from taxonomy parents.
Install and configure Custom Breadcrumbs to also use URL path.
Install and configure Menu Block to use URL path.
Start adding content and assigning sections.

Additional benefits of this approach is that you can also restrict which roles or users can edit content in each section so you can have HR only have access to edit content in their part of the site.


How to link migrated image file to the user profile picture field?

Thanks a lot @MrD I tested using the migration_lookup plugin and it works like a charm:

  user_picture:
    -
      plugin: default_value
      source: picture
      default_value: null
    -
      plugin: migration_lookup
      migration: drupal7_image


How send a node as a newsletter by rules in Drupal 7?

I will only provide some pointers as it would take me an hour or more to write out the steps.

It would be best to use Rules scheduler, rather than a views loop to
send this info. Every cron run you don't want to have to loop
through all of your node to check to see if one needs to be sent.
Enable Rules Scheduler.
Create a Rules component with an action of send email. This will
contain all of the email structure including your field tokens for
your node. The to field will be all users of role "INSERT YOUR
ROLE".
Then create a rule to schedule that component when a node is saved.
Use condition "entity has field" to pull your "trigger field" into
scope. Then add a second condition, "Data comparison" or "data is
empty" (negate if needed as I do not know what type of field your
going to trigger this off of).
Set the schedule time to be the current date. Rules scheduler only
happens on cron anyway, so this will ensure the next cron run it
will send.

Note: Rules and more specifically core does not support html emails out of the box, so use something like mime mail, Html mail or mandrill module to do this. If your nodes contain images that need to be sent, then you are going to need to add a special filter for those fields so that add your site root is added to all images and links. This way it doesn't use relative paths and break your images/links. Use the Pathologic module to do this.


Without Code:

To adjust views to show/hide author content...

under Advanced Tab create a Relationship, Content:Author, Require this field
create a new Filter, User:Current, Relationship Author(or whatever name you gave the relationship), Is the logged in user -> No

This will compare the author of the content to the currently logged in user and only show the content if they don't match. This method can be used to show only content by the current user by changing the 'Is the logged in user' -> Yes


This is something that Views does when a particular field is used in more than one Entity type. In your case, the "Abbreviation" field is used both by node entities (the "Content" views group) and by taxonomy term entities.

It represents the field in both the "Content" and the "Taxonomy Term" group, so that if you were filtering the list by group, you wouldn't be missing it in the list.  But it also represents itself canonically in the "Field" group, to correctly inform the user that the field is available in multiple entity type contexts. This would be important knowledge if you had both entity types available in your View because of a relationship.


display a taxonomy terms as autocomplete using form API

Hope this will help you,

In Drupal 7, it can be done in 2 ways

By using existing taxonomy field(like TAG field), for this example I'm using field_tag

$node=node_load($nid);
$tags = array();
foreach ($node->field_tags['und'] as $item) {
  $tags[$item['tid']] = isset($item['taxonomy_term']) ? $item['taxonomy_term'] : taxonomy_term_load($item['tid']);
}
$form['tags'] = array(
  '#type' => 'textfield',
  '#default_value' => taxonomy_implode_tags($tags),
  '#title' => 'Add Tags',
  '#autocomplete_path' => 'taxonomy/autocomplete/field_tags',
  '#maxlength' => 1024,
  '#element_validate' => array('taxonomy_autocomplete_validate'),page
);

If you dont want to use any field then it can also be using custom autocomplete

//custom field
$form['taxonomy_term_field'] = array(
  '#type' => 'textfield',
  '#autocomplete_path' => 'get_TAXONOMY_NAME/autocomplete',
);
//menu callback for autocomplete
function HOOK_menu() {
  $items = array();
  ....
  $items['get_TAXONOMY_NAME/autocomplete/%'] = array(
    'page callback' => 'TAXONOMY_NAME_autocomplete_callback',
    'page arguments' => array(2),
    'type' => MENU_CALLBACK,
  );
  return $items;
}
//autocomplete callback function
function TAXONOMY_NAME_autocomplete_callback($str = 0) {
  $matches = array();
  //vocabulary id
  $vid = 2;
  $result = db_select('taxonomy_term_data', 't')
    -> fields('t', array('tid', 'name'))
    -> condition('vid', $vid, '=')
    -> condition('name', $str.'%%', 'LIKE')
    -> range(0, 10)
    -> execute();
  foreach ($result as $term) {
    $matches[$term -> tid] = check_plain($term -> name);
  }
  drupal_json_output($matches);
}

References : Existing taxonomy field and Custom autocomplete field


Taxonomy term title as page title in custom view

You can use the argument added into the filter and there will be option to override the title, there  you can pass %1 which will automatically replace the title with the Taxonomy term title.


Custom Validation while adding a term under taxonomy

In Drupal 7, if you go through hook_form_alter.

It uses $form as a reference. You need to use & before $form.

/**
 * Implements hook_form_alter
 */
function hook_form_alter(&$form, &$form_state, $form_id) {
  switch ($form_id) {
    case 'taxonomy_form_term':
      $form['#validate'][] = 'mymodule_taxonomy_form_custom_validate';
      break;
  }
}
/**
 * Implements hook_form_validate
 */
function hook_taxonomy_form_custom_validate($form, &$form_state) {
  //validation goes here
}

Let say if your module name is lms2_validate then use:

function lms2_validate_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'taxonomy_form_term') {
    $form['#validate'][] = 'lms2_validate_term_validate';
  }
}

function lms2_validate_term_validate($form, &$form_state) {
  drupal_set_message('hello');
}


The module relies on the PHPMailer class to send HTML mail.  So to send HTML e-mails using Messaging you first need to install PHPMailer.

Check the README.txt file at /messaging/messaging_phpmailer/ for PHPMailer installation instructions.


How to hide published content to anonymous user programmatically?

By default, Drupals permission system does not support specific view permissions by content types. You will need a module for that. Have a look at Controlling Access to Content Overview. In Drupal 6 projects I have used Taxonomy access control lite quite offen.


Ajax Callback to Update Select List not Working

just got this sorted out! Decided to drill down to the array structure of the form, and found out that the #ajax element had to be attached to the widget array of the field, like this...
$form['product_line']['widget']['#ajax'] = [...]
Now it works. Another reason I keep crying "better documentation for Drupal"!!! How in the world was anybody supposed to know that for existing form fields, this was the format for adding Ajax?!!! Oh well, thanks community  for pointing in the right direction. Anybody knows the right place to insert this in the existing documentation? Cheers all.


How to change the "vid" in a field content_taxonomy

In fact, it is quite simple.

First, change in the type of content vocabulary.

Then you need is to add features and the fields in the .info module configuration managing content type.

Then just make a pretty:

drush fu my_feature

and then we have a taxonomy fields changed continuously integration.


Is there a way to add a timestamp to messages print from drupal_set_message()?

The problem is that at the point where these hooks are being used you have SESSION and FORM available and what you're asking for is a NODE attribute.

This can be done, simply loading the given NODE under the right conditions... but one should recognize doing this does have broader impact as these hooks are called fairly frequently.

How node_load is done is accomplished very differently in D7 and D8, not sure which one you're using from the question.  Lots of answers out there how to render fields from a node.  One more tip; your D7 install should have entity - the future proof method of getting node values is probably entity_load as nodes are entities in late D7 and all of D8...


Count the number of results of a free text field if they are similar

I'd use taxonomy terms and the tagging feature built into drupal. There's an example of it on the Article content type that comes with drupal's standard install

So a user can start typing a term and the autocomplete will appear if that term already exists. The user can select it if it exists already. Otherwise when the node is saved the term will be created. You can select multiple terms by comma separating them exactly as you mentioned

Then getting a count of terms will be much more straight forward and should be do-able in views as each time a term is associated to a field it's stored in the database


Webforms - '[+] Add more fields' (up to 5) button to file upload form control

Have you checked this Webform Add module ?

  Webform Add More enables selected fieldsets to be initially hidden and
  progressively shown with an Add more button, mimicking CCK multiple
  fields.


Assuming what you want to do is :

Make a content type which authenticated user can add by themselves called barandrestaurant.
Make a view displaying all the barandrestaurant content-type.

First creat a new content type called barandrestaurant :

You should unchecked the "promote to front page" in the content type page :

Allow user to add your content type in admin/people/permission --> find your content type node name (barandrestaurant) and allow authenticated user to create new content.

Second make a view page filtering your content type barandrestaurant

Go to admin/structure/views/add a new view and fill the form to filter on your content type like that :
Specifiy that what you want is a view page and that you want to add a menu link in navigation menu :
Add in the header or in the footer (as you want) a "global text area" with a html link to create new barandrestaurant content type page :

Add a new bar or restaurant

This should look like this :

Now you should have a content type called barandrestaurant which can be created by your authenticated users visiting the link http://www.yoursite.com/bar-and-restaurant. The link should be in your navigation menu too.


How do I split a contact form into multiple pages?

You can use the Field Group module. This works for Drupal 7 and 8.

If you use Drush you can use the following command line.

drush dl field_group

drush en -y field_group


Is there any procedure to exclude taxonomy vocabulary terms from views display


Those kinds of aliases cannot be achieved by path auto, because as far as I know, it is difficult to add tokens into the menu settings. To help with this in the past, I have used the Me Alias module.


OK, if you did it with code you probably edited settings.php and did something like:

$conf['locale_custom_strings_en'][''] = array(
  'Read More' => 'More information',
);

You would have to remove that line from the array.

There are a billion ways to do it via code, though, To be safe, you should search for the string "More Information" in all of the sites/ files to be safe.

If you didn't do it with code, there is a decent chance you used the String Overrides module, and did it via the UI.  If so, delete that entry.

If this is related to a view, then you should poke through the settings for that view (don't forget the master and all additional displays).  Look for a link field, and check the "Text to display" option.

If not, poke around the field settings for your content types, eg admin/structure/types/manage/page/fields, and see if you set it there.


Adding Vue.js to my theme with Webpack not working

I recommend looking into the Decoupled Pages module which can make integrating Vue.js simpler.


Running cron without setting a cron job on web server

Yes indeed, Drupal exposes a URL to invoke cron, e.g.

http://www.example./com/cron.php?cron_key=ka_88ikb7ZbkszCQo6_GtZclwUsUsskfH54oOJqqBcE

Which you can call from anywhere, using whatever method you like (pingdom jumps to mind, for example). Obviously if your site is an intranet or something you'll need to work out how to route that request either from the internal or external network, but Drupal has you covered however you decide/need to do it.

You can find your external cron URL by visiting the status report at /admin/reports/status.

Note that if you have an advanced cron module like Elysia cron, your external URL may be different. Check the documentation for the specific module to be sure.


Disable image autoscale when dimensions are bigger than my settings

You don't want to return the message "your image is too big" as people nowadays are uploading directly from their mobile phones and do not have (or know) a way of resizing/cropping themselves before uploading.

So you should try it via another way: do not impose restrictions on the original image, but use an image style to display the uploaded images and add some smart/user/custom crop effect to that image style. There are a number of modules that let users/editors custom crop images, e.g:

Imagefield crop
Manual Crop
Smart Crop
...

Also see Comparison of image cropping and resizing modules.


Broken formatting while displaying both start and end date

Juts found a solution. Please create custom formatting like this:

D, F d, Y (h:ia)

Key here is to wrap time in parentheses

  (h:ia)

after that trick formatting is fixed and looks something like:

  Sat, September 21, 2013 (All day) to Mon, September 30, 2013 (All day)


If you give a permission to the Authenticated User role, you grant that permission to all other logged-in roles. It works like this because all logged-in users get that role.

However, as long as you don't grant a permission specifically to the Authenticated User role, you can pick and choose which individual logged-in roles to give the permission to. Then you can also give the permission to the Anonymous User role.


Page redirect in custom WebformHandlerBase

<?php
namespace Drupal\sa_webform\Plugin\WebformHandler;

use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Serialization\Yaml;
use Drupal\Core\Form\FormStateInterface;
use Drupal\webform\Plugin\WebformHandlerBase;
use Drupal\webform\webformSubmissionInterface;

/**
 * Form submission handler.
 *
 * @WebformHandler(
 *   id = "my_webform_handler",
 *   label = @Translation("My webform handler"),
 *   category = @Translation("Webform Handler"),
 *   description = @Translation("Calculate the score with webform
 *                                                     submissions"),
 *   cardinality =
 *       \Drupal\webform\Plugin\WebformHandlerInterface::CARDINALITY_SINGLE,
 *   results =
 *    \Drupal\webform\Plugin\WebformHandlerInterface::RESULTS_PROCESSED,
 * )
 */

 class MyWebformHandler extends WebformHandlerBase {
 /**
  * {@inheritdoc}
  */
    public function submitForm(array &$form, FormStateInterface $form_state,
                           WebformSubmissionInterface $webform_submission) {

       $form_id = 'webform_submission_' . $webform_submission->getWebform()-
               >id() . '_form';
       if($form_id == 'webform_submission_xxx_form') {
         $values = $webform_submission->getData();
         /* Take the action based on the Webform submission values */
       }
    }

    public function confirmForm(array &$form, FormStateInterface
          $form_state, WebformSubmissionInterface $webform_submission) {
       $form_id = 'webform_submission_' . $webform_submission->getWebform()-
                                                  >id() . '_form';
       if($form_id == 'webform_submission_xxx_form')
       {
          if(based_on_some_condition) {
          /* Here 12 is the node id where i wanted to redirect to */
          $form_state->setRedirect('entity.node.canonical',['node' => 12]);
       }
    }
}
?>

For more examples refer webform modules src code located at webform\src\Plugin\WebformHandler

BrokenWebformHandler.php

DebugWebformHandler.php

EmailWebformHandler.php

RemotePostWebformHandler.php


Local install of live site looks different

Sounds like some CSS files are not loaded on the local site. Or some additional or other CSS files are loaded on the local site.
Clear caches
First thing to start troubleshooting the local site is to clear the caches. Not only CSS/JS caches but all caches.
If the site has the Advagg caching module installed, then sometimes it is not enough to clear its cache by clicking the Administration menu link. Advagg cache might also need to be cleared by clicking the Flush AdvAgg Cache button on this path:  /admin/config/development/performance/advagg/operations
If the above does not help then on the same Advagg page there are more buttons to click, hidden behind the headings containing 'Clear' and 'Delete'.
Look at CSS with Firebug
Firebug is an addon for Firefox. Instead of this you can also use the browsers built in inspector by pressing F12(maybe another key on Mac).
See what CSS is different and if the CSS is taken from different files on live site vs local site.
Panels Page layout
Having blocks on the right vs bottom could also be affected by Panels Page layout. Check for that if the blocks are still wrong after you got all other thematic right by getting all CSS right.


Is there a best practice for what to do with old broken links?

Redirect as much links as you can to existing pages using URL aliases.
Find out what pages are linking to your website on the old URLs, see if you can get them adjusted by contacting the webmaster (using a backlink indexing tool like Open Site Explorer or Majestic SEO).
For other links you have the HTTP 404 status code. Sometimes you just can't redirect the links...


How to use values from a referencing node (parent) in a referenced node (child)

Have you considered looking at how commerce kickstart solves this same issue?  Collections are taxonomy terms and Fabrics are products.


save views->execute result as a static variable

It heavily depends on what you're trying to achieve with caching.
If you're trying to avoid additional DB queries, you won't be adding much here. The view::execute() & view::render() are already making use of its own caching system (if it's enabled on the view in question).
If you're trying to avoid all the theme/module hook execution overhead, yeah that will avoid it. Of course, the trade-off is modules/themes won't be able to modify a view (if that's needed) and you'll have to handle other cache invalidation scenarios as a result of your custom caching.
You'll have to make the call depending on how/what you're trying to optimize it that's worth the trade-off (generally, I would say no but that's opinion).