What to do when there are defined constans in a module and you need to change it

Is there another way of doing?

Depends where it's used. If the use is hardcoded into a function that doesn't offer any altering, then no, there's no other way other than a hack to change it.

Constants are constant, if they could be changed then they wouldn't be constant any more; if someone has used a constant they should have had a very good reason for doing so. So it's up to you to decide whether you trust the knowledge and design decision of the author. If you don't, don't use the module. Or change it to what you know is correct or reasonable.

At the very least, open an issue to ask the maintainer why they've hardcoded that value. There may have been a very good reason.


Creating dependencies between fields in content type creation form

If you are looking out to do this through code, you can use hook_form_alter to hide the dependent field and hook_node_presave to set the value for dependent field.


Unflagging (by rule) doesnt show rightaway

I am assuming you are using flag's javascript toggle to set these flags, and if that's correct, you could hook into flag's flagGlobalAfterLinkUpdate event and refresh the portion of the page where your flags are set.  More details are here:  http://drupal.org/node/336122.  If you don't want to do this, you could always set the flag link to a normal link, which would refresh the page for you in of itself.


How do I cache an object loaded through SOAP from a third party that I use in forms?

Would it not be possible for you to simply pass off the data you need in fields of #type => value? These are passed safely behind the scene through the entire form submission process, acting in a sense as the cache you are striving for.  Consider the following simplistic example :

$form['soap_data_email'] = array('#type' => 'value', '#value' => $soap_data_email);
$form['soap_data_name'] =  array('#type' => 'value', '#value' => $soap_data_name);

After submission, all your soap object's values would be available in the validation and submit callbacks of your form through the usual $form_state['values']['soap_data_email'] and   $form_state['values']['soap_data_name'] array.

If you have many variables this could all be factorised to be more efficient, but this should give you the basic idea.

This is the simplest way I can think of that lets you cache your data all across the form validation and submission process.


Yes this is possible. You will have to create two or more filter groups which will be separated with an OR condition.

Click "And/Or, Rearrange Filter Criteria" from the drop down menu of the Filters section and then click "Create New Filter Group". After that drag the filters you want in the new filter group and change the condition separating the groups to OR from AND. I would do it as follows:

1st group

Content: Published Yes And

Content: Type = News And

Content: Xyz (xyz) = Yes

OR

2nd Group

Content: Published Yes And

Content: Type = News And

Content: abc (abc) = Yes


Is there any File Manager Module for drupal 7

There are many modules available for managing files.

Reference URL : https://drupal.org/module-categories/file-management

Try this module : https://drupal.org/project/elfinder i think it suits your requirement.


Img tag getting removed in views drupal 8

I was using wrong image formatter . Instead of rendering the image the image tag was being rendered.


restrict a field's content based on a selected taxonomy term

option 1:
use a hook_form_FORM_ID_alter MYMODULE_form_node_form_alter(&$form, $form_state) to add an ajax functionality on the taxonomy change event and populates the number field default value depending on the form_state taxonomy value.

option 2:
Add your own javascript with taxonomy terms mapped to number values and when the taxonomy term changes, change the number values to the mapped value. This is pretty much same as above without requiring ajax.


How do I actually get a field value using field_view_value()?

You may have the field_view_value parameters wrong. Instead of the entity_type-> delta try loading the field first using field_get_items. Use the return value as the second parameter in field_get_items.

$node = node_load($nid);
$field = field_get_items('node', $node, 'field_name');
$output = field_view_value('node', $node, 'field_name', $field[$delta]);

I took that answer from the blog: https://www.computerminds.co.uk/articles/rendering-drupal-7-fields-right-way


How to group fields in the form without grouping them in the node view?

Found it. Turns out the array keys are very important. The first time around, I added the form fields to the fieldset without any keys. It started working just by adding the proper array keys to the fieldset, see the last revision.


Programatically Submitted Form With 'file' Field Throws Notice

ok, why are you not submitting a File (or FID) along with your form_state? I don't understand your problem, because I do this all the time (even with files).

Drupals file widgets usually use like Ajax to upload a file in the background and the form takes a FID in $form_state to process your forms if it has files attached.

When I asked you what the $form_state was I meant:

what are you sending to drupal.
what does drupal typically send as the $form_state when that form is sent through the user interface, because you're just trying to do that programmatically.

I dont think you know the answer to (2) above, because you cant get this to work right. You showed me what you're sending for (1). Here is a tutorial on using Firefox's Firebug plugin to view the submitted POST form state values for a drupal form. You want to drupal_form_submit form state to have the exact same parameters passed to it. In firebug you simply press Persist in the Net tab and you can capture URL requests.

So I'm saying goto the form in the website and submit it using your browser and Firebug to see what it expects to be passed.

You may ask how you get a FID for a file, you simply upload it using php before submitting the form and pass along its $file->fid. See this community documentation comment here how to do that.

You're just posting a simple HTTP Form, I really doubt Drupal is doing anything wrong.


It should be:

Proposal .* has been updated

and not

Proposal *. has been updated

What you want is

Proposal, space, any number of any characters, space, ...

But what you wrote is:

Proposal, any number of spaces, one of any character, space, ...


Try setting $output = array(); to $output = ''; and see if that fixes the issue. Also, I would recommend using views instead of custom SQL query while dealing with Drupal.

Views


Why user's rights has that impact on my Views pages?

I'm not sure if I understand your problem correctly but would say that if it works as planned for admin user then the issue is with permissions.

Check permissions like: view user profile, view [entity type] etc.


How to add an specific action button in views?

Here is the solution I found for my problem:
Let say that my entity is named Entity.
I created a new operation in my controller implementing my business logic ,  say we'll call it operation_name.
Then, in my EntityListBuilder.php , I surcharged the operation getDefaultOperations, specifying the name of my operation, the url and title :

 public function getDefaultOperations(EntityInterface $entity) {
    $operations = parent::getDefaultOperations($entity);
    $operations['operation_name'] = array(
        'title' => $this->t('operation_title'),
        'weight' => 30,
        'url' => new Url('url',array(
          'medecin' => $entity->id(),
          )
        )
      );
      return  $operations;
    }

Back to my view configuration: In adding fields section I will add "Action link" , we will notice that the operation "operation_name" was add to the others (edit and delete).


Private Message with node.js issues setting up

I had problems too. On line 3, for some reason using localhost never worked for me. Change line 3 to

"host":"panduh420.com",

Also, if your server has a firewall, make sure port 8989 is open.

Also, if you are not going to use https, then you don't need a key or cert.

here is mine

backendSettings = {
  "scheme":"http",
  "host":"mywebsite.com",
  "port":8080,
  "key":"/path/to/key/file",
  "cert":"/path/to/cert/file",
  "resource":"/socket.io",
  "publishUrl":"publish",
  "serviceKey":"",
  "backend":{
  "port":80,
  "host":"mywebsite.com",
  "messagePath":"/nodejs/message"},
  "clientsCanWriteToChannels":false,
  "clientsCanWriteToClients":false,
  "extensions":"",
  "debug":false,
  "transports":["websocket",
  "flashsocket",
  "htmlfile",
  "xhr-polling",
  "jsonp-polling"],
  "jsMinification":true,
  "jsEtag":true,
  "logLevel":1};


Composer: Dependency "drupal/core" is also a root requirement, but is not explicitly whitelisted. Ignoring

Composer remove removes the selected package and its dependancies. However there are, some dependencies like drupal/core that shouldn't be removed. For example, if we try to remove drupal/pathauto this message would pop up, as Drupal/pathauto depends on drupal/path core module, and should/can not remove anything from core or any dependencies shared with other packages. You can see in pathauto.info.yml file what it depends on.


How to use the path suffix in the Metatag page title?

The only token Pathauto provides is [node:url:args:join-path], the generated alias for the node. The suffix originates from, pathauto_alias_uniquify(&$alias, $source, $langcode), which Pathauto doesn't expose in any way; it's generated as needed to ensure the output alias is unique.

Theoretically, you could provide your a custom token that tries to find the value, but it would be error prone; pathauto isn't storing the suffix independently so there's no guarantee that a matched value is actually the suffix generated from Pathauto.

This is more of an editorial problem then a technical one. So a better solution would be to enforce unique titles at an authoring level.

For example, utilizing the Unique Content Title module to verify that each node title is unique upon submission.


How to copy view modes between content types in Drupal 8?

I had an ah ah moment when I found this page: https://api.drupal.org/api/drupal/core!includes!entity.inc/function/entity_get_display/8.2.x

You can write little scripts to update a field across many content types.  This can potentially save you hours on your Drupal 8 development!  We have a site with nearly 20 content types and let's say you want all of them be able to display with your new view mode, "card".  You've set it up on the article content type and now you need to copy it over.

I created this helper function as an example:

**
 * Utility function to copy a display mode from one entity bundle to another.
 *
 * @param $entity_type
 *   string Entity type to update.
 * @param $source
 *    string Source node bundle.
 * @param $target
 *    string Target node bundle.
 *  @param $view_mode
 *    string view mode to use.
 */
function my_module_copy_display_mode($entity_type, $source, $target, $view_mode) {

    $entity_view_display = \Drupal::entityTypeManager()
    ->getStorage('entity_view_display')
    ->load($entity_type . '.' . $source . '.' . $view_mode);

    if (empty($entity_view_display)) {
      return;
    }

    $items_to_copy = $entity_view_display->get('content');

    $new_entity_view_display = \Drupal::entityTypeManager()
    ->getStorage('entity_view_display')
    ->load($entity_type . '.' . $target . '.' . $view_mode);

    if (empty($new_entity_view_display)) {
      // If it can't load view mode on target type, create it.
      $values = array(
        'targetEntityType' => $entity_type,
        'bundle' => $target,
        'mode' => $view_mode,
        'status' => TRUE,
      );
      $new_entity_view_display = \Drupal::entityTypeManager()
        ->getStorage('entity_view_display')
        ->create($values);
    }

    $arr = $new_entity_view_display->toArray();

    foreach($arr['content'] as $field_name => $field_data) {
      $new_entity_view_display->removeComponent($field_name);
    }

    $definitions = \Drupal::entityManager()->getFieldDefinitions($entity_type, $target);

    foreach($items_to_copy as $key => $value) {
      // Check if they are in the entity field definition array.
      // This prevents adding fields that aren't on this content type.
      if (!empty($definitions[$key])) {
        $new_entity_view_display->setComponent($key, $value);
      }
    }

    $new_entity_view_display->save();
}

