Why does Rules event 'After updating existing content' not result in 'Create a new comment'?

Part 1: Understanding the problem

It takes a little time/effort to get used (and become experienced) in using the Rules module.

My experience is that it is rare to find a bug in the Rules module. Most of the cases where I experience something in Rules that deviates from what I expected, I can find out what "my" problem is by using debug-facilities available for the Rules module.

So within the Rules settings, experiment a bit with the debugging facilities that come with the Rules module. At least have a look at the "Rules Evaluation Log" (to check that the Rules logic being executed, actually matches what you expect that logic to be).

Depending on what the result of that type of debugging is, you may also want to (temporary) enable the Devel module, so that you can (temporary) add a Rules Action like "Display a value".

For more suggestions about Rules debugging, refer to  "How can I display the value of a variable inside a condition?"

Part 2: Examples of creating comments after updating existing content

Sorry to say, but I disagree with this comment that was posted below this answer:

  It seems that it cannot work in this way and it is not possible to create a comment with this event.

Have a look at these answers, which are about questions that are variations of the question here:

How to create a Rule to create a new entity of type Comment and a body with tokens?
How to add a comment form in VBO to add the same comment to mutiple nodes?

Part 3: Experiment with other text formats

Even though your question doesn't provide any details about the text formats you are using, IMO it could well be that your actual issue is caused by the Text format that you're using for the comment body: your rule shows you're using filtered_html, but you should definitely give it a try to experiment with other text formats, such as plain_text.

PS: this answer is about D7 ...


Drupal multisites share modules and libraries?

Yes.

In a multisite setup anything in sites/all is shared.
This means sites/all/modules, sites/all/themes, sites/all/libraries are all shared.

In addition to that, if you have things that are specific to a subsite, for example, a sub-theme, or a module or library, you can add them in sites/subsite_name/modules, sites/subsite_name/themes, sites/subsite_name/libraries.


How can I get a list of content types with drush?

List of names:

drush sqlq "SELECT name FROM node_type;"

List of machine names:

drush sqlq "SELECT type FROM node_type;"

This works in D6 and D7.

The first line of the command's output will be name or type, respectively.
Pipe |tail -n +2 if you want to drop that first line.


After using unset($form['author']); for comment module drupal returns errors

You should try this if you just want to hide the comment default name field !

function user_add_node_form_comment_form_alter(&$form, &$form_state) {
  $form['author']['name']['#access'] = FALSE;
}


Where to find the html.tpl.php $head variable content generation

The most common way to add information to the <head> is using  drupal_add_html_head().

If the data you want to alter was added using that function, you can alter it by implementing hook_html_head_alter() within a custom module. Using the alter hook requires that you know the $key of the data that was added during drupal_add_html_head().

If you want to alter CSS or JS, use hook_css_alter() and hook_js_alter() respectively.


Uc_product module for drupal 7 not found

The uc_product module is part of the Ubercart module.  Based on drupal-commerce you added as tag to the question, I assume you are using the Drupal Commerce module instead of the Ubercart module. In that case, uc_product wouldn't be useful, unless you switched over to using the Ubercart module.

The Commerce Feeds module would likely be more useful if you are really using the Drupal Commerce module.


From the url /admin/structure/block you can set Blocks to Regions on your site.
You simply drag and drop the block(s) to the given Region of your page and Save the block ordering on that page. In this screenshot I have 3 blocks in the main content area for my theme:

You can then go into each block with the configure link and set that block to show only on certain page(s) for instance, or only for certain Roles of the site.

This is the simplest means using Core drupal and no 3rd party modules.

If you want to eventually look into other means of doing this look into the Context module, or Panels.


How to produce markup from a custom views field (FieldPluginBase based) render method in D8?

I can output HTML using my render method. Take a look:

  /**
   * {@inheritdoc}
   */
  public function render(ResultRow $values) {

    $field_abnormal_category = $this->view->field['field_abnormal_category']->original_value->__toString();

    if($field_abnormal_category == 'No') {
      $field_category_image = $this->view->field['field_category_image']->original_value->__toString();
    }
    else {
      $field_category_image = '';
    }

    return [
    '#type' => 'inline_template',
    '#template' => $field_category_image
    ];

  }


Is there a module for user level permissions?

Yes! Check out the Role Delegation module. Here is a quote from its project page:

  ... allows site administrators to grant some roles the authority to assign selected roles to users, without them needing the administer permissions permission.


How to keep "active" css on menu item when clicking on other link on same page?

You could consider using jQuery client-side to set the class based on path. See this post on how to do that: http://www.itworld.com/article/2832973/development/setting-an-active-menu-item-based-on-the-current-url-with-jquery.html

or you could try using Menu Trail By Path module
https://www.drupal.org/project/menu_trail_by_path


what is the meaning of $Id$ at the head of module files?

Its legacy left behind of a no longer used version control system (CVS) used by Drupal.org/projects before the current  version control system (git) was adopted.

You should not use this when writing your own code.  The automated code checker tool at Drupal.org will actually complain if these are present.

And, btw: Git rules!


How to override default class of custom text field in views?

Just found it myself. Sometimes you have to ask to look into something unexpected...

In style settings it's the "Customize field and label wrapper HTML" -settings i was looking for. With "create a css-class" you can override the default setting of the wrapper.

Thanks for looking anyway...


Table locking again, am I doing it correct?

MyISAM performs a table-level lock to do any SQL on a MyISAM Table.

If you convert everything to InnoDB, row-level locking is implicitly done for you. Multiversioning Concurrency Control (MVCC) allows each user to lock only row(s) needed.

Additionally, you may want to perform all atomic writes in a BEGIN...COMMIT transaction to group together several table updates as one unit. That's what InnoDB will do for you. InnoDB is ACID complaint. The A stands for ATOMICITY, a transaction's ability to be atomic.


DPM simpleXMLElement returns just the object but echo returns its value

The issue was that dpm was not printing some of the SimpleXMLElement values. They were only visible from the var_dump after die. Maybe there is a better way to check these. What I noticed was the value was being generated but dpm was not showing it and var_dump did.


How to clear ALL cache, including field and filter caching of nodes and fields?

"All" cache doesn't include the filter cache and if you are working with filters then that's the one you most likely want to clear.

You can clear the filter cache by truncating the cache_filter database table.

If you have drush at your disposal, you can run drush sqlq "truncate table cache_filter;" to get the intended result.

Please note, if you are using database prefixing you will need to add the prefix yourself, as the drush sql-query command executes the query exactly as provided.


Had to manually run the cron via the browser to generate.


How do I add a class to local task links in Twig template?

{% set link = link|merge({ '#attributes': { 'class': [ 'your', 'custom', 'classes' ] } }) %}

<li>{{ link }}</li>


find nodes by attribute and modify at once

Some options:

You can use Views in combination with Views Bulk Operations and Rules.
You can also have a look at Editable Fields in combination with Views


Fatal error after enabling backup and migrate module

Go to this link and install the ctools-cache-handler.patch patch


Display Youtube videos in a gallery of thumbnails with a primary player

I have make something like this using views slideshow.

Added youtube thumbnail in the views
Added youtube video in the views
Add slideshow as style format of the view
Set youtube thumbnail in pager of the slideshow

Its working for me.


Display a field only when dependee image field has more than three images

You can do this by using Conditional Fields module.

  Define dependencies between fields based on their states and values.

  Conditional Fields for Drupal 7 is an user interface to the new States
  API, plus the ability to modify fields appearance and behavior on
  certain conditions when viewing content.

How to use ?


What might block the creation of thumbnails?

Perhaps you need to look for this file: /var/www/httpd-logs/your_site.com.error.log

So, edit your sites/default/files/.htaccess

# Turn off all options we don't need.
#Options -Indexes -ExecCGI -Includes -MultiViews
Options -Indexes -ExecCGI -Includes


Selecting more then one column when groupBy is present (db_select) - Drupal 8 added 'ONLY_FULL_GROUP_BY'

This is pretty annoying, but it is to provide cross database compatibility for Drupal.  You can get around it by adding the following to your database connection array if you only ever intend to live in MySQL compatible land:

'init_commands' => [
  'sql_mode' => "SET sql_mode = 'ANSI,STRICT_TRANS_TABLES,STRICT_ALL_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER'",
],

But I haven't yet figured out how to disable in my Kernel tests.  Still getting something like "PDOException: SQLSTATE[42000]: Syntax error or access violation: 1055 'local.nfd.title' isn't in GROUP BY"


Content Access VBO

Maybe you want to look at Content Access VBO ... It's (still) a sandbox project, so not sure if you really want to consider it. Here are some details about it (quote from that link):

  ... creates an action for Views Bulk Operations to update per node content access (view/edit/delete etc). It adds a menu item to the Content menu tree and adds a new view which lists content with the VBO action as a button.

But at least it may help to get more inspiration to build your custom module to get this done.

Combine Rules with Views Bulk Operations or Content Access

Another approach is to use the Rules module, combined with modules Views Bulk Operations and/or Content Access. Here are a few questions that may help to get more inspiration about its possibilities (the sky is the limit ...):

Is there a module that lets one person do a bulk publish/update?
https://drupal.stackexchange.com/questions/159988/how-to-implement-a-complex-workflow-in-a-website-with-subsites-and-using-opensch/161616?s=8|0.2610#161616
How can an author mark the update date of a node to be visible or hidden for visitors?
Is there a module that lets one person do a bulk publish/update?
How do I publish nodes 3 times a day?.


For Drupal 7 you'll need at least PHP 5.2.5. Have a look at http://drupal.org/requirements
One specific issue I had with PHP less than 5.2 was that I could not install http://drupal.org/project/drush so I had to upgrade. Probably I'd have more problems down the line if I hadn't.

The MySQL version you have is OK.


Never mind!

I just discovered the "limit list to selected items" check box which solved my problem.
It does mean I have to manually select the taxonomy terms I want visible. So, it's not a fully automated solution but it will do for now.


Where can I find the link within admin for running the cleaner module, and how to install it?

