Add background image to block from view I created a view that list items from a content type. I have a block display for this view. I want to be able to put a different background image on each instances of this block.

Ideally, it could show up as an option in Block Settings > Allowed settings so this way every instance would have its own background image.

A second option would be that there is an other option in Block Settings below Block Name, something like Block Bakgorund. This time the same background image would be use as every instance of the block.

An other option would be to create a custom block that has 2 fields, a background image and a entity reference field on the content type my view was listing. Two problems with this, first this come to the same as re-write the functionality of Views, and second I am not sure if I would be able to create a field that is an entity reference on a block created programmatically (module plugin)

Any solution to this or thoughts?

I finally had time to make a custom module for that: ctool_views_extender

In your MODULE.module:

<?php

use Drupal\views\Plugin\views\display\Block as CoreBlock;
use Drupal\MODULE\Plugin\Display\Block;

/**
 * Implements hook_views_plugins_display_alter().
 */
function MODULE_views_plugins_display_alter(&$displays) {
  if (!empty($displays['block']['class'])) {
    $displays['block']['class'] = Block::class;
  }
}

In src/Plugin/Display/Block.php:

<?php
/**
 * @file
 * Contains \Drupal\MODULE\Plugin\Display\Block.
 */

namespace Drupal\MODULE\Plugin\Display;

use Drupal\Core\Form\FormStateInterface;
use Drupal\views\Plugin\Block\ViewsBlock;
use Drupal\ctools_views\Plugin\Display\Block as CtoolsBlock;

/**
 * Provides a Block display plugin that allows for greater control over Views
 * block settings.
 */
class Block extends CtoolsBlock {

  /**
   * {@inheritdoc}
   */
  public function optionsSummary(&$categories, &$options) {
    parent::optionsSummary($categories, $options);
    $filtered_allow = array_filter($this->getOption('allow'));
    $filter_options = [
      'background' => $this->t('Background')
    ];
    $filter_intersect = array_intersect_key($filter_options, $filtered_allow);

    $options['allow'] = array(
      'category' => 'block',
      'title' => $this->t('Allow settings'),
      'value' => empty($filtered_allow) ? $this->t('None') : implode(', ', $filter_intersect),
    );
  }

  /**
   * {@inheritdoc}
   */
  public function buildOptionsForm(&$form, FormStateInterface $form_state) {
    parent::buildOptionsForm($form, $form_state);
    $options = $form['allow']['#options'];
    $options['background'] = $this->t('Background');
    $form['allow']['#options'] = $options;
  }

