How can I read config schema from a config entity? I need to read the schema definition from a config entity, which is located in config/schema. For example the schema from a node type defined in node.schema.yml:

node.type.*:
  type: config_entity
  label: 'Content type'
  mapping:
    name:
      type: label
      label: 'Name'
    type:
      type: string
      label: 'Machine-readable name'
    description:
      type: text
      label: 'Description'
    help:
      type: text
      label: 'Explanation or submission guidelines'
    new_revision:
      type: boolean
      label: 'Whether a new revision should be created by default'
    preview_mode:
      type: integer
      label: 'Preview before submitting'
    display_submitted:
      type: boolean
      label: 'Display setting for author and date Submitted by post information'

How can I do this?

Found, it can be done by using config.typed service:

$typed_config_manager = \Drupal::service('config.typed');
$node_type_definition = $typed_config_manager->getDefinition('node.type.*');


Getting the field of a user based on uid or name I'm trying to display some custom user fields of an author, of a content type's nodes. The only fields in $node that relate to the author seem to be $node->name and $node->uid. I tried this in node.tpl:
global $user;
print render($user->field_foo);

and it makes the field show up in Krumo, but it comes up as

field_foo (NULL)

When I get more specific, using what's available to me in the user page, $field_foo['und'][0] in this case, I'm given something similar:

field_foo (Array, 1 element)
und (Array, 1 element)
0 (NULL)

I'm thinking I need to target the UID or name somehow, but I don't know how. What's described in the answer here sounds like what I want, but I'm not sure how to do what they're describing. It sounds like I should maybe be using a node_submit function. Something like this maybe?
function MYMODULE_node_submit($node) {
  if (isset($node->name)) {
    if ($account = user_load_by_name($node->name)) {
      $node->uid = $account->uid;
    }
    else {
      $node->uid = 0;
    }
  }

  $node->uid->field_foo;

  return $node;
}

I think if you need show more info of author of node, you can try this way.

STEP 1

in file template.php write hook_preprocess_node

function YOURTHEME_preprocess_node(&$vars) {
  $node = $vars['node'];
  $user = user_load($node->uid);

  // if you want render field user
  $phone_render = field_view_field('user', $user, 'field_phone')
  $phone_html = drupal_render($phone_render);

  // if you want get value of filed
  $phone = field_get_items('user', $user, 'field_phone');
  $phone_value = $phone[0]['value'];

  $vars['phone_value'] = $phone_value;
  $vars['phone_html'] = $phone_html;
}

use need change field_phone with your machine name of your field user.

STEP 2
In file node.tpl.php. You can use

<?php
  print $phone_value;
  print $phone_html;
?>

print where you need.


Create view containing all content containing taxonomy terms in free text? I am using a taxonomy together with the Lexicon module to automatically create links to another website (a pretty neat solution with instructions here)

But I would also need to create view that list all nodes that contain the taxonomy terms. I am fairly competent at using the views module but I cannot figure out how to take the list of taxonomy terms and display all nodes that contain the terms in the text and what taxonomy terms the node contain.

If I understand correctly, you want to have one page that will display nodes grouped by taxonomy term they belong to so that the result is like this:

Term 1

article 1
article 2

Term 2

article 2
article 3

Term 3

article 1
article 3

To achieve that:

Create a view to display all content of [content type name] and select the node fields you want to display in place of article 1,2,3 (probably title of the node at least).
Add relationship "Content: Taxonomy terms on node" and decide which taxonomy you want to narrow down the display.
Under View field, there should be now a list of Taxonomy related fields. You probably want to add field "Taxonomy term: Name". Exclude that field from display.
Under View  format settings, select to Group By that taxonomy field.


Need clarification on installing site with DRUSH on localhost I have read tutorials and drushcommands site, but I'm missing something...

My desired info is as follows:

Database name: scratch
Database username: scratch
Database password: 1
Account name: scratch (admin login?)
Account password: 1  (admin password?)
Site in English

I have the username set up in PHP my admin, desired website URL is localhost/scratch

My Drush command is:

drush dl drupal-7.x
drush site-install --db-su:scratch --db-su-pw:1 --account-name:scratch
--account-pass:1 --account-mail:founder@satearn.com --locale:EN

Am I missing something? I'm getting these errors:

  e:\xampp-portable\htdocs>drush site-install --db-su:scratch
  --db-su-pw:1 --account-name:scratch --account-pass:1 --account-mail:founder@satearn.com --locale:EN

  Command site-install needs a higher bootstrap level to run - you will     need to invoke drush from a more functional Drupal environment to run this command.

  The drush command 'site-install' could not be executed. [error]

Use this command to install Drupal.

drush site-install standard --db-url="mysql://scratch:1@localhost/scratch" --account-name=scratch --account-pass=1 --account-mail="founder@satearn.com"

Note: Move to the folder drupal-7.x folder and run this command from there. This command should be run from the place where your drupal files are located.
It would be better just to rename it drupal instead of drupal-7.x for easiness.
I tested it right now and its working.


How can you add a multiple value field to an entity? Edit: My question is similar to How to create multi-value, multi-bundle entity reference fields in code?, except the field doesn't need to reference multiple bundles.

We have an existing view of custom entities.  The view needs to now be filtered based on some related fields that are not part of the entity (or any entity).  Kind of like adding a Taxonomy Reference field to a Content Type.  What is the best way to add those fields to the entity?

I see that many modules use attachLoad to attach fields to an entity, but when I try my implementation those fields don't show up in my list of Fields or Filters in Views.

This is a screenshot of the checkboxes field:

This is my controller:

class ContactsController extends EntityAPIController {

  public function attachLoad(&$queried_entities, $revision_id = FALSE)
  {
    foreach ($queried_entities as $key => $entity)
    {
      $queried_entities[$key]->foo = "bar";
    }
    parent::attachLoad($queried_entities, $revision_id);
  }

}

And this is my hook_entity_info:

function contacts_entity_info() {
  $return = array(
    'contacts' => array(
      'label' => t('Contact'),
      'entity class' => 'Contacts',
      'controller class' => 'ContactsController',
      'views controller class' => 'ContactsViewsController',
      'base table' => 'contacts',
      'fieldable' => TRUE,
      'entity keys' => array(
        'id' => 'ckid',
        'bundle' => array(),
      ),
      'bundle keys' => array(),
      'bundles' => array(),
      'load hook' => 'contacts_load',
      'view modes' => array(
        'full' => array(
          'label' => t('Default'),
          'custom settings' => FALSE,
        ),
      ),
      'label callback' => 'entity_class_label',
      'uri callback' => 'entity_class_uri',
      'module' => 'contacts',
      'access callback' => 'contacts_access',
    ),
  );

  return $return;
}

This is a suggested implementation of EntityDefaultViewsController:

/**
* EntityTest Views Controller class.
*/
class ContactsViewsController extends EntityDefaultViewsController {

  /**
   * Add extra fields to views_data().
   */
  public function views_data() {
    $data = parent::views_data();

    // Add your custom data here
    $data['contacts_topics']['table'] = array(
      'group' => t('Contacts Topics'),
      'base' => array(
        'field' => 'ckid',
        'title' => t('Contacts Topics'),
      ),
      'join' => array(
        'contacts' => array(
          'left_field' => 'ckid',
          'field' => 'ckid',
        ),
      ),
    );

    $data['contacts_topics'] = array(
      'ckid' => array(
        'title' => 'Contact Entity ID',
        'field' => array(
          'handler' => 'views_handler_field_numeric',
          'click sortable' => TRUE,
        ),
        'sort' => array(
          'handler' => 'views_handler_sort',
        ),
        'filter' => array(
          'handler' => 'views_handler_filter_numeric',
        ),
        'relationship' => array(
          'base' => 'contacts',
          'base field' => 'ckid',
          'handler' => 'views_handler_relationship',
          'label' => t('Contact entity relationship'),
          'title' => t('Conact entity relationship'),
        ),
      ),
    );

    return $data;
  }
}

Unfortunately I don't see anything in the Views SQL that shows that any of these attempts to add the fields or join the topics table to the contacts table are working.

How to attach a field to an entity programically solved this problem for me.  It's not an exact duplicate, but the answer and the comments pointed me to the right direction.

So this code creates the field and the instance and it attaches it to the entity very nicely:

function contacts_enable()
{
  if (!field_info_field('related_topics'))
  {
    $field = array(
      'field_name' => 'related_topics',
      'type' => 'list_text',
      'cardinality' => -1,
      'settings' => array(
        'allowed_values_function' => '_contacts_get_related_topics',
      ),
    );

    field_create_field($field);

    $instance = array(
      'field_name' => 'related_topics',
      'entity_type' => 'contacts',
      'label' => 'Related Topics',
      'bundle' => 'contacts',
      'default_value' => NULL,
      'settings' => array(
        'user_register_form' => FALSE,
      ),
      'widget' => array(
        'active' => 1,
        'module' => 'options',
        'settings' => array(),
        'type' => 'options_buttons',
        'weight' => -1,
      ),
    );

    field_create_instance($instance);
  }
}


Batch job not running callback I am trying to run a batch job of importing items from a csv file. When I click submit on my form and my batch process starts, I do get a batch process bar which says its progressing, but it never calls my callback function or my finished function. I've done a dpm() of th $batch array before I run it, and it seems to be in order. What am I missing?

$count = 1;
  while($count <= count($csv) ) {
    $operations[] = array('ons_institutional_subscriber_importer_import', array(array_slice($csv, $count, $count + 10)));
    $count = $count + 10;
  }
  $batch = array(
    'title' => t('Importing Institutional Subscribers'),
    'operations' => $operations,
    'finished' => 'ons_institutional_subscriber_importer_finished',
    'init_message' => t('Import is starting.'),
    'progress_message' => t('Processed @current out of @total.'),
    'error_message' => t('Import has encountered an error.'),
  );
  dpm($batch);
  batch_set($batch);
  batch_process();

and my callback functions

function ons_institutional_subscriber_importer_import($csv, &$context) {
  dpm('hello');
  //more code here...
}
function ons_institutional_subscriber_importer_finished($success, $results, $operations) {
  if ($success) {
    $message = format_plural(count($results), 'One post processed.', '@count posts processed.');
  }
  else {
    $message = t('Finished with an error.');
  }
  drupal_set_message($message);
}

This Problem happens when we put our file in different folder like as includes/form_test.inc.In this scenario batch function can't call.So to handle this we put 'file' => 'path_to_file_containing_myfunctions' in our submit function.I wish this code will help you in understanding.you are missing 'file' in your batch array.

