Why does dpm() sometimes fail and krumo() works

typically inline php code such as a views php field value, or a Display Suite code field for example ... doesn't always run in a page's context.

When you have a field expecting <?php  /* some code here */ ?> this is run an Anonymous php function and returns a value.

In my experience dpm() doesnt always work in these cases.

Another example is trying to dpm within a Cron or Queue task. These dont run in a page context either so using something like Devel's dd function can be useful.


How to create file repository from which I can link files to other content types?

As said in the comments:

Media module is just the thing you are looking for. We are also using it in our project, it's pretty good and solves all the problems you listed.

It's maybe also important to mention that this is going to be part of the core very soon (8.4.x).


You probably need to manage permissions in the following area,

Goto Structure->Menus->Management
Under Administration->Configuration->b_creation
Click Edit link
At the bottom check the roles you need to grant access and Save

But make sure this has security issues, give the permissions to trusted users only.


The groups audience field is an entity reference field, which includes a setting to filter the groups using a view.
So first create a view that lists the logged in users groups, and use that in the groups audience field setting.


Ahhhh!

Just as I posted this I discovered that my $header was malformed!!

$header = array('date', 'name', 'email', 'location', 'time');

should have been

$header = array('date' => 'Date', 'name' => 'Name', 'email' => 'Email', 'location' => 'Location', 'time' => 'Time');

Phew!


Why is my site which resides in a subfolder broken when visiting it through a subdomain URL?

From your description it looks like you need to

add your subdomain to proper site folder. Check your sites.php to be correct, for example-

Check your settings.php to allow your sub-domain as per the documentation-

Check if image urls are hard coded

Cache or CDN plugin are affecting it.

Adding the type of error you are getting could let us help you better.


Receive link from row in views-template file

Have you try the option in the field to "Reqrite the output" ?

First of all, you select "Exclude from display" in the fields you want to group together, then in the last field you rewrite its output using patterns. This allow you to put HTML or text before your fields for example something like this:

Address
City: [field_city_value]

Country: [field_country_value]

Then you also have the option to "Output this field as a link" which allows you to give your group of field a link. This option also provides a way to rewrite the link with patterns.


Custom module integration with Views3 for D7?

Have you tried clearing the cache?

The error is there because some module, expects that there is such a file and tries to include it. It could be a direct result of whatever views integration you are doing.

The error will go away if the file exists, an empty file with <?php is enough.


Getting the pretty value of a Select field in Node twig template

When I call just this :

content.field_*machine_name*

  It display the pretty value but wrapped in a div that I don't want.

This is the correct way, you should if possible render a field in node twigs like this.

The div, that you don't want, is probably in the field twig, that gets invoked by using {{ content.field_*machine_name* }}.

You have to put a copy of field.html.twig in your theme and name it:

field--field_*machine_name*.html.twig

And look there for the div.


My administration menu dissapears when installing a module

The reason in my case was the character encoding of the "mymodule.module" file.
Changing it back from "UTF-8" to "ANSI" solved the problem.


Search API: getAutocompleteSuggestions in D8?

I've solved it with Solarium

//...
use Solarium\Client;
//...

// $value is the search value from the textfield.
if (!empty($value)) {
    $searchAPIconfig = \Drupal::config('search_api.server.server');
    $searchAPIconfigData = $searchAPIconfig->getRawData();

    $config = array(
    'endpoint' => array(
      'localhost' => array(
        'host' => $searchAPIconfigData['backend_config']['host'],
        'port' => $searchAPIconfigData['backend_config']['port'],
        'path' => $searchAPIconfigData['backend_config']['path'],
      ),
    ),
    );

    $client = new Client($config);

    if ($client !== NULL) {
        $query = $client->createSuggester();
        $query->setQuery($value);
        $query->setDictionary('mySuggester');
        $query->setOnlyMorePopular(TRUE);
        $query->setCount(10);
        $query->setCollate(TRUE);

        $resultset = $client->suggester($query)->getData();
        $results = $resultset['suggest']['mySuggester'][$value]['suggestions'];
        $suggestions = array();
        foreach ($results as $key => $termResult) {
          $suggestions[] = $termResult['term'];
        }

        //...
    }
}


Divide a webfrom textfield component into a specific input format

You can use jQuery masked input plugin to mask the field input.
If you really want to have 3 separate fields, you can do that with JS again. Have one field (let's call it "main" field) where you will save the value and generate the other 3 on the fly. Hide main field and on change update the value by adding the values of those three fields.


Drupal SA-CORE-2014-005 - How to tell if my server / sites were compromised?

If you're reading this article and hoping to check a Drupal 7 site more than a month after the exploit landed, your site quite likely already got hacked. Your best bet is to restore a backup from before the attacks commenced and work from there.

There is a FAQ on SA-CORE-2014-005.

  How do I tell if my sites have been compromised?

One way to quickly check if sites are compromised is with the Drupalgeddon drush command.

https://www.drupal.org/project/drupalgeddon

Install to your ~/.drush with drush dl drupalgeddon

Then use drush drupalgeddon-test to test. Drush aliases make this easy and quick.

This tool can confirm an exploited site, but it cannot guarantee your site did not get exploited. There is no "clean bill of health" here unless you upgraded before the attacks started.

Site Audit module includes some of the checks from Drupalgeddon, and gives you a lot more useful input too. I highly recommend it. (EDIT: Now they work together - super nice!)

http://drupal.org/project/site_audit

Security Review doesn't check for Drupalgeddon attacks but is worth having in your toolbelt too.

http://drupal.org/project/security_review

If your site codebase was writeable to the www user , you could additionally check for modified code using the hacked module. This module may not do what you think based on its name alone :)

http://drupal.org/project/hacked

While there is no single certain way to identify all compromised sites, these tools can help you identify the most common indications.

  What should I search for in my apache access logs to detect if my site was a victim or not?

Your access logs will contain a lot of POST requests by now. Unless you had taken the unusual step of logging all post data in advance of the bug, you're unlikely to have the information to tell which of these were malicious.

  So far what are these hackers doing to compromised sites?

Many are reporting that their sites are being patched by the hackers! As an attacker, this makes good sense - you don't want your newly hijacked site whipped out from underneath you by the next attacker :)

Other than that, I'd guess the sites are being used to harvest whatever valuable data is there (maybe grab some creds, maybe lift transaction details after exploiting) and to do boring things like send spam and work as humble botnet slaves. Oh, and further expand the attacker's empire of hijacked Drupal sites. (Sorry, I don't have any hacked sites to observe.)


Is it possible to subscribe to a newsletter without first having to register?

It is supposed to be possible, but the anonymous user is still required to confirm their email address. Check this issue in the Simplenews issue queue.


Is it possible to force redirection from PayPal to the website after successful payment?

The answer is unfortunately no.

PayPal will always display this as an option to the client, so you can't force the redirection back after the payment has been completed.


This has been coming to Calendar for a while now, and I believe is currently in dev (issue queue). Having said that, I notice that fullcalendar has 666 sites using it, so it might be good to increase that number and make it less devilish :)


How to move fields into secondary region where Menu Settings are located?

This can be done in two ways:

1) Use the Field group module.

Field Group has added the ability to move items to the right sidebar on the node edit form, via the "Details sidebar" group type in the dropdown.

2) Write a hook_form_alter() in a custom module.

If you have more complicated needs than what Field Group provides you can do this in custom code.

/**
 * Implements hook_form_alter().
 */
function mymodule_form_alter(&$form, &$form_state, $form_id) {
  // Select the desired entity add/edit form.
  if (is_array($form['#theme']) && in_array('node_form', $form['#theme'])) {

    // Ex 1. Move an existing field container wrapper to the sidebar.
    if (!empty($form['field_myfield']) && $form['field_myfield']['#type'] == 'container') {
      $form['field_myfield']['#type'] = 'details';
      $form['field_myfield']['#group'] = 'advanced';
    }

    // Ex 2. Move an existing field to the expanded 'meta' section of the sidebar.
    if (!empty($form['field_myfield'])) {
      $form['field_myfield']['#group'] = 'meta';
    }

    // Ex 3. Move a field group provided by some contrib module to the sidebar.
    $form['somecontrib']['widget'][0]['#group'] = 'advanced';
    $form['somecontrib']['widget'][0]['#open'] = FALSE;

    // Ex 4. Create a custom collapsible container in the sidebar.
    $form['mycontainer'] = [
      '#type' => 'details',
      '#group' => 'advanced', // This line places the container in the sidebar
      '#weight' => 99,  // ensure it displays last or use -10 to show it first.
      '#title' => t('My custom sidebar settings'),
      '#tree' => TRUE,
      '#access' => TRUE,
    ];

    // Ex 4.1 Move a field into the custom container in the sidebar.
    if (!empty($form['field_myfield'])) {
      $form['field_myfield']['#weight'] = -1; // reset weight
      $form['field_myfield']['#group'] = 'mycontainer';
    }

    // Ex 4.2 Some fields have an inner widget that need to be moved instead.
    if (!empty($form['field_myfield']['widget'])) {
      $form['field_myfield']['widget']['#weight'] = -1; // reset weight
      $form['field_myfield']['widget']['#group'] = 'mycontainer';
    }

  }
}


Problems with Views Load More module loading via AJAX

Your problem is the image path not the load more module.

I inspected the image in your view and found that it is being requested from this URL:
http://www.mustxhave.com/mustxhave/sites/all/themes/simpnews/images/xyz-300x500.jpg
which is wrong.

Removing musthave from the URL will fix the image path.
http://www.mustxhave.com/sites/all/themes/simpnews/images/xyz-300x500.jpg

This may be caused by one of these:

Check the view settings for the image field.
Check settings.php file for base_url variable value.
Check if have Rewrite Base in the .htaccess file.


How to stop redirecting to newest URL after updating a node

There's no easy way. You might have to make your own module with code something like this:

function mymodule_node_presave(){
  $GLOBAL['dont_redirect']=true;
}
function mymodule_drupal_goto_alter(&$path){
  if ($GLOBAL['dont_redirect']==true){
    $path = "";
  }
}


How do I get a block and its content commited to a Git repo?

Turn it into a Feature. Bad thing is, it does not work on built-in custom blocks, so you need to use Boxes to get it work.

That way, you can export block as a module, and modules are text files, so GIT accepts them with it's full support.

