How to create a list of untranslated content in views? I want to create a list of all nodes that has not been translated into a specific language - how do I do that?

I'm using Drupal 8.

You can use the Translation Views module.

I assume you have
enabled core module language and content translation
and added a 2nd language in admin/config/regional/language
and you should also have enable translation and probably language selection for a specific content type lets say basic page

content translation core has a views filter for the purpose of finding the nodes that need translation or ones that need to REVISE their translation (that are outdated)

create a view untranslated and add 2 filters
Content: Default translation (= True)
Content: Revision translation affected (!= False)

NOTE: this will originally show you all untranslated but if a translation flags other translations as flag other translations as outdated then those SOURCE nodes will also be included in the list


Update module with Drush + commit with Git What's the best way to update a module and commit with git?

Currently I'd use drush pm-updatecode then inspect with git status. The problem then is there are many files that have changed, been added or been deleted. Then performing an add or rm on the right files seems a bit cumbersome.

Would it be better to first do rm on the module, commit, then drush dl, add, commit?

git add -A is the simple answer you are looking for.  It will add all of the files anywhere inside the current working directory, including any new files that were provided or removed pm-updatecode.  (Note: git add . behaves similarly to git add -A, except that it will not include removed files in the commit.)

There is one inconvenience with git add -A, though, and that is that if you have any stray files in the way, they will be added to the repository as well (obviously enough).  You can get around this problem by listing the files that should never be committed in a .gitignore file, or simply use git reset HEAD unwantedfile prior to git commit, as recommended by git status.

drush will manage this for you with the --version-control=svn option, but as you may surmise, this is only useful when you project is checked in to svn.  As of yet, no one has written --version-control=git.  This was discussed in http://drupal.org/node/797190, but closed "won't implement".  There are some other good git commands to try in that thread as well.

git rm -r module
drush dl module
git add module
git commit -m "Upgrading module"
git push origin master


Form field default value not working I have an inherited project to which I need to add small form api changes. The changes are to two form fields shown below:

$form['start'] = [
    '#type' => 'number',
    '#title' => t('Between:'),
    '#required' => TRUE,
    '#default_value' => 1988,
    '#min' => 1900,
    '#max' => date('Y'),
    '#value' => 1988,
];
$form['test'] = [
    '#type' => 'number',
    '#title' => t('TEST:'),
    '#required' => TRUE,
    '#default_value' => 1988,
    '#max' => date('Y'),
    '#min' => 1900,
    '#value' => 1995,
];
$form['end'] = [
    '#type' => 'number',
    '#title' => t('and'),
    '#required' => TRUE,
    '#min' => 1900,
    '#max' => date('Y'),
    '#default_value' => 1999,
    '#value' => 1999,
];

This is a bizarre problem as my attempts to set the #value and #default_value for both the start and end fields are not working.

However, I created the test field and it successfully adds to the form and sets my configured value and default_value.

So, for the start field, I expect to see 1988 as the displayed value but instead that form field displays 1900.
The test field I create meanwhile displays and behaves properly ... go figure.

As it is an inherited project, I wonder if there are other means of configuring a form which I am unaware of ?

UPDATE:
Thanks to Leymannx for contributing and attempting to help. As per your suggestions, I tried the following but without success:

$form['start'] = [
    '#type' => 'number',
    '#title' => t('Between:'),
    '#required' => TRUE,
    '#min' => 1900,
    '#max' => idate('Y'),
    '#default_value' => 1988,
];

Note: The problem is that both the start and end fields refuse all my efforts to configure the value and default_value. So, for the start field, I expect to see 1988 but instead that form field displays 1900.

I removed all '#value' keys and replaced date('Y') with idate('Y') and for me it's working without any problem. Flush cache!

$form['start'] = [
  '#type' => 'number',
  '#title' => t('Between') . ':',
  '#required' => TRUE,
  '#default_value' => 1988,
  '#min' => 1900,
  '#max' => idate('Y'),
];
$form['test'] = [
  '#type' => 'number',
  '#title' => t('TEST') . ':',
  '#required' => TRUE,
  '#default_value' => 1988,
  '#max' => idate('Y'),
  '#min' => 1900,
];
$form['end'] = [
  '#type' => 'number',
  '#title' => t('and'),
  '#required' => TRUE,
  '#min' => 1900,
  '#max' => idate('Y'),
  '#default_value' => 1999,
];


How to grant permission directly to a user other than a role? Our client frequently need to grant arbitrary permissions to arbitrary users. It's very boring and fault-prone for our client to create new roles, assign users to roles and then set role permissions.
The module user permissions can grant permissions directly to a user, but the grantee must have the powerful permission "administer permissions", which is not what I want.

Use the user permissions module.  Contrary to your objections to using this module, it is not the grantee who needs the  "administer permissions", but the grantor

Create role:

if (!user_role_load_by_name('new_role')) {
  $role = new stdClass();
  $role->name = 'new_role';
  user_role_save($role);
}

Add Permissions:

$new_role = user_role_load_by_name('new_role');
$values[] = array(
  'rid' => $new_role->rid,
  'permission' => 'create article content',
  'module' => 'modulename'
);
$query = db_insert('role_permission')->fields(
  array(
    'rid',
    'permission',
    'module'
  ));
foreach ($values as $record) {
  $query->values($record);
}
$query->execute();


Hook module placement I have the following file named background_image_style.module

In my Drupal 8.3.3 site, paragraphs.module is at MySite/web/modules/contrib/paragraphs/paragraphs.module.

I installed the site and all contributed modules with Composer.

composer require drupal/paragraphs
vendor\bin\drupal module:install paragraphs

Where does my hook module go? (I just copied it in where the paragraphs.module is.) Are there any other overhead steps that needs to be done (e.g. editing other files)?