$batch = array(
  'title' => t('Custom File uploader'),
  'operations' => array(
    array('test_feeds_import_form_batch', array($uri)),
  ),
  'progress_message' => t('Uploading Multiple Products...'),
  'error_message' => t('Error!'),
  'finished' => 'test_feeds_import_form_batch_finish',
  'file' => drupal_get_path('module', 'test') . '/includes/test_form.inc',
);

batch_set($batch);
batch_process('admin/import-data'); //Work like as drupal goto


How to apply Image Styles to images that have been added to published nodes? We have an image field (field_image) that did not have an image style originally applied. In the end we have hundreds of nodes (pages) where the Image style is not present. When adding an image style to the field under the respective View Mode, we are still getting an image without the image style applied.

How can we enforce the image style to be applied to currently published nodes?

Current results:

Desired results:

What we have tried that didn't work:

Flush image style
Cleared cache

Start by checking your admin logs for one and second make sure that the new style directory permissions are correct. Image styles Troubleshooting -That's assuming that the images are being created and the folder(s)'s .htaccess is all good.

Also maybe force it by adding your specific style as argument using drush if MACHINE_NAME


Webform block: reload page with anchor link I have a webform shown in a block that appears at the bottom of my page.

If I select 'no redirect (reload current page)' when the form is submitted you are taken back to the top of the page and the confirmation message is shown above the form, so unless you scroll down it appears as if nothing happened.

If I select 'Custom redirect URL' and enter [current-page:url]#my-form when the form is submitted you do get taken down the page to the form only now the confirmation message is shown at the top of the page, so unless you scroll up you won't see it.

Is there a way to refresh the page, scroll down to my form and show the confirmation above it or do I have to use AJAX for this?

You can achieve that by using the Webform Ajax module

This module adds AJAX support to Webform (3.0 and above).
As a first step it focusses to simply add form AJAX paging and submit. Form submissions get ajaxified including prev/next pages. Especially for multipage forms, this leads to faster loading (less data transfer), better usability and finally smaller server load.


modify Drush uli returned URL string of to include port? I want to modify a variable (preferably in a Bash Script format) because my PHP environment requires a port number.

To open a browser in Drush, one executes

$ drush uli

In a script:

$ bash-3.2$ VAR='drush uli'; echo ${VAR}; ${VAR}

outputs:

  drush uli

http:/ /website-7-26-2-17-res124725.local/user/reset/1/1393147909/zMiquSr_ikA7xdp7kA3g4CvTGd82mWsVdqEiMCs/login

Can I modify that URL before Drush opens the browser?

Can I stop it from executing and manipulate the URL in a Bash script?

You can create settings.local.php with your development base url:

$base_url = 'http://website-7-26-2-17-res124725.local:8888';  // NO trailing slash!

Drush just uses Drupal's url() function to build user one-time-login link.


Automatically clear cache Theme: Basic 8.x-1.x-dev

I am trying to clear theme data after any change is done to twig files.  I see that rebuildThemeData is here: https://goo.gl/EA2YL4

Currently have this within my .theme file.

\Drupal::service('theme_handler')->rebuildThemeData();

\Drupal::service('theme.registry')->reset();

Does anyone have this sort of implementation complete and working for an example?
https://www.drupal.org/node/2608470

There are some defaults that ship with D8 in your sites/default configuration files that you can configure during development.

The application portion:

Open development.services.yml in the sites folder
and add the following block (to disable twig cache)
        parameters:
          twig.config:
            debug : true
            auto_reload: true
            cache: false

There is more information on this Drupal.org node.


How to implement georeferencing in Drupal? I must make a website with geo-referenced content. And I would like to add POI and the possibility to download this POI for GPX, KML\KMZ (Google Earth), etc.

Any tips or ideas to implement this somehow?

PS: if the above is not clear enough, have a look at this or this (the idea is building a website with such contents).

If you want to use an existing module - something like GMap is probably the easiest place to start.

That being said, the Google Map API is fairly easy to use, so nothing preventing you from writing a module that does exactly what you want.


Cancel user creation from hook_user_presave I created a module that links to Taleo (Talent Management system). When creating a Drupal user, automatically a Taleo Candidate is made.

This works like a charm. But sometimes Taleo answers with an error (example: a candidate with email address info@example.com already exists)

Is there an easy way to cancel the creation of the user from within 'hook_user_presave'? Now the error messages is showed, but the Drupal user is made anyway.

function taleo_user_presave(&$edit, $account, $category) {
    global $client_taleo;
    $session = _taleo_login();
    $error = 0;

    if(!isset($edit['field_taleo_id'][LANGUAGE_NONE][0]['value'])) {
        // NOT LINKED TO TALEO

        $params = array(
            'in0' => $session,
            'in1' => array('id' => '', 'rank' => '', 'status' => '0-Available',
            'firstName'     => @$edit['field_first_name'][LANGUAGE_NONE][0]['value'],
            'lastName'      => @$edit['field_last_name'][LANGUAGE_NONE][0]['value'],
            'phone'         => @$edit['field_phone_number'][LANGUAGE_NONE][0]['value'],
            'zipCode'       => @$edit['field_zip_code'][LANGUAGE_NONE][0]['value'],
            'country'       => @$edit['field_country'][LANGUAGE_NONE][0]['value'],
            'textResume'    => @$edit['field_text_resume'][LANGUAGE_NONE][0]['value'],
            'lastUpdated'   => date('c'),
            'email'             => @$edit['mail'])
        );

        try{
            $edit['field_taleo_id'][LANGUAGE_NONE][0]['value'] = $client_taleo->__call('createCandidate', $params);
        } catch (SoapFault $fault) {
            $error = 1;
            $error_message = check_plain("ERROR: " . $fault->faultcode . "-" . $fault->faultstring);
            drupal_set_message($error_message);
            watchdog('taleo', $error_message, array(), WATCHDOG_ERROR);
            return array();
        }

    }

The equivalent of hook_user('validate') used in Drupal 6 doesn't exist in Drupal 7. For that, you need to add a form validation handler to user_register_form(), and use form_set_error() when Taleo returns an error.


How do I add my new Paragraph type to a content type? I've made a new Paragraph type and it appears as an option in the Basic Page content type, but I'd also like it to appear in another content type.

Would anyone know where I set this?

Turns out I was missing a step:

Structure>>Content Types
Edit the content type you want to add the Paragraph to
Go to Manage Fields tab
Find the Paragraphs entry in the list and click edit
Check your bundle from the list


Use taxonomy path-alias I've been working playing with the Facet API Search lately and I liked a lot the option that Facet API provides to use the alias of the taxonomies in the URL.

I was wondering if there is a chance to do the same in the Views. eg to be able to use the taxonomy alias as a token to construct a link. What I would like to achieve is to be able to construct in the Views a URL that can take me to a Faceted Search page so I can pre-filter it.

I know that is a bit redundant to be doing it, but for the project I work on, is something that was specifically requested. In the Views, there is no way to be able to get the alias of a taxonomy as a field. The only things I've seen so far, is to mimic the re-writing of taxonomy using PHP code here and here .

I tried to find a module that would help use the alias but nothing had come up. Also, here in the forum, I had found similar issues but nothing related to my question about taxonomies.

How to filter a View with Taxonomy alias

Get a node alias as a field value

Nevermind, I managed to do this via a module I wrote.

To whom it may concern, the idea is to create a hook override for the hook field formatter.


How to print a date from Date module using user timezone I would like to send an email out to a user when a new 'event' content type is posted. In this email, I want to display the title of the event, the body, and the date itself. For the date, I would like to print the date in the timezone of the user receiving the email.

So, when I send the email, I first get the user's account and the event node:

<?php
  $account = user_load($uid);
  $event = node_load($nid);
?>

I want to first check if the user has a timezone set in the user's profile, and if not, default back to the timezone used (and stored) with the event itself. So, something like:

<?php
  $timezone = $account->timezone ? $account->timezone : $event->field_event_date[$event->language][0]['timezone'];
?>

But, at this point, I'm not sure exactly how to print the date in the node in the correct timezone. I'm thinking I might have to first create a new DateTime object, then convert it using date.module's date_format_date, or maybe convert the date to a timezone, calculate the offset, and use PHP's date() function or format_date() to display the end result, but this all seems overkill.

Is there a simpler way to print out a date from a date field attached to a node in a user's timezone?

[Edit:]

I'm trying to format the date using format_date() or date_format_date(), but format_date() requires a time stamp, which is difficult to create from the date field's output, and date_format_date() also requires proper timezone information when I create a date object, and I've found it difficult to account for the timezone supplied by the date field, and then translate that into the timezone for output.

[Edit 2:]

Here's the code I ultimately used:

<?php
  $event = node_load([nid]);
  // Build event date + timezone.
  $timezone = $account->timezone ? $account->timezone : $event->field_event_date[$event->language][0]['timezone'];
  date_default_timezone_set($event->field_event_date[$event->language][0]['timezone_db']);
  $date = strtotime($event->field_event_date[$event->language][0]['value']);
  $date_formatted = format_date($date, 'custom', 'M j, Y g:i a', $timezone);
?>

The problem is the configuration of the date field itself. In its settings (field management->edit), you will find an option "Time zone handling". This option controls the way this field is parsed and its display. I will venture a guess that yours is set to "Site's time zone". This means, that the default timezone will be used to convert this datetime into UTC, and the same will be used to display it. If changed to "User's time zone" option, then user's timezone will be used instead, and the default one will be the fallback if none such is set. The latter is taken into account from the format_date() function, without your having to set the $timezone parameter explicitly.

In your case, since each event has a timezone of its own, I would also consider the second option "Date's time zone". In this case, custom date timezone is not taken into account by format_date(), thus needs to be explicitly set.

Read the complete documentation here


How to show view for submitted result of a webform by a user How i can show all submitted value of a webform by a user in a view in a tab of a user profile section.

Iam using drupal 6.For example when user click on a tab say form on his profile the webform value submitted by that user show.

Thanks for your help.

I have done that in drupal 7 but not in drupal 6. In drupal 7, go to View.

Create a relationship "Webform Submissions: User" and require it
Create the contextual filter "User: uid"
Select the relationship which you created in step 2 and select "provide Default Value" under "When the value is NOT in the URL" and select "User ID from logged in User".

I hope this will help you out.


submit function not call I create a menu , in call back of menu create add content form , add one submit function to it, but the function not  call NEVER . where is the problem?

 $items['share/%'] = array(
        'page callback' => 'ym_alter_sharing_content',
        //'page arguments' => array(''),
        'access callback' => 'user_is_logged_in',
        'type' => MENU_CALLBACK,
    );

function ym_alter_sharing_content($form,$form_state) {
module_load_include('inc', 'node', 'node.pages');
$nid=arg(1);
$form = node_add('share');
//$form['#submit'][]='ym_alter_sharing_sub';
//array_unshift($form['#submit'], 'ym_alter_sharing_sub');
//array_unshift($form['actions']['submit']['#submit'][], 'ym_alter_sharing_sub');
//$form['actions']['submit']['#submit'][]='ym_alter_sharing_sub';
array_unshift($form['actions']['submit']['#submit'], 'ym_alter_sharing_sub');
//return render($form);
return $form;
}

function ym_alter_sharing_sub($form,$form_state){

 //dsm($form_state['values']);
 var_dump($form_state['values']);
 die("kill for debugging");
}

I'd do something like this:

$items['share/%'] = array(
  'page callback' => 'ym_alter_sharing_content',
  'page arguments' => array(1),
  'access callback' => 'user_is_logged_in',
  'type' => MENU_CALLBACK,
);

function ym_alter_sharing_content($some_arg = NULL) {
  module_load_include('inc', 'node', 'node.pages');
  $form = node_add('share');
  array_unshift($form['actions']['submit']['#submit'], 'ym_alter_sharing_sub');
  return render($form);
}

function ym_alter_sharing_sub($form, &$form_state){
  //dsm($form_state['values']);
  var_dump($form_state['values']);
  die("kill for debugging");
}

EDIT:
Another suggestion:

module_load_include('inc', 'node', 'node.pages');
$node_type = 'YOURNODETYPE';
$form_id = $node_type . '_node_form';

$node = new stdClass();
$node->type = $node_type;
node_object_prepare($node);

$form = drupal_get_form($form_id, $node);
array_unshift($form['actions']['submit']['#submit'], 'ym_alter_sharing_sub');
return render($form);


Change default on login url How do I change Drupal's default on login url from /user/<uid> to /user/<uid>/edit so that a user gets to there right after they log in?

EDITED:
Tried Rules:

  Events: User has logged in.

  Condition: User has role.

  Actions: Page redirect to user/[current-user:uid]/edit

For some reason it doesn't work.

Tried Login Destination. Redirects work, but the module doesn't support tokens.

Managed to do this with Rules:

  Events: User has logged in.

  Condition: -

  Actions: Page redirect to user/[account:uid]/edit


Set node field value in separate form I have a File field attached to my content type. Using Drupal, when we are creating new node, we use node form to set all field values for particular node. But is it possible to create more forms for editing one node? In particular, I need to setting File field values in separate page separated from node form.

For now, I do it with Form API, and hook_form_alter. For file field I can use form type "managed_file".
 But is it possible with some existing module, using GUI?
Could  I create separate form, where I can set just one (or few) fields of node (or entity, in general)?

EDIT: to explain it shortly. I would like to split node form to more forms. I would be able to set, which node fields would be set in which form.

Not sure i follow your narrative up there but you might be interested in entity metadata wrapper to help you deal with the objects and their states individually with custom forms.

https://drupal.org/node/1021556

The project page:
https://drupal.org/project/entity


View using views content pane not updating on node save On the home page, I have a view content pane to display the latest 3 blog items.  When I save a new blog node I don't see my new item on the home page. The only way to get it to show up is to flush all cache.

Any way to force the cache on the home page alone to clear when the node is saved?

Take a look at the Views content cache module.  It allows you to expire the views cache on add/edit/delete of nodes in your view.

Also, be sure to look at the Panels caching on your home page, whether that be in Page Manager, or Panelizer, you can set caching on items in Panels using the Panels Content Cache module.


Maintaining libraries on a live site without Composer I notice this question has been asked several times on here - and each time the answers always seem to involve using Composer one way or another! :-)