Then, there is Features to Git module. It claims:

  Features to Git allows trusted users to write features directly to disk, commit
  them to git and push them to a remote. This makes it possible for site
  builders to be able to manage features in git without having to get their hands
  dirty on the command line.


You can do it with CSS.

You add CSS to your theme. If you're using a theme like Zen that has SASS, you can add the new rules to your SASS file(s) and compile them to CSS. There is documentation for adding CSS to pages on Drupal.org.


Modify article body for one particular article to add data

I ended up modifying the node when cron runs.

define("JMT_CLASSES_CLASSES_ED_NODE_ID", 574);
// 60 * 60 * 8 - measured in seconds.
define("JMT_CLASSES_EIGHT_HOURS", 28800);

/**
 * Implements hook_cron().
 */
function jmt_classes_cron() {
  // Check current config for time, if greater than 8hrs check for updates.
  $timeOfLastUpdate = \Drupal::configFactory()
    ->get('jmt_classes.settings')
    ->get('last_run');
  $currentTime = \Drupal::time()
    ->getCurrentTime();
  $intervalSinceLastUpdate = $currentTime - $timeOfLastUpdate;

  if ($intervalSinceLastUpdate >= JMT_CLASSES_EIGHT_HOURS || $timeOfLastUpdate == NULL) {
    // Check for updates.
    $raw = jmt_classes_get_classes('https://example.com/Client.WebApi/api/Route?url=query/get?url=jmt');
    if ($raw) {
      $newBodyValueHtml = jmt_classes_render_html($raw);
      $classesEdNode = Node::load(JMT_CLASSES_CLASSES_ED_NODE_ID);
      jmt_classes_update_class_node($classesEdNode, $newBodyValueHtml);

      \Drupal::configFactory()->getEditable('jmt_classes.settings')
        ->set('last_run', $currentTime)
        ->save();
    }
  }
}

/**
 * Update node with new html for the body field and log that it was updated.
 *
 * @param string $node
 *   The node (output page) that should be updated with new data.
 * @param string $newBodyValueHtml
 *   The HTML to set the body to.
 */
function jmt_classes_update_class_node($node, $newBodyValueHtml) {
  $node->body->value = $newBodyValueHtml;
  $node->save();
  \Drupal::logger('jmt_classes')->notice("Successfully updated body field of articles/upcoming-education-classes-field-days");
}

/**
 * Get raw json output for JMT classes. Log error or success.
 *
 * @param string $uri
 *   JMT api uri: should be something like:
 *   'https://example.com/Client.WebApi/api/Route?url=query/get?url=jmt'.
 *
 * @return string
 *   Raw json data or empty if nothing returned from request.
 *
 * @throws \GuzzleHttp\Exception\GuzzleException
 */
function jmt_classes_get_classes($uri) {

  try {
    $response = \Drupal::httpClient()->request('GET', $uri, ['timeout' => 120]);
  }
  catch (Exception $e) {
    \Drupal::logger('jmt_classes')->error("Attempted to get data
from $uri but failed. $php_errormsg");
    return '';
  }

  $data = (string) $response->getBody();
  $data_array = json_decode($data);

  // If this isn't json data return nothing.
  if (empty($data_array)) {
    return '';
  }
  // Otherwise, return raw json data.
  else {
    \Drupal::logger('jmt_classes')->notice("Successfully got data from $uri");
    return $data;
  }
}

This has the advantage that I don't do any preprocessing. The change happens when the data changes when cron runs, not on every page load. This is important because fetching the data is SLOW!


Some forms in CiviCRM (ex: contribution/membership) may have some show/hide options, for, say, organisational memberships, but in general, it's not possible to do it using the admin interface, and doing it programmatically with jQuery is recommended.

Another option, is to use the webform and webform_civicrm Drupal modules to create a custom form. The latest version of webform_civicrm makes it possible to pretty much rewrite most of the contribution/membership forms. Webform has ways to show/hide fields conditionally.

If you want to do it the jQuery way, depending on whether it is a Drupal form (ex: user registration form), or a CiviCRM form (contribution/membership form), you can put the javascript snippet in your Drupal theme, or in a CiviCRM template.

For example, if it's a Drupal form, you can put it in the equivalent of sites/example.org/themes/mytheme/js/custom.js :

/**
 * Show/hide the appropriate custom fields for a membership level.
 */
Drupal.behaviors.myThemeToggleMembershipFields = {
  attach: function (context, settings) {
    $('#my_membership_type_input').change(function() {
      var v = $(this).val();

      if (v == 1) {
        $('..fields for type 1..').show();
        $('.. other fields..').hide();
      }
      else if (v == 2) {
        // etc.
      }
    });
  }
})(jQuery);


What should I use in Drupal 8 instead of votingapi_set_vote()?

Do you know how to set votes programmatically?

use Drupal\votingapi\Entity\Vote;

$vote = Vote::create(['type' => 'vote']); // this comes from /admin/structure/vote-types
$vote->setVotedEntityType('node'); // entity type
$vote->setVotedEntityId($nid); // node id
$vote->setValueType('points'); // this comes from /admin/structure/vote-types
$vote->setValue(1); // the number of points given per vote
$vote->setOwnerId($uid); // the user id of the person who casted the vote
$vote->setCreatedTime($timestamp) // timestamp of when vote was casted (optional)
// it will use the current time if you don't include it
$vote->save();

The above code will create 1 casted vote. Therefore, you will have to run this code for every single vote.


How to add a profile field in page--user.tpl.php

try using field_get_items()

$field_myfield = field_get_items('user', $user, 'field_myfield');
$myfield_value = field_view_value('user', $user, 'field_myfield', $field_myfield[0]);
$variables['myfield'] = render($myfield_value);

More info here and here


How to stop infinite loop on hook_node_grants

Load the node directly:

  // Do not use $node = menu_get_object();
  // This calls hook_access which results in a recursive loop
  $node_url = $_GET['q'];
  $nid = array_pop(explode('/', $node_url));
  if (!is_integer($nid)) {
    return $grants;
  }
  $node = node_load($nid);


How do I display a search result message that includes filter criteria?

I'm not sure I understand your question. You may have a look at :

Exposed Filter Data

  This module provides a themed function called get_exposed_filter_output() which print out the values of the exposed filter used in a view.

related topic in D.O : Use data from exposed filter in title or header. It will give you many ideas on how to print out the chosen exposed filters values programatically.


How can I configure drupal to share modules between two installations on the same server?

There is a great way of accomplishing this, it's called multi-site.
See http://drupal.org/documentation/install/multi-site
and http://drupal.org/node/43816 for a start.

A great project that offers multi-site hosting is Aegir. In Aegir you can even create multiple platforms that run 1 or more sites.
See http://aegirproject.org

1 thing: you can not run multiple sites from a subdirectory if you run with Aegir/Drupal, that won't work with how Drupal is designed, but if your running on some GNU/Linux, then you might be able to symlink something together.

It's true you can use the sites/all/* folders to share modules/themes/libraries, but 1 thing is missing:
In the sites/ folder, you have to create a directory, containing the config files, files directory (etc) for every individual site that you want to run.

You could also offer multiple sites from 1 directory via an alias, but that's not what your looking for now i believe, just as an extra bonus tip. ;) Hope this helps a bit.


Adding multiple buttons on node submit form - every button submits the form

If you leave $form['#submit'] unset or empty then drupal_prepare_form will try to replace it with a submit handler provided by the base form:

if (!isset($form['#submit'])) {

// Ensure that modules can rely on #submit being set.
$form['#submit'] = array(

);

// Check for a handler specific to $form_id.
if (function_exists($form_id . '_submit')) {
  $form['#submit'][] = $form_id . '_submit';
}
elseif (isset($form_state['build_info']['base_form_id']) && function_exists($form_state['build_info']['base_form_id'] . '_submit')) {
  $form['#submit'][] = $form_state['build_info']['base_form_id'] . '_submit';
}

If you're submitting a node form then $form_state['build_info']['base_form_id'] . '_submit' will be equal to node_form_submit, which is why it's being called.

In order to prevent node_form_submit from being called, you'll need to provide a $form['#submit'] handler, or define FORMID_form_submit, which takes the form NODETYPE_node_form_submit for nodes.


Using commerce module for online payment for just 4 product/services?

If all you'd do was display the rooms and manage their bookings, then I would say
Commerce was not only excessive, but perhaps even entirely wrong.

However, since you mention online payments, I think it could be a good fit, for managing of those. No other contrib module is likely to have as many "out of the box" solutions for payment today, or developed tomorrow.


You can print the user profile using:

<?php print render($user_profile); ?>.

You can get specific user information by

<?php print render($user_profile['user_picture']); ?>

<?php print render($user_profile['summary']); ?>

Hope this helps.


How do I implement a custom theme function?

From the description of valid parameters in the docs:

  function: (deprecated in Drupal 8.0.x, will be removed in Drupal 9.0.x) If specified, this will be the function name to invoke for this implementation. If neither 'template' nor 'function' are specified, a default template name will be assumed. See above for more details.

So if you must use a function, you need to be explicit:

function example_theme($existing, $type, $theme, $path) {
   return array(
    'example' => array(
      'variables' => array('items' => array()),
      'function' => 'theme_example',
    ),
  );
}

But considering that method is deprecated in favour of template files, it would be better to use one. You can do so by simply creating a template file at modules/custom/example/templates/example.html.twig


Drupal 7 : Programmatically validate form by form ID

You can add an extra validation function using hook_form_alter.

If all you need is to add a captcha to the contact form you could try simply using the captcha module, or the mollom module.

If you've created the form yourself using a form builder function, you can add a validation function (with all your validators) to that:

function YOURMODULE_YOURFORM_form_validate($form, &$form_state) {
// Your validation code.

}


Listing top level terms in views including those without children

If you add a filter to parent term = "empty (NULL)" it will display all terms that have no parent above them.

For more detailed steps, try this blog post I wrote: http://fdiv.net/2012/08/11/taxonomy-views-browser-arbitrary-depth


In 8.3 there is now an interface for this:

  Content entities that need a published/unpublished flag base field are
  now able to declare a "published" entity key in their entity type
  annotation. Such entities should implement the new
  \Drupal\Core\Entity\EntityPublishedInterface and use the
  \Drupal\Core\Entity\EntityPublishedTrait trait. The interface can be
  implemented directly, by the entity class, or by the entity
  specialised interface.

use Drupal\Core\Entity\EntityPublishedInterface;
use Drupal\Core\Entity\EntityPublishedTrait;
use ...

/**
 * @ContentEntityType(
 *   id = "custom_entity",
 *   ...
 *   entity_keys = {
 *     "id" = "id",
 *     "published" = "status",
 *     "label" = "label",
 *   },
 *   ...
 * )
 */
class CustomEntity extends ContentEntityBase implements CustomEntityInterface, EntityPublishedInterface {
  use EntityPublishedTrait;
   ...
}

  Entities defined in this way can benefit of the new provided methods
  to set the published status ON/OFF and are able to inspect the status
  of the published flag field:

$storage = \Drupal::entityTypeManager()->getStorage('custom_entity');
$entity = $storage->load(123);

// Reverse the published status.
if ($entity->isPublished()) {
  $entity->setUnpublished();
}
else {
  $entity->setPublished();
}

$entity->save()

Source: https://www.drupal.org/node/2830201

If you are developing for 8.4 you can use the base class

  EditorialContentEntityBase - a new base entity class for revisionable and publishable entity types

  Drupal 8.4.0 increases its usage of the revisioning and publishing
  features from Entity API by converting some if its most widely used
  content entity types: Taxonomy terms, Menu links, Comments, etc.

  In order to reduce code duplication and boilerplate, a new content
  entity base class is now available for entity types that want to
  support those features by default: EditorialContentEntityBase.

  If you are defining a content entity type in a contributed module or
  in your project's custom code, it is recommended to extend the
  \Drupal\Core\Entity\EditorialContentEntityBase base class in order to
  get out-of-the-box support for Entity API's revisioning and publishing
  features, which will allow your entity type to be used with Drupal's
  editorial workflow provided by the Content Moderation module.

Source: https://www.drupal.org/node/2870643


During checkout, you'll need to create a transaction because the order needs to be paid before it is actually completed. If you're needing to do other processing, you might consider looking at the architecture of Commerce License, where a license can have a post-checkout set of processes.

The short version of it looks like this:

You create the license or the "queue item" that needs to process.
Redirect to the completion page.
Have an AJAX watcher that looks for the completion of whatever needs to be done (could be handled by queues or some external system that updates state on the site).
Use JavaScript to take action.


Print ALT tag from an Image FIeld in a Custom Field Template

If you install Devel module and use dpm($item); in your code, you will see the structure of $item. Alt is in $item['#item']['alt'].

See for example Modify tpl file to print the path to the image instead of the image itself?.


Show/Hide fields not working for Condition Fields on node display

This is a quirk of the module, per the documentation on the view context:

  The "Value", "Filled" and "Empty" conditions are special: they are the
  only conditions that have ANY effect on form validation and content
  view.

If you want to show/hide fields with the module during content display, you'll need to set the Condition to Value and the according value for your checkbox.


View is returning two default results when no value in filter is being selected. Why?

There is a views setting "Exposed form style", where you can select "Input required" if you don't want results to be displayed by default.

See the attached screenshots:

Then


How can I display conditional fields on page view?

You don't need conditional fields for this. The simplest way to do this IMO is just look at the values either in the Twig file, or create a new variable in a preprocess function to indicate what to do.

Example:

{% if node.field_callout_icon or node.field_callout_text %}
  {% if node.field_callout_link_control.value == 'A single large button link' %}
    markup
  {% elseif ... %}
    markup
  {% endif %}
{% endif %}

Or you can preprocess the node and look at the field value there:

function mytheme_preprocess_node(&$variables) {
  $node = $variables['elements']['#node'];

  $field_value = $node->get('field_name')->getValue();
  // .. do stuff with the field value
  $variables['my_new_flag'] = 'some value or bool';
}

Then in the node twig, if its a bool:

{% if my_new_flag %}

Or if you assigned a value:

{% if my_new_flag == '...' %}

One thing I would advise against is looking into the render array to read or look for values. Use the node object or preprocess the node to evaluate the values and create new variables if you need them.

Here is a real example I am using which seems very similar to yours. I have a select field in a node type that indicates if the content is a service or a tool. Depending on which, I need to output the right SVG file next to the title. I am checking the value and creating a variable for the template:

mytheme.theme:

/**
 * Implements hook_preprocess_node().
 */
function mytheme_preprocess_node(&$variables) {
  $node = $variables['elements']['#node'];

  if ($node->getType() == 'services') {
    $variables['icon_type'] = $node->get('field_service_or_tool')->value;
  }
}

The node type twig file:

{% if icon_type == 'service' %}
  {% include "@mytheme/svg/general/service.html.twig" %}
{% else %}
  {% include "@mytheme/svg/general/tool.html.twig" %}
{% endif %}

I could just check that in the twig as well, but it keeps the template cleaner / easier to read in my opinion.


with panels module you can select witch fields display and just do not add fields that you dont want, do not place "complete node form", also you can control what contentypes node/add form overrides.
If you do not use panels module you can add a custom module with the following code (D7), replace uppercase letters with your data. This code only affect "your_form_id", to find your form_id, inspect an element (right click on your form) and look for it.

 //if form id is YOURFORM_form hide elements
 function YOURMODULE_form_alter(&$form, &$form_state, $form_id) {
      global $user;
        $uuid = $user->uid;
  /*  check that user is NOT admin (No1) */
     if ($uuid !='1') {

        if ($form_id == 'YOUR_FORM_ID') {
            hide($form['field_YOUR_FIELD']); // hides field to all but admin user
            $form['body']['#format'] = 'plain_text'; // forces body format to plain text
            //displays field in form, but disabled
            $form['YOUR_SECOND_FIELD']['#disabled'] = TRUE;
        }
    }
 }


Use your favourite SQL client and amnually populate {field_config_instance} table:

In Drupal, create field in one content type.
In your favourite editor create set of 39 queries (40 content types minus that one you worked out manually), with the same field values. Just leave id empty so autoincrement can work, and populate entity_type with your conetnt type names. I use spreadsheets to do that, first spreadsheet column is first query part, second is for the names of content types (obtained by querying {node_type}, third is for last part of the query.
Paste that query set into your SQL client and execute.


Control the data facebook fetch and post on "share"

Ok, so the problem was that on the admin -> configuration -> Metatag -> open-graph.  I had the token [node:summary] on the description field.
I do not have a field on my site called summary.
This token just fetch a lot of information from the content / view and post it.

I removed it, change it to tokens I wanted, add some text to make the output more readable, and that's it.

After that, it took time for the site to update with the changes..


using contextual filters to filter with relationship

You can't show both. When you choose to show articles,  vieuws will select articles from the database using your conditions. Since an issue is not an article, they will not show.

What you probably can do is embed another view in your views header or footer section and display the related issues in that view.


Poormanscron is the most common module used for calling cron within Drupal (integrated into core in D7).


Your current code doesn't work because of namespaces, but even so, that's not the right way to approach your requirement.

AdvancedHelpManager is a plugin manager, which is a service, so you should get the instance of it like so:

$plugin_manager = \Drupal::service('plugin.manager.advanced_help');
$topics = $plugin_manager->getTopics();

(as always, if you're in a context where DI is available, inject the service instead of calling the static \Drupal method).

If any of this doesn't make sense it would be a very good idea to read the Services and dependency injection docs, which help to explain the architecture behind Drupal 8.


update text format "filtered html" on old nodes

Update the database directly using SQL queries. The queries are something like

UPDATE field_data_field_[example] SET field_[example]_format = '[text_format]';
UPDATE field_revision_field_[example] SET field_[example]_format = '[text_format]'

for a field named field_[example] that was created with the Field UI module and a text format with machine name [text_format]. Clear the cache afterwards.


How to create a new entity with default values if not passed?

For entities in general, set default values by adding preCreate() to your entity class:
  /**
   * {@inheritdoc}
   */
  public static function preCreate(EntityStorageInterface $storage_controller, array &$values) {
    parent::preCreate($storage_controller, $values);
    $values += [
      'auto_open' => TRUE,
    ];
  }

In this specific case, define a class property with the same name as the field, which defaults to TRUE:
  /**
   * Auto Open.
   *
   * @var bool
   */
  protected $auto_open = TRUE;


What would be on your checklist when trying to debug a non-reverting feature?

Do you have any modules implementing hook_strongarm_alter()?

If you're blindly overriding Drupal system variables using hook_strongarm_alter() as follows:

function mysite_strongarm_alter(&$items) {
  $items['upload_extensions_default']->value .= ' qtz';
}

...some Features may incorrectly appear as Overridden.

Instead check to see whether the item is defined first:

function mysite_strongarm_alter(&$items) {
  if($items['upload_extensions_default']) {
    $items['upload_extensions_default']->value .= ' qtz';
  }
}

...and the Strongarm aspect of the Feature will no longer incorrectly appear as Overridden.


Filter menu_tree_all_data() tree by language?

I suppose you have i18n_menu.module installed. In this case, use i18n_menu_localize_tree($MENU_TREE) to get the tree for the current language.

To get secondary menu, for instance (on template.php):

$tree = menu_tree_all_data('menu-secondary');
$variables['secondary_menu_expanded'] = menu_tree_output(i18n_menu_localize_tree($tree));


Found the solution in case anyone else ever has this issue:

    drupal_add_css(drupal_get_path('module', 'tasker_project') . '/tasker_project.css');
    global $user;
    module_load_include('inc', 'node', 'node.pages');
    $node = (object) array(
        'uid' => $user->uid,
        'name' => (isset($user->name) ? $user->name : ''),
        'type' => 'tasker_blog',
        'language' => 'und',
    );
    node_object_prepare($node);
    $form_state['build_info']['args'] = array($node);

    $form = drupal_retrieve_form('tasker_blog_node_form', $form_state);
    drupal_prepare_form('tasker_blog_node_form', $form, $form_state);
    $form['hidden_project_id'] = array(
        '#type' => 'hidden',
        '#value' => arg(1),
    );

I used drupal_retrieve_form and drupal_prepare_form and everything seems to work correctly now. Not sure why drupal_build_form or drupal_get_form don't work correctly.


How to disable edit links/tasks for mobile theme?

Items should be disabled, if they are usually enabled, but not useful in that particular circumstance. For example, a submit button could be disabled when the form does not validate. Having an item that is permanently disabled raises the question why the item is displayed at all.

If you want to hide the items, you can do this using CSS if there is an appropriate CSS selector. Have a look at the HTML to figure that out.

For Drupal 4.7.x, 5.x and 6.x, you can also remove the links as described on the drupal.org page Remove unwanted tabs from pages.

Note that both methods only remove the link from the page. They do not prevent users from actually editing the page (e.g. by entering the URL manually).


How to add javascript library that does not need a module, but is required by modules?

A module is really the only appropriate place for something like that; Drupal doesn't provide any way of making a module dependant on a JS library. You can only make a module dependant on another module, so if you want to enforce a dependancy to your JS code you'll have to create a module to contain/reference it.

If you're worried about having an empty module file, don't be...to formalise your library and describe it to the system properly, most likely you should be implementing the core hook_library() anyway. Then your dependant modules can simply call

drupal_add_library('mymodule', 'library');

to add your library. Putting the JS library files themselves into the sites/all/libraries folder, and referring to them from hook_library(), would probably be the best solution.


Image in View with Lightbox2 formatter lacking alternative text tag

For people coming to this page...I wanted to use the title of the node containing the image as the caption on the lightbox2 image, which I was displaying in a view, but I didn't want to modify the module, which I think is the issue with the above technique.

What I ended up doing was making my own image formatter.  Basically I cut and pasted the hook_field_formatter_info and hook_field_formatter_view from the lightbox2 module and modified them.   There may be a better way, but it works, solved my problem, and I can upgrade lightbox2 without worrying about breaking my site.

/**
 * Implementation of hook_field_formatter_info().
 */
function mymod_field_formatter_info() {
  $formatters = array();
  if (module_exists('image')) {
    $formatters["mymod_custom_formatter"] = array(
      "label" => "Field formatter for my Photos",
      "field types" => array("image"),
    );
  }
  return $formatters;
}

/**
 * Implements hook_field_formatter_view().
 */
function mymod_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
  $element = array();
  $pieces = explode('__', "lightbox2__lightbox__thumbnail__large"); // forced this, you could do something trickier, but it solved my issue

  ... untouched ...
  foreach ($items as $delta => $item) {
    // here is the bit I added which sets the node title to be the image caption
    if ($entity_type == 'node') {
      $item["title"] = $entity->title;
    }

    $uri = array(
    ... etc ...


Administer Users by Role module - show users

I don't know whether this is correct or not but you can try this,

function mymodule_views_query_alter(&$view, &$query)
{
 global $user;
 $role=implode(', ', array_slice($user->roles, 1));//get the current user role
if ($view->name == 'your_view_name')
{
  switch ($role) {
    case 'administrator':
//  drupal_set_message("administrator");
     // $query->add_where(); put your where condition
     // $view->query->set_group_operator('OR');
        break;
    case 'editor':
//  drupal_set_message("editor");
     // $query->add_where(); put your where condition
     // $view->query->set_group_operator('OR');
        break;
    case 'Member':
    //  drupal_set_message("Member");
      // $query->add_where(); put your where condition
     // $view->query->set_group_operator('OR');
        break;
        }
    }

}


Cannot enable node_view in ctools page_manager permanently

Found the reason:

I had a module enabled which implemented a menu_alter which has changed

$items['node/%node']['page callback']


An alternative is to use the Menu Position Module.

This module allows you to create a "rule" that says all of the nodes of type "whatever" go under this menu entry.

So, for your specific case, you would go to Structure > Menu Position Rules and add a new one. Give it a name and location in the menu and specify which content type you want (or pages, or users, or terms).

This is beneficial as it means you don't need to add each node to the menu.


That module has a drupal 7 version in the issue queue at https://drupal.org/node/1138946

Comment #25 has a link to a sandbox of the drupal 7 port: https://drupal.org/sandbox/wojtha/1331132

There is another version in a zip file at comment #46 but it seems that one is inferior.

It seems that it has been reviewed by a few people and works but the module doesn't seem to have an active maintainer so it has not been committed to the repository and made available on the project page.

I would try those versions of the module and see if either of them work.


How do I set a value based upon other values?

If you have a small number of settings to store, you might consider using system_settings_form() to store them in Drupal's variables table. Take a look at the core modules that implement this function for more examples.

If the rates group logically, and/or need to be edited by users, you might make a postage_rates content type with fields on that for the information that changes in addition to any constants set by an admin using the first method. You can then add a entityreference field from you product to the postage_rate.


How to call a function on node submit in drupal 7

function MODULE_form_alter(&$form, &$form_state, $form_id)
{
  //echo $form_id; // get the form id
    switch($form_id)
    {
        case 'name_of_the_form':
           $form['#submit'][] = 'test_form_submit';
           break;
    }
}

function test_form_submit($form, &$form_state)
{
  drupal_set_message("How are you");
}


Conditional PHP works in Node Template but not in Views Custom Fields

If 'm not mistaken you are trying to move this logic out of your tpl.php template file by using views custom field.

You first need to get the name of the accessible fields with this code.

<?php print var_export($data, TRUE); ?>

Then you should be able input in the custom field something similar to this.

<?php if ($data->field_stock == 'No' ) : ?>

Out of Stock

<?php endif; ?>

There is more info here http://drupal.org/node/467190.


Module to create a custom field in all the content types

Instead of installing the field in your install hook (which will be triggered when installing the module only), you should implement hook_entity_base_field_info() to add the field to all nodes and all bundles.

An example below:

use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Field\BaseFieldDefinition;

/**
 * Implements hook_entity_base_field_info().
 *
 * Attaches a custom field 'field_custom_tocken' to all nodes.
 */
function mymodule_entity_base_field_info(EntityTypeInterface $entity_type) {
  // Whether the entity type is 'node'.
  if ($entity_type->id() == 'node') {
    return [
      'field_custom_tocken' => BaseFieldDefinition::create('string')
        ->setName('field_custom_tocken')
        ->setLabel(t('Tocken'))
        ->setDescription(t('My tocken, which might be named token instead.'))
        ->setSettings([
          'max_length' => 150,
          'text_processing' => 0,
        ])
        ->setDefaultValue('')
        ->setDisplayOptions('view', [
          'label' => 'above',
          'type' => 'string',
          'settings' => [
            'link_to_entity' => FALSE,
          ],
          'weight' => 0,
        ])
        ->setDisplayOptions('form', [
          'type' => 'string_textfield',
          'weight' => 0,
        ])
        ->setDisplayConfigurable('form', TRUE)
        ->setDisplayConfigurable('view', TRUE),
    ];
  }
}


Drush Not recognizing it's in a drupal root

If your settings.php file is inside a directory named default, then Drush will find it whenever your current working directory is anywhere inside the document root.  However, if settings.php is in some other directory, then you must either cd to the directory that contains settings.php, or identify your site via some other technique -- for example, by specifying --uri=mysite.com, or by using a Drush site alias.


How to render-print content type fields in an article?

ok, here is what I would do:

Create a subtheme as per this video, let's call it mytheme
Go to sites/all/themes/mytheme and create a file there called

node--comments.tpl.php

Go to modules/node/node.tpl.php, open it and copy eveything inside
Paste that inside the node--comments.tpl.php that was created in second bullet
Inside the node--comments.tpl.php, substitute print render($content); with your code

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

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

The reason we subsitute print render($content); with your code is that your content-type has 4 fields and through your code you render all 4 of them one by one, so nothing is left for print render($content); to do.
Go to appearance, enable and set default mytheme
Lastly, clear cache to be sure all the changes are picked up (configuration -> development -> performance)

In this way, I would achieve to have my styling changes in a subtheme. So anytime I want to change something I can do it there and it will override what would be shown by the base theme, without changing core. This is following Drupal's best practices and keep my styling seperate from core, which makes the site more robust and easily maintained (& upgraded)

note: by creating the file node--comments.tpl.php and following these directions, you will just change the output of the custom content type called: comments, while leaving the rest of the nodes to be handled by the node.tpl.php, without interference.

P.S. you can do without step 1 and go straight to themes/bartik/templates (if bartik is your default theme), create there the node--comments.tpl.php and continue from there, and although this is faster, I think it is bad practice for the reasons explained above :)


Adding multiple taxonomy terms to a single node programmatically

Finally I have a working code:

insert_term_if_not_exists($cat, 'tags');
              $term_tags = taxonomy_get_term_by_name($cat);
              $tid_tags = key($term_tags);
              array_push($tids, $tid_tags);
              $lang_tags = field_language('node', $node, 'field_tags');
            }
          }
          foreach ($tids as $index => $tid) { $node->field_tags[$lang_tags][$index]['tid'] = $tid; }

       }

All the credit goes to user Albright in IRC channel #drupal at http://webchat.freenode.net who pointed out to me that I needed to collect the tids in an array, then add a second loop which loops through that array and adds the tids one at a time to field_tags.


Which webform hook and how use to set programmatically webform target email?

If you just want to customize the target email, webform do this quite easily.
Go to node/123/webform/emails (where 123 is you nid) and there you can configure the recipients.
The option "component value" allows you for example to set the email regarding a select list. Configure a select list for the subject, put these values in the option textarea:

contact@example.com|General inquiries
marketing@example.com|Marketing

Then when the user will use webform the email will be sent to the direction chosen in the subject list.

If you want something more advanced, have a look at my previous answer in "pass cck email value to webform block". This will help you to detect different webform (using hook_form_alter.


Add an image to a views title (Taxonomy Term View)

I would use Panels for that. You may combine any elements from Drupal on the same page (node fields, views, terms, blocks, etc.) with Panels.

With this module you can edit the taxonomy term page as you wish (Structure > Pages > Taxonomy view > Active then edit).

In the Content section, after setting path, context and layout, you add your taxonomy term custom image field, followed by your taxonomy term name (with a little CSS float, you will have your image on the left).

Finally, you add your View below (do not forget to activate the Chaos tools sub-module "Views content panes") and you're done.

Panels needs a little practice but it is a powerful tool to work on page templates.


How can I upgrade ONLY Drupal core with composer?

I do two things.

I use webflo/drupal-core-strict in my composer.json to make sure the same tested core dependencies are the ones used in my project.
I pin both drupal/core and webflo/drupal-core-strict to an exact Drupal version so I can regression test and know exactly what I am deploying.

So, my projects looks like

"require": {
    "drupal/core": "8.3.6",
    "webflo/drupal-core-strict": "8.3.6",
    "composer/installers": "^1.2",
    "drupal-composer/drupal-scaffold": "^2.2",
    "cweagans/composer-patches": "~1.0",
    "drush/drush": "~8.0",
    "drupal/console": "~1.0",
},

And where there is a new core version, I composer update drupal/core webflo/drupal-core-strict and then double check the lockfile.


Check your text formats (Admin > Configuration > Content Authoring > Text formats) and make sure the one you're selecting for your node isn't filtering out the img tag.


I have found that MAX OPEN FILES can have an impact along with maximum size of object, my understanding is this is the case with or without memcache but I have not proved that yet. I created a tool with cURL to log broken views when they occur and use Munin to monitor everything as it happens: https://drupal.org/node/89710#comment-8351855


How do I add javascript to a node or block

Use a function in the template.php file: yoursite.com/sites/all/themes/YOUR_THEME/template.php

Add JS file in a block:

function YOUR_THEME_preprocess_block(&$variables) {
    drupal_add_js(drupal_get_path('theme', 'MYTHEME') .'/scripts/path');
}

Add JS file to one page or node:

function YOUR_THEME_preprocess_page(&$variables) {
  if ($variables['nid'] == 'INSERT_NODE_ID') {
     drupal_add_js(drupal_get_path('theme', 'MYTHEME') .'/scripts/path');
  }
}

Add JS file to a content type:

function YOUR_THEME_preprocess_node(&$variables) {
  if ($variables['type'] == 'INSERT_CONTENT_TYPE') {
       drupal_add_js(drupal_get_path('theme', 'MYTHEME') . '/scripts/path');
  }
}

Add JS file to a view:

function YOUR_THEME_preprocess_views_view(&$variables){
  if ($variables['name'] == 'INSERT_VIEW_MACHINE_NAME') {
    // include javascript
    drupal_add_js(drupal_get_path('theme', 'MYTHEME') . '/scripts/path');
  }
}

As mentioned by @Pierpaolo Cira, you could always replace MY_THEME with MY_MOUDLE. To get the path to your module you would have to use drupal_get_path('module', 'my_module').

Note: MY_THEME and MY_MODULE needs to be lowered case if your module or theme name is lowercased. (E.g. MY_THEME would be replaced with zen if zen)

Source


Drupal has an option to just login using the user reset link. When you add /login after the reset link the user is logged in directly and redirected to their their profile page.


Two possible solutions: 1) set a session var in your validation script to flag when validation fails, then you can check if that session var is set (validation failed once) then add it anyway. 2) If you can't rely on session var, you can look at adding a custom boolean field to your user to flag this this user has failed validation once, then check if that field if true(failed once)/false(hasn't failed yet) and code accordingly, and you'd want to reset this field to false again once the node has been created in case you need to use it again for another node form.


