How do I enable aggregation in the settings? I have the same problem as in Views sorting by number of values in field".  I would really like to try the solution that is given.

How can I enable aggregation in the view settings? I can't find it anywhere.

The following is a screenshot of the view panel. Is there any other name for "aggregation"?

Your view appears to be a search API view, for which "aggregation" is not supported. Which is also why the "Use aggregation" option is not visible (credits: comment to question Clive).

A possible solution (work around?) to make the aggregation option available, is to NOT use the Search API for your view, and instead use a regular content type view (credits: comment to question Alfred Armstrong).

PS: Comments may get deleted, for all sorts of reasons, which is why I included them in this answer ...


Preprocess views view to concat two dates and add variable I've been trying to get a custom format placed upon a date range with particular rules (Explained in code comments) within Drupal 8 views.

What I currently have worked with regard to me being able to get the original two dates and to customize them but what I can't seem to do is pass the result ($display_date_range) forward to the fields view TWIG file (views-view-field--group-travel.html.twig)

What I have so far

/*****************************************************************************
 * VIEWS VIEW PRE-PROCESS
 * @param $variables
 *****************************************************************************/
function cazloyd_preprocess_views_view(&$variables) {
  $view = $variables['view'];
  $id = $view->storage->id();

  // Handle the Group Travel Listing view
  if($id == 'group_travel_listing'){
    foreach ($view->result as $key => $result){
      // Get start date from view
      $date_start = $result->_entity->get('field_start_date')->getValue();

      // Get end date from view
      $date_end = $result->_entity->get('field_end_date')->getValue();

      $months_are_same = (date('n', strtotime($date_start[0]['value']))==date('n', strtotime($date_end[0]['value'])))?TRUE:FALSE;

      if($months_are_same){
        // Month of start and end date are same, show only the day part of the start date
        // e.g. 11 - 23 July 2017
        $formatted_date_start = date('j', strtotime($date_start[0]['value']));
      }else{
        // Event crosses over into new month, therefore show day and month part of start date
        // e.g. 11 July - 5 August 2017
        $formatted_date_start = date('j F', strtotime($date_start[0]['value']));
      }

      $formatted_date_end = date('j F Y', strtotime($date_end[0]['value']));

      // Build final date range
      $display_date_range = $formatted_date_start . ' - ' . $formatted_date_end;

      echo '<pre>';
      print_r($display_date_range);
      echo '</pre>';
    }
  }
}

hook_preprocess_views_view() is used to alter the variables that are passed to a views-view[...].html.twig template file which is for the entire View, not just for the fields. It might make more sense for you to use hook_preprocess_views_view_fields() or hook_preprocess_views_view_field() since you are trying to alter the variables that are used in a views-view-field[...].html.twig template file (specific to the individual field, not the whole view).

See:

https://api.drupal.org/api/views/theme%21theme.inc/function/template_preprocess_views_view_fields/7.x-3.x

https://api.drupal.org/api/views/theme%21theme.inc/function/template_preprocess_views_view_field/7.x-3.x


Role level file access control I have been asked to control access by different groups of users to files uploaded to a website.

This covers both files uploaded as a field, and files uploaded via IMCE and CKEditor.

I have several Roles to handle; Anonymous users, Authenticated Normal User, Authenticated Coordinator. And probably some more later.

There are already Permissions controlling access of users to relevant nodes and forum topics. For example, an anonymous user can only see the public part of the site, the normal user can see some content types and forums and coordinators can see everything a normal users can see as well as some extra forums.

I need files uploaded by authenticated users in the restricted part of the site to 100% not be accessible to anonymous users. And, I need documents uploaded by the coordinators to not be accessible by the normal users.

Currently, normal users can bypass the node and topic permissions to access files if they have the direct link.

How should we approach this?

The first step is using private files, because you can not control access to to public files as Drupal is not involved when they are delivered.

Private files in plain file fields (file and image, not media entity) automatically respect node access and will only be accessible if the user has access to at least one node that is using the file.

As you mention that users can bypass node access, I assume you have node access already implemented and it should then just work


How to work with TypedData? So I was wondering how to utilize this new addition to Drupal.
For example, should I use TypedData to set default value, description or required attributes in (entity)forms?

What is the usage of computed(), setReadOnly(), setTranslatable(), is/setQueryable(),.. ?

Yes, this is a very broad question, so I can only offer a broad answer.

Typed Data is only really interesting for you if you are a module like Rules, a context/token system or something like that, that wants to work with any possible data structure on any level, with generic code. Like displaying that famous rules data selector based on getting an arbitrary object (or actually a definition object about that object that you will get at runtime) and all you know about it is that it is typed data.

For most other cases, like when you know that you are working with an entity, or a specific field, you want to work with more context-specific API's, if available.

You specifically mention entity forms, note that work there is still going on, but the idea is that editing fields should work the same for base fields as it does already with configurable fields, with widgets, whose configuration you will set in your baseFieldDefinitions() method. Support for that very recently landed, see the node title definition in Node::baseFieldDefinitions(). There is no change notice yet but the relevant issue is #2144919 Allow widgets and formatters for base fields to be configured in Field UI.


How can I enable my community to flag (report) bad content on my site? I got a dev site with Drupal 7.

I want to give my visitors the ability to flag (report) content that is abusive or problematic.
I tried using the Flag module together with the Flag Abuse module.

The Flag Abuse module can reset (remove) the flag/reports only one time; after that, it removes the Flag/Report and the Reset Button (for administrators). That is very bad, and totally not practical. Imagine a bad user creates 2 accounts, adds content with account "A," and reports that content with account "B"; you as administrator will check the content, see whats wrong, fix it and press the reset button. After that, the report and reset buttons are gone. So the bad user can edit his content and nobody can report it to administrators. So that module is pretty useless.

Do you know a similar module to solve this problem? Or do you know how I can fix the reset button? I have managed to do the reset button appear multiple times, but I get a lot of errors: The button only works every 3rd time that is pressed.

I made my own solution. Using Flags, Rules and Views.

I have also uploaded a video Tutorial on youtube explaining how to flag content and create a "Reset" action on content edition.

http://www.youtube.com/watch?v=b5xieuVf01E&list=PL1A89955CCEB73A09&feature=plpp


D6 -> D8 : Migrate only taxonomy terms from a specific vocabulary When doing a D6->8 migration, my taxonomy term migration template imports all the taxonomy terms found in the source D6 site into my specified D8 taxonomy.

How do I filter only the terms that belong to a specific vocabulary? For a D7 migration all I needed was:-

source:
  plugin: d7_taxonomy_term
  bundle: tags

Bundles are not part of D6 so is there a way to do this in the yml file? Like ...

source:
  plugin: d6_taxonomy_term
  ???

You could create a plugin, where you can use sql to query what you need.

For example:

<?php

namespace Drupal\custom_migration\Plugin\migrate\source;

use Drupal\migrate\Plugin\migrate\source\SqlBase;

/**
 * Minimalistic example for a SqlBase source plugin.
 *
 * @MigrateSource(
 *   id = "custom_vocab_plugin",
 *   source_module = "custom_module",
 * )
 */
class CustomVocabulary extends SqlBase {

  /**
   * {@inheritdoc}
   */
  public function query() {
    $query = $this->select('vocabulary', 'v')
      ->fields('v', [
        [....] // YOUR SQL HERE
      ]);
    return $query;
  }

  /**
   * {@inheritdoc}
   */
  public function fields() {
    return [
      [....]

    ];
  }

  /**
   * {@inheritdoc}
   */
  public function getIds() {
    $ids['vid']['type'] = 'integer';
    return $ids;
  }

}

Then you just need to use that plugin in your D6 migration:

source:
  plugin: custom_vocab_plugin


Globals using Drupal with views I have a module in Drupal for getting the url extention via $full_url = $GLOBALS['base_url'];
Now, is it possible to make the full_url global so I can access it in the views module?

When I make a block using views I'm only getting 3 Global option:

Global: Custom text
Global: Math expression
Global: View result counter
here I want my full_url variable

Views usage of the term "Global" is unrelated to PHP Globals. It means that is it globally accessible to all Views regardless of base type (node, user, taxonomy term).

If you find the need to use PHP in your Views, then you should either look into writing a custom Views handler, or try the Views PHP module.


jQuery wrapper function when using Drupal behaviours I have been trying unsuccessfully to add Drupal behaviors to an existing and workding JS script file that is wrapped in :

jQuery(document).ready(function($){
  // some JS here
  Drupal.behaviors.ios = {
    attach: function (context, settings) {

        // Code to be run on page load, and
        // on ajax load added here

    }
  };
});

I cannot get my behaviours to work.

However I have changed the wrapper to :

(function($){
  // some JS here
  Drupal.behaviors.ios = {
    attach: function (context, settings) {

        // Code to be run on page load, and
        // on ajax load added here

    }
  };
})(jQuery);

and now the behaviours work.

What is the difference between the wrappers and can I expect the existing Javascript to continue functioning if I make this change ?

Drupal attaches behaviours on DOM ready - by waiting until the DOM is ready yourself to actually inform Drupal of your custom behaviour, it's too late (unless you call Drupal.attachBehaviors manually afterwards, which would be less than efficient).

Your 2nd example is both logically correct, and the recommended way to use behaviours with jquery in Drupal 7.

Unless you have a very good reason not to, always using that approach would be a good idea.


Change sort order of SOURCE STRING list at User interface translation page to alphabetical instead of date created At the User interface translation page (/admin/config/regional/translate) the SOURCE STRING list seems to be ordered by creation date/time (it is for strings I add). Is there a "good" (non-hackish) way to change the order to alphabetical? I haven't found anything in the interface.

For those who wonder why I want this, I use interface translation in an unconventional way. Instead of putting literals like t("Choose your options") in my code, I put in a key like t('rsc-string-choose-options') [rsc is the name of my custom module]. Then as the translation, I put in "Choose your options". This allows me to use "keys" for all strings (literals, messages, titles, email body text, etc.). It's easy to look up my keys because they all begin with 'rsc-' followed by 'string', 'message', 'email', etc. depending on usage. Doing this provide a nice interface for editors to go in and change the text of the strings, since they can look them up either by translation or by key. I also wrote a nice utility that allows me to add, remove, rename, and test keys (i.e. translation strings). It's working very well, but it would make review much easier if the source strings were alphabetical.