To use this, I wrote a secondary function with our site's content types:

/**
 * Copy a given view mode from article bundle to all other node types.
 *
 * @param $view_mode
 *   string View Mode to copy.
 */
function my_module_copy_view_mode_from_article_to_other_types($view_mode) {
  $source = 'article';

  $targets = [
    'car',
    'gallery',
    'video',
    'listicle',
    // etc.  put all the content types you want to copy to.
  ];

  foreach ($targets as $target) {
    my_module_copy_display_mode('node', $source, $target, $view_mode);
  }

}

Then, I just ran this second function from /devel/php, with a handful of view modes I wanted to make sure were consistent across all node bundles.

It's very fast, and what used to take half-an-hour of drudgery, dragging and dropping, is now very fast!

Update: Here's a drush version you can add to a custom module, it also allows you to just copy one field from a display mode to another display mode.

    <?php
/**
 * Implements hook_drush_command().
 */
function mymodule_drush_command() {
  $items = array();
  $items['copy_display_mode'] = [
    'description' => 'Copy display mode to another display mode. Example: "drush cdm node article clinical_trial three_up_item three_up_item"',
    'arguments' => [
      'entity_type' => 'Entity type to update',
      'source' => 'Bundle to copy from',
      'target' => 'Bundle to copy to',
      'source_view_mode' => 'View mode to copy from',
      'target_view_mode' => 'View mode to copy to',
      'field_to_copy' => 'Optionally, copy just one field',
    ],
    'callback' => 'mymodule_copy_display_mode',
    'aliases' => ['cdm'],
  ];
  return $items;
}

/**
 * Utility function to copy a display mode from one node bundle to another.
 *
 * @param $entity_type
 *   string Entity type to update.
 * @param $source
 *    string Source bundle.
 * @param $target
 *    string Target bundle.
 * @param $source_view_mode
 *    string view mode to copy.
 * @param $target_view_mode
 *    string view mode to copy to.
 */
function mymodule_copy_display_mode($entity_type = "", $source = "", $target = "", $source_view_mode = "", $target_view_mode = "", $field_to_copy = "") {

  if (empty($entity_type)) {
    drush_print('Missing entity_type. Type "drush help cdm" for arguments.');
    return;
  }

  if (empty($source)) {
    drush_print('Missing source. Type "drush help cdm" for arguments.');
    return;
  }

  if (empty($target)) {
    drush_print('Missing target. Type "drush help cdm" for arguments.');
    return;
  }

  if (empty($source_view_mode)) {
    drush_print('Missing sourced_view_mode. Type "drush help cdm" for arguments.');
    return;
  }

  if (empty($target_view_mode)) {
    drush_print('Missing target_view_mode. Type "drush help cdm" for arguments.');
    return;
  }

  $entity_view_display = \Drupal::entityTypeManager()
    ->getStorage('entity_view_display')
    ->load($entity_type . '.' . $source . '.' . $source_view_mode);

  if (empty($entity_view_display)) {
    return;
  }

  $items_to_copy = $entity_view_display->get('content');

  $new_entity_view_display = \Drupal::entityTypeManager()
    ->getStorage('entity_view_display')
    ->load($entity_type . '.' . $target . '.' . $target_view_mode);

  $updated = "updated";

  if (empty($new_entity_view_display)) {
    // If it can't load view mode on target type, create it.
    $values = array(
      'targetEntityType' => $entity_type,
      'bundle' => $target,
      'mode' => $target_view_mode,
      'status' => TRUE,
    );
    $new_entity_view_display = \Drupal::entityTypeManager()
        ->getStorage('entity_view_display')
        ->create($values);
    // Change verb for output to user.
    $updated = "created";
  }

  $arr = $new_entity_view_display->toArray();

  if ($field_to_copy == "") {
    foreach ($arr['content'] as $field_name => $field_data) {
      $new_entity_view_display->removeComponent($field_name);
    }

    $definitions = \Drupal::entityManager()->getFieldDefinitions($entity_type, $target);

    $output = [];
    foreach ($items_to_copy as $key => $value) {
      // Check if they are in the entity field definition array.
      // This prevents adding fields that aren't on this content type.
      if (!empty($definitions[$key])) {
        $new_entity_view_display->setComponent($key, $value);
        $output[] = ' -- ' . $key;
      }
    }

    $new_entity_view_display->save();
    drush_print("$entity_type.$target.$target_view_mode $updated from $entity_type.$source.$source_view_mode");
  }
  else {

    $definitions = \Drupal::entityManager()->getFieldDefinitions($entity_type, $target);

    if (!empty($definitions[$field_to_copy])) {
      $new_entity_view_display->setComponent($field_to_copy, $items_to_copy[$field_to_copy]);
      $output = [' -- ' . $field_to_copy];
    }

    $new_entity_view_display->save();

    drush_print("copied field $field_to_copy to $entity_type.$target.$target_view_mode from $entity_type.$source.$source_view_mode");
  }

  if (!empty($output)) {
    foreach ($output as $item) {
      drush_print($item);
    }
  }
}


Strange debug prints appear in the system log

That is what the Syslog module that comes with Drupal does. It is not enabled by default, but enabling it will cause what you are noticing.
The module doesn't have its own settings to disable logging the messages into the system logs; to stop that, just disable the module. Since you are not going to use it anymore, you can then uninstall it. (Don't delete its files, since they are copied every time you update Drupal.)


how to access configuration module from service

To read the variables (configs) you'd do this:

$config = \Drupal::config('modulename.my_service');

$core_port = $config->get('modulename.core_port');

To write to the variables (configs) you'd do this:

// Set and save new message value.

$config = \Drupal::service('config.factory')->getEditable('modulename.my_service');
$config->set('modulename.core_port', 153760)->save();

There's an example you can look at in the core module aggregator.

It has a settings form at /core/modules/aggregator/src/Form/SettingsForm.php

and then it adds a route to access the settings form:

aggregator.admin_settings:
  path: '/admin/config/services/aggregator/settings'
  defaults:
    _form: '\Drupal\aggregator\Form\SettingsForm'
    _title: 'Feed aggregator settings'
  requirements:
    _permission: 'administer news feeds'

You could pretty much copy the form into your module and change the variables to match your config.

Generally you'll want to add the config in your service constructor.

namespace Drupal\modulename;

/**
 * Example Service with config.
 */
class MyService {

  /**
   * Drupal's settings manager.
   */
  protected $settings;

  /**
   * Constructor.
   */
  public function __construct() {
    $this->settings = \Drupal::config('modulename.my_service');
  }

}

Then you'd access the variables like this:

$this->settings->get('modulename.core_port');


There are 2 points here.

SET @x := 5,SET @y := 6, SELECT * from mytable" should be "SET @x := 5,SET @y := 6; SELECT * from mytable

as

SET @x := 5,SET @y := 6;" and "SELECT * from mytable

are 2 separate MySQL statements.

You can not execute multiple statements together using db_query(). Since the PHP functions mysql_query() and mysqli_query() can only execute one SQL statement, the db_query() wrapper can also only execute one SQL statement.

What you can do here is, divide that into two part and run it.

db_query('SET @x := 5,SET @y := 6;')->execute();
db_query('SELECT * from mytable')->fetchAll();


What is the entity ID for private messages?

It turns out mid is correct, but for whatever reason $row['mid'] was returning a string, not an int.  Type-casting the string as an int solved the problem.


How to save a free text views query entered into an exposed filter by the user?

Use hook_form_alter and add an extra submit handler:

$form['#submit'][] = 'my_callback';

In your callback function use node_save to save the values you extracted from $form_state['values'];


Behaviors are only called the first time a view is loaded

Your "once()" function is called on an element with an ID. If your HTML is valid there can be only one such element in the DOM.

What happens with the once() function is that it adds a class to the element which marks it as processed. If the once() function is called again on the same element, it will do nothing. So looking at your code, it does indeed seem it will call the each() function just once on first loading, then never again.

It is right to use the once() function in this situation but you probably want to use a selector representing the children that can be dynamically created. I can't really advise what that should be without seeing the actual HTML.


Author information lost after saving node

That sounds strange and like a sideeffect. I would try do debug this using the devel-module. Write a Module and print (with dsm) the $node inside hook_nodeapi. Inspect the content in subject to the operation ($op). Maybe do this two times with diffrent module weights (-1000, 2000) to see if any hook_nodeapi implementation of another module fails.


Show step-by-step dialogs for helping user with using the site

The modules chrischarlton suggested were fine, but those are unsupported and not maintained.

I recommend using the Boostrap tour module. With this module, you can show popups step-by-step, attach the popups to HTML elements in each step, save the progress of the user, and let the user add feedback to the tour. However, you need to have a boostrap based theme in order to make it work.


Exposed filter value into the session and cookie?

There is a setting in the "Configure filter criterion" form.

Test this one. I guess it will write a cookie for the user.


How to show a view inside another view on only first row?

I'm not sure if Views nodes split module will be useful for your situation as @DnBase mentioned.

However, because you're using Views Field View; you can follow the following steps to achieve what you're looking for:

Edit field view actual view (referenced view)
Add Global: Null from CONTEXTUAL FILTERS menu

From the next dialog box that appear, select Hide view from WHEN THE FILTER VALUE IS NOT AVAILABLE fieldset.
Then from WHEN THE FILTER VALUE IS AVAILABLE OR A DEFAULT IS PROVIDED fieldset, check Specify validation criteria and select PHP Code from validator dropdown menu
Then add the following code in PHP Validate code field
From Action to take if filter value does not validate dropdown menu select Hide view

Code:

if($argument == 1) {
  return TRUE;
} else {
  return FALSE;
}

Now edit the main view
Add Global: View result counter from FIELDS menu, then from field configuration dialog box, check Exclude from display
Then edit Global: View field, from field configuration dialog box, add this replacement pattern [%counter] into Contextual filters field

By applying these steps, you'll notice that view field will only appear on first item.


Validation error on term-reference field when ajax'd option is submitted?

Drupal checks the integrity of the form to make sure submitted values match up with the available options when the form was built; it's a security feature. Manipulating the form on the client-side, without informing the backend that something has changed, causes the integrity check to fail.

Rather than work around it (which is possible but messy), I'd recommend using the AJAX functionality already built into the form API.

The AJAX Forms in Drupal 7 page, FAPI AJAX reference and the AJAX Example in the Examples module are excellent resources for learning about this.