I tried several locations and cleared the cache each time.

    /**
     * Implements paragraphs().
     */
    function background_image_style_preprocess_paragraph__banner(&$variables) {
      $paragraph = $variables['paragraph'];
      if (!$paragraph->field_image->isEmpty()) {
        $image = $paragraph->field_image->entity->url();
        $variables['attributes']['style'][] = 'background-image: url("' .                 $image. '");';
        $variables['attributes']['style'][] = 'background-size: cover;';
        $variables['attributes']['style'][] = 'background-position: center         center;';
      }

From Where to Put the Module Files:

  Manual import location

  If you import a module 'manually', you should place your module in that same default recommended location, HERE:

  [d8-root]/modules/HERE

  [Themes: [d8-root]/themes/HERE]

It's a good idea to keep custom and contrib modules separate, hence Drupal Project putting contributed modules into their own folder; following on from that, there's a pretty common convention to place custom modules under [d8-root]/modules/custom/. But you don't have to, you can use whatever hierarchy you like under /modules, Drupal will pick up anything it finds recursively.

After it's in place, don't forget to enable the module, or it won't do anything.

The problem was the .yml file missing. A little different from d7 but more or less the same concept.


Running Drush on the server I want to run Drush on a OpenSuse Linux Version 12.1 box 32-bit machine.
I have a server admininistrator that takes care for the backend.

What do I need to ask him, in order to get Drush running on the server?

If you want to run Drush, you need ssh access to the server.  This means you need your sysadmin to make an account in the server for you.

To run the "pm-" commands, and a few others, this account will need to have both read and write access to the DOCROOT.  There are a few ways to do this; let your admin pick which is best for your setup.

You will also need PHP available from the command line, preferably with the same php.ini that the website uses.

Drush should be installed as a dependency of Composer, so first install Composer:

sudo zypper install php-composer

Then use Composer to install the Drush 8.x version:

composer global require drush/drush:8.*

To register Drush as a dependency of Composer:

composer require drush/drush

To integrate Drush with the Bash CLI utility:

drush init

OpenSuse Direct Install Packages:

Drush on OpenSuse
Composer on OpenSuse


How to update the node status? I'm using data from JSON to create new nodes or update fields on existing if node exist on my Drupal 8 website. So, when I use method to update nodes, I need to save in array node id of updated nodes and keys of fields with changed values in this node.

After update is finished I need to print table with all nodes of this content type where fields of updated nodes need to have different style (color, background, etc).

So if my old node have
body = "body1" and description  = "description 1" and new node have body = "body2"and description  = "description 1" after update is finished i need to get output like this:

Here is an example:

$node = \Drupal\node\Entity\Node::load($nid);
$node->set("body", 'New body text');
$node->set("description", 'New value');
$node->save();

Any suggestion?

Note: when I use $node->save(); if all updated values is same nothing is changed (date of node in content from admin panel is same as before update), but if values is different I need to store node id, keys and values only of changed fields in array.

To set the status you can use the setPublished() method:

  public function Node::setPublished

  Sets the published status of a node..

  Parameters

  bool $published: TRUE to set this node to published, FALSE to set it
  to unpublished.

In your case:

$node = \Drupal\node\Entity\Node::load($nid);
$node->set("body", 'New body text');
$node->set("field_name", 'New value');
$node->setPublished(TRUE);

you can un publish by setting status to 0
          $node = \Drupal\node\Entity\Node::load($nids);
          //set Unpublishing node
          $node->status = 0;
          //save to update node
          $node->save();


Unable to save textfield on node_save() $fbuser = new stdClass();
   $fbuser->first_name = 'abc';
   $fbuser->last_name = 'cde';
   $fbuser->location = 'Vas';
   $fbuser->link = 'http://www.facebook.com';
   $fbuser->gender = 'male';
   module_load_include('inc', 'node', 'node.pages');
   $node = new stdClass();
   $node->type = 'profile2';
   node_object_prepare($node);
   $node->uid = 1;
   $node->field_profile_fn[0]['value'] = $fbuser->first_name;(textfield)
   $node->field_profile_ln[0]['value'] = $fbuser->last_name;(textfield)
   $node->field_profile_city[0]['value'] = $fbuser->location;(textfield)
   $node->field_profile_facebook[0]['value'] = 'http://www.facebook.com';(textfield)
   $node->field_profile_gender[0]['value'] = $fbuser->gender;(select list)
   node_save($node);

In the above code I am trying to create a new content of type profile2 .
My node is created but some of the fields show empty text like

field_profile_facebook which is textfield does not show value provided above and gives empty text.

You forgot to add the language to your fields:

$node->field_profile_fn[LANGUAGE_NONE][0]['value'] = $fbuser->first_name;

But even then, this is not the way to go. You should take a look at https://www.drupal.org/documentation/entity-metadata-wrappers

This approach allows you to use something like this:

 $wrapper->field_profile_fn->set($fbuser->first_name);
 $wrapper->save();


How to pre-populate fields in checkout? We have a product that is being sold with Drupal Commerce (using Drupal 7). This specific product is going to be advertised in more ways than just the Drupal site (e.g. email, other sites).

These other sites can have a form in which the user enters some basic information (Name, phone, email). This data is sent to Drupal (curl), a cart and session is created (anonymous unless the user is logged in our site) and the session ID is sent back to the calling website.

The user is redirected to our Drupal site, and the session is restored using the id that was passed.

Everything is working fine, but the user has enter the name, phone and email twice because Drupal tries to pre-populate the checkout fields with the user data, and in this case the user is anonymous, even though I have the user data from the first call.

Is it possible to add this information (name, email, phone) after calling commerce_cart_product_add() for anonymous users? The fields in checkout should get pre-populated even if the user is anonymous.

You can do one of two things: store the incoming data in the session somehow and alter it into the appropriate fields via hook_form_alter() or immediately create the relevant customer profiles for the session and reference them from the cart order you create. Default rules in Drupal Commerce will handle assigning those customer profiles to any user account that gets created during checkout for your anonymous sessions.


Override page.html.twig with custom module template I want to override the page.html.twig template from a custom module. I know how to create a suggestion, but I would like it to find the template file in my custom module.
function promo_accc_theme_suggestions_page_alter(array &$suggestions, array $variables) {
    $suggestions[] = 'page__promo__accc';
}

I'm not sure what I would need to do from here to get Drupal to look in /custom/modules/promo_accc/templates.

drupal_get_path('module',$module_name)  function will return the path to your custom module so:
function promo_accc_theme_suggestions_page_alter(array &$suggestions, array $variables) {
    $suggestions[] = drupal_get_path('module','promo_accc').'/templates/page__promo__accc';
}

for more info about the drupal_get_path() function: https://api.drupal.org/api/drupal/core%21includes%21bootstrap.inc/function/drupal_get_path/8.7.x


use URL with query as URL destination I mean can we have something like this? url with double ? in drupal?

http://drupal.org/?destination=xxx/yyy?token=zzz

Sort of, but you'll need to URL encode the second ? otherwise the URL will be invalid.

The best thing to do is use l() or url() which will do this for you:

$query_string = array('destination' => 'xxx/yyy?token=zzz');
$url = url('<front>', array('query' => $query_string));

That will produce the string:

/?destination=xxx/yyy%3Ftoken%3Dzzz

Which is the correctly encoded version of the URL in your question.

Drupal will also respect this method when auto-redirecting based on a form submission etc. So the page you get directed to will actually look like this:

/xxx/yyy?token=zzz

You can do it like this:

http://drupal.org/?destination=xxx/yyy&token=zzz


modified value in form_state but it is not being saved in the validation of my form i pass the form_state by reference and I modified the form state value of one of the fields with $form_state['values']['field_total_payment']['und'][0]['value'] = $total_payment;

I also tried  form_set_value($form['field_total_payment'], array('und' => array(0 => array('value' => $total_payment))), $form_state);

and I add a second submit to check if the value is there and I can see that with both pieces of code it is in the form_state['value'] , but it is not getting saved to the node.

What is missing for this information to be stored into the database?

Use

$form_state->setValue($key, $value);

In your case, that should be

$form_state->setValue(['field_total_payment'], $total_payment);


Why is my migration status table empty? I wanted to delete all migration modules because of that I use

drush config-delete migrate_plus.migration.ID

After that, I create a new migration module and enable it with

drush en migrate_NAME

and rebuild the cache.
I look at the status table with

drush migrate:status

but the table shows no migration. If I enable the migration again I get the message "Already enabled". When I try to import something I get the message "No migrations found".
Does anyone have any idea why this might be?

I think that you are mixing up things. By doing

drush config-delete migrate_plus.migration.ID

you are just deleting migration_plus configuration but you are not disabling the module, it is still enabled. If you really want to disable the module and of course the configuration, you'll have to drush pm migrate_plus.

Concerning the "No migrations found" message, your custom module has to define correctly the new migrations (.yml files).


Display a block based on the term reference field of the current node What I'm trying trying to do sounds fairly simple, but I can't get my head around it.

I'm having 2 taxonomy vocabularies: machinery and batteries (both created with NAT for all that matters), and 2 content types which are named the same.

Both the content types provide the ability to check related items (a regular term reference field). For the machinery node the user can check which batteries are suitable, and for the battery node the user can check which machines use this battery.

Basicly what I'm trying to is: if you're on a page about a specific machine, it should show the batteries that are related to it, be it as teasers (or fields) in a block. And vice versa: when you're on a page about a specific battery, it would show all the machines in which it fits.

I've been boggling around with relationships and contextual filters, but it just wouldn't work out so far (spent a couple of hours here). Does anyone have an idea how to sort this out please?

There's possibly an easier way with the References module. In that case it wouldn't even require NAT, but just a View with contextual filter based on the Reference field.

I can't summarize those instructions, MPD, you have to follow the exact steps or it won't work. Full instructions:

Create
2 content types, both correctly configured with NAT:

Machinery
Battery

2 vocabularies, both will be filled along the way with terms generated by NAT:

Machines
Batteries

Remark the difference in names, just to keep things clear in this explanation (so you don't mix up).

Add a "Term reference" field in both the content types. In het "Machinery" content type this field will refer to the "Batteries" vocabulary, and vice versa: the "Battery" content type has a term reference field that's linked to the "Machines" vocabulary.

Create the necessary nodes with both the Machinery and the Battery content type - which will generate terms in both the Machines and Batteries vocabulary.

Once this is done, check the right terms in each node: what batteries are related to this machine (for the Machinery nodes), and vice versa: in what machines does this battery fit (in the Battery nodes).

Once this is done, create a View and create a block in it. The block in this example will display related machines, being displayed on the page of a battery.

Set the format to whatever you like (HTML-list, unformatted, grid, ...). I'm using fields in this example (not content, but it should work as well).

Add the fields you'd like to show (Title, Image, ...)

Add the following filter: Content: type (=Machinery)

Now add 2 relationships:

NAT: Nid (Identifier: "NAT node")
Content: Taxonomy terms on node

Relationship: "NAT node"
Vocabularies: "Machines"
Identifier: "term"

Add a contextual filter:

File Usage: Entity ID

Relationship: "NAT node"
When the filter is not available: provide default value (Content ID from URL)
Finally go to the Query settings of the View and check "Distinct" (to avoid duplicates).

Et voila, the first block is ready to go.

For the second block that will show associated batteries on a Machinery page, duplicate the block we've just created and modify the proper settings accordingly (content type filter, vocabulary in taxonomy terms on node).

You should be good to go - it works in both ways now.

I've add some screenshots in case they may be useful (with other names though than in this example, so don't get confused).

(Maybe the EVA module does something similar, both the method above works in both directions)


Unable to create an admin menu link I am trying to create a menu link in Drupal 8. I am following this document: https://api.drupal.org/api/drupal/core!includes!menu.inc/group/menu/8

My module name is twitter_pull and I was able to create the path fine, and it loads a form on that page, I just can't get it display a menu link. I have tried flushing the caches but that didn't do anything.
Here is my code:

Inside my twitter_pull.routing.yml

twitter_pull.settings:
  path: 'admin/config/services/twitter-settings'
  defaults:
    _form: '\Drupal\twitter_pull\Form\TwitterSettingsForm'
  requirements:
    _permission: 'administer site configuration'

Inside my twitter_pull.links.menu.yml

twitter_pull.settings:
  title: 'Twitter settings'
  description: 'Twitter settings for your site'
  parent: system.admin_config_services
  route_name: twitter_pull.settings
  weight: 100
  #Use menu_name when you want to add your link to a non-system menu.
  #menu_name: devel

It looks like you are using an older version of Drupal core. Upgrade to one of the betas or the latest 8.0.x from Git and it should work fine.

In the latest versions the filenames have been changed, as reported in YAML files for menu links, contextual links, local tasks, and local actions have been renamed. 8.0.0-alpha14 is the first tagged release with the filename change.

Its because of incorrect file name issues. I also faced the same kind of issues and after analysis I got to know, I was did a minor mistake on the file name( 's' got added additionally ). Like: twitter_pulls.links.menu.yml instead twitter_pull.links.menu.yml

twitter_pull.links.menu.yml
twitter_pulls.links.menu.yml

Thanks


drush @sites command doesn't work The command drush @sites status doesn't do anything.

The full command obtained for the process is:

  /usr/bin/php /home/myuser/.config/composer/vendor/drush/drush/drush.php --php=/usr/bin/php --php-options= @sites status

This is my enviroment:

Drupal:  8.2.4
Drush:  8.1.7

The "drush site-alias" command says me:

@site1
@none
@site2
@self
default
site1
site2

I have a setup for Drupal multi-sites with subdirectories, the aliases file is:

~/.drush/aliases.drushrc.php

<?php
/**
 * @file
 * Site alias for all sites
 */
$root = '/var/www/html';

$aliases['site1'] = array(
    'uri' => 'multisite.local/site1',
    'root' => $root,
    'path-aliases' => array(
        '%dump-dir' => '/tmp'
    ),
);
$aliases['site2'] = array(
    'uri' => 'multisite.local/site2',
    'root' => $root,
    'path-aliases' => array(
        '%dump-dir' => '/tmp'
    ),
);

The full output of the drush status command is:

 Drupal version                  :  8.2.4
 Site URI                        :  http://default
 Database driver                 :  mysql
 Database hostname               :  localhost
 Database port                   :  3306
 Database username               :  db_user
 Database name                   :  db_name
 Database                        :  Connected
 Drupal bootstrap                :  Successful
 Drupal user                     :
 Default theme                   :  bootstrap
 Administration theme            :  seven
 PHP executable                  :  /usr/bin/php
 PHP configuration               :  /etc/php.ini
 PHP OS                          :  Linux
 Drush script                    :  /home/myuser/.config/composer/vendor/drush/drush/drush.php
 Drush version                   :  8.1.7
 Drush temp directory            :  /tmp
 Drush configuration             :
 Drush alias files               :  /home/myuser/.drush/aliases.drushrc.php
 Install profile                 :  standard
 Drupal root                     :  /var/www/html
 Drupal Settings File            :  sites/default/settings.php
 Site path                       :  sites/default
 File directory path             :  sites/default/files
 Private file directory path     :  private/default
 Temporary file directory path   :  /tmp
 Sync config path                :  sites/default/files/config_BrLQsjBr6VkcTEyCkzkY-es-hzISWg4d3oV2EEEoqh-UZMLBJWDiDaq78TIWm-lBbVi-aPHISw/sync

"@sites" is no longer available with Drush 9. I presume this what is being used with Drupal 8 here.

More information here:
https://github.com/drush-ops/drush/issues/3019#issuecomment-334503217

  Drush 9 no longer supports executing a single command on multiple sites with alias lists (@A,@b,@c) or @sites. Neither of those syntaxes are available in any context. You may still use drush sa @group to see all aliases in a group; that is the only context in which Drush recognizes alias lists.


Results page template of Search API module In Drupal 8, the default Search uses template file 'search-result.html.twig' to display results.

I have disabled the default search and enable module 'Search API' and Search API SOLR(used for Backend) to perform search in Drupal 8.

I need to customize the search results page of Search API not default search. How can I do this? The search-result.html.twig template doesn't work, with the Search API module.

Search API filters and results are displayed using views - so you need to override the views template.

So if you create a view page for your search called "Search API" (search_api) - and the machine name of that view is page - then you can add the following file to your theme:

my_theme/templates/views-view--search-api--page.html.twig

You probably want to start by copying in the contents of core/modules/views/templates/views-view.html.twig into the above template file and start tweaking it from there.

For help creating the actual view you may find these links helpful:

https://www.drupal.org/docs/8/modules/search-api/getting-started/search-forms-and-results-pages/searching-with-views-0
https://sweethoneycode.com/custom-search-with-search-api-and-views-drupal-8/


How can I replace all my internal links automatically? I have changed the domain of my website from www.mysite.com to mysite.net. I upload the site to the new domain and all is fine, but I have more than one thousand nodes, and in almost all the nodes I have a link to another node on the site.

The link are absolute so they have this form: www.mysite.com/node/22 and I need to change all nodes to the new domain.

Changing 1,000 links manually is too much. How can I do this automatically??

Why are you using absolute links? If you were using relative links, of the form /node/22, the problem would not arise.

I am assuming you are using Drupal 7. The answer for D6 would be a little more complex.

If the links are in the node body, and if you have direct access to your database, you can update the text by running a query on the field_data_body and field_revision_body tables.

First, back up your database in case this goes wrong.

Then run the following query on your tables:

UPDATE field_data_body SET body_value = REPLACE( body_value, 'a href="http://www.mysite.com/','a href="http://mysite.net/');

Repeat with the field_revision_body table.

This should change all references to the old domain with the new domain.

If you have links in the comments, you might also want to do field_data_comment_body and field_revision_comment_body, scanning for references in the comment_body_value field.

In the event the links are being generated automatically by a text filter, change the REPLACE patterns accordingly.

What you could do if you don't want to touch the db is using hook_process_html, so that you use relative path's for all content, scripts and stylesheets:

function MY_MODULE_process_html(&$vars) {
  //use relative path
  $vars['scripts'] = str_replace("http://www.mysite.com/", "/", $vars['scripts']);
  $vars['styles'] = str_replace("http://www.mysite.com/", "/", $vars['styles']);
  $vars['page'] = str_replace("http://www.mysite.com/", "/", $vars['page']);
}


populating a webform select list from a view? I have a webform in D7 where I want the user to select a value from a dropdown list. These values I want to be dynamically updated from a view. How can I do this?

I found the webform viewreference module, but it's D6. There is a d7 port that someone made using coder, but, like author notes, I get an error when I try to view the form with the view reference webform component.

Are there any solutions out there?

Take a look at the sandbox project Webform Views Select.

  This module will let you populate a webform select component with data from a view.

EVA might work for that, however I haven't used it in this scenario.


Organic-Groups theme selection Does anyone know how to use the OG-Theme module to set unique themes for groups?

I can't find a relevant user interface.

Found the readme file online which describes the steps to add theme selection per group.

It can be found @ here.

It uses fields to make the selection as I suspected but the initial configuration is done via a different user interface.

Thanks for your input Steven.

Themekey module will give you gross control over which theme your OG uses.

  From module documentation,

  ThemeKey allows you to define simple or sophisticated theme-switching
  rules which allow automatic selection of a theme depending on current
  path, taxonomy terms, language, node-type, and many, many other
  properties. It can also be easily extended to support additional
  properties exposed by other modules.


How to use Drupal.behaviors? I am trying to do a simple ajax request when the document is ready. Along with that, I also want to provide a function that is an onclick event.

Here is my code:

(function ($) {

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

            $.ajax({
               type: "GET",
               url: "/admin/user-alert/get-message",
               success: function(data){
                   $('div#block-user-alert-user-alert').html(data);
               }
             });

        $('div.user-alert-close a', context).click(function() {
          alert(1);
        });
    }
  };
}(jQuery));