Can't direct a domain to a working D7 test site

Fundamentally, there is absolutely no problem with pointing a domain to a functioning Drupal instance.  That being said, there are many other things that can be going on here.  Let's tackle a few of them.

First of all, when you change the DNS settings for a domain, it can take a day or more to fully propagate, due to the way different DNS servers cache their entries.  To make matters worse, the change can make it to you at a different time than someone else, which makes it difficult to detect what is going on.

If you want to see results immediately for testing, then you need to manually add an entry to your hosts file that points the domain name to the server that you want to see the results for.  In a Linux machine, the hosts file is /etc/hosts, and on a Windows machine, it is \Windows\System32\drivers\etc\hosts.  You add an entry just by adding a new line to the end of the file in the form of:

XXX.XXX.XXX.XXX www.hissite.com

where the XXXs are the IP address of the target server.  The change is instant when you save the hosts file (i.e. no need to restart).
$base_url is a setting that affects how Drupal creates URLs internally.  If the links that Drupal is creating look correct (e.g., www.hissite.com/node), then it is working correctly.
This could be a problem with clean urls.  If you go to www.hissite.com?q=user, and that works, but www.hissite.com/user does not, then the server is not correctly interpreting clean urls.  Your only options are to either enable clean urls or to choose a different host, since you likely don't have direct access to the server settings.  (Disclaimer: I haven't used GoDaddy's service, so I don't know the extent to which you can modify server settings.)  Basically, if the server is running Apache, then, in order for clean urls to work, Apache must be allowed to parse your .htaccess files, and it must have mod_rewrite enabled.
A final test would be to see if perhaps the .htaccess file is not being interpreted at all.  Try going to www.hissite.com/index.php?q=user.  If that works, but www.hissite.com/?q=user does not, then it is definitely a server setup issue, and I do not know if GoDaddy provides you with the tools to fix it.