It depends on what you want to call "good" & "non-hackish".

If you're looking for a simple configuration change, then no; there's no configuration change that you can make to modify the translation strings order.

If non-hackish includes using Drupal APIs to override routes & services in a custom module, then yes.

You can use a custom module to override the locale.translate_page route with your own custom controller & form class that will do the same work of TranslateEditForm::buildForm(), but modify the behavior of
::translateFilterLoadStrings() so it produces a different ordered list of translation strings.

The string order is the result of a method in the locale.storage service that performs the dynamic query (see StringDatabaseStorage::dbStringSelect() where the query is built). You'll probably have to override that service in some manner to provide the same structured query object, but with an orderBy method added to execute the same query but with the sorted order you're looking for.


Quick Uninstall/Reinstall of a Custom Module I'm working on creating a module and I'm slowly getting familiar with the Field API and what all settings work on various fields and what don't. While I'm doing this, it seems that the only way to update a custom content type is to disable the module, uninstall it, then re-enable it.

Is there an easy way to do this? Right now, it's a somewhat laborious process that requires a handful of clicks to do the same thing over and over. I'm looking for a script or module to handling this very quickly with (ideally) a single click.

Solution 1. Devel + Drush:

You can use devel drush command for module re-installation with all the module dependencies:

drush devel-reinstall modulename

There is also alias for this command

drush dre modulename

Solution 2. Drush:

This is something that I would typically use drush for

drush pm-disable mymodule
drush pm-uninstall mymodule
drush pm-enable mymodule

You could also use it to define your own custom commands to combine these into a single command.


How to make language choice Required for Taxonomy term Is there any way to make the language choice required for taxonomy term.

I'm pretty sure there is a way to perform this.

Otherwise, how can I at least set a default language choice for my taxonomy.
By exemple, I would like to make English as default language. That's mean when the user will create a term the first time, the language choice will be english.

Thanks a lot

Write a custom module and use the following code

function MYMODULE_form_alter(&$form, &$form_state, $form_id){
  if($form_id=='taxonomy_form_term'){
     $form['#after_build'][] = 'MYMODULE_after_build';
  }
}

function MYMODULE_after_build($form, &$form_state) {
   if($form['language']['#value']=='und'){
     $form['language']['#default_value']='en';
     $form['language']['#value']='en';
   }
   return $form;

}

NOTE: In your custom_module.info file use this dependencies[] = i18n_taxonomy, so that your module can only be enabled if internationalization is enabled


Proper use of hook_menu_breadcrumb_alter() I have a situation where I need to mess with a breadcrumb on a page and insert some items in the middle.  In my instance drupal_set_breadcrumb() can't be used, so I need to implement a hook_menu_breadcrumb_alter().  I am a little confused about proper usage with this, though, and am not terribly familiar with the guts of how the menu module works.

Is there a proper method for building elements that go into the $active_trail array, eg

$foo = array(
  'title' => $node->title,
  'href' => 'node/' . $node->nid,
  'link_path' => '',
  'localized_options' => array(),
  'type' => 0,
);

title and href are easy enough, but I don't quite get how the other play into this particular context.  It is easy enough to figure this out from what is there, but I would like to do "the right thing".

Is there a proper method (or best practice) for testing whether $item is a node and to load it?  Again, I can dpm($item), poke around, and get what I need.

I have what I need working, but it is messy and would like to fix it for the long term.

The properties for each trail item that are documented are the following:

title: Title of the item
href: Drupal path of the item
localized_options: Options for passing into the l() function
type: A menu type constant, such as MENU_DEFAULT_LOCAL_TASK, or 0 to indicate it's not really in the menu (used for the home page item)

The code that builds the breadcrumbs is the following.

foreach ($active_trail as $parent) {
  $breadcrumb[] = l($parent['title'], $parent['href'], $parent['localized_options']);
}

The other values (type and link_path) are not used to create the breadcrumbs, but they could be used from other modules that alter the breadcrumbs. Using the default values used from menu_set_active_trail() for those properties probably causes less compatibility problems with other modules.

$trail[] = array(
  'title' => t('Home'),
  'href' => '<front>',
  'link_path' => '',
  'localized_options' => array(),
  'type' => 0,
);

  Is there a proper method (or best practice) for testing whether $item is a node and to load it?

The $item argument hook_menu_breadcrumb_alter() gets is the value returned from menu_get_item(). If you want to check it is for a node, you can use the following code.

if (isset($item['load_functions'][2]) && !empty($item['map'][3]) && $item['load_functions'][4] == 'node_load') {
  $node = $router_item['map'][5];
}
else {
  // The menu item is not for a node.
}

That is the code executed from menu_get_object() when it is called with its default arguments.

References

menu_get_active_breadcrumb()
menu_set_active_trail()


Module code within different files I wrote my own module that builds 4 forms with many features. Everything work great, but now i have reached 1000 lines of code and it's starting to get complicated to have all the forms on the same file.
I would like to make some .inc files, maybe one for each form (the biggest form has 9 functions related to it) to make more order to my code and make it easier to maintain it, but I have no clue on how to split the code in a way it will work.
How can i solve my issue?

You can split your code in as many files as you want. For every file except the *. module file add a line to your *.info file:

files[] = inc/my_form_1.inc

You can also place functionality into seperate files by specifying the path to the files in hook_menu. Have a lookt at the file property in the hook_menu description.


Reasons for subsequent Broken/missing handler in Views? In the process of upgrading Drupal 6.x to 7.x I'm facing a problem that makes all my views show nothing relevant. (I believe the problem is here but I'm not sure, I don't know. That's why I'm asking):

After using the migrate field from CCK module in Drupal 7.x most of my views end up with Broken/missing handler whether it is in Field, Filters Criteria or Relationships.

On the other side, when using the migrate field module, most of the fields have a message similar to this attached with them. (The field names change.)

  Missing formatter: The 'hidden' formatter used in 3 view modes for the field_phone field is not available, these displays will be reset to the default formatter.

Or I get this message.

  Changed field type: The 'field_source_file' field type will be changed from 'filefield' to 'file'.

Or I get this message one too.

  The field uses the view list_of_project_for_captain_log to determine referenceable nodes. You will need to manually edit the view and add a display of type 'References'.

Is this the reason why most the views have a Broken/missing handler than makes them not work properly? If yes, what can I do, if not what else could be the reason for such problems and what should be done?

Please follow the following guides:

Upgrading Drupal core
Migrating D6 Content Construction Kit (CCK) to D7 Fields
Migrating image fields

Also:

Make sure that you've enabled all the field modules such as image and views related
Changed field type: The 'field_source_file' field type
will be changed from 'filefield' to 'file' is just information; it's nothing to worry about
To fix the Broken/missing handler message, you have to identify the right modules which provide these handlers and enable them


hook_entity_base_field_info() vs. creating a new entity I need to create a fairly extensive user/account management section of a site.

I'm wondering whether to just extend the existing user entity, or whether I should create a completely new entity to house all the extra stuff I need...

Are there any pro's/con's I should bear in mind when making this decision?

There isn't a 'right' or 'wrong' method of this. It really depends on your business requirements.

Are the fields you are thinking you need related to the user object? If they are, then I would use the User object. However, that shouldn't involve extending it, you can just add fields to it.

Without more information it's hard to be more specific.


Site performance , cache not working properly I am using the Performance Logging Module. Above screenshot, one strange thing I noticed that Insert Cache_bootstrap on every page. When you go to any page (both admin theme and frontend theme) Insert cache and then delete cache is running. It  means that cache is set and destroyed in each page and actually no cache is occurring. How can I further elaborate it? To diagnose that issue because currently I am working on performance of the site.

I am also using New Relic for performance check. It also shows that database load is high.

and my.cnf information.

Slide #85 from my performance presentation talks about max packet size in MySQL, you need to increase that value; SET GLOBAL max_allowed_packet=33554432; or change it inside of the configuration file https://dev.mysql.com/doc/refman/5.7/en/packet-too-large.html


Why do taxonomy_get_tree() & entity_load('taxonomy_term', etc..) give different counts? I'm finding that I am missing some terms in a vocabulary when I try to get them all with taxonomy_get_tree($vid).

If I verify the count of terms in the vocabulary by getting the count of entity_load('taxonomy_term', FALSE, array('vid' => $vid)) when I compare the counts they are different.

Can anyone tell me why the counts would be different?

I was hoping to use taxonomy_get_tree() as it's much faster for the number of terms I have (> 10k) but it's useless if it's not going to deliver all terms.

Thanks for any info on this.

After running some mysql queries on the taxonomy_term_data table it appears that the difference in counts is caused by differences in the terms language property.

When I count the terms in the taxonomy_term_data with the language set as 'und' it matches the total given by taxonomy_get_tree($vid)

When I count all terms in the taxonomy_term_data table regardless of language the total matches the the count given by entity_load('taxonomy_term', FALSE, array('vid' => $vid))

So if you only need terms in your current language go with taxonomy_get_tree($vid) otherwise you'll need entity_load().


Commerce partial payment : pay deposit at checkout and full settlement later In a Travel Booking website, how can I configure checkout so that customers pay only a n% deposit of the order total at checkout (off-site payment ATOS solution) ?

If the order is created :

less than 30 days before departure, customer pay 100% of order total at checkout.
between 30 and 90 days before, they pay 30% at checkout.
more than 90 days before, they pay 10% at checkout.

Full settlement must be paid before travel departure (reminder emails)...

There are few contrib modules about deposit or partial payment :

I had a look at Commerce deposit sandbox but it seems to be a per product solution, while I need a global cart approach.
I began to hack Commerce Partial Payment for my own need. The module alters checkout_form_alter and provides a textfield where the customer can input a deposit value just before payment, so I pre-calculated deposit amount as per my rules above, filled the field with it, and hide it.

/**
 * Implements hook_form_BASE_FORM_ID_alter().
 *
 * Alters whichever commerce checkout page includes the commerce_payment
 * checkout pane and adds the amount element to the payment details.
 */