The click function does not fire. The ajax does. What can I wrap the ajax in so it only does this on page load, or, is that assumed through attach?

I also tried an onclick on the a tag, but Firebug said the function was undefined, even when it was defined as function (function name) in the .js file.

Edit:

If you have a click event that accepts an argument, how can I pass that in?

As I understood it, Drupal.behaviors attach would allow the .click to fire on an element created at anytime. But just in case, I would try using .delegate(), as in

$('body').delegate('div.user-alert-close a', 'click', function() {
  alert(1);
});

Best practices for this, follow:

$('.yourClassElement').once('behaviorsName').click(function() {
    console.log('Cliqued');
});


User registration form throws validation errors on already unset profiles´ fields Using Drupal 7 with Profile2: I have a number of profile types, with different fields, some of which I want a registrant to already fill up during the registration process. I´ve checked "Show during user account registration" for all. In my custom module, I´m first taking the registrant´s choice of profile, then unsetting (unset(); also tried hide() and ...[#access]=FALSE) all the other profiles and then rendering the registration form. This 'shows up' correctly because I only get to see the chosen profile fieldset. However, when I submit the form I get validation errors (required fields) on the unset profiles´ fields. So apparently only unsetting/hiding/etc. won´t do the trick. What am I missing?

Appreciate any help!

Best,
Mir

The Profile2 Registration Path module  solves the issue!

  This module enables administrators to set unique registration paths per Profile2 profile type.


Search results only for the current language I have a site with 4 languages and am using the builtin search to look for content on the site. How is it possible to restrict the search results only to the currently selected language?

I tried looking into Configuration > Search Pages, but do not see any way how to do that there.

The "Advanced" core search has this built in. If you prefer to do this from a theme - you could do it with form_alter. This basically hides the advanced search settings and sets current language as the only language to get results from, in the search block and search page.

Alternately you can just allow users to control which language they want to get results from and simply allow them to use advanced search.

Code for theme:

/**
 * Implements hook_form_FORM_ID_alter().
 */
function hook_form_search_form_alter(&$form, &$form_state) {
  $form['help_link']['#access'] = FALSE;
  $form['advanced']['#access'] = FALSE;
  $form['basic']['keys']['#title'] = '';
  $manager = \Drupal::languageManager();
  $form['advanced']['lang-fieldset']['language']['#default_value'] = [$manager->getCurrentLanguage()->getId()];
}

/**
 * Implements hook_form_FORM_ID_alter().
 */
function hook_form_search_block_form_alter(&$form, &$form_state) {
  $manager = \Drupal::languageManager();

  $form['advanced-form'] = [
    '#type' => 'hidden',
    '#value' => 1,
  ];
  $form['f[0]'] = [
    '#type' => 'hidden',
    '#value' => 'language:' . $manager->getCurrentLanguage()->getId(),
  ];
}

/**
 * Implements hook_query_TAG_alter()
 */
function hook_query_search_node_search_alter(&$query) {
      $language = \Drupal::languageManager()->getCurrentLanguage()->getId();
      $query->condition('i.langcode', [$language, 'und', 'zxx'], 'IN');
}


Add search to the Drupal 7 find content By default drupal 7 find content page comes with filter by type and status. I wanted to give one more filter, where user can type the few letters from the title they are looking for so that they can find the article/page with ease even when theres 100's of content in the site.

I did something similar using views and exposing title as a filter. But it would be great to add this field and search to the default filters we find in the drupal 7 find content page.

Try the Administration Views module:

  Replaces administrative overview/listing pages with actual views for superior usability.

It will let you replace the standard content admin page with a view, to which you can add as many filters as you need.

I think it's admin accessible area and instead of modifying it why don't you try  search module with Search Autocomplete module

hope it will help you :)


Why am I getting call to undefined function after splitting module functions to two files? Now my module has two main files:

menu_perm.module
menu_perm.admin.inc

I added second file to .info:

  files[] = menu_perm.admin.inc

I cleared the cache.

In my test class (PHPUnit) file I am bootrapping Drupal by:

drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

and I call form submit function manually inside test function, ends with below error:

  Call to undefined function menu_perm_user_form_submit()

Function is in menu_perm.admin.inc.

Before this everything was ok.

What am I doing wrong here?

files[] only works for class/interface autoloading, it won't include arbitrary PHP files. The docs say

  Drupal now supports a dynamic-loading code registry. To support it, all modules must now declare any code files containing class or interface declarations in the .info file

You can get around it by adding a line like this to the top of your .module file:

require_once DRUPAL_ROOT . '/sites/all/modules/my_module/my_module.admin.inc';

Use module_load_include inside your test function, e.g.
    module_load_include('inc', 'my_module', 'my_module.admin');


How to redirect from URL with trailing slash to one without We are using the Redirect module 8.x-1.2 with Drupal 8.5.6. When generating URLs, we are finding that a trailing slash is added to the end of the URL, and this is creating a 503 error code.

How would I redirect the anonymous users from the URL with the trailing slash to the one without trailing slash?

Select the Enforce clean and canonical URLs checkbox in  admin/config/search/redirect/settings.

Enabling this will automatically redirect to the canonical URL of any page. That includes redirecting to an alias if existing, removing trailing slashes, ensure the language prefix is set and similar clean-up.

In my case, whenever I accessed a url, four slashes were automatically appended to the url (IP////<node_name).

Following steps resolved my issue:

Ensure that following entry is available in Apche configuration file - httpd.conf.
LoadModule rewrite_module modules/mod_rewrite.so
Create a php file test.php with the following code.
<?php echo phpinfo(); ?>
Open test.php in your browser. Check the Loaded Modules section to ensure that mod_rewrite is available.
Also open the root Drupal PIP folder and ensure that .htaccess folder is there.


Solution to migrate a field collection My requirement is to migrate  content nodes in xml format to drupal 7 content type fields.The xml contains a node which has to be field collection in drupal.I know how to migrate field which are enity references and term references.But i am new to field collection migration.I am using drupal migrate contrib module for migration.
The field collection node in my xml file.

<myphotos_grid grid="true"><![CDATA[<rows>
  <row rowID="1">
    <rowAttribute>
      <theName>photo-name</theName>
      <value>photname1</value>
    </rowAttribute>
    <rowAttribute>
      <theName>photo-credit</theName>
      <value>my credit</value>
    </rowAttribute>
    <rowAttribute>
      <theName>photo</theName>
      <value>
      <attachment id="1009343343"/>
      </value>
    </rowAttribute>
  </row>
  <row rowID="2">
    <rowAttribute>
      <theName>photo-name</theName>
      <value/>
    </rowAttribute>
    <rowAttribute>
      <theName>photo-credit</theName>
      <value/>
    </rowAttribute>
    <rowAttribute>
      <theName>photo</theName>
      <value>
      <attachment id="4432434344"/>
      </value>
    </rowAttribute>
  </row>
</rows>]]></myphotos_grid>

I am writing a base class for my content types migration by extending XMLMigration class and it defines the migration source files and destination.Also i am writing corresponding classes for each content type which defines the field mapping by extending base class.

Above xml grid node in xml which has to be migrated to to field collection in my content type X in drupal 7 site.

My queries

Whether i need to write a seperate class for field collection extending my custom content type X migration class or adding the field mappings for field collection in the custom content type X migration class?
Whcih is the best standard to migrate field collection in drupal?

I am new to this field collection migration,please help,Also very sorry for my english.

I think you're on the right track. If I'm understanding your question, you won't need to add an extra class.  Instead, you'll want to use your existing Migration class's complete() method, which is called after the node has been created.  Within complete(), you can then use entity_create to create your field collection and entity_metadata_wrapper around your newly migrated node to set a reference to your field collection entity.

In psuedocode,

public function complete($entity, stdClass $row) {
  fc_entity = entity_create(...)
  $ewrapper = entity_metadata_wrapper('node', $entity);
  $ewrapper->fc_ref_field->set( $fc_entity->nid );
  $ewrapper->save();
}

Or something thereabouts. When in doubt, "whatever works" is the correct standard for migration code. Hope that helps get you started!

i have found one method  to migrate field collection.It is similar to your solution.

Please read  my blog http://fieldcollectionmigration7.blogspot.in/


html text or custom image to the user profile page? On my user profile page, how do i add some extra html code or custom php code to the user profile page? as i would like to add a custom generated image based on userid in the profile page.

Please advice.

you can also add a block to the "content area" to be shown below the user profile (restricted to user/* pages). In the block you an use short PHP snippets.

You can add custom php/html code at user-profile.tpl.php.This file can be found inside  the modules/user folder.


Error when creating a custom Twig filter I'm trying to create a custom Twig filter in Drupal 8. The goal is to use my custom filter in a template like so:

{{ a_variable|myfilter }}

I have created a custom module with 3 files:

MODULE.info.yml
MODULE.services.yml
src/TwigExtension/MyExtension.php

The MODULE.info.yml file contains the usual values.

The MODULE.services.yml file contains:

services:
  MODULE.twig_extension:
#   arguments: ['@renderer']  #  <-- Initial code (USELESS)
    class: Drupal\MODULE\TwigExtension\MyExtension
    tags:
      - { name: twig.extension }

The src/TwigExtension/MyExtension.php file contains:

namespace Drupal\MODULE\TwigExtension;

// use Drupal\Core\Template\TwigExtension;  // <-- Initial code (WRONG)

class MyExtension extends \Twig_Extension {
// class MyExtension extends TwigExtension {  // <-- Initial code (WRONG)

  /**
   * Generates a list of all Twig filters that this extension defines.
   */
  public function getFilters() {
    return [
      new \Twig_SimpleFilter('myfilter', array($this, 'myFilter')),
    ];
  }

  /**
   * Gets a unique identifier for this Twig extension.
   */
  public function getName() {
    return 'MODULE.twig_extension';
  }

  /**
   * Replaces all instances of "animal" in a string with "plant".
   */
  public static function myFilter($string) {
    return str_replace(array('animal'), array('plant'), $string);
  }

}

My initial code got following error: "Call to a member function generateFromRoute() on a non-object in /core/lib/Drupal/Core/Template/TwigExtension.php on line 224".

But I have now corrected the code following lauriii's answer and it works perfectly!

The problem in the code above is that your Twig extension class is extending the internal Drupal Twig extension class. That breaks the Twig extensions added by Drupal core and that's why you are getting the error.

To fix this, you should make your Twig extensions extend Twigs internal Twig extension class. Your class should be defined like this:

class MyExtension extends \Twig_Extension {

After making that change, you can also remove arguments set for that class from the MODULE.services.yml

Try https://www.drupal.org/project/twig_extender . Add a plugin system for custom twig functions and filters


Unable to connect to local MySQL db using drush sql-sync I'm attempting to use drush sql-sync to sync my prod database to my local dev copy, and everything seems to work until drush attempts to log into the local MySQL. When it does, it throws this error:

"ERROR 1044 (42000) at line 39: Access denied for user 'drupal_user'@'localhost' to database 'mydb'"

I'm using a group alias file (e.g. mysite.aliases.drushrc.php), and I have my two aliases defined like so:

$local_sites = '/Users/steve/Sites/';
$aliases['local'] = array(
  'uri' => 'default',
  'root' => $local_sites . 'mysite/public_html',
  'path-aliases' => array(
    '%files' => $local_sites . 'mysite/public_html/sites/default/files',
    '%dump-dir' => '/Users/steve/Sites/mysite',
   ),
);

$aliases['prod'] = array(
  'uri' => 'default',
  'os' => 'Linux',
  'root' => '/cluster/www_system/www/www.mysite.org/current_build/public_html',
  'remote-host' => 'control.cphwf01.local',
  'remote-user' => 'sedwards',
  'path-aliases' => array(
    '%files' => 'sites/default/files',
    '%dump-dir' => '/scratch',
   ),
);

I run sql-sync with --verbose, and I can see the file created on the remote server, and then copied to my local.  However, where it fails is at this line:

Calling system(mysql --database=mydb --host=localhost --user=drupal_user --password=mypass --silent < /Users/steve/Sites/mysite/mysiteLeW4G5);

If I paste this command to the command line like so:

mysql --database=mydb --host=localhost --user=drupal_user --password=mypass

it connects just fine. Now, I do notice that the temp dump file is then deleted, but it's there at the time sql-sync is attempting to connect.  Any ideas why this would be failing?

On a side note, what flag do I need to pass to sql-sync to get the dumped file to persist on my local once it's been created? That way I can test w/o having to dump from the server every time. It would also be way to just dump from the remote to my local w/o actually importing into the local db.

Thanks.

EDIT: I've run sql-conf for my local site (with --show-passwords) and it shows the correct information for the local copy.

EDIT 2: Following the advice here, I used the root user, and the sync worked.  However, this still doesn't make sense, since using the drush generated connection string with the db user/pw from settings.php at the command line works fine.

I have faced the same issue.
My solution was to add more rights to mysql user with this comande line :

GRANT ALL PRIVILEGES ON `myDB`.* TO 'mySQLuser'@'localhost' WITH GRANT OPTION

Because previous rights :

GRANT USAGE ON *.* TO 'mySQLuser'@'localhost' IDENTIFIED BY PASSWORD 'pwd'

Do not seem to be enough.

I think you are sync db from local to prod, that means you are accessing your local db from remote server. So you have to change configuration of sql db, so that it can be accessed by remotely.

Edit my.conf file and change the bind address = 127.0.0.1 to  bind address = 0.0.0.0 , mean now you are letting access that db from all IP address.


Conditional token pattern I am looking for a module or a hook that allow me to use if conditions with tokens.

For example I want to check if a field is equal to a specific value or text

[if][field_name][eq]hello[then][field_name_alt]

any ideas will be helpful.

Here is an idea, which I have not tried yet.

Sometimes you have tokens in combination with text formats. E.g. in commerce_checkout_completion_message_pane_checkout_form() the token replacement happens first, before the text format is applied. I am not sure if I agree with this order, but in this case it gives us some interesting options.

You could define a custom text filter which detects and evaluates markup like this:

{if true}hello{else}goodbye{endif}

and then you can use tokens to insert the true/false.

{if [token-which-returns-true-or-false]}hello{else}goodbye{endif}

This still leaves a lot in the open. Most tokens do not produce true/false, so maybe instead you want real equation formulas. But it is a direction you can explore further.

You can try to build it with Rules, but I'm not sure.

Another way is to make you own token module to get it. Token api is one of the easiest api from drupal.


How to inculde 3d parrty libraries into your module? I am using the 3d party php library, and I do not know how to connect. The file structure of my project looks like following:

-my_project
--src
---Plugin
----Action
-----MyAction.php
---libs
----mylibs
-----src
------ClassWhichINeed.php

--my_project.info.yml

So I need to connect ClassWhichINeed.php to MyAction.php.
In ClassWhichINeed.php I specified namespace as Drupal\my_project\mylibs;

And in MyAction.php i use Drupal\my_project\mylibs;

But when I create
$object = new ClassWhichINeed;

I get an error "Undefiened class"

suggestion:

in MyAction.php add:

require_once DRUPAL_ROOT . '/modules/my_project/src/libs/mylibs/src/ClassWhichINeed.php';


How to handle / cleanup obsolete aggregated css / js? I'm only using Drupal 7 built in CSS / JS aggregation, however the files folder where the css.gz and js.gz files live are filling up at a fairly rapid pace, and while I'm sure it'll be a while before it starts to totally fill up the drive, nows as good a time as any to get a handle on the situation.

Current file count in /js is 335
Current file count in /css is 451

Is there any standard method I should be employing to deal with this situation? I'd prefer a solution that keeps the drupal in the loop.

Additionally, I see that many of the gz files have non-gz counterparts. Is there some reason both .css and .css.gz files are kept? Degredation maybe?

Thanks

This is actually by design so that cached pages with older versions of files don't get broken. See this closed issue.

TL;DR: They will be deleted automatically 30 days (or whatever your drupal_stale_file_threshold variable is set to) after they were created via drupal_clear_css_cache() and drupal_clear_js_cache(). So the solution is to modify the drupal_stale_file_threshold value to something lower than the default 30 days.

When are old files deleted

  Old cache files are not deleted immediately when the lookup variable is emptied, but are deleted after a set period by drupal_delete_file_if_stale(). This ensures that files referenced by a cached page will still be available.

  drupal_delete_file_if_stale() defaults to 30 days - so if a) Cron is running properly and b) you see aggregated files older than 30 days, you have a different problem.

variable_get('drupal_stale_file_threshold', 2592000) is the 30 day check.
variable_set('drupal_stale_file_threshold', 172800) would change the timeout to two days. On a site where cache handling is strictly controlled, the time could be even shorter.

Source: http://api.drupal.org/api/drupal/includes!common.inc/function/drupal_build_css_cache/7
See drupal_delete_file_if_stale() for more information.

Is there some reason both .css and .css.gz files are kept?

  If CSS gzip compression is enabled, clean URLs are enabled (which means that rewrite rules are working) and the zlib extension is available then create a gzipped version of this file. This file is served conditionally to browsers that accept gzip using .htaccess rules.

  Source: http://api.drupal.org/api/drupal/includes!common.inc/function/drupal_build_css_cache/7 (In the function comments)

Also see drupal_build_js_cache() which is nearly identical to drupal_build_css_cache().

Get the Rules module
Add a new rule that will be executed when the cron is running
As an action select execute php code.
Write the php code

Might be something like this:

$dir = 'your/directory/';
  foreach(glob($dir.'*.*') as $v){
  unlink($v);
}

These php functions might help you to modify the code as you like.

Glob http://php.net/manual/en/function.glob.php
unlink http://uk.php.net/manual/en/function.unlink.php

Be very careful before executing this! If not used right you may delete your site! Before trying this code test it on a localhost


How to theme only top level menu? I have the following menus

about us
    company
    menu 2
our work
    menu 1
    menu 2
news
contact
jobs

I like to insert an extra li between each top level menus (about us, our work, news, contact, jobs) to make them look like "about us   |   our work   |   news   | contact   |   jobs "

I looked at template.php and I have themename_menu_link, but I don't know how to compare the variable to check if it is a top level menu or not.

The only way I can think of is as follows:

template.php

<?php

function YOURTHEME_menu_tree__YOURMENUNAME(&$variables) {
    global $cur_level;
    $cur_level++;
    return '
' . $variables['tree'] . '
';
}

?>

page.tpl.php

<?php print render(menu_tree('YOURMENUNAME')) ?>

This will give each level an unique class for it's level. Though, there is one big problem with this approach, and that is that menu_tree is working from the bottom up. So you will end up in the following level classes:

ul .level-3
li
li
    ul .level-2
    li
    li
        ul .level-1
        li
    li
li

So, you can never actually be sure about which classname the top level will have, only if you know for sure that there will always be an X count of levels.

Edit
So, just to be clear about my solution here above, this is the only way I can think of doing this programatically at theme level. If you could use a module like Nice Menu's (like suggested above) you should really be using that, since this is more a kind of workaround than a real solution to Drupal's sturdy menu system...

Looks like there's a 'depth' key for each links.

function yourthemename_menu_link(array $vars)
{
    $depth = $vars['element']['#original_link']['depth'];
}

you can check depth to see if it is the first level.


views Filter field equal to the value of another field Is there a way or a module to filter a vie by a field against the value of another field. For example uI'd is equal to the  value of another field that's given.

From what I understand of your request you are adding a view on a node display page and want to use a field on that page as an argument in the view, if this is the case you want to add a contextual filter and under default value select php and then do a node_load or db_select to load the field from the node being viewed.

Not sure if this is what you are looking for - https://www.drupal.org/project/views_dependent_filters - this allows you to use a view as a filter in another view


how to get radio value from radio button by form api drupal How to get radio value from radio button by using the following code

$form['pd']= array(
  '#type' => 'radio',
  '#title' => t('Programme Day'),
  '#options' => array(0 => 'One Day Programme', 1 => 'Two or More Day Programmes'),
  '#required'=>TRUE
);

$form['one_day'] = array(
  '#title' => t('Date'),
  '#type' => 'date',
  '#description' => t('Please select the date of Programme'),
  '#required' => TRUE,
  '#date_format' => "d-m-Y h:i A",
  '#date_year_range' => -15:+1',
  '#states' => array('visible' => array(':input[name="pd"]' => array('value' => 0)))
);

$form['from_day'] = array(
  '#title' => t('From Date'),
  '#type' => 'date',
  '#description' => t('Please select the from date of Programme'),
  '#required' => TRUE,
  '#date_format' => "d-m-Y h:i A",
  '#date_year_range' => '-15:+1',
  '#states'=>array('visible'=>array(':input[name="pd"]'=>array('value'=>1)))
);

$form['two_day'] = array(
  '#title' => t('To Date'),
  '#type' => 'date',
  '#description' => t('Please select the To date of Programme'),
  '#required' => TRUE,
  '#date_format' => "d-m-Y h:i A",
  '#date_year_range' => '-15:+1',
  '#states'=>array('visible'=>array(':input[name="pd"]'=>array('value'=>1)))
);

I tried the following code but the value shows as array not value.

$prog_day = $form_state['values']['pd'];

$one_date = $form_state['values']['one_day'];
$from_date = $form_state['values']['from_day'];
$two_date = $form_state['values']['two_day'];

if you are looking for the submitted values you need to look in the $form_state and not the $form array.

use $form_state['values']['your field name'],
depending on element type you might have ['und'][0] or just [0] on the end.

you need a default_value to get the value !

$form['pd']= array(
  '#type' => 'radio',
  '#title' => t('Programme Day'),
  '#options' => array(0 => 'One Day Programme', 1 => 'Two or More Day Programmes'),
  '#required'=>TRUE,
  '#default_value' => 0,
);


Display field inputs side-by-side in node edit form I have quite a few Field Collections on my node edit form that each have three text input boxes. By default drupal displays them one on top of the other which makes for a very long page:

Ideally I'd like to display the three fields in a single row. Do I have to override this with CSS or is there a setting I'm missing? It's a pai to Google a solution because I keep getting article about in-place editing or theming webforms.

If you are using Field Collections you can have them displayed in a few different ways, one of which is a table, which is more relevant for some situations than others. Have a look at Field Collection Table and see if it suits your needs.
It will, in your example, put the three fields side by side - but in table cells.

Sorry CSS is the only way to do that. You might need to add something to limit the form field and then float them, I did something like this:

div.field-your-field-name .field-item {
float: left;
margin-right: 0.75em;
}

But I had no label, so you might need to change the css for the label too.
Remember to add a

    clear: left;

for the next element css otherwise the next element might be floated too.


What is the 'System' display option in Views? Could you tell me what the "System" display in views is? (shown in red)

I suppose it's a presentation which is only available programmatically, but I'm not 100% sure.

Thanks.

Today I was in the same situation, so I decided to look and this is what I found:

  So, for anyone stumbling upon this, 'system' displays are only to override core views (which you do through the System Path Settings area in the Advanced section of views) and I should just be using a page display with a path that begins with '/admin/' if I want to make custom admin views.

Here is the link: https://www.drupal.org/node/2539256#comment-10150524

The Views System module extends the Views module and allows to create customized lists (pages, blocks) of modules, themes, and theme engines that are or have been installed in Drupal's file system

views system


Theming views data export XLS button I have a view that I have attached a data export view to. I want to change the default orange icon that shows XLS at the bottom of the view, to another button with text "Download View". How can I achieve this?

This image is set in function views_data_export_views_plugins(), in views_data_export.views

Implement your own hook_views_plugins() and override ['style']['views_data_export_xls']['export feed icon'] with your own value. Just make sure your module fires after Views Data Export.

override theme_views_data_export_feed_icon function in your theme template.php

Example :

function themename_views_data_export_feed_icon($image_path, $url, $query = '', $text = '') {

    $url_options = array('html' => true, 'attributes' => array('class' => 'csv-export'));
    if ($query) {
       $url_options['query'] = $query;
    }
    return l(t('Download View'), $url, $url_options);
}


Drupal fancybox views gallery - display only first item of attached images I have multiple images attached to a node that act as a gallery using fancybox.
In views I am attempting to only display the first attached image.

The idea is to only display the first image then when clicked, fancybox will go into gallery mode displaying all subsequent attached images.

I have tried the 'Group multiple values' showing '1value' starting from 0.

This works for only displaying the first item, but unfortunately when clicked fancy box does open but not in gallery mode. It just displays the first item.

What i need to do its open all attached images as a fancybox gallery but from only the first item.

Any help or ideas would be much appreciated.

Use the display CSS properties.

.field-content ul li{
    margin:0;padding:0;
    display:none;
}

.field-content ul li:first-child{
    display:block;
}


How does Drupal know when to run an update script? How does Drupal 8 know what module needs updating and to what version he needs to update?

I have build a module and I'm trying to update it (adding a table). I implemented a update hook numbered 8001, which is the first update, but when I go to update.php Drupal does not see any update for my module.

I expect there must be a place in my module where I can define the current version of my module and another place in the database where Drupal stores the latest installed update of my module. (I need this for debugging the update script later on.)

To store/get the version information for a module use the global functions:

drupal_set_installed_schema_version()
drupal_get_installed_schema_version()

For example set a new version for mymodule with drush:

drush ev "drupal_set_installed_schema_version('mymodule', '8123')"

Print the version with drush, in this example for the module comment:

drush ev "var_dump(drupal_get_installed_schema_version('comment'))"

The functions are defined in schema.inc. Here you can see how to access the key_value table through the keyvalue api, if you want to use your own code:

/**
 * Updates the installed version information for a module.
 *
 * @param string $module
 *   A module name.
 * @param string $version
 *   The new schema version.
 */
function drupal_set_installed_schema_version($module, $version) {
  \Drupal::keyValue('system.schema')->set($module, $version);
  // Reset the static cache of module schema versions.
  drupal_get_installed_schema_version(NULL, TRUE);
}

SELECT *
FROM key_value
WHERE collection =  "system.schema"

The schema value stored in BLOB format.


Autoselect parent taxonomy if child is selected How can I have the parent taxonomy be automatically selected when one of its children gets selected? It would be a convenience if the parent is selected automatically in the backend for every child selected.

Right now, if I select a child and not the parent, then search or browse for the parent term, child terms under that parent are not brought back. This doesn't seem right.

similar question here: Check parent term when checking subterm

but if you need check all child when parent checked, you need some changes in JavaScript file

Easiest way to do that is to use rules module.


Search facet user entered date field display I've recently started working on an existing Drupal site that uses Apache Solr search & have come across a problem when configuring facets.

The search index just indexes one type of content & one of the facets it displays from this is a year field, this is set as a date select field where the user can select a month & year. If I set this to only allow one entry it works fine and the facet links have the years that are available with the number of results it'll return in brackets.

When I set the field to allow an unlimited number of values instead of getting a list of years as links I get what seems to be a random number "1414800000 (1)," timestamp maybe? It also seems to group them by the month & year entered rather than just the year as it did when only one field entry was allowed.

If anyone else has this same problem, there is a patch on drupal.org. If you've not used to patches, See this beginner's guide.


Domain Access module: Adding nodes programmatically to subdomains I am using Drupal 6 and Domain Access-6.x-2.11.
I need to programmatically add nodes to subdomains defined in Domain Access configuration. I've been looking the source code of domain.module but can't figure out how to use the api of the module to add a node to certain subdomains.

Any suggestions?

Since I didnt find a way to do this with api I solved this by editing the table where domain access keeps the info about which node belongs to which domain.

Answer for Drupal 7:

$node->domains = $domains;
$node->domain_site = FALSE;
$node->domain_source = '1';

Where $domains is an associative array like that:

$domains = array(
 '1' => '1',
 '4' => '4',
);


How do I alter the title display with hook_user_view? /**
 * Implements hook_user_view().
 */
function my_statistics_user_view($account) {
    $account->content['statistics']['daily_avg'] = array(
        '#type' => 'user_profile_item',
        '#title' => t('Daily average'),
        '#markup' => 'Hello',
        '#attributes' => array('class' => array('daily-avg')),
    );
}

The above code renders:

Daily average
Hello

in a user's account profile. I would like to render it inline, like this:

Daily average: Hello

How is this done? Thanks.

You don't. To alter display, you have to create or edit user-profile.tpl.php file in your theme, or template_preprocess_user_profile() function in template.php

I think the simplest way here is just to use drupal_set_title:

function my_statistics_user_view($account) {
    drupal_set_title('Your desired title here');
}


What is hook_menu_alter used for? In simple terms, what is hook_menu_alter for? I understand callbacks in general, but I'm not quite sure if this method is misnamed in a sense, as I see it used in the context of permissions rather than menus. I'm probably just confused.

I think that your confusion comes from the fact that Drupal 6 and 7 mixes menu and routing. One set of hooks for both purposes, and here you have problems. If this hook was named hook_route_alter(), using it to alter permissions to some routes would be obvious, right? So that's what modules do, using the name they got. Personally I agree it's not most lucky naming, but once you remember that in this context, basically, menu == routing, it all becomes much more intuitive.

With hook_menu_alter  you can manipulate $items: Associative array of menu router definitions returned from hook_menu(), you can add or remove items or manipulate menu item properties : https://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook_menu/7


Can't access admin after moving localhost to live server Almost finished my site and thought I have completed the puzzle but there is one last frontier in my way and a rather annoying ankle-biter...

I moved my site off my localhost onto my live server everything was successful until I tried to login the first time and was denied access.. I requested a new password through the email I provided when i created the site on my localhost but the emails do not come to my inbox but when i try to recreate the process on my localhost I get the email and can change it etc. I have tried going into my DB>users>browse> and change my password and put MD5 so it becomes encrypted but still no success on the live site.

I have tried to search online for the answer but have been going in circles and would like to see if anyone can offer some advice I am novice level and eager to learn so if responding kindly use terms a novice would be familiar with, thank you.

Install drush
Go to your drupal-core/sites/mysite folder in command line
type sudo drush uli
The console will print a link, use that to access your site as user 1

Hm, you didn't accidentally turn off browser cookies?

Happened to me a few times – no session means no access.


Is there any way to dynamically add a CSS class selector to a view with submitted exposed filters? I need to add some different styling to a view based on whether the exposed filters have been applied or not. Eg add the class "filtered" once a person has submitted their info in the exposed filter?

You can do this with View's pre_render hook, eg, something along the lines of this:

function YOURMODULE_views_pre_render(&$view) {

  if ($view->name=='NAME_OF_YOUR_VIEW') {
    drupal_set_message('<pre>' . $view->exposed_data . '</pre>'); // to see what you have to work with
    if (!empty($view->exposed_data['type'])) {
      $view->display_handler->set_option('css_class', 'view-has-been-filtered');
    }
  }

}

The above is based on a node type exposed filter, you will need to look at your View to see what filter names are involved, but the logic is that the exposed_data filter arrays will be empty until you have applied the filter.  For example, here, this looks like this when you first go to the View:

Array
(
    [type] => Array
        (
        )

    [submit] => Apply
    [form_build_id] => form-85a47ba22bc12a8b443e4cc35afe75f7
    [form_token] => 105c57eec73efe4cfedd9acabc55786a
    [form_id] => views_exposed_form
    [] => Apply
)

and this is what it looks like after selecting 'foo' as a type in the exposed filter:

Array
(
    [type] => Array
        (
            [foo] => foo
        )

    [submit] => Apply
    [form_build_id] => form-85a47ba22bc12a8b443e4cc35afe75f7
    [form_token] => 105c57eec73efe4cfedd9acabc55786a
    [form_id] => views_exposed_form
    [] => Apply
)

ADDITION:

If this works for you, and per your comment, I suppose the following would work for any/all Views, but I haven't battle tested it...

function YOURMODULE_views_pre_render(&$view) {

  $filter_classes=array('view-has-been-filtered');

  if (!empty($view->exposed_data) && is_array($view->exposed_data)) {

    foreach($view->exposed_data as $k => $key) {
      if (is_array($key) && !empty($key)) {
        $filter_classes[]='view-has-been-filtered-by-' . str_replace('_', '-', $k);
      }
    }

    if (count($filter_classes) > 1) {
      $view->display_handler->set_option('css_class', implode(' ', $filter_classes));
    }

  }

}

...with the logic here being the only arrays in $view->exposed_data are filters, and if they aren't empty, the View has been filtered.

EEEK ADDITION:

My logic is somewhat flawed in that my initial tests were for filters that allowed multiple selections, and, of course, Views used arrays to capture them in $view->exposed_data.  If your filters are just single value fields, Views will do something like this first:

Array
(
    [multiple_value_allowed_type] => Array
        (
        )

    [field_single_value_field] => All
    [submit] => Apply
    [form_build_id] => form-f601bde36c625db96bad7a84bf4fa210
    [form_token] => 105c57eec73efe4cfedd9acabc55786a
    [form_id] => views_exposed_form
    [] => Apply
)

so I guess the following dull ax approach would work:

function YOURMODULE_views_pre_render(&$view) {

  $filter_classes=array('view-has-been-filtered');

  if (!empty($view->exposed_data) && is_array($view->exposed_data)) {

    foreach($view->exposed_data as $k => $key) {
      if (is_array($key)) {
        if (!empty($key)) {
          $filter_classes[]='view-has-been-filtered-by-' . str_replace('_', '-', $k);
        }
      } else {
        switch ($k) {
          case 'submit':
          case 'form_build_id':
          case 'form_token':
          case 'form_id':
            break;
          default:
            if (!empty($k) && $key != 'All')  {
              $filter_classes[]='view-has-been-filtered-by-' . str_replace('_', '-', $k);
            }
        }
      }
    }

    if (count($filter_classes) > 1) {
      $view->display_handler->set_option('css_class', implode(' ', $filter_classes));
    }

  }

}

DOUBLE D'OH ADDITION:

Of course, this quick and dirty logic also works:

function YOURMODULE_views_pre_render(&$view) {

  if (!empty($view->exposed_data) && count($_GET) > 1) {
    $view->display_handler->set_option('css_class', 'view-has-been-filtered');
  }

}

ADDITION DUE TO COMMENTARY:

If you are setting css classes via the UI that you want to preserve, you can do this:

$view->display_handler->set_option('css_class', $view->display_handler->get_option('css_class') . ' view-has-been-filtered');

which gets that UI option and then adds the view-has-been-filtered class to it.  Please note the required space in front in the code :)

