Increase weight range for child pages in book outlines (Book module) When a child page is added to a book via "Add child page" (node/add/{content-type}), the Weight drop-down field in the Book Outline tab has a range of -/+ 15. This is due to line 191 in web/core/modules/book/src/BookManager.php:

$form['book']['weight'] = [
  '#type' => 'weight',
  '#title' => $this->t('Weight'),
  '#default_value' => $node->book['weight'],
  '#delta' => max(15, abs($node->book['weight'])), // line 191
  '#weight' => 5,
  '#description' => $this->t('Pages at a given level are ordered first by weight and then by title.'),
 ];

When a child node is initially added, $node->book['weight'] is always 0, resulting in a #delta value of 15. #delta controls the min and max values in the Weight drop-down field mentioned above. There is no way to assign a weight higher than 15.

To simplify the work of non-technical editors repetitively adding chapters to books, we tell them to set the Weight value to the chapter number. This doesn't work for books with more than 15 chapters (which happens).

QUESTION: What is the correct, non-core-hacking way to set the limit to say, 25 in Drupal 8? (see my answer below)

AMENDMENT ADDED 2018-11-24

In addition to the issue expressed above, a related issue is that on the book outline reorder page (admin/structure/book/{book-nid}) there is a drop-down field for the weight of each child page. Child pages with a current weight within the range -/+ 15 get a range of -/+ 15 in their drop-down fields. Child pages with weights outside that range get a drop-down with the range increased to include their current weight.

This is due to lines 202, 203, and 235 in web/core/modules/book/src/Form/BookAdminEditForm.php:

$count = count($tree); // line 202 - count of all child pages for the book
$delta = ($count < 30) ? 15 : intval($count / 2) + 1; // line 203

$form[$id]['weight'] = [
  '#type' => 'weight',
  '#default_value' => $data['link']['weight'],
  '#delta' => max($delta, abs($data['link']['weight'])), // line 235
  '#title' => $this->t('Weight for @title', ['@title' => $data['link']['title']]),
  '#title_display' => 'invisible',
  '#attributes' => [
    'class' => ['book-weight'],
  ],
];

The challenge with varying the weight range based on current weight is that it's not possible to assign a weight greater than 15 to a child page whose current weight is 15 or less because its drop-down allows a maximum of 15. I can add several child pages with weight 0, but I can't change any of them to 16. Maybe I'm missing something in the current user interface?

All of this said, there seems to be a fairly straightforward solution to both of these problems, explained in my answer below. Not knowing every detail of how the Book module works, there may be flaws in what I suggest. I'm using it right now and it seems to work well, but I welcome corrections or suggestions for improvement.

Many people agree it's a big accessibility problem, but it isn't easy to solve and there always seem to be some obstacle.

I just posted about this, possible duplicate, very relevant for this question because the listed issues mention various methods on how to approach solving this and the obstacles you might encounter: How to increase book weight range for a same-level chapters.

The simplest way to solve it might be to rely on an outside sorting method, like Weight, and not on overriding the Book module. I don't have enough expertise to evaluate the difficulty level to modify the Book code, it just seems that way reading the lines and between them on those threads.


How do I add an image to blogs? May you give me few hints on how to enable adding 1 optional image to each blog entry?

I've enabled Blog and Image modules and registered users can create and comment on them.

What is the next step?

Go to "Manage Fields" link for the Blog content type (/admin/structure/types/manage/blog/fields) and add a new field:
Name it whatever you want ("blog_picture" or something) and for the Field Type select "Image"
Click "save", pick a default image if you want and click "save field settings"
On the next screen do not tick "Required", make any other changes you want and click "save settings"
Done!


Token for Field Collection values I have a node that has a field created with Field Collection module.
Field is composed of 3 subfields: dropdown list and 2 text boxes.

I want to get values from those 3 fields in my Rule.

How would I reference those fields?

I have installed Advanced Entity Tokens module.

thx!

Solved! There is a list of all available tokens in: admin/help/token.

In my case I needed to get 3 field values from Field Collection:

[node:field-school-undergrad:0:field-school-list]
[node:field-school-undergrad:0:field-school-degree]
[node:field-school-undergrad:0:field-school-year]


Hook the language switcher and change the URLs it redirects to in Drupal 7 I have a multilanguage site in Drupal 7.

The language negotiation is based on URL. I have got translated content, so when I visit www.example.com/this-is-a-news in English, I can change to Spanish using the language switcher and go to www.example.com/esta-es-una-noticia, which is the URL of the translated node. However, I have some URLs which are dynamic, i.e., they are built in-the-fly, for example: www.example.com/this-is-a-news/on-the-fly-parameter...

As the part of the URL /on-the-fly-parameter is completely dynamic and can change, and because the translation is a non-Drupal table in the database which is updated independently, I want to hook the language switcher and add the translations of all of these URLs dynamically. How can I achieve this?

I have discovered how to do it.

function MYTEMPLATE_language_switch_links_alter(array &$links, $type, $path) {

 $extract_parameters_URL = explode("/", $_SERVER['REQUEST_URI']);

 $code_altered_url = process_URL_extracts($extract_parameters_URL);

 foreach ($links as $langcode => $link) {

    $links[$langcode]['href'] = $code_altered_url ;

 } // foreach


Is there a way to manage public API documentation? I have created a custom module for my site that includes a public REST API.  We've also written public documentation for the API.  It's currently written in Markdown for convenience and easy export.  We maintain the documentation in version control so that it stays up-to-date along with changes to the endpoint in the module itself.

We would like to publish this documentation to the site in a way that is publicly accessible.  I've found documentation on hook_help but that seems to be targeted towards site admins (e.g. documenting settings for the module). Instead, we're looking to document the API endpoint for an end user.  We know we could simply create Page content to hold the documentation but we were looking for something more automatic when the module code is updated.

Is hook_help still the right way to add this content to the site? Is there a way to make only portions of the Help section public? Or is there another way to publish API documentation as part of the module?

We are currently on Drupal 7 if it is relevant.

EDIT:

Additional Info:

We are using the Services module to manage the API endpoint(s)
We are less looking for documentation generation and more looking for a way to publish the documentation that we have already written in a way that it is updated automatically when the module is updated. We maintain our documentation in version control so that it is updated as part of development. By doing it manually, it is more comprehensive and directly useful than generated documentation (IMO). We would just like the work done during development to be displayed publicly without having to do the extra step of copy-pasting to a Page (a step which is easily forgotten).

So far as I know for community driven modules only the Services module has support to autogenerate API documentation via the Services Documention module. If you've been the D7 public API without using Services ... then you may be out of luck.

  The Services Documentation module generates API documentation for your
  site’s Services resources. Most of the documentation is generated
  automatically, using the resource information provided by Services.
  However, this module provides you with the ability to easily extend
  that documentation.

  We make the following assumptions about your usage of the Services
  module:

  You are providing an API to a third party, which allows them to access
  your data via Services.
  You would like to provide a page to API
  consumers that documents your API endpoints, resources, etc.

  Documentation will be made available on your Drupal site at
  /developers.
  It will be organized by API version (arbitrarily defined
  by you), and subsequently displayed hierarchically according to
  resource, method type, method name, arguments, etc.


Does Drupal 7 support connecting to DB using MySQLi? I have tried to connect to Mysql DB using Mysqli by declaring 'driver' => 'mysqli' inside DB array in settings.php but I get the following error:

Warning: require_once(/srv/http/my-domain/includes/database/mysqli/database.inc): failed to open stream: No such file or directory in /http/www/my-domain/includes/database/database.inc on line 1688

Thanks.

No. Drupal 7 does not come with Mysqli support. It only comes with PDO based drivers for MySQL, pgSQL and SQLite.

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

https://www.drupal.org/requirements/pdo

See the files :

INSTALL.mysql.txt
INSTALL.pgsql.txt
INSTALL.sqlite.txt

to find out more about how to install using each option.

There are also many community provided solutions for connecting to other databases including MsSQL, Mongo and Oracle.

Have a look at the Drupal modules page for more information on database drivers

The core advantage of PDO over MySQLi is in its database driver support. PDO supports 10+ different drivers, opposed to MySQLi, which supports MySQL only.

If you are interested in the comparison between PDO and Mysqli there are many articles around including this one.


Thoughts on best practices for user content management I have a website where I need specific user roles (restaurant owner) to edit specific content type (their respective restaurant profile and services) which has a node reference field to the main restaurant profile.

I've been developing a website before where I needed to change the author of the node so this user could edit (with right permission) however, I'm sure there should be a better automated practice.

I am thinking of using Profile 2, with node reference user to a specific content type.

Any ideas on what's best to achieve this ?

If nodes are supposed to match 1:1, why not to make them one node, with different displays and access to different fields?
Or, actually, if you have only one restaurant per owner and one owner per restaurant (and it looks like that, when you say that changing author works) you could define restaurant info as a set of fields at user's profile itself. That way each user would be able to edit his own data, and data of his restaurant, and you can use views to decide what to show and where.


How to resolve lazy_builder error? We have a field that is an Entity Reference to Blocks. In our situation, this field is referencing a View block. We are able to add this field on the content type and node properly, but when the page renders there is the following error message. We set this up using steps from Drupal 8: How to Reference a Views' Block Display from a Field.

  Uncaught PHP Exception DomainException: "When a #lazy_builder callback is specified, no properties can exist; all properties must be generated by the #lazy_builder callback. You specified the following properties: #attached." at /mnt/www/html/netscout/docroot/core/lib/Drupal/Core/Render/Renderer.php line 333

How would we resolve this issue?

What we have tried:

DomainException with #lazy_builder and ['#cache']['keys'], but this did not have anything that helped because we do not load the block by using #lazy_builder
We tried updating our modules, but still get the error message
Tried removing the removing the block reference, but then we were not able to add the view block to the page.

We are using Drupal v8.5.3.

Rather than using Entity Reference to Block, we went with using Viewfield module. It has worked as expected with and without exposed filters.


Drush command to uninstall from enabled...? Is there a command for Drush so I can uninstall a module from the enabled state?  I hate having to drush dis mymod -y (and) drush pm-uninstall mymod -y

Another solution here if you don't want to take the alias route that Tony brought up is to use the && operator to do a one-liner:

drush dis -y my_module && drush pm-uninstall -y my_module


Pre-populate an entity reference field (media image) when creating a node I am trying to open a node creation form (for example, /node/add/article) and to have an Entity Reference field pre-populated.

My field (field_image) is an Entity Reference to a Media of type Image and the form uses the Media Library widget.

I essentially tried doing that by implementing hook_form_alter in a custom module but nothing that I have tried worked. I saw solutions like this one. It works with other field types that I have tried. For example:

// Pre-populate Entity Reference field to taxonomy term

$term = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->load(13);
$form['field_category']['widget'][0]['target_id']['#default_value'] = $term;

The above works just fine. But the below doesn't.

// Pre-populate Entity Reference field to Media Image

$media = \Drupal::entityTypeManager()->getStorage('media')->load(38);
$form['field_image']['widget'][0]['target_id']['#default_value'] = $media;

I also tried by providing just the media id instead of the entity but it didn't work.

I have tried the Prepopulate module too but couldn't get it to work either although it works with all other field types that I have tried.

Anyone knows if this is feasible and how?

Edit: I should perhaps mention that I am not looking for a solution on how to set a default value for that field. The referenced entity must be set dynamically

For reference, here is my complete code:

/**
 * Implements hook_form_alter().
 */
function siteconfig_form_alter(&$form, FormStateInterface $form_state, $form_id) {

  if ($form_id == 'node_article_form') {

    // This works
    $term = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->load(13);
    $form['field_category']['widget'][0]['target_id']['#default_value'] = $term;

    // This doesn't work
    $media = \Drupal::entityTypeManager()->getStorage('media')->load(38);
    $form['field_image']['widget'][0]['target_id']['#default_value'] = $media;
  }
}

It's much easier to prepopulate field values on entity level rather than on form level:

/**
 * Implements hook_ENTITY_TYPE_create() for 'node'.
 */
function mymodule_node_create(\Drupal\node\NodeInterface $node) {

  if ($node->getType() == 'my_content_type') {
    $media = \Drupal::entityTypeManager()->getStorage('media')->load(38);
    $node->field_image[] = $media;
  }

}


Inline entity form shows a content type select list I am using Inline entity form for a non-commerce project.
The settings are:Widget:multiple values,Node:Allow users to add existing content.
Mode:Views:Filter by Entity reference view.So I have created an Entity reference view to show only nodes that have been created by the user.
The issue is:When looking at the Inline entity form to create or add existing content,there is a dropdown with all the content types of the site.This only appeared when I change the mode to Views:Filter by Entity reference view
How can I remove that?
thanks
See image attached

Try editing the inline entity field and only setting one entity (ie Company content type in your example) that can be referenced.


Store array of ids in a field programmatically? Devel noob here. I am writing a module where I need to stash a list of entity ids in a field on a different entity. I've created a field on an entity type programmatically and have it set as field type list(integer), but I'm stuck at actually working with the field data.

How can I add/edit entity ids in the field list programmatically?

For context, this is a Commerce submodule and I am adding to a field on the line item created after submitting an add to cart form. Using dsm($form_data) in a submit handler I added to the add to cart form, I see that the line item object is already stored in $form_data['line_item'] and the data I need to get to would be stored at $form_data['line_item']->field_entity_ids. By this point, I already have my array of ids, I just need some guidance on how to store them properly in the field.

Thanks in advance! :)