Adding a validation handler in hook_form_alter() is the Drupal 7 method of adding validation for a field. It will still work in Drupal 8, however the preferred method of adding validation to Field API Field in Drupal 8 is to add a Constraint to the field. Constraints will be applied when the Node is created, no matter the means of creation. Adding a validation handler to the form only validates the field when the node is created using the Form API - IE through a browser. If a node is created by any other means - IE through an API or programatically, the validation is not applied. Constraints are applied no matter the method of creating the node.

Documentation on how to add a constraint can be seen here: https://www.drupal.org/docs/8/api/entity-validation-api/providing-a-custom-validation-constraint

See Method 2 - adding constraints to fields added to an entity you haven't defined, or fields added through the UI


Commerce 2.x multicurrency / multiprice setting

The https://www.drupal.org/project/commerce_currency_resolver module will help you do this.


Drupal Custom Login Page Using Zen Sub-theme

I think your problem is that you're confusing the login block with the login page in the preprocess function and tpl names

try

function Alphasys_preprocess_user_login(&$variables) {
  //a capitalized theme name?
  $variables['rendered'] = drupal_render($variables['form']);
}

then change the

$hooks['user_login_block']

to

$hooks['user_login']

and drop in your print statement into the tpl

<?php print $rendered ?>

and you should be good to go


Views - create relationship on relationship?

As I understand you don't really need taxonomy here. Instead you can reference Book node to Writer node directly.
Of course, you can solve the problem without modifying your current structure. I will show how to create such View using Entity reference as referencing field. I recommend this module for creating references in Drupal 7 as it is powerful and stable.

First, create new View for Books content type:

Add relationship to taxonomy term:

Now you can add one more relationship to Writers nodes. Here Entity reference comes into play:

Now you can output all you want from Book node, from relative taxonomy term or from relative to that term Writer node. Just select appropriate relationship to use:

Here I added title from Writer node and excluded it from display.
You may want to group output by writer and it can be done in Format settings:

If you didn't use unnecessary dictionary, you would not need the second step.

About a year ago I started with NodeOne series Taming the Beast: Learn Views with NodeOne and Using the Reference modules by Johan Falk and I hope this information will help you too.

Done with love to Isaac Asimov.


How to theme maintenance page for omega subtheme?

There's always a parent template, even if you don't see it in your base_theme.

The inheritance will go:

omega_subtheme template of NAME
then omega template of NAME
then drupal core template of name

So you'll need to copy the drupal core templates. They can be found in

DRUPALROOT/modules/system

You can find page.tpl, maintenance-page.tpl.php and all the base templates.


You can use arg to check for URL arguments. In your case, the second argument has to be empty, so you can try something like this:

if (arg(0) == 'displayimg' && arg(1) == 'mypage') {
  // Do something meaningful.
}


What do I use as URL path in a template file?

In Views, you need to add Path as a field, which you probably already have, and you can print it like this:

{{ fields.path.content }}

so

{{ 'Learn More'|t }}


Found it out after a lot of trial and error. Basically it comes down to breaking everything up into individual "pseudo fields" and prepare the data before processing it into the actual field:

process:
  # First convert legacy wine id's to regular string names in a pseudo field
  _prepare_wines:
    -
      plugin: explode
      limit: 100
      delimiter: ","
      source: wines
    -
      plugin: static_map
      map:
        '1': 'Sauvignon Blanc'
        '2': 'Chiraz'
        '3': 'Pinot Noir'
        '4': 'Malbec'

  # Secondly convert legacy soda id's to regular string names in a pseudo field
  _prepare_sodas:
    -
      plugin: explode
      limit: 100
      delimiter: ","
      source: sodas
    -
      plugin: static_map
      map:
        '1': 'Coca-Cola'
        '2': 'Spa'
        '3': 'Sprite'
        '4': 'Tonic'
        '5': 'Bitter lemon'

  # Third, get all the pseudo field output together in a new pseudo field and flatten them into a single array
  _prepare_field_drinks:
    -
      plugin: get
      source:
        - '@_prepare_wines'
        - '@_prepare_sodas'
    -
      plugin: flatten

  # Lastly, the data is now all in a nice single level array with only names for the new taxonomy terms so we can use those as source.
  field_drinks:
    -
      plugin: entity_generate
      entity_type: taxonomy_term
      bundle_key: vid
      bundle: drinks
      value_key: name
      source: '@_prepare_field_drinks'

Disclaimer: I'm not sure if this is the way it should be handled, but it seemed to do the trick without any custom plugins. Also, please be aware that if any of the source fields can be empty, you should prepend a skip_on_empty plugin to make sure your rows will not be ignored.


Fatal error: Call to undefined function menu_load_all()

The only thing I can of is that you're calling menu_load_all() in hook_install() or hook_enable(); all system module files aren't necessarily included when those hooks are invoked.

If that's the problem, you can force the file with the function to be included by adding the following line of code to the top of your hook_enable()/hook_install() function:

module_load_include('module', 'menu');


How to set up a train schedule content type in Drupal 7?

This post is pretty old at this point, so it may no longer be an issue for you, but I'll try to answer it anyway.

The type of solution I'm imagining for this is what the Double Field module sounds like it does (though I cannot be certain since I have never used it). If this module would be able to do it, you'd want a field with taxonomy with a Date field to select the stop and time of that stop (and then be able to have multiple values for this field so you can select multiple stops and their times).

Otherwise, you could use Taxonomy if the trains have set times that they arrive (like they always arrive on the hour, quarter after, etc.). Otherwise, yeah, it wouldn't be realistic to use that if they can arrive at 12:53, 3:38 - if any time is possible.


weird error - failed to open stream - .module file in theme path?

There are a custom module and custom theme with the same name - activit

That's what causes the problem. Module and theme names need to be unique amongst one another. Drupal doesn't support duplicate names, and weird things can happen if you go against that.

See Module/theme name collision for more information.


How to create a field that references a Views Block display in D8?

Things are confusing because that's how entity reference works. All those things are entities, so they are technically referencable. As you found, block are actual block placements, which is not what you want. And view doesn't allow to select the display, so for your case, that's also not what you want. Drupal 8 core simply can't do that without custom code or a module (yet).

You either need a contrib module like Viewfield, but that doesn't have an official 8.x release yet. The blue box points to the contrib tracker issue, which in turn points to https://www.drupal.org/node/2220929, which has a link to a github repository where someone did an initial port. If and how well that is working already, I can't say.

