Insert a countdown in each node based on a pre-existing date field

I assume you have two fields in one content type - countdown_date and expiration_date. Both values user has to insert manually. And after submit action, you want to assign expiration date to both fields, yes?

Read about hook_node_submit(). In your MYMODULE_node_submit($node, $form, &$form_state) you can check the type of content, then assign expiration_date to countdown_date. This method works with save and preview's action.

For more detailed answer I need more details about these fields.


Multiple blocks on single page, pager issue

You can configure each block's pager to have a different pager ID and then they will/should only update the one you clicked on.


How can I filter users within a user-configurable range in Views?

Install sandbox project Views arguments in filters
Add four contextual filters to your user view:

User:Uid, hide view when filter not available, Exclude (you will send in the user's own uid and exclude him from the result as you do not want him to be matched against himself)

Global:Null, hide view when filter not available, and give it an administrative title of 'current age'. (You will send it the current user's age as a param).

Global:Null, hide view when filter not available, and give it an administrative title of 'min age'. (You will send it the current user's min age preference as a param).

Global:Null, hide view when filter not available, and give it an administrative title of 'max age'. (You will send it the current user's max age preference as a param).

Then add normal filters as follows:

That should take care of the view, and you now just have to construct a link to add the parameters manually, or override a view hook to do so. Possible candidate would be hook_views_pre_view where you have direct access to args param, but on other hooks it should be available on the $view object.
Something like this code will work, and you can just add your own defensive programming and substitute where appropriate.
function MYMODULE_views_pre_view(&$view, &$display_id, &$args) {
  if ($view->name == "compatible" &&  $display_id == "page" && user_is_logged_in() && count($args) != 4) {
    global $user;
    $account  = user_load($user->uid);
    $age = field_get_items("user", $account, "field_age");
    $min_age = field_get_items("user", $account, "field_min_age");
    $max_age = field_get_items("user", $account, "field_max_age");
    $args = array(
      $account->uid,
      $age[0]['value'],
      $min_age[0]['value'],
      $max_age[0]['value']
    );
  }
}


How to block (or redirect) external image source?

I presume you are allowing the uploading and embedding of images via the WYSIWYG. That being the case you need to write a text filter and apply it to the text format the users are allowed to use (Filtered HTML for example).
http://local.example.com/admin/config/content/formats/filtered_html

Have a look at the Examples module for how to do that.

filter_example  Defining an input filter

If you're not allowing them to upload and embed via the WYSIWYG (but uploading via a field for example) you could simply remove img from the permitted tags in your Limit allowed HTML tags filter.


You could use Organic groups.

In that case, every agency would be a group with a group administrator that could set the users that are part of that agency. Every agency could have its own content, which would be created from the users that are associated with the agency. A user of another agency would not be able to create content for another agency, if not in the case the user is member of both the agencies.


create chains of views joins so one view can 'see' across more than one join

I added a relationship to the mix and that's opened up two extra sets of fields ('c' and 'd') I can't explain why, I think it's something to do with the joins that were already setup on these base tables. This then meant that when I bridged them with the relationship it opened it all up.

example:

$data['a']['a_id']['relationship']['handler'] = 'views_handler_relationship';
$data['a']['a_id']['relationship']['base'] = 'b';
$data['a']['a_id']['relationship']['base field'] = 'references_a_id';
    (... etc.)


How do I add JavaScript to the administrative area?

@kiamlaluno explain answer very good way

Using a module, you can follow two methods:

Implementing hook_init()
Implementing hook_form_alter()
The first method would allow you to add the extra JavaScript (or CSS) files to any administration pages, while the second method would allow you to add those files only to pages containing forms.

function mymodule_init() {
  if (arg(0) == 'admin') {
    $path = drupal_get_path('module', 'mymodule');
    drupal_add_js($path . '/mymodule.js');
    drupal_add_css($path . '/mymodule.css');
  }
}

function mymodule_form_alter(&$form, &$form_state, $form_id) {
  if (arg(0) == 'admin') {
    $path = drupal_get_path('module', 'mymodule');
    $form['#attached']['css'][] = $path . '/mymodule.css';
    $form['#attached']['js'][] = $path . '/mymodule.js';
  }
}

Replace "mymodule" with the short name of your module; replace "mymodule.js" and "mymodule.css" with the actual names of the JavaScript and CSS files.

more detials


Administer simplenews subscriptions with views

Answer for 2016 and Drupal 7.  Simplenews module does now include bulk operations.  Simplenews has Views integration built in.  It does not come with a pre-defined view, so you have to create one.

Here is an export of a view that shows when the subscriber was added and by what means.  However Simplenews does not current provide VBO integration to allow a bulk action.

  $view = new view();
  $view->name = 'newsletter_subscriptions';
  $view->description = '';
  $view->tag = 'default';
  $view->base_table = 'simplenews_subscription';
  $view->human_name = 'Newsletter subscriptions';
  $view->core = 7;
  $view->api_version = '3.0';
  $view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

  /* Display: Master */
  $handler = $view->new_display('default', 'Master', 'default');
  $handler->display->display_options['use_more_always'] = FALSE;
  $handler->display->display_options['access']['type'] = 'none';
  $handler->display->display_options['cache']['type'] = 'none';
  $handler->display->display_options['query']['type'] = 'views_query';
  $handler->display->display_options['exposed_form']['type'] = 'basic';
  $handler->display->display_options['pager']['type'] = 'full';
  $handler->display->display_options['pager']['options']['items_per_page'] = '25';
  $handler->display->display_options['style_plugin'] = 'table';
  $handler->display->display_options['style_options']['columns'] = array(
    'mail' => 'mail',
    'name' => 'name',
    'timestamp' => 'timestamp',
    'activated' => 'activated',
    'source' => 'source',
    'status' => 'status',
    );
  $handler->display->display_options['style_options']['default'] = 'mail';
  $handler->display->display_options['style_options']['info'] = array(
    'mail' => array(
      'sortable' => 1,
      'default_sort_order' => 'asc',
      'align' => '',
      'separator' => '',
      'empty_column' => 0,
      ),
    'name' => array(
      'sortable' => 1,
      'default_sort_order' => 'asc',
      'align' => '',
      'separator' => '',
      'empty_column' => 0,
      ),
    'timestamp' => array(
      'sortable' => 1,
      'default_sort_order' => 'asc',
      'align' => '',
      'separator' => '',
      'empty_column' => 0,
      ),
    'activated' => array(
      'sortable' => 1,
      'default_sort_order' => 'asc',
      'align' => '',
      'separator' => '',
      'empty_column' => 0,
      ),
    'source' => array(
      'sortable' => 1,
      'default_sort_order' => 'asc',
      'align' => '',
      'separator' => '',
      'empty_column' => 0,
      ),
    'status' => array(
      'sortable' => 1,
      'default_sort_order' => 'asc',
      'align' => '',
      'separator' => '',
      'empty_column' => 0,
      ),
    );
  /* Relationship: Simplenews subscription: Subscriber ID */
  $handler->display->display_options['relationships']['snid']['id'] = 'snid';
  $handler->display->display_options['relationships']['snid']['table'] = 'simplenews_subscription';
  $handler->display->display_options['relationships']['snid']['field'] = 'snid';
  /* Relationship: Simplenews subscription: Term ID */
  $handler->display->display_options['relationships']['tid']['id'] = 'tid';
  $handler->display->display_options['relationships']['tid']['table'] = 'simplenews_subscription';
  $handler->display->display_options['relationships']['tid']['field'] = 'tid';
  $handler->display->display_options['relationships']['tid']['label'] = 'Newsletter';
  /* Field: Simplenews subscriber: Subscriber */
  $handler->display->display_options['fields']['mail']['id'] = 'mail';
  $handler->display->display_options['fields']['mail']['table'] = 'simplenews_subscriber';
  $handler->display->display_options['fields']['mail']['field'] = 'mail';
  $handler->display->display_options['fields']['mail']['relationship'] = 'snid';
  /* Field: Taxonomy term: Name */
  $handler->display->display_options['fields']['name']['id'] = 'name';
  $handler->display->display_options['fields']['name']['table'] = 'taxonomy_term_data';
  $handler->display->display_options['fields']['name']['field'] = 'name';
  $handler->display->display_options['fields']['name']['relationship'] = 'tid';
  $handler->display->display_options['fields']['name']['label'] = 'Newsletter';
  /* Field: Simplenews subscription: Timestamp */
  $handler->display->display_options['fields']['timestamp']['id'] = 'timestamp';
  $handler->display->display_options['fields']['timestamp']['table'] = 'simplenews_subscription';
  $handler->display->display_options['fields']['timestamp']['field'] = 'timestamp';
  $handler->display->display_options['fields']['timestamp']['date_format'] = 'short';
  $handler->display->display_options['fields']['timestamp']['second_date_format'] = 'long';
  /* Field: Simplenews subscription: Source */
  $handler->display->display_options['fields']['source']['id'] = 'source';
  $handler->display->display_options['fields']['source']['table'] = 'simplenews_subscription';
  $handler->display->display_options['fields']['source']['field'] = 'source';
  /* Field: Simplenews subscriber: Activated */
  $handler->display->display_options['fields']['activated']['id'] = 'activated';
  $handler->display->display_options['fields']['activated']['table'] = 'simplenews_subscriber';
  $handler->display->display_options['fields']['activated']['field'] = 'activated';
  $handler->display->display_options['fields']['activated']['relationship'] = 'snid';
  $handler->display->display_options['fields']['activated']['type'] = 'unicode-yes-no';
  $handler->display->display_options['fields']['activated']['not'] = 0;
  /* Field: Simplenews subscription: Status */
  $handler->display->display_options['fields']['status']['id'] = 'status';
  $handler->display->display_options['fields']['status']['table'] = 'simplenews_subscription';
  $handler->display->display_options['fields']['status']['field'] = 'status';
  $handler->display->display_options['fields']['status']['type'] = 'unicode-yes-no';
  $handler->display->display_options['fields']['status']['not'] = 0;
  /* Filter criterion: Simplenews subscriber: Subscriber */
  $handler->display->display_options['filters']['mail']['id'] = 'mail';
  $handler->display->display_options['filters']['mail']['table'] = 'simplenews_subscriber';
  $handler->display->display_options['filters']['mail']['field'] = 'mail';
  $handler->display->display_options['filters']['mail']['relationship'] = 'snid';
  $handler->display->display_options['filters']['mail']['operator'] = 'contains';
  $handler->display->display_options['filters']['mail']['group'] = 1;
  $handler->display->display_options['filters']['mail']['exposed'] = TRUE;
  $handler->display->display_options['filters']['mail']['expose']['operator_id'] = 'mail_op';
  $handler->display->display_options['filters']['mail']['expose']['label'] = 'Subscriber';
  $handler->display->display_options['filters']['mail']['expose']['operator'] = 'mail_op';
  $handler->display->display_options['filters']['mail']['expose']['identifier'] = 'mail';
  $handler->display->display_options['filters']['mail']['expose']['remember_roles'] = array(
    2 => '2',
    1 => 0,
    3 => 0,
    4 => 0,
    );
  /* Filter criterion: Taxonomy term: Term */
  $handler->display->display_options['filters']['tid']['id'] = 'tid';
  $handler->display->display_options['filters']['tid']['table'] = 'taxonomy_term_data';
  $handler->display->display_options['filters']['tid']['field'] = 'tid';
  $handler->display->display_options['filters']['tid']['relationship'] = 'tid';
  $handler->display->display_options['filters']['tid']['group'] = 1;
  $handler->display->display_options['filters']['tid']['exposed'] = TRUE;
  $handler->display->display_options['filters']['tid']['expose']['operator_id'] = 'tid_op';
  $handler->display->display_options['filters']['tid']['expose']['label'] = 'Newsletter';
  $handler->display->display_options['filters']['tid']['expose']['operator'] = 'tid_op';
  $handler->display->display_options['filters']['tid']['expose']['identifier'] = 'tid';
  $handler->display->display_options['filters']['tid']['expose']['remember_roles'] = array(
    2 => '2',
    1 => 0,
    3 => 0,
    4 => 0,
    );
  $handler->display->display_options['filters']['tid']['type'] = 'select';
  $handler->display->display_options['filters']['tid']['vocabulary'] = 'newsletter';
  /* Filter criterion: Simplenews subscriber: Activated */
  $handler->display->display_options['filters']['activated']['id'] = 'activated';
  $handler->display->display_options['filters']['activated']['table'] = 'simplenews_subscriber';
  $handler->display->display_options['filters']['activated']['field'] = 'activated';
  $handler->display->display_options['filters']['activated']['relationship'] = 'snid';
  $handler->display->display_options['filters']['activated']['group'] = 1;
  $handler->display->display_options['filters']['activated']['exposed'] = TRUE;
  $handler->display->display_options['filters']['activated']['expose']['operator_id'] = '';
  $handler->display->display_options['filters']['activated']['expose']['label'] = 'Activated';
  $handler->display->display_options['filters']['activated']['expose']['operator'] = 'activated_op';
  $handler->display->display_options['filters']['activated']['expose']['identifier'] = 'activated';
  $handler->display->display_options['filters']['activated']['expose']['remember_roles'] = array(
    2 => '2',
    1 => 0,
    3 => 0,
    4 => 0,
    );

  /* Display: Page */
  $handler = $view->new_display('page', 'Page', 'page');
  $handler->display->display_options['path'] = 'newsletter-subscriptions';
  $handler->display->display_options['menu']['type'] = 'normal';
  $handler->display->display_options['menu']['title'] = 'Newlsetter subscriptions';
  $handler->display->display_options['menu']['weight'] = '0';
  $handler->display->display_options['menu']['context'] = 0;
  $handler->display->display_options['menu']['context_only_inline'] = 0;


Drupal 7 Calendar - How do you modify link from day number?

The day page is generated by the day display of the view generated by the calendar module. You can customize this display as much as as you want - add header, footer, embed an attachment view, or otherwise enhance it:

You can disable the day display if you don't want the links at all.

Replacing it with another page would be much harder, but it might be possible using the panels module.


Views: Display filters as a HTML UL list of links with clean mark up

I would also go for step 3 and you really need JS for that option. Another option is, structure the links as it looks when you do a search like so..

// Merge the option name or key into the link
$link = "your-view?category=" . $select_option;
// Create the link
$somearrayforULlist[] = l($select_option, $link);

So when you click one of the links, it would reload the page and your view will use the filter values in the URL in your form.


How to correctly add Google AMP .js files to my theme

Add the AMP component JS in the <head> section of your document, then it will be ok.

<script async custom-element="amp-sidebar" src="https://cdn.ampproject.org/v0/amp-sidebar-0.1.js"></script>

  Extended components are loaded by including a  tag in the head of the document  https://www.ampproject.org/tr/docs/reference/spec


Add class to template based on boolean field

You have written wrong logic in if statement. Correct way is following:

 $class = NULL;
 if (isset($node->field_boolean_field[LANGUAGE_NONE][0]['value']) && $node->field_boolean_field[LANGUAGE_NONE][0]['value'] == 1 ) :
        $class = 'this-is-the-class';
 endif;


How to provide content type in module for Drupal 8?

For a module name my_module and a content type called awesome_page, the directory structure would look like:

my_module/

my_module.info.yml
config/install/

node.type.awesome_page.yml

And the file contents would be:

my_module.info.yml:

name: Awesome page content
type: module
description: 'Add awesome content type.'
core: 8.x
dependencies:
  - node

node.type.awesome_page.yml:

type: awesome_page
name: 'Awesome page'
description: 'Awesome pages are a little better than other pages.'
help: ''
new_revision: false
display_submitted: true
preview_mode: 1
status: true
langcode: en

For several other examples, find all modules in core that provide new content types: find . -iname "node.type*"


I'm using this one to swith and send a query

in the settings.php add

databases['customer_db']['default'] = [
  'driver' => 'pgsql',
  'database' => 'drupal',
  'username' => 'drupal',
  'password' => 'drupal',
  'host' => 'xx.xx.xx.xx',
  'port' => '5432',
  'prefix' => '',
  'namespace' => 'Drupal\\Core\\Database\\Driver\\pgsql',
];

Then use when it's necesary

$db = \Drupal\Core\Database\Database::getConnection('default', 'customer_db');
print_r($db->databaseType());
$query = $db->query("SELECT * FROM customer");
...


Hide the content while the current user has no access on

hook_query_alter() serves this purpose.

The exact query alter you want looks like this:

function modulename_query_node_access_alter(QueryAlterableInterface $query) {
  // Obtain node, if needed
  $node = $query->getMetaData('node');

  // Do some calculations

  // Add condition
  $query->condition( /* your custom conditions here */ );
}

More details on Query alteration documentation page.


How to link to a page view from a template file?

I would recommend you to use l function to build links in Drupal.

  <?php print l(t('Back to blog'), 'node/22'); ?>

I see Content administration page on you screenshot. If you want to build link to this page you may use next piece of code

  <?php print l(t('Content'), 'admin/content'); ?>


'After update' event firing when node is deleted

Have you tried adding a rules condition for the published status of the updated node? That should stop the rule from firing.


Better Exposed Filters: filter options display

You have to use javascript like show/hide jquery plugin/scripts show/hide jquery plugin/scripts  . just take the id of dropdown list and then apply jquery where you want. include jquery script where you mostly write. its upto you.


How to download from private// following a link?

Thanks to @Kevin, I updated my code to

function amap_file_download($uri) {

  $sFileName =  \Drupal::service('file_system')->basename($uri);
  return array(
      'Content-disposition' => 'attachment; filename="' . $sFileName . '"',
  );

}

And it works!


How to inspected the file system to investigate if the image was uploaded

If your file is not appearing after an upload via the field api then you might want to check if your files directory is writable by apache. Typically this would be sites/default/files.

NOTE: sites/default/files should ONLY be writable by apache and nothing else.


Views, Views-Slideshow, and Paging in Drupal 7

(1) Required Modules (Version: Drupal7.0)

Views
Views Slideshow
Chaos tool suite
Libraries
Link Field
Token

(2) Install the Modules

In Drupal7 you can install modules from the admin section, but I still feel this new feature doesn't have any meaning, because we have to search for the module link in the Druapl site and then copy paste into the admin module installation area, really crazy. It would have been so good if they would have made it something like wordpress a small search feasture. Anyway I just gonna download and istall it in the old way (I still recommend this old way).

Download all the modules from Drupal site and install in the directory yoursitename/sites/all/modules.
Go to http://www.yoursitename.com/node#overlay=admin/modules and enable these modules as below;

(1) Views (2) Views UI (3) Views Slideshow (4) Views Slideshow: Cycle (5) Chaos tools (6) Link (7) Libraries (8) Token (Optional)
(3) Create Image Cache

In Drupal7 imagecache is part of core module and is named as Image styles. So let's create two image cache from here, one for the full size slider image and other for the thumbnail image. In this tutorial I use 935x293 (pixels) dimension for the full size slider image and 210x100 (pixels) dimension for the thumbnail image. Note: These configurations csn be defered depends on your needs.

Fullsize Slider image settings

Go to http://www.yoursitename.com/node#overlay=admin/config/media/image-styles and click on the add new style link
  (1) Give an Image style name and click on create new style button
  (2) On the next configuration screen select new style you want and then click add button (In this tutorial I choose resize style)
  (3) On the next screen set the width and height and click on the add effect button. (The settings may vary depend on the style you choose). I set width as 935 and height as 293 pixels.

Do this same process for the thumbnail image too. (for the thumbnail image dimension, I set width as 210 and height as 100 pixels.)
(4) Create New Content Type

Let's create a new content type, From the dashboard menu bar cick on Structure and then content types then click on the add new content type link.

(1) Give a human-readable name, I named it as Featured Slider (machiine name will be auto generated based on the human readable name)
  (2) Give a brief and relevant description
  (3) Submission form settings, I leave as the default settings
  (4) Publishing options, I checked only published (all other settings unchecked)
  (5) Display settings, I have unchecked the authour and date info.
  (6) Comment settings,I set hidden (disabled)
  (7) Menu settings, I leave as default settings.
  (8) Click Save and add fields Button
(5) Create New Fields

Here in this example I create only two fileds, and they are image field and link field.
We will use image field for uploading our slider image and link field for creating a custom link where we want our slider to be linked.

Image Field Settings

(1) Label: Slider Image
(2) Field: slider_image
(3) Field type: image
(4) Widget (form element): image
(5) Click Save button, and on the field settings page leave default settings and click on Save field settings button.
(6) On the image field configuration settings page you can configure as you wish.

I set this field as required, I added a file director name called slider-image so that this images will be arranged sperately from other images.
You can set the maximum upload size and resolution here, I have anabled alt and title field and finally click Save settings button.

By using same method create the link field too.

Link Field Settings
    (1) Label: Slider Link
    (2) Field: slider_link
    (3) Field type: link
    (4) Widget (form element): link
    (5) Click Save button,
For the link field configurations leave evrything to default settings.
I have re arranged the field like shown below;
 Title field
 Image field
 Link field
 Body field (you can even remove this field if not necessary)
Manage Display
On the manage display tab you can conigure how the out put of the field to be diplayed.
I have set the link field as hidden and I have also set image label as hidden
Drupal7: manage fields
(6) Create Feature Slider Content

I have created four featured slider content for this tutorial.

(1) Click on add content link
  (2) Create Featured Slider content
  (3) Give a proper title name
  (4) Upload slider image
  (5) Give alt and title field names
  (6) Give a link title and url where you want the slider to be linked
  (7) Leave all othe settings as default except for the path field if yo want you can give an SEO friendly URL alias.
  (8) Save the content.

Same way create more Featured Slider contents (I have created four contents)
(7) Create a New View

Now it's time to create our new Slideshow view.
From the Dashboard menu click on the Structure and then click on the Views.

(1) Click add new view link
  (2) Give view name, I have named as Featured Slider (machiine name will be auto generated)
  (3) Give an apropriate view description
  (4) Choose Show Content of type Featured Slider (your content type name).
  (5) Uncheck Create a Pge and check Create a block
  (6) Type in Block title and choose display format as "Slideshow" of "fields" items per page 5 (you can enter the number of items you want to display)
  (7) Click the button "Continue & edit"
Views Field Settings
First let's add link field (link must be the first field in order to work everything properly) so click on the add icon and from the filter Groups select Content
Add Content: Link, Click "Add & configure button" in the next cofiguration window uncheck "Create a label". "Check" Exclude from display.
Click "Apply button"

Next let's add image field, so click on the add icon and from the filter Groups select content
Add Content: image field (Note: make sure you choose the image field which we crerated for this slider content type only.)
Click "Add & configure button" in the next cofiguration window uncheck "Create a label".

Formatter: Image (if you have installed Colorbox or lightbox you can choose them here!)
Image Style: Fullsize (Choose the imagecache you have created in the above step)
Link image to: Nothing
Style Settings: Leave default settings
No result behaviour: Leave default settings
Rewrite Results: Check Output this field as a link
Link path: [view_node] (Note:Scroll dow a bit and you can see replacement patterns created by Core Token module, (if we didn't set the link field as first we can't see link field option here) copy only [view_node] then scroll up and paste it in the link path field.)
Click "Apply button"

Finally we need one more field for the thumbnail, so let's click on the add icon and from the filter Groups select Content
Add Content: image field (Note: make sure you choose the image field which we crerated for this slider content type only.)
Click "Add & configure button" in the next cofiguration window uncheck "Create a label" and CHECK EXCLUDE FROM DISPLAY,
Formatter: Image (if you have installed Colorbox or lightbox you can choose them here!)
Image Style: Thumbnail (Choose the imagecache you have created in the above step)
Link image to: Nothing
Style Settings: Leave default settings
No result behaviour: Leave default settings
Rewrite Results: Check Output this field as a link
Link path: [view_node] (Note:Scroll dow a bit and you can see replacement patterns created by Core Token module, (if we didn't set the link field as first we can't see link field option here) copy only [view_node] then scroll up and paste it in the link path field.)
Click "Apply button"

Views Filters Settings

In views3 the filters are created in the beginning while we choose the content type and other settings! If you need any additional filetering you can create it here!

Views Style Settings

Click on the Format Slideshow | settigs and on the next configuratioin window set as below;
  (1) List type: Unordered list
  (2) Wrapper class: Leave default settings
  (3) Style> Skin: deafult
  (4) Slides> Slideshow type: cycle
  (5) Cycle options
You need to download jQuery cycle plugin and copy jquery.cycle.all.min.js to sites/all/libraries/jquery.cycle You can find the plugin at http://malsup.com/jquery/cycle.

IN SIMPLE ENGLISH
Create a folder named "libraries" in the site/all directory and then create an another folder named "jquery.cycle" in that directory and finally copy and paste only the "jquery.cycle.all.min.js" into this directory.

(6) Transittion: Fade
  (7) Action: pause on hover
  (8) Internet Explorer Tweaks: default
  (9) Widgets: You can choose either or both Top and Bottom (I choose bottom here, and the advance settings as below;)
  (10) Bottom Widgets>Pager>Pager type: Fields
  (11) Pager field: Content: Image (Note: last one we added for the thumb, don't mistake since both field will be named same.)
  (12) Activate Slide and Pause on Pager Hove: checked, controls and slider counter leave unchecked.
  (13) Click Apply button.

Format Show Field Settings

Inline fields: Choose the thumbnail field as inline.
Click Apply button. (Note: Well it actually doesn't change much in appearance but it does change in the code. Next step use the firebug and find the class and add some styles to display properly.)

(8) Create a Custom Region (optional step)

(1) On your thems folder open the your_theme_name.info file and add a new region like this shown below;
regions[featured_slider] = Featured Slider and save the .info file.
(2) Open your themes page.tpl.php file and add these code where you want your slide to be displayed as shown below;

You can even create custom front page template like page--front.tpl.php so that you do't need to make any changes to the default page.tpl.php template.
[9] Enable & configure the Block

Now this block will be visible in the blocks disabled area, so from the Dashboard menu go to Structure>Block and enable the block to a themes default region  or the custom region we created (featured_slider). (Regions varies depends on the theme you are using.)

Block Configuration Settings
After enabling the block you get a link to configure the block so click on the Configure link and on the settings section set as below;

(1) Block title (if you don't want blobk title to be displayed just type )
  (2) Again you get all enabled theme specific Region settings.
  On visibility setings
  (3) Pages>Show block on specific page: choose Only the listed pages and type  so that this block will be displayed only on the front page.
CSS TIPS TO DISPLAY THUMBNAILS INLINE

Add these CSS codes to your themes style sheet to display the thumbnails inline.
.views-slideshow-controls-bottom .views-slideshow-pager-field-item { float: left; margin: 20px 6px; } Make necessary adjustments.


How do you allow a user to set the audience of a node to any Organic Group without giving them the "administer nodes" permission?

I created a patch to the Organic Groups module to add the "administer audience" permission.  The patch can be found here, http://drupal.org/node/1211974

Here's the patch inline,

diff --git og.module og.module
index 38cc452..0206115 100644
--- og.module
+++ og.module
@@ -558,7 +558,7 @@
  * Implementation of hook_perm().
  */
 function og_perm() {
-  return array('administer organic groups');
+  return array('administer organic groups', 'administer audience');
 }

 /**
@@ -1833,7 +1833,7 @@
   }

   $node = $form['#node'];
-  $required = variable_get('og_audience_required', 0) && !user_access('administer nodes');
+  $required = variable_get('og_audience_required', 0) && !user_access('administer nodes') && !user_access('administer audience');
   $is_optgroup = FALSE;

   // Determine the list of groups that are shown.
@@ -1843,7 +1843,7 @@
   foreach ($subs as $key => $val) {
     $options[$key] = $val['title'];
   }
-  if (user_access('administer nodes')) {
+  if (user_access('administer nodes') || user_access('administer audience')) {
     // Node admins see all of groups.
     $all = og_all_groups_options();
     $other = array_diff_assoc($all, $options);
@@ -1900,7 +1900,7 @@
   elseif (!empty($gids)) {
    // populate field from the querystring if sent
    $groups = $gids;
-   if (!user_access('administer nodes') && $simple) {
+   if ((!user_access('administer nodes') && !user_access('administer audience')) && $simple) {
      // filter out any groups where author is not a member. we cannot rely on fapi to do this when in simple mode.
      $groups = array_intersect($gids, array_keys($options));
    }
@@ -1949,7 +1949,7 @@
     // show multi-select. if less than 20 choices, use checkboxes.
     $type = $cnt >= 20 || $is_optgroup ? 'select' : 'checkboxes';
     $max_groups = variable_get('og_max_groups_'.$node->type,'');
-    $description_max_groups = ($max_groups && !user_access('administer nodes')) ? format_plural($max_groups," Limited to !max_groups choice."," Limited to !max_groups choices.", array('!max_groups' => $max_groups)):'';
+    $description_max_groups = ($max_groups && !user_access('administer nodes') && !user_access('administer audience')) ? format_plural($max_groups," Limited to !max_groups choice."," Limited to !max_groups choices.", array('!max_groups' => $max_groups)):'';
     $form['og_nodeapi']['visible']['og_groups'] = array(
       '#type' => $type,
       '#title' => t('Audience'),


How do I update the configuration of a module?

As mentioned in the original question, and follow-up comments, there are a variety of contrib modules and manual methods to accomplish this.

To do it automatically, or in a custom fashion, I think hook_update_N() is still probably the most viable option.

For instance, this is an example from the Head 2 Head to update system.site to set the default_langcode:

  $config_factory = \Drupal::configFactory();
  $langcode = $config_factory->get('system.site')->get('langcode');
  $config_factory->getEditable('system.site')->set('default_langcode', $langcode)->save();

You can also read in config (recommended only for adding new config, not necessarily updating or overriding config that may have been customized):

  $source = new FileStorage($path);
  /** @var \Drupal\Core\Config\StorageInterface $active_storage */
  $active_storage = \Drupal::service('config.storage');
  $active_storage->write($name, $source->read($name));

where $path is the absolute path to the my_config.foo.yml file.


Using hook_form_alter() and hook_cron() together

You don't invoke hook_cron_queue_info(); you add an item to your cron queue, which is nothing else that a normal Drupal queue that is exposed to Drupal cron through hook_cron_queue_info().

What you should do in your add_rating_queue_function() is using code similar to the following one.

$queue = DrupalQueue::get('update_rating');
// Add a new item to the queue.
$queue->createItem($data);

$data is the data that is passed to the worker callback you define for the update_rating queue in add_rating_cron_queue_info().

As for running the Drupal cron tasks, you can simply call drupal_run_cron(). This is what system_run_cron_submit() does.

function system_run_cron_submit($form, &$form_state) {
  // Run cron manually from Cron form.
  if (drupal_cron_run()) {
    drupal_set_message(t('Cron run successfully.'));
  }
  else {
    drupal_set_message(t('Cron run failed.'), 'error');
  }

  drupal_goto('admin/config/system/cron');
}

system_run_cron_submit() is the submission callback for the "Run cron" button you find at admin/config/system/cron.

In your case, you simply need to call drupal_run_cron() without checking the error code.

As Jeremy French said, drupal_run_cron() should not be called too often, and in this way. In admin/config/system/cron, the function call is triggered by the user, but a module should not be calling drupal_run_cron(), especially because Drupal 7 includes the code from Poormanscron. This mean that cron tasks could be already executed during page requests; adding a further call to drupal_run_cron() could make the site slower. A better code could be the following one.

if (lock_acquire('cron', 2.0)) {
  $last_cron_execution = variable_get('cron_last', 0);
  lock_release('cron');

  // Check cron tasks were not already executed, or they were not executed few minutes ago.
  // Set $execute if they were executed far enough.

  if ($execute) {
    drupal_run_cron();
  }
}


How do I display page numbers in a book?

You can add simple PHP code in your node.tpl.php

    <?php
      $allbook = book_toc($node->book['bid'],3);
     $allbook_chapter = array_search($node->book['mlid'], array_keys($allbook));
print $allbook_chapter;
            ?>

This code prints page number of current node. This in't better way of course.
Moving this logic to template.php is better solution.


How do I show a term's node count in grid format?

If you import the view proposed in that answer, you will get a table with 2 columns: term name on the left, number of nodes on the right. That's a block, not a page, but that's a good start for your needs, IMHO.

Read this to learn how to import views.


drupal 7 user registration custom url returning a blank page

You can't call a hook in hook_menu(). You can either create an alias for the user registration page or replace your menu item with:

function medical_reg_user_register_menu() {
  $items['page/medical'] = array(
    'page callback' => 'drupal_get_form',
    'page arguments' => array('user_register_form'),
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK
    );
  return $items;
}


How do I print core block or views block in node.html.twig?

In Drupal 8, you don't need (and should not) render in PHP. The rendering is done as late as possible in Twig.

So put the build array of your view in a variable.

function mytheme_preprocess_node(&$variables) {
  $variables['view1'] = views_embed_view('view1', 'block_news');
}

And then render it with {{ view1 }}.

Twig will handle the necessary rendering for all kind of render arrays that are possible in Drupal.

You can use the same for a block. (See the comment from Ivan Jaros.)

$variables['block1'] = entity_load('block', $id)->getPlugin()->build();

The build() method gives you the build array of the entity and you can use {{ block1 }}.


As you can read on https://www.drupal.org/project/drupal/releases/8.3.9 Drupal 8.3.9 fixes SA-CORE-2018-002 (and hence probably also SA-CORE-2018-001). However, there has been several later issues - see https://www.drupal.org/security - and only Drupal 8.5 is supported. Quote from the latest 8.5.6 release:

  Versions of Drupal 8 prior to 8.5.x are end-of-life and do not receive
  security coverage

In other words, you better upgrade to Drupal 8.5.6 and fix/upgrade the modules that no longer works.


How to extend or "hook" Drupal Form AJAX?

Thank you, @yvan, for answer. Links you added are good.
But there are better documentation in source code comments. If you want to understand how it works you should look through files includes/ajax.inc and misc/ajax.js.
My problem was solved like this:

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

        // Overwrite beforeSubmit
        Drupal.ajax['some_element'].options.beforeSubmit = function (form_values, element, options) {
            // ... Some staff added to form_values
            // return false; // to prevent AJAX call if needed.
        }
        //Or you can overwrite beforeSubmit
        Drupal.ajax['some_element'].options.beforeSerialize = function (element, options) {

            // ... Some staff added to options.data
            // Also call parent function
            Drupal.ajax.prototype.beforeSerialize(element, options);
        }

                    //...

These functions are calling in jQuery Form Plugin.


Has the Block Cache Settings from Drupal 8 been back-ported to Drupal 7?

No, it's impossible to backport. See https://api.drupal.org/api/drupal/modules%21block%21block.api.php/function/hook_block_info/7's DRUPAL_CACHE_CUSTOM and https://www.drupal.org/developing/api/8/cache/contexts.


Can I control the weight of a library loaded through a theme preprocess function?

Can you define your subtheme's library as extending or overriding your base theme's library. You'd have to do that in your subtheme's .info.yml. I think that should work. I think if you went this route you would just have a .css file in your subtheme that entends -- gets added whenever -- your basetheme's library is loaded. In this case you're override wouldn't be a "library" in your subtheme. Drupal should be smart enough to load your css file whenever the basetheme's library is loaded.


Archive old content data in different database

Here's what you can do:

Add your archive database to your settings.php below your default database.

$databases['my_other_db']['default'] = array(
  // Your secondary database's credentials here.
  // You will be able to explicitly connect to this database from your modules.
);

In your cron script, load all nodes you want to archive. In this example I retrieve all nodes older than a month and no more than 50 at a time.

$nodes_to_archive = array();

$query = db_select('node', 'n')
  ->fields('node')
  ->condition('type', 'your_content_type')
  ->condition('created', REQUEST_TIME - (86400 * 30), '<')
  ->range(0, 50);
$result = $query->execute();

while($record = $result->fetchAssoc()) {
  $nodes_to_archive[] = $record;
}

In the same script, switch from database and add the nodes to the archive (make sure the second database has the same structure as the existing one)

db_set_active('my_other_db');

foreach ($nodes_to_archive as $node) {
  db_insert('node')
    ->fields($node)
    ->execute();
}

Still in the same script, switch back to the default database and remove the archived nodes.

db_set_active();

$nids = array();
foreach ($nodes_to_archive as $node) {
  $nids[] = $node->nid;
}

node_delete_multiple($nids);

I haven't tested any of this so you might need to improve it here and there. If anything's unclear, please ask.

Here is a list of helpfull resources:

How to connect to multiple databases within Drupal
Function db_select
Function db_insert
Function node_delete_multiple


Add fields to entityform, when it's created

Yes it's possible  here's the steps on how to achieve that functionality.

1. First you need to alter the entityform and add your custom submit handler

Example:

/**
 * Implement hook_form_alter().
 */
function example_form_alter(&$form, &$form_state, $form_id) {
  if($form_id == 'entityform_type_form') {
    $form['#submit'][] = 'add_new_fields';
  }
}

2. Create your custom submit handler, you need field_create_field(), field_create_instance() in creating your field, define all the details of your field inside the $field and $instance array

/**
 * Submit callback adding custom field when saved entityform type.
 */
function add_new_fields($form, &$form_state) {
  // Create email address field.
  if(!field_info_field('field_email_address')) {
    // Create your new field.
    $field = array(
      'field_name' => 'field_email_address',
      'type' => 'text',
    );

    field_create_field($field);

    // Create field instance.
    $instance = array(
      'field_name' => 'field_email_address',
      'entity_type' => 'entityform',
      'bundle' => $form_state['values']['type'],
      'label' => 'Email address',
      'settings' => array(
        'entityform_type_form' => 1,
      ),
      'widget' => array(
        'type' => 'textfield',
      ),
    );

    field_create_instance($instance);
  }
   // Create voucher code field.
  if(!field_info_field('field_voucher_code')) {
    // Create your new field.
    $field = array(
      'field_name' => 'field_voucher_code',
      'type' => 'text',
    );

    field_create_field($field);

    // Create field instance.
    $instance = array(
      'field_name' => 'field_voucher_code',
      'entity_type' => 'entityform',
      'bundle' => $form_state['values']['type'],
      'label' => 'Voucher code',
      'settings' => array(
        'entityform_type_form' => 1,
      ),
      'widget' => array(
        'type' => 'textfield',
      ),
    );

    field_create_instance($instance);
  }
}

Here's the link of working custom module that i created https://github.com/umandalroald/entityform-custom-callback


Go to admin/modules and
Enable Update Manager under CORE modules list

Update Manager: Checks for available updates, and can securely install or update modules and themes via a web interface.


You can use the fields defined on the graphql_json module in order to retrieve the webform structure.

{
  webformById(webform_id: "contact") {
    webform {
      elements {
        name: path(steps: "#name") {
          ... on JsonLeaf {
            value
          }
        }
        type: path(steps: "#type") {
          ... on JsonLeaf {
            value
          }
        }
        title: path(steps: "#title") {
          ... on JsonLeaf {
            value
          }
        }
      }
    }
  }
}

Result:

{
  "data": {
    "webformById": {
      "webform": {
        "elements": [
          {
            "name": {
              "value": "name"
            },
            "type": {
              "value": "textfield"
            },
            "title": {
              "value": "Your Name"
            }
          },
          {
            "name": {
              "value": "email"
            },
            "type": {
              "value": "email"
            },
            "title": {
              "value": "Your Email"
            }
          },
          {
            "name": {
              "value": "subject"
            },
            "type": {
              "value": "textfield"
            },
            "title": {
              "value": "Subject"
            }
          },
          {
            "name": {
              "value": "message"
            },
            "type": {
              "value": "textarea"
            },
            "title": {
              "value": "Message"
            }
          },
          {
            "name": null,
            "type": {
              "value": "captcha"
            },
            "title": null
          },
          {
            "name": null,
            "type": {
              "value": "webform_actions"
            },
            "title": {
              "value": "Submit button(s)"
            }
          }
        ]
      }
    }
  }
}

You can find the available steps with keys field.

{
  webformById(webform_id: "contact") {
    webform {
      elements {
        keys
      }
    }
  }
}


Creating custom bread crumb trails (Drupal 7)

I don't know anything about Organic Groups, otherwise I'm using Path breadcrumbs and Custom Breadcrumbs.


How to prevent other roles from publishing content

Override Node Options overrides this functionality and it's pretty straight forward.

The Override Node Options module allows permissions to be set to each
field within the Authoring information and Publishing options field
sets on the node form.


What is the purpose of the entity_metadata_wrapper() function, and why should I use it?

Yes, changing the status of a node is trivial, as that is a hardcoded property.

Fields on the other hand, are much more complicated. They are nested three levels deep, while there is field_get_items() to get them in the correct language, there is no such function for setting field values. So, you always need to check whether a field is translatable or not and you need know which property exactly contains the values you're looking for/want to set.

Two examples, that show what the entity wrapper can do:

The following line adds the commerce line item to the order, taking care of the language and the actual property that holds the reference id, taken from the following answer https://drupal.stackexchange.com/a/23513/31

$order_wrapper->commerce_line_items[] = $line_item;

In a similar way, being able to directly access a value of a field, without having to check the language, or the delta, even being able to directly access referenced entities, taken from https://drupal.stackexchange.com/a/33010/31

$subnode = entity_metadata_wrapper('node', $node)->field_subnode->value();
$default = $subnode->title;

The entity wrapper is the driving force behind flexible, powerful modules like Search API and Rules as it allows them to work their way through multiple levels of references, so that you can e.g. access a field of the product a user bought in an order with something like [commerce-order:commerce-line-items:0:commerce-product:some-field] (might not actually be correct, but something like that), or add the body summary of a referenced node to your search index.

That said, I'm not necessarly fond of the actual API of the wrapper, it's huge internal arrays and that even simple properties are again wrapper classes. I hope that the improved entity (and hopefully field) system in Drupal 8 will remove the need for such a wrapper thanks to having classed entities.


Get the t function to work in a custom php file

Include these lines in your php file

define('DRUPAL_ROOT', getcwd());

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


Views - comprehensive source for studying?

By all means - start the Taming the Beast screencast series by NodeOne: http://nodeone.se/en/learn-views-with-nodeone-part-1-overview


Will Drupal or PHP use APC if its installed on the server?

Drupal, like any other PHP app will an APC opcode cache if it's available.  Though there are a few settings that may prevent Drupal from using APC as it should.

First and foremost make sure APC has enough memory to work with.  Drupal can eat up a ton of memory and if your APC cache is too small it may actually hurt your performance.

The first memory relevant setting I would look at is the apc.shm_size.  APC's defaults setting have never worked out of the box for any of my Drupal installs. On some servers I have this is as high as 512M.

apc.shm_size = <MB Allocated>

APC may not be caching .module and .inc files by default!

Depending on your setup, APC may not be caching .MODULE and .INC files at all. This means that the majority of Drupal's slowest code may never make it to the APC cache in the first place.

The fix?  apc.filters

On many of my Ubuntu servers adding the following line to my apc.ini has an enormous performance impact on my Drupal installs.

apc.filters = "+module$,+php$,+inc$,-admin"

You may also want to monitor your APC cache using the apc.php script that's generally bundled with APC.

You can also use apc.php to verify that .module and .inc files are making it into your APC system cache.


Enable the module "Configuration Translation" and then you get a tab "Translate view":

/admin/structure/views/view/[view]/translate

where you can add translations and edit the translated view.

The title is in:

Displays -> Master Display Settings -> [View] Default Display Options -> Display title


I've had the misfortune to need to do this before :P , and my advice would be as follows:

Forget about renaming the existing field; the machine name is scattered across several different hard-to-edit places, and you'll probably miss some and get weird errors. For example, if you just rename the tables and the configuration, the field API will throw a fit when it tries to delete the old tables and finds they're already gone. The schema information is kept in the keyvalue store, and cannot be rebuilt from scratch, so if you make manual changes it's easy to end up in a broken state.

Instead, recreate the field with the correct machine name, then copy over the data with SQL, and finally delete the old field.

INSERT INTO node__field_new SELECT * FROM node__field_old;
INSERT INTO node_revision__field_new SELECT * FROM node_revision__field_old;


May be what you need is contextual filters, the user can go to view-name/% where % is a contextual filter for the uid


Get "previous" and "next" buttons on view

This module might be able to do the trick Views navigation

  This module adds next and previous links on content pages when
  accessed from a view. It is intended for dynamic and/or paged view
  results, where the result set changes according to exposed filters,
  current user access rights,...


Taxonomies are best used to define properties that:

are shared across multiple content items;
need to be grouped with similar properties.

For instance, if you're selling t-shirts, the taxonomy terms 'blue', 'red' and 'yellow' are grouped in the 'color' vocabulary. By tagging all t-shirts of the same color with the same taxonomy term, you define a relationship between those t-shirts. This makes it very easy to generate a page showing all blue, red or yellow t-shirts.

Taxonomy terms, like many other entity types, are 'fieldable', which means that you can add fields to them to contain data. For instance, if you add an image field to the taxonomy terms in the 'color' vocabulary, you could define an example image for each color term.

If this example with t-shirts and colors matches your use case, then the answer to your question is: Yes, taxonomy is the Drupal way to do it.

By the way, the word "entity" has a very broad meaning in Drupal. 'Taxonomy term' is a type of entity, just like 'node', 'user' and 'file'. Saying that "entities will do what you need" is like saying "building materials will allow me to build a house". It's a statement that (almost) can't be wrong. You need to answer the question: Which type of entity is best to solve this specific problem?


How to map url_alias table to node table?

They are not related because url_alias table contains all the URL aliases. You can use MySQL CONCAT to concatenate strings (fields or string literals).

$results = db_query("
  SELECT
    n.nid, n.title,
    a.source, a.alias
  FROM {node} n
  LEFT JOIN {url_alias} a
    ON CONCAT('node/', nid) = source
  ")->fetchAll();
foreach ($results as $result) {
  dpm($result);
}


Whats the correct way to programmatically include unpublished content in entity reference fields? (without views)

You will need to create a custom EntityReferenceSelection plugin.
Which should probably extend the NodeSelection plugin in core.


Try to change the node_save($node) to drupal_register_shutdown_function('node_save', $node). It will remove the old node saving process from the actual node saving.
But I don't think, that type of code should have place within a computed field. The computed field good to modify the same field. It isn't designed for modifying other data of your system.
These code should be in a custom module in hook_node_presave().


How do I give access permission for specific node to anonymous User

Give back the "Node access" permission (View published content) to Anonymous user and control the accesss with your custom module

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

function MODULENAME_node_access(NodeInterface $node, $op, $account) {
  $allowed = [1,2];
  if ($op == "view" && in_array($node->id(),$allowed)) {
    return AccessResult::allowed();
  }
  return AccessResult::forbidden();
}


Why doesn't drush respond to commands after install

At the time of my comment the phar for drush wasn't working correctly. That very well may be fixed by now, however, I've still found installing drush via composer to be the easiest solution.


I think this is the expected behavior: Content is marked to index when you update it, and the next cron run will reindex your items.

You need to enable the checkbox "Index items immediately" for this to be a immediate operation. Be aware this is a costly operation.

If your field type is custom, you might need to expose the value you want to entity API. Check out how to do this in Describe field properties to make custom fields work with Entity Metadata Wrappers.


Instead of creating different webforms for each file, you could just have one form that can handle this. Here is my suggestion:

Make all links to your whitepapers to load a webform and pass the filename as a parameter for your webform. You can then store that on a hidden field on the form.
Create a custom submission handler for your webform to trigger a download upon submission (use the filename from the hidden field on the form).


Is there an Input Filter without built-in restrictions?

You can always just make your own text filter through the admin.

If you head to /admin/config/content/formats and click "+ Add text format," you'll be able to customize your own text format, which includes the roles who can use it, what filters you would like to use (using none should allow for any html tag to get through).

If there are some html tags you don't want showing up in your text format, use "limit allowed HTML" tag, and list the tags you want, like this:

<a> <em> <strong> <cite> <blockquote> <code> <ul> <ol> <li> <dl> <dt> <dd> <blink>

You could event throw (as your example) a  tag in there to let it through. There is however, one big warning I need to leave you with:

====================WARNING ========================

Allowing users to place javascript on your page is a huge, huge security threat. If you decide to give users this privilege, make sure it's only with people you absolutely trust. If a text field allows JS to be placed in it, your basicly opening a door for a cross site scripting atttack.

Same holds true for the PHP filter, in fact the php filter is going away in D8, so I would really advise against using that.


So I found the solution : the shell is interpreting the semicolons and cuts the URL so it has to be quoted. Here for example http://sourceforge.net/apps/trac/sourceforge/ticket/9358 it is explained.

my drush cmd should be:

drush make "http://git.mycompany.de/?p=workflow.git;a=blob_plain;f=build-workflow.make;h=170f5329b413bea0efb1ec33bebdc1549403cc3e;hb=HEAD"


Can you post an exact curl request? Does the user in your request have permission to create content?

if basic auth is enabled then you need to add the user name and password to the request. For example curl request:

curl --include \
  --request POST \
  --user admin:admin \
  --header 'Content-type: application/hal+json' \
  https://ddj9.ply.st/node?_format=hal_json \
  --data-binary '{"_links":{"type":{"href":"http://ddj9.ply.st/rest/type/node/article"}},"title":[{"value":"Example node title"}],"type":[{"target_id":"article"}]}'

Otherwise If the user must be authenticated via cookie then:
 1. you have to send a post to login the user.

curl --header "Content-type: application/json" --request POST --data '{"name":"admin", "pass":"admin"}' http://drupal.d8/user/login?_format=json

The output will look like:

{"current_user":{"uid":"1","roles":["authenticated","administrator"],"name":"admin"},"csrf_token":"wBr9ldleaUhmP4CgVh7PiyyxgNn_ig8GgAan9-Ul3Lg","logout_token":"tEulBvihW1SUkrnbCERWmK2jr1JEN_mRAQIdNNhhIDc"}

Retrive a token from the returned value result
Do what you need to do. :

// get X-CSRF-Token.
$url = 'your_url';
$json = '{
"name": "admin",
"pass": "PASSWORD"
}';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
 'Content-Type: application/json')
);
$result = curl_exec($ch);
$user = json_decode($result, TRUE);
$x_csrf_token = $user['csrf_token']
if ($x_csrf_token) {
    // do what you need
 curl_setopt_array($curl, array(
  CURLOPT_URL => "http://www.xxxxxx.com/loyalty/node/?_format=json",
  CURLOPT_RETURNTRANSFER => TRUE,
  CURLOPT_ENCODING => "",
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 30,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => "POST",
  CURLOPT_POSTFIELDS => $input,
  CURLOPT_HTTPHEADER => array(
   // if you need basic auth then uncomment the nextline
   // "authorization: Basic b64Value",
    "cache-control: no-cache",

    "x-csrf-token: $x_csrf_token"
  ),
));
$response = curl_exec($curl);


How to change the value of site_name to "My site name" in multilingual sites using Drush?

I understand your question as trying to use Drush for setting the site name, using Drush command like so:

drush variable-set site_name "Some name here"

And this for a multilingual site.

The equivalent of doing this via Drupal admin screens (instead of Drush), would require to first declare your site name as a "multilingual varialable". For more details on these kind of variables, and how to get this to work, refer to my answer at How to make content translation available for front page?.

In this case however, in "step 4" the variable to be selected is "Site name" (not "Default front frontpage"), within "Site information". While you're at it, you probably want to double check other similar variables like Site Slogan, etc.

If you try to do this using Drush, it won't work however, as explained in the issue about set i18n variables with drush? However, if you have the Variable module enabled, then according to Comment #3 in that issue, it should be possible to use Drush to achieve the equivalent result via Drush command like so (to set the Spanish language (es) to 'Spanish site'):

variable-realm-set language es site_name "Spanish Site"

Curious to some hear if in this case this Drush command resolved the issue here.


How to add facebook like/share button to every new text I post?

Hope this will help you,
You can achieve this with two module views and facebook
after enabling both module go to the structure tab of drupal,click on this

put Fcaebook application Id here:

You can create application id from this link
on reference to ur facebook account.
Than inside Facebook social go to "Presets"
click on add
fill up this form

for like button put only the name and select radio button of "facebook like button plugin" and select your content type,
save the form,
Go to view to create a new view,

Select respective field of your node and below that select the "Node:Facebook Social plugin", on settings of this field put your preset name as below

Finally you will get the face book like button on every row of your view.


Put the route name in a variable in preprocess

mytheme.theme

function mytheme_preprocess_page(&$variables) {
  $variables['route_name'] = \Drupal::service('current_route_match')->getRouteName();
}

and use it in twig:

page.html.twig

{% if route_name == 'entity.node.edit_form' %}
  This is a node edit form.
{% endif %}


Though I'm surprised if there's not an option in the user interface, according to language_default, it appears you could set the default language as a $conf variable in the shared settings.php file.

Something like

settings.php:

switch($_SERVER['SERVER_NAME']){

  case 'www.example.com':

    $conf['language_default'] = (object) array(
      'language' => 'en', 'name' => 'English', 'native' => 'English',
      'direction' => 0, 'enabled' => 1, 'plurals' => 0, 'formula' => '',
      'domain' => 'www.example.com', 'prefix' => '', 'weight' => 0, 'javascript' => ''
    );

    // Example per-domain cache prefix if using memcache
    $conf['memcache_key_prefix'] = 'en_';

  break;
  case 'www.example.de':

    $conf['language_default'] = (object) array(
      'language' => 'de', 'name' => 'German', 'native' => 'German',
      'direction' => 0, 'enabled' => 1, 'plurals' => 0, 'formula' => '',
      'domain' => 'www.example.de', 'prefix' => '', 'weight' => 0, 'javascript' => ''
    );

    // Ensures cache varies by domain
    $conf['memcache_key_prefix'] = 'de_';

  break;

}

Update: Added example memcache cache key prefix setting - to ensure cache varies per domain, if required.


How to get parent node values on inline entity form hook alter?

Perhaps you should try altering the paragraph form instead. When the paragraph is created, you will have access to it's host entity. Then just get the label of the host entity and assign it to the form element as a default value or value(can't remember which one).


Filter a view on field on a user referenced entity

Before adding a filter on the user name you need a relationship for your field assigner. This in the advanced section of views. After you have set up the relationship:

User referenced from field_assigner

You can add a filter:

Name (autocomplete)

and choose the relationship:

field_assigner: User


The error you've shown is from someone running a hacking script.

The nginx documentation offers many solutions to avoid running bad php scripts in their Pitfalls and Common Mistakes FAQ, but the one I like is the try_files directive to only run scripts that exist on your server otherwise return a 404 Not Found status code.

location ~* \.php$ {
    try_files $uri =404;
    fastcgi_pass backend;
    # [...]
}


I finally got through this. In config table in the database there was (probably just from some test long ago) a reference to that example.

Deleting that line made the updates to go through.

Now checking if it solved my actual problem...

Thanks for the help

hank


You can use the UC Down Payment module for this task.

This module allows Ubercart store administrators to add partial payment functionality as a product feature. They can assign down payment amount and the due date to any product, and manage down payments and partially paid orders in the admin section.


In views you cannot access to a list of roles, only to the user entity.

I suggest you to get this list of the roles by a drupal function

Try with user_roles()


Random order at three-column Slick Slider

I already found the solution:

The randomize option has to be enabled in the slick options instead of the view's sort-criteria.
We can either define a optionset to use it in different views (the optionsets have to be set at Configuration -> Media -> Slick) or we override the default-optionset in the view configuration itself (View -> Edit -> Format -> Settings next to Slick Carousel).


View page doesn't output but views_embed_view with same arguments does?

I knew the answer would be stupid.

I had registered the path I was using for my view's page in a module a couple months ago and forgot. ><


how to reference a field in a field collection in a page.tpl file

You may use entity_load. I have a project in which I use Field Collections as you, and this is a fragment of code in my module. I hope it helps you.
The key is the use of entity_load.

    foreach($node->field_imagenes["und"] as $value){
                $a = entity_load('field_collection_item',     array($value["value"]));
                $prefered = false;
                if(isset($a[$value["value"]]->field_prefered_image["und"][0]["value"]) ...


How to associate programatically the translation of new term to the original existing term?

Here is the function which takes $term as current term and $org_term which is original/source term.

<?php
/**
 * Custom function to add term translations.
 */
function foo_add_term_translation($term, $org_term) {
  if ($org_term->i18n_tsid) {
    // Already part of a set, grab that set.
    $i18n_tsid = $org_term->i18n_tsid;
    $translation_set = i18n_translation_set_load($org_term->i18n_tsid);
    $translation_set->add_item($term);
    $translation_set->save_translations();
    watchdog('foo', "Added !source translation: !translated in !lang.", array('!source' => $org_term->name, '!translated' => $term->name, '!lang' => $term->language), WATCHDOG_NOTICE);
  }
  else {
    // We have no translation source nid, this could be a new set.
  }
}

More code examples you'll find in i18n_translation module.

This could be called either during insert or update as below:

/**
 * Implements hook_taxonomy_term_insert().
 */
function foo_taxonomy_term_insert($term) {
  foo_add_term_translation_wrapper($term);
}

/**
 * Implements hook_taxonomy_term_update().
 */
function foo_taxonomy_term_update($term) {
  foo_add_term_translation_wrapper($term);
}

Here is helpful wrapper function with example to load the original term where two terms share the same field value:

/**
 * Custom wrapper to update term translation.
 */
function foo_add_term_translation_wrapper($term) {

  $bundle = 'countries'; // Example bundle name
  $vid = ($voc = taxonomy_vocabulary_machine_name_load($bundle)) ? $voc->vid : NULL;
  if ($term->vid == $vid && module_exists('i18n_taxonomy') && $term->language <> 'en' && empty($term->translation_set)) {

    if ($shared_id = $term->field_shared_id[key($term->field_shared_id)][0]['value']) {

      // Find term which points to the same country, but in English
      $query = new EntityFieldQuery();
      $org_term_res = $query
        ->entityCondition('entity_type', 'taxonomy_term')
        ->entityCondition('bundle', $bundle)
        ->propertyCondition('vid', $vid)
        ->fieldCondition('field_shared_id', 'value', $shared_id, '=')
        ->propertyCondition('language', 'en')
        ->execute();

      // Load term in the main language
      if ($org_term = taxonomy_term_load(reset(reset($org_term_res))->tid)) {
        foo_add_term_translation($term, $org_term);
      } // end: if

    } // end: if
  } // end: if

}

See also:

https://drupal.org/node/2102933


How do I show user created node in user profile page with edit mode?

You have to give permission for Edit own page for that role to see "Edit link" in views or any other page.

Tha can be available from

www.example.com/people/permissions -> <Content Type>: Edit own content

You have to create a module for showing your custom link in user profile page

function <modulename>_menu() {
 $items['user/%user/<yourlink>'] = array(
    'title' => 'Your Pages',
    'page arguments' => array(1),
    'type' => MENU_LOCAL_TASK,
    'weight' => 10,
  );
 return $items;
}

Not to mention you have to clear cache after the this.


Using search_api and search_api_views how do I display images?

We updated ctools to 7.x-1.4 and it started working.


How to specify radio buttons in baseFieldDefinitions?

The radios/checkboxes are displayed based on the field's cardinality:

If the field can store more than one (e.g., unlimited: ->setCardinality(-1), or 2,3,etc. ->setCardinality(2), ->setCardinality(3), etc.), it will be displayed as checkboxes.
If the field can store only one (i.e. ->setCardinality(1)), it will be displayed as radio buttons.


I always find the simplest way to deal with this is just to go to the system table in the site's database, and set the status column for the problematic module to 0.

After clearing the cache tables (either with Drush, or manually) you should be able to access the modules page again.


Upgrading from 8.3.7 to 8.4 conflicts with acquia/blt-project

The problem was a line in my composer.json file which is prevent the upgrade from happening.

In the "conflict" section, there's a line "drupal/core": ">=8.4.0-alpha1"
I have to remove that line and also run the following commands to complete the upgrade.

composer update --lock
composer require acquia/lightning:^3.0 acquia/blt:^8.9 --no-update
composer update acquia/lightning --with-all-dependencies


Limit number of nodes able to have custom field selected

A view can be used with a limit on the number of items to two with a filter that requires that story to be featured, then sorted by publish date (descending to show the latest). Otherwise, if you want an administrator to have total control over exactly which two stories are featured, use Nodequeue or use the node sticky bit and make sure only admins have access to set the sticky bit.

You can reuse the same view to create a page view that shows all stories that have the featured flag set.


I would definitely encourage you to look at the http://drupal.org/project/geshifilter input filter

From the page:

At the time of this writing the GeSHi library supports highlighting for more than 200 programming languages and configuration syntaxes, including: ActionScript, Ada, Apache Log, AppleScript, ASM, ASP, Bash, C, ColdFusion, C++, QT, C#, CSS, D, Delphi, Diff, DOS, dot, Eiffel, Fortran, Groovy, Haskell, HTML, INI, Inno, Java, Javascript, LaTeX, Lisp, Lua, Motorola 68000 Assembler, Matlab, mIRC Scripting, MySQL, Objective C, OCaml, OpenOffice.org Basic, Oracle 8 SQL, Pascal, Perl, PHP, PL/SQL, Python, QBasic/QuickBASIC, Rails, Microsoft Registry, robots.txt, Ruby, SAS, Scheme, Smalltalk, Smarty, SQL, TCL, Text, Visual Basic, vb.net, VHDL, XML, X++.

There is a stable D7 and D6 version.


To be honest you should never, ever run an SQL query inside a template file. This sort of thing should be handled either at the preprocess level, or even better, at an earlier stage in the page build (usually in a custom module file). There are good reasons for this:

Putting business/application logic inside a template file is never a good idea. Literally reams of volumes have been written on the subject; over the past few years MVC has been the 'it' pattern so I'd recommend reading up on that to understand the reasoning behind this kind of separation.
If you execute queries in your template files they will run even for pages for which the rest of the page content has been cached, which is a definite performance no-no.

I imagine there are other good reasons not to do it as well, suffice to say these are two quite strong arguments for moving the logic out of your template files.


Add custom files/file-fields to panels pages

What you are looking for is a customized fieldable panel panes. You can also check Panopoly Widgets for a similar example. It contains a lot of custom widgets which can be embed in panel panes and customized.
Fieldable panels panes makes your widget data as fieldable entities instead of node/content types(which is what you want).

If you want dynamic background images on a specific page context, you could check the dynamic background module.


Pass $form and $form_state as arguments in hook_menu

If you're using Drupal's form API, it already has support for AJAX built into to it via the #ajax property. For example....

function MYMODULE_example_form() {
  //@TODO: various form elments...

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Submit'),
    '#ajax' => array(
      'callback' => '_MYMODULE_example_form_submit'
    )
  );
  return $form;
}

function _MYMODULE_example_form_submit($form, &$form_state) {
  //@TODO: process submitted form
}

The examples module has more examples of this if you'd like to see more of it in action.


Which hook to implement to limit node creation?

Alter the access callback for the menu callback:

function custom_module_menu_alter(&$items){
    $items['node/add/page']['access callback'] = 'my_custom_access_callback';
    // Next line needed for Drupal 7
    unset($items['node/add/page']['access arguments']);
}

Add a function as your custom access callback:

function my_custom_access_callback() {
   global $user;
   $allowed_limit = variable_get('allowed_limit', 10);

   // If Drupal 6.
   $node_counts = db_result(db_query("SELECT count(*) FROM {node} WHERE uid = %d;", $user->uid));
   // End If

   // If Drupal 7.
   $node_counts = db_query("SELECT count(*) FROM {node} WHERE uid = :uid", array(':uid' => $user->uid))->fetchField();
   // End If

   if ($node_counts < $allowed_limit && user_access("create page")) {
     return TRUE;
   }
   else{
     drupal_set_message(t('Print message about exceeded limit and/or user permissions.'));
     return FALSE;
   }
}

This kind of logic will restrict a user to exceed the limit.


Hierarchy and taxonomies (like in the animal taxonomies)

You could try Taxonomy Manager module to quickly create tree of taxonomy nodes where each of taxonomy levels can be your family, genus, species and at the end animals. My suggestion is do not try to create separate taxonomy dictionaries , ie separate taxonomies for family, genus, species. Let's keep them all in one common taxonomy.


Hide certain field on form alter using AJAX

Your AJAX needs to have a target ID where it will put your AJAX output. You declare that ID in the wrapper key.

In your form_alter

  '#ajax' => [
    'callback' => 'xyz_user_signup',
    'wrapper' => 'load-me-here-id', // This element is updated with this AJAX callback.
   ],

Then you need to wrap the field with this ID so AJAX replaces it.

 $form['elements']['field1']['#attributes'] = ['id' => 'load-me-here-id'];

In your ajax callback

return $elements['field1']; // so it doesn't return the entire form.


How to create incremented view filters for numeric fields in Drupal?

If you create a field an select a type of text list using a list widget, you can create the any list you wish for the field.  Then when you expose the field in your view  the drop down list of values will be included in the exposed filter.


How can I create a View that shows nodes without a relation?

You can just create a new filter criteria using your user reference field, and choose "Is empty (NULL)" as operator.

That will show all nodes that don't have any value in the user reference field.


Using Entity Metadata Wrapper to set/get value from custom field added via Field API to custom entity type

I've forgotten to set fieldable => true in hook_entity_info. Now EMW works


Make sure you enabled one of the additional modules that allow you to export the content, e.g. "Recipe recipeML" or "Recipe MasterCook4". They will provide you with extra pages where you can import/export the content.

For example, "recipeML" will add new pages for importing/exporting the recipes on the following paths: admin/content/recipe/export_multi and admin/content/recipe/import_multi.
Visit admin/content, then click on "Recipes" from the list of local tasks and from there you can go to the import/export page.

Hope this makes sense.


Read this article about Leverage Browser Caching for Images, CSS and JS.

Add these lines to your .htacess file.

## EXPIRES CACHING ##
<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType image/jpg "access 1 year"
ExpiresByType image/jpeg "access 1 year"
ExpiresByType image/gif "access 1 year"
ExpiresByType image/png "access 1 year"
ExpiresByType text/css "access 1 month"
ExpiresByType application/pdf "access 1 month"
ExpiresByType application/javascript "access 1 month"
ExpiresByType application/x-javascript "access 1 month"
ExpiresByType application/x-shockwave-flash "access 1 month"
ExpiresByType image/x-icon "access 1 year"
ExpiresDefault "access 2 days"
</IfModule>
## EXPIRES CACHING ##

Also you can try

<FilesMatch "\.(jpg|jpeg|png|gif|swf)$"> Header set Cache-Control "max-age=604800, public" </FilesMatch>


Combine photos from parent node and referenced nodes into a single list (for slideshow)

As always there is more than one way of solving problems in Drupal. There is a way you could build a DB query with only Views that would combine the ER reference through Relationships.
But there is a way to solve this that is (arguably) "more Drupal", and that with the help of Content View Modes. They are not to be confused with Views module, we will actually combine the two separate features, View modes and Views (module), to build your solution.
Use View Modes on ER Fields in Views
View modes are different combinations of entity fields visibility and output settings. With View modes you can create many different "views" of the same content. For example, "Full" and "Teaser" are ubiquitous View Modes.
In your case you want a special View Mode of the Employee CT that shows their photos. Create a new View mode on the Structure > Display modes > View modes (you can also get to this page through each CT "Manage display" page).
Enable that mode, visit it (it becomes a sub-tab) and disable all Fields you don't need, configure the photos field to your liking.
In Views create a list of all Departments, add the Photos and Employees ER Fields.
When configuring the Employees field set the Formatter to the View mode you had created especially for this. ER fields usually only show ID of the referenced entities, exceptionally their titles, but with View modes you can pull any info from the referenced item.
This is how you get a list of all Departments with all the Department and referenced Employees photos listed.
Slideshow
The slideshow part of the Q depends on how you plan to build that in. You'll probably use some external library with a module that implements it into Views.
Depending on how a particular library and module work you will be able to apply it to each Views row, or to each Field.
To combine photos from both fields use the Exclude from display on the top field and Rewrite results on the bottom field. Use Replacement patterns to construct the HTML output that your slideshow library can use. In some cases you'll need to override with twig templates.


Cache pages/variables in hook_preprocess() for anonymous user

You may have encountered a core bug where a page cache is not respecting the max-age, or in other words, max-age is not bubbling up to the page cache. There's a workaround on the issue summary but the workaround has a few problems of its own so make sure you consider the implications carefully. The bug issue is postponed until 3 of the linked issues are resolved. Hope this helps.


Rule check if field value changed give always true

You have to use :value for the body or other textarea fields.

The problem is there:

{ "NOT data_is" : { "data" : [ "node:body" ], "value" : [ "node-unchanged:body" ] } }

Should be:

{ "NOT data_is" : { "data" : [ "node:body:value" ], "value" : [ "node-unchanged:body:value" ] } }


How to hide/remove a specific menu heading tittle

You should:

select the Structure->Blocks menu;
from the blocks list, click on "configure" next to your menu block;
specify <none> as block title.


You should do

$sql = "SELECT id FROM {ap_visits}  WHERE current_ip = ':current_ip' AND url = ':url' AND DATE_FORMAT(date_start, '%%Y-%%m-%%d') = DATE_FORMAT(NOW(), '%%Y-%%m-%%d')  AND is_logout = 0";

$result = db_query($sql, array(':current_ip'=>$current_ip, ':url'=>$url));


changed theme -> Logged out -> No log in field shown :(

You can go to the following path:
http://www.yoursite.com/?q=user/login


How do I include linked data to a Page in Page manager?

In the image below, one can see the Context settings for a particular Page variant. Under Contexts, one can also see Relationships.

Relationships are what one uses to tell Page manager to pull in more, related, data, based on the arguments that the page is built around.

With two nodes related to each other with a reference field, and the base node being supplied through the URI on node/%nid, we can add Node from reference as seen in the screenshot below.

Further content types (and other options) will now be available in Panels for display.


How to include a PHP Framework / Library in my module?

Your file path is maybe incorrect. Try the code below:

function mymod_libraries_info() {

    global $base_url;
    $path = $base_url . '/sites/all/libraries/phpexcel/PHPExcel.php';

    $libraries['phpexcel'] = array(
        'name' => 'PHP Excel',
        'version arguments' => array(
            'file' => $path,
            'pattern' => '/Version (\d+)/',
            'lines' => 5,
        ),
    'files' => array(
       'php' => array('PHPExcel.php'),
    ),
);
return $libraries;
}


You can create a template for that specific content type like

node--yourcontenttype.tpl.php

and inside you can check for the user roles like so

// Load the currently logged in user.
global $user;

// Check if the user has the 'editor' role.
if (in_array('editor', $user->roles)) {
  // print one image
} else {
  //print the other one
}


Alter the conditions in a DatabaseCondition object

You can grab the conditions array for the full query like this:

$conditions =& $query->conditions();

As you're getting the array by reference any changes you make to it (and the conditions within) will be reflected back on the query object before it's executed.

If you want to replace all of the conditions in the query you can simply overwrite that array with a new one (filled with conditions obviously).

It might be safer, though, to loop through the conditions array and remove/alter only the conditions that you need to change. This will make sure that conditions added by other modules will still get their chance to be included in the query.

Editing an existing condition is tricky (I haven't managed to get it to work yet though I haven't tried very hard!). I think your best bet is to rebuild the conditions you need to change from scratch and replace them rather than try to edit them directly.


Can I get dependent services into a custom class without creating a service?

Not sure how many classes/services you have, but the main point for having services is to have the dependencies injected. Drupal core alone has probably 100+ services, so I wouldn't worry too much about adding 10 or so more.

Using ContainerInjectionInterface is also fine, if you do that, you can use the class_resolver service that will take care of doing that, it also accepts both a class implementing that interface as well as a service name.

https://api.drupal.org/api/drupal/core%21lib%21Drupal.php/function/Drupal%3A%3AclassResolver/8.4.x

Depending on how you use/configure/decide which of your classes to you, you could also make a plugin type and make them plugins, e.g. like block plugins or field formatters.


How do I access webform components labels on the congratulations page

The loaded submission doesn't hold the label names so you'll have to get them from elsewhere. One option would be to load the webform node where they can be found. Here's an example about how this would look like in the code:

<?php
include_once(drupal_get_path('module', 'webform') .'/includes/webform.submissions.inc');
$nid = arg(1);
$sid = $_GET['sid'];
$submission = webform_get_submission($nid, $sid);
$node = node_load($nid);
foreach ($node->webform['components'] as $key => $component) {
  if (isset($submission->data[$key]['value'][0])) {
    if ($component['type'] == 'select') {
      $options = array();
      $items = explode("\n", $component['extra']['items']);
      foreach ($items as $item) {
        $item_parts = explode('|', $item);
        if (isset($item_parts[0]) && isset($item_parts[1])) $options[$item_parts[0]] = $item_parts[1];
      }
      $no = count($submission->data[$key]['value']);
      if ($no > 1) {
        $cont = '
'. $component['name'] .': ';
        foreach ($submission->data[$key]['value'] as $k => $v) {
          if ($k + 1 == $no) $cont .= $options[$v];
          else $cont .= $options[$v] .', ';
        }
        $cont .= '
';
        echo $cont;
      }
      elseif (isset($options[$submission->data[$key]['value'][0]])) {
        echo '
'. $component['name'] .': '. $options[$submission->data[$key]['value'][0]] .'
';
      }
    }
    else {
      echo '
'. $component['name'] .': '. $submission->data[$key]['value'][0] .'
';
    }
  }
}
?>


This can be achieved using following approach.

Create a content type for example "Favorite song" and add a field of "Term reference" type into this content type where widget will be "Check boxes/radio buttons" and select the vocabulary of songs for options.
Give permission to users to add/edit content "Favorite song",then while adding user will select their favorite songs from the list of songs.
Again to view/edit favorite song list of a user you can find the correct node by author of the node.

Hope it will help.


Where shall I place "PHP SAML" library so that SAML Authentication module could find it?

I dabbled with this before. In order to get phpsimplesaml to work you need a module that autoloads composer libraries. I ultimately gave up trying it on d7 because it was a nightmare to get everything working, but I at least had the library recognized.


UTMs stopped being caught on webform submission

The answer here provides the method you can use to pass URL query variables into hidden fields in webform.

What you need to do is assign a default value to each field which uses a token representing the query variable. So, for example, the field for "utm_unidad" should have a default value of:

[current_page:query:utm_unidad]

And so on for the other fields.


People created by non-administrator role are not allowed to edit their content

Because they don't have any roles associated with them. You need to add a role to the new users giving them the permissions you want them to have.


How add additional css classes to description field in webform component?

you can do this by using jquery on ready do this something like
jQuery(document).ready(function() {
         jQuery('#YOUR_FORM_ID .description').addClass('new-desc-class');
});


How to get a node content programmatically?

Assuming by 'contents' you mean the HTML for the node in a particular view mode, you're looking for node_view():

  Generates an array for rendering the given node.

e.g.

$node = node_load(1);
$view = node_view($node, 'full');
$rendered = drupal_render($view);


I don't follow exactly what you're asking, but if you want to give lower level users the ability to assign roles without needing the 'administer permissions' permission or other high level permissions, you can add the module RoleAssign.

  RoleAssign specifically allows site administrators to further delegate
  the task of managing user's roles while withholding the Administer
  permissions permission.

  RoleAssign introduces a new permission called Assign roles. Users with
  this permission are able to assign selected roles to still other
  users. Only users with the Administer permissions permission may
  select which roles are available for assignment through this module.

  RoleAssign is ideal for smaller sites with a system administrator and
  one assistant administrator role that should be reasonably restricted
  in what it allows. For larger sites with multiple levels of
  administrators or whenever you need finer-grained control over which
  role can assign which other role, check out Role Delegation.


How do I get the term name in a custom submit handler?

In a submit handler you can find the form object in $form_state:
$term = $form_state->getFormObject()->getEntity();


How to dynamically consume external RSS feed and display content Drupal 7 with feeds module?

I have sucessfully used Views XML Backend in situations like this.


Use rules to assign role based off custom field on user registration

The following Rule export does what you asked, for users created in the UI. In D8. I have tested it and it works. You will also need to use the (temporary) patch from https://www.drupal.org/project/rules/issues/2725525#comment-11438731 to work around the problem with in assigning roles.

The concept to understand is that Rules knows about the base fields for the entity type. But if you add fields, that's a new entity bundle, so you need to tell Rules that your data is of a certain bundle. To do that, you use the "Entity is of bundle" condition, as I show below. Then all the fields for that bundle will show up in the data selector.

langcode: en
status: true
dependencies: {  }
id: set_a_role_for_new_users
label: 'Set a role for new users.'
events:
  -
    event_name: 'rules_entity_insert:user'
description: 'Assign the ''student'' role to new users who identify themselves as students. Requires a boolean field ''field_is_student'' on the user object and requires an available role with machine id ''student''.'
tags: {  }
weight: 0
config_version: '3'
expression:
  id: rules_rule
  uuid: 36de9619-1401-4b21-a651-d3927c5b8dac
  weight: 0
  conditions:
    id: rules_and
    uuid: 416e90b0-d24c-4f37-8272-de0ecee5c375
    weight: 0
    conditions:
      -
        id: rules_condition
        uuid: bafe6fc4-f88f-4df2-af9b-2b3558257c2b
        weight: 0
        context_values:
          type: user
          bundle: user
        context_mapping:
          entity: user
        context_processors:
          type:
            rules_tokens: {  }
          bundle:
            rules_tokens: {  }
        provides_mapping: {  }
        condition_id: rules_entity_is_of_bundle
        negate: false
      -
        id: rules_condition
        uuid: 28787d22-54ca-49cf-af42-6f1011ed6494
        weight: 0
        context_values:
          operation: '=='
          value: '1'
        context_mapping:
          data: user.field_is_student.value
        context_processors:
          operation:
            rules_tokens: {  }
          value:
            rules_tokens: {  }
        provides_mapping: {  }
        condition_id: rules_data_comparison
        negate: false
  actions:
    id: rules_action_set
    uuid: 2933681a-a079-496d-bc79-f27ff53144eb
    weight: 0
    actions:
      -
        id: rules_action
        uuid: 38e8a3bb-0470-427f-80e1-53f6a703e8bf
        weight: 0
        context_values:
          roles:
            - student
        context_mapping:
          user: user
        context_processors:
          roles:
            rules_tokens: {  }
        provides_mapping: {  }
        action_id: rules_user_role_add


Can you use the features module to replace existing functionality

Yes, you can. You can install features, then export all the things you want to change. Install the feature on a copy of the site you are working on, and export again, after you made the changes. (and reinstall again to that copy site, until you are satisfied).

Then copy your feature to your production site, enable, and revert the feature (revert in this case means, making sure the feature behaves like defined in the feature, hence upgrading).

Good luck!


How do I add a Confirm Order button in Commerce Checkout?

I recommend starting at the website.com/admin/commerce/config/checkout/rules address, which will bring you to settings page where you are seeing "Express Checkout" options, which to my knowledge is not a PayPal feature and unfortunately is just shares the same name as their Express Payment Processor.

Next you want want to create a checkout rule, which will give you more control over the order process, which can be found at website.com/admin/commerce/config/checkout/rules

This process might start to get difficult, but essentially you want to create a Rule that will trigger a more detailed confirmation page, which can probably handled numerous ways and probably out of the scope of this question.


At least a partial answer could be to use Commerce in order to pay for access to a node. A user who clicks the link will be sent to the pay page, and upon completion of payment, the user will be assigned the role which can "flag" that proposal.

I'm not sure this would end up using the flag module, but you could theme it to look flag-ish.


Navigate to /admin/config/people/accounts and scroll to the bottom.


I tried executing a query similar to the one you are showing using an desktop application to connect to the MySQL server running on my computer, and I got the following error:

  You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '"%\") AND td.vid = n.vid' at line 1

Drupal reported the following error:

  PDOException: SQLSTATE[42S22]: Column not found: 1054 Unknown column '%\' in 'on clause': SELECT n.* FROM {node} n INNER JOIN {taxonomy_term_data} td ON n.title LIKE CONCAT( td.name, "%\" ) AND td.vid = n.vid;

The PDO driver seems throwing the wrong exception.

The error is caused from the fact you are escaping the second quote, and there isn't any other quote character, except the one ending the join condition.

If I recall correctly, you should not use the double quotes inside SQL strings. Rewrite the query as following, and it works.

$query->join('taxonomy_term_data', 'td', "sbc.tname LIKE CONCAT(td.name,  '%') AND td.vid = sbc.vid");

I also tried escaping the % character with another %, as suggested by @Clive, but the following still raised the same exception.

$query->join('taxonomy_term_data', 'td', 'sbc.tname LIKE CONCAT(td.name,  "%%\") AND td.vid = sbc.vid');

The following worked too, but the result doesn't change, compared to the first query I wrote.

$query->join('taxonomy_term_data', 'td', "sbc.tname LIKE CONCAT(td.name,  '%%') AND td.vid = sbc.vid");


How to use Drupal 8 ajax API for Menu links

You can try this for adding 'use-ajax' class to menu link:

/**
 * Implements hook_menu_links_discovered_alter().
 */
function MYMODULE_menu_links_discovered_alter(&$links) {
  if (isset($links['MENU_LINK_ID'])) {
    $links['MENU_LINK_ID']['options']['attributes']['class'][] = 'use-ajax';
    $links['MENU_LINK_ID']['options']['attributes']['data-dialog-type'] = 'modal';
  }
}


How to switch between conflictual hooks?

If you implement a hook, it will always be executed.

The condition of a query string makes things more complicated in your situation, because all menu items are defined by their path (taxonomy/term/tid in your case). This means that - as far as Drupal is concerned - taxonomy/term/tid?v=value and taxonomy/term/tid have the same menu item, so both requests will be handled by the same code.

Is it really necessary that the URL takes the form of ?v=value? If you could make it taxonomy/term/tid/value, you can create your own custom menu item for taxonomy/term/%/%, and simply leave the taxonomy/term/tid path as is.


Theme the taxonomy tags list in the node teaser

Take a look at this tutorial that shows you how to create a custom formatter for specific field types. The taxonomy term field type machine name is taxonomy_term_reference


Git Workflow Acquia Cloud and Acquia Dev desktop

Working on the frontend isn't tied to using Acquia Dev Desktop or
not. It's a personal preference to work locally by cloning a remote
site and work on theming/frontend and commit changes periodically to
the remote repo when you're happy with the changes you see in your browser. Some customers prefer working directly on the Acquia Cloud dev environment with Livedev. Really, it's what you think is best for you.
Git is a decentralized version control system. It means both you and your client can checkout the Acquia Cloud repo and hold a live copy of the repo. You and your client can then commit/push code either to the default branch (master) or with a feature branch. This is by no means specific to Acquia Cloud. This is how git works. What matters is you git pull always before committing / pushing code, so that you can retrieve the changes your client has made on the current working branch (e.g. master). With a feature branch, it'll require you merge it back to e.g. master when it's ready. See https://git-scm.com/book/en/v2/Git-Branching-Branches-in-a-Nutshell for details.


I have disabled the dev themer and all is better.


How do I keep data without using sessions

If you don't need your data server side, you could use cookies, using user_cookie_save. Or store your variables in window.localStorage (it's HTML5, see here for browser support) in your own javascript code/behavior, like :

function storePersistentValue() {

  //Check whether local storage is available or not

  if (window.localStorage) {

    window.localStorage.MyKey = "HTML 5 features";

  }

}

function getPersistentValue() {

  //Check whether local storage is available or not

  if (window.localStorage) {

    var text = window.localStorage.MyKey;

  }

}