The Cleaner module must be installed before you can use it.


Need to add HTML characters to Select list

You can and should put the UTF-8 characters for the symbols in your list. HTML entities are a relic from the past when it was possible that some symbols did not have a representation in the active code page. Thus simply use €, £, and ¥ in your lists.

Drupal is UTF-8 from back to front: use it.


Problem with dependency injection (File::load and \Drupal::service)

If you are extending FormBase you can use create to inject dependencies. In this case what I think you want is the entity_type.manager service and file.usage.

  /**
   * Class constructor.
   */
  public function __construct(EntityTypeManagerInterface $entity_type_manager, FileUsageInterface $file_usage) {
    $this->entityTypeManager = $entity_type_manager;
    $this->fileUsage = $file_usage;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('entity_type.manager'),
      $container->get('file.usage')
    );
  }

See this docs page for more examples.

The create method sends arguments to the constructor, and then you set those to instance variables, and voila, there are your dependencies. Be sure to update your file with the necessary use statements and declare your protected members (entityTypeManager and fileUsage) at the top of the form class.

Therefore, you can remove the static ::service call and use:

$this->fileUsage->add()...

Also, the reason I am passing entity type manager service, is because you would replace File::load with:

$this->entityTypeManager->getStorage('file')->load($id);

If you need more than that object returns, you may need to use a different service but I don't know that off the top of my head.


Drupal HTML.tpl.php file won't effect site?

There are several ways to achieve this.

You could hand code the meta viewport tag in your html template file as you did. The proper tag may need to be used as shown below:

<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=yes">

You could also use a page alter to add the html to your page as shown below (place in theme template.php):

function YOURTHEMENAME_page_alter($page) {
  // Viewport array, change values in content below.
  $viewport = array(
    '#type' => 'html_tag',
    '#tag' => 'meta',
    '#attributes' => array(
      'name' =>  'viewport',
      'content' =>  'width=device-width, initial-scale=1.0, user-scalable=yes'
    )
  );
  // Drupal add HTML head.
  drupal_add_html_head($viewport, 'viewport');
}

Or you could use the viewport module

Note: Do not alter the system html template file, puppies will die!


Attaching CKEditor to E-mails subject and body?

Looks like there is no any way to attach it. I used only html tags to format this notifications and their subjects.


How to add an article to a page automatically

A couple of ways to do this based on your requirements.

Display multiple articles on your homepage

As @leymanxx mentioned create a view with a page display then set the path of the page you created as your default front page.

Display a single article on the homepage

Create an article and set that's article path as your default front page.
You can read more here


If you're not wedded to AddThis then the Service Links module integrates with the Shorten URLs module to provide this feature. It has the advantage of not being coupled with/crippled by the AddThis service.


Running drush entity:updates claimed successful but not changing anything

For deploying entity schema updates use an update hook and the entity definition update manager. See the release note of Drupal 8.7.0 and the change record Support for automatic entity updates has been removed.

drush entup is moving from core to contrib: https://www.drupal.org/project/devel_entity_updates

  This project aims to restore this functionality as a developer-only
  tool. This module depends on Devel and is not meant to be enabled in
  production environments or relied upon in deployment workflows.

"Or is there any alternative way to update entity definition and make changes to database?"

Yes, there is. Don't use base fields other than for the very basic things that never change (if core makes changes necessary you'll probably find then examples how to write the update hook). Instead use configurable fields (bundle fields), so that you can deploy easily through configuration.


I need to have my site visitors post comments even if they are not logged in as a member

You need to give the "anonymous user" role permissions to post comments. Go to admin/people/permissions and look for the Comment section. Check the box for "Post comments" for the Anonymous user role, then save the settings.

I would not suggest this unless you have good anti-spam measures in place. You can search drupal.org for modules in the Spam Prevention category to help with that. Otherwise, I would require users to sign in before posting comments.

Note that even when requiring users to sign in to post comments, you'll still likely run into spam. Couldn't hurt to look into the list of modules linked to above.


Is there any module for importing news from a WordPress site?

For Drupal 7 try WordPress Migrate:

  wordpress_migrate supports migrating WordPress blog exports (WXR
  format) into Drupal using the Migrate module. Import of posts, pages,
  comments, attachments, tags and categories is supported. Imports can
  be rolled back completely.

and Wordpress Import if you are using Drupal 6:

  This module imports a WordPress blog into Drupal from a WordPress
  eXtended RSS (WXR) file.


Uncaught PHP Exception: Query tagged for node access but there is no node table, specify the base_table using meta data

For anyone else running into this, I was able to get it to go away by checking all my blocks' permissions, especially the ones related to user information, and for me, the culprit was the User Activity Log block. Once I added the Visibility setting that only authenticated users had access to the block, the error went away.
Looks like the Drupal devs aren't having this module fail gracefully for unauthenticated users.


Views: How to change entity view mode settings when a contextual filter is available?

Just create a view with two page displays.

The first display will be on the path with no arguments and will display teasers.

The second display will be on the same path with an argument such as thepath/% and will display full view mode.

When you alter the format and add the contextual filter in the second page, make sure to select it only for that display, otherwise it will overwrite the first display as well.

This is what views displays are for. Use it.


User Register page is different if there is a destination parameter in the url

The drupal_get_form() returns a form array for rendering. In your case drupal_get_form('user_register_form'). You can use drupal_render() with the result to render the html output.

If you need to override the form, use hook_form_alter() and change the $form_state['redirect'][] = 'your/redirect/path'. Also try removing the destination param with unset($_GET['destination']).

Here are some references:

Form Redirect not working if 'destination' is in URL
https://stackoverflow.com/questions/1175687/redirect-after-registration-in-drupal
http://www.brianvuyk.com/story-type/changing-redirect-value-drupal-node-form-d6


Which permission do I need to give to see all open tasks in the Maestro taskconsole

Seems that you need to give the following permissions:

Access Maestro Task Console
View Outstanding Tasks


How to make a particular role user and their content not accessible/viewable to other users?

Content Access

This module allows you to manage permissions for content types by role and author. It allows you to specifiy custom view, edit and delete permissions for each content type. Optionally you can enable per content access settings, so you can customize the access for each content node.

Video Tutorial
I think content access is only for content type nodes. So for the user page umm.... I can't think of anything of the top of my head. I will edit this if I can think of something. Perhaps the only solution is doing it with a custom module programmatically.

If you use pathauto you could make so the user page path is user/[user:role]/[user:name]
then you could use
Path Access

Path_access provides the means to restrict pages based on their path
alias - meaning you can lock out certain user role groups from whole
sections of a site using wildcards.

and lock them out from certain [user:role] paths.


Contribute D8 version of an existing D7 contrib project?

You can use Browse code repository to see your source code on your project page. Currently when you go to list of branches, the 8.x-1.x doesn't exist yet.

To maintain both D7 and D8, you need to have one branch for each, 7.x-1.x for Drupal 7, and 8.x-1.x for Drupal 8.

To create Drupal 8 out of Drupal 7 version, you should first clone your repository as per these Git instructions:

git clone --branch 7.x-1.x your_user@git.drupal.org:project/check_dns.git

then create a new branch:

git checkout -b 8.x-1.x

which allows you to freely modify your files for Drupal 8 version.

Once you did your conversion, you can push your branch back to Drupal.org, e.g.

git push origin 8.x-1.x

To switch between branches, use git checkout command, so you can contribute to both version.

Ideally, you should read more about managing source code using Git. Checkout this GitHub Cheat Sheet.


Make one reference and load the other automatically (Entity Reference)