To any view,you can add a different css class by
1. First clicking on the editing option on a view
2. In the Page details,click on ADVANCED properties
3. Add the css class to the second last attribute present there which is css class.
This way you can add css classes to every view.


Setting up Multisite on windows server with IIS7 First off I'm not a server person. New windows box spun up, IIS7 was used to install one instance of Drupal 7. Great :)

However I need to have multiple sites running. I've read several tutorials on getting this to work, tried several solutions, and continue to gets errors (from page not found to "this drupal site is already set up"). Does anyone know if there are step by step instructions somewhere on exactly how to set up multisite on a windows box with IIS7?

The "base" drupal install is /inetpub/wwwroot/Drupal/DrupalTest/

Having very little knowledge of Windows servers is probably part of the issue. I really need basic step by step instructions and I have yet to locate any that assume you know essentially zero about windows. I've been taking notes so I can write some out if I eventually figure it out :)

One example I've followed: http://drupal.org/node/554336 : Yielded the "site already setup" when I tried to access the install.php from the second site.

I'm at the point where multisite would be nice, but if I need to use multiple instances of Drupal that's fine, I just need to be able to move forward with the content and be finished messing with the dang server, but I have no idea how to accomplish that as well.

After much digging, found out the combo of msSQL and PHP 5.3 caused the site to break. Reinstalled with PHP 5.4 and mySQL and it's running swimmingly!