Consider using hook_entity_presave() to populate any auto-generated fields.

In your case, you could do something like:

/**
 * Implements hook_entity_presave().
 */
function example_product_entity_presave($entity, $type) {
  // Set the values for our computed fields.
  switch ($type) {
    case 'commerce_line_item':
      // @todo: get the value for $foo_ids.
      foreach ($foo_ids as $foo_id) {
        $entity->field_entity_ids[LANGUAGE_NONE][] = array(
          'value' => $foo_id,
        );
      }
      break;
  }
}

If you intend to reference any existing entity, you might want to use the Entity Reference module and use an entity reference field instead of an integer field.


Difference between drupal_write_record and db_insert I want to know what is the difference between drupal_write_record and db_insert
example :
can i translate that drupal_write_record('MyCustomTable', $Myrecord, $primary_key); to an insert query ?

thank you

drupal_write_record doesn't know by itself whether to do the insert or the update, but this is determined by the existence (or not) of the 3rd parameter: $primary_keys which defaults to array() while db_insert is to insert new record to database.

according to drupal_write_record API documentation

  $primary_keys: To indicate that this is a new record to be inserted, omit this argument. If this is an update, this argument specifies the primary keys' field names. If there is only 1 field in the key, you may pass in a string; if there are multiple fields in the key, pass in an array.

Also

  Do not use drupal_write_record() within hook_update_N() functions, since the database schema cannot be relied upon when a user is running a series of updates. Instead, use db_insert() or db_update() to save the record.


Run cron on a different web server? Is it possible to stop the cron on the main web server and run it on another web server that is using the same codebase, same MySQL server and same Memcache sever?

The cron web server will run import and other heavy operations that Drupal is doing during Cron.

Is anyone doing this? Also some tips for the implementation of the shared codebase(performance wise) would help.

This would be very easy to do by either running a run cron job or a jenkins job on the server/node you want to run drupal cron on.  This is very common practice in all of our projects.

If you are doing a large data import on cron, be sure you are using cron queue. http://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook_cron_queue_info/7


Click event not always fireing in Drupal behaviors I'm having a strange problem with a form. Sometimes I have to click the submit button twice to make it submit my form. It also seems to work if I click outside the form before I click submit. The form is built inside a module with FORM API and is submitted with an ajax request. I have some js attached to the form so I can make some client side validation before the ajax call is run. This is what my js code looks like:

(function ($) {

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

    // Cache the form object
    var $form = $("#mymodule-form", context);
    var $submitButton = $('input[type="submit"]', $form);

    // Use once so we dont attach submit multiple times
    // Use off to remove any existing submit handler
    $form
        .once('mymodule')
        .off('submit')
        .on('submit', function(e){
            e.preventDefault();
            var $form = $(this);

            $(function () {
                $('#mymodule-form').submit(function () {
                    if($(this).valid()) {
                        $submitButton.trigger('submitmyform');
                    }
                });
            });

        });

        $(document).ajaxComplete(function(e, xhr, settings) {
            $('#mymodule-form').resetForm();
            $('#edit-mymodule-submit').replaceWith( "<div id='mymodule-confirmation'>TACK FÖR DIN ANMÄLAN</div");

        });

         // Run validation on $form object.
        jQuery.validator.setDefaults({
            debug: false,
            success: "valid",
        });

        $('#mymodule-form').validate({
            rules: {
                mymodule_name: {
                    required: true,
                },
                mymodule_length: {
                    required: true,
                },
                mymodule_suite: {
                    required: true,
                },
                mymodule_email: {
                    required: true,
                    email: true,
                },
                mymodule_phone: {
                    required: true,
                },
            },
            messages: {
                mymodule_name: {
                    required: "lorem ipsum",
                },
                mymodule_length: {
                    required: "lorem ipsum",
                },
                mymodule_suite: {
                    required: "lorem ipsum",
                },
                mymodule_email: {
                    required: "lorem ipsum",
                    email: "lorem ipsum"
                },
                mymodule_phone: {
                    required: "lorem ipsum",
                },
            },
        });

}

};

})(jQuery);

This is what my code looks like for the submit button:

    $form['mymodule_submit'] = array(
       '#type' => 'submit',
       '#value' => t("SEND!"),
       '#ajax' => array(
           'callback' => 'mymodule_form_callback',
           'wrapper' => 'mymodule-form',
           'event' => 'submitmymodule',
        ),
     );

Can anyone see what's wrong with this code?

See comments below...

      .on('submit', function(e){ // Not correct way of using submit.
                e.preventDefault();
                var $form = $(this); // You have already defined this global variable?

                $(function () { // you dont need to check if the document is ready, thats what behaviours are for.
                    $('#mymodule-form').submit(function () { // Why are you submitting again here?
                        if($(this).valid()) {
                            $submitButton.trigger('submitmyform'); // What are you trying to trigger?
// If the form is already submit, why are you doing anything with the submit button?
                        }
                    });
                });

            });

Try this...

var $form = $("#mymodule-form", context);

$form.submit(function(e){
  e.preventDefault();
    if($(this).valid()) {
       // Do something else...
    }
});

UPDATE

You are probably binding to the form before it exists. Bind the event to the document, and pass the form selector...

$(document).on('submit', '#mymodule-form', function(e){
    // Do something...
});


How to solve “This version is not compatible with Drupal 7.x and should be replaced” error? Similar to but the solution doesn't work: How to solve "This version is not compatible with Drupal 7.x and should be replaced" error?

I've followed everything I can find but a basic custom theme in sites/all/themes is not working at all. Here is my .info:

name = Custom
description = Custom custom theme built with Stark
package = Core
version = 7.1
core = 7.x

regions[content] = Content
regions[main_nav] = Navigation
regions[sub_nav] = Sub Nav
regions[landing_large] = Front Large Box
regions[landing_ads] = Landing Ads
regions[landing_ad_bottom] = Landing Ad Bottom
regions[landing_books] = Landing Books
regions[home_first] = Home first
regions[home_second] = Home second
regions[home_third] = Home third
regions[search_box] = Search Box
regions[search_ad_box] = Search Ad Box
regions[content_first] = Content First
regions[content_second] = Content Second
regions[content_authors] = Content Third
regions[content_blogs] = Content Fourth
regions[sidebar_right] = Sidebar Right
regions[footer_first] = Footer First
regions[footer_second] = Footer Second
regions[footer_third] = Footer Third
regions[footer_fourth] = Footer Fourth
regions[copyright] = Copyright
regions[shopping_cart] = Shopping Cart

stylesheets[all][] = css/layout.css

I've tried with and without Package, it clearly has defined the version, the core version, the content region...what is it? I copied the .info file from a theme that works perfectly and this is the .info of that other theme verbatim.