  /**
   * {@inheritdoc}
   */
  public function blockForm(ViewsBlock $block, array &$form, FormStateInterface $form_state) {
    $form = parent::blockForm($block, $form, $form_state);

    $allow_settings = array_filter($this->getOption('allow'));
    $block_configuration = $block->getConfiguration();

    if(!empty($allow_settings['background'])){
      $form['override']['background'] = array(
        '#type' => 'managed_file',
        '#title' => $this->t('Background'),
        '#description' => $this->t('Enter background image'),
        '#default_value' => isset($block_configuration['background'])?$block_configuration['background']:'',
        '#upload_location' => 'public://backgrounds'
      );
    }

    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function blockSubmit(ViewsBlock $block, $form, FormStateInterface $form_state) {
    // Set default value for items_per_page if left blank.
    if (empty($form_state->getValue(array('override', 'items_per_page')))) {
      $form_state->setValue(array('override', 'items_per_page'), "none");
    }

    parent::blockSubmit($block, $form, $form_state);
    $configuration = $block->getConfiguration();
    $allow_settings = array_filter($this->getOption('allow'));

    if (!empty($allow_settings['background'])) {
        $background = $form_state->getValue(['override', 'background']);
        $configuration['background'] = $background;
        // fix bug in Drupal which does not put the image as permanent
        $fid = $form_state->getValue(['override', 'background'])[0];
        /** @var \Drupal\file\Entity\File $file */
        $file = \Drupal\file\Entity\File::load($fid);
        /** @var \Drupal\file\FileUsage\DatabaseFileUsageBackend $file_usage */
        $file_usage = \Drupal::service('file.usage');
        $file_usage->add($file, 'ctools_views', 'image', 1);
    }

    $block->setConfiguration($configuration);
  }
}

Then all you need to do is output it in a twig template. I use another module that I made to simplify things (get_url_from_fid on github or How to get path of image from file id on SE)

{% set background = '' %}
{% if configuration.background.0 %}
  {% set background = 'background-image: url(' ~     get_url_from_fid(configuration.background.0) ~ ')' %}
{% endif %}

<div{{ attributes.addClass(classes) }} style="{{ background }}">

Cheers!

Finally I decided to patch ctools view block. I have plan to replaced this patch with an object that will extend ctools' view's Block (core/modules/ctools_views/src/Plugin/Display/Block.php) I paste here for anyone to use.

[apache{} patches]$ more ctool-add-bg-to-block.patch
diff --git a/modules/ctools_views/src/Plugin/Display/Block.php b/modules/ctools_views/src/Plugin/Display/Block.php
index 9b72f34..19b64aa 100644
--- a/modules/ctools_views/src/Plugin/Display/Block.php
+++ b/modules/ctools_views/src/Plugin/Display/Block.php
@@ -31,7 +31,8 @@ class Block extends CoreBlock {
       'hide_fields' => $this->t('Hide fields'),
       'sort_fields' => $this->t('Reorder fields'),
       'disable_filters' => $this->t('Disable filters'),
-      'configure_sorts' => $this->t('Configure sorts')
+      'configure_sorts' => $this->t('Configure sorts'),
+      'background' => $this->t('Background')
     ];
     $filter_intersect = array_intersect_key($filter_options, $filtered_allow);

@@ -54,6 +55,7 @@ class Block extends CoreBlock {
     $options['sort_fields'] = $this->t('Reorder fields');
     $options['disable_filters'] = $this->t('Disable filters');
     $options['configure_sorts'] = $this->t('Configure sorts');
+    $options['background'] = $this->t('Background');
     $form['allow']['#options'] = $options;
     // Update the items_per_page if set.
     $defaults = array_filter($form['allow']['#default_value']);
@@ -79,6 +81,16 @@ class Block extends CoreBlock {
       unset($form['override']['items_per_page']['#options']);
     }

+    if(!empty($allow_settings['background'])){
+      $form['override']['background'] = array(
+        '#type' => 'managed_file',
+        '#title' => $this->t('Background'),
+        '#description' => $this->t('Enter background image'),
+        '#default_value' => isset($block_configuration['background'])?$block_configuration['background']:'',
+        '#upload_location' => 'public://backgrounds'
+      );
+    }
+
     // Provide "Pager offset" block settings form.
     if (!empty($allow_settings['offset'])) {
       $form['override']['pager_offset'] = [
@@ -270,6 +282,19 @@ class Block extends CoreBlock {
       }
     }

+    if (!empty($allow_settings['background'])) {
+        $background = $form_state->getValue(['override', 'background']);
+        $configuration['background'] = $background;
+        // fix bug in Drupal which does not put the image as permanent
+//      kint($form_state->getValue(['override', 'background'])[0]);
+        $fid = $form_state->getValue(['override', 'background'])[0];
+        /** @var \Drupal\file\Entity\File $file */
+        $file = \Drupal\file\Entity\File::load($fid);
+        /** @var \Drupal\file\FileUsage\DatabaseFileUsageBackend $file_usage */
+        $file_usage = \Drupal::service('file.usage');
+        $file_usage->add($file, 'ctools_views', 'image', 1);
+    }
+
     // Save "Pager offset" settings to block configuration.
     if (!empty($allow_settings['offset'])) {
       $configuration['pager_offset'] = $form_state->getValue(['override', 'pager_offset']);


Install Drupal with MS SQL Server 2008 R2 Is it possible in any ways to connect Drupal 6.x to MS SQL Server 2008 R2 on Windows Server 2008? I am really struggling to find a way out.

please let me know. Any help would be greatly appreciated!

The requirements clearly states that the supported databases in Drupal 6 are "MySQL 4.1 or higher, PostgreSQL 7.1."

You would have to write the database support yourself to get this working.

Drupal 7 does support MS SQL Server however.

First use Godaddy as it only a short time with there help to setup the latest version of Drupal. I use 2008R2 with Drupal but you do need to write code to connect..


Trigger a module function after a node is saved or updated successfully in the database I have used this function hook_node_insert() , but it does not help me because this hook runs before the node is actually saved in the database. I am indexing nodes to a third party application whenever a node is inserted, updated or deleted. The application sends request to the node URL, but using hook_node_insert(). It's giving me an invalid document location error because the node is not actually inserted yet.

Is there any hook invoked after a node is saved or updated in the database?

I followed this approach, without success.

function  my_module_node_insert($node) {
  if (!$node->type == 'article' || !$node->type == 'page') {
    return;
  }
  my_module_do_index($node);
}

You may be able to use Hook Post Action and then use this hook:

function my_module_node_postinsert($node) {
  if(!$node->type == 'article' || !$node->type == 'page' )
      return;
  my_module_do_index($node) ; // indexes the node
}

Give it a try and see if it helps!

The project link: https://www.drupal.org/project/hook_post_action

What you want to use is this function

hook_entity_insert($entity, $type)

This function is called after the hook_node_insert and trigger your my_module_do_index( $node )

Same with the update function use hook_entity_update instead.

Other way to do it could be via hook_cron() and update your index with the cron system.


How can I print a field value in node.html.twig? I want to print a field value in node.html.twig. When I use {{ content.field_test }}, it prints the full HTML markup of the field.

How can I just print the field value?

While you can print the first value of the field without the surrounding div container with {{ content.field_test[0] }}, this is not a recommend way to do it.

The markup you want to change is in the field template. If you don't want for example any div's around the field field-test, then place a field template in the template folder of the theme:

field--field-test.html.twig:

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

The benefit you get is that this outputs multi-value fields and that you keep the attributes of the field, which is important if you want the theme to work with core and third-party modules for client side functionality like, for example, quickedit.

It's a bit later, but just using {{ node.field_test.value }} works.


How do I properly pass values from PHP to JavaScript? I am currently writing a module and I am trying to pass some variables to the Drupal.settings.

My module uses the following code.

function bcc_preprocess_views_view(&$vars) {
    drupal_add_js(array('modulname' => array('key' => 'value')), 'setting');
    drupal_add_js(drupal_get_path('module', 'modulname') .'/script.js');
}

The script.js content is the following.

(function ($) {
    console.log(Drupal.settings.modulname);
})( jQuery );

The output I find in the log is undefined, but when I check the content of  Drupal.settings.modulname from the browser, it gives me the desired value.

When I add this code, the log shows the right values.

drupal_add_js('jQuery(document).ready(function({console.log(Drupal.settings.royal)});', 'inline');

What is wrong with that? What is the correct code to use?

You first JS snippet executes before the page is done loading.  Is it not the same syntax as the shorthand for declaring the document.onready event handler.

You working example runs from an onready, but the Drupal best practice is to use a behavior, eg:

(function ($, Drupal, undefined) {
  Drupal.behaviors.mymodule = {
    attach: function (context, settings) {
      console.log(settings.mymodule);
    }
  };
})(jQuery, Drupal);

Take a look at Managing JavaScript in Drupal 7 for more information.

okay: this does it:

$options = array(
'weight' => 1000, // High number to push this file to the bottom of the list
'scope' => 'footer' // This will output the JS file in the footer scope, so at the end of   the document
);

an then hand it over with:

drupal_add_js(drupal_get_path('module', 'modulename') .'/script.js', $options);

for more details:
https://stackoverflow.com/questions/8330757/drupal-7-add-js-weight


Add an entity reference select to a form I am writing a Drupal 8 module, and I have some code that adds an entity reference field to a form.
$form['commitment']['goal'] = array(
    '#type' => 'entity_autocomplete',
    '#title' => 'Goal',
    '#target_type' => 'node',
    '#selection_settings' => ['target_bundles' => ['goal']],
);

This works, except that I want a select list instead of an autocomplete.
How can I accomplish this?

Basing on the OP solution, I would suggest the follow code.

$options = [];
$goal_nodes = \Drupal::entityTypeManager()->getStorage('node')->loadByProperties([
  'type' => 'goal',
]);

foreach ($goal_nodes as $goal_node) {
  $options[$goal_node->id()] = $goal_node->label();
}

$form['commitment']['goal'] = [
  '#type' => 'select',
  '#title' => t('Goal'),
  '#options' => $options,
];

This has still two issues:

Entities are not translated
Bundle label ('Goal') is not  programmatically coming

Found out after 2 hours of search in drupal core:

->setDisplayOptions('form', array(
            'type' => 'options_select'
        ))


The "php" plugin does not exist I got this error after migrating from Drupal 6 to Drupal 8.1.3.

  Drupal\Component\Plugin\Exception\PluginNotFoundException: The "php" plugin does not exist. in Drupal\Core\Plugin\DefaultPluginManager->doGetDefinition() (line 52 of core\lib\Drupal\Component\Plugin\Discovery\DiscoveryTrait.php).

How can I fix this error?

It's a guess, but the php module was removed from core in D8 and is now supplied by a contrib module: PHP

You will need to install it additionally.

Edit 1:

If you don't intend to use the module in the future, enable it only temporarily, find alternatives for the fields/text formates currently using it (if needed, the filter may be available but not actually used for php) then uninstall it again once you are done.

Do these actions in your database :

Locate php_code in 'node_revision_body' table at
'body_format' column, and change it from 'php_code' to
'filtered_html'.
There is also 'filter.format.php_code' in my config table, i delete that.
drush cr.
Enable 'php' module from drush using the command 'drush pm-enable php'.


Add html to wrap custom panels layout programaticly How to add html to wrap custom panels layout programaticly?
I know that i can change html in *.tpl.php but i want to avoid it.
Also i want to know, how to add class to panals programaticly too.

UPD:
I create custom panels layout and want to add html with custom class to wrapp regions of custom panel layout.
I found good decision to use module Semantic panels, but it add markup to field, not to whole region.

This is part of my html

 <?php if ($content['left'] || $content['middle'] || $content['middle_two'] || $content['right']): ?>

            <?php print $content['left']; ?>

  <?php endif ?>

I want to make it like that

 <?php if ($content['left'] || $content['middle'] || $content['middle_two'] || $content['right']): ?>

            <?php print $content['left']; ?>

  <?php endif ?>

UPD2: I try to add variable through themenaame_preprocess_panels_pane, but it doesn't appear in .tpl.php file.

Code

function dmits_preprocess_panels_pane(&$vars){

$vars['custom_article_class'] = 'seriveces-wrapp';
  kpr($vars);

}

The module suggested (in a comment) by Danny Englander helps me (thank you!).

I.e. module drupal.org/project/panels_extra_styles

Since Dany only posted it as a comment, I'm adding it as a "real" answer (so that I will also be abe to "mark it as accepted".


New action for Views Bulk Operations I'm trying to add some custom actions to my Views Bulk Operations, but for some reason, they don't appear in the list.

This is my code (got it from Drupal.org, so I guess this is a working code...)

function publication_action_info() {
  return array(
    'node_unpublish_action' => array(
      'description' => t('Unpublisedh node--'),
      'type' => 'node',
      'configurable' => FALSE,
      'hooks' => array(
        'node' => array('insert', 'update'),
      ),
    ),
    'node_unpublish_by_keyword_action' => array(
      'description' => t('Unqsdfqsdfpublish node containing keyword(s)--'),
      'type' => 'node',
      'configurable' => TRUE,
      'hooks' => array(
        'node' => array('insert', 'update'),
      ),
    ),
  );
}

So what's wrong with my code or logic to make this thing to work?

Here is the way, I found for D7...

/**
 * Implementation of hook_action_info().
 */
function MODULE_action_info() {
   $action = array(
    'MY_ACTION_NAME' => array(
      'label' => t('MY ACTION LABEL.'),
      'type' => 'node',
      'configurable' => FALSE,
      'triggers' => array('any'),
    ),
 );
 return $action;
}

/**
 * Action function for MY_ACTION_NAME.
 */
function MY_ACTION_NAME(&$entity, $context = array()) {
  // Your code here.
}

Now just add the action MY ACTION LABEL in VBO list.

Try permitting all hooks, rather than just node actions.

'hooks' => array('any' => TRUE),


How can set a custom action with a custom attribute selected in form? I have a view of persons. I like to add the persons to an event. I also like to set the status of the resulting relation to one of the values "optional" or "required".
Therefore I use VBO on a list of persons. With the submitted NIDs I like to build a relation from the person to the event and fill the relation data field "status" with the selected value from the from.
To create only the relation it was easy to create a new action with custom php code, which builds my relations programmatically.
To add a parameter to the relation I have to edit the view's form programmatically. So I hook into the form alter of the views form and add a custom dropdown with the two values "optional" or "required".
The questions are:

Is it possible to use the selected dropdown value in the vbo action with custom php code? I only know how to handle the selected nid's. This option would be easier for me to implement.
If 1) is not possible: Should I use a custom submit function for the vbo form? And where to assign the function?

I tried the following code to assign a custom submit custom_webform_pre_build_list_vbo_submitfunction but it isn't called.
function custom_webform_pre_build_list_form_alter(&$form, &$form_state, $form_id) {
    if ($form_id == "views_form_person_list_panel_pane_9"
    and $form['#id']=='views-form-person-list-panel-pane-9') {
        $form['#submit'] = array('custom_webform_pre_build_list_vbo_submit');
    }
}

It is possible to use the $_POST array in the custom php code, which can be called in the action, which is assigned to the vbo action!
The page to show the view with the vbo fields is: /node/%node/add_person_to_event, so arg(1) is the nid of the event.

So my custom action code is:

$status = $_POST['status'];
$event = arg(1);
foreach ($_POST['views_bulk_operations'] as $key->$vbo_nid) {
   build_relation_person_event($event, $vbo_nid, $status);
}


Is there a tool to covert any template to drupal 7 theme? Is There any tool to convert any template (wordpress, joomla, static html/css etc) to a drupal theme

Nope! :)

There is, however, a nice page full of information to convert Drupal 6 themes to Drupal 7: link

I think there is not such tools of converting form Drupal x to Drupal 7. Theoretically, the process is not so complicated (depends of your theme practically) you can do it yourself following the suggestion of @Alex.

However if the question is to convert form WordPress, Joomla and other themes to Drupal there are nice tools to create a Drupal theme such as Artisteer and maybe it will convent also.


custom service respond me : 401 Unauthorized: Missing required argument foo I have this custom service:

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' => 'struct',
                'description' => 'The FOO to create',
                'source' => 'data',
                'optional' => false,
              ),
            ),
        ),
      )
    )

  );
}

And this little jQuery code in a simple html test file:

$.ajax({
    url: "/rest1/productQuestionForm/send",
    headers: { 'Content-Type': 'application/json','X-CSRF-Token':'MY_WORKING_TOKEN' },
    success: function (res) {
      alert("success");
      console.log(res);
    },
    data : {
      'foo' : 'pippo',
      "type":"page",
      "title":"Page submitted via entity JSON REST",
      "body": {
          "value": "
test
\n",
          "format": "filtered_html"
      }
    },
    type: 'post',
    dataType: 'json',
  });

But when I load the simple test html page I see this in developer suite for the POST url:

  401 Unauthorized: Missing required argument foo

Where am I doing wrong?

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.

Change

'source' => 'data',

to

'source' => array('data' => 'foo'),

Clear the caches, and it should work.


how to inject JQuery into a D7 page I have a Drupal 7 view page where I want to change the behaviour of the submit button by using the jQuery code below. How do I do this in Drupal 7?

$('#reset-button').click(function() {
  $('#views-exposed-form').each(function() {
    this.reset();
  });
  $('#submit-button').click();

  return false;
});

You can add your code in a JS file say somescript.js and save it in your theme folder. In the theme.info file add the following line

scripts[] = somescript.js

This will add somescript.js to all pages by default. If you want it for a particular page add a conditional check and use drupal_add_js(PATH_TO_JS)
For more info check out Managing JavaScript in Drupal 7