Finally, I want to address your fundamental problem as I see it: you are using GoDaddy.  I'm slightly biased against them for various reasons, but mostly I think that you can have a better experience for roughly the same cost by setting up your own VPS somewhere.  I use DigitalOcean, and have for quite some time (I have no affiliation with them other than being a customer).  For the same cost of the GoDaddy deluxe hosting, you can have your own small VPS which can run several sites.  I do this with my personal site, http://cscrunch.com, as well as a handful of other, family sites.


Taxonomy breadcrumb on taxonony block in views (by contextual filters)

I think this could be done with Crumbs programmatically, but this might be overkill. It would also be fragile, because it would depend on Crumbs functionality that is not really part of the public API, so could change in future versions of Crumbs.
Also consider that you don't really need the full breadcrumb, just the taxonomy trail.

Instead, you could write a custom Views header plugin. Unfortunately it is a bit hard to find documentation on that.

Or, you could alter the views header with one of the views hooks.

Or you could use the theme layer to override the views theme output for this specific view.

Or override the block template for the specific block. I think this one is actually the easiest for a starter, and for this specific situation. You can get the taxonomy term from the node, and you get the node with menu_get_object().

Have a look at https://api.drupal.org/api/drupal/modules%21taxonomy%21taxonomy.pages.inc/function/taxonomy_term_page/7 to see how the taxonomy page calculates a breadcrumb based on the taxonomy hierarchy.

(I am mentioning more than one solution here, because other readers might have slightly different requirements.)


Different sets of language icons per theme

As mentioned in my question, I could not do this by using hook_block_view_alter() because I can only have the renderable HTML of the block content in that hook.

I found a theme function theme_languageicons_icon, which renders the icons, in the file sites/all/modules/ languageicons/languageicons.module. I copied the theme function into my custom module and implemented hook_theme_registry_alter() to override it.
Then, I updated the function as my need and flushed caches. It gave me exactly what I needed.

function MYMODULE_theme_registry_alter(&$theme_registry){
    if( isset($theme_registry['languageicons_icon']) ){
        $theme_registry['languageicons_icon']['function'] = 'theme_mymodule_languageicons_icon';
    }
}

function theme_mymodule_languageicons_icon($variables) {
  global $theme;
  $language = $variables['language'];
  $title    = $variables['title'];
  # define icons path for various themes
  $default_path = variable_get('languageicons_path', drupal_get_path('module', 'languageicons') . '/flags/*.png');
  $path_by_theme = array(
    'theme1' => drupal_get_path('theme', 'theme1') . '/flags/*.png'
    'theme2' => drupal_get_path('theme', 'theme2') . '/flags/*.png'
  );
  $path = (isset($path_by_theme[$theme]) && file_exists($path_by_theme[$theme])) ? $path_by_theme[$theme] : $default_path;
  # define dimension for various themes
  $default_size = check_plain(variable_get('languageicons_size', '16x12'));
  $size_by_theme = array(
    'theme1' => '19x19',
    'theme2' => '25x24',
  );
  $size = (isset($size_by_theme[$theme])) ? $size_by_theme[$theme] : $default_size;

  if ($path) {
    $title = $title ? $title : $language->native;
    // Build up $image for theme_image() consumption.
    $image = array(
      'path' => str_replace('*', $language->language, check_plain($path)),
      'alt' => $title,
      'title' => $title,
      'attributes' => array(
        'class' => 'language-icon',
      ),
    );
    if ($size) {
      list($width, $height) = explode('x', $size);
      $image += array('width' => $width, 'height' => $height);
    }
    return theme('image', $image);
  }
}

If you have a better solution, it is welcome.


HTML tags not supported when sending emails in Drupal 8

You can't send HTML email with Drupal 8 "out of the box."

To send HTML email, you can use the Swift Mailer module, which has the following features:

  Sending e-mails directly through a SMTP server of your choice, a
  locally installed MTA agent such as sendmail or the mail functionality
  provided by PHP.
  Sending HTML (MIME) e-mails.
  Adding file attachments to e-mails.
  Adding inline images to e-mails.

The Commerce 2 documentation includes a tutorial on how to install and configure the Swift Mailer module.


How can I return literal JSON from a node as a JSON object in views json?

Views Datasource will escape the contents of any string field. If the field were an object, it would be formatted as JSON. (See: views_datasource/views/plugins/views_plugin_style_json.inc.) There doesn't seem to be any way to override this behaviour other than patching the module or using some field type that would produce this result.

I faced a somewhat related problem and had to write my own API endpoint to get the JSON as I wanted it. I used views_get_view_result() to get the raw data and rework it so that I had the correct array structure. Then I run drupal_json_encode().


Properly adding an action to a ContentEntityForm

This is relatively simple when you define the form class yourself and one of the reasons Drupal 8 has gone all out on OOP. What you need to do is to extend the form class and implement the ::actions method. This would look like this:

class CustomEntityForm extends ContentEntityForm {
  ...

  protected function actions(array $form, FormStateInterface $form_state) {
    $actions =  parent::actions($form, $form_state);
    $actions['cancel'] = [
      '#type' => 'submit',
      '#value' => $this->t('Cancel'),
      '#submit' => ['::cancelSubmit'],
    ];
    return $actions;
  }

  public function cancelSubmit($form, FormStateInterface $form_state) {
    // Du custom submit validation
  }

}

You could also achieve this with normal form alter, but would need to place the submit button inside the actions element, which is usually called actions, fx

$form['actions']['cancel'] = array(
  '#type' => 'submit',
  '#weight' => 10001,
  '#submit' => array('cancel_submit'),
  '#value' => t('Cancel'),
);


How to get alternative text on image hover

In the field settings for the image, make sure to 'Enable Title field' - this will present a text input for each content under the upload button.  You can include the title here, and it will show on mouse over.


You haven't really asked a question. But i'll assume that you want to know what a base and sub-theme is in drupal.
TLDR version
A drupal subtheme inherits the template files (*.tpl.php) and assets (javascript, css, images) of the base theme. If you need to modify or change the template files.
More on subthemes
I think your best bet is to google it. I googled, "drupal subtheme" and found you  drupal documentation regarding subthemes:

Sub-themes are just like any other theme, with one difference: They
inherit the parent theme's resources. There are no limits on the
chaining capabilities connecting sub-themes to their parents. A
sub-theme can be a child of another sub-theme, and it can be branched
and organized however you see fit. This is what gives sub-themes great
potential.

Source: Creating a sub-theme (drupal.org)
In addition to the node page, if you're more inclined to watch a video this is probably a good bet: Drupal Subthemes (youtube.com)
Why should you avoid modifying a base theme

Flexibility: Base themes maintain flexibility. If there is an update, your child theme inherit these changes
Losing your changes: Modifying your base theme means that when an update to the theme comes along your modifications could potentially be lost
Maintain simpler code base: The base theme allows you to abstract a lot of functionality and reduce the code base. This means less maintenance in the long run.

Best Practices with subthemes:

Copy files from the base theme or use the drush command (when available)
Utilize subtheme theme hooks to override your theme


How to reset a form element to its ordinary default value?

field_get_default_value - Helper function to get the default value for a field on an entity.
Usage:

<?php
  $field = field_info_field('YOURFIELDNAME');
  $instance = field_info_instance('node', 'YOURFIELDNAME', 'YOURNODETYPE');
  $defvalue = field_get_default_value('node', $node, $field, $instance, $node->language);
  print_r($defvalue); // Here structure, like $defvalue[0]['value']
?>


Webform 4 - More than one conditional hides or shows component - Confusing Is & Isn't Shown?

ok it works with this setting it seems. it seems that once u set it to "isn't shown" it will auto hide it by default. which is why its throwing an error as it cant do 2 conditions at once.


Safe to delete cache_form table while site is in maintenance mode?

First off, cache_form is not really a cache table, but a temporary table used to contain data necessary to verify the form being submitted to Drupal is not forged.
If you were to empty that table, users would encounter validation errors for the data they submitted from the form they were using. Since the site is in maintenance mode, that should impact the only users who are allowed to access the site when it is in maintenance mode, which includes you. You just reload the page containing the form, and fill it again; it's not a permanent error.


How to create navigation menu on sidebar with different navigation links displayed on different pages?

This totally looks like a Menu Block scenario, where you would want to enable the 'Make the starting level follow the active menu item.' setting. Also enable 'Block title as link', but don't enter a custom title as this would override the link.


You are looking for Theme developer module:

  Firebug for Drupal themeing. See the screenshot and screencast. Note that this module injects markers into the DOM to do its magic. This may cause some themes to behave erratically and less capable browsers may make it worse (especially IE)/. Enable it when needed, and disable it afterwards.

If it is crashing your website

You need to upgrade. You are at 7.0, current version is 7.31. You are 31 minor versions behind. And some of them was security updates. So you probably should upgrade anyway.


How do I configure the database using php_server module

This is because you are running the drush command in directory where your project code doesn't exists. I think you are getting logged in to home directory of a server where the project code does not exists. Your project code is in another directory. for e.g

-opt
 -webcode
  -project_code
-home
-etc

So you are getting loggedin in the home directory but your code is inside /opt/webcode/project_code. You need to reach to project_code directory first and then run the drush command.

You can use filezilla if you are not aware of the directory stucture. It will help you to know which directory has your project code.


How to build a reusable configurable form

In a custom module, use the FormAPI to build your form and create variables to store your #options for example (in the case you mentioned of select lists that change). Set the variable according to the context and you should be good to go.

/**
 * Implements hook_form();
 */
function mymodule_form($form, &$form_state) {

  // For inspecting information about entity and id:
  kpr(arg(0));
  kpr(arg(1));

  $form['selected'] = array(
    '#type' => 'select',
    '#title' => t('Selected'),
    '#options' => $variable_according_to_context,
    '#default_value' => $category['selected'],
    '#description' => t('Varies according to context.'),
  return $form;
}

The $variable_according_to_context will hold the options of your select list. You can set this variable to different options according to the context you are in. You can use arg(0) or arg(1) to get the node or entity type the form is in. I hope that was clear enough on how I would approach this.


Is there ever justification for adding HTML before passing content to a twig template?

It's not possible to put all html markup in templates. Often for example in case of an error you need to generate some extra markup.

If it is a string constant like in your example this is no problem.

If you have variables, don't concatenate in markup.

Use Drupal\Component\Render\FormattableMarkup instead:

$variables['error']['#markup'] = new FormattableMarkup('Error @message at line @line', [
  '@message' => $message,
  '@line' => $line,
]);

Most times you need to make this translatable and this is why t() is still one of the most used functions in drupal:

$variables['error']['#markup'] = t('Error @message at line @line', [
  '@message' => $message,
  '@line' => $line,
]);

If you are in a class use $this->t().

To summarize, the answer to the question is yes, there is justification for adding html in php. This is, if you need to react dynamically on things happening in your code. Then instantiate a new FormattableMarkup object. If you need translation, you can simply use t().


Fields from different content types in a single page

My first thought would be to rethink your publishing workflow.

Having that said, I would try to create a view which takes content from all content types. Instead of showing the content, show the appropriate fields and create a filter so only unpublished content is shown...


Show only nodes that are connected via entity reference with views

Contextual filters work combined (AND), so if you define two or more contextual filters, all of them have to pass.

Here's what I would do.

Use Pathauto to create a pattern for your group content, e.g. g/[node:nid].
Create additional aliases for long name and short name.
Make your view work with just the NID contextual filter and use the block display type.
Configure your block to only show up on group node type and place it in main content.

Alternatively, you can also use Panels to create a similar node page for group nodes. To create the additional URL aliases for each group, you might want to try NodeSymLinks module.


Did you try Entity Translation ?

I find it very much easier and efficient than i18n (which is needed for some other parts of the site anyway).

There you get exactly what you're looking for : translations stored in one node only.


Use $form['#submit'][] = 'xxx_form_submit'; instead of $form['actions']['submit']['#submit'][] = 'xxx_form_submit';.


Not sure if this is still relevant or not but I was having the same issue and I was just missing a dash.

  libraries:
    mytheme/global-styling

to

  libraries:
    - mytheme/global-styling


Trying to update node using node_save() produces integrity constraint exception

please see the documentation of the hook
https://api.drupal.org/api/drupal/modules!node!node.api.php/function/hook_node_insert/7

Notice that it says that the hook is invoked (i.e. triggered) by node_save and that means that the data is NOT yet written in the database! so you essentially create an infinite loop.

Try to do something like $node->yourfield['und'][0]['value']= 'yourvalue_here' and DO NOT call node_save again. Also do not use a wrapper because in this case only adds complexity. Notice that if you dont use the wrapper you must provide the langauage (['und']  in my example) the number of the item ([0] ie the first one in my example) and the key of the table that stores the value (['value'] in my example). This is done automatically when you re using an entity wrapper but since your node is not ready yet it is not the best option because you clone the object by value and not by reference and then even if you change it the changes are not reflected in the original one that will be fed into the database.


Search API Views - How to display facets on a views block?

The answer depends on your theme; but this is an example of how to do it with 'Commons'

in > admin > Structure > Blocks

  Search for your facets and select the block you want them to go in .  ie 'Sidebar First'

  SAVE

  open your View > Page .

  under FORMAT change Show to 'Panel Fields'

  In Settings choose your Panel Layout from the list.  ie 'AT One Column' should display the above block example.

  And then still in the VIEW - making sure you are in the 'Page' display; otherwise you won't see this option.  Under 'Advanced' - you should now see under 'Exposed Form' the text 'Exposed form in block:'  - Change this to Yes.

  once you've added this to the view you'll now be able to
  go back to > structure > blocks.
  And see the exposed form here to move to the block you wish.

This information should be enough to point you in the right direction.


How can I automatically restore my site from a backup using the command line for testing purposes?

I use /applications/mamp/library/bin/mysqldump -uUSERNAME -pPASSWORD DATABASE >backup.sql to back my database up and then /applications/mamp/library/bin/mysql -uUSERNAME -pPASSWORD DATABASE <backup.sql to restore it.


Where to a place a custom php file in the directory

Everything including forms can be integrated nicely within drupal. i would recommend reviewing FAPI. it will save you time/effort in the end.

however, if you absolutely need this not to be built around/within/whatever using drupal's FAPI, what i would do is put the page either directly in your theme folder or make a subfolder and drop it in there. so lets make many assumptions here (awful i know). say your form is called newform.php. rename it to page-newform.tpl.php and drop it into one of those folders. create a page just to give you a node place holder and a path like /newform. then in your template.php file under the THEMENAME_preprocess_page() function, check the URL with either $_GET['q'] or arg() (arg is preferred). if the url is going to /newform simply adjust your $variables['template_file'] to be something like $variables['template_file'] = 'page-newform'. this will pick up your page specifically.

so with a lot of assumptions and very little go on with what you are doing. this could be done.

function themename_preprocess_page(&$variables, $hook) {
 if (arg(0) == 'newform') {
   $variables['template_file'] = 'page-newform'
 }
}


Report complains about Unsupported Release but no modules listed

If using Drush, try:

drush pm-updatestatus

Note: It gives you a list of the individual modules with their status, so you can determine which one is unsupported!


Add image field or other fields from node to a custom Block in Drupal 8

Use Views module for this. In D8 the views module is part of the core, in D7 you need to install it

1) Go to Structure > view

2) Add a view which shows content of type Basic page. Check on create a block.

3) Select the fields to be shown as image (as you want)

4) Under Advanced (on the right side of the view, click on it to expand)

CONTEXTUAL FILTERS click add, and select ID (D8) or Nid (D7) and then choose "Provide Default Value" and Under type select "Content ID From URL". click on Apply and save the view.

5) In structure >blocks, place the block in the region you want to on the content type you wish (In your case Basic Page).

6) Go to your basic page content  and you will be able to see the image which belongs to that node only in the view block you have placed.


These things would be easy to solve if you could set a cache expiration time for anonymous requests in UI, but you can't unfortunately. See Page cache not rebuilding after page cache maximum age is reached
In this case you could add an additional query parameter containing the current date when website 2 is requesting content from website 1 with javascript. This would create a new cache entry on every date change in the page cache of website 1, even if the query parameter is never used. You need to disable caching of the View itself so that it doesn't get cached in other places.


Migrating files from local source are not found

Turns out the problem was not in the Drupal code but simply a path issue. I run the Drupal 8 site inside a DrupalVM server and the migration is done relative to THAT root. So '/absolute/path/to/private/filename.png' is not with respect to the root of my computer, but with respect to the root of the DrupalVM.