Your custom theme is surely not a part of Core package,  so remove that line first. Second, you mentioned that the theme is built based on Stark but you didn't define it in the info file, so add this line :

base theme = stark

Third, usage of version is discouraged in Drupal 7, so delete this line as well.


Is it possible to use Views for listing data created in a custom module? The title says it all.

I'd like to create a view and provide rows for that view from a custom module where I've prepared the data for it.

The data is prepared when a page is visited and a callback function has run, the data is not stored in the database.

Is that possible somehow?

Thank you!

I know link-only answers are generally frowned upon, but this series of blog posts are unlikely to ever go anywhere and are WELL worth a read:

Building Views Query Plugins: Part 1 - Mapping web service data to the Views model

Building Views Query Plugins: Part 2 - Writing and testing the plugin itself

Building Views Query Plugins: Part 3 - Exposing options and configuration

Building Views Query Plugins: Part 4 - Building custom pager plugins

Note: In the unlikely event that someone gets here and the links are dead, please comment and let me know so I can address it :-)


submit button not working correctly To fix the problem with the submit function
I have tried clearing my cache
I have also tried uninstalling the module and reinstalling the module. the code segment is below.

The submit function for some reason never is run

function redirect_custom_reg_menu_alter(&$items) {
  if (isset($items['user/register'])) {
    $items['user/register']['page arguments'] = array('redirect_custom_reg_user_register_form');
  }
}

function redirect_custom_reg_user_register_form() {
  $form = array();

  // Add the form fields for the registration form.

  $form['personal']['username'] = array(
    '#type' => 'textfield',
    '#title' => t('username'),
    // this is built in validation to the form api
    '#required' => TRUE,
    // control the size parameter
    '#size' => 20,
    '#prefix' => '
',
    '#suffix' => '
',
    '#description' => 'Please enter your first name',
    '#maxlength' => 25,
  );

  $form['name']['formtype'] = array(
    '#type' => 'radios',
    '#title' => t('form type'),
    '#options' => array(
      t('form1 form'),
      t('form2 form'),
      t('form3 form')
    ),
  );

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => 'Submit',
  );

  return $form;
}

function redirect_custom_reg_submit($form, &$form_state) {
  drupal_set_message(t('The form has been submitted. personal="@username"',
    array('@username' => $form_state['values']['username'] )));
}

Your form function is called redirect_custom_reg_user_register_form(), so your submit function needs to be called redirect_custom_reg_user_register_form_submit().

If you want to keep the same submit function name that you have currently, you need to add it manually in the form function as Drupal only looks for a function called FORM_FUNCTION_NAME_submit() by default:

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


Load all configuration that has a particular config dependency? I want to load all entity form display configuration that has a particular, DIRECT, config dependency. I feel like this is something that should be doable with an entity query but I haven't been able to figure it out. Any thoughts on how to go about this?

Figured it out. You need to use wildcards and pass an array of potential matching values.

$form_displays = \Drupal::entityQuery('entity_form_display')
  ->condition('dependencies.config.*', ['field.field.paragraph.call_to_action.field_cta_text'])
  ->execute();


Node:Link token in views I want to change the text shown for the Node:Link field, which by default is "View". How can I change it?

You can change the the text in view, in the settings of the field "Node:link"


How to inject a service in another service? I am building a custom service, a membership service.
This service can be called from a controller.
But what I don't seem to get working, is to use another service, the QueryFactory, to use in that custom service.

the membership service:

namespace Drupal\hsbxl_members;
use Drupal\Core\Entity\Query\QueryFactory;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Class MembershipService.
 */
class MembershipService {
  protected $hsbxl_member;
  protected $entityQuery;

  public function __construct(QueryFactory $entityQuery) {
    $this->entity_query = $entity_query;
  }

  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('entity.query')
    );
  }

  public function MembershipsAll() {
    $query = $this->entity_query->get('node');
    $query->condition('status', 1);
    $nids = $query->execute();
    return "Hello World!";
  }
}

services file:

services:
  hsbxl_members.membership:
    class: Drupal\hsbxl_members\MembershipService
    arguments: ['@entity.query']

Can anyone point me out on this?
What am I doing wrong / am I missing?

Tom

The service you need is entity_type.manager:

.services.yml

services:
  hsbxl_members.membership:
    class: Drupal\hsbxl_members\MembershipService
    arguments: ['@entity_type.manager']

MembershipService.php

namespace Drupal\hsbxl_members;

use Drupal\Core\Entity\EntityTypeManagerInterface;

/**
 * Class MembershipService.
 */
class MembershipService {
  protected $hsbxl_member;
  protected $entityTypeManager;

  public function __construct(EntityTypeManagerInterface $entity_type_manager) {
    $this->entityTypeManager = $entity_type_manager;
  }

  public function MembershipsAll() {
    $query = $this->entityTypeManager->getStorage('node')->getQuery();
    $query->condition('status', 1);
    $nids = $query->execute();
    return "Hello World!";
  }
}

The create() method is unnecessary as services use constructor injection.


Creating a route with a form and some content i have created a route with a form:

    amu_404_redirect_import.admin:
      path: '/admin/config/amu_404_redirect_import/upload'
      defaults:
        _form: '\Drupal\amu_404_redirect_import\Form\Amu404RedirectImportForm'
\Amu404RedirectImportController::content'
        _title: '404 redirect Import'
      requirements:
        _permission: 'administrer AMU 404 redirection import'

if now i am creating a controller to display some content to the same page , the form is not displayed anymore

amu_404_redirect_import.admin:
  path: '/admin/config/amu_404_redirect_import/upload'
  defaults:
    _form: '\Drupal\amu_404_redirect_import\Form\Amu404RedirectImportForm'
    _controller: '\Drupal\amu_404_redirect_import\Controller\Amu404RedirectImportController::content'
    _title: '404 redirect Import'
  requirements:
    _permission: 'administrer AMU 404 redirection import'

how could i have both content displayed ?

As doc states

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

  _controller
  _form
  _entity_view
  _entity_list
  _entity_form
  _route

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


Stop overriding for the development snapshot module I have a development snapshot for a module (ABC-8.x-1.x-dev). I added 4 Patches. Now the developer does commit updates to the module.
By running composer update, I will loose all my patches.
When I remove the module name from composer.json, the module gets deleted. I have read that I should remove the composer.json file within the module.
Is there some kind of sub-version that defines the commit or so, for example "drupal/abc": "~1.0-dev-FD1512" or "drupal/abc": "~1.0-dev-221"?

Instead of trying to tie yourself to a specific commit, you might consider using composer patches instead:

{
  ...
  "require": {
    "cweagans/composer-patches": "^1.0",
    "drupal/abc": "~1.0-dev"
  },
  "extra": {
    "patches": {
      "drupal/abc": {
        "Fix for foo": "https://url/to/foo-patch",
        "Fix for bar": "https://url/to/bar-patch"
      }
    }
  }
  ...
}

Patches will be applied on install/update of the relevant packages.


Why is an untranslated string not showing up? In my module I have some custom strings. I use these in the t() function.
When I go to admin/config/regional/translate/translate and filter the untranslated strings my custom strings do not show here.

What could be going wrong?

The strings needs to be rendered a first time on a page in the not default language and your string keys will be visible in the Translate interface.

An important detail, the search is case sensitive. For example My text is different than my text.


Translate interface (export/import) I have two languages:

french
arabic

I want to completely translate the arabic interface. If there a way to export the englisch translations, add the arabic one and reimport the file?

It can be done using Translation template extractor module

  If you are a translator, install the module on a Drupal site as you would with any other module. Once potx module is turned on, you can go to the "Extract strings" tab on the Locale administration interface, select the module or theme you want to have a translation template for, and submit the form. You will get one single template file generated.


Is there a way to force drush to enable a module and ignore dependencies? I'm getting exception 'Drupal\Core\Config\UnmetDependenciesException' with messageConfiguration objects (....) provided by cn_migrator have unmet dependenciesin .../core/lib/Drupal/Core/Config/UnmetDependenciesException.php:84 when trying to enable a custom migration module. I've checked the dependencies listed in the YAML files and can't see anything missing. I really need to push ahead, but can't find a way to force enabling this module.

No, you can't.

But, https://www.drupal.org/node/2655104 was committed today, and it allows you to see what exactly is missing. Try patching your site with that to see the problem.


Stripe_InvalidRequestError: You cannot use a Stripe token more than once I'm trying to integrate Stripe’s Checkout and PHP into a simple module and I've got the following:

Stripe::setApiKey($stripe['secret_key']);

if (!empty($form_state['input'])) {
  $input = $form_state['input'];
  // Create a Customer
  $customer = Stripe_Customer::create(array(
    "card" => $input['stripeToken'],
    "email" => $input['stripeEmail'],
  ));

  // Charge the Customer instead of the card
  $charge = Stripe_Charge::create(array(
    "amount" => 4900,
    "currency" => "GBP",
    "customer" => $customer->id,
  ));
}
else {
  $data = array(
    "data-key" => $stripe['publishable_key'],
    "data-name" => variable_get("site_name", ""),
    "data-amount" => 4900,
    "data-currency" => "GBP",
  );

  $form['stripe'] = array(
    '#markup' => '<script src="https://checkout.stripe.com/checkout.js" class="stripe-button" ' . join(' ', array_map(function($sKey) use ($data) {
      if (is_bool($data[$sKey])) {
        return $data[$sKey] ? $sKey : '';
      }
      return $sKey . '="' . $data[$sKey] . '"';
    }, array_keys($data))) . '></script>'
  );
}

Everything is working great so far apart from when I call $charge = Stripe_Charge::create I get an error returned Stripe_InvalidRequestError: You cannot use a Stripe token more than once but I don't understand how my code would be using the token more than once.

Although I get this error, in my dashboard at Stripe the payment is successfully processed, I'm using the Stripe API Client Library for PHP

OK I have figured it out, when the form code is running, it runs multiple times, to stop it I added a variable to $form_state so the top of my code above becomes:

Stripe::setApiKey($stripe['secret_key']);

