How to alter my query in hook_views_query_alter to use the right where expression? I am displaying a fee schedule using views and need to skip paid fee schedules. For that, I need to add following JOIN in views query using hook_views_query_alter().

LEFT JOIN ic_fee_schedule_payments AS FSP ON fee_schedule.fid = FSP.fid AND fee_schedule_students.uid = FSP.uid AND fee_schedule_instalments.iid = FSP.iid

with added where clause as:

AND FSP.pid IS NULL

I have tried the following code in hook_views_query_alter(), but it does not work.

# In order to add a new table to join, you'll need to create a new views_join object.
    $join = new views_join;
    $join->construct('fee_schedule', 'fee_schedule_payments', 'fid', 'fid');
    $join1 = new views_join;
    $join1->construct('fee_schedule_students', 'fee_schedule_payments', 'uid', 'uid');
    $join2 = new views_join;
    $join2->construct('fee_schedule_instalments', 'fee_schedule_payments', 'iid', 'iid');
    #$join->extra = array(array('table' => 'fee_schedule_payments', 'field' => 'pid', 'operator' => 'IS', 'value' => 'NULL'));
    // $join is the views_join object created above
    $query->add_relationship('fee_schedule', $join, 'fee_schedule_payments');
    $query->add_relationship('fee_schedule_students', $join1, 'fee_schedule_payments');
    $query->add_relationship('fee_schedule_instalments', $join2, 'fee_schedule_payments');
    $query->add_where('fee_schedule_payments', 'fee_schedule_payments.pid', 'NULL', 'IS');

EDIT: Tried the other way but still does not work.

$join = new views_join;
    $join->construct('fee_schedule', 'fee_schedule_payments', 'fid', 'fid');
    $join->extra = array(array('table' => 'fee_schedule_payments', 'field' => 'uid', 'operator' => '=', 'value' => 'fee_schedule_students.uid'), array('table' => 'fee_schedule_payments', 'field' => 'iid', 'operator' => '=', 'value' => 'fee_schedule_instalments.iid'));
    $query->add_relationship('fee_schedule', $join, 'fee_schedule_payments');
    $query->add_where('fee_schedule_payments', 'fee_schedule_payments.pid', 'NULL', 'IS');

Am I missing something or need to alter query in some other way?

I'm not 100% sure, but I think to add the "IS NULL" part, you may need spaces around "IS" such as:

$query->add_where('fee_schedule_payments', 'fee_schedule_payments.pid', 'NULL', ' IS ');

OR...maybe something using add_where_expression...

$query->add_where_expression(0, 'fee_schedule_payments.pid IS NULL');


Responsive Layout of multi-page website in Adaptive Theme I've read the book 'responsive web design' by Ethan Marcotte over the week & gone through the documentation on Adaptive Theme website, however, I'm confused about how to take responsive theming forward in Adaptive Theme when I have multiple web pages with their own CSS files.

From the documentation on Adaptive Theming, we have to split the CSS for each layout into its individual file (responsive.smartphone.landscape.css; responsive.desktop.css). Does that mean, we would have the full site CSS in one file for responsive.desktop.css? (! surely thats not right).

The way we have done thus far (in its current form, website is not responsive) is that there are small CSS files for each different regions/ areas of the page. In addition to this, we have custom modules with their own CSS files. How would we go about taking this mass of CSS files & distributing the code into responsive files in Adaptive Theme?

The more recent methods concerning responsive design is "mobile first". It's more time consuming to theme a desktop site and then bring it down it pieces to a mobile version, but some of this goes into the initial architecting as well. But, this is another topic.

You should keep your CSS as generic as possible at first, then drill down to specific items when you need to. Something you might want to look into is using a CSS preprocessor like LESS or SASS. On our projects (generally using LESS), we make CSS files for different regions of the site. Header, content, sidebar, footer, mobile, etc. and then compile them all into a few CSS files. In this screenshot, you can see the different sections broken up and they're all compiled into the global.css (the others are direct).


Send email to webform submissions when new content is created I have a webform on my site, which collects names and email addresses, for the purposes of receiving content updates. When a new piece of content of a specific content type is added, I want to be able to send the email addresses collected in that webform a message, letting them know that new content has been added.

I've been able to set up rules to send a notification to one specific email address. However, I am struggling with sending to the email values collected in the webform.

I've added the Webform Rules module, and have PHP Filter turned on. However, I'm unable to send. Any help, or PHP code to accomplish what I'm looking to accomplish would be greatly appreciated!

Thanks in advance!!

how about direct get data from database? If you add hidden field and the default value will be [current-page:query:sid]. Use php code to get the data. Example: $raw = db_query("SELECT AGE.data AS age FROM webform_submissions S
    LEFT JOIN webform_submitted_data A ON A.sid=S.sid AND A.cid=1
    LEFT JOIN webform_submitted_data AGE ON AGE.sid=A.sid AND AGE.cid=2
    where [current-page:query:sid] = A.sid)->fetchAll();

I dun know I have not tried to code yet. Hope its can help you.


Remove separator from breadcrumb How can I remove the < from the breadcrumb I tried implode('<', $value['data']) but no luck

   function bootstrap_fit_breadcrumb($variables) {
            $breadcrumb = $variables['breadcrumb'];

            if (!empty($breadcrumb)) {
              //$breadcrumb[] = drupal_get_title();
              $breadcrumbs = '
';

              $count = count($breadcrumb) - 1;

              foreach ($breadcrumb as $key => $value) {
                  if ($key==0) {
                    $breadcrumbs .= '
' . $value . '
';
                  } else {
                   $breadcrumbs .= '
' . $value['data'] . '
';

                  }
              }
              $breadcrumbs .= '
';
              return $breadcrumbs;
      }
   }

displaying

Home < Financial Services

Have you reviewed this page?

https://api.drupal.org/api/drupal/includes%21theme.inc/function/theme_breadcrumb/7

Also, what theme are you using? I would check the base theme to make sure that it isn't preprocessing the breadcrumbs itself. If so, you'll need to make sure you are calling the appropriate function in order to override the breadcrumb settings.


Difference between browser session and Drupal session After reading this question over here from 2014, I'm left wondering:

Is there any benefit, security concern, or real reason to use Drupal's session manager class over the browser session $_SESSION[key]?

Specifically wondering about the Symfony session API that was mentioned in the above linked question and whether or not that provides any benefits over the way i'm storing and accessing session data.

'The Drupal Way':

$tempstore = \Drupal::service('user.private_tempstore')->get('mymodule_name');
$tempstore->set('my_variable_name', $some_data);

How I'm currently doing it:

$_SESSION['three_minute'] = array();
$_SESSION['three_minute']['utility'] = $form_state->getValue('utility');

What you are describing is not Drupal session vs. Browser session. There's just one session, always managed by Drupal (partially by using Symfony code. But it's still Drupal).

The (private) tempstore is just a custom storage that used to be provided by ctools in 7.x. For anonymous users, it actually requires a session to be present, as it uses the session ID to identify the entries.

The main difference is that session data is always loaded, on every request. While for the tempstore, you control when and what is loaded. If you have data that is small and you need on many/all pages, use the session directly. If you have big objects, consider using a temp store.

Drupal itself uses the tempstore for example to store node objects for the preview feature and views while editing them.


Using hook_menu() with hook_permission() - Access denied Can someone see anything wrong with this hook_menu() and hook_permission() code? I am able to see the permissions in the admin menu, admin/people/permissions. I allow access to los user front for authenticated users and save the settings. Then, I  clear all caches and try to access los/register. I am getting You are not authorized to access this page. when I try with either administrative or authenticated users. I have cleared the cache, logged in and out and even closed the browser and restarted it refreshing ever step of the way.

/**
 * Implements hook_permission
 */
function los_permission() {
  return array(
    'los user front' => array(
      'title' => t('LOS User Frontend'),
      'description' => t('Access to LOS user frontend.'),
    ),
    'los user back' => array(
      'title' => t('LOS User Backend'),
      'description' => t('Access to LOS user backend'),
    ),
    'los admin back' => array(
      'title' => t('LOS Administration Backend'),
      'description' => t('Access to LOS administration backend.'),
    ),
  );
}

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

  $items['los/register'] = array(
    'title' => 'LOS Register',
    'description' => 'Large order system registration page',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('los_register'),
    'access arguements' => array('los user front'),
  );

  //... more $items here ...

  return $items;
}

It's access arguments not access arguements :)


Drupal 6.22 - Colorbox plugin missing I can't seem to get the colorbox plugin (colorbox-6.x-1.0) working with my Drupal 6.22 site. I'm currently working on Ubuntu Natty, and this is the folder structure for how I have the plugin and module setup:

 - sites
    - all
       - libraries
          - colorbox
             - colorbox
                - jquery.colorbox-min.js
                - jquery.colorbox.js
             - [other folders: content, examp1, examp2, examp3, examp4, examp5]
    - default
       - modules
          - colorbox
             - colorbox.module
             - etc, etc

Other stuff I already have done:

jQuery Update plugin installed
set permissions on sites/all/libraries folder using chmod a+w ~/public_html/drup_test/sites/all/libraries
flushed all caches

I'm still after all of this getting the "You need to download the Colorbox plugin and extract the entire contents of the archive into the sites/all/libraries/colorbox folder of your server" error. Please could someone help me as I don't know what else could be the problem.

Thanks!

EDIT: SOLVED!!

With iStryker's help, I realised that there was some weird permission setting on the /sites/all folder. Whilst I haven't sorted out the permission issue on that folder, this alternative worked (if this has also happened to you)...under /sites/default/ create a folder called libraries and put your jQuery plugins there. Then in Drupal Admin > Administer by Module > Colorbox > Colorbox Plugin Settings, change the plugin path to /sites/default/libraries/colorbox. Not the grandest solution, but it works!  Note that this also worked for the ShadowBox module and plugin.

Revised:

Your directory structure is correct.  Your file directory permissions are not.  Your chmod a+w command gives read and write permissions.  In your case, to get rid error message you must have read and execute permission on the /sites/all/libraries/colorbox & /sites/all/libraries/colorbox/colorbox directories and read permissions on the 2 javascript files.   Colorbox.module does a file_exist call