Hi you can read more on how to install multisite in drupal 7 with below links.

http://mydons.com/drupal-7-multisite-install-steps-in-windows/


Where is the the site name and slogan set? In the page--front.tpl.php template, I have the following code for site logo.

<img src="<?php print $logo ?>" alt="example.com logo" title="<?php print $site_name_and_slogan ?>" id="logo" />

Where is the title set in Drupal 7? Right now the title is showing blank in the production site.

In your active theme's template.php, check template_preprocess_page() function and add following lines:

$site_name = variable_get('site_name');
$site_slogan = variable_get('site_slogan');
$variables['site_name_and_slogan'] = $site_name . ' ' . $site_slogan;

Assuming that you have used $variables as argument in template_preprocess_page() function.

Now $site_name_and_slogan can be used in page tpl files.

If you have not implemented template_preprocess_page() function, then replace template word with your theme name and add the function as mentioned below:

function THEMENAME_preprocess_page(&$variables){
  $site_name = variable_get('site_name');
  $site_slogan = variable_get('site_slogan');
  $variables['site_name_and_slogan'] = $site_name . ' ' . $site_slogan;
}

Have u tried these?

    <?php print $site_name; ?>
    <?php print $site_slogan; ?>

You can use it as

    <img src="<?php print $logo ?>" alt="example.com logo" title="<?php echo $site_name.$site_slogan; ?>" id="logo" />