if (!empty($form_state['input']) && !isset($form_state['processed'])) {
  $form_state['processed'] = TRUE;


Where is the best place to insert additional logout functionality? To insert additional logic when a user logs off one might look at function user_logout() in user.pages.inc.  This code being in a core module, you should not edit it, but works very well... for example by adding the following code to the top of the 'user_logout()' function...

$last_run = variable_get('cron_last', 0);
if(time() - $last_run > 86400) {
    include_once './includes/bootstrap.inc';
    drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
    drupal_cron_run();
    drupal_flush_all_caches();
    watchdog('user', 'cron set to run and cache to be cleared on user logout', array('%name' => $user->name));
}

... I get the cache cleared and cron run if cron has not run in the last 24 hrs.  Okay, not ideal for cron but that's another issue.

Where is the best place to add this little snippet?  I could simply implement my own logout menu item... but I'm not keen on that solution.

Thanks in advance.

Instead of modifying core, you can implement hook_user() in a custom module. Then you can check the $op parameter to see if it equals "logout". This code will run whenever a user logs out, regardless of what menu item or link they click to log out.

Note that this is different between Drupal 6 and 7. This question was tagged Drupal 6, but if you're using Drupal 7, or plan to later, be aware that this hook was replaced with hook_user_logout().


How to give access to inactive user profile? I guess the title is obvious. I have built a Drupal 7 website showing a view of the previous Users (inactive profiles).

As an admin, I can access these profiles but I need anonymous users to have that permission too (view "previous" or "old" members profiles).

Is there any module to add that kind of permission?

Thanks and sorry for my English ;)

The View Profiles Permissions module will work for that purpose: https://www.drupal.org/project/view_profiles_perms.

In order for this to work, you will also need to give your blocked users a Role.

It is not the primary function of the View Profiles Permissions module, but there is more information about this specific issue here: https://www.drupal.org/node/2490934

Additionally, You can use the Rules module to automatically assign a role to users when they become blocked.

Steps:

Install and Enable the View Profiles Permissions module
Create a role called "Blocked"
Give permissions to anonymous users to "Access to Blocked profiles"
Assign the "Blocked" role to all users who are blocked (aka Inactive, Old, Disabled)
Extra Credit: Install/Enable the Rules module and a new Rule that automatically assigns the Blocked" role to users when they become blocked.


Anchor links not working in Firefox So I know this might not necessarily be a "Drupal" issue, but because I am using Drupal and this issue only happens in my Drupal site, I'm wondering if it has something to do with the way Drupal handles URL's.

SO, I have an anchor on my home page like so:

There is a link in the main navigation that is on all pages to this anchor like so:

We Know Digital

So this works in all browsers, including Firefox, when I am ALREADY on the home page, however, if I am on one of the internal pages and then click this link, it takes me to the homepage, but does NOT go down to the anchor in Firefox. It does go down to the anchor in Chrome and Safari and other browsers, but for some reason it wont in Firefox, even in the latest version. The reason I believe this has something to do with the way Drupal handles URL's is that if I create a standalone plain vanilla HTML page outside of Drupal and replicate the same thing where I have 1 page that has the link and the anchor and then a separate page that has the link to the first page and the anchor, it works as expected in Firefox where it goes to the first page and then down to the anchor. It's only when I try to do this within Drupal, that it stops working. Anyone have any idea what might be going on here? I'm thinking it has something to do with the URL re-writing. ???

The empty anchor target might be the problem. The browser may be having a "problem" fixating the empty (non-visual) target as the page loads.

Ideally, you would attach the id to something. eg. an Hn tag.

The name attribute on the anchor is deprecated in HTML5 if that is of concern. Reference: https://www.w3.org/TR/2008/WD-html5-diff-20080610/#absent-attributes


Auto-remove unused tags Drupal 7.

We want to remove tags (of Tags vocabulary) automatically when all pages referring to this tag are removed.

Is there a module for this?

There are a couple of modules that might help:

Taxonomy Orphanage (specifically the cron interface)

  This module provides interfaces (drush, cron, admin form) for removing orphaned taxonomy term references from entities.

Field reference delete (sandbox only)

  This module removes references to a deleted entity from fields stored in an SQL database. It exists to prevent stale references to non-existent content from causing unexpected problems (for example, when the referencing content is being displayed).


Malicious Code - Website Disable I'm new to Drupal. My website has been disable due to malicious code found in
/var/www/vhosts/domain.com/httpdocs/sites/all/themes/tao/tao/css.php

What should I remove in this file?
http://pastebin.com/4xQixw13

You should remove the entire file.

Also,  this is not enough to fix your site.  I would recommend exporting your content and doing a fresh install, with a fully updated version of Drupal.


Remove "Submitted by [user] on [date]" from content shown on a Views page How does one remove the "Submitted by [user] on [date]" bit from content shown on a Views page?

I am assuming it is to remove some php code, but unsure what php file the code lives in. (I tried node.tpl.php)

I am using Drupal 7 Bartik theme.

Thanks in advance.

Go to Administration > Structure > Content Types. Find the content type on which you want to disable author information, click edit. At the bottom of the edit page you'll click on "Display settings" and uncheck "Display author and date information".

This will disable the display of author info for all content view modes, but you will still be able to pull out this info when constructing a View via Views module if you need to.


How to copy forum structure Advanced Forum? I wish to use the Forum or Advanced forum module to create forums. But to save time I need to duplicate forum structure to create new ones. I've done Google search but did not find any useful information.

For example for a schools website, I can create another school just by copying a school structure that'll copy all child forums as classes which I'll not need to recreate.

Can anybody help me with this?

What you should do is something like an Install Profile: https://drupal.org/developing/distributions

You can create Install Profiles from exiting sites with:
https://drupal.org/project/profiler
https://drupal.org/project/profiler_builder

What I would do is make the first site exactly how you want it and then turn that into a Install Profile.

An easier way to do this if you have AEgir is to just clone your first site and then keep it as a template to clone others.


How do I add a text field that links to the taxonomy_index table When I add a taxonomy tag to a node, I also want to be able to add 1 (or more) text fields specific to that tag and that node. I know how I would set up the underlying db table (compound foreign key of nid and tid with a many-one join to the taxonomy_index table, a primary key and a text field).

How would I implement this? Or does a module already exists that has this functionality?

I am fairly new to the world of Drupal so unsure if this would require writing a module, adding a new content type or another approach entirely.

Many Thanks,
Pete

Use the field collection module.

Create a new field collection field attached to your content type, and then in your field collection put 2 fields: 1 taxonomy term reference field, and 1 text field.


Inline css is not working in ck editor full html I have installed updated version of the CKEditor - WYSIWYG HTML editor module with CK editor library.

Every time I put inline css in my HTML full editor, it vanished.

I have searched the web for it, but not found proper solution.

Anybody any suggestions about this?

This is just an example where you can add inline class to P tag. Similarly you can do this with other tags. Refer CKEditor documentation

In the "Advanced Content Filter" section of CKEditor profile add this:

P [*]

In the "Advanced options" section of CKEditor profile add this:

config.allowedContent = true;

This did the trick for me.


How to show a field in views only when a checkbox is ticked? I want the user to be able to choose whether to show a description or not for each node in the view. Adding the filter only works on the entire object, I just want to show/hide one field. How can I achieve this?

You can do this with Views out of the box. No need for Views PHP here.

Add your boolean field in Views. (This assumes the default boolean set up, i.e. 0 for not checked and 1 for checked.)
Use the Key formatter - this isn't obvious, but I couldn't get it to work without this.
Select REWRITE RESULTS and put the description you want in there. This can include tokens so you can grab material from other fields in the node if that's what you need.
On NO RESULTS BEHAVIOR check all the boxes (Count the number 0 as empty, Hide if empty, Hide rewriting if empty)


Compress Images that are already uploaded I working on a website which has a content type. The content type contains an image field. Thousands of images uploaded already. Because image size is very big, there is requirement to compress the size of images.

I found a module Image API Optimize, but this module works only when a new image is uploaded. But my requirement is that I want to compress the images which are already uploaded.

Can anybody help me solve this problem?

A module like Max Image Size will resize the original images that have already been uploaded, but I don't believe it is possible to also use an optimization on the images when they are resized.  You can only specify a new maximum width and height.


Migrating fails without any error I'm trying to run a migration D7 to D8 which I've coded. This is the command:

drush migrate-manifest manifest.yml --legacy-db-url=mysql://User:PASSW@localhost/drupal7ddbb --verbose

but basically no response, just something like done... but there is no nodes in the list of content.

Anyone knows how to make a deeper debug in Drupal8 migrations?

Thanks in advance.

A few things I see. const JOIN = 'n.vid = nr.vid'; this is dead code. Not sure where it comes from but as far as I am aware there's nothing in DrupalSqlBase or SqlBase that uses the constant JOIN. I am not sure what this even wants to be.

Your process copies the type and then in the destination I think you try to set the type/bundle to article but that's simply not how this works. Everything under the destination key is passed to the destination plugin as configuration and the way we designed and implemented this system the destination plugins do not change a thing, they just import.

So:

source:
  plugin: progweb_custom_blog
  constants:
    type: article
process:
    type: constants/type

In your particular case, you could use a map similar to und: en to map blog to article but if you want article nodes then you must use either the constants or the map.


Drupal Installation running without settings.php (multisite) What we intended to achieve was setup drupal.abcd.com as main installation of multisite setup, and abcd.com, xyz.com, pqrs.com as sub-sites of the multisite setup.

The main installation (drupal.abcd.com) should contain the default Drupal installation (with the Bartik theme), and abcd.com should have the ABCD theme with content.

drupal.abcd.com is automatically taking the settings.php file from abcd.com. So, when I make change in abcd.com (e.g. setting a different database) the same change is done for drupal.abcd.com.

I also tried deleting drupal.abcd.com/sites/default/settings.php, but I can visit drupal.abcd.com with same settings as abcd.com.

The installation and creation of folders were done by the customer; I don't know what mistake he did.

Could anyone please suggest me where things might have gone wrong, or what can be done to avoid this behavior, and run everything as normal?

