How to print only certain block of content in a view

I would look at this as most a front-end styling problem. Basically, you need to add print-only style rules that hide all the page elements you don't need. You can do this via an inline media query:

<style>
@media print {
  /* @TODO: Add other selectors that remove page elements
  header, footer, .my-custom-class, #my-custom-id {
    display: none;
  }
}
</style>

Or a better, more portable, method is to just attach a custom print CSS stylesheet to whatever view that needs to be altered for printing:

drupal_add_css(drupal_get_path('theme', 'MYTHEME').'/css/print-page.css', array('media' => 'print'));


Services 3 Session authentication CSRF Validation with Persistent Log in

Evidently the workflow has been simplified.  I make a single call to /user/login.  Here is an example:

{
  "method": "POST",
  "url": "http://HOSTNAME/SERVICE_PATH/user/login",
  "headers": {
    "Content-Type": "application/json",
    "Accept": "application/json",
    "Connection": "keep-alive"
  },
  "json": {
    "username": "USERNAME",
    "password": "PASSWORD"
  }
}

which returns:

Response: {
  "sessid": "waroHcB4h8rbU0yhZjh-zGLAquZYlpayC_kB38gx--I",
  "session_name": "SESSb4d5ba755bb4eb727d982993490e6681",
  "token": "MHT4hmagxHgf0lOYlkENGlTZGk2AZ96G3p3ZCCc2kvo",
...
}

Now the cookie is created by concating the session_name and sessid with the equal sign separating them.  The X-CSRF-Token header is simply the token in the response.  All future requests will reuse the X-CSRF-Token: and Cookie: headers:

Here is an example of a user profile request:

{
  "method": "POST",
  "url": "http://http://HOSTNAME/SERVICE_PATH/user/profile",
  "headers": {
    "Content-Type": "application/json",
    "Accept": "application/json",
    "Connection": "keep-alive",
    "X-CSRF-Token": "MHT4hmagxHgf0lOYlkENGlTZGk2AZ96G3p3ZCCc2kvo",
    "Cookie": "SESSb4d5ba755bb4eb727d982993490e6681=waroHcB4h8rbU0yhZjh-zGLAquZYlpayC_kB38gx--I"
  }
}

Short answer: call /user/login once, set and reuse the X-CSRF-Token: and Cookie: headers for all future REST calls.


If you want to display the values in table format you can use Table theme
Example:-

$form['table'] = array(
  '#theme' => 'table',
  '#header' => $header,
  '#rows' => $rows,
  '#empty' => t('Empty Rows')
  );

$header and $rows  would be arrays.


That might because of cache. Clear your site cache here /admin/settings/performance. Then try to load your content type edit page /admin/content/node-type/biography.


How to add a region to display only on a specified page?

So, there's multiple ways to approach this: 1) views theme preprocess functions; 2) creating a page specific tpl; 3) jquery/js hacks to only show the content on the specified pages.

For the sake of maintenance and simplicity, I chose to re-build the page as a basic page and add the necessary views to the page and add the region to a page specific tpl. I chose the basic page option for simplicity as well as simplifying other tasks down the line such as breadcrumbs. I copied the page.tpl.php, and renamed it page--my-node-id.tpl.php and flushed the theme registry, restoring the original page.tpl. Just an FYI, going the node page route forced me to set the display for the article class inserted into the page to none, to keep my styling the same.


How to show SUM of values from referenced entity fields in a View?

Under Relationships, add a relationship for the desired field. "Entity Referenced". Not "Entity Referencing".
Under Fields, add the field you want to sum. Add the relationship in the field settings.
Under advanced, enable Use Aggregation.
Under fields, click Aggregation Settings next to the field and choose "Sum".


boost module - no file to Disallow: /boost_stats.php

This file was a part of the Boost module in Drupal 6. It is no longer present in the Drupal 7 version. If you are using D7 this instruction can be ignored.


Show the logged in user their account status

A user that has not been approved by the admin can not login as far as I know.


How do I recalculate the price based on a given address?

Price resolver might be the thing you need. Here's the example: https://www.drupal.org/project/commerce/issues/2931445#comment-12391622


Does it have to be registration? You might find it easier to set up one or more roles with the privileges you want to grant to paying users and then use Ubercart to grant these roles to users who buy the appropriate products.

If this sounds good, look at using the uc_roles module that comes with Ubercart. The Ubercart documentation contains a pretty good overview: on selling site access with role assignment.


Custom field widget that displays a button with JS action and a hidden textbox

Welcome here. You're question is complicated with many steps some involving the Drupal API and others involving Javascript and Ajax. Your question is specific to your needs, so you'll likely not find a module that does exactly what you're asking for out of the box.

You're correct that the Drupal API should be able to do this -- but by asking people to show you how to do like your 5; is basically asking someone to do your homework for you. I can outline the tools you'll need. It's up to you to come to a working solution.

1st off -- outline your code outside of the Drupal API and simply thing "how would this form work in psuedocode" using say PHP and JS; building those steps will take you a long way.

Drupal Resources to help you:

The Field API Documentation pages.
The Official Field API Tutorial, which links some 3rd party tutorials as well.
If the above 2 resources aren't enough to understand what the Field API does look at the Examples module for Developers.
It sounded like you wanted AJAX in your form. Read up on the Drupal Javascript API Documentation, specifically the Ajax Forms section, and again if that's not enough look at the Examples module, or google "drupal jquery form" as while Drupal has it's own JS API, Drupal bundles jQuery so you could try to just use jQuery to fulfill your needs mostly without the field api explicitly.

what do I mean by this? Here is a jquery autocomplete tutorial which uses a text field "in" drupal but is simply using jquery's native autocomplete functions. I used Google Translate for that page and View Source in my browser to fill in the tutorial gaps -- to re-engineer this on a site I have.

Lastly, either route you'll take you will likely be integrating with an existing Node form. You probably want to use hook_form_alter to inject your custom business logic into the existing Drupal functionality.


How to access node from hook_html_head_alter()?

Drupal alter hooks, the group of hooks including hook_html_head_alter(), are not thought to add values, but to alter the values provided by another module. If you need to add a tag to the <head> of a node page, you should:

In a module, implement hook_node_view(), check $view_mode is not equal to 'teaser', and possibly other values for which you cannot provide the tag you want to add. Alternatively you can implement hook_entity_view(), which is called for every defined entity; if you just want to add the tag to nodes, you should rather implement hook_node_view().
You can also implement hook_preprocess_node(), which is invoked every time a node is shown, or hook_preprocess_page(), which is invoked for every page, including the page containing the node edit form. In hook_preprocess_page(), you need to verify $variables['node'] is not empty; if it empty, it means the page is not about a node.
The alternative is implementing hook_init(), but that hook is not invoked for cached pages.
In a theme, implement hook_preprocess_node(), or hook_preprocess_page().

In all the cases, you need drupal_add_html_head() to add the tag, and menu_get_object(), when you don't have the node object, which is available in hook_node_view(), hook_preprocess_node(), and hook_preprocess_page(). You would need to call menu_get_object() in hook_init(), for example.

Notice that menu_get_object() called without arguments returns a node object, if the page is about a node, and its path is similar to node/[node ID], or starts with that string; if the page page is, for example, page/node/[node ID] (where page/node/[node ID] is not a path alias), then menu_get_object() doesn't return a node object; in the example path I used, you should use menu_get_object('node', 2).


Add script on head section without module

Add it your theme instead.

html.tpl.php would be the correct template to use.


Can't access to password input on registration form

You can access the password form field in the registration form, but the ID you are setting is not used.

When a password_confirm form field is being added to a form, Drupal is really adding two password form field with a process function (form_process_password_confirm()); that function doesn't use the ID set for the password_confirm field for the new fields.
There isn't a theme function for the password_confirm form field, which means that the following code (executed from theme_password(), and theme functions for other form fields) is not executed.

element_set_attributes($element, array('id', 'name', 'size', 'maxlength'));
_form_set_class($element, array('form-text'));

What you can do is to wrap the password_confirm form field with a
 tag to which you assign your ID.

$form['account']['pass']['#prefix'] = '
';
$form['account']['pass']['#suffix'] = '
';

If you are using the CSS ID to execute JavaScript code, or to style the field, keep in mind that the default output for the password_confirm field (for the form field you are interested) is the following one.

Password strength:

    Password *
    <input class="password-field form-text required password-processed" type="password" id="edit-pass-pass1" name="pass[pass1]" size="25" maxlength="128">

Passwords match:

    Confirm password *
    <input class="password-confirm form-text required" type="password" id="edit-pass-pass2" name="pass[pass2]" size="25" maxlength="128">

Provide a password for the new account in both fields.

The HTML output includes also the output from the JavaScript code that outputs the password strength.

As alternative, you can add a process function that is executed after the process functions normally used by Drupal.

$form['account']['pass']['#process'] = array('form_process_password_confirm', 'mymodule_process_password_confirm', 'user_form_process_password_confirm');

Use form_process_password_confirm() as guideline for the code you should write.

function form_process_password_confirm($element) {
  $element['pass1'] =  array(
    '#type' => 'password',
    '#title' => t('Password'),
    '#value' => empty($element['#value']) ? NULL : $element['#value']['pass1'],
    '#required' => $element['#required'],
    '#attributes' => array('class' => array('password-field')),
  );
  $element['pass2'] =  array(
    '#type' => 'password',
    '#title' => t('Confirm password'),
    '#value' => empty($element['#value']) ? NULL : $element['#value']['pass2'],
    '#required' => $element['#required'],
    '#attributes' => array('class' => array('password-confirm')),
  );
  $element['#element_validate'] = array('password_confirm_validate');
  $element['#tree'] = TRUE;

  if (isset($element['#size'])) {
    $element['pass1']['#size'] = $element['pass2']['#size'] = $element['#size'];
  }

  return $element;
}

user_form_process_password_confirm() just adds the JavaScript code to handle the password strength, and any messages about the used password (e.g. Make it at least 6 characters, Make it different from your username).

I tried using the following code in my test site, and the output for the password field didn't change.

function code_testing_form_user_register_form_alter(&$form, &$form_state, $form_id) {
  $form['account']['pass']['#attributes'] = array('id' => array('userRegInput'));
}

The ID is not being added to the form field.

Password strength:

    Password *
    <input class="password-field form-text required password-processed" type="password" id="edit-pass-pass1" name="pass[pass1]" size="25" maxlength="128">

Passwords match:

    Confirm password *
    <input class="password-confirm form-text required" type="password" id="edit-pass-pass2" name="pass[pass2]" size="25" maxlength="128">

Provide a password for the new account in both fields.


How to assign nodes to an organic group in code

Found out removing the last line from the snippet 'node_save($node)' and the above type error was the reason for my problem. Thanks for the support.


Ampersand does not get urlencoded and breaks my GET parameters

I'd wager you could refactor a bit, and substitute the id for the title and avoid the problem altogether.

However, you can see similar problems being worked on throughout the Views issue queue. Like this one, for instance.


Conditional form states in hook_form_alter()

This is a little bit tricky the Form API #states works with jQuery selectors if your filed field_openbaar_vervoer coming from a taxonomy entity reference.
So the input generated HTML will be something like (example from tags fields)
<input data-drupal-selector="edit-field-tags-3" aria-describedby="edit-field-tags--description" type="checkbox" id="edit-field-tags-3" name="field_tags[3]" value="3" class="form-checkbox">

So to target all those inputs you should use Starts With Selector in your code and it will work:
$form['field_afstand']['#states'] = [
  'visible' => [
    ':input[name^="field_openbaar_vervoer"]' => ['value' => '236'],
  ],
];


What happens when multiple context conditions match?

Context starts from top and moves downward on all your created contexts and will stop on the first one to trigger it. This is why your context A is being displayed.

You have a few options...

Set a required condition to your context A as "Default Context" this way it will only trigger if no other contexts were found.
Make a few MAIN contexts that apply to many different cases for example, cache 1day, cache 5 days, cache 2hours, etc. The tag you can start with z_caches or something like that and put no conditions to these cache contexts, only the reactions. Note this will move them all the way down and you may think they will never apply... wait... now go to a main context for example, article_type and there you add a condition of "context (any or all)" and add the cache context you already created to that list. That way all article content types will automagically first add the context cache you want applied within this context. This way the page will stop on only one context, yet that one context contains multiple contexts within it. This is perhaps the best solution in most cases that need to apply multiple contexts or share conditions. Seeing your example, you can also create a "Domain" context like we did cache and apply it to whatever contexts you want and easily edit any of the included contexts without having to create so many different contexts since you are sharing some contexts that you know will be common. Cache, Http headers, delta (for theme layouts), domains, language, etc. These are all possible conditions that people may see themselves repeating on multiple contexts, but if you ever need to edit any of these, you have to go one by one to every context you added them and edit that field. However, if you use this method of sharing or including/excluding other contexts within your context, you only have to edit that one particular context that was included and will apply to all contexts referencing it.
Reorder your contexts in the order you want them triggered from top to bottom. The easy way to do this is by using the "clone" link when viewing all your contexts. Simply clone it and change the "tag" field (second field above the description) and you can start all your tags with numbers (like weights) and that will get the contexts in the order you need.

*NOTE: For point #2, you can use the "context all" or "context any" conditions to display or not display (not display using ~) any other contexts or the "context_disable_context" module which will allow you to select which contexts to omit.

In summary, using context is similar to using Path Breadcrumbs for example, in the sense that you have to plan ahead the hierarchy of importance from top to bottom of anything you create and know it will stop on the first item if true.

See your example, and you will see that in fact domain B and C when seeing context A, are in fact true, that is why it stops there (both domain B and C have a  page). If however, you follow my option #3 and reorder A to the bottom (B,C,A) and make all conditions of B & C required, any pages that do not specify the domain B or C will in fact trigger A.

The main difference between path breadcrumbs and context is that with path breadcrumbs you can drag and drop their weight order making things much easier. Here, you must find a way around that by altering your orders based on any of the methods i mention above. Not all will work in every case so i guess you just have to see which one works in your situation. I for example always have my path contexts above my content type contexts to ensure that the path if triggered has precedence over the content types and i use any conditions that are shared across multiple contexts by using method #2 i explain above.

I hope i made sense since i have not slept in over a day. At least it may be a good starting point :)


db_query() is not returning results from a valid query

The SQL looks fine, but you're using the wrong versions of the DB API at the moment.

For Drupal 6 you want to use syntax similar to the following:

$results = db_query($query);
while ($row = db_fetch_array($results)) {
  print "ID: " . $row['id'];
}

There's some good documentation for the D6 API on this post, it's worth a read.

Forgot to mention...db_num_rows() is a Drupal 5 function which is why the script is failing. There's a discussion on the alternative methods for D6 here (most involving COUNT queries)


How to process field input so b52 goes into database as B-52

OK figured it out.

hook_node_presave() is what I want and it can only be called from a module I think.

Found the answer here: node_presave doesn't work

function nodepresave_node_presave($node){
  drupal_set_message('nodepresave DEBUG: PRESAVE Called');
  if ($node->type === 'vehicle') {
    drupal_set_message('nodepresave DEBUG: node->type === vehicle');
    drupal_set_message($node->field_id_number['und'][0]['value']);
  }}


How do I disable APC caching just changing any Drupal setting?

There are multiple settings necessary to do so:

in active settings.php:

/**
 * Class Loader.
 *
 * If the APC extension is detected, the Symfony APC class loader is used for
 * performance reasons. Detection can be prevented by setting
 * class_loader_auto_detect to false, as in the example below.
 */
$settings['class_loader_auto_detect'] = FALSE;

// Default cache backend.
$settings['cache']['default'] = 'cache.backend.database'; // or any other alternative cache backend

After looking at Berdirs comment and diving further into code and looking at more usages of apcu within Drupal it appears to be pretty much impossible to catch every usage / and even if you manage to find all of them - disabling at some points is not possible (e.g. no configuration options present).


I don't think $block['content'] = ''; $block['content'] .= 'uri.'" alt="Se alle vores filter elementer her">';... will work, . is a string(concatination) operator. You should create render array and assign it to $block['content'], example:

$array = array('#markup' => 'SOME HTML');
$block['content'] = render($array);

EDIT:

After below comments, I played a little with hook_block_view hook, and I found out some information about it:

$block[subject] doesn't affect to its content even if you don't set it; content will be displayed without any subject (so, your missing subject doesn't cause any error here, as j.Reynolds mentioned);
$block['content'] can be string value and you don't need to render it, as Molot andj.Reynolds mentioned below, and you can concatinate it as many times as you want:)

So, if we return back to your snippet, you can try something like this:

$block['content'] = 'uri) . '" alt="Se alle vores filter elementer her" />'; // assuming that anchor tag will wrap img
$block['content'] .= '
' . $row->title . '
';
$block['content'] .= '
' . $row->body_value . '
';
$block['content'] .= theme ('item_list',array('items' => $items, 'type' => 'ol',   'attribute' => 'produkt'));

I don't know what $row->uri looks like in your code, but I assumed that it is something like public://FILE_NAME.EXT, if so you can use image_style_url function to generate image src..


How to add a line break between each components in Email template in Webforms

You can add every form component individuell with a syntax like [submission:values:field_key:label]
[submission:values:field_key:nolabel]
Please check the Tokens in your email settings or the following link https://www.drupal.org/node/2490648

You can also modify the webform-submission.tpl.php file and adjust it for your email.


put the logic into a views fields template

If it's a "one-off", most of the time, that's the way I would have gone about it. Display the "primary" field, exclude the seconday. Template the primary to display the second as necessary.

At a recent project, I "was just going to do this once", but then the client started changing their mind, and now I have a really big mess of views templates. If I knew that I would have a lot of logic like this, I would use a Views Context display instead, pull that into Panels, and have the Page manager handle the display logic instead. More complicated, but also neater IMO, and easier to maintain, as the logic becomes independent of the presentation.


D7 - Syntax of js custom file added directly to theme

It just needs to be unique (otherwise you'll overwrite something existing, this is JS after all). So it would make sense to go with

Drupal.behaviors.myThemeBehavior = {

But it doesn't really matter as long you're not elbowing an existing behaviour out of the way.


Request passphrase at user registration and automatically assign role to user

Use the Rules module to implement such feature, as further detailed  below.

Step 1: Add a field to the registration form, which wil be used to have a user enter your passphrase. Even though you can use any "machine name" for that field, let's assume you call it "field_optionlist"

Step 2: Use a variation of the Rule included in my answer to "How to specify a Rules condition related to select list values?". Here is what you should tune in that rule:

Replace the Rules event to something like "After a new user submits a registration request"
Replace the "Value C" in the Rules condition to the value of your passphrase
For debugging reasons, start with a Drupal message to be shown (imilar to the rule mentioned above. After the message shows up as you want it to show, replace the Rules Action with something like "Assign role to user".


You can't. The l() function is only responsible for rendering the HTML link, it has no concept of the tag it's being wrapped in (or indeed if it's even being wrapped in another tag at all).

The simple answer based on your question is to add it manually:

<?php print l('Hapiness','my/hapiness/complete', array('attributes' => array(), 'html' => FALSE)); ?>


According to drupal_convert_to_utf8 it required Requires the iconv, GNU recode or mbstring PHP extension to work,  make sure mbstring Php extension installed(Go to /admin/reports/status and take a look at your unicode library) if not installed install it and try again

 drupal_convert_to_utf8($data , 'us-ascii');

if not worked  according to mb convert encoding you can let Php detect encdoing with AUTO, so  use

drupal_convert_to_utf8($data, 'auto');

Also  I can suggest another solution for you

iconv(mb_detect_encoding($data, mb_detect_order(), true), "UTF-8", $data);


Is there a D7/Services module for sane field content I/O?

With the Services module, no. However you could build a Page display with Views datasource, that accepts a node id as a contextual filter. The fields you specify in the View can then be configured to "clean up" the property name (or just turn off the label to use the machine name of the field), and then the value will be "flat".


How to display flags to anonymous users and redirect to login after clicking a flag?

Maybe the Flag anonymous module is what are you looking for.


How to force drupal to use English version of the field?

Go to the Views admin of the block, and filter by language. It will automatically only show the node in the language that you select.


Drupal 7 node body content missing from search results

Okay, so I was able to resolve this issue through a combination the following efforts.

Under both content types and added in new fields to search index and search results highlighting input.
Under Administrator/Configuration/Search and Metadata/Search Settings I turned off Simple CJK handling.
Under Custom Search Content Tab I used the default of -Any- and under the Exclusion options left all but my two desired content types checked.
Under Administrator/Configuration/Search and Metadata/Search Settings I clicked re-index site.
I then flushed all caches and ran cron until the site was once again 100% indexed.

After all that I performed my tests again and everything was coming up as expected. Hopefully this can help others later in their testing.


How to hook into Drupal 6 search process?

If you look at search_menu(), you will notice the following code.

  foreach (module_implements('search') as $name) {
    $items['search/' . $name . '/%menu_tail'] = array(
      'title callback' => 'module_invoke',
      'title arguments' => array($name, 'search', 'name', TRUE),
      'page callback' => 'search_view',
      'page arguments' => array($name),
      'access callback' => '_search_menu',
      'access arguments' => array($name),
      'type' => MENU_LOCAL_TASK,
      'parent' => 'search',
      'file' => 'search.pages.inc',
    );
  }

Every module implementing hook_search() gets a menu tab. So, your module will be asked to search only when the users select its tab.


How to prevent a Rules Action to happens twice using Rules Event User account validated?

Understanding what's happening

Your question seems like a variation (IMO not a duplicate) of the question 'Why is my rule that reacts on event "After updating an existing user account" firing twice?'. The accepted answer in that question might help to understand your issue (what's causing it) also, ie:

  some other module code is calling a user_save on hook_user_update triggering the rules event a second time.

If I was to debug this, I'd disable all contributed modules (except "Rules" and "Entity API") to check if it's indeed a contributed module (I don't expect it to be core). And then re-enable the contributed modules one by one until the issue comes back. As soon as it comes back, you pinpointed the contributed module causing the issue, and you can start working on a possible remedy for that.

Workaround 1

That question also has another answer with a very interesting workaround, with an image which looks like so (a picture is worth more then 1000 words):

Workaround 2

Another workaround to prevent this issue from happening, is to improve your existing rule to make it similar to the rule included in my answer to "How to implement a Rules Condition like [account:last-login] = never?". More specifically:

Add a Rules Condition like: User does NOT (!!!) have a role with role id = "4".
Add a Rules Action like: Grant User the role with role id = "4".

So this improvement of your rule will check if the user does not yet have some (designated) role with role id = "4" (adapt to whatever role id that fits your case, and make sure this role is NOT yet granted when activating a new user id). If that's the case, then the user is granted that role. With this improvement to your existing rule, this is what will happen:

The 1st time your Rules Actions will still be performed (and grants the designated role).
the 2nd time not ALL of your Rules Conditions will be satisfied (since the designated role was granted before), and therefor your Rules Actions will no longer be performed.

In other words: "this will prevent your Rules Actions to happen twice" (as in your question).


Notification of new comments for author and comment writers

Have a look at this rule (in Rules export format), which does what you're asking for:

{ "rules_notify_users_about_new_comment" : {
    "LABEL" : "Notify users about new comment",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "rules_conditional", "comment" ],
    "ON" : { "comment_insert" : [] },
    "DO" : [
      { "variable_add" : {
          "USING" : { "type" : "list\u003Cuser\u003E" },
          "PROVIDE" : { "variable_added" : { "users_to_notify" : "Users to notify" } }
        }
      },
      { "LOOP" : {
          "USING" : { "list" : [ "comment:node:comments" ] },
          "ITEM" : { "current_comment_item" : "Current comment item" },
          "DO" : [
            { "CONDITIONAL" : [
                {
                  "IF" : { "NOT data_is" : {
                      "data" : [ "current-comment-item:author" ],
                      "value" : [ "comment:author" ]
                    }
                  },
                  "DO" : [
                    { "list_add" : {
                        "list" : [ "users-to-notify" ],
                        "item" : [ "current-comment-item:author" ],
                        "unique" : "1"
                      }
                    }
                  ]
                }
              ]
            }
          ]
        }
      },
      { "CONDITIONAL" : [
          {
            "IF" : { "NOT data_is" : { "data" : [ "comment:author" ], "value" : [ "comment:node:author" ] } },
            "DO" : [
              { "list_add" : {
                  "list" : [ "users-to-notify" ],
                  "item" : [ "comment:node:author" ],
                  "unique" : "1"
                }
              }
            ]
          }
        ]
      },
      { "LOOP" : {
          "USING" : { "list" : [ "users-to-notify" ] },
          "ITEM" : { "current_user_to_notify" : "Current user to notify" },
          "DO" : [
            { "mail" : {
                "to" : [ "current-user-to-notify:mail" ],
                "subject" : "New comment to node with id [comment:node:nid]",
                "message" : "There is a new comment added to the node with id [comment:node:nid]",
                "language" : [ "" ]
              }
            }
          ]
        }
      }
    ]
  }
}

I translate the "... in the same rules ..."-part of your question like "I want it to be a single (monolitic) rule". For that you'll need an additional module, i.e. the Conditional Rules module, while the above rule does use a few of the more advanced techniques available in the Rules module.

If you're familiar with reading/digesting Rules in Rules export format, I'd hope the rule is self explaining. If not here is a summary of the above rule:

Rules Event: obvious ... After saving a new comment.
Rules Conditions: feel free to add whatever fits (eg limit to selected content types only).
Rules Actions:

Add a variable "users_to_notify" (= a list of users).
Loop over all existing comments, and for each comment author, check that it is not the user who just created the comment (which you can check if you have the Conditional Rules module enabled). If that's the case, then add that user to the list of users (= users_to_notify).
If the comment author differs from the node author (which you can check if you have the Conditional Rules module enabled), then also add the node author to the list of users (= users_to_notify).
Loop over the list of users (= users_to_notify) ... again, which we just created and populated). And for each user in that list, do your thing, in this case "send an eMail". The "To" value is crucial here, the body, the from, the title, etc is up to your own imagination.

If you don't want to use the Conditional Rules module, you could also rework the Rules Actions that require this module to performing Rules Components (in which you add the appropriate Rules Conditions), so that you don't need this extra module (for more details on that, refer to the answer to "What's the alternative to using the Conditional Rules module?").

If you want, just import the above rule in your own site (using the Rules UI, which should be enabled to do so), but only after you enabled the Conditional Rules module.

That's really all it takes ... a Rules variable, Rules lists and loops, and Conditional Rules.

Note that the above rule does actually more as compared to what is asked here:

As per the "unique" in Rules Action nr 2, it will not create duplicates in that list of users, to avoid the same user would receive duplicate eMails (i.e. if a user commented multiple times).
As per the "unique" in Rules Action nr 3, it will not create duplicates in that list of users, to avoid the node author would get duplicate eMails (i.e. if the node author also commented already).
This rule will NOT send an eMail if the comment was posted by ... the node author (which seems to me like a contradiction in item 1. and 3. of the question ...). If you disagree on that (i.e. that it should send an eMail anyway: just delete Rules Action nr 3.

Unit testing the rule

If you want to (unit) test the above rule, you may want to add another Rules Action within Rules Action nr 4. I.e. add some sort of "Show a message on the site" (located within Rules group "System"), to produce a message for each user included the list of users (= users_to_notify).

That way, if for some reason your site has not been correctly configured yet to send eMails, those messages will help you confirm that the rule itself is not the cause of that.

Video tutorials

For anybody not familiar (enough/yet) with Rules, checkout the 32 (!!!) great, and free, video tutorials Learn the Rules framework, organized in 7 chapters. Especially these tutorials, which are related to subject of this question:

Notify author of comments.
Notify of comments replies.


How to implement Facebook style Notifications for Organic Group posts?

Below is a blueprint of how you can make this work. To avoid writing a manual as an answer, and to avoid repeating myself, I use some links to other answers (not all of them are mine ...).

Step 1: Get Rules involved

Use the Rules module to capture events about new nodes being created, which belong to some Organic Group. Have a look to either of the answers to  "Get organic group name in a rule?", for 2 possible alternatives to "send an eMail" to each member of the group.

With that, all that's left is to replace the Rules Action to "send an eMail" with something that shows the number of notifications (as in your question), as further explained below.

Step 2: Use Messages to create notification entities

Install/enable the Message module also. So that you replace the Rules Action from the previous step to "send an eMail" by a Rules Action to create message "entities" (which is what you get if you use the Message module). And then just use the power of Views to display those messages later on (hang on: in a format like your shiny notification button ...).

Here is a summary of what you'd need:

Define an appropriate Message type, using the Message module. Think of Message types as similar to "Content types", which will be used to create Messages, similar to Nodes.
Enhance your rule with a Rules Action "Create entity" (of type "Message"). Refer to the answer in Which user related token(s) can be used to create a Rule for setting up a message type? for some examples.
Possibly you may also want to add a Rules Action to pass any relevant tokens, via Rules, as Replacement tokens that you can use in your Message type you created with the Message module. Refer to What's the purpose of "Replacement tokens" of a Message type? for more details on this.
Use Views to display the created messages in the format you prefer.

Step 3: Transform the view in a notification icon

The Menu Badges module can be used to add such notifications to any menu item and/or menu tab of your choice. Here are some details about it (from its project page):

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

  Adding Badges to Menus

  Once enabled, go to Administration > Structure > Menus, and click "list links" next to the menu containing the target item. Click "edit" next to the item and select the badge to display with the Display Menu Badge select box.

  Adding Badges to Tabs

  For adding badges to menu tabs, there is a tab under Administration > Structure > Menus called "Tab Menu Badges". Search for the menu router path of the tab you want to alter, then select a badge from the corresponding select box.

  Badge Types

  The module includes five example badges, and new badges can be created easily with Views. Modules can also supply their own badges with a hook implementation. See the README.txt file for details.

Because of how it integrates with the Views module, you basically reduce the solution for any type of notification to something like this:

Just create an appropriate view of it, create a menu item or menu tab for that view. Obviously, the view created in Step 2 is the view you want to use.
Do a 15 seconds Menu Badges configuration to tell it which menu item/tab you used for it in your view.

Video tutorials:

Defining Menu Badges with Views in Drupal (from the module maintainer).
Drupal 7 Menu Badges Module.

Step 4: Updating the notification icon

After you completed the above steps, you'll have such shiny notification icon corresponding to the relevant messages. What's left is to implement something to get the icon (ie the counter shown in it) updated, as further explained below.

Option 1 - Make the Messages manage-able

This option allows a user to indicate which messages have been read already, and which ones are new (= unread). For that, just perform the steps explained in "How to allow users to manage their own Message Stack messages?", which can be summarized like so:

Create a flag (using the Flag module).
Create a view 'Messages by user' (= improved version of the view specifications described above).
Use Rules to flag/unflag messages.
Trigger the Rules Component to mark messages (using the VBO module).
Create notifications about Unread Messages (using the "Menu Badges" module). So that whenever a new message gets created, the user gets a notification in the format of an iOS-like (red) badge with the number of unread messages.

Option 2 - Remove the notification icon after visiting some path

This option will remove the notification icon entirely, after the user visited the dedicated path to display all messages. Refer to the answer to "How to make menu badges count disappear after the page is viewed?" for details about how to do so.


No need to set up hook_theme, Just include like this:

{% include '@theme_name/system/footer.html.twig' with content %}

this will include that template in your main template.  The variables will need to be available from the main template.

The "with" statement sets up the variables being sent to the sub-template.  See http://twig.sensiolabs.org/doc/tags/include.html


Javascript loaded via DrupalSettings variable not executing?

Use drupalSettings.basic.nr_map.foo instead of settings.basic.nr_map.foo in your JavaScript.


What is the first parameter of this db_query call for?

The first argument taken from db_query() is the query string to execute; the next parameters are the values of the placeholders used in the query strings.

If you see code similar to the one you show, it means the content of includes/database.mysql-common.inc, or includes/database.pgsql.inc (depending on the database engine used) has been changed to alter the first parameter used from db_query(). If you are using third-party database drivers, check the database.<database-engine>.inc file that should come with that database driver.


Run a view's bulk operation immediately but in background. Is that possible?

PHP needs something to drive the process, it's not multi-threaded. Drupal's queue process runs by either the client's browser making a series of calls (kind of like it emulates the cron), or by the cron itself.

Why isn't the cron an acceptable method? You can use something like ultimate_cron The control the schedule for each cron tasks.

Update

As @Molot mentioned, the CLI is an option. I believe shell_exec is subject to PHP's timeout (I could be wrong). See this blog post on executing PHP in an asynchronous fashion.


Fetching client time using JavaScript and comparing them with values stored in the database

Send server time to the client side via js variables: drupal_add_js, see example.


All page access only to administrator in

I think the name of your access callback is wrong. (example_user_has_role => check_user_has_role). Also, you made a mistake on the role name (adminstrator => administrator).

Anyway, you can achieve this in a more simple way like this (avoiding the argument in the URL)

function example_menu() {
  $items['example'] = array(
    'title' => 'My Page',
    'page callback' => 'example_custom_page',
    'access callback' => 'check_user_has_role',
    'type' => MENU_NORMAL_ITEM,
  );

  return $items;
}

function check_user_has_role() {
  global $user;
  if (in_array('administrator', $user->roles)) {
    return TRUE;
  }
  return FALSE;
}


Create a log of create/delete users in Drupal 7

You could actually log the details about user creation at hook_user_insert(), and deletion using hook_user_delete().

User creation: Acts on new user creation

function MODULE_user_insert(&$edit, $account, $category) {
  watchdog('user', 'User created with ID: %userid', array('%userid' => $account->uid]), WATCHDOG_NOTICE, $link = NULL);
}

User deletion: Acts on account deletion

function MODULE_user_delete($account) {
  watchdog('user', 'User having ID: %userid deleted', array('%userid' => $account->uid]), WATCHDOG_NOTICE, $link = NULL);
}


Content, terms and user/author import or migration to D8 without custom module

I have successfully migrated D7 content into a D8 site with similar content types using this small drush extension for D8 along with the built-in D8 Upgrade option:
https://www.drupal.org/project/migrate_upgrade

I believe the upgrade process from D7 or D6 is now apart of D8.3+ in the Admin UI and can simply be enabled after drupal 8 installation under the Module listing. Alternatively, you can use Drush via the module above.

Your D8 project just need localhost access to your old site files (such as images,pdfs, etc ... your old Files directory in Drupal 7/6) and database connection access.

It's a rather painless process for simple websites.

Please review the official documentation on performing a drupal 8 upgrade migration


Why the content of a block created in an external module does not appear?

call a php function to built block-content, in hook_view code should be:

//construct your output as a function
$block['content'] = myfunctionname(); // this function is called 3 lines below
....
return $block;
//then call your output content function
function myfunctionname() {
$output = 'whatever you want(arrays, functions, html, more php, ....)'
 };
 return $output;

that will return $output as your content.


Programmatically adding fields to specific vocabularies

It turns out that with taxonomies, vocabularies are bundles of taxonomy_term entities.

So, it turned out to be something like this:

Assuming a taxonomy machine name of example_taxonomy

  $field_example = array(
    'field_name' => 'field_example',
    'cardinality' => 1,
    'type' => 'text',
  );
  field_create_field($field_example);

  $field_example_instance = array(
    'field_name' => 'field_example',
    'label' => st('Example Text Field'),
    'bundle' => 'example_taxonomy',
    'entity_type' => 'taxonomy_term',
    'widget' => array(
      'type' => 'text_textfield',
    ),
  );
  field_create_instance($field_example_instance);

So, yeah, it turns out that taxonomy_terms are the entities and vocabularies are the bundles...


How do I change the input type of an exposed filter in a view?

Edit View >> Configure filter criterion >> Select grouped filter (instead of the default, single filter) >> Set-up your options. That's it! you now have dropdown filters of free filled node field.


"Updating a module" can comprise of two things:

If it's just code, then simply replacing the old code with the new code should be sufficient. However, when your code is complex or you are working in a multi-user environment, it is best to bring your code under version control like svn or git (as you have tagged), and maintain it with branches and tags depending on the version of Drupal that you are working with.
If your module also involved database updates, then you will need to become familiar both with the .install file as well as hook_update_n() functions. The documentation for the latter along with source examples from the .install files of core modules should guide you to creating update functions correctly.

On a related note, if your custom code is generic enough to be of use to the rest of the community, you can post it as a Drupal project and leverage drupal.org's project management feature which comes with git access.

You should also test everything out on a development server rather than on the production site. Adding lots of documentation to your update functions as well as maintaining a CHANGELOG.txt is also recommended.


The form labels are part of the webform's configuration, and their translation is therefore handled by the Configuration Translation (machine name: config_translation) module. When that module is enabled, it will add the Translate tab.


You can do it in a custom module using entity.query service

$query = $this->entityTypeManager()->getStorage('webform')->getQuery();
$webform_ids = $query->condition('status', 'open')->execute();

$webforms = Webform::loadMultiple($webform_ids);
$webform_urls = [];
foreach($webforms as $webform){
  $webform_urls[] = $webform->toUrl()->setAbsolute()->toString();
}

Here is a demo module that uses entity.query in a controller to output those path as links with title as the title of each webform.


For a similar problem (removing the language switch links for non-translated equivalent pages), I've implemented hook_language_switch_links_alter() in my theme.

Although I haven't tried it out myself, I think the code example will point you in the right direction. Instead of setting an 'active-language' class attribute, you can unset the link.

function mymodule_language_switch_links_alter(array &$links, $type, $path) {
  global $language;

  if ($type == LANGUAGE_TYPE_CONTENT && isset($links[$language->language])) {
    foreach ($links[$language->language] as $link) {
      $link['attributes']['class'][] = 'active-language';
    }
  }
}


Include content of a block in a view template

You can't mix different templates types like views and block templates. Every template has other variables and so the block template doesn't find the content variable in the views template context.

In your case for a View you could place the block in the header or footer in Views UI. For example a Rendered entity - Block.

In general you can use the module Twig Tweak instead of {% include %} to render a block template or any other entity template:

{{ drupal_entity('block_content', 1) }}

This works, because it renders the entity in its own variable scope and so you can place it everywhere in twig.

While entities normally render in their own template, block content is special, because it doesn't have a template on its own. So the command above only shows the fields. To get the block wrapper you need to use drupal_block().


You're only selecting the nid field, you just need some more:

...
->fields('n', array('nid'))
->fields('d', array('fields', 'you', 'want'));


Module is shown as installed but I can't access its settings

Generic way when you face

  The website has faced some unexpected error

when enabling module is:

Find in logs what error was it
Fix it's cause
Disable and uninstall module you was enabling
Enable it again

Alternatively, if you have backups, better way would be:

Find in logs what error was it
Fix it's cause
Restore site from backup to it's state from just before error
Try again

If you have specific problem with this way, ask new question, explaining exactly what you need to know, what you did, what was in logs and so on.


Drupal 7 - Webform 3 - How do you expose form results to Views Easily?

If you want to make a page with links to each webform submission, you can just use Views itself; you don't need an extra module.  Add a new view.  Choose show Content of type webform.  Check the box for Create a page.  As the display format, I would recommend choosing the format you want and using fields; this will easily allow you to add links to the forms.

To be sure the search engines (Google, Bing, etc.) index your content, though, I wouldn't use this approach.  I would use the XML Sitemap module.


How to make a module prerequisite in drupal

using below format in .info file of the module.

dependencies[] = D1
dependencies[] = D2

I the above lines, D1 & D2 represent the names of the modules you module depend on.


Look for these solutions:

In Views, how can I show users with one role before all other users?

Role Weights

This way you can get your desired result. Hope this helps.


Convert Database object into database URL string

Using Drush:

drush sa @site --with-db-url

Or, to isolate just the db-url:

drush sa @site --with-db-url --format=csv --fields=db-url --field-labels=0


Why does my do-nothing subtheme break the parent theme?

The sub theme is fine. Sometimes when you activate a sub theme, you may need to recreate some or all of the block layout. In this case, the primary menu got placed in the header, where it gets a different layout.

Just make note of the block layout in the Bartik theme and duplicate it in the sub theme.


How use settings.local.php with Acquia Cloud

The default .gitignore file that ships with your Acquia Cloud git repository is fine as it is. See https://drupal.stackexchange.com/a/193251/23961

I also advised against adding settings.php to your .gitignore file here.

Using settings.local.php is optional. Details about the file are available in the file or the online Drupal documentation as described already here.


Store data from a specific content type in a different database?

This is not possible without a lot of custom code. Primarily because Drupal stores field content in separate database tables. There is not the one single table that holds the content of all nodes of a specific content type. And fields are also re-usable across different content types. You would need to create your own storage engine.

Wouldn't an intelligent backup strategy be enough to assure data security in your case?


In a taxonomy view, enabling aggregation causes HTML tags in description to be output

This is unintuitive behavior, but it is Views functioning as designed.
To get the HTML tags to render properly, you need to choose Aggregation settings for the taxonomy description and check the box Format under Group columns (additional).


Where is the "Add fields" button on content types when using the Minimal installation profile?

The minimal profile lives up to its name - the vast majority of modules aren't installed when using it.

This include the core Field UI module, which provides the UI you're missing. Just enable that module and you should see a "Manage fields" link as the default option in the table from your screenshot.


Is it possible to make a particular column in a tablefield readonly?

How are you applying the readonly to the fields?

You need to use the FAPI '#attributes' property to set readonly like this:

'#attributes' => array(
    'readonly'=>'readonly',
);

You need to alter the form through hook_form_alter and addd the above property to the textfield you want readonly.


How to attach a view display switch to a view?

Display Suite

A possible solution to this is probably utilizing display suite.

You could trigger a link using display suite & display suite extras to open different view mode. The drawback to this is that the user would have to load a different page.

Quicktabs

Another solution would be to load the two views as blocks and use quicktabs to display the two views in that tab format you require. The drawback to this solution is that you have two views loaded.

Views Header

At the top of your views, just add a header anchor to your other views page. This solution is best if you just have one view where this output is being displayed. Otherwise, it would be difficult to maintain duplicate views.


how to get the value of list field type (check boxes)

Where do you put this PHP code? If it's in the page.tpl.php, then you can use the $logovariable to display the field or not.

Otherwise, this configuration is available in your theme. So you need to get your theme configuration, with theme_get_setting. You should have a variable 'toggle_logo' or something like this. The full code would be

$test = theme_get_setting("toggle_logo");
if($test) {
   //Put your code here
}

If you're using different theme, or you need to get this value for a specific theme, then you need to pass your theme name as second parameter of the function, for example:

$test = theme_get_setting("toggle_logo", "my_custom_theme");

[EDIT FULL ANSWER]

So you just need to check the value of the field field_options_site_logo before outputing the image:

$node=node_load(18);
if(isset($node->field_options_site_logo['und'][0]['value']) && $node->field_options_site_logo['und'][0]['value'] == 'yes') {
  $logo_img = file_create_url($node->field_site_logo[$node->language][0]['uri']); //origional image path
  $show_logo = $node->field_options_site_logo['value']; //original image path
  if(isset($logo_img)) {
    $web_logo = theme('image_style', array('path' => $node->field_site_logo[$node->language][0]['uri'], 'style_name' => 'site_logo'));
    print $web_logo;
  }
}


Restrict users from creating certain title

I would look into using a combination of automatic nodetitles, field_validation and clientside validation. Basically once you have those three installed you can create a new text field on your content type which you will use as the title. In the validation settings for that field you can then set it up to not accept certain rules (see this post). Under the edit section of the content type you can set auto nodetitles to use your new field (and hide the title field) as your title.


How to make Panel Page variant selection rules detect URL parameter?

I found the Selection Rule Query string exists does this.


If some of your menu items are cut off, you should enable the supersubs plugin. You can do that on the block settings page for that particular menu.

If that's not what you want, copy over the stylesheets of superfish to your theme, include them in .info file and play around there.


How can I populate a node field based on a user field?

I believe you could achieve this with the Rules module. Checkout Learn Rules with NodeOne, part 7: Conditions on loaded objects. In part 8 you will see how to Use PHP to populate CCK fields. Although this is for Drupal 6, you should be able to use a similar approach in Drupal 7.


when calling privatemsg_new in a block, how can I correctly set the internal $destination variable?

Try this code in block, if you don't want to implement any hook in custom module.

$node = menu_get_object();
if ($node->uid != 0) {
  module_load_include('pages.inc','privatemsg');
  $recipients = $node->uid;
  print "
Contact " . $node->name ." about this post.
";
  $subject = $node->title ." question.";
  $form = drupal_get_form('privatemsg_new', $recipients, $subject)
  // Setup destination parameter to be equal to current page.
  $form['#action'] = url('node/'. $node->uid, array ('query' => drupal_get_destination()));
  print drupal_render($form);
}


How to deal with PHP Fatal error: Cannot unset string offsets in field.default.inc when implementing custom widget?

hook_node_validate was how I was able to fix this issue.

function MODULE_node_validate($node, $form, &$form_state)
{
    foreach ($form as $field => $field_data)
    {
        $field_info    = field_info_field($field);
        $instance_info = field_info_instance("node", $field, "CONTENT_TYPE");

        // since this field returns a string when an array is required, we need to correct
        // the data here before it goes any further.
        if ($instance_info["widget"]["type"] == "MODULE_taxonomy_autocomplete")
        {
            // Recieved: string
            // Expecting: array(array("tid" => TID),)
            $tag_names = explode(",", $form_state["values"][$field][$node->language]);
            $form_state["values"][$field][$node->language] = array();
            foreach ($tag_names as $tag)
            {
                $term = taxonomy_get_term_by_name($tag, $field_info["settings"]["allowed_values"][0]["vocabulary"]);
                $term = array_shift($term);

                $form_state["values"][$field][$node->language][] = array("tid" => $term->tid);
            }
        }
    }
}


Need to flush cache after node translation

Run the cache clear in a shutdown function. A little bit of a hack but it should work.

<?php
register_shutdown_function('cache_clear_all', 'content:' . $node->nid . ':', content_cache_tablename(), TRUE);
?>

Taken from content_delete()


The comments for my question were pretty much the answer, but I'll elaborate here.

The root of the problem was one of the included files had an ending PHP tag.  However, it wasn't in my code and I had no idea where else to look.

I ended up using something similar, to the following code.

watchdog("Module_name", "Check these files: !files", array("!files" => implode(get_included_files(), ', ')));

This gave me a list of all the files that Drupal had included in order to run my code.  There were about 140 of them.

The best way to figure out which might have superfluous end tags would be to cycle through each file programmatically, as Luke Redpath suggests on http://www.designerstalk.com/forums/programming/8005-php-finding-occurences-string-file.html.

In my case the file permissions were giving me trouble, so I brute forced it until I found an unrelated (but custom) module that had a bunch of ?> tags.


The closest thing I know is:
Switchtheme

Adds a block to allow users to switch between enabled themes.
Themes can be given 'user friendly' names and access can be controlled
by user role.
Switchtheme provides optional support for Browscap module to switch
themes based on the browser of a visitor.


How to style/theme an openlayers map block?

ok, so the answer should have been more obvious to me but I'm not really a front-end guy so it took a little head scratching to see that I just had to target the block by class rather than id...


It is not a bug. User voted up. His vote wasn't counted, but he voted all right. It might be used to update "last voted date" for example, or to give "forgetful" badge to an user who tries to vote many times on the same node. You either need to:

Look for an event that fires when vote is actually saved
Look for a condition that will let you filter out only new votes
Add if in the code that actually gets fired
If first two are not possible and third is to difficult, fill a feature request to add 1. or 2.

I'm deliberately not going to test these and find which one works, in hope future readers can benefit from algorithm for similar problems.


Pre-cautions to take when manipulating table structures

I'm not aware of any support for either of those changes in DBTNG, it's just something you need to do manually.

Luckily that means that once you've done it there's no chance of DBTNG knowing or caring about it - everything should continue to work as you expect.


add Global PHP code field to Views on condition

I think you have not followed a correct way, these are the steps to create a custom field on the basis of value of an existing text field are :

Add a field in any content type on basis of whose value you want to
display a custom field.
Add contents of that content type filling value of newly created
field say its a checkbox having 0 or 1 as its value.
Create a view of that content type.
Add fields and a custom field having some value, say ;

<?php
echo 'Astha Chauhan';
?>

in output code field.

Then add a filter of type Global:PHP and add a filter code
accordingly:

  <?php
      if ( $row->field_test_field == '2') {
       return $row->php;
      }
      else {
       return 'null';
      }
   ?>


Why can't I disable or enable the block cache?

I know you asked "why?" not "can i get around that problem"... but you can get around that problem without removing modules that use hook_node_grants(). Try out the Block Cache Alter module. It allows, among other things, the ability to use block caching even if modules implement hook_node_grants().


Why does my front page only work in one language?

This is the way I use it for a website with one single language in the front end (Spanish), and backend in english.

And..

All nodes are created using default language.


Converting MySQL to db_select with subquery count

Your adding the subquery via a join. you want the subquery to be run as piece of the outermost Select statement, which Drupal 7 SelectQuery cannot do see:

https://stackoverflow.com/questions/20214014/how-do-i-place-a-sub-query-in-a-select-statement-in-drupal7

The easiest way to do this to use db_query (a string) or maybe hook_query_alter after adding a tag to the db_select query and adding in the subquery via a string  later. If you need additional info passed in and out the hook_query_alter then use the metadata options.


I've done this by creating a view only. Please find the attached screenshots.


Difference between Relation and term reference field

In your case you should use https://www.drupal.org/project/entityreference

This one is lighter and does the job without overcomplicating. It simply stores 1 to n relations, which may be used later to display in Views.

Relation - this module is much more advanced and allows you to make:

directional references, example

user A is "boss" of user B

different types of references between same entities, example:

reference type 1:  user C is "friend" of user D

AND
reference type 2:  user C "follows" user D

these references are entities itself, so they are fieldable, could be displayed in Views separately etc.


go to:
/admin/config/content/ckeditor/edit/Advanced (for Filter HTML)
/admin/config/content/ckeditor/edit/Full (for Full HTML)
Then under Advanced Content Filter, select disabled.

If the above does not do it, depending on which one you are using (filter or custom) You need to go to
/admin/config/content/formats/filtered_html
add the <h1> to the limit allowed html list


How to configure drush with Acquia DevDesktop on Windows to access through proxy?

You can follow this tutorial to install drush on windows.
http://www.drupal8.ovh/en/tutoriels/95/install-drush-on-widows

For the proxy you can try:

Controle panel -> System -> Advance settings -> variable -> variable system

PROTOCOLE_proxy  NAME:PASSWORD:HOST:IP

http_proxy http://192.168.100.100:3128

https_proxy http://192.168.100.100:3128

Example from :
http://www.drupal8.ovh/en/tutoriels/208/internet-access-via-proxy


How to add a new element in drupal 7 feed view

Views doesn't provide that functionality, so if you want to configure this via the UI you need to install Views RSS (or another module that provides similar functionality); you don't have another option, apart from writing it yourself.

If you just want to hack something together you can use just manually append your extra elements to the output string, e.g.

function MYMODULE_preprocess_views_view_row_rss(&$vars) {
  // Add an image.
  $node = node_load($vars['row']->nid);
  if ($node) {
    $wrapper = entity_metadata_wrapper('node', $node);
    try {
      $vars['item_elements'] .= '<image>' . $wrapper->field_images[0]->file->url->value() . '</image>';
    }
    catch (\Exception $e) {
      // No need to recover, just means there's no image.
    }
  }
}

But it's not exactly ideal, better to use the purpose-built module.


how to avoid fieldset in drupal date field

Use the latest full release or the 7.x-2.x-dev version of the Date module.

There is an new option Render as a regular field available there:

The option was added at the Make it possible to disable fieldset for date field issue.


How do I implement hook_form_alter() in a module?

Here is a working example I have pulled from a project and altered to have your module name.

Add this at the top of your .module file:

use Drupal\Core\Form\FormStateInterface;

Then copy this in

/**
 * Implements hook_form_alter().
 */
function constellator_form_alter(&$form, FormStateInterface $form_state, $form_id) {

  // Adding custom validation for the welcome page type field.
  if ($form_id == 'node_article_edit_form' || $form_id == 'node_article_form') {
    // Do some stuff.
  }
}

I think most likely what you aren't doing is clearing the Drupal cache to register the hook.  You can click on "clear all caches".  Or better yet, install the drush command line utility and use "drush cr".


Cron timeouts at 60 seconds, but all the related timeouts are set higher

Solved. It was the timeout of the proxy connection to PHP-FPM. It involves going down a rabbit-hole of Apache values and defaults so strap in.

As per ProxyPass the proxy default of connectiontimeout is timeout.

The default value of timeout is ProxyTimeout

The default of ProxyTimeout is the core Apache TimeOut

The default of TimeOut is 60. So there you go.

I set a value of TimeOut 180 in my Virtualhost for the site in question and the import went through.

Now just to wrangle all these values back down to a sensible level now that I know the culprits.


Bootstrap subtheme - theme_menu_link(array $variables) not reacting

I maintain a Bootstrap subtheme that I use for most of my projects and I override theme_menu_link() in my subtheme using the same method with no problem:

/**
 * Overrides bootstrap_menu_link().
 *
 * Resets theme_menu_link() to the default that ships with Drupal. Bootstrap
 * attempts to make every menu with children into a dropdown menu. Remove this
 * function if you want drop down links.
 */
function bootstrap_ignitor_menu_link(array $variables) {
  $element = $variables['element'];
  $sub_menu = '';
  if ($element['#below']) {
    $sub_menu = drupal_render($element['#below']);
  }
  $output = l($element['#title'], $element['#href'], $element['#localized_options']);
  return '<li' . drupal_attributes($element['#attributes']) . '>' . $output . $sub_menu . "</li>\n";
}

You must have a problem somewhere else.


I can do it implementing hook_preprocess_HOOK hook, specifically hook_preprocess_superfish:

/**
 * Implements hook_preprocess_HOOK().
 */
function MODULE_NAME_preprocess_superfish(&$variables) {
  if ($variables['id'] == 'superfish-main-menu') {
    $menu = ($variables['element']['#tree']);
    // ...
  }
}


Since you want to function on a "page level" (outside the content area) what you can do is:

Use hook_preprocess_page
Get the node id being viewed
Query the node using node_load or just your "term field" alone using EntityFieldQuery

This would somehow look like:

Your theme or custom module

// This function is inside my template.php
function YOURTHEME_preprocess_page(&$variables) {
  // This array key is only present when a page is a node page(node/<nid>).
  // If this is set, this contains the node object already.
  if (isset($variables['node'])) {
    $n = $variables['node'];

    // Don't forget to change this also to check if the reference field
    // has at least one reference/target node.
    if (isset($n->body['und'][0])) {
      $variables['site_category'] = 'PARTY! This displays the field we need';
      /**
       * The above line is just an example.
       *
       * You would replace it with the codes to load the target node:
       *   $target_node = node_load($n->field_site_category[......]);
       *
       * Display the title of the target node
       *   $variables['site_category'] = $target_node->title;
       */
    }
  }
}

page.tpl.php

<?php if (isset($site_category)): ?>
  <?php print $site_category; ?>
<?php endif; ?>

I added some screenshots of the outputs:

When viewing a node page

When not viewing a node page

Also to get the array keys inside variables, there is a module called Devel. Install it like any module and use its helper function dsm($your_var). This displays the contents of the variable in a pleasant manner.


I believe there are two ways you can do it:-

In template.php , you can use theme_pager. Then overrite it.
You can make a views template and overrite it. For this just goto advance option in views and search for template suggestion.


How to redirect the user to an external website with POST data?

In D8 for redirection you need to use RedirectResponse Object & thats best way forward. However for improved security the same RedirectResponse object does not allow External URL redirections. For this You may want to use TrustedRedirectResponse. Sample below with assumption that you are trying to post data to the payment getway which can be added as a query string on the URL.

use Drupal\Core\Routing\TrustedRedirectResponse;

public function myController() {
  return new TrustedRedirectResponse($host.'?xyz=abc);
}

PREFERRED

However the above suggestion does has security implications as the data is exposed on the URL. Below solution is a minor tweak from your code.

$response = \Drupal::httpClient()->post($host, [
        'form_params' => $fields,
        'headers' => [
          'Content-type' => 'application/x-www-form-urlencoded',
        ],
    ]);

You can try below if you would like to capture response (If its an XML / JSON)

$response = \Drupal::httpClient()->post($host, [
        'form_params' => $fields,
        'headers' => [
          'Content-type' => 'application/x-www-form-urlencoded',
        ],
    ])->getBody()->getContents();


Custom REST POST resource to accept JSON

Up until Make serialization_class optional (#2419825) issue has been fixed for 8.2.x branch you couldn't get away without creating a custom serialization class which merely passes the provided data to satisfy the requirement for mandatory serialization.

If you need to make it work on Drupal <= 8.1, try the following:

Create a custom normalizer.
Expose it to the system as a service.
Use it as serialization_class for your Rest resource.

modules/mymodule/src/normalizer/JsonDenormalizer.php:

<?php

namespace Drupal\mymodule\normalizer;

use Drupal\serialization\Normalizer\NormalizerBase;
use Symfony\Component\Serializer\Normalizer\DenormalizerInterface;

/**
 * Class JsonDenormalizer
 *
 * @todo Remove this class once https://www.drupal.org/node/2419825 is fixed.
 */
class JsonDenormalizer extends NormalizerBase implements DenormalizerInterface {

  /**
   * The interface or class that this Normalizer supports.
   *
   * @var array
   */
  protected $supportedInterfaceOrClass = array(__CLASS__);

  /**
   * {@inheritdoc}
   */
  public function normalize($object, $format = null, array $context = array()) {
    return parent::normalize($object, $format, $context);
  }

  /**
   * {@inheritdoc}
   */
  public function denormalize($data, $class, $format = NULL, array $context  = array()) {
    return $data;
  }
}

modules/mymodule/mymodule.services.yml:

services:
  # can be removed once https://www.drupal.org/node/2419825 is fixed.
  serializer.normalizer.mymodule.json:
    class: Drupal\mymodule\normalizer\JsonDenormalizer
    tags:
      - { name: normalizer }

mymodule/src/Plugin/rest/resource/SearchAutocompleteResource.php:

/**
 * Provides a resource for search autocomplete.
 *
 * @RestResource(
 *   id = "mymodule:searchautocomplete",
 *   label = @Translation("MyModule: Search Autocomplete"),
 *   serialization_class = "Drupal\mymodule\normalizer\JsonDenormalizer",
 *   uri_paths = {
 *     "canonical" = "/api/v1/search-autocomplete",
 *     "https://www.drupal.org/link-relations/create" = "/api/v1/search-autocomplete"
 *   }
 * )
 */


How to get the referenced node id in a webform?

Make sure that the webform's source entity id can be prepopulated via a URL and the below code should work using $source_entity->id() instead of $source_entity->id

/** @var \Drupal\webform\WebformRequestInterface $request_handler */
$request_handler = \Drupal::service('webform.request');
$source_entity = $request_handler->getCurrentSourceEntity('webform');
$node_id = $source_entity->id();


Drupal 8 function from controller returns html markups only

The error message is not pointing in the right direction. It should say:

"The controller must return a render array"

For example the most basic one:

return array(
  '#markup' => '
This is html markup
',
);

The error message is from symfony, and from the stand point of symfony this is correct. A controller must provide a response, but drupal has extended the response handling to look for render arrays, that are then used the generate a response with the rendered html. If you don't provide a render array, then there is no response and then this error message will come up.


Creating a template file for one specific page created by a custom module

I think you can't pass the single_view_theme as a page callback.

create a new function with something like this:

function single_view_callback($something) {
  return theme('page__single_view', $variables);
}

And in your page callback replace 'single_view_theme' with 'single_view_callback'.


Append html after node content in custom module in Drupal 7

You can use the node view alter hook in your module to add/change your node object:

  This hook is called after the content has been assembled in a structured array and may be used for doing processing which requires that the complete node content structure has been built.

If you have devel enabled, you can dpm($node) inside your node_view_alter function to see the node structure and then you can add to it as needed from the module.


Not able to export nodes from one drupal site to other drupal site?

When using content_sync module, you must set the content_sync directory in your settings.php file.

From module description:

  Set the export directory in settings.php. Similar to configuration management, we want to set the export directory for YAML files using the settings.php file.le:
  Use the variable: $content_directories['sync']
  ie:

global $content_directories;

$content_directories['sync'] = '/../content/sync';

  Note: set $content_directories as global


How do I find the default value or change state of a form element?

public function validateForm(array $form, FormSateInterface $form_state) {
  $element = $form['elementname'];
  $default_value = isset($element['#default_value']) ? $element['#default_value'] : NULL;
  $value = $form_state->getValue($element['#parents']);
  $changed = $default_value == $value;
    if ($changed) {
    // This is stupid, it's just an example.
    $form_state->setError($element, $this->t("The value has changed."));
    }
}


Request a page - as admin - via command line to build up cache

Load the page via the cron (maybe 5 mins after deleting the cache) using wget. You'll need to set this up on the server as opposed to through the Drupal UI.

This won't hit the page as admin but I'm not sure what value that adds. You just need the caches to be built so hitting as an anonymous user will do this.

Also checkout hook_drush_command() for creating your own Drush functions (good tutorial here).


How to add a class to a checkbox in a form?

Sure.  You can copy theme_checkbox() from includes/form.inc:

function theme_checkbox($variables) {
  $element = $variables['element'];
  $element['#attributes']['type'] = 'checkbox';
  element_set_attributes($element, array('id', 'name', '#return_value' => 'value'));

  // Unchecked checkbox has #value of integer 0.
  if (!empty($element['#checked'])) {
    $element['#attributes']['checked'] = 'checked';
  }
  _form_set_class($element, array('form-checkbox'));

  return '<input' . drupal_attributes($element['#attributes']) . ' />';
}

into your theme's template.php file and rename it accordingly:

function YOURTHEME_checkbox($variables) {
  $element = $variables['element'];
  $element['#attributes']['type'] = 'checkbox';
  element_set_attributes($element, array('id', 'name', '#return_value' => 'value'));

  // Unchecked checkbox has #value of integer 0.
  if (!empty($element['#checked'])) {
    $element['#attributes']['checked'] = 'checked';
  }
  _form_set_class($element, array('form-checkbox', 'checkradios')); // <-- checkradios added in here

  return '<input' . drupal_attributes($element['#attributes']) . ' />';
}

along with the addition of the checkradios class and this will be added to each checkbox.

Now, if you want to restrict it to certain fields, you can look inside $element and add some additional logic to this.


I think your problem is due to a misunderstanding of how Drupal forms work.

Drupal uses the PRG pattern for form submissions. That means for you, that you can't set form elements in the submit handler.

You can either set a message using drupal_set_message() which will be displayed on the next page.

Or you can instruct the form to rebuild, which will result in a redirect to the same form page that you came from with your form builder being called again. In the form builder function you can then check if the form has previously been submitted and then build the form accordingly. This second option is usually referred to as a multistep form. Have a look at this blog post for an example: http://davidsonj.com/blog/how-create-multi-step-form-drupal-7


I have achieved this goal in the past for Drupal 7 using a bit of custom code.

Set the cookie lifetime and server session timeout to the larger of the 2 numbers, in your case I guess that's 2 years.
Write a custom script (e.g. in drush) that will find stale sessions and delete them.

For item #2 for you that means it has to find the Internal users with a short lifetime and delete their session if the sessions.timestamp is beyond a limit. According to system.install, that column contains The Unix timestamp when this session last requested a page.

The limit of your sessions table depends on database server hardware, but my experience on a fairly large site is that you can have millions of sessions records and it's not a huge problem for performance. That said, I also found that user interaction followed a power-curve. 90% of users who committed and got engaged did so within the first day. 95% were within the first week and going out to 3 months got up to 98%. Saving the cookie data beyond that for what amounts to a rounding error is generally not super useful.

I found that trying to do a sql delete directly does not scale well. Instead, I wrote a loop that would find records to delete and then run individual delete queries with a condition WHERE sid = :sid so it was using a primary key. This had the greatest performance while having minimal impact. You can even run the select against a read-replica database to reduce the performance impact further. For my scenario, 1 class of users who had not been active in the last hour were logged out so that job ran every hour. The other class of users who got deleted after 3 months would be deleted in a job that ran overnight as it performed more operations and had more impact on server resources.

If you truly need to store session data for 2 years that's fine. However, you might consider if you can instead store the data in the cookie instead of in the session. That way your sessions table stays lightweight and you can still do tracking of the user inside the cookie. For example, if your goal is to track a channel that brought the user to the site you could simply store that channel information in their cookie instead of the $_SESSION. If you can avoid generating/keeping a session then the scalability problem goes away.

Beware that many spiders and bots generate significant traffic and are poorly behaved a it relates to sessions: they may discard cookies, effectively generating a new session for every page request if your app does that. You can either place a bot-blocking/caching network in front (like Cloudflare) or just plan to periodically analyze the sessions table and delete sessions from these bots based on something like IP address.

I would not suggest memcache for this purpose, but instead a sql database (perhaps a dedicated database instance) or Redis. Memcache is optimize as a temporary data store. You purposefully want a persistent data store, which sql or redis do provide.


viewing fields with field_view_field after EntityFieldQuery doesn't work

Your code will only work if there is only a single value returned by your EFQ. Whatever you want to do with the nodes, you need to put in a foreach():

$nodestoload = $query->execute();
foreach ($nodestoload as $loaded_node) {
  $nid = array_keys($loaded_node['node']);
  $node = entity_load('node', $nid);
  print_r($node);
  $output = field_view_field('node', $node, 'suppliername');
}


Looking for a function that searches for nodes

The closest thing that you get is EntityFieldQuery, which will allow you to construct a query that will yield the nodes that match the conditions.


Update script fails due to Service capacity

Attempt to answer your questions ...

  Has anyone seen this one before? If so how do I solve it?

I've never seen this error before. But what I don't see anywhere in your question is that you FIRST disabled all modules, prior to upgrading Drupal core. And that is problably where your error originates from.

So if you have not done that, try doing so now as a first step. Note each of the modules you're disabling, so that afterwards you know which one to re-enable again. Note "all" is more then just the 18 modules you mentioned that needed updating (so also those modules which do not require any update).

After all these modules are disabled, try to upgrade Drupal Core. I'd expect that upgrading core then should work just fine.

  If not, can I run the other 18 pending updates somehow?

I would NOT try to do that. Instead first make sure core is upgraded, as explained in my prior item.

After core upgrade completed fine, re-enable all modules again that you disabled to complete the core upgrade. From then on the 18 pending updates should appear also again (of course). Then perform the update of each of those 18 modules, one by one.

  If not, how harmfull is it if I don't run update.php?

NOT running update.php is not something I would consider. In other words: if your Drupal installation shows messages that updates are pending, you better apply them ASAP.

Does this help somehow?

PS: worst case (if everything else goes wrong): restore from your last backup (you have that, right???). Then apply the steps I described above. I'd assume you would not run into similar errors anymore.


What is "alias" in db_select() function?

In Drupal database API alias means exactly the same thing it means in SQL world - short name assigned to table or field to simplify further referencing it during this one query. Some table names are pretty long, and you can't always count on Drupal to be able to resolve prefixes, so aliasing mystupidlongprefix_field_revision_field_some_pretty_long_name_for_field_containing_a_gallery with something simple, like frg (field revision gallery), or something other you will recognize when you will read this query, both make it way easier and faster to write and understand code, and also allows you to use this table for example in conditions, where using {table_name} syntax for automatic prefixes is not always feasible.


Using hook_user_format_name_alter(), how to change username on user paths?

This is the title callback you have in core for /user/UID:

UserController::userTitle

/**
   * Route title callback.
   *
   * @param \Drupal\user\UserInterface $user
   *   The user account.
   *
   * @return string|array
   *   The user account name as a render array or an empty string if $user is
   *   NULL.
   */
  public function userTitle(UserInterface $user = NULL) {
    return $user ? ['#markup' => $user->getUsername(), '#allowed_tags' => Xss::getHtmlTagList()] : '';
  }

Unfortunately this uses the method getUsername(), which doesn't invoke hook_user_format_name_alter().

You need a custom title callback, where you get the username with the method $user->getDisplayName(), which does invoke the hook.

Then change the title callback in the user route entity.user.canonical:

$route->setDefault('_title_callback', '\Drupal\mymodule\Controller\MyController::userTitle');

See https://www.drupal.org/docs/8/api/routing-system/altering-existing-routes-and-adding-new-routes-based-on-dynamic-ones.

Had the feeling this can't be right and searched for an issue: https://www.drupal.org/node/2648420. This is committed for D8.5. Until then you can apply the patch, which simply replaces getUserName() with getDisplayName() in UserController.


How to show link upload option on statuses updates form which converts to embedded content?

So do you want it to act like Facebook aka pulling in content from the link automadgicly?
If so then I did have some success with a alter / Ajax callback and then file read contents and pulling in an image tag at appropriate size was not the best solution but look in to https://stackoverflow.com/questions/6476212/save-image-from-url-with-curl-php

And file_get_contents()


Displayng menu description under main-menu links in Drupal 7

It worked when I used the Main Menu block in header region.

It wasn't working before because the Main Menu was directly being output in the page.tpl.php file by a call to theme('links_system_main_menu'). I followed the instructions on "Descriptions under main menu" at the Fusion Themes forum, and enabled the Main Menu block to get the desired effect.


Site upgrade to D7 using drush stuck on the "Run update.php" step

You may get the information you need by running drush with the verbose flag: -v or --verbose.


Based on your comment about the 500 error and the menu entry problems, I suspect that the problem isn't really with the Devel module, but rather with your server.

Take a look at your Apache error_log to see what is causing the 500.  Following the steps for fixing a WSOD may also help.

A total guess is that you are running out of memory, and this is happening during the menu rebuild phase when you have an empty cache.  Enabling the Devel module likely was just the tipping point and now you are seeing memory problems.  You can try increasing the memory_limit and see if that fixes things.  But, you really do need to look at the error logs and find the true cause of the 500 errors.


"Simple FB Connect" module return page not found when user path replace with another module called "Rename Admin Paths"

after 2 days, i solved my problem by change 'user/simple-fb-connect' to 'connection/simple-fb-connect' and its now working.


The Crumbs module will do what you are looking for. It allows you to set the pattern for crumb generation. In your case the pattern for an article would be something along the lines of

[node:field_tags]

Home is automatically generated so this will give you a crumb path of: Home >> Taxonomy Term

If you want to include the article title, then you would just add [node:title] to the crumb pattern.

[node:field_tags]/[node:title]

Which would produce: Home >> Taxonomy Term >> Title


Ok so it was a bit weird how it all came together, I restarted the nginx and that didn't do anythig.

I opened the default config file for nginx and just saved it without making changes and restarted the service.

After than I went from a 404 error to a 500 error.

To fix the 500 error I changed a line in my default from this:

 try_files $uri $uri/ /index.html;

To this:

 try_files $uri/ $uri /index.php?$query_string;

I saved the config file and restarted nginx and it worked!


Make a picture display images if a CCK checkbox is checked

You will have to rewrite the results of your fields.  NodeOne has some videos that describes what to do and I think this one http://nodeone.se/blogg/learn-views-with-nodeone-part-17-rewriting-fields will have the info you need.

Short answer is that you will configure field > Rewrite Results > Rewrite the output of this field and then use the "REPLACEMENT PATTERNS" that will show only the fields that are available (can't use fields that come after in the list).

You can use [field_NAME]_icon.png where the [field_NAME] will either be black or grey to load the correct icon.  This would work if Black and Grey were the allowed values of a radio button for each field.  Checkboxes should be similar, but I didn't need to use them for my issue.


How to change a fields text_format for admin users, and show a plain_text for anonymous users?

I'm afraid what I assume you are trying to accomplish just isn't available to you because Drupal saves the text entered in a field unfiltered/as is; it then filters it when it is actually displayed or rendered.

So, if you enter for example:

Hello world <some html tag>blah blah blah</end some html tag>

in a text field, that exact content will be saved.

Then, when the entity is displayed, Drupal will look at the text format and if it's plain_text, it will output

Hello world blah blah blah

but if the text format is full html it will output (with minor exceptions)

Hello world <some html tag>blah blah blah</end some html tag>

but once again, in both instances whatever the user inputs will be stored in the database.

Of course, you could create a field that toggles some sort of "display the body with full html after an admin has verified its contents" that would be looked at and if set, display the entity with that field using full html, but until set, would just display it in plain text.


If you want to see the result of your code in THEMENAME_preprocess_field() you have to put {{ promo_date }} in a field.html.twig.

But in your question you asked about the page.html.twig. To access the field value in this template, you can use the node object, which is preloaded in the page template. But only if there is a node in the url of your page. Otherwise this will return an empty string:

{{ node.field_date.value }}


I'm sure you could do this in hook_field_widget_form() (which I'm guessing is where your current code is) by just adding a child element to your existing element, e.g.

$element['text'] = array(
  '#type' => 'textfield',
  '#title' => 'Title',
  // etc...
);

If that doesn't work I know it will definitely work if you use hook_field_widget_form_alter().

For example, the following is a small function which enables the alt field for an Image field type using the Media Selector widget (for some reason it's not enabled by default):

function media_image_attributes_field_widget_form_alter(&$element, &$form_state, &$context) {
  if ($context['field']['type'] == 'image') {
    $element['alt'] = array(
      '#type' => 'textfield',
      '#title' => 'Image Description',
      '#weight' => 10000,
      '#default_value' => count($element['#default_value']) ? $element['#default_value']['alt'] : ''
    );
  }
}

As far as the ajax functionality goes, I think you're definitely going along the right lines. I think the Field Example module in Examples has some sample code which might help.


First you need to add User relationship, “Content: Author” for example.
After that you will be able to add new relationship “User: Profile” on base of User relationship.

Now you can add fields from user and user profile. You must not forget that SQL query becomes heavier with each new relationship.


After programmatically creating a token, it does not get overridden

Where are you using the token? Drupal may be caching information at a higher level (like the filtered output of a node, for example) and only calling the token generation code once.


How do I get the path for the private filesystem?

The problem is solved.

I had a problem with the path, so the correct path is

$settings['file_private_path'] = '/Users/adriancid/private-drupal-folder';

And I give permissions to write in the folder to the webserver.


How to theme each field of exposed filter from Views?

You can try to catch it with hook_form_alter(): $form_id is views_exposed_form, and $form contains all the values.

$form['field_custom']['#options'] = array(
  'group1' => array('key11' => 'value11', 'key12' => 'value12'),
  'group2' => array('key21' => 'value21', 'key22' => 'value22' ),
);


Views Data Export: How can you include a raw database column?

Table column will not be automatically imported as available views field. Any extra field you want to use in views. You can define it with hook_views_data. Anyway, I can find pretty much fields are ready to use.


How to keep the non mapped paragraphs during migrations?

I have created a custom source plugin for this to achieve.
Here is my source plugin code.
class MYSOURCECSV extends CSV {

  /**
   * {@inheritdoc}
   */
  public function prepareRow(Row $row) {
    $database = \Drupal::database();
    $table = 'migrate_map_migration_id';

    // The migration removes the manually created entities from the system,
    // that are not present in the migration source. But we want them to be
    // ignored during the migration.
    if ($database->schema()->tableExists($table)) {
      $organisations = [];

      try {
        $results = $database->select($table, 'mmt')
          ->fields('mmt', ['destid1', 'destid2'])
          ->condition('sourceid1', $row->getSourceProperty('personal_number'))
          ->execute()
          ->fetchAll();

        if (!empty($results)) {
          foreach ($results as $result) {
            $paragraph_id = $result->destid1;

            $paragraph = \Drupal::entityTypeManager()

  ->getStorage('paragraph')
          ->load($paragraph_id);

        if ($paragraph instanceof ParagraphInterface) {
          $node = $paragraph->getParentEntity();

          // If paragraph is already attached to a node. Get the ids from
          // the node.
          if ($node instanceof NodeInterface) {
            $organisations = $node->get('my_paragraph_field')->getValue();

            if ($key = array_search($paragraph_id, array_column($paragraphs, 'target_id'))) {
              $paragraphs[$key]['target_revision_id'] = $result->destid2;
            }
          }
          else {
            $paragraphs[] = [
              'target_id' => $result->destid1,
              'target_revision_id' => $result->destid2,
            ];
          }
        }
      }
    }

    $row->setSourceProperty('my_paragraph_field', $paragraphs);
  }
  catch (Exception $exception) {
    \Drupal::logger('my_module')->error($exception->getMessage());
  }
}

parent::prepareRow($row);
  }

}

And then change the paragraph field mapping in the  migration file to:
my_paragraph_field:
    - plugin: sub_process
      source: organisations
      process:
        target_id: target_id
        target_revision_id: target_revision_id


It seems that this could provide an answer to your question :

$fid = theme_get_setting('footer_logo');
$image_url = file_create_url(file_load($fid)->uri);

(but I didn't test it).


Block won't appear on specific language pages

Disregard the question above. After my 'frustration post' I realized the most obvious thing. It wasn't Showing French because I didn't have French translations... I had FR-CA - French CANADIAN translations.

Doh!


How can I restrict access to a static HTML page served from a subfolder of my site to authenticated users only?

One of the options to achieve this is using drupal's private file system. Drupal core out-of-box provides a way to access private files in a secured URL. Here are the steps:

upload the directory (e.g. foo-bar) to drupal's private file scheme. (you can find it under  Administration->Configuration->Media->File system)
Create a hook_file_download($uri) in a custom module and check for necessary access conditions:

function mymodule_file_download($uri) {

  // Check user permission only if the requested
  // file is under foo-bar directory.
  if (strpos($uri, 'foo-bar') !== FALSE) {
    if (\Drupal::currentUser()->isAnonymous()) {
      return -1
    }

    // Return a header to inform access is granted.
    return ['Cache-Control' => 'private'];
  }
}

Now the directory is available for authenticated users at www.example.com/system/files/foo-bar/index.html.

Check Drupal\system\FileDownloadController::download() for more details

This would work for both Drupal 8 & 9. I haven't checked 7.


How add markup and prefix / suffix for computed field

I don't know where your variable $entity_field_item comes from, but you can generally add additional markup in at least three different ways:

1. Adding #prefix and #suffix to the fields render array using a preprocess function:

function mytheme_preprocess_field(&$variables, $hook) {
  $element = $variables['element'];
  if ($element['#field_name'] == 'field_myfield') {
    $variables['items'][0]['#prefix'] = '
';
    $variables['items'][0]['#suffix'] = 'Count
';
  }
}

2. Adding #prefix and #suffix in hook_node_view():

$node->content['field_myfield'][0]['#prefix'] = '
';
$node->content['field_myfield'][0]['#suffix'] = 'Count
';

3. Adding a new item to the $content array:

$node->content['my_custom_output'] = array(
  '#type' => 'markup',
  '#markup' => $entity_field_item['value'],
  '#prefix' => '
',
  '#suffix' => 'Count
',
);


How to import and merge existing site from svn to git?

I don't see any advantages to being "in sync" with drupal git repo unless you're "chasing head."

I would just convert your current SVN repo to git. You can create a new branch that tracks drupal git and merge that branch in occasionally (if your directory structures match) or just download the final release packages and copy them into your directory and commit the changes.