Add and customize login block on page.tpl I'm trying to add the user login block in my page.tpl file. I've tried inserting the following code but  the only thing I see is the username, password and submit fields. The "Register" and "Forgot your Password" fields are not there. And I would like to do this in code form. Cause I wanna put the user login block in a specific place.

if(!user_is_logged_in() ){
    $userLoginForm = drupal_get_form('user_login');
    print drupal_render($userLoginForm);
}

Thanks :)

you can do it like this:

$block = block_load('user', 'login');
$block = _block_render_blocks(array($block));
$block_build = _block_get_renderable_array($block);

print drupal_render($block_build);

this will generate a block with title and contexual links also..


Field permission for Administrator How to disable this fields for Administator?

Install Disable Field module and install. After installation go-to admin/structure/types/manage/YOUR_CONTENT_TYPE/fields and edit the desired field. In the bottom, you can see DISABLE FIELD SETTINGS open that and you can choose to disable option in DISABLE THIS FIELD ON ADD CONTENT FORM? and DISABLE THIS FIELD ON EDIT CONTENT FORM?. In that Select Disable for certain roles and choose administrator. After that save and that field will be disabled in ADD/EDIT based on your selection

It should be administrator.

if (in_array('administrator', $account->getRoles())) {
  return AccessResult::forbidden();
}