if (file_exists($library_path .'/colorbox/jquery.colorbox.js') && file_exists($library_path .'/colorbox/jquery.colorbox-min.js')) {

Depending on your operating system, and setting, PHP's file_exists() function is handle differently.


AJAX error on form alter I have a form alter function, it seems working fine, but, i am getting this strange error, i am not able to figure this out. Please help me out. I have a dependent dropdown. I am pulling 1st level vacabulory in 1st dropdown. 2nd dropdown is basically the childrens of the parent chosen from the 1st dropdown. The code works, but give me error.

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

  if($form_id == "teacher_profile_node_form"){

        $form['field_teacher_city'] = array (
           '#title'   => 'City',
           '#type'    => 'select',
           '#options' => _teacher_city_options_list_taxonomy(),
           '#ajax'    => array(
                'event'=>'change',
                'callback' =>'_teacher_location_list_dropdown',
                'wrapper' => 'edit-field-city',
                'method' => 'replace',
                )
          );

      $form['field_teacher_locations'] = array(
           '#title'   => 'Location',
           '#type'   => 'select',
           '#options' => get_dropdown_list(),
           '#prefix' => '
',
           '#suffix' => '
',

       );
     }

    return $form;
}

function get_dropdown_list() {

      $options2 = array(
        0 => t('Zero'),
        1 => t('One'),
        2 => t('Two'),
        3 => t('Three'),
           );

return $options2;
}

function _teacher_location_list_dropdown($form, $form_state)  {
  // use this method to populate the demo list from the list of courses
  $vocab = taxonomy_vocabulary_machine_name_load('locations');

  $vid = $vocab->vid;

  $sel = $form_state['values']['field_teacher_city'];
  drupal_set_message($sel);

  if (!isset($sel)) {

      $options = array(
        0 => t('four'),
        1 => t('five'),
        2 => t('six'),
        3 => t('seven'),
           );

  }
  else {
      $terms = taxonomy_get_tree($vid,$sel,1,FALSE);

      $options = array();
      foreach ($terms as $term)  {
    $options[$term->tid] = $term->name;
      }
  }

  $form['field_teacher_locations']['#options'] = $options;

  return   $form['field_teacher_locations'];
;
}

Error is below

Warning: array_values() expects parameter 1 to be array, string given in _field_filter_items() (line 515 of C:\wamp\www\drupal-7.19\modules\field\field.module).
Warning: Invalid argument supplied for foreach() in list_field_validate() (line 392 of C:\wamp\www\drupal-7.19\modules\field\modules\list\list.module).

You're not supposed to change the $form element in the AJAX callback, only in the form_alter function. Otherwise,

  when the form is submitted (ajax or not), the submitted form does not
  match the cached form, which causes Drupal to fail


How can I output markup fields or descriptions in my Webform email? I have a webform that requires a markup field, or alternatively, a description to be carried through to the email or "View form submission" page.

Typically one can put the token %email_values in the email template which will give a list of fields and their labels that are submitted to the form - but this doesn't seem to include markup fields, or field descriptions.

I have tried using other tokens such as %post or %value. For instance, I have a markup field with machine name "foo" in a fieldgroup "bar", and putting %value[foo][bar] just dumps the string [foo] into my email.

So is there a way to reference these parts of the webform?

Did you tried using this? If the markup field foo sits within the fieldgroup bar, you need to inverse the order and the last % shouldn't be there.

%value[bar][foo]


How to catch username or password using hook_form_alter I need to catch username/password using the hook_form_alter(). I'm using this code:

function sds_form_alter(&$form, FormStateInterface $form_state, $form_id ) {

  if (in_array($form_id, ['user_login_block_form', 'user_login_form'])) {
    $username= $form_state->getValue('name');
    echo "Username Value".$username;
  }

}

but it returns null. What am I missing here?

You can use in VALIDATE function like

$form['#validate'][] = 'mymodule_user_validate';

In this you can all values even if there is no successful values in it.
But remember to call your function first before default validate function.