Broadly if your node reference is required your user must to fill it on node creation. So you could try to use hook_node_presave or in the form layer you could have your submit handler to deal with that. Once you get the reference chosen by the user you would need to retrieve the other 4 related references that will be also added as siblings in the multi valued node reference field.
By another hand if you want to make all of this visible in the form before it gets submitted you could use hook_form_alter (in case you don't have your own hook_form) to add a behavior to the node reference field form element and if it has just a checkbox widget you could simply automatically check the other nodes to be referenced using the behavior to react the check box that has been checked.


Can the core Profile module (it is deprecated) be used? And how will I upgrade?

First of all, it's important to understand something MotoTribe has already mentioned. The most important functionality of "Profile" is now in for Drupal 7 new "users are entities" concept. Since this allows you extend users with fields, the profile module was considered redundant.

If I recall correctly, the main reason for it remaining in Core, was as a transition path from D6 Profile. In D8 I don't believe Profile will exist at all, and since it's already deprecated, I very much doubt there will be an upgrade path from D7 profile.

If we instead follow the trail of issues that follow from yours on the Profile2 queue, we find a Core issue, which is so far advanced that it has been applied to D8, and applies cleanly against D7 with full test coverage. I would apply that D7 patch, and try with Profile2 again.


Figured it out!

The parent must be the Views local task id for both definitions.

So parent_it should be views_view:view.media.page


How to display nodes in a view, each row using a preselected view mode ?

First you need to save the view mode for each entity (e.g. in a field).

Implementing hook_entity_view_mode_alter you can override the view mode:

function mymodule_entity_view_mode_alter(&$view_mode, $context) {
  if ($context['entity_type'] == 'node') {
    $entity = $context['entity']
    if (get the view mode of $entity) {
      $view_mode = 'custom_view_mode';
    }
  }
}

Remember to do a check to run this in your view only, otherwise this will affect the node everywhere.


You can create your own layouts in a module or theme by defining a my_module.layouts.yml or my_theme.layouts.yml file. Then you'll have to create the templates for your layouts where you output the regions.

This is the layout definition for the DS 2 Col Fluid layout (ds.layouts.yml):

ds_2col_fluid:
  label: Fluid two column layout
  category: Display Suite
  class: '\Drupal\ds\Plugin\DsLayout'
  type: partial
  template: templates/ds-2col-fluid
  library: ds/ds_2col_fluid
  icon: images/ds-2col-fluid.png
  regions:
    left:
      label: Left
    right:
      label: Right

label defines the label that's displayed when you're selecting your layout on the Manage Display screens.

category defines the option group that your layout appears in on the Manage Display screen. It can be helpful to use My Module or My Theme here to group all layouts defined by your module or theme.

class I've never had to change this to anything else to anything other than \Drupal\ds\Plugin\DsLayout

type I've never set this to anything other than partial. I'm not sure what the other options are.

template defines the template file to use. This should be the relative path, from your module or theme, to the template.

library allows you to load a drupal library as a dependency when you're layout is being rendered. Add js or css that you may need.

icon defines the path to the icon that appears on Manage Display screens to represent your layout.

regions define the regions of your layout.

As far as I know you don't need to include the icon or library parameters and it won't cause any errors.

Your template file will have variables for content, attributes, html element for each region, layout and outer wrapper. See ds/templates/ds-2col-fluid

Here's an example for how you can render a region you defined in your layouts.yml file (taken from ds/templates/ds-2col-fluid):

{% set left = left|render %}
{% if left %}
  <{{ left_wrapper }}{{ left_attributes.addClass('group-left') }}>
    {{ left }}
  </{{ left_wrapper }}>
{% endif %}

If you define your layouts and templates in a module file, you can later override the templates in a theme if needed, as you can with any standard template in drupal.


How Do I Disable CiviCRM locally if I don't need it?

In a clean Drupal and CiviCRM install, the CiviCRM module can be disabled without generating any errors.

Getting CiviCRM working in a local development environment that doesn't mirror the configuration of the actual site can be a pain and CiviCRM adds a lot of overhead to page loads and increases the memory required for many tasks, but the steps for resetting the paths and deleting temp files are well documented at http://wiki.civicrm.org/confluence/display/CRMDOC/Moving+an+Existing+Installation+to+a+New+Server+or+Location

CiviCRM includes handful of Drupal modules that give Drupal access to the CiviCRM data in modules like Views and Rules as well modules that do things like add or remove users from roles based on having paid their membership, but CiviCRM is much more than just those modules.  CiviCRM is a large PHP project (much larger than Drupal core) that runs within Drupal, WordPress, or Joomla's menu and authentication and includes APIs and hooks that allow custom development to tap into CiviCRM at many levels with any of those CMSes.

You could probably get away with a "dummy" CiviCRM install if the site hasn't done much customization to CiviCRM or written any custom code that leverages it, but if disabling CiviCRM "throws a bunch of errors on various places" my guess is you are working with an instance of CiviCRM that has already been customized and integrated.  You'd have to share the specific errors for anyone to confirm that.  As soon as anyone added a custom field to one of the CiviCRM data types (profiles, contributions, events, etc), that fields could be used in a View.  If a custom field is already used in a View, you have to get the client's copy of CiviCRM running or risk deleting a CiviCRM reference when updating a View.

While CiviCRM isn't Drupal, it isn't rocket science either.  If you aren't sure what customizations and integration have been done, it is much safer to get CiviCRM working than trying to disable it.


It looks like you're using code from Drupal 6 in your first example, but from your second you must be using Drupal 7...$node->taxonomy isn't used in Drupal 7, taxonomy terms are related to entities via fields instead.

Your second example isn't working because the taxonomy_index table is just an index table relating nodes to terms...the hard-link between those two entities is actually contained in the field reference, which you haven't updated.

If I could offer a different approach, it would be to use hook_node_presave(). Using that method you can simply add another term id to the list of selected terms from the form, and rely on the node/field API to commit the changes and update the cache on your behalf.

function MYMODULE_node_presave($node) {
  $term_id = 73;

  // In reality you'd want to loop through the existing field values and check to
  // avoid duplicates; this is just an example to actually set the value.
  if ($node->type == 'mytype') {
    $node->field_term_reference_field_name[$node->language][] = array('tid' => $term_id);
  }
}

As an added benefit this will also work for any nodes that you add programatically, not just those added/edited through the node form.


{% if product_entity.status.value == 0 %}
  {%
    set classes = [
    'is-unpublished'
    ]
  %}
{% endif %}
<article{{ attributes.addClass(classes) }}>
..
</article>


Drupal 7 + Solr - Importing feeds after website restore leads to 1062 Error

It turned out it was the Solr module itself. I'm not sure why it wasn't clearly it's index completely, but after disabling and actually removing the module, then reimporting, everything worked.

So if you're having this kind of trouble importing content, and you have the Search API Solr module active, first disable and then remove it so that you have a clean slate on that end. Then you can reimport the content, then later re-add the Solr module and reindex your content.


Insert a Views Block into a node in Drupal 7

Output is "array" because indeed is an array, then I guess that you want to print your array to see what fields you can use:

print_r($block);
print_r($block['content']['#content']);
print_r(render($block['content']['#content']);

About display a View, you can use this line of code inside your template, to call a view:

echo views_embed_view('view-name', $display_id = 'display-name');

for example, inside my node.tl.php I want to insert a view called test view and I want to use his Block display with machine name block_test, then I can use:

echo views_embed_view('test_view', $display_id = 'block_test');

(Remember to use the machine name of your view and machine name of your display).

I hope this information will be useful.


Automatic registration for anonymous node authors

I am not sure how easily you would be able to do this, but you might be able to do this using rules.

Have a look at Inline Registration.  You can configure quickly to attach a registration form to the node creation form.


1) you need to implement EventSubscriber, use KernelEvents::REQUEST in getSubscribedEvents() method

2) then you use \Drupal::request()->query->set('key', 'value');


You could use the Rewrite results option on that field and choose Strip HTML tags.

This will "remove" the image from display.

If you have some other HTML inside the Body that you want to keep you can enter them into the Preserve certain tags field, for example <em> <span> <p>.


Try this in your template.php of your theme. Change MYTHEME to the name of your theme and bookmark to the machine name of your flag. And change node-flag-bookmark to the css class you want to be added to your node.

/**
 * Implements template_preprocess_node().
 */
function MYTHEME_preprocess_node(&$variables) {
  $flag = flag_get_flag('bookmark'); // Machine name of your flag.
  if ($flag && $flag->is_flagged($variables['node']->nid)) {
    $variables['classes_array'][] = 'node-flag-bookmark';
  }
}


How to translate the URL alias (path) for an English version to an Arabic version?

For URLs related to nodes, users or taxonomies

Consider using the Pathauto i18n module for this. Excerpt from its project page:

  ... by default Pathauto creates alias only for one language or for all languages one alias. This module provides functionality to create aliases for each language. Also this module will be helpful, if you use field translation and you want show node on all language with paths, different from node/nid.

This module contains 3 submodules which can be used to enable separate functionality for each entity:

pathauto_i18n_node (for nodes).
pathauto_i18n_user (for users).
pathauto_i18n_taxonomy (for taxonomy).

Example (also from project page):

When you create node without pathauto_i18n:

English alias: en/articles/first_article
Italiano alias: not exist
Deutsche alias: not exist

When you create node with pathauto_i18n:

English alias: en/articles/first_article
Italiano alias: it/articolo/first_article
Deutsche alias: de/artikel/first_article

For URLs related to views or panels

Use the i18n_path (Path Translation) sub-module of the i18n module. Refer to its Community documentation for more details about it.


Is there a way to automatically have a copyright attribute when content is submitted?

The only ready-made solution I know of is Plagiarism Checker - Authentication Framework.

  The module is a framework which supports various search APIs (plugins) to scour the net looking for possible plagiarized content. The framework provides support for 2 different types of APIs - Standard APIs (Google and Yahoo plugins are included here) and Custom APIs (such as the 3rd party paid authentication service from iThenticate (www.ithenticate.com)).

Note that these APIs are either not designed to plagiarism discovery, giving a lot of false positives, or may be paid. Also, low usage count and Development status: Maintenance fixes only should make you careful.


Bootstrap 3, how disable auto-added Glyphicon?

I haven't tried it for Drupal 8, but its works for drupal 7. It should work for drupal 8 as well.

In your bootstrap theme setting, under bootstrap setting there is tab of General setting. Inside that tab the are settings for different bootstrap components. You will see Buttons there. Just open that section and un-check Iconize Buttons option. That's it.

This will disable all the auto icons in buttons.


How to alter a custom text field in a block with AJAX

You have some examples in "Examples for Developers" https://www.drupal.org/project/examples

If you see in ajax_example module, you have "Ajax Link" which points to the url ajax_link_callback,  (defined by  menu hook ajax_link_callback in file ajax_example.module, line 181).
This menu hook has a callback function (see file ajax_example_misc.inc, line 102), which does the magic.

You can see that the ajax response is made with a few components. First the $commands array with the target div and the content to output. Then this array is wrapped in another array ($page), and delivered by the function: ajax_deliver.

Note that the original link ( which is produced by the menu callback ajax_example_render_link() in file ajax_example_misc.inc, line 22), has a use-ajax class attribute and previously the drupal.ajax library is added to the page.


how to print db_select result using watchdog?

execute(): - this will not return query results to you. All it will return is database connection object and query string. See the screen shot.

In order to get query results, you need to call any of the retrieve function. For example

fetch();        // Use the default fetch mode.

fetchObject();  // Fetch as a stdClass object.

fetchAssoc();   // Fetch as an associative array.
Debugging queries:

I would recommend you to use devel module and its help functions as dpm() and dpq() . They will make your debugging process a lot more faster can clean than watchdog.
watchdog() - I confirm the answer by @Decipher(+1) will record the query object in database, see the scrrenshot tested with a simple query

Might be that log is not something that you want to see, a small change to @Decipher answer if you want to see the query String

watchdog('userpoints', 'perishables->remainder %perrr', array('%perrr' => print_r($perishables->queryString, TRUE)), WATCHDOG_DEBUG);

You can definitely make it better the way you want with above mentioned tools


When managing fields for a content type, fields of type "list (integer)" can't be shared?

Here's the answer to this question:

I cannot use the same field within one content type. Only one instance of a field may be used within each content type. This is why the field which I have created is not showing up in the drop-down for "add existing field" - it is not available.


How to remove Neighborhood and Address 2 fields in commerce kickstart?

If you log in as admin:

Got to: admin/commerce/customer-profiles/types
Select the "manage fields" for the correct profile
Edit the Address field
Under "Format handlers" there should be checkboxes to hide the fields you do not want to show.

To do via code, see Use only one address field


You can use 'Field collection' in your content type for products, In your  field collection field keep one field as label and other for the value. This approach will suit your needs


Use views to display taxonomy children terms from parent

With in view there is a an option to add a contextual filter Content: Has taxonomy term ID (with depth) There you can select the depth of till which you wan to show the children. So if you select say 5 all the child nodes till a depth of 5 would be shown. I think that should do what you are looking for.


I tested out the hook_menu in my local. The hook seems fine. Check if you have added an  access denied code in the callback function

function commons_menu() {
  $items = array();
   $items['data/update'] = array(
    'page callback' => 'dataupdate',
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
  );
   $items['onthewayout/forward'] = array(
    'page callback' => 'register_click',
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
  );
  return $items;
}

function dataupdate() {
  return drupal_set_message("First one is working");
}

function register_click() {
  return drupal_set_message("Second one is also working");
}

This returns a Access Denied to me even if access callback is true.

function register_click() {
  drupal_access_denied();
  exit;
}


Search settings: Indexing status stuck on 0%

Run cron. (example.com/cron.php or go to Admin >> Reports >> Status and click "run cron")


How to split Views exposed filters into separate blocks

The MEFIBS - More exposed forms in blocks module provides this functionality.


Print selected fields from a referenced node

I would use Display Suite for this problem. Using it, you can define an extra view mode for the referenced node type, with just the fields you want, then configure the display of the entity reference field to use that view mode. We are doing this in the current project I am working on, and it's just the ticket.


How to insert a view in the body field of a node?

I've found this module Insert View

I haven't tried yet. Let me know if it fits your request.

I found this as well Views Reference
I tested both and I think the second is more appropriated for you.


The cause of the problem is probably not the template but how the field is configured in Views. You should be able to find a solution there, even if it means you need to rewrite the field output.
If you want to try solving it in this template you have to check what is inside of output. Views usually puts the field output in a markup object. Then you have to render it first before applying twig filters:
{{ output|render|striptags|trim }}

I've also added |striptags, otherwise you would see HTML tags in plain text on the screen because they are escaped by trim.


Dynamic ordering of views based on argument

I ended up using this code to get the desired functionality:

function mymodule_views_query_alter(&$view, &$query) {
  // in my case I'm pulling info from the user object to decide the sort,
  // but obviously you could check anything here. Use arg($x) to read URL arguments.
  global $user;
  if ($user->country == 'AU') {
    // Note in this case NULL is above AU, so descending order it is.
    $query->orderby = array_merge(array('location_country DESC'), $query->orderby);
  }
}

I'd love to hear any other thoughts on good ways to do this, particuarly some guidance with adding sort objects to the view using hook_views_pre_execute or similar.


How do I add a checkbox to the performance page and have it repopulate?

to have it "repopulate" after save provide a #default_value key that retrieves it on page load.
to actually save it append (add another) custom form submit handler to the form, after the original one gets fired. Something like $form['#submit'][] = 'mymodule_mysubmit_handler'; You will have to check where the submit handler is set already in the form, or the element you're trying to hook into (such as $form['caching'] ...


When you create filter "Taxonomy term: term" there's first step you are choosing "vocabulary" and "selection type" of the filter. It looks like vocabulary you have chosen has no terms.


How to use mmenu without breaking core Overlay

You should consider using Mobile Sliding Menu. It could save you a lot time and pain.

  The mobile sliding menu module integrates the mmenu jQuery plugin for
  creating slick, app look-alike sliding menus for your mobile website.


Delete/ Deactivate account in a separate block

What you are describing will require a custom module that will provide the non standard functionality.

You will need to provide hooks for blocks (hook_block_info and hook_block_view) producing forms using the FAPI to produce the forms as you are showing in your mock.

Deleting an account would require using form validation to test that the username and password is correct and matches the content that you are viewing as well matches the user that is logged in. Once validated you would call the user_delete function, however be aware that this will delete all content owned by the user.

Disabling or Deactivating account will require a hook_block_info and hook_block_view  as well the form using the FAPI as well a subset of the  validation mentioned above, then calling the user_cancel function passing in the appropriate arguments.

The forms could be rendered using...
1. the blocks ui with conditional visibility settings.
2. at the theme level using a preprocess_page hook in template.php
3. other...

As Drupal is like a swiss army knife and this is one of many ways to solve the issue.


The problem is not your hook_menu implementation, but your function leg_node_form. That function probably calles node_form, which is in file modules/node/node.pages.inc you have to include that file manually using module_load_include.


How to prevent node delete for a specific node?

I don't think there's a catch all solution.

On second though, you maybe can create a new content type, say node2, and set the permissions for that content type to admin only.

and if you will ever need more than one admin-only node, you'll have no problems at all.

however i have no experience whatsoever there :p

in hook_menu_alter change the 'access callback' for the "node/%nid/delete", since you need it only for a particular node ( say nid=120)

$items['node/120/delete'] = $items['node/%nid/delete'];
$items['node/120/delete']['access callback'] = 'custom_function';
unset($items['node/120/delete']['access arguments']);

this will prevent that node to be deleted directly.

then you need to remove the delete button from that node form edit (however i don't know the form name).

this should be enough and prevent the deletion "nicely", but you can use hook_delete like pointed out in the other answer to catch everything and everything else that can't be prevented like that.


What @Clive said is the right answer as far as core goes. You have to make another request.

There are some contrib projects that provide more flexible interfaces. One of them is https://www.drupal.org/project/graphql, which allows you to execute a query and specify what data you want to have shown. I believe it's still fairly experimental though.


Pass variables from one preprocess function to another in .theme

well after finking a lot about this problem, i realized that i don't wont to duplicate this variable at all.

lets start from beginning i wanted to copy the $variables['message_list'] from status-messages.html.twig to make my custom layout for different situation.

for example i wanted to have different layout/design of status message on  my custom login page and another layout/design for my custom register page. but now i understend that i can have this two in one place (in status-messages.html.twig) i can check if my URL is /login tean  with help of twig if condition i can render one layout and if  my URL is /register then i could have second layout! and in aver situation u would have default layout.

is that correct? how would you solve the problem if you ware in my place


It's hard to say, what your problem with Commerce subscription products is, without more detail.

Randy Fay have made a lot of screen casts about Commerce which also include configuration about Rules. You might be able to find a more better tutorial on Rules, but Randy does a really good job on stepping through different tasks in Commerce. There isn't a screen cast about subscriptions, but you should be able to get a lot of help from some of these anyways.


Drupal 7 Views table style with exposed filters

The only way to do this is in the theme layer.

One way would be to implement a theme override - probably with a hook_preprocess function, maybe also hook_form_alter. Embedding the form in a table will be particularly tricky, since the exposed filter and results table are rendered in distinct processes.

If you are comfortable with jQuery, it might be easier to do this with javascript.


Drupal 7 - When to use template suggestions?

page--internal-path is already defined by Drupal core as a theme hook suggestion, so adding your own version of it won't really have any effect (just as then removing that version won't have any effect).

You can see a full list of the core-implemented hook suggestions on the Drupal 7 Theme Hook Suggestions page.

The simple answer to the question is that you need to provide your own template suggestions when you require that functionality, and Drupal's core system, or a contributed module, haven't already provided the overrides for you.


What is the meaning of the field:delta content type offered in contextual filters in views?

It appears only for multi-value fields. It refers to the order of the values. A delta of 0 is usually the first item, 1 is the second, etc. This can be used to restrict results to ones that have values for a specific delta.


Removal of all markup and overall customization

you can customize drupal as deeply and drastically as you please. typically that requires more intimate knowledge of how drupal works.

For alot of field based modifications the Display Suite module allows per-field HTML Reset to customize the HTML outputted per field. A lighter weight approach to the same idea of "resetting" how drupal outputs a field is the Fences module.

With regards to JS there is hook_js_alter which you may use the remove/alter what javascript files are loaded on the page.

All the HTML for the page can be tweaked from the html.tpl.php file used by your installed theme (or the base core supplied html.tpl file).

Have I done allll of these?! No, but I have used hook_js_alter to conditionally include JS on some pages via a module. I have for example removed all sidebars and unset I think most of the CSS found in <head> by conditionally supplying my own template file to a menu path via hook_menu:

Load custom template from MENU_CALLBACK

So there are tons of utilities to do this in Drupal. How these utilities play with 3rd party modules you want to leverage on your site ... or just how much custom work you want to do on your own website -- I leave as an exercise for you.


The short answer to all this is :

Create custom module , use provided Form API
Don't parse anything, use Field Collection to add linked nodes


Looks like your database cannot be contaced, run drush status to make sure of that. If that's the issue, then you should update your settings.php files with the correct ip, I guess 127.0.0.1 for your xampp stack.

Not an answer to your question, but running PHP/Drupal on Windows is just asking for problems. You should look into Vagrant or Docker to run your Drupal sites on Windows, that will save you a lot of pain in the long run AND will make it easier to deploy your sites later on.


How do I create a block in a module that can be referenced via an entity reference field?

To achieve this you may use the Block field:
From module description:

Use Cases
Add blocks to a node's sidebar.
Add blocks to paragraph.
Create a carousel of content and configurable blocks.

install and enable the module
Create a new field of type Block(plugin) in your paragraph type
In case you want only your custom block to be referenced in the field settings uncheck all other blocks in the AVAILABLE BLOCKS config like this for my Hello block for exemple

now you can reference your block in the paragraph.


How can I float a specific field to the right of another field

You can just use CSS for this. You will need to find the specific element ID or class for the containing element (div for example) for each of the fields (you can find this out using Firebug with Firefox), then create a CSS rule for each of those elements such as:

#field1 {
  float:left;
  width:150px;
}

#field2 {
  float:left;
  width:150px;
}

You will probably need to then use the CSS rule clear:left; for the field or element that follows after them.