I get that one can get around shared hosting constraints by using Composer in their local dev environment and then uploading the lot, but what about maintaining libraries without Composer at all. Is it even possible?

I recall in D7 it was possible to manually download and maintain libraries in a nominated folder location. Is this still possible in D8?

Well, turns out it is possible, at least in terms of getting modules like Webform and Entity Print working.  Both of these require libraries and many guides on installing them are emphatic that you MUST use composer for them to work.

I managed to get both of them working without using Composer:

Regular libraries such as those used by the Webform module can simply be extracted to the /Libraries folder. Simply create the directories specified in the admin/reports/status report after you instal the Webform module and put each library there.

Here is a great guide on manually installing dompdf (to use with modules like Entity Print) in the /Vendors directory: https://www.drupal.org/project/entity_print/issues/3081358#comment-13667896.

So far, at least, not so hard after all...


Add custom styles for printing taxonomy terms I'm using print module for generating a PDF file. Here, the node that I'm printing has a field that lists all the taxonomy terms for that specific node.

When the page is printed, the taxonomy terms are displayed in an unordered list with bullets, leaving an empty line between field name and taxonomy terms as:

Field name:

 - term1
 - term2

But, I wish to display the terms next to field name in the generated pdf. I tried using taxonomy menu module, but i anticipate it doesn't work with print module. Is there any way to get this done.

If you go to the display settings for your node (eg. admin/structure/types/manage/article/display) and in the "Custom display settings" fieldset check the box for "Print" and the save.
Then click the tab for the "Print" display settings.

Then configure your field with an inline label.

If this is not sufficient for your requirements you could also then override node or field templates specifically for that print display mode.

I can provide more information on that if you require it.

For node and field templates you can either use an if statement in the template to specify a specific view mode or you can add specific template suggestions so that you can have specific templates, like node--print.tpl.php

For the if statement method there are variables already available in those tempaltes:

node.tpl.php

<?php if ($view_mode == 'print'): ?>
  Your code goes here.
<?php endif; ?>

field.tpl.php

<?php if ($element['#view_mode'] == 'print'): ?>
  Your code goes here.
<?php endif; ?>

Or you can add template suggestions like this in your template.php file:

node.tpl.php

/**
 * Variable preprocessor for the node templates.
 */
function THEMENAME_preprocess_node(&$vars) {
  // Template suggestions for node--VIEW-MODE.tpl.php.
  $vars['theme_hook_suggestions'][] = 'node__' . $vars['view_mode'];
  // Template suggestions for node--NODE-TYPE--VIEW-MODE.tpl.php.
  $vars['theme_hook_suggestions'][] = 'node__' . $vars['node']->type . '__' . $vars['view_mode'];
}

field.tpl.php

/**
 * Variable preprocessor for the node templates.
 */
function THEMENAME_preprocess_field(&$vars) {
  $element = $vars['element'];

  // Template suggestions for field--VIEW-MODE.tpl.php.
  $vars['theme_hook_suggestions'][] = 'field__' . $element['#view_mode'];
  // Template suggestions for field--FIELD-TYPE--VIEW-MODE.tpl.php.
  $vars['theme_hook_suggestions'][] = 'field__' . $element['#field_type'] . '__' . $element['#view_mode'];
  // Template suggestions for field--FIELD-NAME--VIEW-MODE.tpl.php.
  $vars['theme_hook_suggestions'][] = 'field__' . $element['#field_name'] . '__' . $element['#view_mode'];
}

Those are examples. You can make other suggestions based on pretty much anything you want.
You can also just do a specific template suggestion for the print view mode instead of doing dynamic ones for all view modes like the above examples.
If using the above examples be careful that you don't have conflicts, for example if you have a node type that is the same as a view mode.


How to get a patch for the Views module reviewed and committed to the project? Recently I found an issue with the Drupal Views module. I have submitted a patch to fix it.

Does anyone know what the process is to:

get this issue (and related patch) reviewed?
ultimately get the patch committed to the project?

Due to the amount of open issues (like over 3.700 ...) it appears the maintainers for Views are possibly dealing with more complex issues, or there might be a views project specific process to get a patch committed?

Does anyone know the answer to my questions?

Note: The specific issue I have fixed can be found at https://www.drupal.org/node/2428065, so if anyone could check this any confirm on the issue if this is fixed that would be appreciated.

A pitty that nobody has reviewed your patch so far. I think you should consider posting a question in one of the Drupal.org forums, with some kind of friendly reminder about it. Something like "can anybody help me on this specific issue to get it in status  Reviewed & Tested by the Community (RTBC) please?".

By the way: RTBC is not to be considered as a synonym of "Patch to be ported". Though as a maintainer of a few Drupal modules, I often treat an issue in such status as "Ready To Be Committed".

RTBC is, in my opinion, the next status that your issue should be changed to (assuming your patch is tested by somebody else, and confirm to indeed solve the issue).

After the issue receives RTBC status, it's up to any of the (co-) maintainers of that project to actually apply the submitted patch to the most current dev version (make sure your patch was created as compared to that, if not there is a risk the patch needs to be re-rolled, which in turn will cause more delays until that gets done). It is perceived as a good practice in Drupal to also "give credit" to the submitter of the patch, by indicating your drupal userid as part of the commit message.

And from then on, it's a matter of waiting for a new release that includes the corresponding commit of course.

A great illustration of this workflow can be found in the issue at https://www.drupal.org/node/1947876 ... Even though that specific issue has taken really long (over 2 years ...) before it made it to the finish, i.e. status fixed and closed. What I find so amazing about this issue is that it is a perfect illustration of "the community at work", where each of the players did their part of the work ...

FYI: I'm a (co-) maintainer of a few Drupal modules (refer to my SE profile for details), sometimes it's hard to find sufficient time to process such RTBC-patches (waiting to be committed). But whenever I have time, I always give those RTBC-issues the highest priority, out of respect for the contributors of such patches (and the people who reviewed them) ...

PS: even if your patch doesn't get committed as fast as you'd like it to be, you should still continue submitting patches. Because that way you have them available for any sites where you believe this patch is required. This may require however that occasionally you need to update / rework your patches.


I want to add a field in drupal commerce products by default like commerce_price? I want to add some default fields whenever new product types are added like we have for commerce_price field in drupal commerce.
I already have a field_abc_attribute(widget is select list and field type is option_set_reference) added which in one of the product type
I was checking through hook_fields_extra_fields() function but it did not create new fields on
How can I achieve it?

function custom_module_field_info() {
  drupal_set_message('jsdfsdfsdfsd');
  return array(
    'field_product_attribute_val' => array(
      'label' => t('Product Attributes'),
      'description' => t('This field product attributes.'),
      'settings' => array(),
      'instance_settings' => array(),
      'default_widget' => 'commerce_option_set_reference_select_list',
      'default_formatter' => 'commerce_option_set_reference_form',
 //     'property_type' => '',
   //   'property_callbacks' => array('commerce_price_property_info_callback'),
     // 'default_token_formatter' => 'commerce_price_formatted_amount'
    ),
  );
}