The problem is solved by adding an extra synced folder to the DrupalVM that points to the Drupal 7 root:

vagrant_synced_folders:
  - local_path: /path/to/drupal8/root
    destination: /var/www/drupalvm
    type: nfs
    create: true
  - local_path: /path/to/drupal7/root
    destination: /var/www/drupal7
    type: nfs
    create: true

Then restart the server:

vagrant halt
vagrant up

In the migration file the source path becomes:

constants:
    source_base_path: '/var/www/drupal7'

Now the files are found.


I'm not sure how you are using Views to do this, but with a custom module you could easily do this with a fairly simple hook_menu(), eg, something along these lines:

function YOURMODULE_menu() {

  $items=array();

  $items['pages'] = array(
    'page callback' => 'YOURMODULE_get_some_rest',
    'access callback' => TRUE,
  );

  // any other menu items go here

  return $items;

}

and then:

function YOURMODULE_get_some_rest() {

  $args=func_get_args();

  if ($args) {

    $alias='pages/' . implode('/', $args); // so pages/foo works as does pages/foo/bar etc

    $data = /* get your data from your external service */ ;

    if ( /* $data was found */ ) {

      drupal_set_title( /* title in $data */ );

      return /* content in $data */ ;

    } else {

      return MENU_NOT_FOUND; // we don't have an alias of that name

    }

  } else {

    return MENU_NOT_FOUND;  // just called 'pages' so do something else here if need be, perhaps a list of all pages but for now, we just return not found

  }

}

so after a cache clear, users should now be able to go to www.example.com/pages/alias and Drupal will go out to your external service and grab the content and if found, populate the page with it, otherwise will return not found.

Now, if this data is going to be fairly static, I'd look into caching it so your users aren't delayed while Drupal fetches it.  For that, I'd look into cache_set() and cache_get().

ADDITION:

Drupal's menu system works on a sort of best fit methodology.  For example, if you define a menu item foo, it will obviously match www.example.com/foo, but, if no menu item has been defined for foo/bar, it will also match www.example.com/foo/bar or even www.example.com/foo/bar/baz/bing etc etc.

So, in my example above, I defined pages.  This will match www.example.com/pages which is just an error condition above, but with some programming could list all of the potential pages you have available to you, but also will match www.example.com/pages/alias-of-page or www.example.com/pages/alias/of/page.

Inside the callback, I use PHP's built-in function func_get_args() to deal with the variable number of arguments that can be passed to this function.  When you go to www.example.com/pages, no arguments will be passed to this callback and func_get_args() will return an empty array.  But, when you go to www.example.com/pages/alias-to-page, Drupal will automatically pass alias-to-page to the callback, and func_get_args() will return an array containing it, and when you go to www.example.com/pages/alias/to/page, it will pass three arguments, alias, to, and page to the callback function and func_get_args() will return an array containing all three.

As to your commentary question regarding this inside Views, once again, I'm not sure how your are doing this inside Views, but yes, this would go inside YOURMODULE.module and would stand alone outside of Views (although Views might be a great place to generate the listing on pages by itself).


You need to rebuild cache with Drupal 8, rather than clear it:

drush cr


Hope this will help you,

For Drupal 7

Tools used:

Firefox Poster add-on to do tests and debugging.
There may be other add-on as well. But for this example im using Firefox add-on.
To help editing and validating the JSON data you can use

Edit the JSON data using this link
Validate the JSON data using this link

HTTP requests

To make the HTTP requests, you need use the Firefox add-on POSTER.
Two commonly used methods for a request-response between a client and server are:

GET
POST

After the add-on is Downloaded. Open Firefox -> Tools -> Poster

Make sure to enable the Session authentication. After the Services is configured properly, before creating the node you should log-in. Once logged-in you can create the nodes.
For login use POST method, with the URL like - http://XXXXXXXX.com/demo/rulebook/rulebook_endpoint/user/login

If it is a valid user then it will return user details with session ID and Name. If not valid it will return Access denied

By using Session name and ID in the POST HEADER, we can able to create new nodes

Now after adding the HEADER, You need to make HTTP POST request and make sure  user should have permissions to create node.

If the node is created you will get the response with node link

NOTE : If you want the response in JSON then, you should always append .json at the end of the URL. eg., http://XXXXXXXX.com/test/endpoint/user.json OR http://XXXXXXXX.com/test/endpoint/node.json OR http://XXXXXXXX.com/test/endpoint/user/user_id.json OR http://XXXXXXXX.com/test/endpoint/node/node_id.json


How to create a Drupal calendar with 2 digits (day date format) instead of 1?

At first you should add a date format on that page admin/config/regional/date-time/formats/add.

For example this format (F d, Y) gives you that result: September 9, 2015.

Then you can use it anywhere on your site.


HIde node in view when field message is equal

Just an idea if you can try...

As per my point of view you may try to use flags with the timer? whenever the countdown is ended invoke a flag and you can use this flag in views.If the flag is invoked do not show the content else it will be visible.


Solution was here : https://drupal.stackexchange.com/a/150657/8753

For D6 the path is : admin/settings/language/edit/en

No need to set the prefix into the URL provided by pathauto here : admin/build/path/pathauto

in admin/settings/language/configure , both choice between Prefix only or Prefix and alternative solution seem to work.


You can do it simple, add 2 form concurrent to the page you want ( if they are block  put two block in that page) and then with simple Jquery you can handle it with something like below code