How do I implement two-way node references?

There are many modules available, your milage may vary:

BackReference (Drupal 6 only)

NodeReferrer (Drupal 7 beta release)

Node Relationships (Drupal 6 only)

Corresponding node references (Drupal 7 stable release)

Corresponding entity references (Drupal 7 dev release)

Content Dependency (Drupal 7 stable release)


How do I translate the Book module tree navigation?

I found this that outlines the path to doing this with menus in general:
https://www.drupal.org/node/2182497

After testing it appears that this does NOT work with the Book module menus. All configuration options I have tried thus far have not been successful and I'm guessing the only options left are probably a custom code alter of the book_navigation or a custom book menu all together.

Those steps would included either using the book_navigation preprocess hook:
function template_preprocess_book_navigation
https://api.drupal.org/api/drupal/core%21modules%21book%21book.module/function/template_preprocess_book_navigation/8.2.x

and/or the twig template that renders the menu:
book-navigation.html.twig
https://api.drupal.org/api/drupal/core%21modules%21book%21templates%21book-navigation.html.twig/8.2.x

Hopefully those are a good start.


How can I sort by last word in the node title field?

This is probably not best solution, but it should work:

Try Views PHP. With this module you should be able to create sorting in view which will take only last word of given string (content of your title field) with PHP code (something like this example).

  This module allows the admin account (user 1) to add fields, filters and sorts to views which use PHP code.


Create a User View. Then add a "Contextual Filter" for the field "User: Roles". Set the "When the filter value is NOT available" option to "Display Summary" and leave all the other settings. Now you should get the list you want ...

Check the other settings for any customization of the list.


Do not show errors including database error to users in D7