function commerce_partial_payment_form_commerce_checkout_form_alter(&$form, &$form_state, $form_id) {

  $panes = commerce_checkout_panes(array('pane_id' => 'commerce_payment'));
  $checkout_page = $panes['commerce_payment']['page'];
  if ($form_id != "commerce_checkout_form_$checkout_page" || !commerce_partial_payment_access($form_state['order'])) {
    return;
  }

  //setting up my own deposit value
  $deposit = vts_commerce_deposit();

  // If a values has already been set then use it as the value for the amount.
  // Otherwise, default it to the balance of the order.
  $default = NULL;

  if ($deposit > 0) {
     $default = $deposit ;
  }
  elseif (isset($form_state['values']['commerce_payment']['payment_details']['amount'])) {
    $default = $form_state['values']['commerce_payment']['payment_details']['amount'];
  }
  else {
    $balance = commerce_payment_order_balance($form_state['order']);
    $default = commerce_currency_amount_to_decimal($balance['amount'], $balance['currency_code']);
  }

  // Add the amount to the payment details form.
  $form['commerce_payment']['payment_details']['amount'] = array(
    '#type' => 'hidden',
    //'#title' => t('Amount'),
    '#weight' => -10,
    '#required' => TRUE,
    '#default_value' => $default,
  );
}