Have a look at sites.php in your sites folder.

 $sites = array(
   'devexample.com' => 'example.com',
   'localhost.example' => 'example.com',
 );

  The above array will cause Drupal to look for a directory named
  "example.com" in the sites directory whenever a request comes from
  "example.com", "devexample.com", or "localhost/example".

So in your case you should have 'drupal.abcd.com' => 'default'

The reason why its picking up settings file from abcd.com is because when a request comes for drupal.abcd.com it looks for folder drupal.abcd.com since that folder is not there it will look for next match like abcd.com and it picks it up from there.

I am not sure about Drupal 7 site set up but playing around with sites.php should fix it.


How to get entity from transliterated argument in URL? I have panel, where I have argument: taxonomy term name

term names are transliterated (like "My custom taxonomy title" into my-custom-taxonomy-title)

path is like this: my-custom-list-of-nodes/my-custom-taxonomy-title

How can I get in PHP code (in some hook) original taxonomy term name from argument "my-custom-taxonomy-title"?

Original string can have diacritics, uppercase, spaces.
How can I detect Term ID from transliterated argument "my-custom-taxonomy-title" ?

Short answer:

You can't do what you are asking.

Why is that?
While transliterating is a pretty simple procedure that follows a very specific number of steps:
- Replace every character with the corresponding-transliterated version
- If the resulting URL exists, add a -{Insert Number here} at the end until you find a URL that does not exist

reversing the transliteration is not that easy. Think of the extreme case where 5 different nodes/terms/entities have the exact same title. Their transliterated paths would be: /common-title /common-title-0 /common-title-1 /common-title-2 /common-title-3.

In this case, how do you know which transliterated title corresponds to each entity? Creation date (first one created gets the smallest index)? Besides the fact that this is extremely complex to predict, there may still be problems if a path was updated manually or one of the entities was deleted and a new one was added.

Long answer:

Even though what you are asking is not feasible, you can use a number of different approaches in order to solve the specific problem that you are facing.

Possible Solution 1:
You can use the current_path function. This will return the unaliased path of the currently viewed Drupal page. I am not exactly sure how the panels' pathing system works, but there is a very good chance that you will get something with the term id in it (that's what you need in your hook, right?).

In order to investigate this further in your code, assuming you have devel installed, you can do something like:

dpm(current_path());

Possible Solution 2:
If the above-mentioned solution does not work, you will need to do some more digging in order to figure out which variables are available. Something that can get you started is a simple:

dpm(get_defined_vars());

Depending on the results that you will get, you may be able to find the term name somewhere in the defined variables and use taxonomy_get_term_by_name() function to retrieve the tid.


How to edit the content page fields column in the admin section? In the admin section --> Content menu displays all the contents of the site.

I want to have options (or atleast to know where I have to change) for adding and removing the columns in the content section.

You can use hook_form_FORM_ID_alter() and do your changes inside that.

Example:

function YOUR_MODULE_form_node_admin_content_alter(&$form, &$form_state, $form_id) {
 // YOUR CUSTOM CODE GOES HERE
}


Drilldown search with Search API and Facets I have a type 'projects' referencing two other types ('kustomer','products') via entity reference.
Now I want to implement a drilldown search.
I therefore use search API with facete api. I build a index and a view for Type 'project'. The filtering works well on this view. I have facetes for types 'customer' and 'product' and can filter.

The target is a workflow where you start at a list of 'products'. When you select one you will get a list of 'customers' where a 'project' exists that contains that 'product'. After that you select a 'customer' and you get a List of all 'project's having that 'product' and 'customer' preselected as facetes.

Can someone point out a module or configuration that does that?
Thanks in advance
Clemens

I use CER,  "Corresponding Entity References" to achieve similar results, but not with Search_API.. for that, I just tell the search-page to render the "teaser", and modify the teaser display to include the entity_reference list of associated entities as links, that way, if you search for a "Kustomer", it will show you a list of Kustomers and each project will also appear as a list of links underneath the title, or visaversa, you can also use Facets to filter by taxonomy etc.. handy!


Help with finding field reference to node title within webform select options view? field reference issue so I'm trying to implement a similar "sample request" feature like the one in Drupal Steve's tutorial. Drupal 7 Sample Request.

The issue I'm having is that I'm not sure how the field reference is made to the node title within my view. Right now the select list is being generated and is available to my webform, but the list appears unpopulated. I'm provided with an empty select list widget, but no actual options to select

The issue is that the view itself is of a custom commerce content type "posters," with a relationship set on flag, such that I'm not sure what the field reference is to get the title field from my view. Steven mentions reference the node's owner, but I'm not sure what that means. Here is the code from Steve's implementation modified to meet my needs. I basically want to know how to pull the title field out of the view of flagged items, just no idea where to find what the reference to that would be...

    function webform_hook_webform_select_options_info() {
   $items = array();
   if (function_exists('webform_hook_user_flag_sample_requests')) {
     $items['webform_hook_user_flag_sample_requests'] = array(
      'title' => t("Sample Requests (User Flag list)"),
      'options callback' => 'webform_hook_user_flag_sample_requests',
     );
   }
   return $items;
 }
 function webform_hook_user_flag_sample_requests() {
   $view = views_get_view('webform_flag_views', TRUE);
   $view->set_display('webform_options');
   $view->execute();
// dpm($view);
   $options = array();

   if ($view->result) {
     $row_class = $view->style_options['row_class'];
     $attributes = $row_class ? " class='$row_class'" : '';
     foreach($view->result as $item) {
       $options[$item->nid] = '' . render($item->field_field_img[0]['rendered']) . ' ' . $item->field_title . ' (' . $item->node_title . ')' . '';
     }
     dpm($item);
   }
   else {
     $options[0] = t("Nothing");
   }
   dpm($options);
   return $options;
   }

Here is the result of my dpm statement on the $item variable

(Object) stdClass
    commerce_product_title (String, 9 characters ) The Rapid
    product_id (String, 3 characters ) 354
    field_data_field_image_commerce_product_entity_type (String, 16 characters )       commerce_product
    _field_data (Array, 1 element)
    field_field_image (Array, 1 element)
    field_field_img (Array, 1 element)

I've tried most of the obvious options, but I've been hitting a brick wall.

The DPM of the $options variable only returns the a tag

... (Array, 1 element)
(String, 11 characters )  ()

Again, many thanks in advance.

OK, you're just accessing the wrong (non-existent) properties.  You need

foreach($view->result as $item) {
   $options[$item->product_id] = '<a' . $attributes . '>' .
       render($item->field_field_img[0]['rendered']) .
       ' (' . $item->commerce_product_title . ')' . '</a>';
 }

I removed $item->field_title because I don't see it's equivalent in your $items. And without knowing what the field_field_img is it's impossible to tell if that will work for it as well.


How to map views url to blog url In my site I am using blogs module. When I used sitename/blog default blog page will display. But my requirement is, I have created a view to display the blogs, this is on the path of sitename/blog-display. I want to display this view when i type the url sitename/blog. please suggest me how can I solve this. Thanks in advance for any suggestions.

Create a custom module with this code:

<?php

function MYMODULE_menu_alter(&$items)
{
  $items['blog']['page callback'] = "MYMODULE_blog_replace";
  $items['blog']['file'] = "MYMODULE.module";
  $items['blog']['module'] = "MYMODULE";
}

function MYMODULE_blog_replace()
{
  return views_embed_view('VIEWMACHINENAME', 'default');
}


Index custom content in apache solr I have several custom modules that load and display data from custom tables. I have successfully managed to use the drupal search on these contents, using the drupal search hooks like, hook_update_index, hook_search_execute, etc. But now we have decided to use solr instead. Now I'm totally confused and don't know how to make solr index my custom data. The closest I've come to solving this is to this:

function msearch_apachesolr_index_document_build(&$document, $entity, $entity_type) {
    if ($entity_type == 'people' && isset($entity->description)) {
        $document->addField('s_firstname',
                $entity->field_firstname['und'][0]['value']);
        $document->addField('s_lastname',
                $entity->field_lastname['und'][0]['value']);
        $document->addField('ts_description', $entity->description);
    }
}

This code does not work(as in indexing my data) and it really shouldn't. There's no way that the $entity passed to this hook could have my desired data in it. Is there something I should do to manually pass the object to this hook? Do I need to implement hook_cron and do this there?

Thanks, any help is appreciated

PS:

I know how solr indexes data, through POST requests to solr/corename/update, but I doubt that's the way to go. If I had to go this way, I would've had to implement the whole mechanisms for indexing rows and making sure no duplicates were sent for indexing. OR SHOULD IT BE EXACTLY LIKE THIS???

function msearch_group_apachesolr_query_alter($query){
     $query->addParams(array('fl' => array('ss_firstname')));
 //  $query->addParams(array('fl' => array('ss_lastname')));
}


Mathematical operations and Twig variables Is it legal to do this in a node template with Drupal 8?

{% set percentVariable = content.field_my_customfield.0 * 100 / content.field_my_second_customfield.0 %}

which will be output like this

Both fields deliver integer values to that variable

Is there any major syntax error or misunderstanding in doing so?

Yes, it is legal to do mathematical operations in Twig (and in PHP as well). The issue you have is you are trying to calculate render arrays, which doesn't work, no matter which programming language you use. You need to do this on the field values. For example the first value you are looking for:

in PHP:

$value = $node->field_my_customfield->value;

or in Twig:

{% set value = node.field_my_customfield.value %}

This code should work then in Twig:

{% set percentVariable = node.field_my_customfield.value * 100 / node.field_my_second_customfield.value %}


Using drupal_http_post() to submit to external site: What am I doing wrong? I intended to make a module that utilized drupal_http_request with a webform so that the form gets validated before it gets sent to an external url.

I actually was recommended this method over $form['#action'] from a previous inquiry earlier. I did as recommended, thought it worked, but found out that I was mistaken.

I did some troubleshooting and concluded my module is the culprit since:

The module utilizing $form['#action'] had no problems posting to our external url/web app and another external site/service for testing HTTP POST submissions (http://requestb.in)
The module utilizing drupal_http_post could neither post to our external url/web app nor requestb.in

My setup uses the following:

Drupal 6.x
Webform 6.x-3.17

My custom module contains the following code.

function webform_to_data_repo_form_submit(&$form, &$form_state, $form_id) {
    if ($form_id == 'webform_client_form_765') {
        $url = 'external.url.goes.here';
    $headers = array(
                 'Content-Type' => 'application/x-www-form-urlencoded',
               );

$response = drupal_http_request($url, $headers, 'POST', http_build_query($form_state['values'], '', '&'));
   }
}

Is there something wrong with my module? Just wanted to make it post to some external URL.

Thank you everyone for the pointers.

I realized that my custom module that uses the webform module to submit to an external url (via drupal_http_request) had to be written as two separate functions: one using hook_form_alter and one using a custom submit handler. The code is as follows.

<?php

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

//I only want form 765 to submit externally //
if ($form_id == 'webform_client_form_765') {
$form['#submit'][] = 'my_additional_submit_handler';
 }
}

function my_additional_submit_handler(&$form, &$form_state) {

$url = 'your.external.url.here'
$headers = array('Content-Type' => 'application/x-www-form-urlencoded',);
$response = drupal_http_request($url, $headers, 'POST', http_build_query($form_state['values'], '', '&'));

}

?>

As a side note, I never got to test the result of using dpm($response) using the Devel module as beth suggested.

I'm using a webform (via the webform module) to test. What I wanted to happen are two things.

The webform validates the submission which in turn would keep a log of the submission through Drupal (webform module by default and by design).
Simultaneously submit inputs from #1 to external url.

For the longest time, only #1 is happening and I can't seem to make Devel look into $response because that variable only exists when there's an attempt on submission. How does one make Devel module load when a successful submission has been made through a Webform? I guess this is another question for another time.


How to display custom block without default wrapped html around I have custom module with new block. When this block is displayed, the output is wrapped with html tags from block.tpl.php template:

<section id="<?php print $block_html_id; ?>" class="<?php print $classes; ?>"<?php print $attributes; ?>>

I would like to display only content without the wrapped html around. I can accomplish this by overriding the block.tpl.php file in the theme, however. This requires me to go into every possible theme and override the template file every time installing the module. How to avoid that? How to display only content of the custom block from custom module without overriding template file?
Is there some attribute that i can set in the block render array like #theme_wrapper?:

$block['content'] = array(
               '#markup' => '
Hello World!
',
              // '#theme_wrappers' => array('attempt_to_override'),
)

I was thinking the 'theme_wrappers' attribute can be used, but i wasn't able. Thank you for any help

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

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

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

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

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


Any way to get localized term names in node paths I have a node type "news" with an included term reference field named "newscategory". i18n-module incl. taxonomy-i18n is also installed, vocabulary is translatable and all terms are translated. But for pathauto patterns there is only the token "[node:field_newscategory]" available, which will not be localized depending on the node language.

Is there any trick on achieving this?

Okay, after 2 more hours of research and development I've finally managed to get the problem solved. I ended up writing a tiny custom module implementing hook_pathauto_alias_alter().

The module has several dependencies:

dependencies[] = taxonomy
dependencies[] = field_extract
dependencies[] = pathauto
dependencies[] = i18n
dependencies[] = i18n_string
dependencies[] = i18n_taxonomy

Here's how I did it (tailored to my special needs, so go on and modify my code)

<?php

  /**
   * Implements hook_pathauto_alias_alter()
   */
  function mymodule_pathauto_alias_alter( &$alias, array &$context ) {
    if ( $context[ 'module' ] == 'node' ) {
      $node = $context[ 'data' ][ 'node' ];
      if ( $node->type == 'news' ) {
        // determine actual context variables
        $language = $context[ 'language' ];
        $pattern = $context[ 'pattern' ];
        $category = field_extract_value( 'node', $node, 'field_newscategory' );

        // translation & preparation
        $category_translated = i18n_string_object_translate( 'taxonomy_term', $category, array( 'langcode' => $language ) );
        $sanitized = pathauto_cleanstring( $category_translated->name, array( 'langcode' => $language ) );

        // re-build the alias
        $alias = explode( '/', $alias );
        $pattern = explode( '/', $pattern );
        foreach ( $pattern AS $index => $part ) {
          if ( $part == '[node:field_newscategory]' ) {
            $alias[ $index ] = $sanitized;
            break;
          }
        }
        $alias = implode( '/', $alias );
      }
    }
  }

?>


dbQuery with condition and date_format() I have a request that should return a list of nodes that have a creation date <= 6 months. It works well with $query->where() but I want to use $query->condition ().

Query with CONDITION:

$query = db_select('node', 'n');
$query->innerJoin('field_data_field_date_de_publication_news', 'fn', 'fn.entity_id = n.nid');
$query->innerJoin('field_data_body', 'fb', 'fb.entity_id = n.nid');
$query->fields('n', array('title', 'status', 'nid'));
$query->fields('fn', array('field_date_de_publication_news_value') );
$query->condition('fn.field_date_de_publication_news_value', 'MONTH(NOW())-6', '<=');
$query->orderBy('fn.field_date_de_publication_news_value', 'DESC');
$rows = $query->execute();

But if I replace CONDITION with WHERE it works:

$query->where(" MONTH(fn.field_date_de_publication_news_value) <= MONTH(NOW())-6" );

I also tried:

$query->fields('fn', array("DATE_FORMAT(FROM_UNIXTIME(field_date_de_publication_news_value), '%m')") );

condition() can only be used for simple expressions (=, >, <, <>, BETWEEN, LIKE, and a few others).

Using where() as you are already is the correct way to construct a more complex query.


WSOD when redirecting based on cookie I have a site where I set a cookie when the user is visiting a specific content-type:

function THEME_preprocess_node(&$variables) {
  if (isset($variables['node']) && $variables['node']->getType() == 'MYTYPE') {
    // Store cookie with id of active node.
    user_cookie_save(['THEME_location' => $variables['node']->get('nid')->getString()]);
  }
}

Then if the user again is going to the frontpage, I would like to redirect him to the node referenced from the above cookie:

function THEME_preprocess(&$variables, $hook) {
  $variables['is_front'] = \Drupal::service('path.matcher')->isFrontPage();

  // Redirect the user to the selected node.
  $cookies = \Drupal::request()->cookies->all();
  if ($variables['is_front'] && isset($cookies['Drupal_visitor_THEME_location'])) {
    $nid = $cookies['Drupal_visitor_THEME_location'];
    $response = new RedirectResponse(\Drupal::url('entity.node.canonical', ['node' => $nid]));
    $response->send();
  }
}

The above works fine most of the time, but sometimes when loggin out from the backend and visiting the frontpage I only get a white screen and the page is completly dead.
I know this is very vague but I cannot seem to reproduce this error by performing some specific steps. It just happens once in a while. If I then clear the cache everything seems to work as expected again? Can someone see what I am doing wrong here?

You should not be using theme_preprocess to perform any processing the results of which cannot be cached, only manipulation of variables to be passed to the final theme processing function or template.

Doing a redirection in a theme_preprocess will cause the result to be empty and this is what leads to the WSOD, I believe.

Instead the preferred method is to use an event subscriber, as described on this page: https://www.drupal.org/node/2013014

  Register your Event Subscriber in your mymodule.services.yml and tag it as such:

services:
  mymodule_event_subscriber:
    class: Drupal\mymodule\EventSubscriber\MymoduleSubscriber
    tags:
      - {name: event_subscriber}

  Your MymoduleSubscriber should be placed in folder structure of modules/src/EventSubscriber/MymoduleSubscriber.php and should implement the EventSubscriberInterface interface and in its getSubscribedEvents() point to the method that should be executed:

namespace Drupal\mymodule\EventSubscriber;

use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

class MymoduleSubscriber implements EventSubscriberInterface {

  public function checkForRedirection(GetResponseEvent $event) {
    if ($event->getRequest()->query->get('redirect-me')) {
      $event->setResponse(new RedirectResponse('http://example.com/'));
    }
  }

  /**
   * {@inheritdoc}
   */
  public static function getSubscribedEvents() {
    $events[KernelEvents::REQUEST][] = array('checkForRedirection');
    return $events;
  }

}


Ckeditor Wordcount plugin - How to target specific textareas I'm using the CKEditor - WYSIWYG HTML editor Drupal 7 module and wordcount plugin. I've added the wordcount plugin file in the ckeditor plugins directory and got it working, however my config max word and character count etc is the same for all fields. I would like to specify different max word and character counts for specific fields. Here is my config:

ckeditor.config.js

Using CKEDITOR.replace I did the following:

  CKEDITOR.replace('edit-body-und-0-summary',
      {
          extraPlugins: 'wordcount',
          wordcount: {
              showCharCount: true,
              maxCharCount: 123
          }
      });

This worked, but after refreshing the page it went back to the global max word and character count. The Textrea ID is edit-body-und-0-summary but this tag is repeated elsewhere in the page.

How do I go about adding a unique ID to the textarea tag and having different word counts for different fields e.g.
Summary and Body fields

I figured it out, hope this helps anyone else out there.

I added the following to my Adminimal Sub theme to add a class to the summary textarea:

function adminimal_sub_form_alter(&$form, &$form_state, $form_id) {
 if (isset($form['#node']) && $form['#node']->type == 'article') {
 // Add class to body textarea for various content types. This is used for the Ckeditor wordcount plugin to target summary textarea.
   $form['body']['und']['0']['summary']['#attributes']['class']['0'] = 'article-summary';
 }
}

Then downloaded the Ckeditor 4 Wordcount plugin and saved it in the plugins directory (sites/all/libraries/ckeditor/plugins).

In the Drupal UI I went to configuration > CKEditor Filtered HTML (edit) and in the Custom Javascript configuration under Advanced options I added a path to my ckeditor.config.js (config.customConfig = '/sites/all/themes/global/js/ckeditor.config.js';).

This is my ckeditor.config.js:

CKEDITOR.editorConfig = function(config) {

 if (this.element.hasClass('article-summary')) {
 config.wordcount = {
    showCharCount: true,
    maxCharCount: 170
    }
}
// Make CKEditor's edit area as high as the textarea would be.
 if (this.element.$.rows > 0) {
    config.height = this.element.$.rows * 20 + 'px';
 }
}