Good idea! Regarding this I found painless solution. I installed jQuerify from here https://chrome.google.com/webstore/detail/jquerify/gbmifchmngifmadobkcpijhhldeeelkc
It injects jQuery 1.8 even in HTTPS pages with one click  with no conflict to Prototype )))


How to disable a module and its dependents modules with Drush? Is there any way to disable a module and its dependents modules with Drush.

Let's say I need to disable views but I have enable views_accordion as well.

If I run $ drush pm-disable views I don't get the views module disable.

You should update your drush by the sounds of things. Doing drush dis views should result in the following:

drush dis views
The following extensions will be disabled: views, views_bulk_operations, og_ui, views_content, og_example, views_php, views_ui
Do you really want to continue? (y/n)

Which means the dependents are disabled at the same time.

In Drupal 8 we can uninstall the module with the following command:

drush pm:uninstall oauth2


Behaviors are only called the first time a view is loaded On a Drupal 8 site I have a world map where the user can click on a country; a view with content is then loaded with AJAX using a custom module and the following JavaScript.

(function($, Drupal, drupalSettings, window, document) {
  Drupal.behaviors.worldmap = {
    attach(context, settings) {
      console.log('behaviors called');
      $('#map-container', context).once('addmap').each( () => {
        let map = new InteractiveMap('.interactive-map', (country) => {
          let id = settings.worldmap.yearsnids[country];
          if(!id) {
            id = 0;
          }
          console.log('id');
          let ajax_settings = {
            url: '/my_module/ajax/expand/' +
                  settings.worldmap.ctype + "-infobox/" + id,
          };
          Drupal.ajax(ajax_settings).execute();
        });
        map.init();
      });
...

I have a custom template for the view where I add a ajax link.

See the project

Clicking that link loads another view with more content.
So basically a preview is loaded when the user clicks on a country, and a link in the preview then loads the full content if clicked.

Both the preview and the content (also a view), is loaded from my_module with an AjaxResponse:

namespace Drupal\my_module\Controller;
use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Ajax\ReplaceCommand;
use Drupal\Core\Controller\ControllerBase;

class my_moduleController extends ControllerBase {
  public function loadContent($method, $action, $type, $nid) {
    $response = new AjaxResponse();
    // logic to determine which action and type we want to load
     ...
    $build['view'] = [
      '#type' => 'view',
      '#name' => $viewname,
      '#display_id' => $did,
      '#arguments' => [$nid],
    ];
    $response->addCommand(new ReplaceCommand($replaceClass,
                          $build, ['fadeIn']));
    return $response;
  }
}

This all works, but the link in the preview only works for the first preview loaded. In every other preview loaded, clicking the link sends the user to the actual ajax-path (eg. mysite.com/my_module/ajax/expand/my_ctype-infobox/the_actual_id), and the content that should have been rendered to the page are displayed like json in a textbox:

[{"command":"settings","settings":{"pluralDelimiter":"\u0003","ajaxPageState":
...

When the page with the map is loaded, and first time the preview is loaded, 'behaviors called' prints to the console - the link to load the full content works. On subsequent times, clicking on a country loads the preview, but behaviors aren't called at all. 'id' gets printed to the console every time I click.

This is the HTML structure:

The preview is loaded into the info-box__content div, which is outside the #map-container.

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.

The Root of the problem is the ReplaceCommand in the ajaxResponse.

By reading the issue that I mentioned in my comment, I realized the root of my problem is probably the same as in that issue.

When the preview is loaded the first time by clicking a country, all behaviors are attached correctly to the new div inside .info-box__content.

The next time a preview is loaded, that new div inside .info-box__content is replaced by another via the ReplaceCommand. Drupal.behaviors.worldmap tries to attach the behaviors again, but, for reasons I don't quite know, it tries to attach it to the old div that was just removed by the ReplaceCommand, and thus it fails (silently).

At least this is what I think is going on. To work around that issue, I simply remove any old div and add a new placeholder before the ajax execute call - my javascript now looks like this:

(function($, Drupal, drupalSettings, window, document) {
  Drupal.behaviors.worldmap = {
    attach(context, settings) {
      console.log('behaviors called');
      $('#map-container', context).once('addmap').each( () => {
        let map = new InteractiveMap('.interactive-map', (country) => {
          let id = settings.worldmap.yearsnids[country];
          if(!id) {
            id = 0;
          }
          console.log('id');
          let ajax_settings = {
            url: '/my_module/ajax/expand/' +
                  settings.worldmap.ctype + "-infobox/" + id,
          };
          // new code for removing old div and adding new placeholder
          $('.info-box__content div', context).remove();
          $('.info-box__content', context).html('

');
          Drupal.ajax(ajax_settings).execute();
        });
        map.init();
      });
...

And now it works :)


How to Filter view by comparing 2 fields. If field-a < field-b I have a product content type that has 2 price fields.

I want to create a view that shows all products where price-A is less than price-B.

I was hoping I could just add a filter and select price-A then choose operate less than and set the value as price-B, however you can't do that.

I have looked into using a views hook, mainly hook_views_query_alter but haven't had any luck.

I've also tried using the Views PHP module and been unable to get it to work.

Does anyone know the best way to achieve this?

What you're looking for is the filter criteria Global: Fields comparison:)

If price is a field in your content type, in Drupal 7 views you can automatically, and easily choose a field com-parer. I guess this should work.


Can you make a field unique in a content type? I have an Employee content type with an ID field.

Can I make the field unique, so that Drupal would prevent me from entering the same ID more than once by mistake?

You can add a validation constraint to your field.
There is two ways to do that:

Setting a validation constraint to a field you haven't defined by implementing hook_entity_bundle_field_info_alter:

function YOURMODULE_entity_bundle_field_info_alter(&$fields, EntityTypeInterface $entity_type, $bundle) {
  if ($entity_type->id() === 'ENTITY_TYPE' && $bundle === 'BUNDLE_NAME') {
    if (isset($fields['FIELD_NAME'])) {
      $fields['FIELD_NAME']->addConstraint('UniqueField');
    }
  }
}

Setting a validation constraint to a field you have defined in baseFieldDefinitions

public static function baseFieldDefinitions(EntityTypeInterface $entityType) {
 $fields['FIELD_NAME'] = BaseFieldDefinition::create('string')
   ->setLabel(t('MY UNIQUE FIELD'))
   ->addConstraint('UniqueField');

 return $fields;
}

If you want to create your own validation constraint you can check here.

A core Drupal way to achieve your result:

Create Taxonomy "Employee ID".
Add Taxonomy reference field to "Employee" content type.
Ensure to check "Create referenced entities if they don't already exist" in field settings.

You will know if the ID exists if the term can be referenced. Plus this data becomes easily reusable.


How to implement side-by-side translation? How can you set up a translation system in Drupal which displays, for example, the English and the French node edit forms side-by-side? Is this possible using any of the contrib modules?

Additionally, how would I go about setting a requirement that a translation must always be entered when entering English content. Eg, to publish a piece of content, it must have both an English and French translation. Maybe through rules?

There hasn't been a whole lot of public work on this that I can find.

Some module options:

Side-by-Side Translation (no code)
Entity Translation Side-by-side Editor (code, no release)
Dual-Language Editor (code, no release)

liquidcms helped me find that last one.

I'd recommend trying the latter two and seeing how far you get.  Post patches for missing functionality as necessary.

Also, see the issue Create Node With Multiple Translations Using Single Form.

for D7 there is entity_translation_unified_form
it is the best one that I have found
https://www.drupal.org/project/entity_translation_unified_form


Is it possible to reference a field to a node, and also to a user? My question: Is it possible to reference a field to a node, and also to a user?

I want to keep track of scores scored by users while playing a boardgame. So, I'll need a reference between nodes (boardgame) and users. I'm using the "entity reference" for this.

With the module field_group and field_group_multiple, I can make rows with user field, score field, etc... But the problem here is: the score field is linked to the node, not to the user. (So if I want to make a view and get all scores scored by a player, this will be not possible.)

I found an answer. The modules entity_reference and field_collection are what I needed. field_collection makes a collection that has a reference to the node, and also to the user_reference. An awesome module!

**EDIT
This would probably be best as a module then.  You could either create separate views of each player or game instance and use view_embed_view() function or  You could use a noad_load() to grab the information as well.

http://api.drupal.org/api/views/views.module/function/views_embed_view/7

http://api.drupal.org/api/drupal/modules%21node%21node.module/function/node_load/7


Menu hook callbacks not working for anonymous users My custom error handler module is somewhat based on the customerror module, but instead of returning markup, my menu callback function redirects based on the original path. It registers error paths as follows:

function my_customerror_menu() {
  $items = array();

  $items['my_customerror/%'] = array(
    'title callback' => FALSE,
    'access callback' => TRUE,
    'page callback' => 'my_customerror_page',
    'page arguments' => array(1),
    'type' => MENU_CALLBACK,
  );
  return $items;
}

'access callback' => TRUE should make it accessible to all users. I can use the path my_customerror/404 for example in the site settings and it is recognized as a valid path. This works fine in a local instance and on the Pantheon development  site, but once I pushed it to the Pantheon test environment, my_customerror/404 is not invoked on 404 - Drupal uses the default error response. Unless I am logged in, then it works in Test as well.

But the path my_customerror/404 works regardless when I type it in manually and does what it should. Somehow Drupal erroneously thinks that this path is not accessible to anonymous users.

What could be causing this?

Here is a simplified version of the callback function that shows what it does:

function my_customerror_page($code) {
  $dest = variable_get('my_customerror_' . $code . '_default', '');
  switch ($code) {
    [conditional stuff]
    default:
      header('Status: 301 Moved Permanently', false, 301);
      header("Location: " . $dest);
      break;
  }
  return "";
}

Don't ask why I use header() and not drupal_goto() ....

Just bringing something into the problem description that I already mentioned in a comment. When the Devel module is turned on and anonymous users are given permission to see developer output, it starts working! But this is not a solution, I obviously can't do this in the Live environment.

You're doing a switch(), but with only a default for the switch and no options, it means the switch is unnecessary. Drupal also provides the drupal_goto() function, which handles both redirects, as well as cancelling killing the script so the redirect can proceed. Your code can be simplified to:

function my_customerror_page($code) {
  $dest = variable_get('my_customerror_' . $code . '_default', '');
  drupal_goto($dest);
}

Or if you're really set on using header() to set headers for whatever reason, you just need to add drupal_exit() after your call to header().

Two subtle changes to the callback function appear to have resolved this. It is working now:

returning something other than an empty string
using drupal_add_http_header() to set the response code instead of the low
level PHP function.

As in:

function my_customerror_page($code) {
  $dest = variable_get('my_customerror_' . $code . '_default', '');
  drupal_add_http_header('Status', '301 Moved Permanently');
  header("Location: " . $dest);
  return "redirecting ....";
}


Does having too many content types negatively affect site speed and performance? I building a site that could potentially utilize 20 different content types. The content types are very similar, but may only utilize one or two fields that are unique to that content type, and they would use the same 5 fields with each other. Does having 20 different content types slow the site down? Would it be better to build one content type and display the unique fields on a case by case basis using FAPI or the conditional fields module?

The number of content types does not affect the performance of a Drupal site.

Sharing fields among the content types does affect the performance. This is because of the way CCK stores fields.

If the field is not shared and allows only one entry, it is stored along with other such fields in a table designated for that content type. That way, all such fields can be loaded in a single query.
If the field is shared or allows multiple entries, the field is stored in its own table, making an extra query (or join) per field necessary to load the field.

You are probably using 19 extra content types that you could save in different ways.

The first one, for example, using all the fields in the same, unique, content type, but giving the user the choice to fulfill them or not, depending on your/their needs.

The other is hiding the fields, using the nodeapi or a module like conditional fields: https://drupal.org/project/conditional_fields

Depending on the context, project, requirements, you could find other ways or solutions.


How much time does it take to manage sites within a multisite architecture as compared to multiple single installs? A service my company offers is similar to managed hosting where we help keep a server, Drupal, related modules, and backups up to date on behalf of clients who can't or don't want to do that in house, and typically this averages out to be about 30 to 90 min of work per site per month.
A client has asked me to manage their entire portfolio of 70 Drupal sites, all of which are part of a multisite architecture with site files on one server and DB on another.
I can't imagine that this is 70 hours of work, but I'm not familiar enough with multisite installs of this size to understand fully what this would entail.
To ensure that I estimate time correctly, what would I need to take into consideration when comparing management solutions for single server / single site installations as compared to the same number of sites in a multisite installation?

Short: It really depends.

Long: Each individual multisite installation adds complexity to the whole. If these 70 sites are more ore less the same in terms of individual content but (nearly) same codebase, modules and similar themes (imagine a large organization spread over the world with region specific characteristics), you'll most likely need less time to maintain.

If these are 70 profoundly individual sites, you'll probably end up checking dependencies over dependencies for modules and themes, debugging deadlocks and incompatabilities. Maintaining this can be a real challenge and 70 hours a month are gone faster than you have "drushed and rollbacked" everything to working.

Accurate documentation and a SLA designed fair for both parties should be the key to a successful maintenance.

(I maintain a multisite installation with around 30 instances for a large organization with all the pros described above.)

I can say that you should take into consideration that managing multisite drupal installation usually takes less time then handling same amount of single installations. I will briefly explain how it can be done for drupal 7

1) when you download drupal you can find sites folder in root;

2) You can add as many websites as needed inside sites folder, just create for example "example" folder;

3) In example folder create settings.php file

$databases['default']['default'] = array (
  'database' => 'example',
  'username' => 'admin',
  'password' => 'admin123,
  'host' => 'db_host_address',
  'driver' => 'mysql',
);

4) create modules, themes, libraries folder for site specific modules, themes and libraries in sites/example folder. All common (used by more then one site or features which potentially can be used in future by multiple sites) modules, themes, libraries can be added into corresponding folders inside sites/all directory.

5) To establish http connection with example website you should create server alias then add sites.php file inside sites folder.

$sites['localhost.example'] = 'example';

where localhost.example is your server alias and example is your site folder.

you should take into account that in future it will be easier to update drupal core and contributed modules but as cons you should take into account that during each common change all websites which use changed module, theme should be tested well. In case of updating core all sites should go through round of testing.

From my personal experience multisite installation is easier to maintain. I wish you good look with your task!


Password reset email is not valid? In setting up a new Drupal 7 site, I went to try out the password reset option, and while I received the password reset email just fine, clicking it takes me to a page with an error "You have tried to use a one-time login link that has either been used or is no longer valid".

I've tried sending the reset email a few times and clicking the link immediately each time, and keep getting the same error message. What sort of things make a reset link "no longer valid"? I'm working on a staging server that will be translated to a live server, so URLs and cookie paths might be getting tangled; where do I need to start looking to unravel this?

Note: The user accounts being tested were imported using the Migrate module from another system, hence their passwords are invalid, and I'm hoping users can just request a new password to login.

It's not documented nicely anywhere I can find, but it seems that you can't use the password reset option via email for a user who's an Administrator of the site. Instead you have to use some alternate method to change the database directly, like this.

That's not the case - you should be able to get admin password reset by using the link /user/password . The problem I found was its not set to my domain, instead it set to gmail.com .

After i changed to my domain, I started getting emails for Password Reset from my D7 installation.


Drupal Front end Form with fields with option to add More Fields I want to create a Form in the frontend, so user can able to add the data in the form and submit the data. Then i have to display all the data submitted by the user using that form. Just like a Internal Messaging system. I want a Add Reports Form and i want to list all the reports in a page ( View Reports). I planned to create a content type ( Reports), After that i will be able to add the fields. Upto this i know how to do. But i want to know how to have a row with three fields with add button, then if user click on the button,  i want to append a new row with same three fields. Just like Multiple Image upload. I have screenshot. In screen one, i have a add button above a row with three fields. In the screen two which is taken after clicking the "add button" , It displays the same add button with two rows with same three fields .

Screen 1 :

Screen 2 :

Any help would be greatly appreciated.

Assuming that "Name of Stocklists", "Sales as on Date", and "Closing Stock Value" are all CCK fields, you should be able to do this using Field Collection (https://drupal.org/project/field_collection).

1) Install Field Collection

2) Create a field collection field on your Report content type. Use the embedded widget. Be sure to make the field multi-value / unlimited values.

3) Go to admin/structure/field-collections and click Manage Fields for the field collection you created.

4) Add the 3 stock text fields to the field collection.

5) Now on the Report add/edit forms, you'll have the "Add Another Item" button.

To align the fields in a row, you should be able to use CSS. To make the button a +, you should be able to use hook_form_alter() or hook_form_report_node_form_alter().


Add next/prev link to image in drupal 7 I have a taxonomy with lots of nodes in it. Each node contains a large image. I want that image to be linked to the next node within the taxnomy. How can I do this in Drupal 7?

Please see the solution that should work !

Hook into node view using hook_node_view by writing a custom module.
Change the image field to a image with link using below technique

Get nid of current node using $node->nid;
Get taxonomy term id associated with node object using this technique.
Get all other nodes attached with same taxonomy term that you got in step 2 using taxonomy_select_nodes
From the list of node id's that you got in step 3 check the node id which is just greater than $node->nid and store it in variable $next_nid
Form a link using l function that should be markup for image field.

$overrided_image_field_value = l($image, 'node/' . $next_nid, array('html' => TRUE));

That should do the work !

I would use the Views Slideshow module to have a view block with all the nodes belonging to the taxonomy term that is being viewed at the time.
Aspects such as adding next/previous links are 'easy' using views slideshow. For node that contain large images this module should be more than apt for the job.The link should get you started.


Drupal_add_js is not working inside hook submit I have alter and hook submit for webform. I would like to pop a modal if form is successfully submitted. But drupal_add_js seemed to be not working inside the hook submit.

function myModule_form_alter(&$form, &$form_state, $form_id) {

    if($form_id == 'webform_client_form_9') {
        $form['#submit'][] = 'myForm_submit';
    }

}

function myForm_submit($form, &$form_state) {
    drupal_add_js(drupal_get_path('module', 'myModule') . '/misc/custom.js');
}

You should do this with #attached.

Like,

if (!empty($form_state['values'])) {
  $form['#attached']['css'] = array(
    drupal_get_path('module', 'ajax_example') . '/ajax_example.css',
  );
  $form['#attached']['js'] = array(
    drupal_get_path('module', 'ajax_example') . '/ajax_example.js',
  );
}

I think so a javascript file is added when a page loads.In this case page loads after hook_submit gets called.Why dont you try to add the js the time a page loads in hook_init and try.

Thanks,
Keep calm and clear the cache.


programmatically taxonomy update node DrupalDefaultEntityController error When I programmatically create a taxonomy term and update node, in hook_node_presave() I have the following code:

$node->field_status_tags[LANGUAGE_NONE][]['tid'] = $value->tid;

I get the following error:

  Notice: Array to string conversion in DrupalDefaultEntityController->cacheGet() (line 369 of  includes\entity.inc).

This is the code I am using. I'm sure the value for tid is right.

/**
 * Implements hook_node_presave().
 */
function love_layout_node_presave($node) {
  /*
   *if ($node->nid && $node->moderate) {
   *  // Reset votes when node is updated:
   *  $node->score = 0;
   *  $node->users = '';
   *  $node->votes = 0;
   *}
   */
  if($node->type == 'status') {

   $pattern = '/#([^\\#|.]+)#/';
   preg_match_all($pattern, $node->title, $matches, PREG_SET_ORDER);
   $node->field_status_tags[LANGUAGE_NONE] = array();
   foreach ($matches as $key => $value) {

      $term_name = $value[1];
      $term = taxonomy_get_term_by_name($term_name);
      if(!count($term)){
       $term = new stdClass();
       $term->vid = 1;
       $term->name = $term_name;
       taxonomy_term_save($term);
       $term = taxonomy_get_term_by_name($term_name);
       foreach ($term as $value) {
          //dpm($value,$key);
          $node->field_status_tags[LANGUAGE_NONE][]['tid'] = (int) $value->tid;
        }
      }else{
        foreach ($term as $key => $value) {
          //dpm($value,$key);
          $node->field_status_tags[LANGUAGE_NONE][]['tid'] = (int) $value->tid;
        }
      }
   }
   //dpm($node,'love_layout_node_presave-node');
  }
}

Basically I would think that $value->tid when you are using it is not a number but an array. Because I do the same assignment and it works.

So I suspect you are misusing the taxonomy term you created. This is how I created the taxonomy in a function:

function create_new_term($term_name, $vocabulary_id, $language = LANGUAGE_NONE, $i18n_tsid = 0){
  $tid = db_insert('taxonomy_term_data')
  ->fields(array(
    'name'=>$term_name,
    'vid'=>$vocabulary_id,
    'language'=>$language,
    'i18n_tsid'=>$i18n_tsid,
  ))->execute();
  db_insert('taxonomy_term_hierarchy')
    ->fields(array(
      'tid'=>$tid,
      'parent'=>0,
  ))
  ->execute();
  print "Created new taxonomy term tid #".$tid." $term_name in $vocabulary_id<br>"."\n";
  return $tid;
}

And here is how I add that term:

$my_new_node->field_my_term['LANGUAGE_NONE'] [] ['tid'] = $returned_tid;

I hope this helps.

This appears to be the same as one the existing core issues (https://drupal.org/node/1525176).

As of 2013-09-11, there are patches in the issue, but it still remains open.


Using ImageWidget as form element I would like to have a multi image upload in my form with an option to sort images and provide optional title/alt. This functoonality is present in the image widget field widget plugin and so instead of writing a lot of new code I am wondering if there is a simple way to use it as form element somehow?

I agree with @mradcliffe, that there is probably no simple way to reuse field widgets for normal form fields. The code of field widgets heavily depend on an underlying entity field.

I think the best solution is to create a mock custom entity. As you obviously don't need to store the result, otherwise you would already use an entity, you can set

"storage" = "Drupal\Core\Entity\ContentEntityNullStorage",

in the entity. Example for this is the core Contact Form, which needs very little code to implement fully customizable forms by reusing the form API for entity forms.

Simply configure your field to unlimited value with image type, and you'll get exactly what you said: upload multiple images, provide there title and alt attributes, and sort them.

You can change this in the field parameter (number of authorized values).


How do I get only one result using db_query() I am transitioning from 'old school' PHP MySQL methods of using mysql_fetch_array(), etc. and I am trying to be more Drupally by using the Database API in my modules.

I simply want to return and print out a value. For example:

$query = db_query("SELECT zip FROM {zipcodes} WHERE city = :city LIMIT 1", array(":city" => $city));

I know the value is there, I can access and print it by using traditional methods outside the database API.

print $query->zip is not working.

The API documentation is as clear as mud.

Can someone tell me the correct way to access these values?

Is there a good tutorial anyone could recommend as well?

If you wish to fetch only one result you could use fetchField with db_query to fetch the result, e.g.:

$zip_code = db_query("SELECT zip from {zipcodes} WHERE city = :city LIMIT 1", array(":city" => $city))->fetchField();

You could also fetch the values retrieved from the query's returned result source using options like fetchObject() similar to methods of conventional PHP (mysql_fetch_object) coding like using and get results.

Drupal 6

$query will be your result
You need to fetch values from it,
In your case If it fetches only 1 row and 1 column i.e zip then to get directly

$zip = db_result(db_query("YOUR SQL QUERY"));

$query->zip will not work as $query is result set not a loaded object or an array.
So this should do

while($row = db_fetch_object($res)){
  $row->zip ; // etc
}

Note: db_fetch_array is another API to fetch values in array format


How to create a contact form using FAPI in a custom module? I want to create a contact form using FAPI my custom module.

I created 2 files: one is .info and the other is .module. But I do not understand how I should link that module with my template name page--contact-us.tpl.php as I already activated that module from module list.

I used the code below in my module_name-module:

<?php
  function my_module_form($form,&$form_state) {
  $form['name'] = array(
    '#type' => 'textfield',
  );
  $form['company'] = array(
    '#type' => 'textfield',
  );
  $form['phone'] = array(
    '#type' => 'textfield',
  );
  $form['email'] = array(
    '#type' => 'textfield',
  );
  $form['message'] = array(
    '#type' => 'textfield',
  );
  return $form;
  }

And in my template.php file I wrote this code:

<?php
 function mytheme_theme($existing, $type, $theme, $path) {
 $items['my_module_form'] = array(
 'render element' => 'form',
 'template' => 'page--contact-us',
 'path' => drupal_get_path('theme', 'mytheme') . '/template',
  );
  return $items;
  }
  ?>

Finally I wrote a single line of code in my page--contact-us.tpl.php file to check whether a name field is appearing or not:

<?php print render($form['name']); ?>.

But nothing is happening on my contact-us page ... Why?

UPDATED: I also implemented hook_menu, here it is:

 function form_module_menu() {
 $items = array();
 $items['contact-us'] = array(
 'page callback' => 'drupal_get_form',
 'page arguments' => array('form_module_form'),
 'access callback' => TRUE
 );
 return
 $items;
 }

When dealing with Form API in Drupal 7 there are two major steps:

Step 1: Create and implement the form in a module

In this step 1, you will setup the form, and then validate and submit the form, as further detailed below.

a) Setup the form

    function form_example() {
       $form['first_name']=array(
       '#type' => 'textfield',
       '#title' => t('First name'),
       '#description' => t('Enter first name'),
        );
        $form['last_name']=array(
        '#type' => 'textfield',
        '#title' => t('Last name'),
        '#description' => t('Enter last name'),
        );
    $form['submit_button'] = array(
        '#type' => 'submit',
        '#value' => t('Click Here!'),
        );

    return $form;
    }

    function form_example_validate($form, &$form_state) {

    }
    function form_example_submit($form, &$form_state) {

    }

b) Validate and submit the form

Now the form is ready to be displayed.

One way to display the form, is to theme the form in the module and then print the form.

function mytheme_theme($existing, $type, $theme, $path) {
   'theme_contact_form' => array (
        'variables' => array(
            'contact_form' => FALSE,
            ),
        'template' =>'theme-contact-form',
    ),
 }
function mytheme_block_info() {
   $blocks['block_contact_form'] = array(
      'info' => t('My Theme Contact form'),
      );
   return $blocks;
}
function mytheme_block_view($delta = '') {
  $block = array();
  switch ($delta) {
  case 'block_contact_form':
        $block['content'] = array(
            '#theme' => 'theme_contact_form',
            '#contact_form' => drupal_get_form('form_example'),
            );
        break;
  }
  return $block;
}

Then create theme-contact-form.tpl.php in the module file and print the form:

<?php print render($contact_form); ?>

With all previous steps complpeted, the form is created and implemented in the module.

Step 2: style the form

To style the form from theme layer, refer to How to a use a template file to theme a form?

There are no any need of callback or anything just add bellow code in any custom module.
Drupal have inbuilt facility for contact form so if you want to add field just alter form using hook_form_alter.

function YOURMODULENAME_form_alter(&$form, &$form_state, $form_id) {
  if($form_id === 'contact_site_form') {
  $form['name'] = array(
    '#type' => 'textfield',
  );
  $form['company'] = array(
    '#type' => 'textfield',
  );
  $form['phone'] = array(
    '#type' => 'textfield',
  );
  $form['email'] = array(
    '#type' => 'textfield',
  );
  $form['message'] = array(
    '#type' => 'textfield',
  );
  return $form;
}
}


Crumbs not adding home link to beginning I have installed Crumbs on the site I am currently working on and for some reason I can't get it to display the "Home" link.

I have tried debugging some of the nodes and according to the results the home link should be displayed.

The home link is definitely enabled and there isn't any CSS or anything like that which may be interfering with it, am I missing something?

How to find out why not seeing the home link in bredcrums Drupal 8.

Check your theme (admin/appearance/settings/THEMENAME)

Some themes like bootstrap can set to show or not.
Check modules for any 'hook_system_breadcrumb_alter'

These can alter how bredcrums work.
Check modules for any services tagged with - "{ name: breadcrumb_builder" (same as above)
Check theme templates for any templates overriding core bredcrums or .theme overrides
Check if the block is enabled (admin/structure/block)
Cry

Not sure what the cause of the problem was, but this was solved by using jQuery to prepend a "Home" link to the start of the breadcrumbs list.


Regenerate image styles I'm currently using Drupal 8.2.3 for my website design. My aim is to use it for publishing my blogs to social media sites, such as Facebook, Twitter, LinkedIN, etc. With that in mind, i'm using image styles to create OpenGraph and Twitter meta tags in my blog posts to properly display content on various platforms.

The problem comes when I make a change to the imagestyle. When I flush the contents, it doesn't automatically regenerate the imagestyle content for my metadata. Is there a way to automatically regenerate the imagestyles and content?

Any help much appreciated.

There is a setting to flush the image style at admin/config/media/image-styles:

Or you can use drush:

drush image-flush --all (flush all styles)
drush image-flush thumbnail (flush thumbnail style)

It seems you want to generate proper metatags for your node pages (blogs).
To generate them dynamically i propose to add to your module.module file next code with hook_entity_view function:

  function your_module_entity_view(array &$build, \Drupal\Core\Entity\EntityInterface $entity, \Drupal\Core\Entity\Display\EntityViewDisplayInterface $display, $view_mode) {

  if ($entity->getEntityTypeId() == 'node') {
      $bundle = $entity->bundle();
      switch ($bundle){
          case 'blog':
              $image = $entity->get('field_image');
              $image_id = $image->getValue()[0]['target_id'];
              $image_file = \Drupal\file\Entity\File::load($image_id);
              $uri = $image_file->uri->value;
              $facebook_image_url = Drupal\image\Entity\ImageStyle::load('your_facebook_style')->buildUrl($uri);
              $facebook_metatag = [
                  '#tag' => 'meta',
                  '#attributes' => [
                    'property' => 'og:image',
                    'content' => $facebook_image_url,
                  ],
                ];
               $build['#attached']['html_head'][] = [$facebook_metatag, 'facebook_metatag'];
// the same for other social networks:

$twitter_image_url = Drupal\image\Entity\ImageStyle::load('your_twitter_style')->buildUrl($uri);
//etc
                  break;

          }

      }

    }

And you get this metatag type meta property="og:image"              content="http://static01.nyt.com/images/2015/02/19/arts/international/19iht-btnumbers19A/19iht-btnumbers19A-facebookJumbo-v2.jpg"
Also you can add any metatag in such a manner:

 $facebook_metatag = [
    '#tag' => 'meta',
    '#attributes' => [
             'property' => 'og:title',
             'content' => $your_node_title,
          ],
   ];
   $build['#attached']['html_head'][] = [$facebook_metatag, 'facebook_metatag'];


Extra Space Below Footer in Drupal 7 I'm currently in the process of updating our current site from Drupal 6 to Drupal 7. Between the designer guy and myself, we have been banging our heads trying to figure out where the extra large chunk of space below our footer is coming from. We have added two new regions and three blocks below our main content and when enabling the blocks, the space appears. We have tried everything we can think of. Any help would be greatly appreciated. Thank you.

The site URL is http://prosifland.webhost.uits.arizona.edu/

This looks more like a css issue than a drupal issue.
I am not sure if you are looking for some drupal hooks to solve this problem. But adding this css will solve the issue.

 .region-links-region{
      overflow: hidden;
  }

If this does not work, you can try overflow: hidden !important;


How do I use a different node template on taxonomy term node listing pages? For a node listing on a taxonomy term page, like:

  taxonomy/term/4

It's currently using the node template I set up just for when you are looking at a node:

  node--spot.tpl.php

I added this code to hook_preprocess_node:

if(arg(0) == 'taxonomy') {
  array_push($vars['theme_hook_suggestions'], 'node_taxonomy');
}

The node template file name I want to use is:

  node-taxonomy.tpl.php

I confirmed the hook is running but it's still using:

  node--spot.tpl.php

What am I doing wrong?

Update 1: According to the source code theme_hook_suggestions are listed in reverse priority order, so I changed array_unshift to array_push.

Update 2: I am correctly seeing in Devel themer that my template should be used first, even when it isn't:

  node_taxonomy < node_14 < node_spot < sites/all/themes/hotness/templates/node--spot.tpl.php

This answer had two parts:

As detailed in my Update #1, you have to put your suggestion last in the theme_hook_suggestions array, as last is highest priority.
Your template files must be named with two dashes, not one.

File system:

  node--taxonomy.tpl.php

As added to theme_hook_suggestions array:

  node__taxonomy

Actually there is $variables['theme_hook_suggestions'] in hook_preprocess_node, $vars is in hook_preprocess_page I guess.


How do I jump to a specific place on a page? I wish to be able to jump to a specific place on a given page.

I have inserted  into the text of the page, and set the link to the page to be "about_us/customers/#placetojumpto."

If I type the URL in the address bar it works fine, but when I try use the link generated by Drupal, it converts the "#" to "%2523," so the link becomes "about_us/customers/%2523placetojumpto" and then fails.

The problem is that you have the #, called fragment, in the path, Drupal escapes it for you, and what you need to do is tell Drupal specifically that you want a fragment in the url.

Example:

l('linktext', 'node/1', array('fragment' => 'placetojumpto'));

Documentation here: http://api.drupal.org/api/drupal/includes--common.inc/function/l/7


How to configure Workbench to allow author to publish own content without moderation? I have author role for creating content. This content is moderated by moderators. Now I would like to add second role super author. Super author can published his own content without moderation. How should I configure Workbench for this?

EDIT

There is a WB Access permission for this:

  Bypass moderation restrictions

Have a look at this issue, it discusses this topic: https://www.drupal.org/node/1338750


"Drupal calls should be avoided in classes, use dependency injection instead" In my module using below code for getting url alias of given url:

$alias = \Drupal::service('path.alias_manager')->getPathByAlias($_POST['url']);

But one I run Automated Review(http://pareview.sh/) in my module I am getting below warning:

  16 | WARNING | \Drupal calls should be avoided in classes, use dependency injection instead

How can I update above code using dependency injection? My entire class code is given below.

<?php

namespace Drupal\my_module\Controller;

use Drupal\Core\Controller\ControllerBase;

/**
 * MyModule Class defines ajax callback function.
 */
class MyModule extends ControllerBase {
/**
 * Callback function for ajax request.
 */

  public function getUserContent() {
    $alias = \Drupal::service('path.alias_manager')->getPathByAlias($_POST['url']);
    $alias = explode('/', $alias);
    $my_module_views = views_embed_view('my_module', 'default', $alias[2]);
    $my_module= drupal_render($my_module_views);
    return array(
      '#name' => 'my_module_content',
      '#markup' => '
' . $my_module. '
',
    );
  }

}

Take the BlockLibraryController class as example; it extends the same class as your controller.

You define:

A static and public create() method that gets the values from the dependency container, and creates a new object of your class
A class constructor that saves the values passed from the previous method in object properties
A set of object properties to save the values passed in the class constructor

In your case, the code would be similar to the following one.

class MyModuleController extends ControllerBase {
  /**
   * The path alias manager.
   *
   * @var \Drupal\Core\Path\AliasManagerInterface
   */
  protected aliasManager;

  /**
   * Constructs a MyModuleController object.
   *
   * @param \Drupal\Core\Path\AliasManagerInterface $alias_manager
   *   The path alias manager.
   */
  public function __construct(AliasManagerInterface $alias_manager) {
    $this->aliasManager = $alias_manager;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('path.alias_manager')
    );
  }

  /**
   * {@inheritdoc}
   */
  public function getUserContent() {
    $alias = $this->aliasManager->getPathByAlias($_POST['url']);
    // Omissis.
  }

}

Don't forget to put use \Drupal\Core\Path\AliasManagerInterface; on the top of the file containing the code you are showing.

As side note, the code you use to render the view is wrong: You don't need to use drupal_render() because views_embed_view() already returns a renderable array.
Then, the render array you are returning is probably not giving the output you expect. #name is probably not going to be used from Drupal, and #markup filters the markup you are passing to it, as described on Render API overview.

  #markup: Specifies that the array provides HTML markup directly. Unless the markup is very simple, such as an explanation in a paragraph tag, it is normally preferable to use #theme or #type instead, so that the theme can customize the markup. Note that the value is passed through \Drupal\Component\Utility\Xss::filterAdmin(), which strips known XSS vectors while allowing a permissive list of HTML tags that are not XSS vectors. (I.e, <script> and <style> are not allowed.) See \Drupal\Component\Utility\Xss::$adminTags for the list of tags that will be allowed. If your markup needs any of the tags that are not in this whitelist, then you can implement a theme hook and template file and/or an asset library. Alternatively, you can use the render array key #allowed_tags to alter which tags are filtered.
  #allowed_tags: If #markup is supplied this can be used to change which tags are using to filter the markup. The value should be an array of tags that Xss::filter() would accept. If #plain_text is set this value is ignored.

It is other for to solve the problem.
https://www.previousnext.com.au/blog/injecting-dependencies-into-drupal-8-plugins


Can Date API/Calendar and CCK send an argument to Views with data from a field? I have a data/calendar content type using the Date API and Calendar Modules. Each event I add to the calendar uses Advanced Node Reference and returns a list of 5 other events of the same type.

What I want is a list of the next five events following the event node's advertised event date (not the date it was published). If a new event node is added, and it falls within the next five events parameter, then when the page is generated, it is listed, bumping the furthest future event from the list. If a event node is removed, then a new (previously out of range) event node is added to the list. It is a simple sort, and very reasonable requirement using the "advertised" date and not the "published" date. The field data would be the advertised date.

The Node Reference module allows a view to be used to make the selection to populate the node reference. This I have also done. The problem is the list of possible dates/events to be linked are produced by a filter with relative date value from today's date ('>= now'), rather than from the node's content value for event date.

TDW might use an argument to pass the current date value of the date/event being edited to Views. If this exists, where is it? What is it? Some kind of [keyword] to pass in the allowed argument field of the Advanced Node Reference of this Date Content Type?

If this was a PHP template I was hand coding, the value of the current form's 'event date' field would be available from the query used to populate the form. In Drupal I don't know where this is. I'm still a newbie at Devel Module and its variables page was no help.

It sounds like you need to do a relationship to the parent node, and then use a Filter by node published date using that relationship.


Override templates for one view page or block I am trying to figure out if there is a way to override the base templates for one view.
I created a page with a view called 'Promotions'.
I need to override the views-view-field.html.twig, views-view-fields.html.twig, and views-view-unformatted.html.twig for just the one view/page.

I read about putting it into your custom theme's template folder in it's own folder that mimics the page name.
In my case, following the example it was views-view-fields--promotions--page.

The overrides work but they work for all the views (pages and blocks) that I created.
Can you narrow it down to just one view/page?

Yes.

The pattern will be something like views-view-promotions--display_name.html.twig

See https://api.drupal.org/api/drupal/core%21modules%21views%21views.theme.inc/group/views_templates/8.2.x

Also, I recommend you activate Twig debugging (https://www.drupal.org/docs/8/theming/twig/debugging-twig-templates) to see actual suggestions.

Hey i think you need to override only one node template,

If i am not wrong then,you need to override only node page for eg.you created 'Promotion' node page and in your case your 'Promotion' page node has eg. 101.

According to that node '101' will be override.

eg. node--101.html.twig  or
    node--promotion.html.twig

Note - You don't need to create views view for this.

Hope,this will help you.


Embedded views into another view via twig_tweaks, but the results only update after clearing drupal caches I have a view that needs to embed child views, which I did using the twig_tweaks module to insert the child view as a field in my parent view, by using a custom text field:
{{ drupal_view('my_child_view', 'block_1', arguments.null, tid) }}

The first argument arguments.null is the group id, which the child views get from the URL
example.com/group/58/parent-view
It all works perfectly when i view the results for a given group id. However, when I then open the view for another group id, I get the results for the first queried group id. The results will only change after i delete the Drupal caches. Then I can display the view correctly for any group id, but afterwards, it will again never change the results.
My best guess is that the results of the embedded view are cached? Is there any way to disable this? I tried including {'#cache': {'max-age': 0}} into the custom text embedding the child view, but this did not help either.

Use the Views Field View module instead.

There are a lot of cases in views where you want to embed a list inside each row. One
example could be, you have a list of groups, and for each groups you
want to list the first and last name of all of their members.

Then in the Views UI add view embed as field.

I found an easy solution: just disable the caching for the parent view itself in its advanced settings.


Why a unnamed  is added to a specific region? I have 2 blocks sitting in a region called "headline".

Drupal 8 seems to add these 2 blocks , into an unnamed div and thus their display:flex CSS layout is cancelled (you can't scatter 2 container items if these are wrapped into one div).

Please see attached image to make sure you understand me.

I have no idea where this inspected div is coming from. I don't recall adding it myself. Only because it seems to be added by Drupal 8 itself, I publish this question here.

The problem can be seen live here.

A Drupal 8 themer might have an idea on why this is happening.

I might need to note that the twig markup also doesn't contain such div.

The regions' twig markup:

{% if page.headline %}
     {{ page.headline }}
{% endif %}

The CSS code I used:

#headline . container {display: flex; flex-direction: column; align-items: center}

@media screen and (min-width: 1080px) {

#headline .container {display: flex; flex-direction: row; justify-content: space-between; align-content: flex-start; flex: 1; margin: 0 auto}

}

It could be coming from region.html.twig:

https://api.drupal.org/api/drupal/core%21modules%21system%21templates%21region.html.twig/8.2.x

{% if content %}
  <div{{ attributes }}>
    {{ content }}
  </div>
{% endif %}

→
{% if content %}
  <div{{ attributes != '' }}>
    {{ content }}
  </div>
{% endif %}


Is there a way to clone a content type and its fields? I have a content type named "event_xyz" that I want to rename to "event".  I figure I can clone the content type and then delete the original.  But I don't see any tuts or modules on how to do this.

Alternatively, is there a way to rename a bundle's machine name?

I found a closed question related to cloning content types for Drupal 7, but not for Drupal 8.

The best way to do this is the entity_clone contrib module.  I downloaded it, installed it, hit the clone button and all of fields and form settings were copied to the new content type.  It worked very well.

For D7, you can use Node Convert.  Build a fresh content type, with fields new/same/similar then use field mapping (field matching) to move/migrate them. Maybe or maybe not with Views Bulk Operations.


Complete export of Drupal nodes I am programatically generating nodes in my local Drupal 6 installation.  I have to do it locally because I don't have access to some of the more nifty PHP commands / modules that I need in order to create the modules on the production server.

These nodes come out properly formatted with aliases already created, and I would like to export those to the production server with aliases intact.

I have been attempting to use the Node Export module, however that doesn't preserve aliases (as far as I can see anyway).  The Deployment module has never left alpha for Drupal 6, and I have been running into errors while using it.  When it did work, aliases were not preserved.

Is there a method to preserve aliases available?

I've successfully used a combination of the following modules to do similar migrations:

feeds (for import)
feeds_tamper (data normalization and mapping)
views_rss or views_bonus (RSS feed of nodes or CSV export)

I can see (although I've never used) a patch for the Feeds module to maintain aliases as found here http://drupal.org/node/1284522

One big bonus with using the Feeds module for import is it understands (through a hashing system) data that has already been imported. So, if you used the ViewsRSS module you can setup a timed event for Feeds to grab only the new or update existing content without having to initiate a transfer on the production server -- they just stay in sync. I've also implemented a workflow where nodes are only published in the RSS feed after they have been reviewed by an editor ...

Cheers,

Rob McCrea

I know this is an old link but I had a similar issue: I have two drupal systems and I wanted to export nodes from one drupal install and import them into another. When exporting/importing nodes via node-export, the menu links and the node path alias were not getting imported.

I noticed settings on admin/config/content/node_export/ for each content type. There are checkboxes that allow you to "reset the values" of the alias, parent menu, etc. on import. Make sure the items you need are unchecked.

Drupal 7.


Different responsive image per breakpoint I have the following scenario - the main page banner should have at any time 1 of 3 images displayed at a given viewport size. These images are art-directed, that is to say, that will differ in content and layout and are created with desktop, tablet and mobile in mind. (All of this is despite my protests).

I'm wondering what are the options for requesting the correct image at the appropriate viewport size? (Optimisation is very much a concern here! I don't want to serve 3 images only to use 1.) My understanding when it comes to D8 and responsive images is that D8 will create versions of the same image for the srcset rather than giving the option to serve different images at different viewport sizes.

So what are my options here? Perhaps the best option is to have 3 image fields that are outputting directly into a srcset in a banner template.

Are they completely different images?

Then I'd use Paragraphs module and create a heavily customized template outputting your different images as <source srcset="..." media=""> inside a single <picture> tag. Modern browsers will only download the correct version for the visitors viewport. (Manually add a polyfill library if required.)

Is there one large source image rendered with different focal points or different crop areas (Modules "Focal point" or "Image widget crop")?

Then I'd create a specific breakpoint group only for your banner. Create a responsive image style for this group and use Select a single image style for each individual breakpoint width. Drupal will then automatically render a similar markup as above and also add polyfills for older browsers.

In any case, definitely use a <picture> tag with multiple <source srcset="...filename..." media="(...mediaquery...)">s for art directed responsive images.

I came across the same problem, solved it, and wrote a tutorial about it.
The key is to use 2 different images (rendered as picture elements), positioned on the same place. An image uses the Mobile only responsive image style; the other images uses the Desktop only style. In this way, for any given viewport, there is only an image loaded and visible.
Implementing a hook, it's possible to add a max-width property to the Mobile only image style to make it not visible in desktop mode. Another can prevent the <img> tag from rendering.
function od_helper_preprocess_responsive_image(&$variables) {
  $responsive_image_style = $variables['responsive_image_style_id'];

  // Prevent mobile images to be shown for viewport-width > 767px.
  if ($responsive_image_style == "mobile") {
    if (isset($variables['sources'])) {
      foreach ($variables['sources'] as $source) {
        $value = $source["media"]->value();
        $value = $value . " and (max-width:767px)";
        $source["media"] = new AttributeString("media", $value);
      }
    }

  // Prevent fallback-image from rendering by removing src and alt and store it in data attributes. This fallback-images are later repaired depending on viewport size by js behaviour px1_ResponsiveImageContainerActivateFallbacks

  if ($responsive_image_style == "mobile" ||
      $responsive_image_style == "desktop") {

    $img = $variables["img_element"];
    $img["#attributes"]["data-src"] = $img["#uri"];
    $img["#attributes"]["data-alt"] = $img["#alt"];
    $img["#uri"] = "";
    $img["#alt"] = "";
    $variables["img_element"] = $img;
  }
}

We can later activate the appropriate image via JavaScript, depending on the viewport size. This is relevant for Internet Explorer which doesn't support the picture element.


Display a key from unserialized data field I really don't understand how the "User: Data" field works. Couldn't find any documentation of this.

I want to set the Display format to "A certain key" to output the identifier value from this serialized data (relevant snippet):

a:1:{s:10:"hybridauth";a:26:{s:10:"identifier";s:17:"76561198181833179";

When I enter identifier as key, I only get this notice and no output.

  Notice: Undefined index: identifier in views_handler_field_serialized->render() (line 60 of www/htdocs/****/sites/all/modules/views/handlers/views_handler_field_serialized.inc).

What do I have to enter in the "Which key should be displayed" field exactly, to display the identifier value?

You need to add an Global PHP field and put the following code in output value to get the identifier field value.

<?php
 $result = unserialize($row->data);
 print $result['identifier'];
?>

Note : You should exclude Data field from display.

Since you very cautious in not using PHP, did you try the following option, change the ckeditor_skin to identifier. But it will produce the output as 76561198181833179['identifier'].

Try %ckeditor_skin in the field 'Which key should be displayed'.

If the error message

  Notice: Undefined index: identifier in views_handler_field_serialized-render() (line 60 of /www/htdocs/drupalsite/sites/all/modules/views/handlers/views_handler_field_serialized.inc).

still exists but the number of the error messages is less than before, try to change the code

return check_plain($value[$this->options['key']])

to:

if (!empty($value[$this->options['key']])) {
  return check_plain($value[$this->options['key']]);
}

in line 60 of the module file to avoid the error message.


How to reset 'new' and 'updated' flags without visiting a node page? In my drupal site I have a content type that has its nodes visible only in a view and they have always the 'new' (or 'updated') flag up for all users.

How can I reset the flags without visiting the node page?
Is there a function to tell drupal "this user has seen this node"?

You can use node_tag_new() for that

  Updates the 'last viewed' timestamp of the specified node for current user.

e.g.

node_tag_new($node);

Check out the theme function theme_mark:

function theme_mark($variables) {
  $type = $variables['type'];
  global $user;
  if ($user->uid) {
    if ($type == MARK_NEW) {
      return ' ' . t('new') . '';
    }
    elseif ($type == MARK_UPDATED) {
      return ' ' . t('updated') . '';
    }
  }
}

You can use that in a module to override the marking of your nodes. So if you define mymodule_theme_mark like:

function mymodule_theme_mark($variables) {
  $type = $variables['type'];
  global $user;
  if ($user->uid) {
    if ($type == MARK_NEW && (NOT YOUR NODE VIEW TYPE) ) {
      return ' ' . t('new') . '';
    }
    elseif ($type == MARK_UPDATED && (NOT YOUR NODE VIEW TYPE)) {
      return ' ' . t('updated') . '';
    }
  }
}

That should get you close to where you need to be.


How to get fields of certain content type in template file without writing iteration loops in tpls? Here I'm getting all fields of certain content type in my .tpl.php file with the help of hook_theme.

return theme('carousal', array('carousal' => $fields));

And my template file is something like this:

<?php
global $fields;
foreach($fields as $key => $value){
echo $value['title'];
print render ($value['fields']['body']);
}
?>

Now, what I want is, I don't wanna use foreach loop in my template file. And if possible, not even any php tags.

How far is it possible to render fields in template file without using any loop?

Can't we write only "BODY" and we get "body" field rendered itself automatically?

I don't know whether it's possible or not. If it's possible, kindly let me know the way out of this.

You can pass your $fields to a custom function. Run your logic or foreach loop in the custom function and pass the title,body values back. Thus you would not need to use the foreach loop in template file.

Here is some sample code if it helps.

$field_data = _my_function($fields);
$data = theme('carousal', array('carousal' => $field_data));
return $data;

Try this

print render($content['your_field_name']);

this will print that field value .


Storing a date created with Form API Very simply, I'm creating a date of birth field pragmatically like so:

  $form['dob'] = array(
    '#type' => 'date',
    '#required' => TRUE,
    '#title' => t('Date of Birth'),
    '#default_value' => $sponsorship->dob,
  );

The API says the return value is in the form:

array('year' => 2007, 'month' => 2, 'day'=> 15)

My question is simply, how should I store this in a database table? I originally set the table column to varchar. But I would like to know what is normal practice and most efficient for handling a date using the Form API for Drupal, both saving to the database and then displaying on a page.

Drupal 7 Schema API Data types does not support the DATE datatype that you find in popular SQL dialects such as MySQL.  My preferred solution is the same as the one you suggest (set the column to varchar and store it as a an ISO 8601 format date string: 2013-05-07 for May 7, 2013).  It is human readable (useful when debugging) and it is the format used by the DATE format of most SQL dialects.

For date arithmetic, I use built-in PHP-functions such as gregoriantojd to convert to Julian dates to compute date differences, etc.

While it is possible to force Drupal to use the DATE type to your SQL dialect of choice - see this answer for details, a varcharis the simplest and most portable solution.

For displaying a date in Drupal, you may want to use the the Drupal format_date function (from common.inc), as this makes sure that dates are rendered consistent across the site, and adapt month names, etc. to the preferred language.  Note that this function takes a Unix timestamp as its first argument, so you need to convert from the ISO 8601-format to a Unix timestamp in order to use this (and this won't work for dates fore 1970-01-01).  Because of this limitation I instead use a small custom module with a slightly adapted copy of this core function that shares the format templates with the core function, but accepts an ISO 8601 date and datetime as valid input. I also supply my own custom format (you can set up this on the Home » Administration » Configuration » Regional and language  » Date and time  » Add Date type admin page) without any hours, minutes or seconds.

PS: Some people recommend using Unix timestamps (seconds from epoch starting 1970-01-01) for anything that has to to with time and date.  However, I do not like to use Unix timestamps  for dates where the resolution wanted is whole days.  In addition to not being human readable, and having a rather limited timespan (making it inappropriate to store the date of birth for someone born before 1970), Unix timestamp dates based upon the local time tend to produce weird bugs when dates cross seasons because DST is being taken into account when you do not expect it.  It may be considered strange that I depreciate the Unix timestamp when the format_date function wants this format - but I find that storing the dates in the database  in the ISO 8601 format is so attractive that I put up this extra conversion step when calling the format_date function.


How to attach profile type to specific user role? I have multiple profile types and multiple user roles.  I want to combine specific profile types with users of specific roles.  For example, customer roles have their own profiles, content authors have their own profiles, etc.

Is there a way to assign them together?


How to set a coming soon page on drupal? All request must be redirected to the coming soon page, is there any module can do it or a solution, I'm using the zen base theme.

Thank you for your help :)

You can put the site on maintaince mode and can use the message as coming soon.

you can create a panel with one column and put a block in it with all data you need
so you wil have a new page with a unique url then choose this page from configuration - site information in Default 404 (not found) page or put its link to all your incoming page


How to modify taxonomy term path in the page render array? I'm trying to change the path of a term before it's displayed on a node page. I'm using this preprocess function in template.php:

function bartik_preprocess_node(&$variables) {
    $variables['field_photo_topic']['0']['taxonomy_term']->uri['path'] = 'photo/test';
}

The path won't change, what am I missing? This is the dpm output:

This question makes perfect sense if photo/% and video/% are views.  It might be even better to map taxonomy/term/% to topic/%, and then make a single view with a path topic/%/%, where one argument is the content type and the other is the taxonomy term. However, you may also use the paths you suggest by building two views (or two pages in one view), each with its own path.

On to your main question, though. Changing items in the render array is easy, but it can sometimes be hard to figure out what needs to change and when. It is a general problem with render arrays that sometimes there are shadow copies of info that are available for your reference. Changing these copies does not affect the rendering of the page, because they are only copies of the item that is used to build the actual page.  The problem with the code in your question is that it was altering a copy of the target link; the master information that you need to change to affect page rendering appears somewhere else in the data structure.  You need to adjust the copy that appears inside the 'content' item.

Here is some code that works for a similar content type:

function MYTHEME_preprocess_node(&$vars) {
  if (array_key_exists('content', $vars)) {
    $content = &$vars['content'];
      if (array_key_exists('field_photo_topic', $content)) {
        foreach ($content['field_photo_topic']['#items'] as $index => $info) {
          $tid = $info['tid'];
          $content['field_photo_topic'][$index]['#href'] = 'photos/' . $tid;
        }
      }
  }
}

From here, you can use pathauto to map photos/% to a pleasing URL to your photos + taxonomy term view.

First, I don't understand why you would do this, the taxonomy is still going to have this path, your theme is just going to show a wrong path for it if it worked. Have you tried using autopath module or changing the path in the taxonomy form? There you can define an alias for the taxonomoy.

If what you are trying is to change the taxonomy of a node, then change the node. What you are doing now is probably working but being overwritten by some other process. But I think you might want to provide more details, since your question is not very clear.


Modify field in node drupal 7 I have field "myfield" in a node. The field is created in the content, not by hook. I want to change the value of that field. I do not want to display the value from database, but my value let's say random number. I tried to do this with hook_node_view and with hook_entity_view but I cannot change it on the display. Here is my code:

function mymodule_node_view($node, $view_mode) {
  if ($node->type == 'my_node_type') {
    if ($node->nid == 46) {
      $node->myfield['und'][0]['value'] = 55;
//or I tried with $node->content and no success
    }
  }
}

What am I missing? Can you help me, please!
Thanks you in advance!

You can use this line instead:

$node->content['myfield'][0]['#markup'] = '55';


How to add google translate to comments I want to be able to have the ability to translate to comments only , is there any type of module I could use for this

Use the [Automatic] Comment Translation module

  Comment translation utilizes the Microsoft Translator to create translations of submitted comments on nodes that have existing translations available. Translated comments are placed in moderation for review.


Removing line breaks in Twig My twig file is adding line breaks in the HTML which results in white spaces, as shown in this picture:

In the browser inspector:

When I remove the line breaks in the inspector, the white spaces disappear.
The default code in the file views-view-field.html.twig is:
{{ output -}}

I have researched the problem quite a bit and tried the following already, without success:
{{ output|replace({"\n":''}) }}
{{ output|trim }}
{% spaceless %}{{ output }}{% endspaceless %}
{% spaceless %}{{ output|render|trim }}{% endspaceless %}

I'm working on Drupal 8.7.6.
Any help would be appreciated.

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

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

The solution
{{ body|replace({"\n": "", "\r": "", "\t": ""}) }}

works for me in views Global/Custom text field. It removes new lines from the body field.


Find out the user's IP address given their UID? I'm running Drupal 7 web site with a Russian multiplayer card game and have to block some very annoying players every 4-5 days.

Before Drupal I was using phpBB 3. When these persons would come from a small city/village I'd just add their IP-network to the firewall rules, so that they can't re-register with a new mail address. This worked well in my case and my question is not about this policy.

My problem is that with Drupal, I can't find the last IP address used by a user id. I.e. the abuser is reported to me by other users and I know his uid, but I can't find his IP address in the logs, because:

I've enabled syslog-logging and see the Drupal messages in /var/log/messagess but there is rarely a message about a user logging in, probably because sessions are long by default, and I'd like to keep it this way for user comfort.
I've also enabled "database logging," but don't know where to see it (which database table).

If you have statistics module enabled, the "accesslog" table contains the IPs for all your visitors.

SELECT hostname FROM accesslog WHERE uid = %UID_FOR_YOUR_USER% LIMIT 1

If you do not have statistics enabled, I advise you to leave it off, even for this result, because enabling it, causes a severe performance-penalty.

In that case, you can use sessions table:

SELECT hostname FROM sessions WHERE uid = %UID_FOR_YOUR_USER% LIMIT 1

The benefit of the first over the latter, is that the first will always show you the latest hostname, whereas the latter might not always be up to date.

session_id() gives you current user session-id whether he/she is a guest or a member.

$result = db_query("SELECT hostname FROM sessions WHERE sid = '".session_id()."'");
$data = db_fetch_object($result );
echo $data->hostname;


Why do I get "Access Denied" on every page? I've been trying out Drupal 8 on localhost which has been great, and I've now transferred it to a server, but every page gives me Access Denied. I can't even access the front page, or the user login page.

I have tried truncating the session and cache tables, and deleting cookies, but don't know what else to try. I've also installed drush, cleared the cache, and tried user-login drush command - still no access.

What things should I check? How do I fix this?

Don't edit core code as suggested by Flounders answer. If you're not using HTTP auth then simply disable the Basic Auth module via the UI or Drush:

drush pmu basic_auth -y

Drupal has different authentication providers. The defaults are: basic_auth and cookie, basic_auth has a higher priority but is not enabled by default.

After debugging I found what was the problem for me.

Drupal has some authentication providers. For standard pages this are:
basic_auth and cookie (basic_auth has higher priority).

Because test site has a basic_auth from the htaccess, this resulted in that Drupal marked my request as using basic_auth.
Only all pages did not require this.
Result was just redirect to the 403 page (access denied in the watchdog table)

My temporary fix was the following:
Open the file core/modules/basic_auth/src/Authentication/Provider/BasicAuth.php

Go to this code:

public function applies(Request $request) {
    $username = $request->headers->get('PHP_AUTH_USER');
    $password = $request->headers->get('PHP_AUTH_PW');
    return isset($username) && isset($password);
}

Change it to this:

public function applies(Request $request) {
    return false;
    //$username = $request->headers->get('PHP_AUTH_USER');
    //$password = $request->headers->get('PHP_AUTH_PW');
    //return isset($username) && isset($password);
}

If there is a better solution, let me know. But this makes the site working.