You should be able to add the following to your settings.php to hide all errors (It will mean the admin screen you mentioned will no longer be used so any changes to this setting will need to be done via settings.php

$conf['error_level'] = ERROR_REPORTING_HIDE;


It's because you used the "Votes: Value" twice, use it once, "Exclude it from display" and render it using tokens as many time as you want and you must be good to go.


What are the implications of changing the default language?

The main problem used to be i18n and all the things that it translates.

Most of those (like taxonomy terms, fields, node types, menus), do not have an explicitly language assignment like nodes do. So the original strings are assumed to be in the default language (unlike interface strings, where the original is always en).

If the old default language was english and you change it to german, then i18n will no longer translate them to german on the german site but will try to translate them from english to english.

i18n added a workaround for this problem, on one of the many settings pages can be controlled if a different language than the default should be used as that original language. That's not a perfect solution, because it means that the site admins must create the original fields, node types, menu links and terms (assuming that i18n_string is used to translate them) in english and then translate them to german.


(hook_menu_alter) override the same path twice

There can only be one set of metadata for a single path. Hooks are invoked sequentially, so yes, if you have another module altering the same path, either yours or theirs will 'win'; never both.

You can control the order hooks are called in using the 'weight' column in the system table, or through the use of hook_module_implements_alter().


You need to utilize Drupal's JavaScript Behaviors functionality in order to ensure that your javascript is run after the DOM has loaded and that it will not conflict with other javascript in Drupal.

Try changing your JS file's code to this:

(function ($) {

Drupal.behaviors.myModuleBehavior = {
  attach: function (context, settings) {
    console.log("hello world");
    $('li').addClass('hello');
    $('div').addClass('hi');
  }
};

}(jQuery));


The Aggregator module that ships with Drupal core can pull in posts from the WordPress site's RSS feed. For more functionality and overall flexibility, you could use the Feeds module.


This is a lot harder to do than I first thought.  Formatted dates, including strings for the month (and day) names are produced by format_date().  This function is not themable, and there is no hook to override it.

That means that (AFAIK) there is no right way to change how this function behaves (the wrong way is to hack it - i.e. hack core - which is not an option in my book).

What we can do is to make a tiny custom module with a version of this function that outputs months and days in Dutch, no matter what the default language for the site is.  This function will do this:

function MYMODULE_format_date($timestamp, $type = 'medium', $format = '', $timezone = NULL) {
  return format_date($timestamp, $type, $format, $timezone, 'nl');
}

(Where MYMODULE is the name of your custom module.)

Now, if you set the default language of your site to English, but keep the Dutch translation available, one of the following calls:

MYMODULE_format_date($timestamp, $type);
MYMODULE_format_date($timestamp, 'custom', 'j F Y');

(where $timestamp is the timestamp to print and $type is the format to use) will output names of months and days in Dutch, but everything else will be in your site's default language.  The first will do this for any valid format (Long, Medium, Short, etc.), the second for the custom format 'j F Y'.

This will give you Dutch month names if you call this custom function instead of the standard one when outputting formatted dates.

However, it will not change the output in existing code which of course uses the standard version of the function.  This may not be a problem for you, since you want to use it with a custom date format (which obviously is not in use in legacy code), but I still want to make that clear.

If you want to change how months and days are spelled everywhere, you need to override the templates node.tpl.php and comment.tpl.php (and possibly other templates that uses format_date). In the override, just replace any calls to format_date with calls to MYMODULE_format_date.


"Really" disable entire cache during development (also routing, twig templates, css+js libraries)

I asked this on twitter and @renebakx replied:

  @stevepurkiss check how devel modules handles this, it worked for
  templates and added css/js to the theme's library. Not for added
  routes


Use inline template:

  return [
    '#type' => 'inline_template',
    '#template' => '{{ somecontent }}',
    '#context' => [
      'somecontent' => $somecontent
    ]
  ];

In your case without context, just straight up html.

You can also use the html_tag element for things like script or link and so on.


How do I store node form data between form steps using ajax?

This code is quite impressive. I did not think it was possible to build a multi-step entity form with a few lines in a form alter hook. To keep it this simple you can try to use the entity object to store the values, because the form object is serialized and cached between the steps and a method to build such an entity from the submitted values is part of the entity form class:

  if ($trigger = $form_state->getTriggeringElement()) {
    $form_object = $form_state->getFormObject();
    $new_entity = $form_object->buildEntity($form, $form_state);
    $form_object->setEntity($new_entity);


Tag autocompletion fails for anonymous users?

Figured it out myself while I was typing the question.

Since JS didn't work at all, I checked the console, found a CKEditor related error, fixed it, and things went back to normal.


How can I hook into an entityform? So that i could create a custom dropdown which is populated from a database

You can write a hook_form_alter()

function hook_form_alter(&$form, &$form_state, $form_id) {
    dpm($form);
}

After you cleared the cache you can print the form ID or just alter the form right away.

I suggest to check what the form ID is and then add:

function hook_form_FORM_ID_alter(&$form, &$form_state, $form_id) {
    dpm($form);
}

To alter it. (Make sure to clear cache again)

in both instances hook is to be replaced by your module name. When you want to use the dpm() function you'll have to install the Devel module.

I hope this helps!


Deny/allow access to group-content only for some roles

Install the Module Grants module. It will solve the conflict. Actually, it will take the conflict into account, which Drupal does not.

  Module Grants makes modules that deal with content access permissions operate better on unpublished (as well as published) content. It also makes sure that access grants behave in an orderly fashion when such modules are used together.


Is it OK to programatically access fields defined through the UI?

I usually use the entity_metadata_wrapper() function to create a wrapper, and deal with fields through that. But if the field doesn't exist, you can get some not-very-helpful wrapper errors.

To see if a field exists, you don't need a wrapper. You can use:

if ($node->my_field) {
...
}

You can create content types in code, but nothing (except common sense) is stopping a rogue user from deleting fields after they are created. So if you are really worried about fields disappearing, you should check that they exist before using them, as above.


Loading specific bootstrap mode in hook_menu

It's not possible, because hook_menu() is invoked when Drupal is completely bootstrapped, also because only when Drupal has been completely bootstrapped, all the modules are loaded; only in this case all the menu callbacks defined in hook_menu() are available.

If you really need to limit the bootstrap to a phase, then you can write a file that is similar to index.php, for example.

define('DRUPAL_ROOT', getcwd());

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

An example of file used for a specific task is cron.php.

define('DRUPAL_ROOT', getcwd());

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

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

Generally, there isn't the need to limit the bootstrap, only to serve data in JSON format. Creating a file like cron.php should be done for a dedicated task that is time consuming, or for limiting the pages being served, as with install.php.


Show all content related to child taxonomy terms in parent

Looking around I have found the solution that helps me. It's a module called Hierarchical Select.


Detect if its first time that user accesses the page

For authenticated users you can use a table where you write a record for each user who visits a page; in the case there isn't a record for the currently logged-in user, you create the record, and then redirect the user.

For the anonymous users, you can register the IP from which they connect, and remove the record after X hours, as the same IP can be used from different users, especially from users with a dynamic IP.


How should I insert a row into a database table created by another module?

I recommend using DrupalUpdateException to make update 7005 fail if the table doesn't exist so that it can be ran again when the table has been added, or at least notify the web builder that the table doesn't exist and needs to be worked on.


Custom maintenance page breaks module install process

Be sure to add the $content variable in the template even though you customized some texts in your template file. A sample would be:

<?php if ($content): ?>

<?php print $content; ?>

<?php else: ?>

Offline due to an unknown issue. Our engineers are working on it 24/7 to resolve this.

<?php endif; ?>

Apparently, Drupal limits/locks access to the database during module/theme install, thus triggering the maintenance-page--offline.tpl.php. Take note that if you don't have the mentioned file, it will trigger maintenance-page.tpl.php.


D6 - Create a files table entry for a file

It's just done manually, e.g.:

$file = new stdClass();
$file->filename = 'foo.bar';
$file->filepath = $file;
$file->filemime = file_get_mimetype($file->filename);
$file->uid = $user->uid;
$file->status = FILE_STATUS_TEMPORARY;
$file->timestamp = time();
drupal_write_record('files', $file);

See file_save_upload() for a much broader example, including validation.


Send a regular reminder (or do other normally cron-dependent tasks) while in maintenance mode

I, personally, can think of a hamfisted, hacky way do do this, but I would prefer for someone else to provide a more elegant solution.

My web host doesn't allow SSH, but does have a "tasks" feature that essentially pulls a designated website URL at regular intervals; I'm currently using it to run Cron externally and get around Drupal 7's default Poormanscron implementation.

So I could bootstrap Drupal from a custom script and have it get pulled as an hourly task. It would variable_get('site_offline') and do nothing (or maybe redirect to index.php in case a 'bot discovers it) if false and invoke the Rule that sends the reminder e-mail if true.

Heck, if Rules or Drupal's e-mail abilities are also disabled while in maintenance mode, I can just generate the e-mail with straight PHP.


You have two options in the settings file that should allow you to configure the session timeout however you wish, session.gc_maxlifetime & session.cookie_lifetime.

/**
 * Set session lifetime (in seconds), i.e. the time from the user's last visit
 * to the active session may be deleted by the session garbage collector. When
 * a session is deleted, authenticated users are logged out, and the contents
 * of the user's $_SESSION variable is discarded.
 */
ini_set('session.gc_maxlifetime', 200000);

 /**
  * Set session cookie lifetime (in seconds), i.e. the time from the session is
  * created to the cookie expires, i.e. when the browser is expected to discard
  * the cookie. The value 0 means "until the browser is closed".
  */
ini_set('session.cookie_lifetime', 2000000);


One content type two different node--MYCONTENTTYPE.tpl.php for content style

I think the best way is to change this by clicking the title field in the views page and using the "Trim this field to a maximum length" option under "Rewrite results". You can set it to 60 for the first view and 100 for the other.


Not really a Drupal specific question, but use CSS image replacement. I personally use the Phark revisited method, because you don't need any additional markup and you use only three or four rules to make it work (in some cases you don't need to use width).


How to Sum up 2 fields of integer, and present as "Time period"?

One way to do this is the Computed Field module, which will allow you to use PHP to perform calculations.

To use this, you could add a field, Total time, of type Computed Field.  Then you could write some PHP code to calculate the value for Total time based on the other two fields.  This way, every time the node is updated, the correct calculation value will be saved in the Total Time field.

If you need to customize the display output, the Computed Field module allows you to optionally add PHP code to output the field for display with custom formatting as well.

But

Please note the warning on the module's page:

  This module is intended to be used by PHP developers to insert &
  execute PHP code on a Drupal website. It does not provide a macro
  interface, a code builder or anything other than insert your working
  code here into this text area. You need to have a good working
  knowledge of PHP and the Drupal API to use this module. To get the
  best results with this module, pre-test your PHP code in the Body
  field of a Page in Drupal.


What is the equivalent of sess_count in Drupal 7

drupal_session_count() was removed from Drupal 7. I'm not sure what an equivalent would be other than writing your own function.

Looks like the user block has it's own query. And admin menu had to replace it too.


Why are these filters producing different results?

I actually figured it out - as it turned out, I missed a small but important detail. The original (local) filter included a relationship to a content type within the view, which was providing the correct results. When I went back to edit it, I'd noticed that when I created the contextual filter, I hadn't provided the relationship to the filter. Upon adding the relationship, everything worked out the way I'd intended - getting all the expected results. I still don't know why I was getting that unexpected behavior, though.


OG: Only allow certain Drupal roles to join a group

I don't think that functionality is packaged with OG on its own.

Are you looking to map certain Drupal roles to certain groups or only have the ability to apply to a group available to certain roles?

I would think this hook is a place to start:
http://www.drupalcontrib.org/api/drupal/contributions%21og%21og.api.php/function/hook_og_permission/7

But here is a list of all hooks you can use with OG:
http://www.drupalcontrib.org/api/drupal/contributions!og!og.api.php/7


Override user/%user page callback for a role

The approach that you took is fine. It's one of the ways that you can control which page you have to show depending on (this case) the role.

Tip: take in consideration if "client" is going to be always the role allowed to see that page. If that could change in the future (add more roles or change to other), try to make it configurable.


Setting Drupal Image Field via Services, and image won't attach to node?

I'm late to the party, but I think you might be encoding the image wrongly. You need base64 encoding. Here is how encoding works on my end with Python 3.5.2:

import os, base64
size = os.path.getsize(filename)
filesize = os.stat(filename).st_size
filemime = mimetypes.guess_type(filename)
fd = open(filename, 'rb')
image_data = base64.b64encode(fd.read())
fd.close()


Drupal 8 override administration theme node form css

If you only has to add some custom css form alteration will does it.

If you also have to make some changes in field templates, or some theme function alteration, I suggest you to create your custom theme, and add Seven as a base theme


Why wouldn't hook_form_submit be called?

The form should be:

   function  mymod_reviewer_node_form($form_state) {
     $form = array();

     // Build the form...

     return $form;
   }

The submit handler should be:

   function mymod_reviewer_node_form_submit($form, &$form_state) {
     // Do something with $form_state['values'] or whatever
   }

And make sure that whatever is rendering the form passes through drupal_get_form().

Finally, one tricky bit: Make sure you are not accidentally overriding a hook. mymod_form(), for example, implements hook_form(), which is probably not what you really intend to do.

I find that nine times out of ten, if the submit handler is not being called, it's because I named the function incorrectly.


How to access backbone model from custom javascript outside of view

After some debugging I have found I can access drupalSettings object and It has a property addToCart with all the data I need.


For an import of that size you will need to run the import in the background and in steps.

This will use cron to run the feeds cron job. Drupal uses a poor-mans cron so it would be best to setup a cron on the server or use a module like Elysia cron. If you do not not you could try something link https://www.pingdom.com (you can use a free account) to ping your site every e.g. minute to trigger the drupal corn.

I would also make sure that your server is optimal for Drupal 7 and just for the import consider increasing php memory limit and execution timeout value.

Nevertheless I would recommend using a more generic module like "Migrate", though it needs some more work to be done.

I personally imported 23K user profiles into Drupal a few months ago, so it is possible.


Using views, how to render a block of father terms with a brief shortlist of child terms?

If you didn't find better solution you may create one view that will display parent term name and parent tid and second view that will display four children with a contextual filter by parent tid. And using template_preprocess_views_view_field insert view with terms children in the view with parents.

/**
 * Implements hook_preprocess_views_view_field().
 */
 function mymodule_preprocess_views_view_field(&$vars) {
   switch ($vars['view']->name) {
     case 'terms_parents':
       if ($vars['field']->options['id'] == 'tid') {
         $vars['output'] = views_embed_view('children_view', 'display', array($vars['output']));
       }
       break;
   }
}


Using hook_menu to add a child to a menu item

An example child item would just fall under the parent item in the path hierarchy, no need for plid.

e.g

  $items['admin/sponsorship/child'] = array(
    'title' => 'Sponsor child',
    'description' => 'This is where all of the child sponsorship data is stored',
    'page callback' => 'mymodule_sponsor_child_page',
    'access arguments' => array('access sponsorship section'),
    'type' => MENU_NORMAL_ITEM
  );

system_menu has some good examples of menu item containers, using system_admin_menu_block_page,  e.g admin/appearance/*

Make sure you clear menu cache to get any new menu item to show up there.


I had faced this problem a while ago. After lot of research, I found that running
composer install from the site root resolves any problem.


How to extend entityreference field by another custom field?

Gave an approach here https://www.drupal.org/node/2001822#comment-9165509

Hope that it will work for you


How do I add authentication to a POST request on an implementation of hook_menu?

Turns out this is actually really easy.

You can get the current user's roles with:

global $user;
$roles = $user->roles;

That returns an associative array with the roles as values. Getting the values is trivial with in_array():

if (in_array("Teacher", $user->roles)) {
  // allow the post request to have effect
}
else {
  // don't go through with the request; return an error
}

Because the module is called during the lifecycle of the Drupal structure, you have access to the whole environment.


How do you add a custom field to a menu link in Drupal 7?

Menu icons should do what you're after.

This module allows you to upload an image in the menu-item's configuration form.
After uploading the image, the icon data will be added to the menu link's
options array.


Unable to add Quantity in Stock in Drupal Commerce 8 using Commerce Stock Module

You need to configure the Stock Services found at /admin/commerce/config/stock/settings and choose Local Stock for your product variation.

Related topic can be found here.

EDIT: reading your question again and it seems that you added the field to the product itself, instead of adding it to the product variation. Stock field needs to be attached to the stock variation entity.


How do I hide the body field in a node using hide()?

You're rendering the wrong thing: you need to render $content:

hide($content['body']);
print render($content);

See core's implementation of node.tpl.php for more information.


Theme hook suggestions for the breadcrumb block

You should copy theme_breadcrumb to your theme's template.php file:

function YOURTHEME_breadcrumb($variables) {
  $breadcrumb = $variables['breadcrumb'];
  if (!empty($breadcrumb)) {
      $crumbs = '
';
      foreach($breadcrumb as $value) {
           $crumbs .= '
'.$value.'
';
      }
      $crumbs .= '
';
    }
      return $crumbs;
  }

By this function you can set up a ui li structure.


Using hook_entity_base_field_info for adding new field

As said in the other answer, the entity storage internally handles the schema.

Here is an explanation for it, taken from the documentation

  If your field doesn't have any special requirements Entity Field API
  can take care of the database storage and update the database schemas
  accordingly. This is the default for fields that are not marked as
  being a computed field (setComputed(TRUE)), or has specifically
  indicated to provide its own field storage (setCustomStorage(TRUE)).

Say you want to add a new base field to all Node entities that contains a simple boolean value to indicate whether the content is "highlighted".

<?php
/**
 * Implements hook_entity_base_field_info().
 */
function MYMODULE_entity_base_field_info(EntityTypeInterface $entity_type) {
  $fields = array();

  // Add a 'Highlight' base field to all node types.
  if ($entity_type->id() === 'node') {
    $fields['highlight'] = BaseFieldDefinition::create('boolean')
      ->setLabel(t('Highlight'))
      ->setDescription(t('Whether or not the node is highlighted.'))
      ->setRevisionable(TRUE)
      ->setTranslatable(TRUE)
      ->setDisplayOptions('form', array(
        'type' => 'boolean_checkbox',
        'settings' => array(
          'display_label' => TRUE,
        ),
      ))
      ->setDisplayConfigurable('form', TRUE);
  }

  return $fields;
}
?>

Now all it takes is to visit update.php to run the database updates,
   and an additional 'highlight' column will be added to the tables
   holding the node data.

To run this database update automatically when your custom module is
   enabled or disabled, you can trigger it by executing the event
   listeners that are responsible for performing these updates in your
   hook_install() and hook_uninstall() implementations:

<?php
/**
 * Implements hook_install().
 */
function MYMODULE_install() {
  // Create field storage for the 'Highlight' base field.
  $entity_manager = \Drupal::entityManager();
  $definition = $entity_manager->getFieldStorageDefinitions('node')['highlight'];
  $entity_manager->onFieldStorageDefinitionCreate($definition);
}

/**
 * Implements hook_uninstall().
 */
function MYMODULE_uninstall() {
  $entity_manager = \Drupal::entityManager();
  $definition = $entity_manager->getLastInstalledFieldStorageDefinitions('node')['highlight'];
  $entity_manager->onFieldStorageDefinitionDelete($definition);
}
?>


Running functional tests on a non-English site

I think there are a few ways. The simplest might be to override the installParameters() method to specify your desired language:

protected function installParameters() {
  // This will come back with the langcode set to `en`.
  $parameters = parent::installParameters();

  // Update to desired langcode:
  $parameters['parameters']['langcode'] = 'es';

  return $parameters;
}

I didn't find any tests in core that did it this way, but there are a few that change it during setup via the UI. (This example from LanguagePathMonolingualTest)

// Make French the default language.
$edit = [
  'site_default_language' => 'fr',
];
$this->drupalPostForm('admin/config/regional/language', $edit, t('Save configuration'));


For utilizing browser history and reload buttons with AJAX request, you can use the jquery plugin "jQuery Address"
http://www.asual.com/jquery/address/


Can you tell which page you're on of a DB API pager?

Instead of access $_GET directly, you should use pager_find_page().


Taxonomy filter. List terms with ajax checkbox selection

Use combination of next modules:

Better Exposed Filters - module replaces the Views' default single- or multi-select boxes with radio buttons or checkboxes, respectively.
Views Filters Auto-submit (views_filters_autosubmit) - auto-submits exposed filters on change.


How to drupal_add_js an external and defer script

Just add a value in $options

$options = array(
  'type' => 'external',
  'defer' => TRUE,
);
drupal_add_js('http://example.com/whatever.js', $options);

From the documentation:

  Parameters

  $options: (optional) A string defining the type of JavaScript that is being added in the $data parameter ('file'/'setting'/'inline'/'external'), or an associative array. JavaScript settings should always pass the string 'setting' only. Other types can have the following elements in the array:

  type: The type of JavaScript that is to be added to the page. Allowed values are 'file', 'inline', 'external' or 'setting'. Defaults to 'file'.
  ...
  defer: If set to TRUE, the defer attribute is set on the  tag. Defaults to FALSE.


Use the #method parameter of the form like this:

<?php
  $form['#method'] = 'get';
?>


How to allow users to edit the profile of users in the same department?

In Drupal 7 if you want to change the access check for any path you need to use hook_menu_alter.

After you change the access callback you can write your own code which does the check you want.

You just need to be careful so you don't override access callback with a bad check.

What I suggest here is to keep the original function which does the access callback user_edit_access check in your custom callback function.

I wrote sample code which gives you an idea which direction to go:

/**
 * Implements hook_permission().
 */
function example_permission() {
  return array(
    'edit own department users' => array(
      'title' => t('Edit own department users'),
      'description' => t('Allowed department manager to edit own department users.'),
    ),
  );
}

/**
 * Implements hook_menu_alter().
 */
function example_menu_alter(&$items) {
  $items['user/%user/edit']['access callback'] = 'example_custom_user_edit_access';
}

/**
 * Custom access callback for user account editing.
 */
function example_custom_user_edit_access($account) {
  if (user_access('edit own department users')) {
    // We perform our check only for user with edit own department permissions.
    global $user;

    // Load user ( Department manager) via entity api.
    $user_wrapper = entity_metadata_wrapper('user', $user);

    // Get array of managed department terms id.
    $user_departments = $user_wrapper->field_user_department_managed->value();

    // Load user (Editor) via entity api.
    $account_wrapper = entity_metadata_wrapper('user', $account);
    // Get array of department belongs to terms id.
    $account_departments = $account_wrapper->field_user_department_belongs->value();

    // Check any common term id.
    $common_departments = array_intersect($user_departments, $account_departments);

    return !empty($common_departments);
  }
  // For other user we perform default check.
  return user_edit_access($account);
}


How do I format a date value for a 3-column date drop-down widget?

The Form API documentation will help you figure this out, you'll have to pass an array with the year, month and day keys like this:

$form['date'] = array(
    '#title' => t('Date'),
    '#type' => 'date',
    '#default_value' => array('year' => 2013, 'month' => 4, 'day' => 23),
);


Adding a dropdown list to the Registration Form. Drupal 7

You can do this via the UI by going to (admin/config/people/accounts/fields) and then adding your new field.  There is no limit to how many fields you can have.


Node Gallery not using administration theme for its custom tabs

Generally, to declare a path as an admin path (and thus one that would open in the overlay/use the admin theme, etc.) you need to declare them using hook_admin_paths.

If this is the issue (I don't know Node Gallery, so I can't be more precise) the best would be to implement hook_admin_paths in the Node Gallery module and submit the patch on the Node Gallery issue queue.


"Allow multiple selection" not available in exposed filters

You can go for Better Exposed Filters module.

  The Better Exposed Filters module replaces the Views' default single-
  or multi-select boxes with radio buttons or checkboxes, respectively.
  Description fields and Select All/None links can be added to exposed
  filters to make for a better user experience.


Creating a route with a form and some content

As doc states

  defaults (required): Defines the default properties of a route.
  Provide one of the following to specify how the output is generated:

  _controller
  _form
  _entity_view
  _entity_list
  _entity_form
  _route

you can't list a _form and a _controller in the same routing.yml entry, only one of those keys is allowed. Either append that content via form API to your form, or render the form manually in your controller.


How can I add template suggestions by UUID?

You should add a hook in your template.php, like this:
function MYTHEME_preprocess_node(&$vars) {
  if ($vars['node']->uuid == '12345') {
    $vars['theme_hook_suggestions'][] = 'my-best-tpl';
  }
}


Display alternate content after webform submission

You'll notice that for anonymous visitors, webform does store a cookie so that it knows if you've submitted a particular form (assuming a default webform configuration). So in theory, you could hook into that with some custom code to display and/or hide content.


How do I set the custom upload directory for a plupload from field?

I eventualy found the solution in the plupload.module file itself. In there there is a page that can be found on folowing url: /plupload-test.

The form has a submit callback function:

/**
 * Submit callback for plupload_test form.
 */
function plupload_test_submit($form, &$form_state) {
  $saved_files = array();
  $scheme = variable_get('file_default_scheme', 'public') . '://';
  // We can't use file_save_upload() because of
  // http://www.jacobsingh.name/content/tight-coupling-no-not
  // file_uri_to_object();
  foreach ($form_state['values']['pud'] as $uploaded_file) {
    if ($uploaded_file['status'] == 'done') {
      $source = $uploaded_file['tmppath'];
      $destination = file_stream_wrapper_uri_normalize($scheme . $uploaded_file['name']);
      // Rename it to its original name, and put it in its final home.
      // Note - not using file_move here because if we call file_get_mime
      // (in file_uri_to_object) while it has a .tmp extension, it horks.
      $destination = file_unmanaged_move($source, $destination, FILE_EXISTS_RENAME);
      $file = plupload_file_uri_to_object($destination);
      file_save($file);
      $saved_files[] = $file;
    }
    else {
      // @todo: move this to element validate or something and clean up t().
      form_set_error('pud', "Upload of {$uploaded_file['name']} failed");
    }
  }
}

I ended up using the same function in my custom module but adding my custom directory to the $destination the function now looks like this:

function plupload_files_submit($form, &$form_state) {
  $saved_files = array(); //Array to capture file objects
  $scheme = variable_get('file_default_scheme', 'public') . '://';
  $directoryname = 'imagebank'; // Directory where images are collected
  $imagebankpath = $scheme . $directoryname;
  file_prepare_directory($imagebankpath, FILE_CREATE_DIRECTORY); // Create the folder if it doesn't exist
  // We can't use file_save_upload() because of
  // http://www.jacobsingh.name/content/tight-coupling-no-not
  // file_uri_to_object();
  foreach ($form_state['values']['uploadfiles'] as $uploaded_file) {
    if ($uploaded_file['status'] == 'done') {
      $source = $uploaded_file['tmppath'];
      $destination = file_stream_wrapper_uri_normalize($imagebankpath .'/'. $uploaded_file['name']);
      // Rename it to its original name, and put it in its final home.
      // Note - not using file_move here because if we call file_get_mime
      // (in file_uri_to_object) while it has a .tmp extension, it horks.
      $destination = file_unmanaged_move($source, $destination, FILE_EXISTS_RENAME);
      $file = plupload_file_uri_to_object($destination);
      file_save($file);
      $saved_files[] = $file;
    }
    else {
      form_set_error('uploadfiles', "Upload of {$uploaded_file['name']} failed");
    }
  }


Docker website running locally not loading CSS

You forgot to link the db container. Look at the quickstart here https://hub.docker.com/r/feikede/drupal8-docker/ and take care for the "--link" to your database container.


how can I use special Font awesome character in Twig link()?

The point of the FontAwesome selectors is that you do not need to print out the Unicode equivalent for the character. FontAwesome usually works by adding a pseudo element before or after the HTML element using the class.

In this case, use the fa fa-envelope classes and optionally add in a class to hide the text with a text-indent or something.

{{ link('Contact Us', 'base:contact', { 'class':['fa', 'fa-envelope', 'fa-lg', 'contact-us-link'] }) }}


Create nodes from a JSON file uploaded in a form by an user

Ok I made it works, first I get the file's path using the solution given here
and then once I got the path, I'm reading the file using
$file = file_get_contents($file_path);

then calling my function createActualite($file); and it creates all the nodes up to the content of the JSON as expected.


Is Drupal 4.7 compatible with Mysql 5.1 and PHP 5.3

I think that both may be an issue. PHP definitely is. I'm not sure about Mysql.

Drupal 4.7 is quite a few versions out of date and it is no longer being maintained. You really should be looking to use a more recent version.


How do I return a number in render arrays?

There is a mismatch in hook_theme(), template is "test", elsewhere "my_module_test". And the return array has three levels, with the keys variables and template in the second level and the twig parameters in the third:

  return [
    'loremipsum' => [
      'variables' => [
        'source_text' => NULL,
      ],
      'template' => 'loremipsum',
    ],
  ];


Here are the steps you need to allow only the node author to rate the node.

For the Task content type, change the role permissions so that only the authenticated users (or whichever role you want to allow to complete and rate Tasks) have the "Edit own content" permission.
Under "Manage Fields" for the Task content-type, configure your rating/fivestar field to use the widget "Stars (rated while editing)". Now, only the node's autor can edit and rate a Task node. The vote will still be visible to other users.

Hope this helps!


How can I update file attachment and keep filename?

It is not possible. If files were deleted "in real time", node your readers see would have a link and reference to a file no longer on server's hdd.

If you need to get the same file name, remove file, save node, upload new version, save node. That way you will avoid both broken links and name conflicts.


How do I restrict access to the install.php file

In apache vhost:

RedirectMatch 403     "/(install|update).php"

Or in htaccess change the part on top:

# Protect files and directories from prying eyes.
<FilesMatch "\.(engine|inc|info|install|make|module|profile|test|po|sh|.*sql|theme|twig|tpl(\.php)?|xtmpl|yml)(~|\.sw[op]|\.bak|\.orig|\.save)?$|^(\.(?!well-known).*|Entries.*|Repository|Root|Tag|Template|composer\.(json|lock)|web\.config)$|cron\.php|install\.php|update\.php|^(CHANGELOG|COPYRIGHT|INSTALL.*|LICENSE|MAINTAINERS|README|UPDATE).txt$|^#.*#$|\.php(~|\.sw[op]|\.bak|\.orig|\.save)$">

Please note this htaccess also protects access to cron.php, update.php, web.config and txt files like /core/CHANGELOG.txt


How to set one of the fields displayed in the view to be a link to a webform submission?

This is an old post, so I expect you found your answer already.  You need to have the post's id number.  Try adding that field to the set, but excluding it from view.  Also, rearrange fields so it is earlier in the list than the field you are turning into the link.  You should then be able to use replacement tokens to make the path entry look something like:

/drool_calendar/node/[content:nid]/submission/[content:subid]

Starting the path with a / tells Drupal that you want this to stem from the site base url; discarding the leading slash tells Drupal you want this link to stem from the current page.


From the above code replace:

use Drupal\block\BlockBase;

with:

use Drupal\Core\Block\BlockBase;

Then Flush cache and check.
Go to Structure, BlockLayout and click on Place block.


How to relate the user table with the fboauth table to show up who's logged in through fb?

You have two options.

First is that you can add a field to the USER, named as fb_user(Keep the default value as "no"). Now look into the fbouth code where a user is being created. Write a sql query there using Database API to update the field fb_user as "yes". Now you can easily add the field in views to find out FB users.
Create a custom module. Inside that write a hooks_views_query_alter:-https://api.drupal.org/api/views/views.api.php/function/hook_views_query_alter/7
Custom query in Views?


How to display custom block without default wrapped html around

I don't actually think this is possible using a block; however, take a look at hook_block_view() and hook_block_view_alter().

Those MAY do what you want.  They allow you to alter the contents of a block before it is displayed; however, it is likely that you'll still end up with the contents of the block 'inside' the template's block boiler plate.

Keep in mind that it's up to the theme to decide how blocks are styled so the theme markup boilerplate is there by design.

If you need to inject html into specific areas of the site / page you might need to do something differently.

In that case hook_page_build() or hook_page_alter() might be a better choice.


taxonomy tokens throwing invalid token error

Look at http://drupalcontrib.org/api/drupal/contributions!token!token.module/function/token_element_validate/7. Implement hook_form_alter() of form you are trying to submit and look for #element_validate array key, in field you get an error should be

  '#element_validate' => array('token_element_validate'),

Then you should check  #token_types key value. It can have any value, as examples:

 '#token_types' => array('node'),

OR

 '#token_types' => array('all'),

In my case I got similar error in metatag_context module when I was trying to save taxonomy token into metatags context field. Problem was in '#token_types', they was empty, I added array('all') value and form works fine.


notify after event in followed node by follower

If i understand you right, you want to do something after a user was flagged...

The flag module has a full Rules module integration.
This module gives you the ability to react to specific events (like flagging a user) and do actions like showing a message, sending a email, or execute some custom php-code.


Is there a standard Drupal way to link to 3rd party configuration forms?

For instance is there a Drupal function that takes the menu path (eg.
  'admin/config/system/cron') and provides an actual URL?

Definitely!

print l(t('Cron configuration'), 'admin/config/system/cron');

Will print an a tag as follows:

Cron configuration

to the configuration with paths resolved correctly (works well when you have installed Drupal in a sub folder as well - just use the Drupal path).

If you are putting your own text, most likely that you are using t() function.
Example:

$form['warning']['#makup'] = t('You need to make sure that you have setup a working !cron',
  array('!cron' => l(t('Cron configuration'), 'admin/config/system/cron')));

l()  -  Generates the anchor link (text)

url() -  Returns URL for a given Drupal path (l() calls this function to get the correct link)

See function reference for more configuration (absolute URLs, prevent using aliased path, etc)


Instead of "Hello World", use t("Hello World").

Using the Localization client module, you can add the translation of that string in any language you want.

  This module helps you fix translations on your site as you see the issues. Just by navigating around your pages, you'll be able to fix translations and fill in missing ones using the on-page translation editor. At the same time, if configured properly, the module also submits your translations back to the community, to localize.drupal.org or any other localization server.


Is there a postcode for deliveries checker module for drupal 7?

There's no single module for this, but you can use a suite of modules.  For example, you can take addresses stored in the Address Field module and then use Geocoder to geocode them and save the results in a Geofield.  You can then use Rules to check the distance.

That said, there is no simple way to do this.  In fact, there's an entire book about Mapping with Drupal.


How to edit comment reply link for specific content type in Drupal 7

You can try to use preprocess comment function:

function MYTHEME_preprocess_comment(&$vars) {
  unset($vars['content']['links']['comment']['#links']['comment-reply']);
}

Also check https://www.drupal.org/node/319298


A general reason is that contributed modules or theme code can hook in and add attributes in. Outputting {{ attributes }} ensures that they are all printed without hardcoding them all in templates.

Here is an example.

I want to add a class and data-attr to an input field on a particular form. Instead of hardcoding it, I add to the #attributes key, and they are rendered out for me since {{ attributes }} is printed on the element:

/**
 * @param $form
 * @param \Drupal\Core\Form\FormStateInterface $form_state
 * @param $form_id
 */
function mytheme_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  if ($form['#id'] == 'views-exposed-form-search-results') {
    $form['actions']['submit']['#attributes']['data-twig-suggestion'] = 'search_results_submit';
    $form['actions']['submit']['#attributes']['class'][] = 'search-box__button';
  }
}

My class and data-attr are added to that element automatically. I don't need to know what twig file is rendering it, I just need to provide the attributes I want to add on to, or print out.

Here are some links that explain a bit more in depth what Attributes are:

https://api.drupal.org/api/drupal/core!lib!Drupal!Core!Template!Attribute.php/class/Attribute/8.2.x
https://www.drupal.org/docs/8/theming-drupal-8/modifying-attributes-in-a-theme-file

I heard that in 8.3.x it will be easier to work with attributes, but I can't find the thread offhand.


extend $.fn or Drupal.ajax.prototype.commands for calling javascript after ajax callbacks

Extending Drupal.ajax.prototype is the way Drupal and almost every contrib handles this.

is there a preferred method or is this just a matter of style?
are there differences in the benefits of each approach?

The preferred method would be the latter. However, note that both methods are not the same. Ajax commands are passed through ajax_render() function, which allows modules to alter the ajax commands by implementing hook_ajax_render_alter(&$commands). If you use the former method, you will see the invoke as the command, which makes it difficult to figure out the exact invoke command.
For Javascript eyes, it's just a matter of $.fn (shorthand for jQuery.prototype) vs Drupal.ajax.prototype.


How do I get rid of the Search at the top of the search results page?

I suggest way three way

Hide it with css ( set it to display:none)
Remove it with simple Jquery command  ( .remove)
override  search result page template

I mean duplicate page.tpl.php file in your custom theme set name to page--search.tpl.php and remove
<?php print $title; ?>
. finally don't forget clear the cache

If this TPL doesn't work then you have to declare it in template.php using theme_hook_suggestions in the same way as answer of your linked question. See for the URL which your instance is using for giving search result.

For $base_url/search use

//replace your theme name with MYTHEME
function MYTHEME_preprocess_page(&$vars) {
  if (arg(0)=='search') {
    $vars['theme_hook_suggestions'][] = 'page__search';
  }
}

Add this in your template.php & as you are suggesting TPL for page, you have to use THEME_preprocess_page($vars).


One way to accomplish this is to use Strongarm to set the admin theme variable as part of a Feature.

Given that the "Standard" Drupal installation profile creates a lot of other stuff that won't be in a custom installation profile -- Basic Page and Article content types, for instance -- I've created a Feature with all those and added the Admin Theme Strongarm variable as part of that.

That said, leaving question open in case somebody knows how to set the Admin theme as part of a Profiler makefile.