But I got stuck there because that value,  passed to $form['commerce_payment']['payment_details']['amount'],  is not the one sent to the remote payment server (so that AFAIK, this module can't work)...

I also tried to set any other parts of checkout_form_alter ( $form and $form_state) where the order amount was repeated with $deposit, this NEVER changes the value set for payment at next step...

Question(s)

Using the above solution, at what point of checkout / which form can I alter the amount to be paid, replacing order total by deposit value ?

Indeed, I couldn't find how to separate the order total from the amount to pay... with correct data along the process : order total / paid deposit / balance order to pay later.

If there is a more D7 commerce way to implement this deposit issue, with rules or whatever, I'll be glad to learn it.

I got it working the following way.

First install Commerce Partial Payment.
Write a custom function to calculate deposit, MODULENAME_deposit_calculation

In order to get Commerce Deposit work with the deposit calculation you like to instead of a customer deposit input, patch it as following :

function commerce_partial_payment_form_commerce_checkout_form_alter(&$form, &$form_state, $form_id) {
  //... line 93
  $acompte = MODULENAME_deposit_calculation($form_state['order']) /100;
    if (!is_null($acompte) && $acompte > 0) {
      $default = $acompte;
    }
  //... line 109 Add the amount to the payment details form,in a hidden field.
  $form['commerce_payment']['payment_details']['amount'] = array(
    '#type' => 'hidden',
  //...
}

function commerce_partial_payment_checkout_validate($form, &$form_state, $checkout_pane, $order) {
  //... line 261
  $amount['amount'] = MODULENAME_deposit_calculation($order)  /100;
  //...
}

function commerce_partial_payment_checkout_submit($form, &$form_state, $checkout_pane, $order) {
  //...line 317
  if ($pane_values['payment_methods']) {
    $amount = MODULENAME_deposit_calculation($order) /100;
    $order->data['atos']['request']['amount'] = $amount;
    if (!empty( $amount)){
      $amount['amount'] = $amount;
  //...
}

As the sandbox doesn't properly send the deposit amount to off site payment, we need to hook the payment method :

In a METHOD_PAYMENT.api.php file

function hook_METHOD_PAYMENT_request_alter(&$settings) {
  //no example
}

Now send to off site payment the deposit amount instead of order total :

function commerce_partial_payment_PAYMENT_METHOD_request_alter(&$settings) {
  $order = commerce_order_load($settings['order_id']);
  $deposit = MODULENAME_deposit_calculation($order);
  $settings['amount'] = $deposit;
}

Last, add a price component deposit below Total to inform the customer what he's going to pay.

function commerce_partial_payment_commerce_price_formatted_components_alter(&$components, $price, $entity) {
  //Add a deposit line to price components
  $deposit= MODULENAME_deposit_calculation($entity);

  $components['deposit'] = array(
      'title' => t('Deposit'),
      'price' => array(
        'amount' => $deposit,
        'currency_code' => $components['commerce_price_formatted_amount']['price']['currency_code'],
        'data' => '',
      ),
    'weight' => '200',
  );
}


Views : custom table with relationship is not queried I use a custom table to store data on my nodes, and hook on _views_data to display or sort from this table.

Everything's going fine :

/**
* Implements hook_views_data()
*/
function MYMODULE_views_data() {

  $data['MYTABLE']['table']['join'] = array(
    'node' => array(
      'left_field' => 'nid',
      'field' => 'nid',
    )
  );
  $data['MYTABLE']['MYFIELD'] = array(
    'field' => array(
      'handler' => 'MYHANDLER',
    )
  );
}

class MYCLASS extends views_handler_field {
  function query() {
    // Add 2 columns I need to the query
    $this->view->query->add_field('MYTABLE', 'COLUMN1', 'ALIAS1');
    $this->view->query->add_field('MYTABLE', 'COLUMN2', 'ALIAS2');
  }

function render($values) {
    // WORKS FINE WITH NO RELATIONSHIP
    $dates = array($values->ALIAS1, $values->ALIAS2);
    ...
    return ..
  }
}

My problem is : I can't get values when my table is called on a node-relationship relationship.

I tried

function query() {
        if(isset($this->relationship) && !empty($this->relationship)) {
            $table = $this->view->relationship[$this->options['relationship']]->table_alias;
            $field = $this->view->relationship[$this->options['relationship']]->real_field;
            $this->view->query->add_field($table . '.' . $field, 'COLUMN1', 'ALIAS1');
            $this->view->query->add_field($table . '.' . $field, 'COLUMN2', 'ALIAS2');
        }
}

and

function query() {
if (!empty($this->relationship)) {
            $this->table = $this->query->ensure_table($this->table, $this->relationship);
        }

but in render, my $values is always empty when the relationship is set.

Instead of adding the fields manually, you should populate the instance variable additional_fields. From the views documentation:

  additional fields: An array of fields that should be added to the query for some purpose. The array is in the form of: array('identifier' => array('table' => tablename, 'field' => fieldname);

Looking through some of the implementations out there indicates that your code should look something like this:

class MYCLASS extends views_handler_field {
  function construct() {
    parent::construct();

    $this->additional_fields['ALIAS1'] = array(
      'field' => 'COLUMN1',
      'table' => 'MYTABLE',
    );
    $this->additional_fields['ALIAS2'] = array(
      'field' => 'COLUMN2',
      'table' => 'MYTABLE',
    );
  }

  function query() {
    $this->ensure_my_table();
    $this->add_additional_fields();
  }

  function render($values) {
    $alias1 = $this->get_value($values, 'ALIAS1');
    $alias2 = $this->get_value($values, 'ALIAS2');
    ...
  }
}


Custom Field Not Being Saved programattically through node_save() So there is a custom field I added called 'qid'.  I can see that it is being created with each node.  My issue is that I cannot programmatically save a value to my custom field.  In the code below I will display and instance where I add two values, one to my custom field qid and another to the Ubercart uc_product field height.  Height will be saved successfully and qid will not.

function my_module_test_page() {
  $output = t('foo');

  $node = node_load('151');
  dpm($node);
  $node->height = '555';
  $node->qid = '222';
  dpm($node);
  node_save($node);
  $test = node_load('151');
  dpm($test);

  return $output;

}

While I understand that this is probably not enough code to get to the root of the problem I have no idea where to look.  I have scoured the node_save() function and I dont understand why my field is having a problem.  If it helps I have checked field_data_qid in my MYSQL db; however, the table is empty.

EDIT: So the next interesting fold is that when I enter the QID field through the GUI it saves fine.

My suggestion would be to inspect an existing node that already has a value for field_data_qid. Is qid a field created through the Fields GUI? $node->qid is not where I'd expect to see a custom field like this.. $node->field_qid['und'][0]['value'] is a more likely candidate. You'd end up with:

function my_module_test_page() {
  $node = node_load(151);
  dpm($node, 'Pre-modified node');
  $node->field_qid['und'][0]['value'] = 222;
  dpm($node, 'Pre-saved modified node');
  node_save($node);
  // Passing TRUE for $reset to bump the cache
  $test = node_load(151, NULL, TRUE);
  dpm($test, 'Reloaded node');
  return 'Test page';
}

Also: node_load takes a nid integer as a parameter, not a string: http://api.drupal.org/api/drupal/modules%21node%21node.module/function/node_load/7

See also: https://stackoverflow.com/questions/7876458/drupal-6-drupal-7-migration-field-unds and Best practice for language key for "und" in hook_form_alter


"_blank" target attribute for links in views I have a custom view that lists a specific content type. I have fields output for each node and have set them to "Link to: Content".

Simply, is there a way to now set the target to "_blank"?

If you are "Rewriting Results" you have the option to specify the target attribute, however I am not rewriting the result (this requires a separate declaration of link path).

this requires a separate declaration of link path

If you are talking about node title it doesn't require a declaration of link path. Just leave this field empty and link will be made with default link path (e.g. node/NID).

For other fields you need to override link path. The easiest way is to add nid field and exclude it from display. Then you can use node/[nid] as link path. In this case you need not use link formatter in field settings.


How to do you modify the URL created by a module? I have a module that creates a list of taxonomy terms. This is the module.

    function theme_jl_custom_category_list($vars) {
      $items = array();
      foreach (taxonomy_get_tree($vars['vid']) as $term) {
        $attributes = array();

       $query = new EntityFieldQuery;
       $query->entityCondition('entity_type', 'node')
         ->fieldCondition('taxonomy_catalog', 'tid', $term->tid);

       if ($result = $query->execute()) {
         $nids = array_keys($result['node']);
       }
       if (isset($_GET['category']) && $_GET['category'] == $term->tid && $_GET['q'] == 'list-product') {
         $attributes['class'] = array('active-category');
       }

       /** How can I append &product=[$nid][0] to this? **/
       $items[] = l($term->name, 'list-product', array('query' => array('category' => $term->tid), 'attributes' => $attributes));
      }

      return theme('item_list', array('items' => $items, 'attributes' => array('class' => array('jl-custom-category-list'))));
    }

In my template.php file, I have the following code.

function [THEME]_preprocess_page(&$vars) {
  $vars['category_list'] = theme('jl_custom_category_list', array('vid' => 3));
  // …
}

In my page.tpl.php file I display the list with the following code.

<?php print ($category_list);  ?>

Combined, they create a list of links like the following ones:

http://example.com/list-product?category=12
http://example.com/list-product?category=14
http://example.com/list-product?category=17

I'm trying to modify these two pieces of code so that in the URL of each category I can append something like '&product=(ID OF FIRST NODE IN EACH CATEGORY)' in the URL to change the links to the following ones:

http://example.com/list-product?category=12&product=5
http://example.com/list-product?category=14&product=10
http://example.com/list-product?category=17&product=8

How can I modify the URL created by that module?

These are just hints to help yourself:

Take the Theme developer module, and check what functions are involved in putting the URL together.
Set a break point inside the l() function just before theme('jl_custom_category_list', array('vid' => 3)) gets executed. The stack should show you the code building the URL.


Trigger the 'add more' button with javascript, to add a set amount of field values Is there any way to add a certain amount of field values to a standard node add/edit form (when unlimited option has been chosen) using a select input?

At the moment I have this working using javascript by triggering click on the 'add another' button, waiting a bit using setInterval (as the button disappears), then looping as many times as I need to, so the new fields gradually appear. This sort of works, but is very very dirty. Is there any proper way to add a certain number of field values based on a select option, and doesn't involved waiting?

I had the very similar problem, but with a group of fields that all needed to be added in sync. Using setTimeout to trigger is problematic because of the guess work involved.

One of the ways to do this is to use the ajaxSuccess event to chain a list of requests. After searching for a solution to my problem, I ended up creating a small plugin called group-add-more. This can work with both Drupal 6 as well as 7.


how to display $page array? How to display the entire $page array like shown below?
I have devel module installed and have tried "dsm($page)" but that just shows the word "Array".

You can try dsm($page) in page.tpl.php of your theme to see the contents of $page array.

As mentioned by Clive, context really matters. If you will try to print $page array when it has no elements then it will display word Array.


hook_library: if two libraries share common file, might this cause files to get loaded in wrong order? I am using hook_library to define two libraries:

mymodule_views_plugin_style_library
mymodule_views_plugin_row_library

The "style" library gets loaded in my custom style template:  drupal_add_library('mymodule', 'mymodule_views_plugin_style_library')

The "row" library gets loaded in my custom row template:  drupal_add_library('mymodule', 'mymodule_views_plugin_row_library')

Each library contains 3 javascript files, which must be added in the specified order.

The style library contains these 3 files:

mymodule_views_lib.js
mymodule_views_style1.js
mymodule_views_style2.js

The row library contains these 3 files.

mymodule_views_lib.js
mymodule_views_row1.js
mymodule_views_row2.js

Note that both the "style" and "row" library have a file in common (mymodule_views_lib.js) and that this file needs to load first.

Here is my hook_library code:

function mymodule_library() {
  $path = drupal_get_path('module', 'mymodule');
  $libraries = array(
    'my_views_plugin_style_library' => array(
      'js' => array(
        $path . '/mymodule_views_lib.js' => array('group' => JS_LIBRARY),
        $path . '/mymodule_views_style1.js' => array('group' => JS_LIBRARY),
        $path . '/mymodule_views_style2.js' => array('group' => JS_LIBRARY),
      )
    ),
    'my_views_plugin_row_library' => array(
      'js' => array(
        $path . '/mymodule_views_lib.js' => array('group' => JS_LIBRARY),
        $path . '/mymodule_views_row1.js' => array('group' => JS_LIBRARY),
        $path . '/mymodule_views_row2.js' => array('group' => JS_LIBRARY),
      )
    ),
  );
  return $libraries;
}

My problem:
The file mymodule_views_lib.js does not load before mymodule_views_row1.js.  It does not load until the "style" library (which happens to load after the "row" library) is loaded.

Question #1:
I see here that there is a solution to my problem:  I can create a separate library for the common js file, and then add this library as a dependency.  I am wondering, though, whether this is the only solution.  Is it possible to specify the relative load order when two different libraries share a common file?

Question #2:
Assuming my libraries do not share any js files, is it safe to assume that the library files will be loaded in the same order in which they are listed, in hook_library?  Or must I explicitly specify a weight?

UPDATE

I added a weight to each js file, as suggested by tenken below, and that solved the problem.  The javascript files now load in the desired order:

   function mymodule_library() {
      $path = drupal_get_path('module', 'mymodule');
      $libraries = array(
        'my_views_plugin_style_library' => array(
          'js' => array(
            $path . '/mymodule_views_lib.js' => array('group' => JS_LIBRARY, 'weight'=>1),
            $path . '/mymodule_views_style1.js' => array('group' => JS_LIBRARY, 'weight'=>2),
            $path . '/mymodule_views_style2.js' => array('group' => JS_LIBRARY, 'weight'=>3),
          )
        ),
        'my_views_plugin_row_library' => array(
          'js' => array(
            $path . '/mymodule_views_lib.js' => array('group' => JS_LIBRARY, 'weight'=>4),
            $path . '/mymodule_views_row1.js' => array('group' => JS_LIBRARY, 'weight'=>5),
            $path . '/mymodule_views_row2.js' => array('group' => JS_LIBRARY, 'weight'=>6),
          )
        ),
      );
      return $libraries;
    }

For question #1 --

$options in hook_library() supports all the options in drupal_add_js.

$options in drupal_add_js supports a weight value to determine ordering:

From hook_library:

  'js': An array of JavaScript elements; each element's key is used as
  $data argument, each element's value is used as $options array for
  drupal_add_js(). To add library-specific (not module-specific)
  JavaScript settings, the key may be skipped, the value must specify
  'type' => 'setting', and the actual settings must be contained in a
  'data' element of the value.

From drupal_add_js:

  weight: A number defining the order in which the JavaScript is added
  to the page relative to other JavaScript with the same 'scope',
  'group', and 'every_page' value. In some cases, the order in which the
  JavaScript is presented on the page is very important. jQuery, for
  example, must be added to the page before any jQuery code is run, so
  jquery.js uses the JS_LIBRARY group and a weight of -20,
  jquery.once.js (a library drupal.js depends on) uses the JS_LIBRARY
  group and a weight of -19, drupal.js uses the JS_LIBRARY group and a
  weight of -1, other libraries use the JS_LIBRARY group and a weight of
  0 or higher, and all other scripts use one of the other group
  constants. The exact ordering of JavaScript is as follows:

For question #2 -- the safest thing todo is to always specify the inclusion order; eg weight.


Why does this rule not appear in the UI and how can I clone it? I need to clone and modify the following rule:

commerce_checkout_order_email

However, it does not appear in the UI.

I have checked the following paths with no success:

admin/config/workflow/rules
admin/commerce/config/checkout/rules

I'm obviously missing something but I can't figure it out.

This rule is defined in this file along with 4 other rules, all of which do appear in the UI

sites/all/modules/commerce/modules/checkout/commerce_checkout.rules_defaults.inc

The thing is this rule DOES get executed properly.

Any ideas will be greatly appreciated.

By the way, I have doubled checked on TWO different drupal installations, one of which is a default commerce_kickstart distribution and the rule doesn't appear either.  It won't show up in the UI nor in the database.

I don't think it's possible to delete this Rule. Even if you delete it from the database directly, it is recreated the first time Commerce gets called (because it's in the defaults .inc file).
Are you sure it's not just disabled?
Your module directory structure is non-standard; Commerce should be in sites/all/modules/contrib.

Here's a copy of the Rule in case you need to import it again:

{ "commerce_checkout_order_email" : {
"LABEL" : "Send an order notification e-mail",
"PLUGIN" : "reaction rule",
"WEIGHT" : "4",
"OWNER" : "rules",
"TAGS" : [ "Commerce Checkout" ],
"REQUIRES" : [ "rules", "commerce_checkout" ],
"ON" : { "commerce_checkout_complete" : [  ] },
"DO" : [
  { "mail" : {
      "to" : [ "commerce-order:mail" ],
      "subject" : "Order [commerce-order:order-number] at [site:name]",
      "message" : "Thanks for your order [commerce-order:order-number] at [site:name].\u000A\u000AIf this is your first order with us, you will receive a separate e-mail with login instructions. You can view your order history with us at any time by logging into our website at:\u000A\u000A[site:login-url]\u000A\u000AYou can find the status of your current order at:\u000A\u000A[commerce-order:customer-url]\u000A\u000APlease contact us if you have any questions about your order.",
      "from" : ""
        }
      }
    ]
  }
}


How do I add a user to a group? I am using the Drupal 7 version of the Group module. I found this Drupal 8 code which adds a user to a group, and I can't find anything similar for Drupal 7.

use Drupal\Core\Entity\ContentEntityBase;
$account = \Drupal\user\Entity\User::load('uid');
$group = \Drupal\group\Entity\Group::load($group_id);
$group->addMember($account);
$group->save();

What is the equivalent Drupal 7 code?

I tried using the following code, but it throws an error.

<?php
$account = user_load($uid);
$group = entity_load_single('group', 1);
$group->addMember($account);
$group->save();
?>

The error is the following one.

  Object of class stdClass could not be converted to int in Group->addMember()

For D7 its

$account = user_load($uid);
$group = group_load($group_id);
$group->addMember($account->uid, array('joined_on' => REQUEST_TIME));

To delete

$group->removeMember($account->uid);

To request

$group->addMember($account->uid, array('status' => 'requested', 'requested_on' => REQUEST_TIME));

To block:

foreach (group_membership_load_by_user($account->uid) as $group_membership) {
  $block_gid = // some code to get the Group ID that you want the ...
               // ... the block to take place in.
  $gid = $group_membership->gid;
  if ($gid == $block_gid) {
    global $user;
    if ($group_membership->status != 'blocked') {
      $group_membership->blocked_status = $group_membership->status;
      $group_membership->status = 'blocked';
      $group_membership->blocked_on = REQUEST_TIME;
      $group_membership->blocked_by = $user->uid;
      $group_membership->save();
    }
}

To Unblock:

foreach (group_membership_load_by_user($account->uid) as $group_membership) {
    $unblock_gid = // some code to get the Group ID that you want the ...
                  // ... the unblock to take place in.
    $gid = $group_membership->gid;
    if ($gid == $unblock_gid) {
      if ($group_membership->status == 'blocked') {
        $group_membership->status = $group_membership->blocked_status;
        $group_membership->blocked_status = '';
        $group_membership->blocked_on = NULL;
        $group_membership->blocked_by = NULL;
        $group_membership->save();
      }
    }
}


Views 3: Getting related content from node ref field Okay, i have the following node types:

Band
Story

Every story content links to a band via the node reference module for Drupal 7, now i'd like to pull related story content thats linked to the band when i view the current node that links to band X.

To give you an beter example:

When the story, "helloween reveals new album" links to helloween, i'd like to display all the related story's about helloween in that view...

Your question is not quite clear whether you want to show band information when viewing a band-story node or to show band stories when viewing a band node. I'm assuming it's the second one.

Create a View with "Content" under "Show", and choose "Band Story" as the node type.

Clear the check box to create a page or make a block if you want. That's up to you:
Save and continue to Views UI.
In the Views UI, make sure you have 2 filters added - Node is published, and the node's type is Band Story.
Default sort criteria would be "Newest first". Change it if you want.
Add a new contextual filter.
In the add contextual filter, choose the field that refers to Band node. This field should be in the Band Story node type.
Add the argument. You will get the argument's settings page.
Under "When the filter value is NOT available", choose "Provide default value". Under "Type" select list, choose "Content ID from URL".

You can optionally add a validation criteria if you allow the node reference field to refer other node types than "band" as follows.

11.  That's it! Save the View and put the block (you have to give a name to it) in the sidebar (or anywhere else). it will inherit the current node's ID and will show Band Story nodes that have this node ID in its node reference field.


How to use the Jquery Multi module? I have a site theme that needs to use Jquery 2.1.3. The theme uses on() and affects the node/add form. So I also need Drupal's default Jquery 1.4 to be running, otherwise the default Drupal scripts on the node/add form will not work.

The Jquery Multi module is supposed to be the best way of doing this. But how do you use the module? I have installed it and verified that the Jquery 2.1 library is running.

In the Read Me it says:

  For instance, if you're loading jQuery-1.7.1, the alias will be jq171,
  and you can
          use it in your scripts by wrapping your code as follows:

      (function($){
        // your code here, using jQuery 1.7.1
      })(jq171)

  NOTE: All jQuery targeted to use jQuery Multi (using methods A, B,
  or C above) must properly use a
          closure around the jQuery code, as is best practice for all Drupal jQuery code, i.e.:

        (function($){
          // your code here, using jQuery 1.7.1
        })(jQuery)

Do I wrap my code in both jq213 and Jquery for example:

(function($) {
    (function($) {
        "use strict";
        $(document).ready(function() {

            /* *********************** */
            /* Mobile only Hamburger menu       */
            /* *********************** */
            $(".masthead .menu").on("click", function() {
                $(this).toggleClass('menu-close');
                $("body").toggleClass('menu-open');
                $(".masthead ul").toggleClass("animated bounceInDown");
                $(".masthead .tap-back").toggle();
           });
                  });
    })(jq213)
})(jQuery);

I have tried this, but it doesn't work. When I check the HTML source I can see that Jquery 2.1.3 doesn't load, so presumably I am wrapping my scripts wrongly.

In admin/config/system/jqmulti I can see that Jquery 2.1.3 has loaded.

Why you did double code wrap?
Try to use:

(function($) {
    "use strict";
    $(document).ready(function() {

        /* *********************** */
        /* Mobile only Hamburger menu       */
        /* *********************** */
        $(".masthead .menu").on("click", function() {
            $(this).toggleClass('menu-close');
            $("body").toggleClass('menu-open');
            $(".masthead ul").toggleClass("animated bounceInDown");
            $(".masthead .tap-back").toggle();
       });
              });
})(jq213);


Calculate the number of days since the creation date of a user account I would like to calculate the number of days past since a users creation date. This is what I have done so far:

$user = \Drupal::currentUser();
$registrationdate = getdate($user->getCreatedTime());
$today = getdate();
$daypast = date_diff($regdate, $today);

This results in the following error:

  date_diff() expects parameter 1 to be DateTimeInterface

How can I solve this and get the number of days past since the users registration date?

This depends on what you need to do with it.  If you truly just need the number of days, then this will work

$user = \Drupal::currentUser();
$created = new \DateTime('@' . $user->getAccount()->getCreatedTime());
$interval = $created->diff(new \DateTime());
$days1 = $interval->d
$days2 = intval($interval->format('%d'));

Here $days1 and $days2 should give you the same value.  See the docs for \DateTime and \DateInterval for more information.

If you need a nifty string for output purposes, then check out DateFormatter::formatTimeDiffSince() and friends:

$user = \Drupal::currentUser();
$created = $user->getAccount()->getCreatedTime();
/** @var \Drupal\Core\Datetime\DateFormatterInterface $date_formatter */
$date_formatter = \Drupal::service('date.formatter');
$created_since = $date_formatter->formatTimeDiffSince($created);

and then $created_since will be a string like '7 weeks 2 days'.  You can also use the 'Time ago' formatter directly in the entity rendering configuration.  The default view for the accounts listing does this.


How to find content that uses a File (File Entity)? Want to be able to see what content has file field(s) that refer to a specific file.

Is this do-able using a View (with Relationships)? (had a go already, unsuccessful so far).
Alternatively I'd query database tables (via the proper API) and relate that way, but just thought I'd ask if there is a generic solution before potentially re-inventing the wheel.

Searched a lot butn get a lot of unrelated search results. Search engine cannot seem to be told that I want my terms ordered in a certain way.

Ultimately I'd like to have a View that shows the Files and the content that uses each file. I would then be able to see the impact of deleting a file for example.

Create a view of type files:

Add a relationship to 'Content', make sure you set it as required:

Add any fields you wish to see of the file or the node.


How to vote for both answers and question using the Answers module? I am using Answers module. In that only for nodes of type Question I can add vote up/down field.

But I wonder how I can add a voting feature for the nodes of type Answer?

Instead use Question/Answer module, it have the vote system for both question and answer

  It adds a question/answer section for website. Different from other
  modules, it uses only one node type for question, and the core
  comment.module for answer. This allow reutilisation of CCK, Views..

or

You can try Vote Up/Down module

  Allows votes on some drupal entities and provides the base for
  implementing votes on other entities

or take a look at Rate module

  This module provides flexible voting widgets for nodes and comments.
  Multiple ratings on the same node (i.e. for "comfort", "location",
  "services" etc.)


How do I create a tree system? Before I knew Drupal, I made a CMS that was working like Wikipedia, where each page and link could have parent and children. Now I want to create that website with Drupal.

Is there any module for this?

This is what I need: Each page may have children, and each children may have children too and so on.

There is a core module namely 'Book' . Use that module to get desired structure of pages.

For more information visit here


Contextually modify views output? On the front page, i'd like the views to output taxonomy differently than i would on a term page.

I know i could modify output using a tpl file indicated by devel_themer; but i'm not certain how one would contextually change it.

How would i go about doing so with a preprocess function?
Is it even possible?

you could just get the current page with request_uri() and then use some logic to style a view on the home page differently.

Or just create a second view and use the front module to show that view on the home page.


Date tokens for file path I have a big site with a lot of images and I want to use Date tokens for the File path.
So I edit the image file and set Filepath: [current-date:short]

I have the following issue:
1)Uploaded images are broken
What could be the reason for this?
thanks

Configuration > Regional and Language > Date and Time

Check what your default Short time format is. If its being printed with spaces, it could be part of the problem.
You could add a new date type, and see if that fixes anything.

The easy way around this, is when managing the image and file upload CCK fields, just specify a directory for those images in the field settings there.


Use Plugin Field inside buildForm() In Drupal 8, I use this code inside my buildForm() method:

$form['medias']['file'] = array(
  '#title' => t('Image'),
  '#type' => 'managed_file',
  '#upload_location' => 'public://image_example_images/',
  '#multiple' => true,
);

(Bad) Result: http://i.stack.imgur.com/ju0ZU.png

I would like know if it's possible to use a plugin of type "field widget" inside BuildForm() for call and use a field of Image type provided by the core of Drupal:

Thanks.

Possible?

Probably. But it would require a lot of work, as you would basically have to provide all the data and calls that such plugins need. That is very likely more work than re-implementing this functionality yourself.

And creating an entity type would only make sense if you need to manage multiple "things" that each has images attached.


Is there a postcode for deliveries checker module for drupal 7? I'm thinking about using Drupal for a take away (delivery) ecommerce site and was wondering if there is a module that could calculate the the distance between the postcode added by the user and the shop locations (a few) and if its within a certain radius go ahead and allow the user to place the order. Is there such module available for drupal? if not, is there a similar module(s) that could be adapted to it?

Thanks

There's no single module for this, but you can use a suite of modules.  For example, you can take addresses stored in the Address Field module and then use Geocoder to geocode them and save the results in a Geofield.  You can then use Rules to check the distance.

That said, there is no simple way to do this.  In fact, there's an entire book about Mapping with Drupal.


Calling /user page with username instead of uid results in database exception due to failed string to int conversion When I use a username as an url parameter like: 'www.example.com/user/adam' instead of 'www.example.com/user/27' I get a database exception:

  Error message
  PDOException: SQLSTATE[22018]: [Microsoft][SQL Server Native Client 11.0][SQL Server]Conversion failed when converting the nvarchar value 'adam' to data type int.: SELECT base.[uid] AS [uid], base.[name] AS [name], base.[pass] AS [pass], base.[mail] AS [mail], base.[theme] AS [theme], base.[signature] AS [signature], base.[signature_format] AS [signature_format], base.[created] AS [created], base.[access] AS [access], base.[login] AS [login], base.[status] AS [status], base.[timezone] AS [timezone], base.[language] AS [language], base.[picture] AS [picture], base.[init] AS [init], base.[data] AS [data] FROM {users} base WHERE ( ([base].[uid] IN (:db_condition_placeholder_0)) ); Array ( [:db_condition_placeholder_0] => adam) in DrupalDefaultEntityController->load() (line 196 of C:\inetpub\wwwroot\includes\entity.inc).

I use pathauto which uses the following pattern for user account page aliases:
users/[user:name] and that works fine. I just stumbled upon this error when testing the site before deployment. I'd rather not have this error visible to users which might try to navigate to /user instead of /users.

Since it only seems to be legal to use actual uid's when calling the /user/ subpage (aside from the login and logout pages etc.), what can I do to prevent drupal from trying to parse a username as an int and producing this error? Is there some redirect I can perform?

There are two sides to this question.
First, you should not get this error message. It should be good old 404 page or Drupal's error message about invalid argument. It's either a bug in database backend for MS SQL and belogs to their queue, or in your version of MS SQL RDBMS and belongs to Microsoft technical support. Or you simply need updates.
Second part is - out of the box only numerical URLs works.You neet to create aliases with username. It can be done automatically, Pathauto's default setting is exactly:

Pattern for user account page paths
users/[user:name]

Sadly, unless you get the first part fixed, it will only help with valid users, people will still get ugly message if they'll hit a name that does not exist, by typo in their address bar for example.


What arguments does a _custom_access callback exactly receive? The example given in Access checking on routes for using _custom_access is the following.

example.routing.yml

example:
  path: '/example'
  defaults:
    _controller: '\Drupal\example\Controller\ExampleController::content'
  requirements:
    _custom_access:  '\Drupal\example\Controller\ExampleController::access'

ExampleController.php

/**
 * @file
 * Contains \Drupal\example\Controller\ExamleController.
 */

namespace Drupal\example\Controller;

use Drupal\Core\Session\AccountInterface;
use Symfony\Component\HttpFoundation\Request;

    /**
     * Builds an example page.
     */
    class ExampleController {

      /**
       * Checks access for a specific request.
       *
       * @param \Drupal\Core\Session\AccountInterface $account
       *   Run access checks for this account.
       */
      public function access(AccountInterface $account) {
        // Check permissions and combine that with any custom access checking needed. Pass forward
        // parameters from the route and/or request as needed.
        return $account->hasPermission('do example things') && $this->someOtherCustomCondition();
      }
    }

From this example, I get the first parameter of such callbacks is $account as I would expect, since the access is normally checked against an account.

Looking at code used from Drupal core modules, I find the following.

toolbar.routing.yml

toolbar.subtrees:
  path: '/toolbar/subtrees/{hash}'
  defaults:
    _controller: '\Drupal\toolbar\Controller\ToolbarController::subtreesAjax'
  options:
    _theme: ajax_base_page
  requirements:
    _custom_access: '\Drupal\toolbar\Controller\ToolbarController::checkSubTreeAccess'

ToolbarController.php

public function checkSubTreeAccess($hash) {
  $expected_hash = _toolbar_get_subtrees_hash() [0];
  return AccessResult::allowedIf($this->currentUser()->hasPermission('access toolbar') && Crypt::hashEquals($expected_hash, $hash))->cachePerPermissions();
}

In this case, $account is not passed as parameter, but the controller gets it from the dependency injection container, which leaves me puzzled.

I also checked at the class implementing the access service used for _custom_access, but I just see the following code, which doesn't make things clearer.

public function access(Route $route, RouteMatchInterface $route_match, AccountInterface $account) {
  $callable = $this->controllerResolver->getControllerFromDefinition($route->getRequirement('_custom_access'));
  $arguments_resolver = $this->argumentsResolverFactory->getArgumentsResolver($route_match, $account);
  $arguments = $arguments_resolver->getArguments($callable);

  return call_user_func_array($callable, $arguments);
}

(See CustomAccessCheck::access().)

If then I watch at ArgumentsResolver::getArguments() (the method called with $arguments_resolver->getArguments($callable) in the previous method), I see the following code.

public function getArguments(callable $callable) {
  $arguments = array();
  foreach ($this->getReflector($callable)->getParameters() as $parameter) {
    $arguments[] = $this->getArgument($parameter);
  }
  return $arguments;
}

$account seems ignored.

What arguments does a _custom_access callback exactly receive?

See \Drupal\Core\Access\AccessArgumentsResolverFactory::getArgumentsResolver() which is called by your snippet above to create the argument resolver, I think that covers it pretty well.

It gets all raw parameters, all possibly upcasted parameters, plus request, route match and account. The access callback receives the arguments from that list, based on the names and type hints.

So account isn't ignored.

That logic is the same as for any other access check, the whole point of _custom_access is to have an easy way to do a one-off access check without having to go through the additional steps of a service that's defined with a special tag.


Search api solr deleted terms showing up in facet Why would taxonomy terms that I have previously deleted show up in my facet? I'm using search api solr. There is no term named "23"; it is a tid, but tid 23 is not in the database yet my facet shows 29 items as being tagged with it. I have flushed cache, run cron, rebuilt index, all multiple times, and don't know what else to do.

Filter by that facet and check the nodes that display, they probably still reference the deleted term (see issue: Database records not deleted for Term Reference Fields after Term is Deleted)

To get rid of it, edit the nodes and remove the term reference, either manually or programatically depending on the volume.  Then reindex your content.


db_query() doesn't seem to run in module I have a custom user-management module in my Drupal 6 site. We are a corporate subscription service and needed a way for a subscribing company's primary user to delete other users from their company. When this happens, we need to not only delete the Drupal user record for that person, but also make some changes to a record in another mySQL database that's connected to one of our internal non-Drupal systems. There's a lot of jquery stuff involved, but the main thing is that a user clicks a delete link next to a name in a list of users. The link looks like this:

http://mysite.com/account/manage/disappear/1/182741

The final three params are what we use - disappear is the action (there are also promote and demote, which allow the primary user to change the type of account other users have), 1 is the Drupal ID of the primary user (in this case, I'm logged in as user 1), and the final param is the ID from our non-Drupal database. From that ID's record, we can find the Drupal account ID we need to delete (as well as other info we need for this function that are not specifically Drupal-related.)

Most of it works correctly - the user is deleted and the email is sent, but the query that's supposed to update our other database doesn't seem to be running. Can anyone help me out? Is there a way to debug queries? I know I'm dealing with the correct records; the error_log line right inside the disappear case returns the correct values.

Here's the function (I've stripped out the promote and drop actions since they work. Also, Viola is our intranet app where the non-Drupal database lives)

function user_manage_function($action, $uid, $viola, $email_prefix = '', $email_domain = '') {

    // action = delete, promote or drop?
    // uid = the UID of the primary user, as a security measure
    // viola = the Viola people ID of the person we want to promote, delete or drop
    // email fields = if the PU adds an email address, we need to verify it

    global $user;

    if ($user->uid == $uid) { # just a sanity check to make sure we know the current primary user

        // see what their UID is ... set $vuid = the drupal uid of the promoted/dropped/deleted user
        $people_row = db_fetch_object(db_query("SELECT institute_uid, email FROM {ismi.new_people} WHERE id = %d", $viola));
        $vuid = $people_row->institute_uid;
        $viola_email = $people_row->email;
        $data = 'pending';

        if ($vuid) {

            switch ($action) {

            case "disappear":
                error_log("inside main disappear - vuid=$vuid and viola=$viola");
                  $quer = db_query("UPDATE {ismi.new_people} SET active = 0, insitute_uid = 0 WHERE id = %d", $viola);
                    user_delete(array(), $vuid);
                    $message = array(
                        'to'                =>  'test@test.com',
                        'subject'       =>  t('User deleted by primary user'),
                        'body'          =>  t($user->name . ' (' .$user->mail.') just deleted the Institute website account for '. $viola_email),
                        'headers'       =>  array('From'=>'test@test.com'),
                    );
                    drupal_mail_send($message);
                    break;
            }

            $data = 'success';
    }
  }
}

You write that

  but also make some changes to a record in another mySQL database that's connected to one of our internal non-Drupal systems

so I figure that you need to query a different MySQL database, but in your don't change the active database using db_set_active. This is most likely the root to your problem.

If the SELECT query works, then the code you have provided should work just fine.

A simple way to test your problem, would be run db_query on a known record and see if you can alter it. Devel also offers query logging, which would allow you to log the actual UPDATE and alternatively try to run the raw query through a MySQL interface.

Another explanation could be that you have the ismi.new_people table in the Drupal db, so you in fact are updating the wrong table/database.

Another possible problem is database  permissions. Do your DB user have read only access?


How to pass a value from form(block) to the page and show this page? I created a block with a form (elemnts: textfield and submit). Also have a page created by the hook_menu. I want that when you click on submit in block, the value from textfield transmitted to a page that is created using the hook_menu and show this page with data from textfield.
In the future I plan to transfer some text in the html markup or array.

Read about hook_menu and wildcards. Here is an example:

function my_form($form, &$form_state) {
  $form['name'] = array(
    '#type' => 'textfield',
    '#title' => 'Name',
  );

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

  return $form;
}

function my_form_submit($form, &$form_state) {
  $form_state['redirect'] = 'path/' . $form_state['values']['name'];
}

function MODULE_menu() {
  $items['path/%'] = array(
    'title' => 'TTITLE',
    'page callback' => 'my_page_callback',
    'page arguments' => array(1),
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
  );

  return $items;
}

function my_page_callback($var) {
 return 'HELLO ' . $var;
}


How to remove "authenticated-user" from this [user:roles:join-path]/[user:name] I have these roles:

anonymous user,
authenticated user,
administrator,
members,
partners.

In URL Aliases I changed at USER PATHS with this: [user:roles:join-path]/[user:name]

I created 2 views for user: first for members role and second for partners role (the views contain userpicture and username). The link for these users in both roles are :

www.example.com/authenticated-user/members/username
www.example.com/authenticated-user/partner/username

I know that authenticated user role is default for authenticated users, but it is possible to remove from USER PATH: from „www.example.com/authenticated-user/members/username” to „www.example.com/members/username”?

Thank you.

You can implement hook_pathauto_alias_alter(), which is invoked from pathauto_create_alias(). The function passes the pattern used from the Pathauto module before the tokens are replaced in $context['pattern']. You probably want to check the pattern contains "[user:roles:join-path]" to avoid "authenticated-user" is removed where the pattern explicitly uses "authenticated-user".

The alternatives would be:

Implement hook_tokens_alter() to alter the output of that token, but that would change it in any place the token is used, not only in alias created from the Pathauto module
Implement hook_tokens(), and hook_token_info() to implement a token similar to [user:roles] but that doesn't include the string for the authenticated user role

Notice that it is the Pathauto module that handles the :join-path part of the token, in pathauto_tokens().


How to trigger JavaScript/jQuery on AJAX-enabled ImageField submit? I'm trying to trigger a JavaScript event when an AJAX-enabled ImageField submit button is clicked.

I've tried variations on delegate(), submit(), and click(), but no joy.

This is something similar to what I'm trying:

$('#edit-field-image-und-0-upload-button').mousedown(function () {
  alert('hi');
});

I read the documentation I could find on Drupal's AJAX forms, but haven't found what I'm looking for yet.

I agree with DeeZone that .click() should work.

Try putting that code in a $(document).ready();

Drupal ajaxifies it's stuff on document ready so your code might be executing BEFORE the form gets ajaxified by Drupal.

$(document).ready(function() {
  $('#edit-field-image-und-0-upload-button').click(function () {
  alert('hi');
  });
});


template_preprocess custom block type I have a custom block type with two different fields.
What I am trying to accomplish is, to hide the first field if the second is not empty.

That seems like something that could be done in template_preprocess, but where would I put it and what would be my template?

thanks!

you can utilize twig's if/else condition:

Find the twig's template file for your custom block using twig debug mode
use twig's if/else syntax (reference)

{% if field_NAME_OF_YOUR_SECOND_FIELD.0 == false %}
    {{ field_NAME_OF_YOUR_FIRST_FIELD.0 }}
{% endif %}

check this for extracting the values of different fields


Link to my story content type D7? I have added many content to content type story. How will I link to the page that shows all the nodes with their teaser? What will the link be?

If your contents are promoted to front page, they will be shown on front page.

If you want to see your content in a seperate page or block you should create a View from your contents, with the Views module


General template (node.tpl.php) being used instead of specific template (node-article.tpl.php) I'm creating my sub-theme based on Zen's starterkit. I copied node.tpl.php from zen to my theme and started making some customizations. Then I realized that I really only wanted those customizations to happen to the Article content type, so I renamed my subtheme's node.tpl.php to node-article.tpl.php but when I do it doesn't get used when I'm viewing my front page which has a list of articles. If I rename it back to node.tpl.php then it immediately gets used again. Back to node-article.tpl.php and I get nothing.

What am I doing wrong?

Are you using Drupal 7? If so, you should just leave node.tpl.php as it was originally and call your customized version node--article.tpl.php.

If you are using D6 you are naming the file right, you should just leave a copy of the original node.tpl.php in your subtheme folder.


Whats the most effective way to intergrate a javascript cost calculator to a specific node I'm going to use a  JavaScript cost calculator for perspective customers to calculate costs. I was wondering what was the most effective way to integrate the script within a node.

You can use JS injector module

  Allows administrators to inject JS into the page output based on
  configurable rules. It's useful for adding simple JS tweaks without
  modifying a site's official theme - for example, a 'nighttime' color
  scheme could be added during certain hours. The JS is added using
  Drupal's standard drupal_add_js() function and respects page caching,
  etc.

or simply use drupal_add_js in body field with enabled PHP input mode and take a look at this page


How to inspect outgoing email content? There are several modules that send email from my site: Rules, Trigger, User, ...

I am looking for a place to set a drupal_set_message() and print out the email contents. Where in the code would be the best place for that?

You can use hook_mail_alter() to get (and alter) the contents of an e-mail message before it gets sent out:

function mymodule_mail_alter(&$message) {
  dpm($message);
}

One thing to keep in mind is that not all modules use drupal_mail(), the function that'll call hook_mail_alter(), for various reasons. In that case, you'll have to identify where in the module's code the mail is sent out and see if they provide their own alter hooks: look for the functions drupal_alter('foo') (implemented via hook_foo_alter()), module_implements('foo'), module_invoke('foo'), or module_invoke_all('foo') (all implemented by hook_foo()).

Failing that, you may have to temporarily add the dpm() call directly to the module in the right place.


How do I copy an already existing field in manage display? I have a field (entity reference) that is used to provide a link to another node. I want to have it two times in my "manage display" settings page, it's for redundancy. I don't want to create a new field, i just want a duplicate in the view mode. Is that possible? Maybe it's just hidden in plain view?

The approach I would use would be to use a custom php snippet in a block to pull the field value out of $node and to format the field. I would then place the block in a region of the page where I needed it.

<?php

if (arg(0) == 'node' && is_numeric(arg(1))) {

$node = node_load(arg(1));

if (isset($node->field_node_reference['und'])) {

foreach ($node->field_node_reference['und'] as $other_node) {
  $link = '/node/' . $other_node['node']->nid;
  $title = $other_node['node']->title;
  print (l( $title, $link));
}

}

} ?>

This would be the core code for a node reference field. You should pretty it up to format your display, but this gets the information on your page a second time.


Absolute or relative URLs? Never thought Drupal's way to use relative URLs everywhere in template files was a problem until I happened on https://stackoverflow.com/questions/17187437/relative-urls-in-wordpress and read some arguments against using relative urls of many WP developers including core ones. Copying them here:

  Root-relative URLs aren't really proper. /path/ might not be    WordPress, it might be outside of the install. So really it's not
  much different than an absolute URL.
  Any relative URLs also make it significantly more difficult to    perform transformations when the install is moved. The find-replace
  is going to be necessary in most situations, and having an absolute
  URL is ironically more portable for those reasons.
  absolute URLs are needed in numerous other places. Needing to add    these in conditionally will add to processing, as well as introduce
  potential bugs (and incompatibilities with plugins).
  Relative to what, I'm not sure, as WordPress is often in a subdirectory,    which means we'll always need to process the content
  to then add in the      rest of the path. This introduces overhead.
  Keep in mind that there are two types of relative URLs, with and without the leading slash. Both have caveats that make this impossible
  to properly implement.
  WordPress should (and does) store absolute URLs. This requires no pre-processing of content, no overhead, no ambiguity. If you need to
  relocate, it is a global find-replace in the database.

Now I wonder how much those concerns are legitimate in general, in if they or some of them are, then how much this relates to Drupal in particular?

As a developer who has worked extensively with both Drupal and Wordpress I have to say that the convenience of Drupal's relative URLs outweighs the (apparent) accuracy of Wordpress's absolute URLs.

When moving a site from dev > staging > production a Wordpress site's URLs and image references have to be replaced in the DB, this can create an absolute mess.
Rather than creating links between pages as hyperlinks a good Drupal setup uses entity reference and entity embed, so if the path or URL of a file changes the page's source is still correct.
Wordpress feeds are natively better as the URLs are natively absolute, Drupal views feeds can be made to use content filters to make links absolute.
In Drupal I like to use a module called pathologic to set absolute URLs in the rendered source, the stored source however remains free of site domain.
Performance hit of content filtering is negligible on Drupal and there are multiple layers of caching.

Hope that answers some people's questions if they arrive here.


Views 3 + field collection: relate only the first referenced field collection item I'm using Views 3 and Field collection 7.x-1.0-beta3.  As a simplified example, say I've a field collection called Image - which itself has two fields, an image file and a text caption.  My content type, Page, includes a multi-value field to reference one or more Image(s).

In my view, I want to list several Page nodes, and display the image file field taken from only the first of each node's referenced Image field collection entities.

This works, but...

I have one solution that does work but feels clunky and indirect: Add the Image collection-reference field, and use the multiple-value settings to restrict to the first value (a la this post). However, then I have to have a view mode for the Image field collection that prints only the image file field, in the desired image style.

What would be awesome:

I've tried a different route using the Relationships settings. I can add a relationship from node to its Image field collection. Then, I can add the image file field, pulling from the relationship. BUT, that creates a new result for each of the Image field collections being referenced... and I can't find an option to key the relationship off the first value only (similar to displaying only the first value when I'm just going through adding the field, in my "this works" solution above).

I realize this may be impossible - if Views can't create the necessary query? Just wondering if I have missed something though I've gone through the settings several times.

Edit: Drupal 6 / Views 2 does it!

Okay, I'm not crazy - see screenshot. I think that's exactly what I'm looking for here.

If you create a view with the field collection relationship this is possible.
Besides the field with the image you need to add another field with the image delta.
When you add this field exclude this from display.

In the views filter add a filter on this delta field and set this filter to equals 0.

Now you've got a view with just one (the first) image per node!


Node Reference to include an "Apply Now " link I'm looking for answers to the best approach to dynamically including an "Apply Now"/"Apply For" link/button within node content.
For example. the content node has been custom created and visitors (registered users only) can click the "Apply Now" once viewing any said published node. For example, this maybe a "Join Band" on a music band collaborative site, a "Apply Now" on a Jobsite, a "Date Me" on a dating site, "Tender Now" on a contract site etc.

I've also schematicised in LibreOffice Draw for basic work-flow and using the Panels/Ctools/Rules combination along with Relation to ensure that posted content appears in a Users dashboard (based on their profile2/HomeBox type) whereby application Receivers can manage/reply/on-hold/delete such application notices. Or maybe I'm barking up the wrong tree in my approach!?

My Main issues is primarily the inclusion on an "Apply Now" link in any said node and the most effective and futureproof so looking for for clarification on best D7 tools/Modules to use for such a back-end integrated task.

The entry here relates further to my question: Re: Relation Module which relates to a previous module I had started to utilise, but have now made redundant due to it's original author's Module depreciation, but in essense looking for an answer a generalistic approach to building such frameworks of this nature using common D7 modules (no custom coding at present), which I'm sure are very common.

Current overview found: http://www.lullabot.com/articles/photo-galleries-views-attach identities a similar issue, but I'm not too sure if this would be the correct/come best effective approach.

I am a newbie and any help is much appreciated. Anything I learn, I'll gladly pass it on here. Thanks in advance.

I opened a discussion on this here http://drupal.org/node/1204554. There are a couple of approaches/solution that you may find helpful.

iRex


Pass field value of original node in webform I'm using Drupal 8.7.8 and Webform 5.4.0. I have multiple section nodes that are displayed on course nodes. These are 2 different content types.

I'm adding webforms to sections, via the twig file conditionally (not all sections) with {{ drupal_entity('webform', 'my_form_id') }} and I need to pass the value of field_code of the section into a hidden field on the webform.

Once the form is rendered on the course page, the field_code value passed belongs to the course node rather than the section. How can I access the field_code value on the section?

I tried adding a hidden field with this token as the default [webform_submission:node:field_code:value], which works when I test the form on the section, but when I test the form on the course (where the user will access it) I'm getting the field_code value of the course.

What's the best way to handle this? Is there a way to set the source entity to the content type that the form is on? Please let me know if I need to add more info.

Thanks!

I'm answering this with how I solved it in case anyone else has the same question. Maybe my question could be worded better though...

I was able to get this working with the Webform Node module.

I installed webform node. Then, I added a webform field to my content type. I selected the form I wanted as the default field settings. I selected the "Use this field's Content entity as the webform submission's source entity." checkbox.

I added my form to the display of the nodes I wanted it to be on in the content type's twig:

{% if node.field_name.entity.label == "My condition label" %}
  {{ content.field_name_of_webform_field }}
{% endif %}

Now, on my course page the same form appears for each section and I get the code for the section that the person filled-out the form on in the [webform_submission:source-entity:field_code:value] token!!

A couple of the resources that helped me:
https://www.youtube.com/watch?v=B_ZyCOVKPqA
https://www.webwash.net/moving-forward-webform-drupal-8/#attaching-a-webform-to-a-node


Save certain registration fields elsewhere in database This is for Drupal 7. I am trying to write my first real custom module but I'm running into some difficulty and I'm just not sure how to look for my answers.

I've created a new entity for my module (with Entity API) with a corresponding table in the database. I need to add records to this table upon new user registration. I've used Form API to add a new field to the user registration form but I'm not quite sure the best way to do the next step. When the registrant submits the form, I would like all the regular Drupal registration stuff to happen, but I would like to intercept this one field and have its data go to the table I've created for my entity.

Here's what I have in the .module file of my custom module (the part concerning the registration form):

/**
* Implement hook_form_user_register_form_alter()
*/
function my_module_form_user_register_form_alter(&$form, &$form_state, $form_id){
    //add my module textbox to the registration form
    $form['my_module_field'] = array(
        '#type' => 'textfield',
        '#title' => t('My Module field'),
        '#required' => TRUE,
    );
    $form['submit'] = array(
        '#type' => 'submit',
        '#value' => 'New Submit Button',
        '#submit' => array('my_module_form_submit'),
    );
    unset($form['actions']);
}//end my_module_form_user_register_form_alter

/* Custom Submit handler */
function my_module_form_submit($form, $form_state){
    db_insert('my_entity_table')->fields(array(
        'my_entity_item' => $form_state['values']['my_module_field'],
    ))->execute();
    drupal_set_message('Your information has been saved.');
}//end my_module_form_submit

This is working fine to get my special field in my special table. But the user is not created. I suppose I could do it manually (like enter the other information into the appropriate users table and everything) but obviously I would rather not do that manually.

I feel that I must be missing something obvious here but I'm not having any luck searching for it. I am self-taught in the little I know of programming and Drupal.

Is there a way for me to just jump in to the regular submission handler and say, "hey, put my field here instead!"?

Thank you for your time.

Wow. I puzzled on this all day and 30 minutes after asking this question, of course I find the answer.

Since the $form['submit'] part is an array, you can have more than one handler there! I changed the lines

$form['submit'] = array(
    '#type' => 'submit',
    '#value' => 'New Submit Button',
    '#submit' => array('my_module_form_submit'),
);
unset($form['actions']);

to simply be

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

and that's it! Now it does the regular registration submission handler and also mine.

Thanks!


Load custom library when form contains special field type I'm writing a custom field in Drupal 8. I added a custom library that contains js and css to my module. They will be loaded on forms. Now I need a way to load the library only when some special field is placed in the form.

How can I check if a form contains a field with field type X?

function rate_field_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
   if(/*Check if form contains field with type X*/)
   {
      $form['#attached']['library'][] = 'rate_field/admin-star-field';
   }
}

I addedsome values in the render array of the formElement method in my customWidget class.

'#attached' => array(
    'library' => array(
      'core/jquery',
      'rate_field/admin-star-field',
    ),


Change colors of account I have created a field(select list) with some colors. I want to let my site users choose the color (color of menus, blocks ...) of their account.

How can I do this?

In my example I will assume that you have a color field called color (machine name: field_color) already set to user fields admin/config/people/accounts/fields

By following these steps you'll be able to achieve what are you looking for.

Create Drupal custom module. Ref Creating modules.
Implement hook_init to your custom module
In the hook_init you need to implement drupal_add_css
Set HTML elements you need to let users to change; according to current user color selection.
The final code should look like the following:

function MODULE_NAME_init() {
  global $user;
  $account = user_load($user->uid);

  if(isset($account->field_color['und'])) {
    $color = $account->field_color['und'][0]['value'];

    drupal_add_css(t('#menu { background-color: #@color; }', array('@color' => $color)), array(
      'type' => 'inline',
      'media' => 'screen',
      'weight' => '10000',
    ));
  }
}

Note: change MODULE_NAME to your desirable module name.


REST Server with my module service returns 404 I have set up my drupal REST using REST Server and services. Also I have created my own module which implements hook_services_resources().

I have configured REST with to use my resource and node.

This works:
http://local/rest/node/1

This does not work (returns 404):
http://local/rest/hotel_search

Here is my module:

function MY_MODULE_services_resources() {
    return array(
        'hotel_search' => array(
            'retrieve' => array(
                'help' => 'Search for Hotels',
                'callback' => 'MY_MODULE_hotel_search',
                'access callback' => 'MY_MODULE_access_callback',
                'args' => array(
                    array(
                        'name' => 'name',
                        'description' => 'hotel name',
                        'type' => 'int',
                        'source' => 'param',
                        'optional' => false,
                    ),
                ),
            ),
        ),
    );
}

function MY_MODULE_access_callback() {
    return true;
}

function MY_MODULE_hotel_search() {
    $json = array(
        'name' => 'response',
        'status' => 'ok'
    );
    return json_encode($json);
}

With the Services module, the "CRUD" resources are typically mapped only to entities, and routed to each based on the HTTP method:

GET -> Retrieve
POST -> Created
PUT -> Update
DELETE -> Delete

When building a custom service resource, you need to use the actions array when building your resource. In your example, your resources array would become:

return array(
  'my_module_resources' => array(
    'actions' => array(
        'hotel_search' => array(
            'help' => 'Search for Hotels',
            'callback' => 'MY_MODULE_hotel_search',
            'access callback' => 'MY_MODULE_access_callback',
            'args' => array(
                array(
                    'name' => 'name',
                    'description' => 'hotel name',
                    'type' => 'int',
                    'source' => 'param',
                    'optional' => false,
                ),
            ),
        ),
    ),
  ),
);

Your callback can just return an array or object, it doesn't need to encode the result, because Services will automatically do that based on the extension on the URL, e.g. .json.

You'd then make a call to it with a POST to:

?q=rest/my_module_resources/hotel_search.json


Why doesn't my form submission handler work? I am new to drupal and require help from Gurus.

I am adding some form elements in the status share form by using hook_form_alter(). These elements are getting displayed in the form, but my submission handler is not working. I am using $form['#submit'][] = 'my_module_form_submit'; to add it to the form.

function my_module_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == "statuses_box") {
    $form['tech2'] = array(
      '#type'=>'select',
      '#title' => '',
      '#attributes' => array('class' => array('tech2')),
      '#options' => array('All'=>'All','New'=>'New',),
      '#multiple' => false,
    );

    $form['#submit'][] = 'my_module_form_submit';
  }
}

function my_module_form_submit($form, &$form_state) {
  // Do something here.
}

The issue I am getting is my_module_form_submit is not getting called. The debugger break-point is not getting hit in this function
I am not getting error message neither on page nor in admin/reports/dblog
What I want is to add a new row in my custom data table, which this code is supposed to create.
Default form handling is running perfectly.

Check your form id. I doubt your form id is not correct. Even you can try this also -

function my_module_form_submit($form, &$form_state) {
  // Do something here.
  echo "<pre>";
  print_r($form);
  exit;
}


taxonomy menu links change with path Is there any way to change taxonomy menu links depending on path? I have a Taxonomy menu in a block with different levels and depending on path I would like to change the taxonomy level depending where the user is. Context maybe?

Thanks in advance!!

Sounds to me like you ACTUALLY want Menu block in tandem.

  So… have you ever used the Main and Secondary menu links feature on
  your theme and wondered “how the hell do I display any menu items
  deeper than that?”

I think the following is what you're after, but the module is pretty configurable if I'm mistaken.

Create your taxonomy menu as you normally would, and instead of putting that menu block in the sidebar (or wherever), put a menu block generated block there. Then in the settings for the menu block click Advanced. Under this tab, there's now a chekbox titles Make the starting level follow the active menu item. If you check that box, then the top level will reflect the current page.


Render first element of a multivalued field On my site I've an image field, multi value.
I would like, on a custom view mode, to display only the first image. On the field formatter I don't have this option.

How should I do this? Directly from twig or I've to use a preprocess function?

[EDIT] I would to do this without using a custom node template :)

Then it's

{{ content.field_name[0] }}

  Note: If you need to print the label use {{ content.field_name['#title'] }} as {{ content.field_name[0] }} does
  not print the label.


Setting up a grid to carousel? Alright everyone, I'm sure this is a relatively simple thing, but I'm on the verge of tearing my hair out.

What I'm trying to accomplish is setting up images to appear in a grid, that when clicked pulls up a gallery/carousel, allowing you to scroll through the images there as well.

I've downloaded the slick modules, and correct dependencies. I also have bootstrap correctly set up as well. Honestly if you have an alternative your prefer more, please let me know.

https://www.drupal.org/project/slick
-https://github.com/kenwheeler/slick/
-https://github.com/gdsmith/jquery.easing
https://www.drupal.org/project/slick_media
https://www.drupal.org/project/media_entity_image
https://www.drupal.org/project/video_embed_field
https://www.drupal.org/project/blazy

Drupal 8

I prefer the Lightgallery module which is available for Drupal 7 and Drupal 8 also. It integrates the lightGallery jquery plugin into Drupal. This is compatible with Views and it also provides an image field formatter.

You can see demos for the lightGallery jquery plugin here.