How to permit one sub admin to change passwords of other certain users? I'ld like to make a sub admin be able to change other user's passwords depending on other user's role or uid.

The sub admin should be able to type the password by himself. Emailing a generated password is unfortunatley no optionn since the aimed user accounts will be used by a quite loose group of people (teachers and pupils, sub admin wants to change password every school year).

Until now there are only very few different accounts where that needs to happen. So can I maybe do that with uids?

Is it maybe possible to build a block that provides a form with password fields of the desired users? What hooks or forms would I need to use or alter then?

Any idea and/or explanation is very much appreciated!

Thanks to arpitr and my coworker J., I finally did it with a form on a page which is accessible only to selected roles via hook_permission(). The desired array() of uid=>name of that certain role to pass on as select list #option comes from db_select(), which definitely was the most difficult thing to get:

function _get_users_by_role($role_name) {
  $query = db_select('users', 'u')
    ->fields('u', array('uid', 'name'));

  $query->innerJoin('users_roles', 'ur', 'u.uid = ur.uid');
  $query->innerJoin('role', 'r', 'ur.rid = r.rid');
  $query->condition('r.name', $role_name);

  $result = $query->execute()->fetchAllKeyed();

  return ($result) ? $result : array();
}

For those interested in the custom block approach arpitr proposed, check the accepted answer on How can I display a change password form on its own? for a even more detailed description.

Take a look http://drupal-create-sub-administrators.blogspot.com/ .. this may meet your needs. Allows creation of sub-admins that can manage other lower level sub-admins or regular users including editing of user info (just like the user herself can).


drupal 7 lack of understandig location of bartik's color.css I liked to change some css color styles. I created my own css file and let bartik theme (my enabled theme) know this in its info file. But no changes took effect.
Then i realized, that there are two color.css files. One is in bartik/css/ and the other in sites/default/files/color/. The second one is used. Can someone explain to me, why not all css are just taken from bartik/css. I think i didn't get the concept yet.

The Bartik theme has support for the Color module, which is a module that allows themes to change the color used in their images, or in their CSS style files basing on a schema defined in the theme settings page.

When the selected color set is not the default one, color_scheme_form_submit() generates the files that will be used for the theme. The files you have seen inside the sites/default/files/color directory are the ones generated from the Color module, and that will be used for the theme. The files in the theme directory are the ones used when the color set is the default one.

As side note, if you are editing the files used by a theme that supports the Color module, you need to disable, and then re-enable it, or the files used for the theme could still be the old ones.

This second css file may be cache file. Try flushing your cache and then checking if your changes take effect.


How do I automatically remove spaces from a path in the blog module Some places on the site are correct
e.g.  http://groundhogresearch.com/blogs/bob-schweickert-jr
but the blog module block show this path
http://groundhogresearch.com/blogs/Bob%20Schweickert%20Jr. which of course can't be found

Using Pathauto you can replace spaces with a character of your choice (and do a lot of other stuff too), like for example a dash. Once you have enabled the module go to admin/config/search/path/settings and start configuring the module.

You can use Pathauto to configure that kind of behaviour.


How do I get the uid of a node? I am trying to get the user ID associated with a node using this code in Drupal 7, without any luck:

$uid =  $node->uid;
echo "uid: " . $uid;

$uid doesn't have any value in it.

I want to get it so that I can count the number of my members' posts.

$node = node_load('NID');
$uid = $node->uid;
$sql = "SELECT nid FROM {node} WHERE uid = $uid";
$result = db_query($sql);

$number_of_rows = $result->rowCount();
echo "uid: " . $uid;
print "
$node->name has submitted $number_of_rows source code / articles.
";'

I tried putting it in a display suite module under fields. I also tried putting in a page content type.

That should work. Try making sure that you have a properly loaded node object.

$node = node_load('NID');
echo $node->uid;

It is possible that if the node was created by an anonymous user that the $uid would be zero and thus wouldn't print.

You can only get the author id of a node by using the following code. FYI it will work only in the node template.

<?php echo $uid; ?>

If you want to use the user id in any other template or in any custom module you can use the following code.

<?php $node = node_load(NID); $uid = $node->uid;?>


Display data from web service using views I need to query data from a web service and display it in a view without storing the data in Drupal database. I am using WSData module for this purpose but I am unable to figure out how and when the webservice is getting invoked. My web service doesn't have any parameters passed and it returns a list of items. I would like to display the list as a table using views.

It would be of great help if I can get any samples or references.

You can take a look at https://www.drupal.org/project/wsdata

This module allows you to bypass the default data storage location for fields and entities and instead load the data from a web service.

This is useful when your primary data source is in another system but you want to display/use this data in your Drupal site without the hassle of syncing or importing data.


Tracking how long it takes a user to submit a node edit form? For a quiz node, I want to track how long it takes a user to submit a node form (the time from Drupal generating the form until the time that the user presses submit), and I want to store this duration in a field on my node.
Use case
Each node of content type Quiz is a 10 question quiz.  I want to track the time that users spend filling out the node in order to track their improvement in speed over time.
I do NOT want to track the time spent on the website in general; for that, I already use Google Analytics with scroll tracking, and there is also the Time Spent module.
What I tried
On my node, I added an Integer field, Duration.  My thought was that I could calculate the interval from the timestamp when the form was generated until the time the node was saved by adding code in hook_node_presave():
  $original_time = ??? // How do I get the time when the node form was generated?
  $current_time = \Drupal::time()->getCurrentTime();
  $duration = $current_time - $original_time;

Where I'm stuck is I don't know how to get the time when the node form was created.
I tried to add a Datetime field to my node with a Default date of Current date, but the current date is not set until the node is saved, so that doesn't work.
So, how can I track the time from generating a node edit form until the time the user presses submit?

Here is how I would do it:
/*
 * Implements hook_form_FORM_ID_alter().
 */
function mymodule_form_node_quiz_edit_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  $form['field_duration']['widget'][0]['value']['#type'] = 'hidden'; // hide field
  $form['field_duration']['widget'][0]['value']['#default_value'] = time(); // set default value to start time
  array_unshift($form['actions']['submit']['#submit'], 'mymodule_calc_duration'); // adds a custom submit that runs before the default node submit
}

function mymodule_calc_duration(&$form, \Drupal\Core\Form\FormStateInterface $form_state) {
  $start_time = $form_state->getValue('field_duration')[0]['value']; // get default value
  $duration = time() - $start_time; // calculate duration
  $duration_value = [
    ['value' => $duration],
  ];
  $form_state->setValue('field_duration', $duration_value); // set duration value
}

create a field in your form and in Hook_form_alter and hide it

  if ($form_id == 'form_id') {
      $form['field_view_node_start']['#access'] = FALSE;
      $form['field_view_node_start']['widget'][0]['value']['#default_value'] = time();
  }

at hook_entity_presave get time between field_view_node_start and field_view_node_end

function hook_entity_presave(Drupal\Core\Entity\EntityInterface $entity) {
      $entity->set("field_view_node_end",time());
}


Use url alias for page parameters I'm new to Drupal and created a basic page in which the clean url is

/todo

If I want the todo's for a certain month I can do

/todo?month=januaray

However what I would like to do is provide a clean url which looks like

/todo/januaray

I tried modifying my .htaccess file like explained here

RewriteCond %{REQUEST_URI} ^/todo/(.*)$
RewriteRule ^.*$ /todo?month=%1 [L]

But that didn't seem to work. Is there any easy way to achieve this?

This will work:

RewriteRule ^todo/(.*)$ todo?month=$1 [L,QSA]

No need for the rewrite condition.

That will internally forward, e.g. http://example.com/todo/january to http://example.com/todo?month=january.

Make sure you add that code before Drupal's main index.php RewriteRule

I would consider using Pathauto as it is way more flexible and easier to use.

  The Pathauto module automatically generates URL/path aliases for
  various kinds of content (nodes, taxonomy terms, users) without
  requiring the user to manually specify the path alias. This allows you
  to have URL aliases like /category/my-node-title instead of /node/123.
  The aliases are based upon a "pattern" system that uses tokens which
  the administrator can change.


Date format in another language I have a multilingual site. English and Dutch are the languages. I need to display date format in Dutch, ie  I need to display a timestamp in Dutch(nl), as 16 oktober 2017. Tried the below code and format_date(), but didn't do the trick.

$date = $node->getCreatedTime();
\Drupal::service('date.formatter')->format($date, 'custom', 'd F Y', $timezone = NULL, $langcode = 'nl'); //not working for me

format_date($timestamp, $type = 'medium', $format = '', $timezone = NULL, $langcode = 'nl');

Above code returned date in "en" language. Am I missing something here.. Thanks..

The Drupal way of handling and translating Dates is through Configuration > Regional and language > Date and time formats, as Hudri mentioned in his comment.

The same date and time Pattern between languages