Dynamic site title based on role and/or content type I need to dynamically change the Drupal site title to match the role the current use has, or as an alternative option I need to be able to change it based on the content type that is being viewed (on my installation, each role has it's own content).
How can i do that? I'm using Drupal 6

As much as I know the site name is being output with $site_name in a basic Drupal 6 page.tpl.php file and is also part of the $head_title variable. To change them dynamically you could use template_preprocess_page() in your template.php file. Assuming you want to change one or both of those variables based on the user role you could use the following example:

function mytheme_preprocess_page(&$variables) {
  global $user;
  if (in_array('administrator', $user->roles)) {
    $head_title = explode(' | ', $variables['head_title']);
    $head_title[1] = 'Title for admin';
    $variables['head_title'] = implode(' | ', $head_title);
    $variables['site_name'] = 'Site name for admin';
  }
}

Both the head title and site name variables are modified for the 'administrator' role in this case. It should be relatively simple to make this work for all roles the way you want if writing some custom code is not an issue.


Adding hundreds of fields to a content type in Drupal 6 I have over a hundred fields to be added.

How can I use CSV or SQL statement to add these fields in Drupal? Is there any module to do this?

The one time I had to do something like that (it was a Drupal 6 site) I exported the content type, edited the export manually (lots of copy-paste and search-replace) and imported it back into my site.

That said, a content type with hundreds of fields is going to be huge. I'm afraid that it's going to be a nightmare for your editors, terrible to maintain, and it might hurt performance as well. If I ever needed a content type with hundreds of fields, I would stop right there and start re-thinking my site architecture.


Creating a Faculty and Staff Directory with Links to their Profile Pages If I add a field to a regular content type, I can configure that field in a view to link to the page for that content type.  On the other hand, if I add a field to a User type, it seems that I cannot link that field in a view back to the user profile.  How can I link a User field to the respective user's profile page?

Cheers.

The short and simple answer is there is no way to link a custom User field to the user page itself.  However, this can be achieved by manipulating the view to expose the pertinent field data.

The situation is we have a couple of custom fields added to a User type.  These are last and first name fields (field_last_name and field_first_name, respectively).  Unfortunately there's no easy way (or is there?) to link these fields directly to their respective user's profile page through Views.  I have posted an answer below that goes the theming route by creating .tpl.php files, but we don't want to do that because we also work with people who aren't coders.  So how do we do this without code?  WITNESS THIS!

Let's say we want to display a list of users' names, titles, phone numbers, email address in tabular format on a page.  Great, pretty standard.  Do the following (I will assume you've created the page already in Views):

Add the User: Name (the one built into Drupal), field_last_name and field_first_name fields, rearrange them so that they're at the top, and then (this is VERY IMPORTANT), exclude them from being displayed
Add the field_last_name and rearrange it so that it's below the first two instances of field_last_name and field_first_name

Now, we're going to configure the last field that should be in the list: field_last_name.

Set it's label to Name
Open up the Rewrite Results pane
Check off 'Rewrite the output of this field' and 'Output this field as a link'
Under 'Output this field as a link', check off 'Use absolute path'
For the Rewrite text area, enter "[field_first_name] [field_last_name]"
For the link URL, enter "users/[name_1]" (name_1 might not be the same for you, just use whatever == User: Name when looking at the Rewrite Patterns

Apply and Save

You can edit your table settings so that it's displaying the way you want it to display.  You should now have a collection of names that link directly to their users' profile pages.

Essentially, we've exploited the rendering order of the fields.  Since we organized our fields such that the username, first name, and last name came before every other field, their values were available to the Rewrite processor in the remaining fields.

The reason I chose the field_last_name field, was because that if you choose to enable column sorting on the table, then the table will still sort on the initial value provided by that field, and not the rewritten result.  I wanted to sort by last name in my own case, this may differ for you.

Also a note, I have presupposed that you are using Pathauto to create friendly URLs in your website, and so the path to a user profile would look like http://site/users/username rather than http://site/users/uid.  If this is not the case for you, and you'd like to use the UID field instead, substitute out the User: Name field for User: UID, and the procedure shouldn't change besides that.

Hope this helps someone, I was pulling out my hair for a long time until I figured out this little gem.


How do I direct users to my custom search? I'm trying to use hook_search_execute to run a custom search inside my module:

function mymodule_search_execute($keys = NULL, $conditions = NULL) {
    die; // just to see if we get called
    // lots of lines copied from the hook_search_execute doco
    return $results;
}

I can get the default Drupal search form inside my page.tpl.php with:

<?php print render(module_invoke('search', 'block_view', 'search')); ?>

But, when I click the "search" button on that form, my custom search isn't called.

I'm using D7. What's the appropriate way to actually force a search to get results from my custom search function?

I would use hook_form_alter() to alter the default search form to call your own submit function.

So, in your custom module do something like this:

// Alter regular search box
function YOURMODULENAME_form_alter(&$form, &$form_state, $form_id) {
  if($form["#id"] == 'search-block-form') {
    // Add any additional fields or things you need here

    ...

    // Modify the submit handler that is called
    $form['#submit'] = array('YOUR_CUSTOM_search_submit');
  }
}

This actually modifies precisely that block search form, so including the search block just like you've described in the template file should work once you've implemented the form alter.


How do I resolve a merge conflict with features? This might seem basic, but I am new to Drupal (and, to and extent, git).

I've made some changes to a Feature and downloaded its files to be pushed up to the remote server with git. However, I get the following merge conflict:

<<<<<<< HEAD
  $pane->uuid = '992af322-74c5-4a5c-a261-1e73677d3645';
  $display->content['new-992af322-74c5-4a5c-a261-1e73677d3645'] = $pane;
  $display->panels['content'][2] = 'new-992af322-74c5-4a5c-a261-1e73677d3645';
=======
  $pane->uuid = 'bf806592-c85c-4155-a97c-516f72427e4e';
  $display->content['new-bf806592-c85c-4155-a97c-516f72427e4e'] = $pane;
  $display->panels['content'][2] = 'new-bf806592-c85c-4155-a97c-516f72427e4e';
  $pane = new stdClass();
>>>>>>> refs/heads/my-branch

I would know what to do with a conflict with other code, but this is all very foreign to me and I don't want to break anything.

Would anyone know the best course of action here?

Check the panes with the following uuid "bf806592-c85c-4155-a97c-516f72427e4e"
and "992af322-74c5-4a5c-a261-1e73677d3645".
Check which one should not be there and remove it from the code.


looking for equivalent webform select view module on Drupal 8 I am a new to Drupal 8

I am trying to make select options with webform submission.

What module do I need?
and
How can I make this select options with that module?

Thank you very much!

implement

I believe what used to be webform_views_select module is part of Webform core for Drupal 8.

You can search for entity and choose any of the following elements

configure an entity reference view to be use as options

NOTE1:  Due to perhaps this issue entity reference is not recognized by webform the way outlined above, but it should work if core patch in #7 is applied (as confirmed by reports in this issue)

NOTE2:  Perhaps a work around would be to use content or taxonomy term instead of a view (since view reference is not working) if you don't have great need for views filtering capabilities.


How to combine two contents of same type and display in views How to combine two contents of same type and display in views?

the following picture will clear my question.

There is a module for that, Views Merge Rows. From the project's description:

  Sometimes when you use relationships in views you get a number of rows
  with the same content in some of the fields. This results in a huge
  table (grid, list, etc.) that affects the usability of your view. The
  Views Merge Rows module provides a way to combine rows with the same
  content in the specified fields.

Keep in mind that there is a pretty straightforward guide to configure the module in the project's page that includes very descriptive screenshots.


How to set up registration for event with parallel sessions? I would like to set up the registration for an event.
During the event there are various parallel sessions.

(I was thinking in using the entity registration module)

Needs / problems encountered:
The (registered) user needs to chose the session he/she would like to attend (shouldn´t be possible to sign in for sessions given at the same time!)
Each session has a maximum capacity.

Any idea how to achieve this?

Thanks in advance

Make a node type for sessions, then add the registration field to it. You should make a small module which compares a time/date range/duration field on your session node types to ensure the user cannot register for sessions that are conflicting.

If you have multiple events on your site, consider making a node-reference field to another node type: "events". Then update your session conflict module to take events into account.

This is for Entity Registration (D7)


Load PDF through colorbox I am trying to load a PDF from a link using colorbox but although the colorbox window opens the pdf is just text characters. This is what the link looks like:

This is what my link looks like:

View

and when it's rendered out it looks like this:

View

which looks right to me but the pdf is just text characters. The pdf loads fine just as a link opened in your browser.

I suggest you, use this module https://www.drupal.org/project/pdf_to_imagefield since colorbox is designed to display images.

If you still want to show the complete pdf. You could embed it in a basic page:

        Download file

You can then reference the page by node id.

 Link name


How do I modify the attributes of ? I need to be able to change attributes (like class, data-toggle, data-direction) of the label itself, at a PHP level, in a way that will support conditions in form definition function.

The solution given in How can I add a class to a label? doesn't work for my problem, as they are only workarounds that will not work with the theming JavaScript I need to expose my data to. Also, they are pretty much limited to styling, and that's only one of the attributes that may be needed.

I'm OK with only having limited, predefined sets of attributes, as long as I can select one at the time of form building.

Solution is to implement theme_form_element_label.

Changing one line from:

$attributes = array();

to:

$attributes = isset($element['#label_attributes'])?$element['#label_attributes']:array();

in your implementation makes it possible to use '#label_attributes' just the way you would use normal #attributes.

NOTE: If your parent theme defines this function already, then you need to copy function from parent theme, not from form.inc.

Full implementation, to put in template.php:

function mymodule_form_element_label($variables) {
  $element = $variables['element'];
  // This is also used in the installer, pre-database setup.
  $t = get_t();

  // If title and required marker are both empty, output no label.
  if ((!isset($element['#title']) || $element['#title'] === '') && empty($element['#required'])) {
    return '';
  }

  // If the element is required, a required marker is appended to the label.
  $required = !empty($element['#required']) ? theme('form_required_marker', array('element' => $element)) : '';

  $title = filter_xss_admin($element['#title']);

  // NOTE: CHANGED LINE BELOW!
  // If there are attributes already, use them. If not, create empty array.
  $attributes = isset($element['#label_attributes'])?$element['#label_attributes']:array();

  // Style the label as class option to display inline with the element.
  if ($element['#title_display'] == 'after') {
    $attributes['class'] = 'option';
  }
  // Show label only to screen readers to avoid disruption in visual flows.
  elseif ($element['#title_display'] == 'invisible') {
    $attributes['class'] = 'element-invisible';
  }

  if (!empty($element['#id'])) {
    $attributes['for'] = $element['#id'];
  }

  // The leading whitespace helps visually separate fields from inline labels.
  return ' <label' . drupal_attributes($attributes) . '>' . $t('!title !required', array('!title' => $title, '!required' => $required)) . "</label>\n";
}


How to attach token in a custom form field I have a custom form in Drupal 8. I need to attach tokens for fields of my form. Basically I want to add "Browse tokens" option for each field of my form.

token.module has various examples, for example this:

// Add the token tree UI.
$form['email']['token_tree'] = array(
  '#theme' => 'token_tree_link',
  '#token_types' => array('user'),
  '#show_restricted' => TRUE,
  '#weight' => 90,
);

This displays a link for tokens for the type user (and global tokens).

You can also use the #element_validate callback token_element_validate together with also adding #token_types to have it validated.


Display a Block for mobile only without creating new theme I'm trying to display a main navigation menu block but ONLY for the site when it's viewed on a mobile. I need to do this without creating a new theme to do so though so it all works on 1 theme only.

Any ideas how this can be done?

Thanks

Take a look at the Browscap Block module. Here is a quote about it (from the module's project page):

... adds visibility options to block configuration settings to allow you hide or show blocks in mobile devices.
If you are looking for the same thing for Panel panes check out Browscap CTools.


"Add link" in my account menu The user account page (http://example.com/user) consists of some default tabs like  "View," "Edit," etc.

I want to add my menu link over there. The content to be returned should depend on the user ID. How do I do this?

If you just want to add a new tab, then the module should just implement hook_menu(), using code similar to the following.

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

  $items['user/%user/new_tab'] = array(
    'title' => 'New tab title',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('mymodule_newtab_form', 1),
    'access arguments' => array('access new tab'),
    'type' => MENU_LOCAL_TASK,
  );

  return $items;
}

function mymodule_newtab_form($form, &$form_state, $account) {
  // ...
}

mymodule_newtab_form() would get the user object in $account. That menu callback would build a form using the form API. If the purpose is to output, the menu callback declaration would be similar, except two array indexes, which would be:

'page callback' => 'mymodule_newtab_form',
'page arguments' => array(1),

The argument passed to the callback would be different too.


Entity view mode and form mode schema node_type_example module provides a file that defines form display configuration for a custom node type defined in this module. The file is named core.entity_form_display.node.basic_content_type.default.yml.

The example file clearly sets some field settings but is there a a schema for these config files? How to build my own config file for view mode and form mode?

First, form/user mode and form/user display isn't the same thing.

But the schema for all of them is in in core/config/schema/core.entity.schema.yml.

That said, I'm not sure why you want to build that file? Especially for a node type. Create the node type and the fields, configure the form and view displays in the UI, export it, add the files to your modules, don't. You don't have to build them yourself.


How does an entity get printed into a page after going though the page callback function? This following code snippet is the value of page callback from hook_menu(). However, I cannot connect entity_view and the page template. How can I print or access the entity_view returned in this code from  my page template?

function example_task_view($task) {
  drupal_set_title(entity_label('example_task', $task));
  return entity_view('example_task', array(entity_id('example_task', $task) => $task), 'full');
}

You should pass the array of fully-loaded entity objects to the entity_view function, not only the id.

For example:

...
$entity = entity_load('example_task', array($task);
return entity_view('example_task', $entity, 'full');


Block configuration per region Anyone ever accomplished building a module that manages to have block configuration per instance?

The main issue with blocks is that each block does only one thing no matter where it shows up, you can't have the same block taking different parameters based on eg region.

If you just need the functionality, you can try MultiBlock to see if it fits your needs:

"Each block has a 1:1 relationship with its region, weight, visibility (and other) settings. This means that it is impossible to have blocks in multiple regions or to have blocks that have different settings on different pages. MultiBlock module solves this problem by allowing you to create multiple Block Instances of already existing blocks."

However, you question is about being able to accomplish building a module that manages this. So, yes, I recently did something similar. I needed a homepage with blocks displaying a list of articles, each one with custom options (e.g. different categories, with / without images, etc.) and also in different regions across the site. I created one module, and then instead of having each block with a harcoded-fixed name, I generate the block's names ($delta) dynamically, like this:

function MY_BLOCK_block_info() {
  // Instead of having a static number of blocks, let's choose how many
  // we want, via the administration.
  $blocks_qty = variable_get('MY_BLOCK_blocks_qty');
  for($i = 1; $i <= $blocks_qty; $i++) {
    $blocks['MY_BLOCK-' . $i] = array(
      'info' => t('My block ' . $i),
      'cache' => DRUPAL_CACHE_PER_ROLE,
      'region' => BLOCK_REGION_NONE,
    );
  }
  return $blocks;
}

Then you will have different names for each block (MY_BLOCK-1, MY_BLOCK-2, etc). So you can individually configure them like this:

function MY_BLOCK_block_configure($delta = '') {
  $form = array();
  $parts = explode('-', $delta);
  $block_number = $parts[1];

  // Your form here...
  $form['MY_BLOCK_' . $block_number . '_title'] = array( ...

So, in the general Configuration page you get to choose how many blocks you want to generate. And then, in the individual block's configuration page you choose the individual block's settings.


How can I download specific dev version of Drupal module? What to do when I want specific dev version of Drupal module.

For example:

Geocoder dev version from Jan 07 2016 is broken. Latest working dev version was from Sept 01 2015.

How can I download previous dev version of Drupal module (Geocoder in my case)? Any method is welcome.

For the easiest way to do it:

Go into the repository
Select a version there and click on it
There will be hash of commit (example)

So, you know the hash of commit - just clone this module from repository and switch to required hash of commit.

How to clone module via git

How to checkout the specific commit

Example:

git clone --branch 7.x-1.x https://git.drupal.org/project/geocoder.git
cd geocoder
git checkout c994066d58bc7518bc9796c60d4d43f98ae477cd


Hide comments and show them using views Am using views to display the comments below my node types in drupal 7.

The view works fine but i can't find a way to hide the regular drupal comments above the form.

How do i just display the comment form and the comments using views.

In node.tpl

    hide($content['comments']);

This hides both the comment form and the comments.

To render the comment form alone use

    print render($content['comments']['comment_form']);

Then you can create your view for them nice comments and display them below the form.


How can I get translation for a field of custom date I am using the paragraphs module. I have a field which contains a date and time e.g. for events, which is added by an author. For the output I use a paragraph-twig-file and I have this:

<div class="timeline-date">
    {{ content.field_date }}
</div>

In the backend of Drupal I created a custom time "D, d.m.Y - H:i". The output is right e.g. "Fri, 24.08.2018 - 17:14", but my site is in german and not english. So how, can I translate the day of week in german?
In my case this solution is not working

In Twig, you can use built-in translation contexts. I had to output my dates in dutch format. The default formatting was:
{% set date = node.created.value|date("j") ~ ' ' ~ node.created.value|date("F") ~ ' ' ~ node.created.value|date("Y") %}
// now {{ date }} outputs: 8 August 2020

When I use translation contexts, it worked as expected:
{% set date = node.created.value|date("j") ~ ' ' ~ node.created.value|date("F")|t({}, {'context' : 'Long month name'}) ~ ' ' ~ node.created.value|date("Y") %}
// now {{ date }} outputs: 8 augustus 2020

More about translation contexts in Twig: https://stefvanlooveren.me/blog/translate-dates-twig-drupal-8


How do I enable and weight fields through .yml? I have a custom module where I succesfully created a field for videos. But I want the field to be enabled and weighted on by default. I supposed active and widget->weigth and display->weight was the way to go but it's disabled.

id: media.field_video_alt_text
field_name: field_video_alt_text
entity_type: media
bundle: video
label: 'Alternativ tekst'
description: 'Kort beskrivelse som vises under videoen. Lad feltet være tomt, hvis dette ikke ønskes.'
required: false
translatable: true
default_value: {  }
default_value_callback: ''
settings: {  }
field_type: string
active: true
widget:
  weight: 2
display:
  weight: 1
  label: hidden

Adding formatters or widgets to field configuration doesn't work. You have to add them to the existing display modes in hook_install().

See entity_get_display and entity_get_form_display, which are deprecated, but contain examples how to add components to display modes and code replacing the deprecated functions to load the entity displays.


Archive page for custom content I want to create an archive page for a custom content type.  Essentially list them all on a single page.

I understand that I need to create a module, and implement hook_block_info() and hook_block_view().  What I don't know how to do is to retrieve content so I can loop it out. In wordpress there is query_posts($post_type = mycustomcontenttype). Is there an equivalent in Drupal 7?

I do not want to use the Views module for this.

If you're looking to retrieve $node objects and aren't afraid of formatting the info yourself, node_load_multiple() probably comes closest to solving your problem. The $conditions parameter is supposed to be deprecated, but you could use it to specify content type. If you want to use node_load_multiple() in the manner recommended by the API page, I believe you would just use a simple db_query() to retrieve the node ids (nids) of all content with a given type:

$nids = db_query('SELECT nid FROM {node} WHERE type = my_content_type');

Then you could iterate through the results to create an array of nids to pass to node_load_multiple().

$nid_array = array();
foreach($nids as $nid){
  $nid_array[] = $nid;
}
node_load_multiple($nid_array);

From there you're going to have to iterate through the $node objects returned to create your archive page. Depending on whether you're using path aliases, you might have to retrieve the alias for each node.

drupal_lookup_path('alias',"node/".$node->nid);

All that said, I would do this in Views in a heartbeat.


Custom template suggestion I have this preprocess function:

function drisco_preprocess_page(&$vars) {
    $node = $vars['node'];
    $vars['theme_hook_suggestions'][] = 'page__node__' . clean_class($node->title);
    array_unshift($vars['theme_hook_suggestions'], 'page__node__' . clean_class($node->title));
    dpm($vars);
}

dpm() tells me my suggestion array looks like this:

0 (String, 26 characters ) page__node__hotel-overview
1 (String, 10 characters ) page__node
2 (String, 13 characters ) page__node__%
3 (String, 14 characters ) page__node__68
4 (String, 10 characters ) page__page
5 (String, 11 characters ) page__hotel
6 (String, 26 characters ) page__node__hotel-overview

My template file is called "page--node--hotel-overview.tpl.php" but isn't being used. I have page.tpl.php template file in my theme dir.

What am I doing wrong?

If I erase the template suggestions array and replace it with my own with only one file in it like thus, it loads the template. If I append or prepend the same suggestion, it just loads page.tpl.php.

$vars['theme_hook_suggestions'] = array('page__node__68');

This is a child theme; could that be making a difference?

Let me explain you the template order

In this, you can alter the header and footer if you wanted it to be different than normal page layout that is set in the page.tpl.php

page--[content-type name].tpl.php = page--lab.tpl.php
It will be used to theme all contents of type lab including header and footer

page--node--[content-id].tpl.php = page--node--12.tpl.php
It will be used to theme  content with 12 including header and footer

Secondly,

node.tpl.php Will work for all type of content on the site
node--[content-type name].tpl.php (node--lab.tpl.php) will used to alter the content part only of lab type content excluding header and footer
node--[node-id].tpl.php(node--10.tpl.php) will use to alter the content part of node 10 only excluding header and footer

Including and excluding meand control over header and footer.

Hope it will help you!


How to allow the translation of menu links provided by my_module.links.menu.yml I have the Configuration Translation module installed in a multilingual site and I am able to translate any menu created with the UI.... This is fine!!
I have a module which is creating some menus with the help of a yml static file: my_module.links.menu.yml
Unfortunately,
1-I couldn't translate any title/description (created in the yml) through in the UI as the translation tab is "locked" with this message : This link is provided by the xxx module. The title and path cannot be edited.
2-the User interface translation page (/admin/config/regional/translate) couldn't find the titles/descriptions (created in the yml) that I would like to translate
More to add: I have checked Custom menu link in the Content language an translation page (/admin/config/regional/translate) but this doesn't change anything... What is the purpose of this option?
...If someone can help me on this, I assume I will be able to use the provided solution to translate items created in other yml static files like my_module.links.action.yml

Ensure you visited a page with these menu items at least once in the target language before trying to translate them at user interface translation. They need to be picked up first before appearing there and can only then be translated like any other UI string.


Is it better to use module_invoke_all(), or  module_invoke() and module_implements()? Using module_invoke_all('some_hook') is easy, but is this better for performance?

foreach (module_implements('some_hook') as $module) {
  $data = module_invoke($module, 'some_hook');
}

There is little difference; module_invoke_all() runs the following code:

function module_invoke_all() {
  $args = func_get_args();
  $hook = $args[0];
  unset($args[0]);
  $return = array();
  foreach (module_implements($hook) as $module) {
    $function = $module . '_' . $hook;
    if (function_exists($function)) {
      $result = call_user_func_array($function, $args);
      if (isset($result) && is_array($result)) {
        $return = array_merge_recursive($return, $result);
      }
      elseif (isset($result)) {
        $return[] = $result;
      }
    }
  }

  return $return;
}

The only difference is that with module_invoke_all(), for example, func_get_args() is invoked only once, while when using module_invoke() func_get_args() is called each time module_invoke() is called; that is a marginal difference, though.
There are a few cases where module_implementing() and module_invoke() are used, normally when a module needs to know which module is invoked, such as in the case of search_get_info() that builds an array of information about the modules implementing search functions.

function search_get_info($all = FALSE) {
  $search_hooks = &drupal_static(__FUNCTION__);

  if (!isset($search_hooks)) {
    foreach (module_implements('search_info') as $module) {
      $search_hooks[$module] = call_user_func($module . '_search_info');
      // Use module name as the default value.
      $search_hooks[$module] += array(
        'title' => $module,
        'path' => $module,
      );
      // Include the module name itself in the array.
      $search_hooks[$module]['module'] = $module;
    }
  }

  if ($all) {
    return $search_hooks;
  }

  $active = variable_get('search_active_modules', array('node', 'user'));
  return array_intersect_key($search_hooks, array_flip($active));
}

Another example is image_styles(), which gets the list of all the image styles implemented by the modules, and that uses the following code:

  foreach (module_implements('image_default_styles') as $module) {
    $module_styles = module_invoke($module, 'image_default_styles');
    foreach ($module_styles as $style_name => $style) {
      $style['name'] = $style_name;
      $style['module'] = $module;
      $style['storage'] = IMAGE_STORAGE_DEFAULT;
      foreach ($style['effects'] as $key => $effect) {
        $definition = image_effect_definition_load($effect['name']);
        $effect = array_merge($definition, $effect);
        $style['effects'][$key] = $effect;
      }
      $styles[$style_name] = $style;
    }
  }

In both the cases, the retrieved information is put in an array where the index is the short name of the module.


Trouble with implementing contextual links I have a block with dynamic content and two contextual links.

I have at the moment two problems:

The second element is not visible.
The first link does not allow to pass a date. I have to set a prefix e.g. "_"

How can I fix this problems?

Here is the main part of my module:

define('MY_DIR', 'somedir');

function mymodule_menu() {
    $items[MY_DIR] = array(
        'page callback' => 'status_page',
        'access callback' => TRUE,
        'type' => MENU_LOCAL_TASK,
    );
$items[MY_DIR.'/%'] = array(
    'page callback' => 'status_page',
    'access callback' => TRUE,
);
    $items[MY_DIR.'/edit'] = array(
        'title' => 'Edit item',
        'page callback' => 'drupal_get_form',
        'page arguments' => array('mymodule_object_edit_form', 2),
        'access callback' => TRUE,
        'type' => MENU_LOCAL_TASK,
        'context' => MENU_CONTEXT_PAGE | MENU_CONTEXT_INLINE,
    );
    $items[MY_DIR.'/%date/update'] = array(
        'title' => 'Edit date',
        'page callback' => 'drupal_get_form',
        'page arguments' => array('mymodule_object_edit_form', 2),
        'access callback' => TRUE,
        'type' => MENU_LOCAL_TASK,
        'context' => MENU_CONTEXT_PAGE | MENU_CONTEXT_INLINE,
    );

    return $items;
}

And here is my status page:

function status_page($date=null) {
    $object=new stdClass();
    $build=array();

    if(empty($date)) {
        $day=get_next_match();
    } else {
        // parse data
    }

    // set title
    $title="Title for ".$day->format("j.m.Y");
    drupal_set_title($title);

    $object->title = $title;
    $object->content = "Some dynamic content";

    $build[0] = array(
        '#theme' => 'filteredusers_object',
        '#object' => $object,
        '#contextual_links' => array(
            // contextual link 1
            'update-option' => array(
                MY_DIR,
                array("_$date"),
            ),
            // contextual link 2
            'edit.option' => array(
                MY_DIR.'/edit',
                array(),
            ),
        ),
    );
    return $build;
}

If something is unclear feel free to ask.

After one day of research I got a solution:

$build[1] = array(
    '#theme' => 'filteredusers_object',
    '#object' => $object,
    '#contextual_links' => array(array('', array())), // replaced by dummy data
    '#marker' => 'marker',
);

And adding this new hook:

function filteredusers_contextual_links_view_alter(&$element, &$items) {
    if(isset($element['#element']['#marker']) &&
             $element['#element']['#marker'] == "marker") {
        $element['#links']['custom-link'] = array(
            'title' => 'Some title',
            'href' => url('node/42', array('absolute' => TRUE)),
        );
    }
}


Privatemsg rule problem With Privatemsg and Rules modules, I want to create a rule :

Anyone create a node, a special role user recept accepted a privatemsg.

But when I create the rule, in the actions, meet a problem:

The "Data selector" in RECIPIENT, I can't find the role.

Does anyone have a solution ?

The Recipient in the Privatemsg rules integration does not provide a user object, because the recipient could be a user or a role.  (There is a Privatemsg function for sending messages to roles, not just individual users.)

So, this is a limitation of the Privatemsg rules integration.  If you want to do this, you will have to add that functionality to the module yourself.


Bootstrap's css is not loading I am have a website on drupal and have enabled  Bootstrap theme .
The problem is http://netdna.bootstrapcdn.com/bootstrap/3.0.2/css/bootstrap.min.css is not loading .
It says "This webpage is not available" when i try to load

http://netdna.bootstrapcdn.com/bootstrap/3.0.2/css/bootstrap.min.css

in ubuntu ,

But when works fine in windows.

I have no idea why is this happening .
Plz help.

Add this to your template.php

function MYTHEME_framework_page_build(&$vars) {
    // Add bootstrap cdn.
    drupal_add_css('http://netdna.bootstrapcdn.com/bootstrap/3.0.2/css/bootstrap.min.css ', array('type' => 'external'));
}

where MYTHEME should be replaced with the name of your theme in your MYTHEME.info.

Save the file on your server

clear all chaes and reload the page.

now this should be fixred


Force capitalization of terms on entry with Autocomplete Deluxe module I would like to force the capitalization of taxonomy term entries, or alternatively make them case insensitive so that 'book' and 'BOOK' are not different taxonomy terms. Is there a way to enable this. The context is this form http://www.wequest.co.uk/user/register on the 'skills' and 'resources' field... I need these to be standardised because they represent catalogues of skills and resources and I don't want duplicates either: of terms or due to different cases.

The Taxonomy dupecheck module would probably help for most of that (I'm not entirely sure about the case-sensitivity issue but give it a try; MySQL queries for term names will be case-insensitive so my gut instinct is this would work)

  Taxonomy dupecheck module prevents Drupal administrators from adding duplicate taxonomy vocabularies and/or terms. It's helpful when entering large amounts of terms or vocabularies in situations where each value must be unique. This saves time by preventing administrators from having to enforce a unique value policy through later cleanup of duplicate terms.

To force title-case on the term you could implement hook_taxonomy_term_presave() in a custom module and force it like so:

function MYMODULE_taxonomy_term_presave($term) {
  if (some_condition_applies_to($term)) {
    $term->name = ucwords($term->name); // Or ucfirst() depending on your requirement
  }
}


Changing hash throw: Uncaught Error: Syntax error, unrecognized expression I want to change the hash in the URL when I trigger an action (a click for instance) using a pattern like #/param-1=foo&param-2=bar
In a fresh Drupal 8 theme, when I try this, I got an error saying
Uncaught Error: Syntax error, unrecognized expression: #/test=0
It works fine when I try with #param1-foo_param2-bar but I would like more flexibility. It looks like jquery is trying to consider the hash as a selector and returns an error that says it's not a valid selector.
Here is the code I use on a fresh classy based theme:
(function ($, Drupal) {
    Drupal.behaviors.myModuleBehavior = {
        attach: function (context, settings) {
            $('.layout-container', context).once('myModuleBehavior').each(function () {
                $('.site-name a').on('click', function (event) {
                    event.preventDefault();
                    event.stopPropagation();
                    console.log("clicking on logo");
                    window.location.hash = "/test=0";
                });
            });
        }
    };
})(jQuery, Drupal);

And here is the result I get from chrome console:

Thanks to @Alfred Armstrong pointing down form.js. It seems this event is responsible of that behaviour:

 $(window).on('hashchange.form-fragment', debouncedHandleFragmentLinkClickOrHashChange);

It looks like unbinding it in my custom .js does the trick. We won't benefit from the scroll functionality form.js provides, but we could recreate it with:

$(window).off('hashchange.form-fragment').on('hashchange', function() {
    //something that scroll
});


User fields that are visible, but can't be manually edited I have a web service that will be automatically populating certain attributes of a user's profile.

I am creating my fields via field api when the module is installed. I want all of the fields to be visible when editing the user profile, and some of these fields will be visible publicly as well.

My current plan is to form_alter my away around the issue, but I was wondering if someone has an alternate approach they would take.

Between the hooks used from the field API, there is hook_field_access(), which allows to define which users has access to a field when the entity is being viewed, or when the entity is being edited.

function mymodule_field_access($op, $field, $entity_type, $entity, $account) {
  if ($field['field_name'] == 'field_of_interest' && $op == 'edit') {
    return user_access('edit field of interest', $account);
  }

  return TRUE;
}

There is also a module that uses that hook: Field Permissions.

  The Field Permissions module allows site administrators to set field-level permissions to edit, view and create fields on any entity.

  Features

  Enable field permissions on any entity, not just nodes
  Role-based field permissions allowing different viewing patterned based on what access the user has
  Author-level permissions allow viewing and editing of fields based on who the entity owner is
  Permissions for each field are not enabled by default. Instead, administrators can enable these permissions explicitly for the fields where this feature is needed
  Field permissions overview


What stops the import of the rule contained in my custom module? I have exported rules from the existing rules and I wanted to import rule using custom module. But when I enable this module. Rules weren't imported in rules list.

I created 3 files:

1) my_module.INFO file:

name = My module example
description = My module for import rules
core = 7.x
package = My module

2) my_module.MODULE file (blank file):

<?php

3) my_module.rules_defaults.INC file:

<?php
     function rules_example_default_rules_configuration() {
      $configs = array();
      $rule = '{ "rules_final_save_pdfs" : {
        "LABEL" : "final save pdfs",
        "PLUGIN" : "reaction rule",
        "ACTIVE" : false,
        "OWNER" : "rules",
        "REQUIRES" : [ "rules", "views_pdf", "entityform" ],
        "ON" : { "entityform_insert" : [] },
        "IF" : [
          { "entity_has_field" : { "entity" : [ "entityform" ], "field" : "field_test_pdf_form" } }
        ],
        "DO" : [
          { "views_pdf_rules_action_save" : {
              "views_pdf" : "test_new_view:pdf_1",
              "path" : "\/workout\/sites\/default\/files\/test_pdfs\/[entityform:field-date]"
            }
          }
        ]
      }
    }';
      $configs['rules_final_save_pdfs'] = rules_import($rule);
      return $configs;
    }
?>

Please let me know if there any changes to do.

Assuming this is for D7, try this variation of the your code in your item "3)":
<?php
     function my_module_default_rules_configuration() {
      $configs = array();
      $rule = '{ "rules_final_save_pdfs" : {
        "LABEL" : "final save pdfs",
        "PLUGIN" : "reaction rule",
        "ACTIVE" : false,
        "OWNER" : "rules",
        "REQUIRES" : [ "rules", "views_pdf", "entityform" ],
        "ON" : { "entityform_insert" : [] },
        "IF" : [
          { "entity_has_field" : { "entity" : [ "entityform" ], "field" : "field_test_pdf_form" } }
        ],
        "DO" : [
          { "views_pdf_rules_action_save" : {
              "views_pdf" : "test_new_view:pdf_1",
              "path" : "\/workout\/sites\/default\/files\/test_pdfs\/[entityform:field-date]"
            }
          }
        ]
      }
    }';
      $configs['rules_final_save_pdfs'] = entity_import('rules_config', $rule);
      return $configs;
    }
?>

Note the changes in the line with function ... (near the top) and the line with entity_import (near the end).
Be aware: if I try to import your rule (= the string contained in $rule) in a site of mine (where I don't have views_pdf module enabled), and using the Rules UI, I get an import error like so:

Import failed.
Missing the required module views_pdf.

That makes sense of course (since I don't have that module). So check that that is not the case why your rule isn't imported (same for entityform). A possible technique to prevent this issue, is to declare those 2 modules as a dependency in your my_module.info file.
PS: have a look at the code of the Answers Userpoints module for an example where this technique is used also.


Importing location data into Drupal 7 New to Drupal but am interested in it as an option to transition to from a hand coded site. This site is primarily a location searchable venue index, with venues having various categories.

In Drupal I have set up my content type 'Venue' and have added the location module to store the venue addresses and other contact details.

Now I am wanting to import my existing data which I have ready in a CSV.

To do this I understand I should use the feeds module which I have now installed (along with ctools and job_scheduler).

Now under Structure-> Feeds importers -> Add importer I can create and configure my CSV import - Great!

Unfortunately I can't see any option under Processor to associate my CSV address fields with the location module fields. What am I missing here?

A little late but there's this module: https://drupal.org/project/location_feeds
Location Feeds :D

Haven't actually tried it yet but It seems to do exactly what you want.


How put a product display on the "Shop" not the "Home" page? I have created all suggested types and objects for a product display (drupal commerce module) but it only shows on the "Home" page (which I have renamed "News"). I have a page named "Shop" for this purpose i.e. where I want the products to be on. How do I tell drupal to place the product display there?

Test site: http://marius-raphaelius.com/drup

(In fact, how does one edit the content of a page in general?)

Thanks a lot.

If I understand you correctly, you want to tell Drupal to use a different node for the home page.   If this is what you mean you can do this by going to

Home -> Administer -> Site Configuration

You can change the node for the Default front page there.


How to load Ubercart orders for certain user ID? How to load Ubercart orders for certain user ID programatically?

There is only uc_order_history() which returns formatted order table and does not work in that case.

Find the following function in Drupal 7:

/**
 * Custom function to return list of orders for certain user
 */
function foo_get_user_orders($user, $order_status = 'completed') {
  $query = db_select('uc_orders', 'uo');
  $query->addField('uo', 'order_id');
  $query->addField('uo', 'order_total');
  $query->addField('uo', 'order_status'); // optional: $query->addField('uo', 'product_count');
  $query->addJoin('LEFT', 'uc_order_products', 'p', 'p.order_id = uo.order_id');
  $query->addField('p', 'nid');
  $query->condition('order_status', $order_status);
  $query->condition('uid', $user->uid);
  $result = $query->execute()->fetchAll();
  return $result;
}

For Drupal 6, please install dbtng module and it should work as well.


How do I add the edit link of a content in a custom view mode? I have a content type (Sample) which includes a field (A) whose widget type is View. I'm using the Entity Reference View Widget View module for this.

The output of this field is having only the title of the node added from the view, but I want also the Node Edit link.

As far as I know, the output of Entiy Reference View Widget View can be printed with any custom view mode. I'm trying to add the node edit link in this custom view mode.

Do you have any idea on how to add a custom field having the edit link in the view mode?The steps which i followed are:

Step 1:I selected the particular view mode in the content type field settings A:
Here is the screen shot:

Step 2: In Display suit fields(admin/structure/ds/fields) i have added custom edit link field like Edit
I can see Edit link in the output ,but the  token value i provided [node:nid] is not fetching the node id. Link is redirecting to node/edit/%5Bnode%3Anid%5D .Can anybody help me in this? Please the below screenshot

Correct me if i'm wrong.
Any other approach or method is also fine.

You can enable views_ui in module page, then go to structure/views and edit the views you are using for the widget. Add Content: Edit link in fields and save it. It will got the edit links for each entity as above image.

Override theme function by custom module

There is no easy way to add the edit link for the widget on node page. But you can still make it happen by overriding the theme functions provided by Entity Reference View Widget View

Below is the sample snippet with assuming the name of your custom module is mymodule. You can copy and paste it into a custom module for testing. (Remember to change the mymodule if you have different name for your custom module.)

<?php

/**
 * Implements hook_theme_registry_alter().
 */
function mymodule_theme_registry_alter(&$theme_registry) {
  if (isset($theme_registry['entityreference_view_widget_widget']['function'])) {
    $theme_registry['entityreference_view_widget_widget']['function'] = 'mymodule_entityreference_view_widget_widget';
  }
  if (isset($theme_registry['entityreference_view_widget_rows']['function'])) {
    $theme_registry['entityreference_view_widget_rows']['function'] = 'mymodule_entityreference_view_widget_rows';
  }
}

/**
 * Override theme_entityreference_view_widget_widget().
 */
function mymodule_entityreference_view_widget_widget($variables) {
  $widget = $variables['widget'];
  $settings = $widget['add_more']['#ervw_settings'];
  $order_class = drupal_html_class($settings['element'] . '-delta-order');
  $required = !empty($settings['instance']['required']) ? theme('form_required_marker', $variables) : '';

  $header = array(
    array(
      'data' => '' . t('!title !required', array('!title' => $widget['#title'], '!required' => $required)) . "",
      'colspan' => 2,
      'class' => array('field-label'),
    ),
  );
  $header[] = array(
    'data' => "" . t('Edit link') . "",
    'class' => array('field-label'),
  );
  if ($settings['field']['cardinality'] !== '1') {
    $header[] = array(
      'data' => t('Order'),
      'class' => array('tabledrag-hide'),
    );
  }
  $rows = array();

  // Sort items according to '_weight' (needed when the form comes back after
  // preview or failed validation)
  $items = array();
  foreach (element_children($widget) as $key) {
    if ($key === 'add_more') {
      $add_more_button = &$widget[$key];
    }
    else {
      $items[] = &$widget[$key];
    }
  }
  usort($items, '_field_sort_items_value_helper');

  // Add the items as table rows.
  foreach ($items as $item) {
    $item['_weight']['#attributes']['class'] = array($order_class);
    $delta_element = drupal_render($item['_weight']);

    $cells = array(
      array('data' => '', 'class' => array('field-multiple-drag')),
      drupal_render($item),
    );

    $target_id = $item['target_id']['#return_value'];
    $entities = entity_load($settings['target_type'], array($target_id));
    $cells[] = array(
      'data' => _mymodule_entity_edit_link($settings['target_type'], $entities[$target_id]),
    );

    if ($settings['field']['cardinality'] !== '1') {
      $cells[] = array('data' => $delta_element, 'class' => array('delta-order'));
    }
    $rows[] = array(
      'data' => $cells,
      'class' => array('draggable'),
    );
  }

  if (empty($rows)) {
    $rows[][] = array(
      'data' => t('No items have been added yet. Click "Add items" to launch the widget.'),
      'colspan' => '3',
    );
  }

  $output = '
';
  $form_errors = form_get_errors();
  $classes = array('field-multiple-table');

  // Add an error class to the table in case of error.
  if (isset($form_errors[$settings['element']])) {
    $classes[] = 'error';
  }

  $output .= theme('table', array(
    'header' => $header,
    'rows' => $rows,
    'attributes' => array(
      'id' => $settings['table_id'],
      'class' => $classes,
    ),
  ));
  $output .= $widget['#description'] ? '
' . $widget['#description'] . '
' : '';
  $output .= '
' . drupal_render($add_more_button) . '
';
  $output .= '
';

  if ($settings['field']['cardinality'] !== '1') {
    drupal_add_tabledrag($settings['table_id'], 'order', 'sibling', $order_class);
  }

  return $output;
}

/**
 * Override theme_entityreference_view_widget_rows().
 */
function mymodule_entityreference_view_widget_rows($variables) {
  $zebra = array('even' => 'odd');

  $settings = $variables['rows']['#widget_settings'];
  foreach (element_children($variables['rows']) as $row) {
    $output[$row]  = '
';
    $output[$row] .= '	';
    $output[$row] .= '' . render($variables['rows'][$row][$settings['column']]) . '	';

    $target_id = $variables['rows'][$row]['target_id']['#return_value'];
    $entities = entity_load($settings['target_type'], array($target_id));
    $output[$row] .= '' . _mymodule_entity_edit_link($settings['target_type'], $entities[$target_id]) . '	';

    if ($settings['cardinality'] !== '1') {
      $output[$row] .= '' . render($variables['rows'][$row]['_weight']) . '	';
    }
    $output[$row] .= '
';

    $zebra = array_flip($zebra);
  }

  return implode("\n", $output);
}

/**
 * Helper function to build the entity edit link.
 */
function _mymodule_entity_edit_link($entity_type, $entity) {
  $uri = entity_uri($entity_type, $entity);
  return l(t('Edit'), $uri['path'] . '/edit');
}

The key concept here is programmatically override the 2 theme functions with hook_theme_registry_alter:

theme_entityreference_view_widget_widget()
theme_entityreference_view_widget_rows()

So we can now modify the table output.

Add a new column header

$header[] = array(
  'data' => "" . t('Edit link') . "",
  'class' => array('field-label'),
);

Add link for new column

For static output.

$target_id = $item['target_id']['#return_value'];
$entities = entity_load($settings['target_type'], array($target_id));
$cells[] = array(
  'data' => _mymodule_entity_edit_link($settings['target_type'], $entities[$target_id]),
);

For dynamic output. (ajax callback)

$target_id = $variables['rows'][$row]['target_id']['#return_value'];
$entities = entity_load($settings['target_type'], array($target_id));
$output[$row] .= '' . _mymodule_entity_edit_link($settings['target_type'], $entities[$target_id]) . '	';

Helper function to build edit link

/**
 * Helper function to build the entity edit link.
 */
function _mymodule_entity_edit_link($entity_type, $entity) {
  $uri = entity_uri($entity_type, $entity);
  return l(t('Edit'), $uri['path'] . '/edit');
}


How to set the default "Show as expanded" to true in a custom menu item I am creating a series of menus in a custom module. This site also has a custom theme. Is there a way in the theme, or in the module, to set a menus "Show as expanded" to true. This way, if I move my site, uninstall, or whatever, it comes back the way it should right out of the box.

I couldn't find it anywhere on the Drupal documentation, but adding

expanded: TRUE

in the module.links.menu.yml file works.


DS Views Block Field page visibility settings I have a Views block Sectors. I have created a DS block field that renders this view and I have configured it to be available only for specific bundle|view_mode. It gets displayed on every bundle|view_mode page after that.

I wan't to configure this block to be visible only on a certain page(s) and not in all bundle|view_mode specified. Basically, I need a Show block on specific pages settings as in D7.

Go to /admin/structure/block under the disabled region, click on Place block button and try searching for it on the search box, if you find it, place it and then Configure.


Set access restriction for baseroute Let's say I have the following in example.links.task.yml from a contributed module:

    example.view:
    title: 'View'
    base_route: 'entity.example.canonical'
    route_name: 'entity.example.canonical'

    example.edit_form:
    title: 'Edit'
    base_route: 'entity.example.canonical'
    route_name: 'entity.example.edit_form'

    ... more routes with the same base_route

Now I'd like to add a custom access restriction for all these local tasks. I tried to set a restriction to the base_route, thinking that all other routes with this particular base_route would have the restriction too, but it only works for entity.example.canonical. I tried the following way:

class RouteSubscriber extends RouteSubscriberBase {

  /**
   * {@inheritdoc}
   */
  protected function alterRoutes(RouteCollection $collection) {
    if (($route = $collection->get('entity.example.canonical'))) {
      $route->setRequirement('_role', 'administrator');
    }
  }

}

I could explicitly name all different routes, but I thought there might be a way to only use the base_route - not knowing if this would work though. Any ideas?

This might work

if (($route = $collection->get('entity.example.canonical'))) { // base_route
      $current_route = \Drupal::routeMatch()->getRouteObject(); // get current route
      $current_route->setRequirement('_role', 'administrator');
}


How to build an egg timer in Drupal I would like to implement a reminder functionality on a website, where a (anonymous) user can define a time for a (pop-up) reminder to fire automatically. Think of it as a digital egg timer, where you are reminded after some 5 minutes that your eggs are hard boiled... ;-).

My initial idea was to save the due time in $_SESSION['reminder'] and let Drupal check at each cron run whether the reminder is due. However, this approach fails because hook_cron operates on a global level and therefore does not recognise $_SESSION variables. On the other hand, saving the due time in, say, a node field does not make sense either: Drupal would find all due reminders and fire a pop-up which would be visible to every user currently on the site! So summing up, I need to find a way to initiate a process at a given time that is restricted to a particular session. Can anyone give me advise on how to go for this one?

Also, I need the reminder to pop up at the very top of all running applications in order not to be missed by the user. This is obviously something that all pop ups would like to achieve, so a user would probably have to give special pop-up permissions to this site. But how can I program such a pop-up, and what special settings are required? Alternatively, I could display the reminder as a (browser independent) system message, like the messages when receiving an MS Outlook email for example. Does anybody know whether and how this can be easily achieved?

I am sorry that this request is a bit vague, but it's really more about the general strategy and I haven't reached the level for detailed questions yet. So I would highly appreciate your ideas and experiences in similar applications in order to get inspired.

You have two approaches.

You could create a non cacheable block, that will check a session_variable, if a timer is set and the time is passed. If is has, it will render something, else it will be invisible. The will create the pop up on page refresh.

Alternative you can use a javascript and use setInterval to check if the time has passed and then display a popup. You would then have to add the javascript info on page load.


How to load to panels a referenced node? I have the user profile panel and I want to load in the panel a node that is referencing this user.
There is a trick to load a view in the panel,but I don't know exactly how to do this...
Can somebody help me on this?thanks

You'll want to add a display to your view of type "pane". Give it a descriptive title so you can find it from your Page Manager.

Then you'll create a Page Manager variant that displays on the entity (user) to which you want to attach this view. Under "content" you'll click the gear that appears in the top left, and click "add content". Select "view panes" and then select the view pane you just created.

In order to pass the node ID to the view pane, you'll go back to the view. Under "pane settings" select "argument input" and set it to "from panel argument". You'll probably want the first argument.


Custom install profile calls another install profile I want to create a custom install profile that will switch on some modules. I want it to be based on the open atrium profile. Ie Run the OA install profile and then switch on some additional modules. Is this possible?

The way install profiles work on Drupal 6, I don't think this will be possible. The modules that are installed are based of the dependency list in the .info file, and since you can't depend on an install profile you can't create that full attachment.

You could come far, by doing includes and callling the fuctions that would otherwise be called by Drupal though, but you would probably have to maintain your own .info file.


Views with taxonomy contextual filter not working in Russian language in Drupal 7 I have a View which works perfectly in English.
It has a contextual filter, with options
Content: Has taxonomy term ID ,
filters by taxonomy term with term name converted to term Id.

But when I put in the URL the term in Russian, Раздел, it does not show the content.
When I check the SQL, to my surprise and dismay, this is what I find: search_index.word = 'razdel'.

Clearly there has been a transliteration. Maybe this is why it does not work. I do not really what to do.

It's probably the collation of your fields and tables in database, try to check to see if all the tables collation is set to utf8_general_ci

you can google to find an script to bulk update your tables and or fields collation


Custom field doesn't show up in 'field type' dropdown I've been trying to create a custom field for my module.  I have used the field_example module as a guide but my field doesn't show up in the 'field type' dropdown on the 'manage fields' page.

Here is my code:

mantis.module

function mantis_field_info() {
    return array(
        'mantisform' => array(
            'label' => 'Mantis ' . t('Form'),
            'description' => 'Mantis Support Request Form',
            'default_widget' => 'mantis_mantisform_widget',
            'default_formatter' => 'mantisform_default'
         )
    );
}

function mantis_field_is_empty($item, $field) {
    if($field['type'] == 'mantisform') {
        if(empty($field['mantis_form_id'])) {
            return true;
        }
    }
    return false;
}

function mantis_field_widget_info() {

    return array(
    'mantis_mantisform_widget' => array(
        'label' => 'Mantis ' . t('Form'),
        'field_types' => array('mantisform'),
        'behaviors' => array(
            'multiple_values' => FIELD_BEHAVIOR_DEFAULT,
            'default_value' => FIELD_BEHAVIOR_NONE
            )
        )
    );
}

function mantis_field_widget_form($form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) {

    $base = $element;

    if($instance['widget']['type'] == 'mantis_mantisform_widget') {
        $widget = $instance['settings'];
        $settings = $widget['settings'];

        $element['mantis_form_id'] = array(
            '#type' => 'select',
            '#title' => t('Support Request Form'),
            '#default_value' => isset($items[$delta]['mantis_form_id']) ? $items[$delta]['mantis_form_id'] : NULL
        );
    }
    return $element;
}

function mantis_field_formatter_info() {
    return array(
        'mantisform_default' => array(
            'label' => t('Default'),
            'description' => t('Allows a ') . 'mantis' . t('support form to be selected'),
            'field types' => array('mantisform'),
        )
    );
}

function mantis_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {

    $element = array();

    switch($display['type']) {
        case 'mantisform_default': {

        }
    }
    return $element;
}

mantis.install

function mantis_field_schema($field) {
    if($field['type'] == 'mantisform') {
        $schema['columns']['mantis_form_id'] = array(
                'type' => 'int',
                'not null' => false,
        );
        return $schema;
    }
}

I haven't completely fleshed out mantis_field_formatter_view but figured that I should still be able to see the new field as an option in the dropdown.

Can anyone see where I'm going wrong?

This does appear to have been a caching issue. The field has appeared now. weird.


Access row value in template_preprocess_views_view_fields(&$variables) In template_preprocess_views_view_fields(&$variables), when I print $variables['row'], I get the following object.

How can I access values inside the node entity?

I tried with the following code, but it is not working.

$variables['row']->_entity->values['field_file_pdf_upload']->target_id

values is protected, so you have to use the get() method:

$variables['row']->_entity->get('field_file_pdf_upload')->target_id;

For the field object this shortcut is available (this is not standard OOP and works for fields only):

$variables['row']->_entity->field_file_pdf_upload->target_id;


Sticky at top of lists node at certain time I would like to sticky node at certain time and update time of publishing. I tried with module Scheduler but it unpublishes content I need published content it is more like republishing and put that content at the top.

I tried some with Rules module but no success. Is it possible to that somehow?

Looks like Rules Scheduler (part of the Rules module) is what you're looking for. "Publish content exactly 24 hours after it was created" contains step by step instructions about how to do so (using the Rules Scheduler).

Here are some video tutorials about a few variations of your question (some are pretty close to your question), which are all resolved with Rules Scheduler:

Schedule front page publishing.
Publish a newly created Drupal node on a future date.
Send a follow-up email one week after a user registers.

Ps: There is also the rules-scheduler tag, specific to the Rules Scheduler.


Caching pages with boost based on a cookie value I have a Drupal website where a part of each page varies depending on the value of a certain cookie. In order to use Boost in this situation, I was thinking of rewriting the cookie value into a query parameter, because Boost takes these into acccount for its cache.

To achieve this, I put the following lines in my .htaccess before the Boost code:

RewriteCond %{HTTP_COOKIE} cookie=([a-zA-Z0-9\-]+)
RewriteRule ^(.*)$ $1?cookie=%1 [QSA]

I tested this on a simple PHP script which shows all GET parameters, and the cookie parameter is added based on the cookie. Which is the way it should be. I also tested that these rules actually rewrite the %{QUERY_STRING} for later use, and they seem to do that. However, Boost does not seem to take into account this new query parameter.

Any ideas about what could be wrong? Does Boost do something special with the query string?

Thanks in advance!

Ok, it took me a while, but I solved it. It lead me to learn some interesting details about Apache and Drupal.

In my question above I wondered why the rewrite rules did not alter the QUERY_STRING in Apache because apparently, the correct page was not fetched from the cache. However, the problem was not that the correct page was not fetched, but that the correct page was not written to the cache in the first place.

Looking into the code of Boost showed that it uses Drupal's request_uri() function to determine the name of the cache file. This function in turn uses PHP's $_SERVER['REQUEST_URI'] if set. Some tests in PHP then showed that the rewrite rules do actually change $_SERVER['QUERY_STRING'], but that this change is not reflected in $_SERVER['REQUEST_URI']. In other words, the query parameters in $_SERVER['REQUEST_URI'] are the ones of the original request, not the ones as potentially rewritten by mod_rewrite.

To solve this, you can add some code to (for example) Drupal's settings.php to update $_SERVER['REQUEST_URI'] similarly as done in your .htaccess. This worked for me:

if(isset($_SERVER['REQUEST_URI']) && isset($_GET['cookie'])) {
  $cookie = $_GET['cookie'];
  if(strpos($_SERVER['REQUEST_URI'],'?') === false) {
    $_SERVER['REQUEST_URI'] = $_SERVER['REQUEST_URI'] . '?cookie=' . $cookie;
  } else {
    // I'm not sure what happens if &cookie is already set
    $_SERVER['REQUEST_URI'] = $_SERVER['REQUEST_URI'] . '&cookie=' . $cookie;
  }
}

Note 1: $_GET does contain the rewritten request parameters, so I guess this is based on QUERY_STRING.

Note 2: code above only adds my application-specific cookie. I guess a generic solution would be to completely remove the request string of $_SERVER['REQUEST_URI'] and add all elements in $_GET again.

Note 3: you need both the rewrite rules in .htaccess and this code in settings.php. The former are needed to have Boost fetch the correct page from the cache, the latter to have Boost write the correct page in the cache.


prevent script to run twice after 2 ajax loads I use colorbox node, which loads a node inside colorbox overlay. Inside colorbox I load a jquery script to add some parameters to all links inside. However, the loading is done by 2 ajax calls and I end up with doubled parameters on all links.
I tried to use .once() but that does not return anything, probably because it fires after first ajax call. How to wait until second ajax call? Thank you.

my script:

(function($){ // Create local scope.
Drupal.behaviors.jjj = {
  attach: function (context, settings) {

$('#colorbox #block-book-navigation a', context).once('jjj', function () {
       $("#colorbox #block-book-navigation a").each(function(){

                       $(this).addClass("xxx");
console.log( "test" );
       });

 });
}};
})(jQuery);

I figured it  out. The wrong code came out of misunderstsatnding .once function. "nav" means a class that the selector #colorbox #block-book-navigation would be marked, so code is not fired multiple times on that selector.
http://codekarate.com/blog/drupal-7-prevent-duplicating-javascript-behaviors
Correct code should be:

(function ($) {
  Drupal.behaviors.myCustomJS = {
    attach: function(context, settings) {
      $('#colorbox #block-book-navigation').once('nav', function() {

        $("#colorbox #block-book-navigation a").each(function(){
            $(this).addClass("colorbox-node");

       });

      });
    }
  };
})(jQuery);


Using cache tags for a particular node list Caching in Drupal 8 is great, but documentation is thin (at this time) on using cache tags for render arrays in Drupal 8.

I have some code that basically generates a list of node teasers, say for content types "books" and "magazines". I'm caching the list to speed things up. I would like to refresh the list every time a "book" or "magazine" is added/deleted/edited. So I have a render array that looks like this:

$build = array(
  '#type' => 'markup',
  '#markup' => $sMarkup,
  '#cache' => [
    'keys' => ['home-all','home'],
    'tags'=> ['node_list'], // invalidate cache when any node content is added/changed etc.
    'max-age' => '36600', // invalidate cache after 10h
  ],
);

By using the cache tag ['node_list'], the cache invalidates properly when content is added or edited, but will also invalidate when a content type not being listed here is changed, say "casette".

What cache tags can I use to limit the invalidation to when only "book" or "magazine" is added/changed/deleted? I've tried using: ['book_list','magazine_list']
but that doesn't work.

Starting Drupal 8.9.0, there is a new ENTITY_TYPE_list:BUNDLE cache tag added (see the change record).
So in your case you would simply need to tag our list with node_list:book.
https://www.drupal.org/node/3107058


Change order of markup for exposed views filter I have a search box on my homepage, and to style it correctly I need the button to come before the text box in the markup. The current block code looks like the following.

<form action="/drupal-7.22/search" method="get" id="views-exposed-form-commerce-search-page" accept-charset="UTF-8">

            Search for products

 <input type="text" id="edit-search-api-views-fulltext" name="search_api_views_fulltext" value="" size="30" maxlength="128" class="form-text required error">

      <input type="submit" id="edit-submit-commerce-search" name="" value="Go!" class="form-submit">

</form>

I've looked at hook_form_alter() and a few template files, but I think that's the wrong way to do it and I'm far from an expert.

I wouldn't mind being able to clean up that tangle of divs too!

You can create your own views-exposed-form.tpl.php file and move the submit button to the top, or add a class to it and use css to float left and right. This however would affect all exposed filter on your site.

If you want to alter the form you should use the function

function MODULENAME_form_views_exposed_form_alter(&$form, $form_state)

Your best option is however to try manipulating it with css.


Webfrom : Having two textfield boxes inline . What I need to do is have two input boxes next to each other.  As it's to except data that comes in two parts.  I can do this with CSS but using inline errors causes me problems. Has anyone done this or have any ideas on a solution.

Drupal 7 - webfrom 7.x-4.9+2-dev

You can easily accomplish this using the Webform Layout module.

This module allows you to arrange fields into rows or columns.


How to exclude product variations from product teaser display? I am developing an online shopping website using Drupal Commerce.

In my products teaser display all my products variations are also shown. I want only the main product to be displayed and not its variations on teaser display. Right now I am using in-build taxonomy term view to display my product teaser.

Any suggestions?

Fortunately I got the answer, by looking at the solution described in a comment to View of products with multi-value product reference field show multiple rows per product node. Here is a summary of it:

  I created a view of product display nodes. Added the relationship to products. Added two fields "Content: Title" and "Commerce Product: Image".
  Got a row for every display node and product (so a node that references two products gets two rows). This is what I expect to happen.

  Possible solution A:

  I click on "Query settings" in the third column, and in query settings enable "Distinct" (it's a checkbox).
  That kills the duplicates.

  However, DISTINCT is usually a bit stupid, so it might not work in all cases. In those cases, you can try the next possible solution.

  Possible solution B:

  I enable Aggregation (again, it's in the third column). I make sure to have a "Content: Nid" field added at the top of the fields list, so that it groups by that first. Might need to apply "MIN' to the title (by setting: Aggregation type to "Minimum" in "Aggregation settings" for that field).

  Note that once you do that, the image will stop displaying. The solution for that is to go into "Aggregation settings" for the image field, and change the "Group column" from "fid" to "Entity ID". That makes it display again.


Update to Search API 1.18 causes HTML to be displayed as plaintext A security update to Search API (7.x-1.18) adds new sanitation as a security measure.  Great!  ..Except it now causes my custom field to be displayed as plaintext instead of HTML.

Here is the relevant code that was added to Search API:

/**
 * Sanitizes field values returned from the server.
 *
 * @param array $values
 *   The field values, as returned from the server. See
 *   SearchApiQueryInterface::execute() for documentation on the structure.
 *
 * @return array
 *   An associative array of field IDs mapped to their sanitized values (scalar
 *   or array-valued).
 */
function search_api_get_sanitized_field_values(array $values) {
  // Sanitize the field values returned from the server. Usually we use
  // check_plain(), but this can be overridden by setting the field value to
  // an array with "#value" and "#sanitize_callback" keys.
  foreach ($values as $field_id => $field_value) {
    if (is_array($field_value)
      && isset($field_value['#sanitize_callback'])
      && ($field_value['#sanitize_callback'] === FALSE || is_callable($field_value['#sanitize_callback']))
      && array_key_exists('#value', $field_value)
    ) {
      $sanitize_callback = $field_value['#sanitize_callback'];
      $field_value = $field_value['#value'];
    }
    else {
      $sanitize_callback = 'check_plain';
    }
    if ($sanitize_callback !== FALSE) {
      $field_value = search_api_sanitize_field_value($field_value, $sanitize_callback);
    }
    $values[$field_id] = $field_value;
  }
  return $values;
}

Question

Because it says

  // Sanitize the field values returned from the server. Usually we use
  // check_plain(), but this can be overridden by setting the field value to
  // an array with "#value" and "#sanitize_callback" keys.

I know I need to set the field value to an array with #value (my custom HTML) and #sanitize_callback keys, but where do I set this, and what do I use for #sanitize_callback?

My Custom Code

I'm using a callback to generate my field with custom HTML:

<?php

/**
 * @file
 * Contains SearchApiAlterAddViewedEntity.
 */

/**
 * Search API data alteration callback that adds an URL field for all items.
 */
class MySearchAlterAddUsercacheEn extends SearchApiAbstractAlterCallback {

  /**
   * Only support indexes containing entities.
   *
   * @see SearchApiAlterCallbackInterface::supportsIndex()
   */
  public function supportsIndex(SearchApiIndex $index) {
    return (bool) $index->getEntityType();
  }

  public function alterItems(array &$items) {
    // Prevent session information from being saved while indexing.
    drupal_save_session(FALSE);

    // Force the current user to anonymous to prevent access bypass in search
    // indexes.
    $original_user = $GLOBALS['user'];
    $GLOBALS['user'] = drupal_anonymous_user();

    foreach ($items as &$item) {
      // Since we can't really know what happens in entity_view() and render(),
      // we use try/catch. This will at least prevent some errors, even though
      // it's no protection against fatal errors and the like.
      try {
        $render = user_view($item, 'ensearch', 'en-US');
        $text = render($render);
        if (!$text) {
          $item->search_api_viewed_en = NULL;
          continue;
        }
        $item->search_api_viewed_en = $text;
      }
      catch (Exception $e) {
        $item->search_api_viewed_en = NULL;
      }
    }

    // Restore the user.
    $GLOBALS['user'] = $original_user;
    drupal_save_session(TRUE);
  }

  public function propertyInfo() {
    return array(
      'search_api_viewed_en' => array(
        'label' => t('Entity (en-US) HTML output'),
        'description' => t('The whole HTML content of the entity when viewed.'),
        'type' => 'text',
      ),
    );
  }

}

check_plain() encodes special characters that has special meaning in HTML (such as < and &) into plain text entities (i.e. < and & respectively) that will make these be rendered literally (not interpreted as HTML) when that string that is then displayed as part of a page with HTML-markup.
filter_xss() filters an HTML string to prevent cross-site-scripting (XSS) vulnerabilities.

In other words, filter_xss() takes care of security, while not plain-texting HTML.

I propose you to patch the Search API function with 'filter_xss' as a callback instead of 'check_plain', create an issue on drupal.org and explan that case.


Isotope and Views Load More error - Javascript breaks on some Ajax calls I've created a view with Views Isotope and Views Load More contributed modules.

The objective is to have a Isitope grid that we can zoom in/out on items.

After long time to get it working I got a strange bug:

When I load the page it works fine.
When I click on load more first time the grid breaks.
When I click on load more second time the grid works fine.
When I click on load more third time the grid breaks.
And so on...

See it working here.

This is my javascript:

(function ($) {
Drupal.behaviors.skeletonthemeCustomBehavior = {

attach: function (context, settings) {

  // $grid.isotope('destroy');

  var $grid = $('#isotope-container').isotope();

  $grid.isotope({
    masonry: {
      columnWidth: 10
    }
  });

$grid.on( 'click', '.isotope-element', function() {
  if ($( this ).hasClass( 'gigante' )) {
    $( this ).toggleClass('gigante');
  } else {
    // change size of item by toggling gigante class
    $( '.isotope-element' ).removeClass( 'gigante' );
    $( this ).toggleClass('gigante');
  }
  $grid.isotope('layout');
});

$('#destroy').bind( 'click' ,function(e) {
  event.preventDefault(e);
  $grid.isotope( 'destroy' );
});

  $('.relayout').bind( 'click' ,function(e) {
    event.preventDefault(e);
    var $grid = $('#isotope-container').isotope();
    $grid.isotope({
      masonry: {
        columnWidth: 10
      }
    });
    $grid.isotope('reloadItems');
  });

  $( document ).ajaxComplete(function() {
    var $grid = $('#isotope-container').isotope();
    $grid.isotope({
      masonry: {
        columnWidth: 10
      }
    });
    $grid.isotope('reloadItems');
  });
}

};
})(jQuery);

I did noticed that after the 1st load more, you can't zoom in, then after the 2nd load more zoom works, and after the 3rd load more zoom doesn't work again.

I believe it's your code. You need to add the zoom in/out part again inside the ajaxComplete function

(function ($) {
Drupal.behaviors.skeletonthemeCustomBehavior = {

attach: function (context, settings) {

  // $grid.isotope('destroy');

  var $grid = $('#isotope-container').isotope();

  $grid.isotope({
    masonry: {
      columnWidth: 10
    }
  });

$grid.on( 'click', '.isotope-element', function() {
  if ($( this ).hasClass( 'gigante' )) {
    $( this ).toggleClass('gigante');
  } else {
    // change size of item by toggling gigante class
    $( '.isotope-element' ).removeClass( 'gigante' );
    $( this ).toggleClass('gigante');
  }
  $grid.isotope('layout');
});

$('#destroy').bind( 'click' ,function(e) {
  event.preventDefault(e);
  $grid.isotope( 'destroy' );
});

  $('.relayout').bind( 'click' ,function(e) {
    event.preventDefault(e);
    var $grid = $('#isotope-container').isotope();
    $grid.isotope({
      masonry: {
        columnWidth: 10
      }
    });
    $grid.isotope('reloadItems');
  });

  $( document ).ajaxComplete(function() {
    var $grid = $('#isotope-container').isotope();
    $grid.isotope({
      masonry: {
        columnWidth: 10
      }
    });
    $grid.isotope('reloadItems');
    // adding the zoom in/out after ajax complete
       $grid.on( 'click', '.isotope-element', function() {
       if ($( this ).hasClass( 'gigante' )) {
       $( this ).toggleClass('gigante');
       } else {
       // change size of item by toggling gigante class
       $( '.isotope-element' ).removeClass( 'gigante' );
       $( this ).toggleClass('gigante');
       }
       $grid.isotope('layout');
       });
  });
}

};
})(jQuery);


Safely change module without losing change at module update I'm using the Image_Widget_Crop module for a Drupal 8 website. In this module there is a .js file setting the default values for Cropper.

Drupal.ImageWidgetCropType.prototype.defaultOptions = {
    autoCropArea: 1,
    background: false,
    responsive: false,
    viewMode: 1,
    zoomable: false
  };

I want to add a setting without putting it in the module so when updating my change doesn't get lost, how can I do this?

I want it to look like this.

Drupal.ImageWidgetCropType.prototype.defaultOptions = {
    autoCropArea: 1,
    background: false,
    responsive: false,
    viewMode: 1,
    zoomable: false,
    toggleDragModeOnDblclick: false
  };

Add your own library with a JS file, make sure the file has a weight higher than the image widget crop's JS file, then simply monkey patch the existing object like so:

Drupal.ImageWidgetCropType.prototype.defaultOptions.toggleDragModeOnDblclick = false;