function commerce_module_field_extra_fields() {
  $extra = array();
  drupal_set_message('nerer');
  foreach (commerce_product_types() as $type => $product_type) {
    $extra['commerce_product'][$type] = array(
      'form' => array(
                      'field_product_attribute_val' => array(
                                     'label' => t('Product Attribute For Vendor'),
                                     'description' => t('Product Attribute Field For Vendor form element'),
                                     'weight' => -10,
                      ),
      ),

      'display' => array(
        'field_product_attribute_val' => array(
          'label' => t('product attribute vendor extra'),
          'description' => t('The product attribute vendor extra of the product'),
          //      'theme' => 'commerce_product_sku',
          'weight' => -10,
        ),
      ),
    );
  }
  return $extras;
}

The hook you're trying to use is unrelated to Field API fields, unfortunately. You should look at the commerce_product.module and commerce_product_ui.module files to see how I did it in core for the default price field. Either on module enable or when a new product type is created via the UI, I call the commerce_product_type_configure() function that in turn adds the default price field to the product type. You'll want a similar function that you can invoke when a module is enabled or on hook_commerce_product_type_insert() to add your custom fields.


How to unsubscribe from issues on drupal.org to not see the updates in my dashboard? I visit My dashboard to see answers on my issues. This is comfortable.

I've been typed comments in other issues and got the answer, but now I receive the info about new comments on those issues that I do not want to look. I get the "updated" tag on them.

How to kick those issues from My Dashboard https://www.drupal.org/dashboard?

You can unfollow the post by clicking on following.


How does a view (/admin/build/views/) relate to a .tpl file I am new to Drupal and now maintaining a completed Drupal site and I am struggling to understand how it all came into existence :)

What I have gathered from poking around the current code base is that there is some kind of relation from a view you create in the admin section to a .tpl file, and for the life of me I cannot figure out what it is.... am I even on the right track?

Any help or good reads would be much appreciated!

Actually, a view will use many template files (which you can override in a theme if desired); it depends a lot on how you configured your view (e.g. style, content).

The most useful information can be found when you're configuring your View. Just click Theme: Information in the Basic settings pane of your View, and the View itself will give you a list of tpl.php files that are used for rendering. Don't forget that there isn't only one tpl.php - there are many, and they wrap each other a lot (they're nested). Reading about generic Drupal theming will help a lot. The same rendering basics are used for Views.

If you want a template file for one specific View, look at the suggestions given by "Theme: Information." You can override any template file, for a specific View only (identified by its machine-name). This is probably what you're asking for, actually.

A good link on the subject is Theming Views.


How to disable 'Path prefix language code' for admin panel? My sites requires the use of 'Path prefix language code' under admin/config/regional/language/edit/en to append the language prefix to the URL path, so if the language is English, node/1 would become en/node/1

The problem is that when I am trying to translate content, the links to the translation pages contain this prefix too, and that will reach a page that is not there:

/tc/my-node-title/edit/zh-hant is the wrong path, the correct path is...

/my-node-title/edit/zh-hant

So is there a way to remove the language prefix on the admin panel?

Have you tried to use the GlobalRedirect module? You may be able to set the option 'Language Path Checking' to true in the module configuration page and add the paths for admin pages in there.


How to grant edit access only to set of users defined in a cck field of a node? I am trying to restrict edit(node/%nid/edit) access only to users defined in one of the node fields. can I use hook menu alter for node/%nid/edit so i can write a custom access callback or use hook node access to achieve it. One thing to mention here is any user can comment on that node and when they save the comment, I am updating some fields on the node and saving it thru node_save. What will be the best way to achieve this access restriction.

As per me the best way to restrict the edit access would be by implementing hook_node_access, something like the following:

function MODULE_node_access($node, $op, $account) {
  if ($op == 'update' && $node->type == 'YOUR_TYPE' && $node->field_custom[LANGUAGE_NONE][0]['value'] == 'some value') {
    return NODE_ACCESS_ALLOW;
  }
  else {
    return NODE_ACCESS_DENY;
  }

}


Override exposed filter dropdown values I have exposed filter of taxonomy with dropdown. I want to override the dropdown menu, so that when I filter through this exposed filter, the url contains title of taxonomy and not the ID of taxonomy.

So, I have used hook_form_alter to override this dropdown, and made it in the form,

<option value='TEXT'>TEXT</option>,

initially it was like

<option value='ID'>TEXT</option>,

But in this case it is not filtering out any results, please suggest how can I make it work.

Thanks for your time.

Implementing hook_form_alter() alone is not enough. The View query will check the taxonomy by term id. Now you just altered it to title in the dropdown values.

You would then need to implement hook_views_query_alter() and alter the query condition as your need. Assuming you have a taxonomy term field field_cat, your view query will have the following similar condition - field_data_field_cat.field_cat_tid = {the_selected_value}

Now, you need to check it against taxonomy_term_data.name:

function MYMODULE_views_query_alter(&$view, &$query){
    if($view->name == 'your_view_name'){
        $conditions = $query->where[1]['conditions'];
        $k = 0;
        foreach($conditions as $cnd){
            if($cnd['field'] == 'field_data_field_cat.field_cat_tid'){
                $replaced_condition = array(
                    'field' => 'taxonomy_term_data_field_data_field_cat.name',
                    'value' => $cnd['value'],
                    'operator' => $cnd['operator']
                );
                $query->where[1]['conditions'][$k] = $replaced_condition;
                break;
            }
            $k++;
        }
    }
}

Hope this helps.


Set a specific changed date for a node I am creating nodes programatically based on the feed from an external api. I have managed to create all nodes, assign field values and also set the created date. Now my problem is that I also need to set the changed date of each node to match the value returned from the feed. I have tried to set this value before saving the node without any success:

// $data contains the release information used to create and populate the node
$node = new stdClass();
$node->title = $data->Release->Title;
$node->type = 'release';
node_object_prepare($node);
$node->status = NODE_PUBLISHED;
$node->uid = 1;
$node->language = LANGUAGE_NONE;

// handle any field data - not really important
handleFields($node, $data);

// submit the node
$node = node_submit($node);

$node->created = strtotime($data->Release->PublishDate);
// here I'm trying to set the changed value for the node
$node->changed = strtotime($data->Release->LastChangeDate);

// finally save the node
node_save($node);

Would be nice if anyone have a solution to this problem. Perhaps I can make a raw query against the database in order to update the changed date of the node?
The reason I need to set this value is because later on it will be used to compare against the modification date of a release in the feed so I can decide if the node needs to be updated or not. I know I could use a custom field for this purpose, storing the releases modification time and then compare against this value instead of the changed column in the node table.

The code you are using doesn't work as expected because you are first setting $node->changed, and then calling node_save(), which then unconditionally sets its value.

The code it uses is the following one.

// Set the timestamp fields.
if (empty($node->created)) {
  $node->created = REQUEST_TIME;
}
// The changed timestamp is always updated for bookkeeping purposes,
// for example: revisions, searching, etc.
$node->changed = REQUEST_TIME;

$node->timestamp = REQUEST_TIME;
$update_node = TRUE;

// Let modules modify the node before it is saved to the database.
module_invoke_all('node_presave', $node);
module_invoke_all('entity_presave', $node, 'node');

If you want to set $node->changed, you would need to implement hook_node_presave(), which is invoked right after node_save() sets
$node->changed.
For example, in the code you are showing, I would add $node->release_change_date = strtotime($data->Release->LastChangeDate);; your implementation of hook_node_presave() would then use $node->release_change_date to set $node->changed ($node->changed = $node->release_change_date).


Drush 9 - Destination Argument Does Not Exist I've been struggling a lot with Drush 9 sql:sync the past few months. I've gotten it to work a few times, but I've been stumped by this most recent problem:

$ drush sql:sync @prodv2 @local --debug
Using the Drush script found at /Applications/MAMP/htdocs/ianmoffitt/vendor/drush/drush/drush using proc_open
 [preflight] Config paths: /Applications/MAMP/htdocs/ianmoffitt/vendor/drush/drush/drush.yml,/Applications/MAMP/htdocs/ianmoffitt/drush/drush.yml
 [preflight] Alias paths: /Applications/MAMP/htdocs/ianmoffitt/web/drush/sites,/Applications/MAMP/htdocs/ianmoffitt/drush/sites
 [preflight] Commandfile search paths: /Applications/MAMP/htdocs/ianmoffitt/vendor/drush/drush/src,/Applications/MAMP/htdocs/ianmoffitt/drush
 [bootstrap] Bootstrap to none [0.13 sec, 8.14 MB]
 [bootstrap] Drush bootstrap phase 0 [0.13 sec, 8.14 MB]
 [bootstrap] Try to validate bootstrap phase 0 [0.13 sec, 8.14 MB]
 [error]  The "destination" argument does not exist. [0.13 sec, 8.19 MB]

Can't find anything online towards this specific error message. Not sure what I'm missing or what to even check.

Again, this command worked about a week or so ago. All I've done since then is run composer update. Did something change recently?

Using Drush 9.3.0.

Just for the record - in my case, given "destination" argument was coming from an outdated custom Policy command I got when I was setting up the project - https://github.com/drupal-composer/drupal-project/blob/8.x/drush/Commands/PolicyCommands.php

It should be "target" instead and the current state of https://github.com/drupal-composer/drupal-project reflects that change.


Adding multiple fields in node_save() Its possible to add a node using the code below, but how do i add multiple fields?

$node = new StdClass();//creating a bare node
$node->type = 'answer';//giving it type
$node->status = 1;//give it a published staus
$node->title = "Step up to the FLava";//gives title
$node->body = "Body Body body"; //gives body

node_save($node);

Singles custom field, we can use:

$node->field_my_custom_field['und'][0]['value'] = 'my value';

But what if I want to add multiple entries for one field?

Second index after 'und' is used for delta of values. You can make it 1 , 2, 3 etc to add multiple values... Something like below...

$node->field_my_custom_field['und'][0]['value'] = 'my value one';
$node->field_my_custom_field['und'][1]['value'] = 'my value two';
$node->field_my_custom_field['und'][2]['value'] = 'my value three';
$node->field_my_custom_field['und'][3]['value'] = 'my value four';


How to get translated field using Twig tweak? I use twig tweak for rendering username on site this way:

username.html.twig:

{#
/**
 * @file
 * Theme override for displaying a username.
 *
 * Available variables:
 * - account: The full account information for the user.
 * - uid: The user ID, or zero if not a user. As used in anonymous comments.
 * - name: The user's name, sanitized, and optionally truncated.
 * - name_raw: The user's name, un-truncated.
 * - truncated: Whether the user's name was truncated.
 * - extra: Additional text to append to the user's name, sanitized.
 * - profile_access: Whether the current user has permission to access this
     users profile page.
 * - link_path: The path or URL of the user's profile page, home page,
 *   or other desired page to link to for more information about the user.
 * - homepage: (optional) The home page of the account, only set for non users.
 * - link_options: Options to set on the \Drupal\Core\Url object if linking the
 *   user's name to the user's page.
 * - attributes: HTML attributes for the containing element.
 *
 * @see template_preprocess_username()
 */
#}
{% if link_path -%}
  {{ drupal_field('field_name', 'user', uid) }}{{ extra }}
{%- else -%}
  {{ drupal_field('field_name', 'user', uid) }}{{ extra }}
{%- endif -%}

But this doesn't work with translation. How to get translated field?

4k4 answer this way:

{{ drupal_field('field_name', 'user', uid, user.langcode.value) }}

But I don't need language from session/url, not from user settings

Try the language parameter:

{{ drupal_field('field_name', 'user', uid, user.langcode.value) }}

This was added to drupal_field() in this issue Support drupal_field translatability.

For this to work the user entity needs to be available in your template.


Escaping special characters in custom submit handler redirect URL? My submit handler contains a redirect to a URL formatted thus:

mysite.com/node/123/edit?step=step_2

and my problem is that it's appearing in the browser bar as:

mysite.com/node/123/edit%3Fstep%3Dstep=step_2

which messes up my redirect.

How do I escape the characters "=" and "?" for use in a URL for redirection from a custom submit handler?

If you use an array as the value for $form_state['redirect'], it will eventually be passed to url(). So you can use the same options as for that function to build up a structured query string:

$path = 'node/' . $nid . '/edit';
$query = array('step' => 'step_2');
$form_state['redirect'] = array($path, array('query' => $query));

There's more explanation in the documentation for the drupal_redirect_form() function.


How to add a node to a taxonomy term? I have searched long and hard for this, but I cannot figure out how to add a node to a taxonomy term.

I have taxonomy (Region) with term (North America) and I am trying to add the node (USA) to North America.

Could someone please teach me how this can be done? I just cannot find it anywhere on Drupal 7 Admin controls.

You need to add a 'Term reference' field on the relevant content type:

Go to http://mysite.com/admin/structure/types/manage/page/fields (where 'page' is the name of your content type).
Add a new field, using 'Term reference' as the field type.
On the next page, choose the vocabulary you want the content type to reference.
On the page after that, choose specific settings for the field.

Next time you go to add/edit a node of that content type, you'll be able to choose terms from your selected vocabulary.


add pre-registered links to user menu via hook_menu One step before being forced to using internationalization (i18n) module!

I'am trying to add translatable Register and Login links to secondary menu via hook_menu in way which user module dose for Account and Logout links via user_menu():

// user module:

function user_menu(){
  ...
  $items['user/logout'] = array(
    'title' => 'Log out',
    'access callback' => 'user_is_logged_in',
    'page callback' => 'user_logout',
    'weight' => 10,
    'menu_name' => 'user-menu',
    'file' => 'user.pages.inc',
  );
  ...
}

but as this two links (user/register and user/login) re pre-defined via user_menu(), I whould like to know how can I add my links to primary menu?

so simplified question is:

how can I add pre-registered links to menu via hook_menu() ?

You can use hook_menu_alter() to override properties for existing paths:

function MYMODULE_menu_alter(&$items) {
  $items['user/logout']['menu_name'] = 'primary-links';
}


How to use the Achievements module? I want to create some kind of challenges for users. And when it is fulfilled the user is able to unlock a new level and gain some kind of victory say in terms of a new theme, i.e, after completion of that challenge the user is awarded a new theme which the user can set as their theme.

I want to do this using the Achievements module. However there seems to be almost no documentation available, so I'm looking for ideas on how to proceed.

Note: I have basic understanding of php and have created few basic modules as described in drupal.org.

The comments and example code in the documentation: achievements.api.php show how to create a new achievement.

There is no administration interface, you must create a module and use the hooks described in the above link to create new achievements.


Have Leaflet marker popup open on page load Has anyone used Leaflet to display a single location, while making the "popup" open when the map is loaded?  This is really easy to do in Leaflet, but the module's JS is a little hard to decipher.  Any help would be appreciated.

The leaflet module fires an event after a map is created, called "leaflet.map".
You should be able to listen for this event and get the map object like this:

(function ($) {
  Drupal.behaviors.openMarker = {
    attach:function (context, settings) {
      $(document, context).on('leaflet.map', function(event, map){
        // console.log(map);
        // logic to open marker goes here
      })
    }
  };
})(jQuery);

Leaflet module also fires an event called 'leaflet.feature'.

NOTE: the above code is untested


Status report for Commerce Kickstart 7.x-2.41 reads Not supported Just upgraded from commerce_kickstart-7.x-2.38 to commerce_kickstart-7.x-2.41. When I view the status report it shows "Unsupported release" for module and theme update status. When I click on the list, it shows the following message:

  Distro Update Manager: libraries version 7.x-2.2 does not match .make
  file version 7.x-2.3 from commerce_kickstart.

Any ideas how to fix this?

This is a common problem. The best solution, but not necessarily the easiest, is to use drush. You can find the instructions at Installing & upgrading Drupal Commerce under the "Updating your files" section.

tl;dr

Here’s the workflow. Be sure to backup your files and database first!

Move your /sites folder, .htaccess and all non Drupal stuff out of your docroot
Delete your old commerce_kickstart installation. Your docroot folder should be empty.
Run drush dl commerce_kickstart. It will fetch and intall the latest commerce_kickstart version
Move back your /sites folder, .htaccess from above
Run drush updatedb -y


Should I be concerned about enabling too many modules at the same time? I am using features to manage deployment.  I have a controller feature which lists 8 other features I have created as dependencies.  These features in turn together list over 100 modules as dependencies.  Is it ok to simply turn on the controller module and allow it to automatically enable all the other modules, or does Drupal have trouble doing this?

So far when I enable them all at once it seems fine, but I'm just asking to make sure I don't have problems down the line.

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


HTML Mail not working with custom module I have installed HTML Mail and Mail System modules and set them up with a template.. this is working fine when I send the test email it uses the template.

However when I send mail from my function, it doesn't use the template.. it was my understanding this should happen automatically, but how can I force it?

I have a mymodule_mail function that just does a switch on $key and fills $message based on various types of messages the system sends.

I call it using drupal_mail().. and that's working, but not loading the template file.

So I added this line above where the mail is being dispatched:

mailsystem_set(array(mailsystem_default_id() => 'HTMLMailSystem'));
drupal_mail('mymodule', 'notification', $email, user_preferred_language($user), $params);

Then I tried moving the mailsystem_set to inside the mymodule_mail function.

and it still isn't working. What am I missing??

drupal_mail has a module parameter that I'm using to call my own module that processes the different templates based on database calls etc. I'm wondering if I have to use that to call HTMLMailSystem, but I need to call my own first. (and still thought using the HTMLMailSystem would be the default)

The configuration can be done through the Mail System UI.  Here is how I send HTML messages with a custom module without a template.

First, install HTML Mail and Mail System as you already have.

Next, create your module and implement hook_mail() and add an identifier (key) to use when sending.

function hook_mail($key, &$message, $params) {
  switch ($key) {
    case 'MODULE_unique_sending_key':
      $message['Reply-To'] = $params['Reply-To'];
      $message['subject'] = $params['subject'];
      $message['body'] = $params['body'];
      $message['headers']['Reply-To'] = $params['Reply-To'];
      break;
    }
}

Next, implement drupal_mail().

$key = 'MODULE_unique_sending_key';
$message = drupal_mail('MODULE', $key, $to, LANGUAGE_NONE, $params, $from);

Lastly, you will need to tell Drupal to use the HTMLMailSystem to send when using the 'MODULE_unique_sending_key' key.

To do this, go to admin/config/system/mailsystem and go to 'New Setting.'

Under module, choose your custom module.

Under Key, enter your unique message identifier you used in drupal_mail().

Now, while still on the admin/config/system/mailsystem page look under 'MAIL SYSTEM SETTINGS' look for the Module+Key combination you just created.

From here, you will need to select the HTMLMailSystem as your sending class.  Save and test your module.  HTML mail should now be working without using a template.


How can I display an element only if any value has been selected from an entity select field? I have a field on a webform (Drupal 8) that should be displayed only when a user has selected one or more options from an entity select field regardless which options are selected.
The available conditional logic options in webform do not seem to include such state. I have searched online and looked through the example_element_states.yml in the webform module and all select related examples specify a particular option value as the conditional logic.
Has anyone encountered and resolved such issue?

Got it! You need to check for a value greater than 0.
user:
  '#type': webform_entity_select
  '#title': User
  '#multiple': true
  '#target_type': user
  '#selection_handler': 'default:user'
  '#selection_settings':
    include_anonymous: false
    filter:
      type: _none
text:
  '#type': textfield
  '#title': Text
  '#states':
    visible:
      ':input[name="user[]"]':
        value:
          greater: '0'

I guess in PHP that must be:
$form['text']['#states'] = [
  'visible' => [
    ':input[name="user[]"]' => [
      'value' => [
        'greater' => "0",
      ]
    ]
  ]
];


Is there an easier way to print taxonomies in the tpl? I get this working code, but it should be a "shorter" way! After a painful day and a half I get this code, that prints out in my node.tpl.php the taxonomy terms associated to that particular node that the user is viewing.

It works just fine. As it is quite long I´ll just put the whole thing inside a module and into a variable, to just print that.

The thing is that it should get an easier, better way to do this!
Any ideas?

<?php
$vid = 11; //vocabulary id
$nid = $node->nid; //it looks for the current loaded node
$query = "SELECT tid, name
FROM (
SELECT td.tid AS tid, name
FROM taxonomy_term_data AS td
JOIN taxonomy_index AS tn
  ON td.tid = tn.tid
JOIN node AS n
  ON n.nid = tn.nid
WHERE td.vid = ". $vid ."
  AND n.status = 1
  AND n.nid = ".$nid."
GROUP BY td.tid
) AS t
ORDER BY name ASC";
$result = db_query($query);
foreach($result as $term) {
      echo l($term->name, "taxonomy/term/$term->tid") . ', ';
}
 ?>

UPDATE:

This is devel output:
(I´ve used (dpm($node);) because it let me print the result here without losing the indentation)

(object) array(
  'vid' => '5178',
  'uid' => '1',
  'title' => 'PROYECTO',
  'log' => '',
  'status' => '1',
  'comment' => '2',
  'promote' => '0',
  'sticky' => '0',
  'nid' => '155',
  'type' => 'jornadas',
  'language' => 'und',
  'created' => '1095048000',
  'changed' => '1360589684',
  'tnid' => '0',
  'translate' => '0',
  'revision_timestamp' => '1360589684',
  'revision_uid' => '1',
  'taxonomy_vocabulary_4' => array(),
  'taxonomy_vocabulary_6' => array(
    'und' => array(
      array(
        'tid' => '33',
        'taxonomy_term' => (object) array(
            'tid' => '33',
            'vid' => '6',
            'name' => 'Jornadas Gratuitas',
            'description' => '',
            'format' => NULL,
            'weight' => '0',
            'vocabulary_machine_name' => 'vocabulary_6',
          ),
      ),
    ),
  ),
  'taxonomy_vocabulary_7' => array(
    'und' => array(
      array(
        'tid' => '40',
        'taxonomy_term' => (object) array(
            'tid' => '40',
            'vid' => '7',
            'name' => 'Para PH',
            'description' => '',
            'format' => NULL,
            'weight' => '-10',
            'vocabulary_machine_name' => 'vocabulary_7',
          ),
      ),
    ),
  ),
  'taxonomy_vocabulary_11' => array(
    'und' => array(
      array(
        'tid' => '262',
        'taxonomy_term' => (object) array(
            'tid' => '262',
            'vid' => '11',
            'name' => 'colegios',
            'description' => '',
            'format' => NULL,
            'weight' => '0',
            'vocabulary_machine_name' => 'vocabulary_11',
          ),
      ),
      array(
        'tid' => '543',
        'taxonomy_term' => (object) array(
            'tid' => '543',
            'vid' => '11',
            'name' => 'derecho',
            'description' => '',
            'format' => NULL,
            'weight' => '0',
            'vocabulary_machine_name' => 'vocabulary_11',
          ),
      ),
    ),
  ),
  'body' => array(
    'und' => array(
      array(
        'value' => "

Few things here:

Your SQL is open to injection
You're running a query that has already been run, and for which data has already been returned by the core field system. Drupal already runs way too many queries in a page load, adding another unnecessary one should be avoided wherever possible.
Your code should be in a template preprocess function (or module file as you've mentioned). But that's not because of the length of the code. It's because you should maintain a good separation of logic and display.
Drupal has already prepared the display of the field for you, so it would be preferable to use that instead of building up from scratch again.

With those in mind, try simply adding:

<?php echo render($content['field_name_of_term_ref_field']); ?>

in place of your code.

To control how those field items come out (e.g. as links), navigate to admin/structure/types/manage/TYPE/display, and choose appropriate settings for the display widget.


What is better for performance: Many entity types with one bundle or one entity type with many bundles I am using the ECK module to build custom entities.
When using custom entities, the decision must always be made: shall I create a number of entity types or shall I create one entity type with a number of bundles.

From a usability perspective, the latter is obvious since, just as the node system, all entity types can easily be connected in views. It gets harder when different entity types must be used in views.

Apart from that, I assume that there must be a benefit from using multiple entity types. It has something to do with memory that drupal carries around, but it is not clear to me what exactly makes a difference.

I am aware of the benefit of using entity properties instead of fields. However, most of my entities use fields that cannot be replaced by a property.

So the question is: should I in general aim for using more entity types (each of which automatically create one bundle) or should I not worry about performance impact and create all bundles under one (generic) entity type.

This might not be the answer you want as it does not cover performance, but I think that you should choose what makes sense.

The Drupal entities system is about 'families of things'. Think of it as Classes in object oriented programming. An entity is a base class and a bundle is a sub-class that has access to the properties of its parent.

If all the types of entities have no shared fields/properties, create them as different entities. If they share properties, create them as bundles and put the shared properties in the entity. (Or use a combination of entities and bundles if it makes sense.)

But you can use other comparisons too. If you for instance have multiple types of documents (invoices, orders, notes, etc.) that all have different data, it could still make sense to make them as bundles of a 'document' entity.

With respect to memory, I think that ECK creates all entities as a type of EckEntity and then performs some magic to label it differently (please correct me if I am wrong). So you should not need to worry about loading of different classes, it is just the ECK classes.


How to translate a database query with a subquery to a db_select statement? Assume any variable that doesn't have a definition in the sample code is defined elsewhere. I need to get the results of the following query:

select type, eid, vid, language, keyword, custom_value from (select * from custom_keywords_entity_values where language = 'en' order by eid asc, vid desc) as ckev group by keyword;

However, I'm not entirely sure how to translate this into a query that leverages the Database API.

Fatal error: Unsupported operand types in /Users/lpeabody/Sites/jandj/docroot/includes/database/query.inc on line 1809

This is my working structure right now:

$subquery = db_select('custom_keywords_entity_values', 'a');
$subquery->fields('a')
  ->where('language', $language)
  ->orderBy('eid')
  ->orderBy('vid', 'DESC');

$query = db_select($subquery, 'ev');
$query->fields('ev')
  ->groupBy('keyword')
  ->execute();

$keywords = $query->fetchAllAssoc('keyword', PDO::FETCH_ASSOC);

I feel like that's the most literal translation, but I'm probably missing something since I'm getting this sweet error:

Fatal error: Unsupported operand types in /Users/lpeabody/Sites/jandj/docroot/includes/database/query.inc on line 1809

Let me know if there's any other information you need me to provide you.

SelectQuery::where() takes a string (not an object).

You probably meant to use SelectQuery::condition():

$subquery->fields('a')
  ->condition('language', $language)
  ->orderBy('eid')
  ->orderBy('vid', 'DESC');

Your execution is slightly off too; at the moment you're discarding the results of the execution, and instead invoking fetchAllAssoc() on the wrong type of object.

What you need is

$keywords = $query->fields('ev')
  ->groupBy('keyword')
  ->execute()
  ->fetchAllAssoc('keyword', PDO::FETCH_ASSOC);

or

$result = $query->fields('ev')->groupBy('keyword')->execute();
$keywords = $result->fetchAllAssoc('keyword', PDO::FETCH_ASSOC);

Or some other derivative of the same logic.

After those changes you should wind up with

SELECT  ev.*
FROM
(SELECT  a.*
FROM
{custom_keywords_entity_values} a
WHERE  (language = 'en')
ORDER BY eid ASC, vid DESC) ev
GROUP BY keyword

Pretty close to your original, and functionality identical.


Problems with accessing private files uploaded via file field in a webform I have a webform with a file field configured to private files. When I'm logged in as a superuser (uid=1) and trying to download the file, I get access denied.

I was trying to debug this, and this is what I noticed.

All private files served by the file_download() function that is called in the system.module. This function validates if the file exists and request the file headers using file_download_headers() function that triggers hook_file_download().

In the webform_file_download() function the module determines whether the file was a webform upload and grant or deny file access based on access to the submission. It validates access permission by calling webform_submission_access(). When I run dpm($account) in this function, I get an anonymous user when I'm trying to access the private file. When I browse recent log messages I have the entry below:

access denied   06/02/2015 - 11:23  system/files/webform/cv-uploads/cv.pdf  Anonymous

When I change the URL to file that doesn't exist, I get this:

page not found  06/02/2015 - 11:26  system/files/webform/cv-uploads/cv.FDP  admin

As you can see for some reasons when the module is trying to get access to the file that does exist, I get access denied and the user is anonymous. When the file doesn't exist, I get page not found and the user is a logged in user.

Any ideas why this happens?

UPDATE

I've added the following code to my index.php but I still get anonymous user when I'm trying to access the file.

define('DRUPAL_ROOT', getcwd());

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

+ global $user;
+ watchdog('user', '<pre>'. print_r($user, TRUE) . '</pre>');

menu_execute_active_handler();

I've copied over the whole site including database and files to my local machine, and I'm not experiencing this issue. There's should be some settings that does this on the live site.

UPDATE 2

I've noticed that on the live site we have a list of disabled functions that I'm not aware of. Maybe it will help somehow.

disable_functions = apache_child_terminate, apache_setenv, define_syslog_variables, escapeshellarg, escapeshellcmd, eval, exec, fp, fput, ftp_connect, ftp_exec, ftp_get, ftp_login, ftp_nb_fput, ftp_put, ftp_raw, ftp_rawlist, highlight_file, ini_alter, ini_get_all, ini_restore, inject_code, mysql_pconnect, passthru, php_uname, phpAds_remoteInfo, phpAds_XmlRpc, phpAds_xmlrpcDecode, phpAds_xmlrpcEncode, popen, posix_getpwuid, posix_kill, posix_mkfifo, posix_setpgid, posix_setsid, posix_setuid, posix_setuid, posix_uname, proc_close, proc_get_status, proc_nice, proc_open, proc_terminate, shell_exec, system, xmlrpc_entity_decode, parse_ini_file,show_source,shell_exec

If you are using private file system every module can prevent you from downloading a file. It comes from file_download_header function:

function file_download_headers($uri) {
  // Let other modules provide headers and control access to the file.
  // module_invoke_all() uses array_merge_recursive() which merges header
  // values into a new array. To avoid that and allow modules to override
  // headers instead, use array_merge() to merge the returned arrays.
  $headers = array();
  foreach (module_implements('file_download') as $module) {
    $function = $module . '_file_download';
    $result = $function($uri);
    if ($result == -1) {
      // Throw away the headers received so far.
      $headers = array();
      break;
    }
    if (isset($result) && is_array($result)) {
      $headers = array_merge($headers, $result);
    }
  }
  return $headers;
}

So basically you should discover which implementation of hook_file_download returns -1. You can do that by printing (or writing into watchdog) value of $function variable inside if ($result == -1) { statement (so you will know that this function is responsible for giving -1 result).

However, there is also other case when you'll get access_denied() - if none implementation of hook_file_download will return file headers.

So try to figure out which function (=> module) prevents you from downloading file, then debug that function and try to deduct why.


Patch tests in issue queues? How does one get a patch tested in core and attached to an issue queue (with the pretty red or green styling)?

Is it automatically done when you attach a patch? Or do you have to have an account to the qa.drupal.org server?

Patches uploaded on issues are automatically tested if they meet the right conditions which include:

not excluded based on name (described in description on upload field)
project has testing active
patch is again d6-8 banch

For core, testing is enabled; if you upload a patch against Drupal 7, for example, it will automatically be tested. For other projects, it can be enabled if you are a maintainer by looking at the "Issue" settings tab, there is a checkbox to enable testing.


Migrating user accounts to Okta I'm trying to migrate users exported from Drupal into Okta using the /api/v1/users API (specifically [creating users with import hash][1]), and am stuck, and desperate for help as I'm late on a project now because I haven't cracked this issue.
FYI

I posted this to both Okta forum: https://devforum.okta.com/t/migrating-users-from-drupal-7-to-okta/13103
and Drupal forum: https://www.drupal.org/forum/support/post-installation/2021-02-27/migrating-users-from-drupal-7-to-okta
I also contacted support@okta.com who weren't able to offer any further advice
And pestered a bunch folk in various places on Slack and Discord.

I think the core issue is that I'm not getting the 'right' value for the hash from the Drupal pass string.
Here's an example of a user:
{
"name" : "m.nick",
"first": "Nick",
"last" : "M",
"mail" : "m.nick@gmail.com",
"pass" : "$S$D9./psEr4CRGa61wFXVVxPA4sdxK4IRWPuWJMbbkOHBQNnIoUwOb",
}
I believe the $S$ means SHA-512 was used by Drupal, the D means 15 rounds of hashing were performed, character 4-12 are the salt and the rest of the string is the hash?
Here's how I get the settings, salt and hash from the Drupal pass:
const hashType = pass.substring(0,3)
const rounds = pass.substring(3,4)
const salt = pass.substring(4,12)
const hash = pass.substring(12)
I'm then calling /api/v1/users?activate=true with
profile: { firstName: first, lastName: last, email: mail, login: username },
credentials: { password: { hash: { algorithm: 'SHA-512', salt: salt, saltOrder: 'PREFIX', value: hash }}}
Which successfully creates the user, but on attempting sign in with the username: m.nick and the password that works on the old system, gets rejected with INVALID_CREDENTIALS.
I've tried:

Switching the saltOrder to POSTFIX
base64 decoding the hash
base64 decoding and encoding the hash
Concat'ing the salt and the hash together
Every combination of the above

Please help, as I don't know what else to try, and I can't find any examples of Drupal user accounts being imported into Okta.
I'd be grateful for any advice you can offer.  I assume that someone has previously migrated users from Drupal, and so I'm missing something.

The number of iterations is wrong. The stored value is the power of 2, encoded using a Base64 alphabet. D means 32768 iterations (215).
The other issue you have is that the hash and salt values are Base64 encoded, but using the same alphabet used by cript() (the POSIX function also part of the BSD Library). The PHP code Drupal uses to encode is the following one. It may be helpful to write the JavaScript code you need.
function _password_base64_encode($input, $count) {
  $output = '';
  $i = 0;
  $itoa64 = _password_itoa64();
  do {
    $value = ord($input[$i++]);
    $output .= $itoa64[$value & 0x3f];
    if ($i < $count) {
      $value |= ord($input[$i]) << 8;
    }
    $output .= $itoa64[$value >> 6 & 0x3f];
    if ($i++ >= $count) {
      break;
    }
    if ($i < $count) {
      $value |= ord($input[$i]) << 16;
    }
    $output .= $itoa64[$value >> 12 & 0x3f];
    if ($i++ >= $count) {
      break;
    }
    $output .= $itoa64[$value >> 18 & 0x3f];
  } while ($i < $count);
  return $output;
}

function _password_itoa64() {
  return './0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
}

The full code used from Drupal 7 to hash passwords is contained in the password.inc file. In particular check the following functions:

_password_itoa64(), the function returning the Base64 alphabet used
_password_base64_encode(), the function to encode in Base64 using that alphabet
_password_generate_salt(), the function that generates the salt
_password_crypt(), the function to hash the password, which calls all the other functions

I cannot say what should be used for saltOrder, since that isn't used from Drupal code and it's specific for the platform to which you are migrating the users.


Is it possible to show password reset email success in user password page? I am completely exhausted trying to find out a solution for this simple problem.

I am intending to put a "Forgot Password" in my Drupal site and wants a confirmation when the form emails the password to the user.

For instance, I go to this link http://www.some.com/user/password for the "Forgot Password" link.

when I enter the username or password, it just doesn't show anything and just redirects to the homepage. I intend to change that and want to show the confirmation that an email has been successfully sent.

Any idea how I can do this?

What I tried

I tried creating a page--user--password.tpl.php but it doesn't allow me to make any changes. I am not sure where the values are coming in the form.

By default, drupal_set_message() is set and displayed on form submission when a new password is emailed. It's possible LoginToboggan is interfering with this but I haven't encountered that in my use of it.

Alternatively, if you cannot resolve the issue, you can use hook_form_alter() to create your own submission handler on the password reset form, and use drupal_set_message() to re-show the message (or any custom message you provide) on the form.

function MYMODULE_password_reset_form_alter(&$form, &$form_state, $form_id) {
  $form['#submit'][] = 'my_custom_handler';
}

function my_custom_handler($form, &$form_state) {
  drupal_set_message('An email has been sent with instructions to reset your password.');

}


Proximity filter without Solr We have a view that displays indexed nodes and we would like to add the ability to filter by proximity to a user-input zip code.

I know this can be achieved with Solr and the Search API Location module (https://www.drupal.org/project/search_api_location) but we are not using Solr.

Is there some other way to implement a proximity search on indexed nodes?

In order to solve this issue, I combined the results of two views.

The Primary View

uses the search index and displays indexed nodes
has the correct search facet exposed filters
can't perform a proximity search (without Solr & Search API Location)

The Secondary View

uses the node content and displays non-indexed nodes
can't use search facets for the exposed filters because the nodes are not indexed
can perform a proximity search with just Geofield, GeoPHP, and GeoCoder (all of which we already had installed)

To create the secondary view, I followed the steps outlined here.

Then I used hook_search_api_views_query_alter() to alter the query for the primary view. In this hook, I retrieve the secondary view, pass in the zip code from the exposed filter in the primary view, and execute the secondary view to get the results. Then I turn those results into an array of nids.

Finally, I add a condition to the views query to filter out all nodes that do not have an nid from that array.

/**
 * Implements hook_search_api_views_query_alter().
 */
function mymodule_search_api_views_query_alter(view &$view, SearchApiViewsQuery &$query) {
  if ($view->name === 'my_primary_view') {

    // Try to get the zip code from the exposed filter.
    $zip_code = NULL;
    if (isset($view->exposed_input['field_geo_latlon'])) {
      $zip_code = $view->exposed_input['field_geo_latlon'];
      unset($view->exposed_raw_input['field_geo_latlon']);
      unset($view->exposed_input['field_geo_latlon']);
      unset($view->exposed_data['field_geo_latlon']);
    }

    // Get the second view, pass in the zip code, get the results.
    $proximity_view = views_get_view('my_secondary_view');
    if (isset($zip_code)) {
      $proximity_view->exposed_input['field_geofield_distance'] = array(
        'distance' => '100',
        'unit' => '3959',
        'origin' => $zip_code,
      );
    }
    $proximity_view->init_display();
    $proximity_view->pre_execute();
    $proximity_view->execute();

    // Turn the results into an array of nids.
    $proximity_nids = array();
    foreach ($proximity_view->result as $proximity_result) {
      $proximity_nids[] = $proximity_result->nid;
    }

    // Add that condition to the view query.
    $view->query->condition('nid', $proximity_nids, 'IN');
  }
}

Note: Initially, the dysfunctional zip code filter from the primary view was filtering out all results when a zip code was entered by a user. I needed to keep this field so that users could still enter their zip code, but I did not want the filter to actually be applied.

To get around this, I edited the settings on the exposed zip code filter in the primary view so that when a zip code is provided, it returns all nodes where the zip code is not empty.

This ensures that entering a zip code into the primary view won't change the result set (technically it will remove results without zip codes, but that's ok) but will still allow us to retrieve the value from the input and pass it to the secondary view for the "real" proximity filter.


Need to disable Auto Preview in views for local development in settings.php Can I add a setting in settings.php to disable Auto Preview in views. I know this can be changed under /views/settings/. But I don't want this configuration added to Git. I only want this change on my local site. Something like this.

$config['system??']['foo']['bar'] = FALSE;

I unchecked 'Automatically update preview on changes' in Views settings and exported the changes. The result is that it updated  'views.settings' Below is part of views.settings.yml

     ui:
      show:
        additional_queries: false
        advanced_column: true
        master_display: true
        performance_statistics: false
        preview_information: true
        sql_query:
          enabled: true
          where: below
        display_embed: false
      always_live_preview: false
      exposed_filter_any_label: old_any

The setting may look something like this.

$config['views.settings']['ui']['always_live_preview'] = FALSE;

This should do it, make sure you clear cache:

$config['views.settings']['ui']['always_live_preview'] = 'false';


views output file alterations I am using d7 and views.

I've created a view tpl file specific to my view using the the file name of: views-view-fields--cameras.tpl.php

<?php

foreach ($fields as $id => $field): ?>
<?php
$output = '';
$output .=  $field->label_html;
$output .= '
';
if($field->label_html == 'camera_brand_star:')
{
$output .= $field->wrapper_prefix;
$output .= '
hello
';
$output .= $field->wrapper_suffix;
}
else if($field->label_html == 'camera_price_star')
{
$output .= $field->wrapper_prefix;
$output .= '
'.$field->content.'
';
$output .= $field->wrapper_suffix;
}
else if($field->label_html == 'brand:')
{
$output .= $field->wrapper_prefix;
$output .= '
'.$field->content.'
';
$output .= $field->wrapper_suffix;
}

else
{
$output .= $field->wrapper_prefix;
//$output .= '
'.$field->content.'
';
$output .= $field->wrapper_suffix;
}
$output .= '
';
echo $output;
//echo $field->label_html;
?>
<?php endforeach; ?>

The if conditions are not working at all as its not printing any content. Only it prints the output of     $output .=  $field->label_html;   What am I doing wrong?

Please provide the markup that's currently produced by this code. The PHP logic looks fine but it's not cleat if $field->label_html has a value that will trigger and of the if statements. As a bare minimum you should be getting:

<table width=100% border=1>
</table>


Can I display video from youtube and file system in the same field? I am using Media (7.x-1.4), Media: YouTube (7.x-2.0-rc4) and MediaElement (7.x-1.2) modules for drupal 7.

I have a video field where you can upload videos or enter a youtube url, thanks to the media module.

The problem is, I cannot display videos from the two sources. If I choose "rendered file" in the "Manage display" settings, the youtube video displays, but the local file is given as a link. If I choose "media element video", then the local video is displayed, but the youtube one will not.

Is there a way that I can display videos from both sources?

Video Embed Field Module:

You need to use Video Embed Field module. This is enabled in filed type in MANAGE FILEDS.If you select a filed to Video Embed and select a widget to Video.
as WELL as MANAGE DISPLAY that  select  format to Video Player. and you add a youtube url to content type that display video format.


why does drupal_get_path() not work in my code? somehow drupal_get_path is not working I'm my module in my function vacancies_manage_test_pager()

drupal_get_path() returns notting ( empty string or NULL or something ) when I DSM(drupal_get_path('module','vacancies_manage')); I get an empty message

module code:

/**
 * Implements hook_permission
 */
function vacancies_manage_permission() {
    return array(
        'manage own vacancies' => array(
            'titel' => t('Manage own vacancies'),
            'description' => t('Allows users use the own vacancies page'),
        ),
    );
}

/**
 * Implements hook_menu
 */
function vacancies_manage_menu(){
  $items = array();

    // Test items
    $items['vacancies_manage'] = array(
      'title' => 'Vacatures beheren',
      'description' => 'Eigen vacatures beheren.',
      'type' => MENU_NORMAL_ITEM,
      'page callback' => 'vacancies_manage_test_pager',
      'access arguments' => array('manage own vacancies'),
    );

    // needed for jQuery / ajax callback
    $items['vacancies_manage/callback'] = array(
      'title' => 'vacatures beheer Callback',
      'type' => MENU_CALLBACK,
      'page callback' => '_vacancies_manage_test_pager_callback',
      'access arguments' => array('manage own vacancies'),
    );

    return $items;
}

function vacancies_manage_test_pager() {
    drupal_add_js(drupal_get_path('module', 'vacanies_manage') . '/jquery.url.js' );
    drupal_add_js(drupal_get_path('module', 'vacanies_manage') . '/vacanies_manage.js' );
    drupal_add_js('initializeTable();', 'inline');

    return ('

');
}

function _vacancies_manage_test_pager_callback() {

    global $user;

    header("Content-type: text/html");
    header("Expires: Wed, 29 Jan 1975 04:15:00 GMT");
    header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
    header("Cache-Control: no-cache, must-revalidate");
    header("Pragma: no-cache");

    // build header for HTML table

    $header = array (
        array('data' => t('Titel')),
        array('data' => t('Aangemaakt op')),
        array('data' => t('Gepubliceerd')),
        //array('data' => t('Dupliceer')),
    );

    // query db for user nodes
    $query = db_select('node','n');
    $query->fields('n', array('nid','title','created','status'));

    if($user->uid !== "1" ) {
        $query->condition('n.uid', $user->uid);
    }

    $results = $query->execute();
    dsm($results);

    // display nodes
    $rows = array();

    foreach($results as $vacancy) {
        $rows[] = array(
            'data' => array(
                $vacancy->title,
                $vacancy->created,
                ($vacancy->status == 1?t('Ja'):t('Nee')),
                //dupliceer
            ),
        );
    }

    //Theme the html table
    $html = theme('table',
        array(
            'header' => $header,
            'rows' => $rows,
            'sticky' => TRUE, // Optional to indicate whether the table headers should be sticky
            'empty' => 'U heeft geen vacatures.', // Optional when no results
        )
    );

    $html .= theme('pager',
        array(
            'tags' => array(),
        )
    );

    die($html);
}

You've spelled vacanies_manage wrong....  (same with your js file, too [and titel in your permissions])


Webform questionnaire with scoring and reports I've created several long/multipage questionnaires with webform and I need to have a scoring/rating at the end with the results gathered in a report for the user (preferable in pdf).
But there are no models available that add a scoring per option and/or per form component.

What would be the preferred way to achieve a score ?
Could this be done with Views or with the webform-conditions? or via webform_validation?

Any recommendation or direction is very appreciated as I'm bit stuck now.

If you want to create charts from the survey results of the Webform module, there are 2 typical/popular alternatives to pick from:

Webform Charts (used in about 400 sites), to display Webform results in a graphical manner using a charting library.
Webform Chart (used in about 220 sites), which integrates with the "Analysis" tab of a Webform (created with the Webform module) to provide charts for each individual component's analytical data.

The Drupal 7 version of both modules, requires the Charts module (dependency).


Create a Rules link to update a field in a submitted webform I have a view which is a list of submitted webforms. I want to add a link using Rules link that, when clicked, updates a field in the submitted webform (specifically, updates a hidden field with the current date).

Is this possible?

Have a look at what's asked for in the feature request "Expose submission data to rules", status is "Needs review". Here is a summary of it:

  Right now, submission data is not exposed to rules except by way of token replacement or custom php actions. This patch exposes submission data in a "first-class" way.

So if submission data are not even exposed yet (in the current version of Rules), then it might not be obvious (if possible at all) to update such data.

Possible alternative

I'd rather try to come up with some kind of alternative for such hidden field to "record the clicking of such link" (also using the Rules Link module). A possible alternative is to use the Message module to create a message like so:

Date = date the link was clicked.
User target = the user who clicked the link.
Message type = something like "Webform processed via Rules link").
message text = whatever you want and possibly using "Replacement tokens" to have any of the available webform tokens available in your rule included in your message text also.

Since messages are entities, you could add any additional fields you may need to complete such custom logging.


Drush installation - setting symlink to /usr/local/bin/drush is a must? Refering to https://www.drupal.org/node/2132447, I would like to install Drush in /usr/slocal/abc directory, and I tried the following steps:

$ cd /usr/slocal/abc
$ wget --quiet -O - http://ftp.drupal.org/files/projects/drush-7.x-5.9.tar.gz
$ tar -zxf drush-7.x-5.9.tar.gz
$ ln -s /usr/slocal/abc/drush/drush /usr/local/bin/drush

Then, I got this error:

  ln: creating symbolic link '/usr/local/bin/drush': Permission denied

I asked my system admin who said that the company policy does not allow to install stuff into /usr/local/bin.

I've searched many installation guides, all of them requires to create a symbolic link '/usr/local/bin/drush' in order to run Drush. Is there any other way I can do it?

This may not answer the question directly, but a preferred and much simpler way to install Drush, is to install it through the Composer.

Installing Composer

See Composer's website for greater detail.

curl -sS https://getcomposer.org/installer | php
# If the above code fails, use this one.
# php -r "readfile('https://getcomposer.org/installer');" | php
sed -i '1i export PATH="$HOME/.composer/vendor/bin:$PATH"' $HOME/.bashrc source $HOME/.bashrc

Installing Drush

See Drush instructions on GitHub for greater detail.

To install Drush 6:

composer global require drush/drush:6.*

Or to install Drush 7:

composer global require drush/drush:dev-master

Update

Per @leekit, he was able to solve his original issue by substituting the symbolic link with export PATH="$PATH:/path/to/drush:/usr/local/bin". For that and other alternatives, refer to step 3 of Install - Manual, on Drush instructions on GitHub.


How can I restore removed menu items? I create a menu "XXXX" move "Create content" and all of it's children to "XXXX" then remove XXXX menu. now I miss "Create content", how can I restore them?

You can execute the following query.

if ($mlid = db_query("SELECT mlid from {menu_links} WHERE link_path = :path AND menu_name NOT LIKE :menu", array(':path' => 'node/add', ':menu' => db_like('shortcut-set-') . '%'))->fetchField()) {
  db_update('menu_links')
    ->fields(array('menu_name' => 'navigation', 'plid' => 0))
    ->condition('mlid', $mlid)
    ->execute();
  db_update('menu_links')
    ->fields(array('menu_name' => 'navigation', 'plid' => $mlid))
    ->condition('link_path', db_like('node/add/') . '%', 'LIKE')
    ->condition('menu_name', db_like('shortcut-set-') . '%', 'NOT LIKE')
    ->execute();
}
else {
  // There isn't any row for node/add.
}

What the code does is the following.

It finds the database row where the link path is node/add, and where the menu name doesn't start with shortcut-set-, which is the menu name used from the Shortcut module for its shortcut sets; as the default shortcut set used from that module contains a link that points to node/add, the code exclude that link. If there are other rows that would point to node/add, you need to edit the first query to exclude them.
For the row found from the first query, it changes the menu name to navigation, and plid (the parent link ID) to 0.
For any row whose link path matches the SQL regular expression node/add/%, it sets plid to the mlid previously found.

In the code I used db_like(), even in this case was not strictly necessary. The purpose of db_like() is escaping any character that for the SQL regular expressions has a specific meaning. Suppose that I would change the code to find any database row whose link path is node/%, where % is the character that is really present in the link path; without db_like(), the query would find any row where the link path starts with node/, which would include more rows than the ones where the link path is node/%.

As the code is using two update queries, it should use transactions. In that way, if the second query would fail, the database would be left in a consistent state, which means that the rows for node/add, and node/add/[content type] will be part of the same menu. If the first query is executed, and the second one fails, you would have node/add that is part of a menu, while any node/add/[content type] link would be part of a different menu (or some of the node/add/[content type] links will be part of a menu, and other node/add/[content type] links will part of another menu).

if ($mlid = db_query("SELECT mlid from {menu_links} WHERE link_path = :path AND menu_name NOT LIKE :menu", array(':path' => 'node/add', ':menu' => db_like('shortcut-set-') . '%'))->fetchField()) {
  $transaction = db_transaction();
  try {
    db_update('menu_links')
      ->fields(array('menu_name' => 'navigation', 'plid' => 0))
      ->condition('mlid', $mlid)
      ->execute();
    db_update('menu_links')
      ->fields(array('menu_name' => 'navigation', 'plid' => $mlid))
      ->condition('link_path', db_like('node/add/') . '%', 'LIKE')
      ->condition('menu_name', db_like('shortcut-set-') . '%', 'NOT LIKE')
      ->execute();
  }
  catch(Exception $e) {
    // One of the queries failed; rollback the database to the previous status.
    $transaction->rollback();
  }
}
else {
  // There isn't any row for node/add.
}

PS: As the only way to find the menu item is too look for its link path, there could be more than one row using that link path. It is important the code excludes those rows that are not the correct one, and that is what my code does when it excludes the rows there the menu name starts with shortcut-set-. Unfortunately, it is not possible to write code that generic enough to work in any condition.


How do I know Honeypot is working on my custom module form? I have a custom module that renders a form. In hook_form_alter() I have added honeypot_add_form_protection($form, $form_state, array('honeypot'));

Though, when I perform 'Inspect Element usnig chrome I cannot see any honeypot fields in the html of the page. So, I'm slightly confused on whether this actually work or not.

Any idera on how to test this or atleast see that the form is protected by the Honeypot module?

You can enable an option Log blocked form submissions on page admin/config/content/honeypot, set Honeypot time limit to, let's say, 30 seconds and try to submit your form faster than 30 seconds. Then check your log (admin/reports/dblog). You will see Honeypot log message if it worked.

And you probably should include some option in array:

  honeypot_add_form_protection($form, $form_state, array('honeypot', 'time_restriction'));

  Note that you can enable or disable either the honeypot field, or the time restriction on the form by including or not including the
  option in the array.
  (https://www.drupal.org/node/1232638)