What you should do depends on what pattern you want your date to be in English, if it should also be 'd F Y' as in Dutch. If yes, then you should edit the relevant Date format through the interface. Content types use Medium as default for the “Submitted by” so edit that to keep things simple.

I expect you'll have the date and time related terms already translated into Dutch, so you'll get oktober and not October on the Dutch side.

Different date and time Pattern between languages

If you want the Pattern of the same Date format to be different between laguages, for example you want English to be “10/16/2017” with Dutch “16 oktober 2017” you need to translate the Date format Pattern.

What is important to mention is that you need to have the Configuration Translation module enabled to be able to translate Date format Patterns. This will add the Translate link to the Operations button drop-down:

This enables you to have a different Pattern for different Languages under the same Date format.

Don't forget to Flush cache if you don't see the changes on existing content!

Code manipulation

The format_date() is Depricated, more info: Date formats API changes, public function DateFormatter::format.

You dont need custom code for it, every string can be translated via the translation interface.

Check this answer https://drupal.stackexchange.com/a/139407/3776


How to redirect an anonymous user to the login form after a 403 error? I want to redirect an anonymous user to the login form if such user encounters a 403 error.

I have created event subscriber and this is my code, but I end up on loop on the current page.

/**
   * Redirect anonymous user to login page if he encounters 404 or 403
   * response.
   *
   * @param \Symfony\Component\HttpKernel\Event\GetResponseEvent $response
   *   The created response object that will be returned.
   * @param string $event
   *   The string representation of the event.
   * @param \Drupal\Component\EventDispatcher\ContainerAwareEventDispatcher $event_dispatcher
   *   Event dispatcher that lazily loads listeners and subscribers from the dependency injection
   *   container.
   */
  public function checkLoginNeeded(GetResponseEvent $response, $event, ContainerAwareEventDispatcher $event_dispatcher) {
    $routeMatch = RouteMatch::createFromRequest($response->getRequest());
    $route_name = $routeMatch->getRouteName();
    $is_anonymous = \Drupal::currentUser()->isAnonymous();
    $is_not_login = $route_name != 'user.login';

    if ($is_anonymous && $route_name == 'system.403' && $is_not_login) {
      $query = $response->getRequest()->query->all();
//      $query['destination'] = $routeMatch->getRouteObject()->getPath();
      $query['destination'] = \Drupal::url('<current>');
      $login_uri = \Drupal::url('user.login', [], ['query' => $query]);
      $returnResponse = new RedirectResponse($login_uri, Response::HTTP_FOUND);
      $response->setResponse($returnResponse);
    }
  }

I think this is related to the fact that the response already contains destination(current uri) and system.404 and system.403 have some high priority that prevent me to override this.

I've seen that this question was never answered how to do this programmatically. The code actually does work, when placed in an Exception Subscriber:

/src/EventSubscriber/RedirectOn403Subscriber.php:

<?php

namespace Drupal\mymodule\EventSubscriber;

use Drupal\Core\EventSubscriber\HttpExceptionSubscriberBase;
use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Url;

class RedirectOn403Subscriber extends HttpExceptionSubscriberBase {

  protected $currentUser;

  public function __construct(AccountInterface $current_user) {
    $this->currentUser = $current_user;
  }

  protected function getHandledFormats() {
    return ['html'];
  }

  public function on403(GetResponseForExceptionEvent $event) {
    $request = $event->getRequest();
    $is_anonymous = $this->currentUser->isAnonymous();
    $route_name = $request->attributes->get('_route');
    $is_not_login = $route_name != 'user.login';
    if ($is_anonymous && $is_not_login) {
      $query = $request->query->all();
      $query['destination'] = Url::fromRoute('<current>')->toString();
      $login_uri = Url::fromRoute('user.login', [], ['query' => $query])->toString();
      $returnResponse = new RedirectResponse($login_uri);
      $event->setResponse($returnResponse);
    }
  }

}

mymodule.services.yml:

services:
  mymodule.exception403.subscriber:
    class: Drupal\mymodule\EventSubscriber\RedirectOn403Subscriber
    tags:
      - { name: event_subscriber }
    arguments: ['@current_user']

function THEME_preprocess_page(&$variables) {
global $base_url;
$is_anonymous = \Drupal::currentUser()->isAnonymous();
$route_name = \Drupal::routeMatch()->getRouteName();
$is_not_login = $route_name != 'user.login';
if ($is_anonymous && $route_name == 'system.403' && $is_not_login) {
$response = new RedirectResponse( $base_url . '/user/login' );
$response->send();

}
}


How do I pass a value to a content type field with a custom submit please and thank you for your patience in helping me learn

I have created a content type called response (Through Drupal, not in a custom module)

In the content type I have a field called field_response_number which is a text field.

When I create new content for the response content type and press submit I want to first submit the form, then run a custom submit afterwards that populates my field_response_number based on the result of a custom function.

I can submit and call my custom form submit function fine, but how do I get the total returned from my custom function to populate the field_response_number please

So my work flow is

Create new response content
Submit results in form and then call custom submit handler
Get count from DB
Populate the field_response_number with the result
Display result

Can anyone assist please, as I think I'm almost there

My code is as follows

function testmodule_form_node_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  foreach (array_keys($form['actions']) as $action) {
    if ( $form_id == 'node_response_form'){
      if ($action != 'preview' && isset($form['actions'][$action]['#type']) && $form['actions'][$action]['#type'] === 'submit') {
        $form['actions'][$action]['#submit'][] = 'testmodule_form_submit';
      }
    }
  }
}

function testmodule_form_submit(array $form, FormStateInterface $form_state){
  // This works
  //$result = testmodule_get_node_count('response');
  //drupal_set_message($result);

  How do I populate my field_response_number here please
}

//This handles incrementing by one I want to use to populate the field_response_number with
function testmodule_get_node_count($content_type) {
  $query = "SELECT COUNT(*) FROM {node} n ".
           "WHERE n.type = :type";
  $total = db_query($query, array(':type' => $content_type))->fetchField();
  return $total;
}

Many Thanks for your assistance

I guess you have multiple options.

You set the field value in the alter as a #value, this is not editable by the user, not like #default_value. Then drupal will save it automatically on successful save.
You set the field value in the validate callback into the $form_state variable. Not too elegant, but the drupal will save the value automatically (normally) on successful submit.
You create a custom submit (as you did) and then you load your node (D7: node_load($nid) D8: \Drupal::entityTypeManager()->getStorage('node')->load($id);), set the field value (D7: $node->field_name[LANGUAGE_NONE][0]['value'] = 'something'; D8: $node->set('field', 'field_value');), and then save the node (D7: node_save($node);, D8: $node->save();).
You can use hook_ENTITY_TYPE_insert() to update your field and save the entity again. (https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Entity%21entity.api.php/function/hook_ENTITY_TYPE_insert/8.2.x)
You can use hook_ENTITY_TYPE_presave() you just set the field value here, you don't need to save it. Drupal's next step will the save. (https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Entity%21entity.api.php/function/hook_ENTITY_TYPE_presave/8.2.x)

For D8 a bit more detailed: https://www.heididev.com/how-programmatically-update-fields-value-drupal-8
And also, maybe the entity is already loaded, check this: https://www.drupaleasy.com/quicktips/drupal-8-getting-entity-id-formstate

You just need the following

       function testmodule_form_submit(array $form, FormStateInterface $form_state){

              $nid = $form_state->getformObject()->getEntity()->id();

              $node = \Drupal::entityTypeManager()->getStorage('node')->load($nid);
              $node->set('field_response_number', 'field_value');
              $node->save();
        }


Customizing webform results submission page I'm new to drupal. I'm using the Drupal 7 version. I have created one webform with Name, gender, program, branch, district, college..etc fields. And now I want to customize the webform result submissions page. I want to display the submission list based on the district selected. Can anyone help me with this? I will be very thankful.

Look at EntityForms to have more control over submissions and selecting what submissions to view.

Features
Ability to attach any Drupal Field to the Forms
Ability to use most field based and entity aware modules.
You can download submitted data to XML and / or CSV data files using View Data Export.
Rules based form submission notifications. Allows for complex notifications logic.
Rules based form access control. Allows for complex access logic.
Use Views to create to create an administrative listing of each Entityform type Submissions for fine grain control.

The Webform module uses the webform-submission.tpl.php template file to show the result page. The variables available for that template file include $node, $mode, $submission.


What are the downsides of using PHP Filter code in blocks, nodes, views-args, etc? I have seen many times people saying not to use custom PHP/PHP filter (from the Drupal UI) in blocks, nodes, views-args, rules, etc. I have searched around a bit and haven't found much, it seems like this is a Drupal best practice that all "just know".

I understand it poses a potential security risk especially in the hands of end users or people new to Drupal or PHP, but as a developer/site builder what are the real reasons to not use custom PHP from the Drupal UI?

Some reasons:

Code in your database can not be version controlled and is also harder to find in general later on.
Eval()'d code is much slower than something hardcoded in a file.
If there is an error somewhere in that code, you will get a very unhelpful error message (error in eval()'d code at line 3) and you might even have go through your database manually to find and fix the error. If it is inside a block that is displayed on all pages and results in a fatal error all the time for example.
The above is also true when upgrading from Drupal 6 to 7 and whatever API's you used were changed. So you will have to port your code while migrating. If the code is in a module, you can port it in advance, test it, and only deploy it on the new site. Inside a node or block, it will only work with either Drupal 6 or 7.
Writing and maintaing that code is also harder, because you are working in a textfield inside your browser. Having it in a module allows you to use an editor/IDE with syntax highlighting, autocomplete and so on.
There is always the possibility of a misconfiguration that gives people access to a text format/block/whatever with php execution enabled. If php.module (in D7, D6 is not so strict, for example for block access rules) isn't even enabled, that risk is much lower already.
If your CMS allows execution of PHP then an attacker who finds a security vulnerability of XSS or privilege escalation can now use your server for enormously malicious things (as part of a DDOS, sending spam, hosting malware, hacking into other sites/databases on the server, hacking into other servers on the network that might be behind firewalls). In addition to making small vulnerabilities more painful, this makes the site a more likely target of attack if its known that it can be used to execute php.

There might be more reasons, but that should be enough :)

You should care about portability of your data. What if you migrate your nodes from drupal 7 to drupal 8 and some node's body text has <?php whatever_function_that_does_not_exist_anymore(); ?> in it?

Do not think about your project within 5 months but within 5 years. Updates, good practices and portability are important aspects of any good IT project in my opinion.

Using as less contributed modules as possible is also one aspect of this.