(function($){
// change jquery selector with real ones
$('.user-register1,.user-profile-register').hide(); // or you can hide them with css
var selector= $('your radio option selecotr').value();
if(selector==1) {
     $('.user-register1).show();
     $('.user-profile-register').hide();
}
elseif(selector==2){
     $('.user-register1).hide();
     $('.user-profile-register').show();

}

})(jQuery);

This code IS the way how can you achieve it and if you copy/paste it it will not worked till you changes its selector and values with your forms


Referencing both a node and user in the same field

There are a few ways to do this. You said "and/or", you could use Field Collection and add a node reference and a user reference to it. See the field collection module.

The other option would be the relation module or the entity reference module which can both reference any "entity." The former is a lot more complex. Entity reference has a usable widget with autocomplete which might be exactly what you need. To narrow the entity reference down to the exact content types you want along with users, you will probably have to write a custom widget. You can see the default widget implementation in the source.


I don't think there's an easy way to replace the user IDs with usernames, but you can easily add the usernames using the Realname integration (you have to set up the Realname module as well though).

My Privatemsg send page looks like this:

I did this by enabling Realname and following the instructions here.  You will need the dev version as well; the 1.3 release has broken Realname AJAX.


Render Profile2 field out of Profile2 page

Retrieve Profile2 Profile Data Programmatically

Implement profile2_by_uid_load() to get the data.

$profile2_data = profile2_by_uid_load($user->uid, 'profile_id');

$profile2_data will be an object containing all the data from profile_id for the requested user.

Retrieve Profile2 Edit Form Programmatically

module_load_include('inc', 'profile2_page', 'profile2_page');
$profile2 = profile2_by_uid_load($user->uid, 'profile_id');   // profile_id = machine name
$entity_form = entity_ui_get_form('profile2', $profile2, 'edit');
return $entity_form;


How to run the Flags module after the Rules module?

The problem arises because the Flag module runs before Rules, so it has already removed the flag before Rules performs its test. One way to deal with this is to install Modules Weight which will allow you to adjust the relative priorities of modules so Flag runs after Rules.


Rewrite query string for exposed taxonomy filter

You can accomplish this look by using Contextual Filters instead of an exposed filter in Views. But this approach will involve several changes. In a nutshell you would need to:

The list of tags on top would need to be a different (taxonomy) Views, embedded in the Header area of your catalogus View using Global: View area. In the taxonomy view, you will need to rewrite the output of the Taxonomy field (use "Rewrite results" in the taxonomy field) to a link that points to /catalogus/[field_portfolio_tags]
Add a Contextual Filter to your catalogus View. Be sure to add the taxonomy field Portfolio tags to the list of fields in this View (you can hide it if you don't want it to display for every single product). Choose the taxonomy Content: Portfolio tags. Choose Display all results in When filter value is not in URL. In WHEN THE FILTER VALUE IS IN THE URL OR A DEFAULT IS PROVIDED  choose Specify validation criteria. Validator: taxonomy term. Filter value type: term name converted to Term Id.

When you click on a taxonomy term in the embedded header View you will be redirected to /catalogus/name_of_tag. The Contextual Filter will assure that only products with that tag will be shown.

This should be it!


Before doing any updates, make sure that you've backed up your production site to avoid loss of data. Also make sure that you have an easy way to restore the backups (:

Solution 1

You can replicate the site on your local dev environment. Then, apply the updates using composer and upload the relevant files to the prod site.

Solution 2

You can use drush up MODULENAME to update specific modules. However, make sure you've tested the updates on a dev site. However, some modules have dependencies which need to updated separately. It is for these dependencies that people recommend using composer for updating Drupal packages.


Show original price and discounted price?

It does work with the discount module. In fact the moudle was built with that one in mind. Install Commerce Price Savings Formatter and go to your product types's display settings and change it as per the screenshot.


The locking issue is likely related to your database type and configs.

But you definitely do want to keep the truncate operation. To explain why, here is an order of operations on Entity CRUD in the entitycache.module. For example, on Entity update:

entitycache_entity_update() (an implementation of hook_entity_update()) is invoked
Skipping the condition check for a moment, cache_clear_all($id, 'cache_entity_' . $type); fires, and it seems your Entity type is node (hence why cache_entity_node cache bin is cleared. You want this, otherwise you will get stale data.
cache_clear_all in turn calls _cache_get_object($bin)->clear($cid, $wildcard);, and if for example your cache backend is the default cache implementation, this will call DrupalDatabaseCache::clear, which in turn will likely call db_truncate()
db_truncate() calls Database::getConnection($options['target'])->truncate($table, $options);, and that returns the TruncateQuery class
This is just so you can try to do these traces yourself, if you haven't already (or someone else reading can do this).
Skip to TruncateQuery::__toString(). If there is a transaction in progress, the SQL is 'DELETE FROM {' (and if not it's 'TRUNCATE {' (which is much faster). It sounds like you have a transaction in progress, and so you definitely want a row-by-row deletion with locks during (so it can roll back on failure if needed, whereas TRUNCATE is destructive). If you have many rows, depending on your database configs, this could possibly lock the entire table, not just the rows in question during the operation.

If this is the case, you can try various things to resolve it (caveat: you really want to contract a DBA or someone who knows your infrastructure and database setup very well). But for example, let's say your database type is MySQL: you could try reducing the lock wait timeout from the default. You could also try to change the transaction isolation level (preferable to READ COMMITTED). You'll want to read closely the comments above the $databases array in default.settings.php, specifically init_commands (issued for each connection which allow sessions settings to persist – you can set lock_wait_timeout and transaction_isolation here). There are various references to this, like Use READ COMMITTED for MySQL transactions core issue (for 8.x now, was for 7.x initially).

There is no single answer to this question, because like I said it very much depends on your setup. But I hope this gives you some direction toward solving your locking issue.

Update

Based on the issue tied to the patch your comment, I am adding more info to my answer:

Looking over Waiting for table metadata lock on cache_field table, the earlier patch in #3 gave way to an updated patch in #26. However, if you read all the information, in the end it looks like your best bet is to either 1. Not use entitycache module with DB cache backend (as Fabianx said - then again, I have experienced a similar issue using memcache so, again depending on your DB configs YMMV), or 2. try out the Asynchronous Prefetch Database Query Cache module that @mikeytown2 created to resolve this issue.


Rules- how to perform processing on cancelled accounts?

For this kind of configuration, you need to use the Event After updating a user account with the conditions User is blocked (account) and NOT User is blocked (account-unchanged).


There is backstory to this that is a little complicated.

The Timestamp field type was added back into Drupal 8.2.0 core as a "UI Field".  The field type had always been there, just as a behind-the-scenes field, and used as the base field for CreatedItem and ChangedItem for entity timestamps (which are both non-UI field types).

If this field is rendered out on with the proper widget on the edit page (see bug), then you end up using  TimestampDatetimeWidget.  This widget has a ::massageFormValues() method, which enforces the current time being used (at save) as the field value if the element is empty.

So, the behavior you are seeing is by-design.  The widget was initially intended for entity edit pages, where created and changed timestamps never have empty values after the entity is saved.  When this field was added as a UI field, it inherited the widget and its behavior.

If you really want a timestamp and don't want this behavior, you need to make a custom module and make your own widget.  You should just be able to copy TimestampDatetimeWidget into the module, rename it, update the annotation, and update the ::massageFormValues() method:

remove the else branch containing $date = new DrupalDateTime(); - this won't set the default datetime
handle unset $date variable, example: $item['value'] = !empty($date) ? $date->getTimestamp() : NULL;

That should allow you to have empty timestamps.

Personally, I would not use Timestamp fields, though.  I would use Date fields, which can have empty values or default values, and better widgets and formatters in general.


How can I get a taxonomy menu into the main menu AND a block?

Taxonomy menu block combines the idea of Taxonomy menu with the workings of Menu block:

This module does not make use of Drupal's menu system. Taxonomy menu first creates a menu which can then be displayed through a block, this module creates the block directly.

Make multiple menus per vocabulary.

"Split" the taxonomy into different menus.

Make a menu out of a specific branch of your vocabulary only.

Follow the active trail, also for nodes coupled to a term with a term reference field.


'access content' should be good in general, check it under "people/permissions" to seem if also anonymous users have right to "access content".
You can also declare:

_access: 'TRUE'

In this case you don't need the permission part, this one should definitely work!


I see that no one has put up an answer for quite a while, so I will put it up here. This has been correctly answered by RaisinBrainCrunch above.

Drupal 8 hashes its session ID before it puts it in the database. The hash function used is hashBase64($sid) under Drupal\Component\Utility\Crypt.

Therefore, I am guessing you will have to write the same function in Node. This is the full function:

public static function hashBase64($data) {
  $hash = base64_encode(hash('sha256', $data, TRUE));
  // Modify the hash so it's safe to use in URLs.
  return str_replace(['+', '/', '='], ['-', '_', ''], $hash);
}


Insert 'select all' choice in a particular level in Taxonomy Term Reference Tree Widget

Drupal have Taxonomy Manager module where all levels and terms have checkbox options and also add, edit, delete, move, functionality here.
Taxonomy Manager:

This module provides a powerful interface for managing taxonomies. A vocabulary gets displayed in a dynamic tree view, where parent terms can be expanded to list their nested child terms or can be collapsed.
For using the Taxonomy Manager you should have JavaScript and automatically load of images enabled in your browser.


Set default image when file not found (404)

Install and configure ImageCache Defaults module.

  ImageCache Defaults detects file paths in broken images (404 errors) generated by ImageCache (D6) and Image (D7). ImageCache Defaults can either remove images with broken paths from your markup completely or replace them with a configurable default image.


Spambots causing server crashes. How do I block them?

This is better solved at the Apache level.  The industry standard method for doing this is to create a honeypot directory, make it off-limits to bots in robots.txt, then logging the IP-address of those who still go there, and block it.

For an example of this, see the this page: http://www.kloth.net/internet/bottrap.php. You can set up this on shared hosting as long as you can edit .htaccess.

For a more sophisticated solution, take a look at Project Honeypot (NB: no relation to the Drupal Honeypot module).  There is already an Apache module which interfaces with Project Honeypot's IP blacklist. To install this, you ned to have access to the Apache config (usually not available on cheap shared hosting).

Edit: There already exists a Drupal module, http:BL, that uses Project Honeypot's IP blacklist, that may save you some time setting this up (thanks to @vr3690 for pointing this out).


How to add auto generate password link for admin?

You can used hook_user_presave() to get the changed password in your module:

function mymodule_user_presave(&$edit, $account, $category){
 echo $_REQUEST['pass']['pass1'];
}

and use the functions hook_mail() & drupal_mail() to send the email in hook_user_presave() with the changed password in $_REQUEST['pass']['pass1'].


Subscribe flag to auto-subscribe authors

For the Answers module (you know the dril: I'm a co-maintainer ...) to function, you must have the Rules module enabled also.

Therefor, have a look at this rule (in Rules export format, use the Rules UI to import it in your own site):

{ "rules_subscribe_question_author_automatically" : {
    "LABEL" : "Subscribe question author automatically",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "flag", "rules" ],
    "ON" : { "node_insert--answers_question" : { "bundle" : "answers_question" } },
    "DO" : [
      { "flag_flagnode" : {
          "flag" : "subscribe_answers_notifications",
          "node" : [ "node" ],
          "flagging_user" : [ "site:current-user" ],
          "permission_check" : "1"
        }
      },
      { "drupal_message" : { "message" : "You\u0027ve been subscribed to your own post automatically (use the unsubscribe link if that\u0027s not what you want)." } }
    ]
  }
}

For those who are not an expert in Rules-ese, this is what the above rule will do:

Rules Event: after saving a new node of type "Question".
Rules Actions:

flag that node by the user who created it, by the flag with machine name subscribe_answers_notifications (which by accident is exactly also what happens if a user manually clicks the "subscribe" link (below the question).
Show an informational message like "You've been subscribed to your own post automatically (use the unsubscribe link if that's not what you want)."

I think this Answers (oeps: answers) the question ... which was "... authors are automatically subscribed to those types of nodes that they author ..."

Notes:

in case some author does not want to be subscribed to a question author by that author, it is still possible to use the unsubscribe link  (typically bottom right below the question) after they created their question (node).
the above rule only applies to nodes of type "Question", though with a minor improvement you could as well make it work for type "Answer".


Multivalue field with Twig and its length

How to count in page or node template

content is the render array of the fields, that is build according to the view mode you have configured. The render array contains a lot of additional elements, that are not field items.

If you want to count the items in the field that are in the database, use the node object:

In php:

$node->field_banner_images->count();

In twig:

count() is not on the whitelist of allowed methods. Use .getvalue() instead, which gets the complete field array and count the array keys with the filter length:

{{ node.field_banner_images.getvalue|length }}

Better solution with field template

But you don't have to code the loop yourself in the node template, you can add the wrapper in the field twig.

Put the complete field in the node template:

{{ content.field_banner_images }}

And then put the wrapper in:

field--field-banner-images.html.twig

{% for item in items %}
    <span>{{ item.content }}</span>
{% endfor %}

You can remove the content of the field twig and replace it with the code above. You know the content of this field and you don't need the div containers, when you want span's.


How to install oAuth using PHP 7 and PECL OAuth library?

Well, while I have no final solution, since I humbled over the same issue 2 years later today, I can at least put some more light on it and help with some more tests, etc.

First things first: There is some bug tracking missing in your report.

What is php -m saying? It should list all recognized php modules. The pecl php extension oauth should be listed here. If not, check if you carefully followed the instructions printed on the terminal while installing sudo pecl install oauth. It says that you have to make sure that the line  extension=oauth.so is added to your php.ini. This is a standart recommendation which can also be translated to: make sure that oauth.ini is in .../php/mods-available and symlinked from .../apache2/conf.d/... to it to be recognized as a enabled module.

If not then check php-config --extension-dir to see where all your php .so extensions are really installed and then list them with ls -ahl to make sure that oauth has been compiled correctly.

Another thing to be aware of is that php comes in 2 modes: cli mode and server mode. Both can be mixed sometimes and can cause confusion since even Drupal mixes it all the time to check php extensions. Create a simple test.php file and put <? phpinfo(); ?> in it and run it as a local link in browser to check if OAuth is listed there somewhere (CTRL+F oauth). If it is listed it seems that only php cli does not recognize the extension and Drupal cannot find it. In this case repeat the step above (symlink) with the extension also symlinked in .../php/cli/conf.d/.... Then php -m would show the module recognized.

Finally, if you checked it all twice like me and found out that the oauth extension still doesn't load into your php/apache2 enviroment correctly or Drupal won't find it, you will stuck on the same level like me :) And I found out, that I am not allone. There seem to be a list of issues regarding this in the web (Google) OAuth making some trouble under php7.

But if you have checked twice that php AND(!) php-cli can find the module, you will be part of the 99% who made it work with Drupal finally then. Good luck.


This thread helped me understand the logic.

https://www.drupal.org/node/1784196

Basically what tobiasb said:

  OR (All conditions below this or between the lines are OR-Conditions)
  - condition1 (OR)
  - AND  (All conditions below this or between the lines are AND-Conditions, default condition)
  -- condition2 (AND)
  -- condition3

  This means:

  condition1 OR (condition2 AND condition3)