Here I can set the maxwordcount and loads more besides, but for this project only needed the maxwordcount. This way if the Drupal Ckeditor module gets updated this file will not be affected.


Why drupal need hidden option in comment settings of content types? In content type setting in drupal, we have tab comment setting .The comment setting on future content of this type will default to:

Hidden: No comments are allowed, and past comments are hidden.
Closed: No comments are allowed, but any past comments remain visible.
Open: Any future content of this type is open to new comments.

Why do we need HIDDEN option? It  does not make sense in content type setting . If we set this option - in any new nodes that will be created next  - comment will be closed.

This option has sense only in particular material, if it has comments.

Please explain me why this option need in content type settings?

Thanks...

This option has sense only in particular material, if it has comments.

Precisely. So you should use this option when a content type has comments that you don't want to delete, but don't want to allow people to see either permanently or temporarily.

If you don't need that option, you don't need to use it. But its existence makes perfect sense.


Is there a module for site explanation messages? Many sites have text areas which appear to explain things to new users. With an option to hide the message in future.

I haven't seen such a module for Drupal, does one exist?

I have tried googling but to be honest I have no idea what terminology to use when searching for one.

The closest module I know is the Legal module, this is more for showing the terms of service or similar for users before registering, but it might be close to what you need.


Is it possible to use multiple captcha based on language selection? I have a multi-language site.I wish to integrate captcha based on which language is selected.

Suppose if i selected language1 then captcha1
language1 => captcha1
language2 => captcha2

Well, you should do this in template.php. First check the language then add the captcha based on the language. As an example to do this in webforms:

function THEME_form_alter(&$form, $form_state, $form_id) {
    global $language;
    if($language->name == "ENGLISH")
    {
        if (strstr($form_id, 'webform_client_form')) {
            $form['my_captcha_element'] = array(
                '#type' => 'captcha',
                '#captcha_type' => 'image_captcha/Image',
            );
        }
     }
}

You can check the language and add the mollom programmatically as well. Follow this link to learn how to add mollom by code.


Message template with mail key In template_preprocess_mimemail_message() I checked that mail key is mimemail_message__subscriptions_mail__node-type-post, but none of these templates is using in the email:
mimemail_message__subscriptions_mail__node-type-post.tpl.php
mimemail_message--subscriptions_mail--node-type-post.tpl.php
mimemail-message--subscriptions-mail--node-type-post.tpl.php

What I'm doing wrong?

Templates must be put in the theme's directory, not in the Mime Mail module directory or in your own custom module directory. The Mime Mail documentation explains the proper template naming and location. See https://www.drupal.org/docs/7/modules/mime-mail/theming-html-mail-sent-through-mime-mail
The most specific template name should have three parts, separated by "--". These parts are:

"mimemail-message" This is the same for all templates.
"modulename" This is the machine name of the module that provides the hook_mail() implementation used to send the mail. This is also the module name that appears as the first argument to your drupal_mail() call.
"key" This is an identifier used to differentiate multiple emails sent by the same module. This appears as the second argument to your drupal_mail() call.

Any underscores appearing in the "modulename" or the "key" should be replaced by dashes.
For example, if my module has a machine name of "example_module" and the mail key is "example_key" then the specific template name, used just for email with that key sent by that module, should be:
  mimemail-message--example-module--example-key.tpl.php

The documentation for drupal_mail() explains a number of these things. See https://api.drupal.org/api/drupal/includes%21mail.inc/function/drupal_mail/7.x


Add contextual link to panels "custom content" pane? I am wondering if there is a way to add a contextual link to a "custom content" pane? For example my "block" panes have the block contextual link that allow for easy edit. But is there a way to do this for regular panes?

I am trying to find a way to make Panel's more accessible to the "non technical user". Having to click Panel Content, then find the gear, then edit that. Is a little too much work that can easily get lost.

Try FAPE, Field API Pane Editor. It is a separate module from ctools.

It does make it much easier for non-technical users to edit a field or a single pane of a page.


Drupal Commerce - ability to close shop (restaurant/takeaway) Looking for the best solution for this. Ideally I would like it to be similar to how we put a Drupal website in and out of maintenance mode.

It would need to disable the add to cart button and change the text to Restaurant closed or something similar.

I would then as well like to have a message on the site in the header somewhere that says Open or closed for business.

I have some minimal module development experience so looking to advance my skills with this one and get stuck into some further development.

What I really need is someone with a better understanding of drupal to point me in a good direction so that I can figure this one out.

Appreciate any words of wisdom here.

To do some flip-flopping with the Add to Cart buttons, take a look into the Commerce Stock module(s).  I'd imagine it's in the commerce simple stock.  When a product goes out of stock, it disables the Add to Cart button on the relevant product displays.  Though if even one product is available on that display, it won't disable it.  So, I would recommend checking out the commerce_stock.module and commerce_stock.rules.inc to see how they are doing that.

I envision a simple admin form page with a Close Store and Open Store buttons, and in their submit handlers, just running through and disabling the Add to Cart(s).  I'm sure there's a good way to do the "Restaurant Closed", "Restaurant Open" text, it's escaping me at the moment.


D7 CKEditor missing buttons I'm using:

Drupal 7
CKEditor 7.x-1.18
Jquery Update 7.x-3.0  (running jquery version 1.10)

I don't understand how to make the 'Font' & 'Size' dropdowns appear on the CkEditor interface.

The first image shows the settings for the "Full HTML" profile.
The second image shows the CkEditor in action.  You can see that there are lots of buttons missing, but at the moment, I'm only interested in making the 'Font' & 'Size' dropdowns appear.  You'll also notice that even though "Styles" hasn't been selected on the "Full" profile - it still appears here !?!?

I have been to the CKEditor site and downloaded the full package from here: http://ckeditor.com/download

The existing CKEditor install says to download, "Then
uncompress the contents of the "ckeditor" directory of the downloaded file to
this folder (modules/ckeditor/ckeditor)."

I appreciate similar questions have been asked before, but none of the solutions offered have worked for me.

pic 1 (above) Editing the Full HTML profile for CkEditor

pic 2 (above) Buttons are missing, and Styles has appeared !?

Hugronaphor's comment helped me find a solution that worked for me... I'm just going to explain it clearly.

Browse to /admin/config/content/ckeditor
Edit the CKEditor GLOBAL Profile
Under the "Advanced Settings", change the "Path to CKEditor"

What you enter here will depend on whether you have downloaded and installed the full package (as described in my initial question) and where you have installed it, or whether you want to use the CDN.
The instructions given below the text box are quite clear, but much like anything, it's just knowing where to look !

Because I'd already installed the full package and installed it to "modules/ckeditor/ckeditor" it means instead of using the CDN, I entered "%m/ckeditor" which made it work perfectly.

If I'd installed the full package to "/sites/all/libraries/ckeditor" I would have entered "%l/ckeditor"

...and if I wanted to use the CDN version, I would have entered "//cdn.ckeditor.com/4.4.3/full-all"  Although, I assume this version number will possibly change in the future


How to print the product variation separately from the submit/pay button in a Commerce add to cart form? I want to put the calculated product price between the "product variation" select widget and the "pay" button.

In commerce-product.html.twig (my products display an add to cart form on the product itself), I have this code:

<article{{ attributes }}>
  <h2>{{ product.title }}</h2>
  {{ product|without('title', 'variation_price' }}
  {{ product.variation_price }}
</article>

variation_price is the calculated price.

What is the name of the variable that contains the product variation select widget?  Answer: product.variations
How can I place the submit/pay button separately from the variation type selection widget?  Answer: ??

I tried using kint to debug but it broke my site.  (And then people on this site kindly explained how to fix it.)  So I now understand that the variable containing the widget that shows the variations is named product.variations, and this is actually the "Add to cart" form (since that is what I set the display widget to in the UI).

So I guess I need to print the "Add to cart" form twice, and in one instance show the submit button, and in the other instance show the select widget... But how do I do that?

I looked at the twig debug theme suggestions but they don't give me a template for the "Add to cart" form:

<!-- FILE NAME SUGGESTIONS:
   * field--commerce-product--variations--contenttype.html.twig
   * field--commerce-product--variations.html.twig
   * field--commerce-product--contenttype.html.twig
   * field--variations.html.twig
   * field--entity-reference.html.twig
   x field.html.twig

This is how I fixed this issue:

Added this preprocess function in my .theme file

function YOURTHEME_preprocess_commerce_product(&$variables) {

   // Get the commerce product.
   $product = $variables['elements']['#commerce_product'];
   // Pass the price.
   $variables['price'] = $product->variations->entity->getPrice();
}

And in my twig file I print the price like this:

{{ price|commerce_price_format }}


Show only terms that have been used? In the exposed filter form of a view, I have a taxonomy term selector set as a drop-down (you know, an HTML <select>). By default, that dropdown includes all of the taxonomy terms in the vocabulary. Is there a way to limit the terms shown to only those that will return results (i.e. only show the terms that have been used)? Basically, I want to ensure that any of the available terms will return at least one result.

An easier approach without really coding a lot would be to create your search with Search API and/or Facets.

Facets are designed to expose only options that will return results.

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

While you would have to rebuild the View, it probably is not a huge deal - and you won't have to write a bunch of code every time you expose taxonomy or similar fields as facets.


Why is a new post not shown in the Latest Topics Block after updating Advanced Forum? I updated the version of the Advanced Forum module today. I posted a new topic and now it doesn't show on a block I have in the side bar where latest created topics always used to show up.

What can be happening?

Some problems get resolved just by being patient for a while. Some of those problems are caused by either of the following:

You should have cleared the cache.
Something required a cron job to run.

If such kinds of actions are not performed (eg because you're not aware they are needed), it is just a matter of time to get such problems resolved automagically ... as illustrated in this specific comment (last paragraph) also.


Create a block Most popular content using google analytics Can anyone explain how to create a block of most popular contents using google analytics. I know about the modules Google Analystics Statistics and Most Popular but there is no good documentation about this.

How can I get any of these module to work?

Consider looking (also) at the Google Analytics Reports module. Here is an excerpt from its project page:

  ... provides graphical reporting of your site's tracking data. Graphical reports include a dashboard widget for admins, a small path-based report in blocks, and a full path-based report.


Show full query for anonymous user I'm currently troubleshooting an issue where anonymous users and certain roles see a different set of results from a view than administrators and roles with more permissions do. The view is supposed to have two node results, but for anonymous and others, there is only one.

I am trying to get the full SQL of the final query that's creating the anonymous pages. I'm using hook_views_query_alter(), and I can get the full query using dpq($view->query->query()); when I'm logged in as an administrator.

However, when I'm an anonymous user, or one of the other roles encountering the bug, I get SQL like this: ((taxonomy_index.status = :db_condition_placeholder_7) AND (node_field_data.type IN (:db_condition_placeholder_8))).

I tried getting the placeholder values from a technique I used in drupal 7, using the arguments() method, but apparently that doesn't exist in Drupal 8.

But moreover, I would like to avoid matching up the string db_condition_placeholder manually, because I could make a mistake, and misdiagnose what the source of the problem is. I want the full query string that drupal sends to the database, so that I can debug it directly with the MySQL server.

I tried other techniques listed here, such as ->addTag('debug'), which apparently did nothing, and kint($view->query->query());, which only returns output for administrator users.

How can I get the full query string from a view executed for anonymous users?

Note: This does not answer the question of "trying to get the full SQL of the final query that's creating the anonymous pages", but answers the underlying issue.

tl;dr Checking the Advanced Settings > Query > Disable SQL Rewriting option will allow views to return consistent results.

Explanation

The views module (contrib and core) configures views with restrictive entity access enabled by default. This sends the query object through hook_db_rewrite_sql (6), hook_query_TAG_alter (7, 8). Nodes for instance will add in joins to the node_access table, which can be prohibitively expensive on queries.

This is important for sites that use complex entity access where one node may be hidden from view based on node grants/access rights.

However query results will be different when querying entities (such as nodes) depending on if you are logged in. This can be frustrating when building a view as a site builder - what you see is not what you get.

It may not necessary to use SQL rewriting because a view has other access restrictions. Checking the Advanced Settings > Query > Disable SQL Rewriting option will allow views to return consistent results.

This is usually the first thing I do when creating a view unless I specifically need the extra access checks because

It improves performance significantly.
I create selective and filtered views that naturally restrict data using filters, contextual filters and view access restrictions.

Update 2019.06

Note that the views module changed the label for this setting from "Disable SQL Rewriting" to "Disable Access Checks".


Views taxonomy for multiple content types I have three different content types: News, Events and Resources. They all use the same set of taxonomy so that all content is tagged with the same categories.

I want to build a view with the taxonomy terms exposed so that they can be searched by users.

However, I seem to have to add each as a separate field, which looks quite messy.

I've tried a grouped filter, however, no results are found when I know they exist.

You can achieve this by using views :

Create a new view with show content of type ALL -> continue and edit
Under format select show fields
Under filter criteria select Content: Has taxonomy term and select selection type Drop down later check Expose this filter to visitors, to allow them to change it and click apply

Result : You can have an exposed filter with taxonomy term that filters the contents irrespective of content type


Views BEF checkbox count in drupal 7 I have created views with BEF check boxes as a filter criteria.

I want to get count of each check boxes as mentioned in below image.

Reference link.

My view name is photo_search. So I have renamed below tpl to views-exposed-form--photo-search.tpl

  I have copied views-exposed-form.tpl from views/theme to
  mytheme/templates
  . But its not working (Cache cleared & Rescanned tpl from views).

First of all make alter in your view and place the code.

// Set an index if there are multiple terms used.

    $index = 0;
    // Used for the array's string index.
    $string_index = '';
    // Continue for each vocabulary that is used.
    while (isset($form['tid' . $string_index])) {
        // Cycle through each of the terms.
        foreach ($form['tid' . $string_index]['#options'] as $tid => $option) {
            // Build a query to get the nodes for this term that have been
            // specified as filters.
            $query = db_select('node', 'n')
                    ->fields('n', array('title'))
                    ->condition('n.type', $form_state['view']->display_handler->handlers['filter']['type']->value, 'IN')
                    ->condition('fa.field_advertisements_value', 'forsale', '=')
                    ->condition('ti.tid', $tid, '=');
            // A quirk in db_select(). You need to add the join separately.
            $query->innerJoin('taxonomy_index', 'ti', 'ti.nid = n.nid');
            $query->innerJoin('field_data_field_advertisements', 'fa', 'fa.entity_id = n.nid');
            $results = $query->execute();
            $count = $results->rowCount();

// get the count of nodes or watever with your costom query

            $val = $form['tid' . $string_index]['#options'][$tid];
            $form['tid' . $string_index]['#options'][$tid] = str_replace("(" . $count . ")(" . $count . ")", "(" . $count . ")", $val . '(' . $count . ')');
        }
        // Increment for the next tid index in the array.
        $index += 1;
        $string_index = '-' . $index;
        //$string_index = '_' . $index;


Easy way to add EU cookie notification to multiple Drupal websites? I have 20+ Drupal sites that I have to add Cookie notifs to. Is there an easy/batch/automated way to do it?

Check out EU Cookie Compliance for your notifications.

  This module intends to deal with the EU Directive on Privacy and
  Electronic Communications that comes into effect in the UK on 26th May
  2012. From this date on, you run the risk of enforcement action if you are not compliant or visibly working towards compliance.

Automating the process however is quite localised depending on your server setup, and would probably be considered off topic.


Using Carousel without module I want to use jCarousel plugin or similar. But I do not want to use the module.

Add content will form part of and the carousel will add pictures. How can I do? Does anyone have an idea?

You can do this on the theme level.

Your obviously going to want to setup the content using the CMS so will take the form of nodes.

You can then use a process function to determine what content type you are on for applying your script, for example...

function YOURTHEME_preprocess_node($variables) {
   if ($SOME_NODE) {
      // Add JS plugin...
   }
}

You can then create template files for node or specific fields in that node with markup that the plugin can manipulate.

node--[CONTENT_TYPE].tpl.php

To be honest, take Clives advice, use the modules, thats what makes Drupal what it is.


What's the advantage of using Git submodules for Drupal core and contrib? I've seen a number of questions/blog posts about setting up a Git repository with Drupal Core and Contrib Modules as submodules, such as Setting up the ideal multiple repository Drupal Site version control with a DVCS.

What advantages do you get from this kind of repository set up?
Many people say things like "core and module updates are really easy," but what makes this approach easier/better than have a single repository containing everything for the site and using Drush to update Core and Contrib, then committing back to your repository?
I can see this being great for contributing to those projects since each module is a separate repository, but what benefits does to provide when focusing on building your own site?

At our workplace we avoid git submodules as they add unneccessary complexity to the system.

We run one git repo for each site, and we have drupal core as an upstream remote. This makes merging in 7.12 for example as easy as:

git fetch upstream
git merge 7.12

As for contrib, drush is king

drush dl views
git add -A
git commit -m 'bumps views to next stable'

Hope this helps


How do I list modules on my site that are not covered by the Drupal security advisory policy? We have a number of contributed modules installed on a Drupal 7 site, but there doesn't seem to be an easy way to see those covered by the Drupal security advisory policy, without copy-pasting each module name into the address bar and manually checking the page.

Is there a way to do this with Drush?

I'm not aware of a report (a good home for such a thing might be the Site Audit project? (#2882555)

Here's a very quick report for D7 that shows:

Custom modules
Modules without a release covered by Security Policy

You can download this and use it with drush scr, or copy it for drush eval directly. Feel free to improve on it!

<?php
$projects = update_get_available(true);
$uncovered = [];
foreach ($projects as $name => $project) {
  if (!isset($project["releases"])) {
    $uncovered[$name] = "No releases found";
  }
  else {
    $latest_release = reset($project["releases"]);
    if (!empty($latest_release["security"])) {
      $uncovered[$name] = $latest_release["security"];
    }
  }
};
print_r($uncovered);


Assigning revision owner when moderating backwards with Workbench I have a site that has a complex set of permissions and roles to support a workflow we have defined with Workbench Moderation.  This particular workflow has the "normal" three states:

Draft
Needs Review
Published

The workflow is set up to allow both forward progression through the workflow (eg, Draft to Needs Review) and also backwards (eg, Needs Review to Draft).  The site also uses the basic features in Workbench, and content creators like the My Content, My Drafts, and Needs Review, etc, pages / views that it provides.

OK, here is my problem.  One of the common tasks are editors pushing nodes back to Draft status for original authors to do major work on.  The problem is that if you examine node_save, revisions have their $uid set to the used who did the save (ie, $user->uid).  In this case, it would be the editor.  Therefore, the new draft shows up in the editor's queue and not the original author's (if you examine the view for this page, you can verify this behavior).

I am curious whether others have run into this problem and how they solved it.

Using a hook_node_presave to set the isn't an option, as it fires too soon, and node_save would nuke any changes, anyway.

I suspect that I could do a hook_node_update, eg

function mymodule_node_update ($node)
{
  db_update('node_revision')
    ->fields(array('uid' => $node->uid))
    ->condition('nid', $node->nid)
    ->condition('vid', $node->vid)
    ->execute();
}

but I am worried that there may be side effects that I am not considering.

Are there better options?

Old question, but in response to the comment, this is the solution that I deployed.  As far as I know, it has been working well:

/**
 * Implements hook_node_update().
 */
function mymodule_node_update($node) {
  db_update('node_revision')
    ->fields(array('uid' => $node->uid))
    ->condition('nid', $node->nid)
    ->condition('vid', $node->vid)
    ->execute();
}

/**
 * Implements hook_workbench_moderation_transition().
 */
function mymodule_workbench_moderation_transition($node, $previous_state, $new_state) {
  if (isset($node->nid) && isset($node->vid) && isset($node->uid)) {
    mymodule_node_update($node);
  }
}

This covers the case where a user updates a node via the edit form, and when a user pushes a node through moderation via the workflow forms.