An approach that would require a bit of custom code would be to have a list field with a few options ( since you don't want to allow all views anyway..), and based on that, there needs to be a bit of code that loads and calls the view and displays the results.


Send email to users, except author comments

You can install Rules Conditional module, which will give you an option to run conditional logic inside a Rules Action, in your case related to the loop that you created.

So, you'll do a check in the loop as follows:

IF comment:author:mail NOT EQUAL users:mail THEN send email


You're right, that is overly complex.

First of all, make sure your mytheme_preprocess_page() function is actually getting called by adding print & then exit statements. If it's not getting called, clear your theme registry by clearing the site's cache.

Once you're sure the preprocessing function is getting called, this will do the trick for you:

if (preg_match('#user/register#', $_GET['q'])) {
  drupal_add_css(drupal_get_path('theme', 'mytheme') . '/style.css');
}

$_GET['q'] always contains the 'internal' Drupal path, not the alias. The internal path for the normal registration form is user/register, so that's what you want to check for.


This is a field themeing issue.  The field.tpl.php API docs and linked source is a good place to start.  The comments on that page also have useful information for you.


Try below code... You can read node arguments using arg function in Drupal...

global $user;
$flag = flag_get_flag('purchase');
$node = node_load(arg(1));
$flag->flag('purchase', $node->nid, user_load($user->uid), TRUE);


As @codesmith mentioned it looks like you have some issue with the Aggregator module but, usually you might also see other problems once you fix the aggregator module issue. The reason you see the issue on aggregator_feed is that it is the first table in your table list.

In case you are lucky and the issue is only on the aggregator module use the query below to recreate the missing tables (I am providing the two tables that are created when you install aggregator module).

CREATE TABLE `aggregator_feed` (
`fid` int(10) UNSIGNED NOT NULL,
`uuid` varchar(128) CHARACTER SET ascii NOT NULL,
`langcode` varchar(12) CHARACTER SET ascii NOT NULL,
`title` varchar(255) NOT NULL,
`url` varchar(2048) NOT NULL,
`refresh` int(11) DEFAULT NULL,
`checked` int(11) DEFAULT NULL,
`queued` int(11) NOT NULL,
`link` varchar(2048) DEFAULT NULL,
`description` longtext,
`image` varchar(2048) DEFAULT NULL,
`hash` varchar(255) CHARACTER SET ascii DEFAULT NULL,
`etag` varchar(255) DEFAULT NULL,
`modified` int(11) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='The base table for aggregator_feed entities.';

and the second table

   CREATE TABLE `aggregator_item` (
  `iid` int(10) UNSIGNED NOT NULL,
  `langcode` varchar(12) CHARACTER SET ascii NOT NULL,
  `fid` int(10) UNSIGNED DEFAULT NULL COMMENT 'The ID of the target entity.',
  `title` varchar(255) DEFAULT NULL,
  `link` varchar(2048) DEFAULT NULL,
  `author` varchar(255) DEFAULT NULL,
  `description` longtext,
  `timestamp` int(11) NOT NULL,
  `guid` longtext
  ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='The base table for aggregator_item entities.';


Linking organic groups - or am I overlooking a better solution?

I have not played around with og much but from what you are saying this should be possible with rules. Basically you would create an event based on the change (perhaps create a group admin role only flag which lets them flag each other to create the bond and the trigger. That way if one breaks the bond, the permissions are reversed which would require an extra but similar rule) that would trigger an action to load a list of users from the group. Then add a loop to loop through the list of users performing an action on each one as you go (i.e. add to other group). Not sure what custom actions og brings to rules or vice versa but I see no reason why it shouldnt be possible this way.


Get unzip for windows:
http://gnuwin32.sourceforge.net/packages/unzip.htm
It solved the "unable to unzip" problem for me.


How do I create a node using web services and Anonymous user?

I have posted to /node and it works for anonymous after granted that permission and cleared cache by the way you don't have to set the field uid and it's not necessary if you set

  $request_url = 'domain/endpoint/node';

// Node data
$node_data = array(
  'title' => 'product testing',
  'type' => 'product',
    "uid" => 0,
    "language" => "en",
    "sticky" => 0
);
//$node_data = http_build_query($node_data);
$data = json_encode($node_data);

// cURL
$curl = curl_init($request_url);
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
    'Content-Type: application/json')
);
curl_setopt($curl, CURLOPT_POST, 1); // Do a regular HTTP POST
curl_setopt($curl, CURLOPT_POSTFIELDS, $data); // Set POST data
curl_setopt($curl, CURLOPT_HEADER, FALSE);  // Ask to not return Header
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($curl, CURLOPT_FAILONERROR, TRUE);

$response = curl_exec($curl);


How to create a confirmation page linking to the content just created by a user

use Rules module http://drupal.org/project/rules, you can build a new rule to redirect (to a new page) the user when create, for example, a node. see examples to Drupal 6 http://drupal.org/node/298483 or Drupal 7 http://drupal.org/node/878712

specifically, I suggest that you review events like 'After saving new content' or/and 'After updating existing content' , then you can launch  task (or add conditions to the task and lauch the task) according your needs. Seems that 'Page redirect' Action can be useful.


Printing fields in theme: Undefined index: safe_value

The problem is with your function, not the template.

Ideally you should check if the index exists, e.g.

print array_key_exists($format, $field[0]) ? $field[0]["$format"] : '';

or:

print !empty($field[0]["$format"]) ? $field[0]["$format"] : '';

or:

print @$field[0]["$format"] ? $field[0]["$format"] : '';

Alternatively you can ignore the notices in PHP config (php.ini) or in Drupal admin.

Or you can just prefix the field with @ to silence/suppress any errors (usually not recommended), e.g.

print @$field[0]["$format"];


Why is form submit handler not called when calling form_set_error?

submit handlers are only invoked if there are no validation errors. Calling form_set_error() results in a validation error.

From the quickstart guide that you linked:

1. A submit function is called only if a submit button was present and exists in the $_POST, and validation did not fail.


Including views in tpl is going backwards. Drupal allows you to use views as pages and as blocks. You can apply templates to that pages and blocks, and you can put blocks in regions. By calling views from template, you are messing with theme registry and cache logic. It might be not an issue if site is small, and both read and write volumes are low, but it will result in pages being out of sync on heavy loaded site.

Instead of outputting view directly, make a region, output it in template file, and put a views block inside.

Using views_embed_view in a preprocess function in template.php might be OK. Opinions and experience with it can vary, and I would try to avoid it, but certainly it does not mess with cache or theme registry like using it in tpl would.


hook_page_attachments() not called from mytheme.theme file

It appears that this function is only callable from a module, as it is listed in  Adding stylesheets (CSS) and JavaScript (JS) to a Drupal 8 module but not listed as a valid method in Adding stylesheets (CSS) and JavaScript (JS) to a Drupal 8 theme.

It should be noted that the related function hook_page_attachments_alter() can be called from the theme layer (i.e. can be called from mytheme.theme file).

function mytheme_page_attachments_alter(&$page) {
  $page['#attached']['library'][] = 'mytheme/general-js';
}

Alternatively one can attach libraries to a page from within hook_preprocess_page()

function mytheme_preprocess_page(&$variables) {
  $variables['#attached']['library'][] = 'mytheme/cuddly-slider';
}

The advantage of these two methods is that it enables one to utilize logic/code to determine whether or not to attach a library to a page.


How to use hook_views to add calculation to a field?

Finally, after some (!!) digging, I did it in assoc_views_post_execute

function assoc_views_post_execute(ViewExecutable $view)
{
  switch ($view->id()) {
    case 'assoc_persons':
      if ($view->current_display == 'page_1') {
        $database = \Drupal::database();
        foreach ($view->result as $key => $value) {
          $person = $value->_entity->get('id')->value;
          $solde = $value->_entity->get('balance')->value;

          some code to calculate credit with database query
          $credit = $result[0]->credit;

          some code to calculate debit with database query
          $debit = $result[0]->debit;

          $solde = $solde + $credit - $debit;
          $value->_entity->set('balance', $solde);
        }
      }
      break;
    default:

  }
}


What if a rule doesnt fire or is interrupted because of server down etc?

To my knowledge there is no such thing as "make sure a rule will always execute?" (as in your question). However, by using the Message module, you can create your own custom "Events logging" (to register things that happened in a site).

A great sample of this you can find in Commerce Kickstart, which uses the Commerce Message module, to create such "Events logging". In this case in the format of an Order History, as shown in this screenprint (from this module's project page).

So in your case, if you'd create an appropriate events logging of all sorts of Rules related Events that you're interested in (= are critical enough?), then at least you'd have appropriate data you can use to investigate if anything went wrong.

To actually do so, for any of your Rules, you could add these Rules Actions to them:

create a "Start Rules Action"-message (as the very first action).
create a "Stop Rules Action"-message (as the very last action).

With that, for any set of Rules Actions that started executing, you can check if you have 2 corresponding messages.

Here is a variation that might work also: instead of creating such "Stop Rules Action" message, you could also use the Flag module to flag the corresponding "Start Rules Action" (the Message module creates messages as entities, so you can flag them for sure). Such flagging would indicate that the set of Rules Actions completed without problems. And to list all the groups of Rules Actions that were interrupted, you'd just have to use the Views module to report about all  "Start Rules Action" messages that were NOT flagged ... Piece of cake, no?

Attention: this covers the part related to Rules Actions, not (yet) something like "what are all Rules Events that were triggered but for which not even 1 Rules Action (= create the start-message) had started (because of some kind of interruption).


Drupal 8 Commerce 2 Trigger custom mail to product author

This is described in the Commerce 2 documentation:

  In our case we want to send the email after the transition to the
  Fulfillment state has occurred. We therefore need to create an event
  subscriber that listens to the commerce_order.fulfill.post_transition
  event.

// my_module/src/EventSubscriber/OrderFulfillmentSubscriber.php

    namespace Drupal\my_module\EventSubscriber;

    use Drupal\state_machine\Event\WorkflowTransitionEvent;
    use Drupal\Core\Language\LanguageManagerInterface;
    use Drupal\Core\Mail\MailManagerInterface;
    use Drupal\Core\StringTranslation\StringTranslationTrait;
    use Symfony\Component\EventDispatcher\EventSubscriberInterface;

    /**
     * Sends an email when the order transitions to Fulfillment.
     */
    class OrderFulfillmentSubscriber implements EventSubscriberInterface {

      use StringTranslationTrait;

      /**
       * The language manager.
       *
       * @var \Drupal\Core\Language\LanguageManagerInterface
       */
      protected $languageManager;

      /**
       * The mail manager.
       *
       * @var \Drupal\Core\Mail\MailManagerInterface
       */
      protected $mailManager;

      /**
       * Constructs a new OrderFulfillmentSubscriber object.
       *
       * @param \Drupal\Core\Language\LanguageManagerInterface $language_manager
       *   The language manager.
       * @param \Drupal\Core\Mail\MailManagerInterface $mail_manager
       *   The mail manager.
       */
      public function __construct(
        LanguageManagerInterface $language_manager,
        MailManagerInterface $mail_manager
      ) {
        $this->languageManager = $language_manager;
        $this->mailManager = $mail_manager;
      }

      /**
       * {@inheritdoc}
       */
      public static function getSubscribedEvents() {
        $events = [
          'commerce_order.fulfill.post_transition' => ['sendEmail', -100],
        ];
        return $events;
      }

      /**
       * Sends the email.
       *
       * @param \Drupal\state_machine\Event\WorkflowTransitionEvent $event
       *   The transition event.
       */
      public function sendEmail(WorkflowTransitionEvent $event) {
        // Create the email.
        $order = $event->getEntity();
        $to = $order->getEmail();
        $params = [
          'from' => $order->getStore()->getEmail(),
          'subject' => $this->t(
            'Regarding your order [#@number]',
            ['@number' => $order->getOrderNumber()]
          ),
          'body' => $this->t(
            'Your order with #@number that you have placed with us has been processed and is awaiting fulfillment.',
            ['@number' => $order->getOrderNumber()]
          ),
        ];

        // Set the language that will be used in translations.
        if ($customer = $order->getCustomer()) {
          $langcode = $customer->getPreferredLangcode();
        }
        else {
          $langcode = $this->languageManager->getDefaultLanguage()->getId();
        }

        // Send the email.
        $this->mailManager->mail('commerce_order', 'receipt', $to, $langcode, $params);
      }

    }


How to make subprocess & migration_lookup plugins behave consistently with single and multiple items arrays

This is just guessing, but you could try forcing the multiple flag on the source field using the multiple_value plugin from Migrate Plus:
field_behaviour:
  -
    plugin: multiple_values
    source: behaviour_array
  -
    plugin: sub_process
    process:
      target_id:
        plugin: migration_lookup
        migration: import_behaviours_json
        source: name


commerce_order_status_update() doesn't update the order status

It sounds to me like you're updating the order to completed before the checkout completion rule fires that updates the order to pending. You can confirm this by looking in your revision log for the order in question.

If I were you, I'd just add a condition to that default checkout completion rule to not update the order status if it is already completed.


Content type template only for viewing, not editing

This was the most convenient variable I found in the $variables array to check whether I was viewing or editing

function THEMENAME_preprocess_page(&$variables) {
  $is_editing = isset($variables['page']['content']['system_main']['#node_edit_form']) && $variables['page']['content']['system_main']['#node_edit_form'];

  if( !empty($variables['node']) && !$is_editing ) {
    $variables['theme_hook_suggestions'][] = 'page__node__' . $variables['node']->type;
  }
}


How to create a clickable area on the whole block view?

Use CSS and custom template structure...

Markup:

    // Your various markup.
    {{ content }}
    // Link contains no text and is absolute positioned to cover the entire markup area.

    // The span can be absolutely positioned as well so it is on top of the link.
    This is a flag

CSS:

.views-row {
    position: relative;
}

a.link {
    display: block;
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    z-index: 100;
}

span.flag {
    position: relative;
    z-index: 200;
}

With this approach, you will avoid having a link that contains a lot of text and markup that makes no sense to browsers and screen readers.


Render array value empty for Datetime field

The solution was $item['value']['#default_value']->render(). This outputs the value in the following format Y-m-d H:i:s e.

Alternatively, calling format('Y-m-d') or any other format string will update accordingly

because '#default_value' was of type DrupalDateTime which must not implement jsonSerialize this is why I was getting and empty object for a value when dumping out as JSON.


You can Use Image style before save the node.

$original_image = 'public://images/image.jpg';

// Load the image style configuration entity.
use Drupal\image\Entity\ImageStyle;
$style = ImageStyle::load('max_2600x2600');

$uri = $style->buildUri($original_image);
$url = $style->buildUrl($original_image);

Here some links may helps you

Drupal 8 - Create an Image and ImageStyle Programmatically

Drupal 8 images with image style

Flexible image style system


Handling anonymous orders in custom commerce module

Perhaps you could use PHP's session_id()?

  session_id() is used to get or set the session id for the current session.

Basically copied from this answer.

You may also find useful information here: Anonymous Personalization Without Leaving Drupal, which appears to be a topic from DrupalCon Seattle 2019.


Drush does not work invoking the local Drush

This Drush issue has been fixed in the recent version (8.1.5 and above) by refactoring how the code was using Phar class.

Here are updated steps how to install Drush using phar (as per install.md):

# Download latest stable release using the code below or browse to github.com/drush-ops/drush/releases.
php -r "readfile('http://files.drush.org/drush.phar');" > drush
# Or use our upcoming release: php -r "readfile('http://files.drush.org/drush-unstable.phar');" > drush

# Test your install.
php drush core-status

# Make `drush` executable as a command from anywhere. Destination can be anywhere on $PATH.
chmod +x drush
sudo mv drush /usr/local/bin

# Optional. Enrich the bash startup file with completion and aliases.
drush init

Or by the following one-liner:

sudo install <(curl http://files.drush.org/drush.phar) /usr/local/bin/drush


This can have a whole bunch of reasons. I'm just providing the imho most probable non-obvious one:

Go to "pager settings" (on your screenshot click "Paged, 5 items") and change the "pager id". Docs say this is only needed when there is more than one view on a page, but i saw live examples where this fixed a non-showing pager on a single-view page.


Modifying Field Values for a Custom Content Type?

I just checked a select list I have on a site with text key|value pairs under 'Allowed Values'. Although I had the message at the top that 'There is data for this field in the database. The field settings can no longer be changed.' I went ahead and altered the list, and it took the changes fine.

There should be no impact on the existing data if you change the order. Just be careful you never delete a value.


How to make my mobile app to work more faster when web services made from drupal7 REST services

I'm used to create my own resources / module then i can send all the information i need with custom query / joins, following the next tutorial:

http://drupal.org/node/1246470

Also on my module i could enable cache etag and then programming on mobile device the http client with etag support.


How to make private (hidden) node path aliases?

There is different solutions

https://www.drupal.org/sandbox/ajlee/2109425 (disable access to nodes through the "normal" URL such as node/123)
https://www.drupal.org/project/access_unpublished (key to give view access to unpublished node)
https://www.drupal.org/project/node_authlink authorization key for every node and gives additional grants (view/edit/delete) to every user (anonymous too) who accesses page with correct key in URL


In Drupal 6 you can alter the system modules uninstall form.

function MYMODULE_form_system_modules_uninstall_alter(&$form, &$form_state) {
  if (isset($form['modules']['MYMODULE'])) {
    //alter form how you would like
  }
}

The only change for Drupal 7 is there is an additional function argument

6       hook_form_FORM_ID_alter(&$form, &$form_state)
7 – 8   hook_form_FORM_ID_alter(&$form, &$form_state, $form_id)

NOTE: This form gets call on the /admin/module/uninstall & /admin/module/uninstall/confirm.   If you just want it on one then add an additional case to the if statment, checking the path.


ctools export_api question: ctools_export_crud_load vs ctools_export_load_object

ctools_export_crud_load():

  Load a single exportable object.

ctools_export_crud_load_all():

  Load all exportable objects of a given type.

ctools_export_load_object():

  Load some number of exportable objects.

The first two are just shortcut functions to ctools_export_load_object() (with a bit of setup logic) ctools_export_load_object() is a more complicated function that can filter the required exportables by various criteria. The main point of interest as I can see it is that the first two accept a $reset parameter to reset the exportable(s)'s caches, whereas ctools_export_load_object() doesn't accept that parameter.

Basically, I'd say if the exportables you need to load can't be queried by using ctools_export_crud_load() or ctools_export_crud_load_all(), then use ctools_export_load_object(). Otherwise use one of the former functions, as they handle some of the necessary setup for you.


To captcha protect a webform you NEED to add a captcha element to it. When captcha contrib module is enabled on your site the available captcha challenge types are available to be used on a per webform basis.

The template twig file is mostly for design puproses.

If the placement of captcha within the form is not to your liking you should copy the default webform template from /modules/contrib/webform/webform.html.twig to your theme /themes/custom/MYTHEME/templates/webform--WEBFORM_MACHINE_NAME.html.twig and perhaps place each element seperately.

The default webform.html.twig is

<form{{ attributes }}>
  {{ title_prefix }}
  {{ children }}
  {{ title_suffix }}
</form>

And in our own copy we should take out {{ children }} and replace with individual elements but also we have to make sure form ids and actions are included manually and it the final template should end up looking similar to this

<form{{ attributes }}>
  {{ title_prefix }}
  {{ element.elements.first_name }}
  {{ element.elements.last_name }}
  {{ element.elements.captcha }}

  {# necessary elements #}
  {{ element.form_build_id }}
  {{ element.form_id }}
  {{ element.actions }}

  {{ title_suffix }}
</form>

Where captcha for example is the machine name of the captcha field


How to find out if a Rule is successfully executed or not?

Try enabling debugging in rules->settings.
Hope this will help you in finding the execution of action


How to add AJAX call back from another AJAX result in a form

You are adding form elements in the ajax callback. These will never work, as the form has already been cached before the ajax callback is reached. You need to add your form elements in the original form definition, or a _form_alter hook. Use values in the form state to determine whether or not the form has already been submitted.


Drush make: "Found makefile: myfile.make. Aborting"

Have you tried this recently?  It's hard to tell from the info you posted above, but your problem could very well have been caused by the ssl certificate problem on updates.drupal.org.  Since sometime yesterday until a few hours ago, https connections to updates.drupal.org were failing due to a limitation of the new CDN they are using now.  This caused drush dl and drush make to fail.  (n.b. Drush caches update information, so things likely continued to work from the cache on systems that were working before the cert problem started.)

The drupal.org team has things patched up now, so try doing everything again from the beginning, and see if it starts working again.  If that does not clear up the problem, try running drush make again with the --debug option, and post the results.


Field Max Size limited to 10 for Integer in Number Module

Maximum number that Number module can hold is 2 147 483 647 (231 - 1), because of the size of SQL INT datatype. For larger numbers you must use string field or Bigint module, that allows to storing numbers up to 9 223 372 036 854 775 807 (263 - 1).


Drupal Commerce: Alter 'Checkout' link in user menu

Use this function in your custom module to return a bool for determining if there items in the basket/cart.

function items_on_cart(){
global $user;
$cart = commerce_cart_order_load($user->uid);
$line_items = count($cart->commerce_line_items) ? true : false;
return $line_items;
}

Then in your theme template do the following...

function YOURTHEME_menu_link(array $variables) {

    $element = $variables['element'];
    $sub_menu = '';
    $name_id = strtolower(strip_tags($element['#title']));

    // add class to checkout link if basket active
    if ($name_id == 'checkout') {
        if (YOURMODULE_items_on_cart()) {
          $element['#localized_options']['attributes']['class'][] = 'active';
        }
    }


Call to undefined function field_attach_load() on a newly migrated site

I had this same problem today and I fixed it by simply running the update script:

The update script is located in the root folder of your Drupal 7 install.
eg.

  www.mynewlymigratedtoserver.com/update.php

One other thing you should probably know, you have to be logged in to run the update script, you can login right? No, you can't! That's ok, there's a work around.

In your settings.php (usually /sites/default/settings.php) there is a line (231 for me) that says this:

  $update_free_access = FALSE;

This variable determines if the update script can be used by anyone, not just logged in people. Set it to TRUE and you'll be able to run the update script. You'll want to set it back to false when you're done.

If that didn't work try this


hook_user_update : Modules may use this hook to update their user data in a custom storage after a user account has been updated.

So that hook is call only when you edit the user account. other things is disable you module which implement this hook.

Morever if you want to edit the role every time when user is created/edited use hook_user_presave.


I would not expect any performance problems on a site with 30 different content types. Nevertheless I wouldn't recommend implementing a scheme like you are intending. Should you come into the situation where you have to add a new field or change field/display settings, it will require you to go over all blog-types.

In order to simplify the creation of new content for your authors, I recommend to create shortcut links where the term-id of the blog is passed by an url parameter. You may use the Prepopulate or the Entityreference Prepopulate module, or simply alter the node_form in a custom module.


Custom access method for a Page Manager page

So, what I ended up doing is extending the Page Manager PageAccessCheck service:
services:
  custom_route_access.page_access_check:
    class: Drupal\custom_route_access\Entity\PageAccessCheck
    tags:
      - { name: access_check, applies_to: _page_access }

And then:
<?php

namespace Drupal\custom_route_access\Entity;

use Drupal\Core\Access\AccessResult;
use Drupal\Core\Entity\EntityAccessCheck;
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\Core\Session\AccountInterface;
use Symfony\Component\Routing\Route;

/**
 * We're overriding the page access checks so that we can add our own.
 * Mimics the generic entity access but with a custom key to prevent collisions.
 */
class PageAccessCheck extends EntityAccessCheck {

  /**
   * {@inheritdoc}
   */
  public function access(Route $route, RouteMatchInterface $route_match, AccountInterface $account) {

    // Backup the original requirements.
    $original_requirements = $route->getRequirements();

    // Replace it with our entity access value and run the parent access check.
    $route->setRequirement('_entity_access', $route->getRequirement('_page_access'));
    if($route->getPath() === '/project/{node}/take_attendance'){
      return self::takeAttendanceAccess($account);
    }
    $access = parent::access($route, $route_match, $account);

    // Restore the original requirements.
    $route->setRequirements($original_requirements);

    return $access;
  }

  /**
   * Check that user is admin or staff OR has an active team leader registration.
   */
  private static function takeAttendanceAccess($account){

    // ... my custom access check code
  }

}


How to delay the execution of a rule for 5 minutes?

Is there a way to delay the execution of the actions so the node is
  actually created already?

Yes, you need to enable the Rules Shecheduler module (comes with rules).

Then Create a Rule Component that will do your action.

Then create a rule with action of schedule component. (set it to 5 mins)

For example, see Rules Conditions being evaluated after schedule time elapsed?

Attention:

  Be aware that the actual trigger will only happen the next time
  your Cron job runs. So if you say "after 5 mins", and the next Cron
  job runs in say about an hour, then it'll only be after about an hour.
  If that's not acceptable (as was the case in this question), then
  you'd have to run your cron job like every 5, 10 or 15 minutes.

So I suggest using Ultimate Cron, that way you can target, so that only your rule cron job runs every 5 or x mins, instead of running every single cron job.

In other words, it allows you to run different catagories/module cron jobs at different times. While you could run less crucial jobs, like Update Manager, only once a day (every 24 hours).


You want to investigate menu_get_object and drupal_lookup_path.

Something like this would do what you want:

$alias = "some/path/to/a/page";
$path = drupal_lookup_path("source", $alias);
$node = menu_get_object("node", 1, $path);


How to show fields in different regions?

As with anything in Drupal there are many ways of doing this. Display suite and Panels (as mentioned by Serpiente above) are great. However, if you are not already using them for your project, they are indeed overkill to get what you need.

You can use the CCK Blocks or Field as Block module. These essentially turn any field (you set) into a block to be placed in another region.

You can also use the Views module to create a block with a contextual filter based on the nid in the url and display whatever fields you choose.


Why Drupal won't remember "use search" permission settings for roles?

PHP has a default setting of 1000 for max_input_vars, and once you have a significant number of modules and/or roles defined, you end up with an excess number of permissions boxes on the page.

In your php.ini file add max_input_vars = 1500 and keep incrementally increasing it until it saves.


How to place a users role after username in Forums

If you can find the display in views.

You can add a  "User: Roles" Field. Mark it as excluded.

Then

Under "user: name" field. select "Rewrite the output of this field" and include the [rid-role] token in the username.

Be sure to add the "role field" before "user field" otherwise the token will not be available.

Example


The primary way to control visibility is through block visibility conditions.

There is no default condition available for what you are trying to achieve, so you have to implement your own.

See \Drupal\user\Plugin\Condition\UserRole, that does visibility based on the user role, what you want would be fairly similar, visibility based on a field, so like any other plugin, you can copy that into your module into the plugin namespace (\Drual\yourmodule\Plugin\Condition) and then adjust it to check the field instead and also offer the same select.

Then you place two blocks in the same region, each with a visibility configuration using your plugin. You need to think about what should happen when a user is not logged in, so maybe you have a default or hide both for anon users/users without a selection.


You need to implement both

template_preprocess_page() : this will take care of node full view mode.
temaplte_proprocess_node() : this will take care of node teaser view mode

In your theme template.php

function mythemename_preprocess_page(&$variables) {
  if(isset($variables['node']) && $variables['node']->type == "your content type") {
    drupal_set_title("your_title");
  }
}

/**
 * Override or insert variables into the node template.
 */
function mythemename_preprocess_node(&$variables) {
  if($variables['type'] == "your content type") {
    $variables['title'] = "your title";
  }
}

Note:

  only changing in template_preprocess_node(), will now reflect on node teaser view as it will be overridden by page template.
  in order to change  you should use drupal_set_title() instead of $variables['title'].


How do I synchronize sites/default/files wtith a AmazonS3 bucket?

If the need is to occasionally copy files from a directory to a corresponding directory on S3, you can use S3 CLI from AWS.

It provides a recursive copy:
aws s3 cp /tmp/foo s3://bucket/ --recursive

Reference: s3 — AWS CLI 1.2.13 documentation : http://docs.aws.amazon.com/cli/latest/reference/s3/

I programatically called this once using the shell-exec from python and invoking the CLI commands.

The long route require the use of AWS S3 REST API (or one of the client SDKs). I havent done this myself, but it is possible since the CLI itself is implemented this way. May be you can take a look at the CLI code on github


The node/*/done seems to be the fix.
Just thought I'd pass it along.


Get referenced node fields in twig where reference is on remote node only

Your node is unaware of the fact that it is referenced by other nodes. So you need to query the nodes that are referencing your node in a preprocess hook:

/**
 * Implements hook_preprocess_HOOK() for node templates.
 */
function mytheme_preprocess_node(&$variables) {
  $node = $variables['node'];
  $storage = \Drupal::entityTypeManager()->getStorage('node');
  $nodes2 = $storage->loadByProperties(['field_reference' => $node->id()]);
  $variables['nodes2'] = $nodes2;
  $variables['#cache']['tags'][] = 'node_list';

}

Then you can use the nodes you've found in Twig directly:

{% for node2 in nodes2 %}

This node is referenced by {{ node2.label }} ({{ node2.id }})

{% endfor %}

Rendering of the nodes

Or better build a entity view of those nodes by specifying a custom view mode, which you have configured to display the fields you want:

if ($nodes2) {
  $view_builder = \Drupal::entityTypeManager()->getViewBuilder('node');
  $nodes2_rendered = $view_builder->viewMultiple($nodes2, 'custom_view_mode');
  $variables['nodes2_rendered'] = $nodes2_rendered;
}

and render those nodes in Twig:

{{ nodes2_rendered }}


Can't place context-controlled block below user picture on user profile page

The weight for the user picture element is set to -10 by default, but
  even if I make it lower, nothing changes is.

The default weight for system content is 0, so display below that you would want a weight of 1 or more for your block in Context > Reaction > Block (if I'm understanding your issue correctly).


Is there any way to clear the cache with specific cid?

You can pass a cid to cache_clear_all() to clear a specific bin.


How can I display the list price field in product page?

it much be easier to add a 'product reference' to your product type when you define the 'content type'. and simply the 'Product: Price' field will add to your 'manage display' in that 'content type'
if the price doesn't show up, Modify the settings for the price field on the product type "manage display" configuration.


Should I be concerned about enabling too many modules at the same time?

Well I guess it depends on max_execution_time in your php.ini settings. And maybe similar setting in your my.cnf file on your server(mysql configuration).


SOLUTION:

Thanks to @tenken for giving me a hint this was related to "clean urls" issue.

I got this working with the following steps:

Run sudo a2enmod rewrite # Enabling "rewrite" module
In /etc/apache2/apache2.conf and look at the block <Directory /var/www/> changed from AllowOverride None to AllowOverride All
Run sudo service apache2 restart

This reference was helpful https://drupal.org/getting-started/clean-urls


how to get a node field value in a html.tpl.php template file?

Another way - without edit template and adding code in template.php

function THEME_preprocess_html(&$variables, $hook) {
    if (arg(0) == 'node' && is_numeric(arg(1))) {
      $node = entity_load_unchanged('node', arg(1));

      if (isset($node -> field_FIELD_NAME['und'][0]['value']) && $node -> field_FIELD_NAME['und'][0]['value']) {
        $variables['classes_array'][] = $node -> field_FIELD_NAME['und'][0]['value'];
      }
    }
  }

replace THEME with your theme_name and FIELD_NAME with your field_name, clear the cache

edit: I change "$node = entity_load('node', arg(1));" to $node = "entity_load_unchanged('node', arg(1));"


Why does a try block affect drupal_set_message?

The second argument of drupal_set_message() should be a string. This string is just added as a class around the message. It an be anything you want.


Need some advice on implementing a HDFS file storage solution for drupal

I am not aware of any existing module for that, but you could start with storage_api and extend it by your custom implementation for HDFS.


How to get the referenced entity name instead of target_id in Normalizers?

you have the target id so just load the term and send the label instead of target id, something like :

$tid = $node_detail['field_story_type'][0]['target_id'];
$term  =  \Drupal\taxonomy\Entity\Term::load($tid);
$news_data['type'] = $term->label();

Note: you are in class it's better to inject entity.manager service and change the line \Drupal\taxonomy\Entity\Term::load($tid); with something like:

$this->entityManager->getStorage('taxonomy_term')->load($tid);


If you have a link field added in your content type then there is no need to render the field programmatically. As I understand with your comment, you need to add field value programmatically.  So in drupal 7 it was hook_node_insert and in drupal 8 it is hook_ENTITYTYPE_insert.

So in drupal 8 your hook_node_insert will look like following :

function hook_node_insert(Drupal Core Entity EntityInterface $node) {
  // Change node object how you wanted.
}

Helpful Links :

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

http://www.drupalcontrib.org/api/drupal/drupal!core!modules!node!node.api.php/function/hook_node_insert/8


View module diplaying wrong content type extra

You need to set up a filter - filter by content and choose the content type you want to show or use a contextual filter(advanced settings) to show only the content type you want to show. Right now youre not filtering so your view is set to show all content types.

In the example below I have a relationship of author. I have a contextual filter set up with this relationship so that it will only show content with this relationship and finally i have a filter that only shows content types of the kind flashcard and only the content where the logged in user is the author of the content.

There is a great set of tutorials about views here at nodeone


How to modify .htaccess to serve brotli compressed static assets over gziped ones?

Give this a try

# Rules to correctly serve gzip compressed CSS and JS files.
# Requires both mod_rewrite and mod_headers to be enabled.
<IfModule mod_headers.c>
  # Serve brotli compressed CSS files if they exist and the client accepts gzip.
  RewriteCond %{HTTP:Accept-encoding} br
  RewriteCond %{REQUEST_FILENAME}\.br -s
  RewriteRule ^(.*)\.css $1\.css\.br [QSA]

  # Serve gzip compressed CSS files if they exist and the client accepts gzip.
  RewriteCond %{HTTP:Accept-encoding} gzip
  RewriteCond %{REQUEST_FILENAME}\.gz -s
  RewriteRule ^(.*)\.css $1\.css\.gz [QSA]

  # Serve brotli compressed JS files if they exist and the client accepts gzip.
  RewriteCond %{HTTP:Accept-encoding} br
  RewriteCond %{REQUEST_FILENAME}\.br -s
  RewriteRule ^(.*)\.js $1\.js\.br [QSA]

  # Serve gzip compressed JS files if they exist and the client accepts gzip.
  RewriteCond %{HTTP:Accept-encoding} gzip
  RewriteCond %{REQUEST_FILENAME}\.gz -s
  RewriteRule ^(.*)\.js $1\.js\.gz [QSA]

  # Serve correct content types, and prevent mod_deflate double gzip.
  RewriteRule \.css\.gz$ - [T=text/css,E=no-gzip:1]
  RewriteRule \.js\.gz$ - [T=text/javascript,E=no-gzip:1]
  RewriteRule \.css\.br$ - [T=text/css,E=no-gzip:1]
  RewriteRule \.js\.br$ - [T=text/javascript,E=no-gzip:1]

  <FilesMatch "(\.js\.gz|\.css\.gz)$">
    # Serve correct encoding type.
    Header set Content-Encoding gzip
    # Force proxies to cache gzipped & non-gzipped css/js files separately.
    Header append Vary Accept-Encoding
  </FilesMatch>
  <FilesMatch "(\.js\.br|\.css\.br)$">
    # Serve correct encoding type.
    Header set Content-Encoding br
    # Force proxies to cache gzipped & non-gzipped css/js files separately.
    Header append Vary Accept-Encoding
  </FilesMatch>
</IfModule>


I'm having the same issue at the moment. Looking into including a few fields from a Profile2 content type into a Display Suite custom code field.

I used the following PHP code in the custom code field (using php filter format and enabling tokens, just in case). Then I was able to view a collapsed tree of all tokens available to that node.

You could prabably do the same in a block and have it displayed when you need it.

<?php
$output .= 'Available tokens:';
$output .= theme('token_tree', array('node'), TRUE, TRUE);
return $output;
?>

I'm sure there's a better way, but that quickly worked for me! gOOD LUCK.


How to add user info along with address info in a single form using 2 content types?

You probably should have a look to Profile2 module. If you really want to use content types, you should have a look to Inline Entity Form and then configure permissions to be sure users can only edit their own content.

Hope that helps ;-)


How can I display a node so that it appears as a regular page

If its the path name you want different how about simply using Pathauto

If not - for setting the page title u should do a drupal_set_message() with $node->title and disable it in the node object.

I hope this is of some help.

EDIT
Trying to be of help again

  '' However, I want to show this node object to the user that pushed the button as soon as it has been created (i.e. to avoid having the user click through a link in order to view it) ''

If it is one node at a time, since you are creating the node programmatically, how about redirecting the user to the node right after you create/save the new node?


Download Views Field View module and install it.

Next create a new view that shows content revision instead of content. See image below.

Pull in the fields you want to see. See Image below.

Add a views contextual filter. See Image below.

Add the Content: Nid field as the contextual filter. Image below.

Configure the field as below.

Next edit your original view that pulls over the current content. Add a field and select the Content: Nid. Make sure to uncheck the Create Label checkbox. We just want the number. Then check the exclude button.

Now we add the views_field_view to the view via the field section of the view. You should select Global: View.

Now we configure it like the image below.

Save your view and now you should be able to go and see each node along with the historical data.


You can use HOOK_views_post_execute() and cycle through the results rows,  updating the row with something like:

        foreach ($viewExecutable->result as $key => $rr) {
          $title = $rr->_entity->getTitle();
          // update $title value...
          $viewExecutable->result[$key]->_entity->set('title', [['value' => $title]]);
        }


Stuck. Installing Drush via Composer not working

Try adding the following to the end of your /Users/jensimmons/.bashrc file:

export PATH="$HOME/.composer/vendor/bin:$PATH"

and then run

source $HOME/.bashrc

Edit:

I just noticed there was a section in the Install/Update - Composer section of the Drush README.md file that mentions this:

https://github.com/drush-ops/drush#installupdate---composer

It's the second point "Make sure Composer's global bin directory is on the system PATH (recommended)"

Hope that helps.


You can do this in UI, UI and code mixed, code only and in html:

Display Suite

Install the module Display Suite and configure this in UI.

Extra Field

Use the hook hook_entity_extra_field() to get an extra field in Manage Display. You need hook_ENTITY_TYPE_view() to copy the data (in this case the file) into the new field.

Clone field in code

See
How to display a field twice in a view mode?

The last has the least overhead, but is not customizable and you have to define the field settings yourself. If you configure the second field temporarily in UI and export the view mode to yaml this helps to find the settings you need in code.

Place link html in template

Or if you want a quick solution in the template and you only need a simple formatted file link you can get the file url from the node and put it in html markup:

Example Video


Module ldap_sso lost when updating module to the new version

I found the solution,
In the mentioned version of ldap, ldap_sso was removed to a separate project, I proceeded to compare the code in case there was any important difference and the result is that they are the same.

So I proceeded to download:

ldap_sso from https://www.drupal.org/project/ldap_sso/releases/7.x-1.0-beta15 and

ldap from: https://www.drupal.org/project/ldap/releases/7.x-1.0-beta15 (by suggestion of drupal)

Now these modules go separately and I ran the update and it did not give any problem.

regards


Something just dawned on me...if you have a menu on the page that links to the '/foo' page, Drupal will query the access callback to find out if the menu link can be shown.

Since you're not providing a type in your menu item, it will default to MENU_NORMAL_ITEM which will place it in the site's Navigation menu.

I would guess that's what's causing the function to be run at least once on every front end page, but not for the admin pages (where you probably won't have the same menus).

It's definitely what was causing the issue on the test installation I just set up for this.


Render main menu in page.tpl.php, with override from template.php

The function you need to override is theme_links() and to do that just for the main menu you can use mytheme_links__system_main_menu as the function name. To add span tags you can then modify the part that starts with if (isset($link['href'])):

if (isset($link['href'])) {
  // Pass in $link as $options, they share the same keys.
  $link['html'] = TRUE;
  $output .= l('<span>'. check_plain($link['title']) .'</span>', $link['href'], $link);
}


use user_hash_password() to validate the password for existing users.


How to get the content of a node with Devel Path?

If your main goal is to expose a piece of data to JavaScript, you can use drupal_add_js() to add a "setting". Here is the example from api.drupal.org:

drupal_add_js(array('myModule' => array('key' => 'value')), 'setting');

(https://api.drupal.org/api/drupal/includes%21common.inc/function/drupal_add_js/7.x)

That then becomes available in the frontend in the Javascript variable: Drupal.settings.myModule.key.

Now, the question is WHERE do you put that call to drupal_add_js? That depends on exactly what data you want to expose, and when you want to expose it, but in general you would create a custom module and implement a Drupal hook that runs drupal_add_js at a specific point in the Drupal pageload life cycle.

If, as it sounds from your question, you want to add node information to a node's "view" page (ie: on the /node/1 path), one option is to implement hook_node_view() in a module called mymodule like so:

/**
 * Implements hook_node_view().
 */
function mymodule_node_view($node, $view_mode, $langcode) {

  // If the node contains the field we want, add it to a JS setting.
  if (!empty($node->location['postal_code'])) {
    drupal_add_js(array('mymodule' => array('postal_code' => $node->location['postal_code'])), 'setting');
  }
}

Here is the documentation for that hook: https://api.drupal.org/api/drupal/modules%21node%21node.api.php/function/hook_node_view/7.x

That's just one way to do it. There are lots of other hooks where this could be done, again: depending on when and where you want it to.


Passing page arguments to custom block inside panel

While a very different question, the answer is the same as mine in https://drupal.stackexchange.com/a/188629/31.

In short, define a context on your block, make sure that the parameter in page manager is defined as type node and the rest should just work.


Block machine name is in use that is not available

Block machine names must be unique in the system, not only in the theme.

When you know the machine name of a placed block you can delete it in UI:

/admin/structure/block/manage/sitelogo/delete

This will of course remove the site logo from one of the other themes.


How to control field visibility in Views based on permission?

Take global php field in view and write below logic in.

global $user;
$node=node_load($nid);
$author=$node->uid;

if($user->uid==$author)
{
   print flag_create_link('flag_machine_name', $nid); // flag for author
}
else
{
  print flag_create_link('flag_machine_name', $nid);//flag for other users.
}

Hope this will help.

NOTE : replace flag_machine_name with your specific flag's machine name which you want to display.


Why would my import of multiple selections work in one content type but not the other?

Eventually finding no solution to the problem I decided to replicate the multiple field selection import that was working.

I made a new content type which contained nothing but the data items I wanted to be able to select and then used a node reference from the original content type. This isn't the most opportune method as whenever this data is displayed it is displayed as a link, a link which then takes you to a page which has nothing on it apart from the name of the data. However imports correctly put the desired data into the the field.

My suspicions regarding this issue are around how the node reference handles multi-fields. Perhaps handling them in a similar way to the import, as in [datafield1,dataf2,"dataf3,dataf3,dataf3",dataf4](as clarification, the previous example is how the csv is laid out). However I've no idea whether or not this actually has any grounds.


\Drupal::currentUser() returns information about the anonymous user, even though I am logged in

To determine if a user is logged-in (authenticated), it would be best to use:

\Drupal::currentUser()->isAuthenticated()


Huge delay on first request due to many slow SQL queries

So this is how I fixed the problem. It is not a real solution as I could not nail the exact source of the problem (if there is one).

1) Aggregate CSS (cache settings). This reduced the latency by half
2) Set cron to never (and run it externally)
3) Set up a cron job that calls the home page with Lynx every 30 minutes


Recommendation for hosting Git VCS from my drupal installation

Look at Case Tracker for project SCM hosting from Drupal:

  Case Tracker enables teams to track outstanding cases which need
  resolution. This module was inspired by the issue handling in project
  module, but unlike Project module, which is specific to software
  development, Case Tracker was designed to be a generic issue tracker.

  Case Tracker is usable right out of the box as a basic ticketing
  system, it's default UI is minimal but feature complete. The module
  was designed to be extended by programmers and site builders to meet
  complex needs, and so tries to avoid making too many assumptions about
  all the ways it can be used.

  Drupal 7

  7.x-2.x - it is an Entity based approach(#1653184: Case Tracker 7.x-2.x - a new approach, with entities) and is on heavy development. As it's based on Entity API, it has a deeper integration with Views,
  Rules, Message and a lot of other modules natively.
  7.x-1.x - has the content types for Project and Cases working without problems. The Notifications, Actions and View integration that needs
  to be tested.

This module is D6 specific but look at Case Tracker Commits as well.

See also Project which powers Drupal.org itself, and the modules it uses such as Versioncontrol Project and its dependant modules.


resizing the dimensions of the an image field

I hope you attach an image field to the content type. In that case, you can define the image styles at admin/config/media/image-styles. It is the core continuation of the Imagecache module.

Create a new style and set the dimension for the images; then, go to admin/structure/types, click "Manage display" in "Article", and click the icon under format of image field; choose the image style you created.


What does features_exclude mean in a features info file?

features_exclude is generated by the Features UI when creating a Feature. It is not created by drush fu FEATURE_NAME. See https://www.drupal.org/node/1064472#comment-7196064.

  The features_exclude lines are purely for the new UI to determine if an auto-detected dependency should be checked or if you have specifically unchecked it.


How to use Rules to set a value for a multi-value field?

Looks like you could just use the "Add to list" Rules Action. And since your question is about a multi-value field, for sure you should NOT use a  Rules Action like "Set a data value", which is used to set assign a single value to a field (which seems to be what you've tried, a common mistake when using the Rules module for such fields).

Refer to the answer to "How to set multiple values to an unlimited Term Refence field with Rules" for "some" more details ...

PS: I'm assuming this question is about D7.


How to add the value of a drupal field to the class of a wrapper div

Something like this should do it:

function MYTHEME_preprocess_node(&$vars) {
  if ($vars['node'] == 'some_type') {
    $field_items = field_get_items('node', $vars['node'], 'field_name');
    $first_item = array_shift($field_items);

    $value = $first_item['value'];

    // If you want to write <div class="<?php echo $extra_class; ?>">... in your template file:
    $vars['extra_class'] = $value;

    // Or if you want to add this to the classes on the main node <div>:
    $vars['classes_array'][] = $value;
  }
}


custom service respond me : 401 Unauthorized: Missing required argument foo

The problem is the mismatch between the data type you define for foo ('struct'), and what you pass with JavaScript (a string). If you are going to pass a string, then your hook implementation should be the following one.

function zbs_services_resources() {
  return array(
    'productQuestionForm' => array(
      'actions' => array(
        'send' => array(
          'help' => 'save a FOO entity via send form',
          'file' => array('file' => 'inc', 'module' => 'zbs'),
          'callback' => '_zbs_productQuestionForm_create',
          //'access arguments' => array('note resource create'),
          //'access arguments append' => FALSE,
          'args' => array(
              array(
                'name' => 'foo',
                'type' => 'string',
                'description' => 'The FOO to create',
                'source' => 'data',
                'optional' => false,
              ),
            ),
        ),
      )
    )
  );
}

'source' => 'data' is perfectly fine, as shown in the example at hook_services_resources(), but notice what the documentation says.

  In the case of 'data' unless you put things in an array, you will get passed to your functions. 'source' => array('data' => 'nid') will pass them off as a single variable; 'source' => array('data') will give you all argument values to each argument.


How to count the number of values in a multi value field with the Paragraphs module?

If you're theming the paragraph field using a theme template or a preprocess function, an $id or $variables['id'] variable is available that has the count of the current paragraph item.


The way I'd do this would be to use Views to override the default taxonomy listing, then add a filter to the view so that the application date must not be in the past.

Life gets a little more complicated if you have multiple vocabularies and this rule won't work with all of them. Ctools page manager will let you load a different view per taxonomy.


Meta tags on taxonomy term pages not showing(using views 3)

I can offer next solutions:

Support of taxonomy term pages generated by views is already included in the
Metatag module since 7.x-1.0-beta2.
If you are using the Metatag module with version lower than 7.x-1.0-beta2 you can use module Meta tags term view.
Try Meta tags quick.


Entity Reference - User reference field Hide "Restricted access" label instead of showing useless choices

You change the reference widget to use Views as a filter to provide the options with Views Reference Filter. Then in Views, provide this users UID as a contextual argument to only get their own relationships instead of every user.


Pros and cons of exposed filters versus contextual filters

Nothing wrong with your approach. i have used it myself a couple of times and seemed to have worked pretty well.

regarding the situation you faced, contextual filters are more sort of an argument rather than a filter so the miss the comparison operators.

The tool in view to use external input to filter is the exposed filter. that is what it is designed for and I think you can go ahead with this approach.


I Found the Solution for this.. and it is by using the BareHtmlPageRenderer (found it here) and then attach the files in the controller php file like this

$build['#attached']['library'][] = 'product_tree/product-tree-libraries';

with out the attachments hook function.

so the controller would look like:

    $build =  array(
        'page' => array (
            '#theme' => 'products_tree',
            '#items' => $term_data,
            '#title' => 'products',
        )
    );

    $build['#attached']['library'][] = 'product_tree/product-tree-libraries';

    $attachments = \Drupal::service('html_response.attachments_processor');
    $renderer = \Drupal::service('renderer');

    $bareHtmlPageRenderer = new BareHtmlPageRenderer($renderer, $attachments);

    $response = $bareHtmlPageRenderer->renderBarePage($build, 'Page Title', 'markup');
    return $response;

it could also be in the $build array it self i think.. but this way its better when looking at it..

and still no need for:

{{ attach_library('product_tree/product-tree-libraries') }}

Or

<link href="css/style.css" rel="stylesheet">


Unsupported operand types in system.module line 2134 when trying to add product with drupal commerce

Either $item, or the return value from the db_query() statement, are resolving as something other than an array. Drupal is expecting them both to be arrays, so you get an error when it unconditionally tries to combine them.

It's not possible to debug something like this without access to the site; I'd recommend stepping through the code with a proper debugging tool to see exactly which side of the equation is failing.

At a guess, I'd say $item is the problem. You'd expect to see more notices about undefined array indexes if it was simply that $item['path'] was missing or something like that.

One low-tech debugging approach is to temporarily disable custom/contrib modules one by one and see if you can find something responsible.


Page--front.tpl.php not working - Tao theme

I think I see a Windows specific issue here.

Notice how block.tpl only has the extension tpl and your new file page--front.tpl.php has php as extension in the filename?

Maybe Windows hides the php extension when you list files (and instead shows it under Type)?

Try removing .php from page--front.tpl.php and see if it still under the Type column shows up as php. If so clear cache and carry on :)


You can use Entity Reference Views module

  This module provides an advanced Entity Reference widget that uses a
  view embedded in a modal dialog for selecting items. The view can be
  paginated and have exposed filters.

You can also use tables in your views for referencing now.


Drupal Commons: notify all users on creation of new group

You can use the Rules module and set it to fire an action, when a group is created.

CVS Instructions
You could also implement this User register notify

But since Drupal Commons uses Organic Groups
you might be able to use this Organic Groups Notifications
but take a look at the Rules module and Flag module.

best regards


How to bind javascript to ctools modal load

I know this is an old question, but maybe this answer can help someone - I know I searched for an answer for a while.

I had a similar issue, I wanted to execute some javascript when a specific page of mine was rendered by ctools modal.

I found the answer in the help folder of the ctools module ctools/help/modal.html :

  If you need to do more than just render your modal, you can use a CTools $commands array. See the function ctools_modal_render() for more information on what you need to do here.

How to apply that to this situation: you need to grab the contents of the very small ctools_modal_render() function and use it to add commands to the array of commands that is executed in the function. This is the function:

function ctools_modal_render($title, $output) {
    $commands = array();
    $commands[] = ctools_modal_command_display($title, $output);
    print ajax_render($commands);
}

This is what my snippet looks like in my page - I wanted to add a body class among other things, so I could style the #modalBackdrop for the modal overlay based on context, so here's my modified page function:

function gc_alterations_modal_page($js=null){

    $page = array();

    $page['search-results'] = array(
        '#markup' => '
My Markup
'
    );

    if( $js ) {
        // Required includes for ctools to work:
        ctools_include('modal');
        ctools_include('ajax');

        // alternate to using: ctools_modal_render('Search', $page);
        $commands = array();
        $commands[] = ajax_command_invoke('body', 'addClass', array('myclass-modal'));
        $commands[] = ctools_modal_command_display('Search', $page);
        print ajax_render($commands);
        return;
    }

    return $page;
}


Prevent view to urlencode contextual filters

You need to use theme_links() function in template.php file of your theme. The original theme_links() function has this:

if (isset($link['href'])) {
  // Pass in $link as $options, they share the same keys.
  $output .= l($link['title'], $link['href'], $link);
}

You should replace it with this to undo the encoding:

if (isset($link['href'])) {
  // Pass in $link as $options, they share the same keys.
  $link_html = l($link['title'], $link['href'], $link);
  // Decode the link HTML before adding it to the output
  $link_html = rawurldecode($link_html);
  $output .= $link_html;
}


Drupal 7 views Contextual filters with Blocks, default value doesn't work properly , wield

If your first contextual filter is your username filter then it will respond to the first argument passed in the preview textfield, no matter what default value you have specified. Your default value is for when an argument is not passed. So, entering "projects/abc" in the Preview with contextual filters box will pass 'projects' to your username filter, but passing a valid username as the first argument as in "abc/*" will work correctly.

It sounds like you've got it set up correctly to me. Have you tried deploying your block view on an actual page?


Detect front page in Drupal 6 with javascript

Generally Drupal adds a "front" class to the body element of whatever page is acting as the front page. If your theme's page.tpl.php is printing the body classes (i.e <body class="<?php echo $classes; ?>"), which it most likely is (it should), then your javascript can check if the body element has the "front" class.

So, assuming jQuery (because Drupal includes it) then you'd do:

if ($('body').hasClass('front')) { // do stuff...}


Add content -> taxonomy autocomplete input field size

You can use the Entity Reference module; it allows the size of the autocomplete input field to be changed.


Try to write JS in drupal way like this:

(function($) {

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

//            $('.test', context).click(function() {
//                $(this).next('ul').toggle('show');
//            });

//myid_js_start();
            function myid_js_start() {
                alert("hello world");
                //console.log(' Hello');
            }

        }
    };

})(jQuery);

For More info visit here


Generally the migrate module is very flexible.


A field that is a multiple of a float field. How?

The easiest way would be to use the Computed Field module. Use something like:

if ( isset($entity->field_price)){
  $entity_field[0]['value'] = ($entity->field_price[0]['value'] * 10);
}

in the Computed Code (PHP) box.


Ubercart - moving uc_order-customer.tpl.php to my theme folder makes emails sent twice

Updating to the latest module version fixed this.


I would start by looking at the Flag Module Documentation and look into several of the ways you might accomplish this:

You can hook into the Flag Module via PHP, so, in preprocess, you can see if a node has been flagged by either the like or dislike flag (or none yet) and display just the one or both of them when the node is displayed.
You can also hook into the Flag Module via Javascript:  it provides two events you can act upon, so, for instance, after a user has clicked on a flag, you can via jQuery hide the other flag.

And of course, with Views, you can filter on whether or not a node has been flagged by a particular flag or not and then list them accordingly.


What module do I turn off to hide or remove the voting widget in Drupal Commons?

Nevermind. I found it was the Rate module.


Bootstrap 3 sub theme - missing header for banner?

I think you are using the Bootstrap 3 subtheme and in that case you have to modify the corresponding templates. So to do that create a new directory "templates" in your subtheme directory and then there you have to place a page.tpl.php then edit as per your needs.

For further reference you can follow, Theming Guide & Bootstrap sub-theming "how to"