How do I check whether a node is flagged when it is being deleted? I'm using the Flags module for some functionality on my site. When a node is deleted, I need to check whether it's flagged or not and take additional action based on that. I've implemented hook_nodeapi() in my module to add my logic when a node is deleted. However, it seems I'm unable to check whether the node is flagged or not... I always get FALSE when I check, even when I know that node was in fact flagged. My code so far is:

// check if this node is flagged for renewal
$flag = flag_get_flag('machine_name_of_my_flag');

if($flag && $flag->is_flagged($node->nid)) {
   // add my custom logic here
}

This code is definitely run when the node is deleted. The $flag is found correctly, but $flag->is_flagged($node->nide) always returns false. I based this code on the documentation for the Flag API. I'm not sure why the is_flagged check is always returning false. Is it something to do with the delete action? When I debug this code in xDebug, I can see all the properties of the node object, but I can't find out if it's flagged or not.

That code works, but if the module that implements hook_nodeapi() is executed before Flag; differently, it will be executed after flag_nodeapi(), which removes any reference to the deleted node from the database tables used by Flag.

case 'delete':
  foreach (flag_get_flags('node') as $flag) {
    // If the flag is being tracked by translation set and the node is part
    // of a translation set, don't delete the flagging record.
    // Instead, data will be updated in the 'translation_change' op, below.
    if (!$flag->i18n || empty($node->tnid)) {
      db_query("DELETE FROM {flag_content} WHERE fid = %d AND content_id = %d", $flag->fid, $node->nid);
      db_query("DELETE FROM {flag_counts} WHERE fid = %d AND content_id = %d", $flag->fid, $node->nid);
    }
  }
  break;

If the short name of the module starts with any letter after the f, then that module needs to change its weight to a number lower than 0; it is usually done in the implementation of hook_install(), or hook_update_N().

db_query("UPDATE {system} SET weight = %d WHERE name = 'mymodule' AND type = 'module', -1);


Lazy load with inline images It looks like all popular lazyload modules only work with Images. I would like to get lazyload to work on my inline images (images inserted with Media/FCKEditor).

Do any modules support this? Or is there another way?

I realize this is an old question, but I think this may help others with the same issue.

I recently contributed a module to Drupal community for lazy-loading inline images (and iframes).
Once the module is installed, the filter needs to be enabled in desired text-formats.

It requires no changes to the existing content.

Lazy-load
https://www.drupal.org/project/lazy


Are there any alternatives to drupal_add_js()? Are there any alternatives to drupal_add_js() that permit to write inline JavaScript code?

drupal_add_js() allows inline code:

drupal_add_js($your_js, 'inline'):

You should however not rely on it too much. JS can be better cached by the browser (and aggregated with other JS) if delivered in a separate file.


How to set rel="alternate" hreflang="x"? I am trying to set my hreflang links with this code:

$langcode= $GLOBALS['language']-> language;
//Get enabled languages
$langcode= array_pop(language_list('enabled'));
unset ($languages[$langcode->language]);

// Get path
$path1 = drupal_is_front_page() ? '<front>' : $_GET['q'];
//Get Urls
$links = array();
foreach ($languages as $lang) {
  $links[$lang->language] = array(
    'href'=> $path1,
    'language'=>lang,
    'absolute'=> TRUE,
  );
}
drupal_alter('translation_link', $links, $path1);

//Set head tags
foreach($links as $link) {
  drupal_set_html_head('<link rel="alternate" hreflang="'.   $link['language']->language .'" href="'. url($link['href'], $link) .'" />');
}
//Update head
$vars['head'] = drupal_get_html_head();

with no luck.

While researching I have found this module Internationalization contributions
but it doesn't do anything. Or I don't know how to use it.

You tagged your question as Drupal 7 so I'm guessing the only problem is that you're using drupal_set_html_head() which doesn't exist in Drupal 7.

It's been replaced with drupal_add_html_head(), which you can use like so:

$element = array(
  '#tag' => 'link',
  '#attributes' => array(
    'hreflang' => 'some_language',
    'rel' => 'alternate',
  ),
);
drupal_add_html_head($element, 'mymodule');


Respond.js not working Ive made sure my CSS files are being aggregated but respond.js isnt working.

Here is my site:
http://smartpeopletalkfast.co.uk/cc/

Ive tried both the module (currently enabled) and also using the Zen themes built in option to use respond.js.

Ive added this for debugging, so when media queries are working the page is blank for desktop sized displays.

@media all and (min-width: 720px) {
  body {
    display: none;
  }

I had 'Debug info' turned on in my coumpas.app. Disabling this made it work.


Query URL containing term name instead of term ID on Views Exposed Filters I've got a View with an Exposed Filter that shows Taxonomy Terms that are used to filter the content that's going to be displayed as the result.

It's a View that shows recipes based on the filters chosen by the user (Type of Recipe, Type of Meat).

When I submit the form, I get the following URL:

/recipes-view?type-of-recipe=all&type-of-meat=22

The last parameter shows the number 22, which is the Term ID for the value chosen. The URL has to contain the Term Name instead of the Term ID.

Can I change it via hook_views_query_alter() or is it needed to create a custom handler for that?

Thanks in advance.

There's no need to do this in code. You basically need to:

Add relationship to taxonomy term via entity reference field (it would probably also work with term reference)
Add exposed filter using this relationship (search for field Taxonomy Term: Term)

It works fine and you get URL, such as:

recipes-view?tid=vejuu

If you want to have an URL key type-of-meat, you can set it in More drop-down in you exposed filter configuration. The field name is Filter Identifier

I experienced problems with using features trying to prevent duplicates created by joining taxonomy terms.


Display field in views-view-field--field_title.html.twig If I have view with fields:

field title [hidden]
field text [hidden]
field image [hidden]
field display

and I make rewrite in "display" field with "title" and "text" field added, how can I print content of field "image" (url of this image) with views-view-field--field_display.html.twig? I need wrapper with image url from this field. I see all available variables (view, field, row, output) in template and suggestion to fetch output with construct:

data = row[field.field_alias]

but when I try to write twig code with my field_image alias it's not showing me anything. Field with image is set up to display just url to image. I translated few code lines from drupal 7 to twig, but I am unable to see anything in kint, just dump show me some key strings. Views create block and I am placing this block on my page.

What I am doing wrong?

URL FORMATTER module

This module add a url formatter for image field. Then you can output image url directly.

Enable the module, then in views, click on your image field, and change the Formatter to Image url.
{{ field_with_image_url }}  // will display url instead of picture


What are the pros and cons of using Acquia Drupal install packages? My firm is considering using the Acquia Drupal install packages at http://acquia.com/downloads as a default boilerplate to start with for new client sites. What are the pros and cons of taking this approach?

Boris Mann once described Drupal as a big box of Lego. Acquia Drupal is just a bigger box of Lego.  It still doesn't do anything out of the box, it just gives you more pieces.  Given how much stuff went into Drupal 7 core it is mostly redundant - download core, views, wysiwyg and admin and you can start building good sites.

In terms of pros for Acquia Drupal I'm struggling a little.  The first is that it helps inexperienced users get onto the Acquia Network.  The other is that you don't have to download everything, but this is also a con as you get everything Acquia thinks you need.

One of the biggest cons as I see it is that they dump all the modules under modules/ which is considered bad practice in the Drupal community.  Not only is this annoying if you decide to switch back to stock Drupal + contrib or Pressflow + conrib, but it teaches users bad practices from day 1.

I must admit I played with it once and decided against using it.  These days I assemble my code using drush make as it gives me only what I want and I'm not dependent on a third party to provide security releases after a module is updated I can just update my make file and reroll my stuff.

[rant]These days the community has moved on to building true distros, not just throwing more Lego pieces in a box.[/rant]


Query with db_select() to select node by id and join field and terms I am trying to write a query using db_select that selects a particular node by id, and then joins it's field_data_field_projectresources column and also selects the terms from taxonomy (because this is a term_reference field)

I have tried numerous attempts but I am finding myself stuck (I didn't even get to the part about joining the  dr_taxonomy_term_data table)

 $query = db_select('node','n')
  ->condition('n.nid','5')
  ->fields('n')
  ->fields('p');
 $query->Join('field_data_field_projectresources','p','p.entity_id = n.nid');
 $result = $query->execute();

 while($record = $result->fetchAssoc()) {
   print_r($record);
 }

Any help appreciated, Thanks

I hope this works for you:

 $query = db_select('node','n');
 $query->join('field_data_field_projectresources','p','p.entity_id = n.nid');
 $query->fields('n',array('yourfieldnames'))
       ->fields('p',array('yourfieldnames'))
       ->condition('n.nid','5');
 $result = $query->execute();

Here is another answer that will help you very much.

Check out documentation for 'join' on drupal.org.


handling non-node based items with ubercart I'm working on a book repository website very similar to Islandora which is based on  Fedora Commons and Drupal.

Books's information stored in repository outside Drupal. Apache Solr is configured on server and Drupal to search repository and display result in Drupal.

everything works fine, now I want make this books purchasable in Drupal.

As these search results are not nodes and there is not a node per book, I'm looking for a way to adding this non-node based items to cart!

any suggestion may be helpful!

http://www.ubercart.org/forum/support/14856/non_node_based_items

Having dealt with this exact circumstance before, we had a content type named 'bundle' which was purely a placeholder for the product details in Ubercart.

The user views the product and clicks 'add to cart' and in the cart is an instance of this 'bundle' with the product details in it.

Its far from a good solution and I would definitely be looking at creating a node for each of the products you have for sale - You could even create the nodes when 'added to cart' so you didnt need to add any in advance.

Ubercart has a great API for manipulating cart contents and line items, have you looked at that at all?


Dynamic configuration form i need to do a configuration file wich allow an admin to select a lot of terms from a vocabulary. Then i want to make a form with 2 select field : Vocabulary and Terms. So, i can select the vocabulary i want and a lot of terms of a vocabulary but i don't know to show all terms of the selected vocabulary.

My code :

/*
 * ==================================
 * CONFIGURATION MODULE
 * ==================================
 */
function food_truck_form_admin() {
  $form = array();
  $form['vocabulary'] = array(
      '#title' => 'Vocabulary',
      '#type' => 'select',
      '#options' => food_truck_form_vocabularies()
  );
  $form['terms'] = array(
      '#title' => 'Terms',
      '#type' => 'select',
      '#multiple' => TRUE,
      '#options' => food_truck_form_terms('marqueurs')
  );

  return system_settings_form($form);
}

/**
 * Implementation of hook_menu()
 */
function food_truck_form_menu() {
  $items = array();
  $items['admin/settings/food_truck_form'] = array(
      'title' => 'Food-Truck Configuration',
      'description' => 'Global configurations',
      'page callback' => 'drupal_get_form',
      'page arguments' => array(
          'food_truck_form_admin'
      ),
      'access arguments' => array(
          'administer food_truck_form settings'
      ),
      'type' => MENU_NORMAL_ITEM
  );

  return $items;
}

/*
 * ==================================
 * OTHER FUNCTIONS
 * ==================================
 */

/*
 * Return a term list of a vocabulary by it's machine name or null
 */
function food_truck_form_terms($machine_name) {
  if (! empty($machine_name)) {
    $vid = taxonomy_vocabulary_machine_name_load($machine_name)->vid;
    $terms = taxonomy_get_tree($vid);
    foreach ($terms as $data) {
      $output[$data->tid] = $data->name;
    }
    return $output;
  }
  return NULL;
}
/*
 * Retur a vocabulary list or null
 */
function food_truck_form_vocabularies() {
  $vocabulary = taxonomy_get_vocabularies();
  if (count((array) $vocabulary) != 0) {
    foreach ($vocabulary as $data) {
      $output[$data->vid] = $data->name;
    }
    return $output;
  }

  return NULL;
}

Thanks, i've did this and this work perfectly :

/*
 * ==================================
 * CONFIGURATION MODULE
 * ==================================
 */
/**
 * Implementation of hook_admin()
 */
function food_truck_form_admin() {
  $form = array();
  $form['vocabulary'] = array(
      '#title' => 'Vocabulaires',
      '#type' => 'select',
      '#options' => food_truck_form_vocabularies(),
      '#ajax' => array(
          'callback' => 'terms_callback',
          'wrapper' => 'terms-wrapper',
          'event' => 'change'
      )
  );
  $form['terms'] = array(
      '#title' => 'Types de marqueurs',
      '#type' => 'select',
      '#prefix' => '
',
      '#suffix' => '
',
      '#multiple' => TRUE,
      '#options' => food_truck_form_terms('marqueurs')
  );
  return system_settings_form($form);
}

/**
 * Implementation of hook_menu()
 */
function food_truck_form_menu() {
  $items = array();
  $items['admin/settings/food_truck_form'] = array(
      'title' => 'Food-Truck Configuration',
      'description' => 'Global configurations',
      'page callback' => 'drupal_get_form',
      'page arguments' => array(
          'food_truck_form_admin'
      ),
      'access arguments' => array(
          'administer food_truck_form settings'
      ),
      'type' => MENU_NORMAL_ITEM
  );

  return $items;
}

/**
 * CALLBACKS
 */
function terms_callback($form, &$form_state) {
  $machine_name = $form['vocabulary']['#options'][$form_state['values']['vocabulary']];
  $form['terms']['#options'] = food_truck_form_terms($machine_name);
  return $form['terms'];
}
/*
 * ==================================
 * OTHER FUNCTIONS
 * ==================================
 */

/*
 * Return a term list of a vocabulary by it's machine name or null
 */
function food_truck_form_terms($machine_name) {
  if (! empty($machine_name)) {
    $vid = taxonomy_vocabulary_machine_name_load($machine_name)->vid;
    $terms = taxonomy_get_tffree($vid);
    foreach ($terms as $data) {
      $output[$data->tid] = $data->name;
    }
    return $output;
  }
  return NULL;
}
/*
 * Retur a vocabulary list or null
 */
function food_truck_form_vocabularies() {
  $vocabulary = taxonomy_get_vocabularies();
  if (count((array) $vocabulary) != 0) {
    foreach ($vocabulary as $data) {
      $output[$data->vid] = $data->machine_name;
    }
    return $output;
  }

  return NULL;
}


Why can't I update core from 8.6.16 to 8.7.1? I need to update my Drupal 8 site from 8.6.16 to 8.7.1, but when I run composer update drupal/core --with-dependencies it says "Nothing to install or update". I have been banging my head on the wall about this for 45 minutes, and haven't found anything on Google that fixes this.

Does anyone know why it says there is an update, but then says there is nothing to update or install?

There seem to be some version dependency issue with that email-validator.

I solved it by updating the composer.json to the newer version before updating Drupal:

composer require drupal/core:~8.7.0 --no-update
composer require webflo/drupal-core-require-dev:~8.7.0 --no-update
composer update drupal/core webflo/drupal-core-require-dev --with-dependencies --dry-run
composer update drupal/core webflo/drupal-core-require-dev --with-dependencies
cd web
[../vendor/bin/]drush updatedb
[../vendor/bin/]drush cr

YMMV, here is the Issues where you can get more help if this doesn't work (check the related Issues as well):

Cannot update to Drupal 8.7.0 from 8.6.15 -- egulias/email-validator version conflict

Don't forget to attach your composer.json and composer.lock there so the problem can be properly diagnosed.


Add a wrapper around two panes I want to add a wrapper around the panes which are shown in red box in the given image. How to achieve it.

I have already tried Panels Extra Styles module but it is not providing a wrapper around two or more panes.

Create mini Panel, and add that. In mini panel you give classes, so you can wrap a class.


Views Block: one node latest of several categories Is it possible to do with the views I had one recent node of the 5 categories?
example:
- Category 1 (20 node)
- Category 2 (10 node)
- Category 3 (5 node)
- Category 4 (17 node)
- Category 5 (2 node)

VIEWS BLOCK:

Newest node (category 1) only one!
Newest node (category 2) only one!
Newest node (category 3) only one!
Newest node (category 4) only one!
Newest node (category 5) only one!

You can create a normal view first listing only the newest item (see Pager settings).
Then, create a contextual filter for the category so that you can call the view with different category ids.

Now, you'll the Views Field View module, it enables you to add other views as fields. Add a View Field Views field for each category to your block display.


Update a field without changing the node I need to change a field in a node without altering the 'changed' timestamp. I know this was possible in Drupal 7 using field_attach_update(), but that has been removed since then.

I could use an update query and change the field directly in the database, but I was wondering if there is a better way (or a replacement for field_attach_update()).

Let's try this code:

function MODULE_NAME_node_presave(Drupal\node\NodeInterface $node) {
  $node->set('FIELE_NAME', 'FIELD_VALUE');
}

OR

use Drupal\node\NodeInterface;

function hook_entity_presave(Drupal\Core\Entity\EntityInterface $entity)   {
  if ($entity instanceof NodeInterface) {
    $entity->title->value = 'testing';
  }
}


Store the Logged in Users's Country in the DataBase How could I store the country of the registered user, when he/she logs in. I am hoping I could store it in the DB to later retrieve it within the reports.

I am using Drupal 7.

Many Many Thanks.

Turns out there's a pre-built solution for just that: ip2country

  This module uses a visitor's IP address to identify the geographical location (country) of the user. The module makes this determination and stores the result as an ISO 3166 2-character country code in the Drupal $user object, but otherwise has no effect on the operation of your site. The intent is simply to provide the information for use by other modules. A function is also provided for you to perform your own lookup, to use in your own manner. Features include automatic updates of the IP-country database and admin spoofing of an arbitrary IP or Country for testing purposes.


Is there any way to restore deleted core block in Drupal 8? How to restore core/menu or other programmatically created blocks if they have been deleted in D8?

I remember in D6 and D7 was no possibility to delete programmatically created blocks.
But D8 allows to delete any block. If I delete custom block, I can create it again manually, but if I delete for example Page Title block, there is no way to return page title block to my site.

If you delete some code block in /admin/structure/block

You just need to go on Place block and add block again.

Also Page Title block you can delete and return like this.

In drupal 8 every think is block, menu even a page title.


How can I show field from profile2 instead of username depends on user's role? I have 2 profile2 types (and two common user roles) - "employer" and "applicant". I have "field_company_name" in "profile_employer" and "field_real_name" in "profile_applicant". I want to show field_company_name instead of username for employers and field_real_name for applicants (and "Editor" string for admins). How can I do that?

You can show an alternative name using the Real Name module.

However, you can't show one field for employers and a different field for applicants with Real Name out of the box.

What I would do is reuse the field_real_name in profile_employer and change the label to the company name; this will allow you to use field_real_name as a token for both employers and applicants.

In Drupal, you generally want to reuse fields across content types instead of making new fields if the uses are similar. Doing so makes it much easier to use modules like Real Name, Views, and Rules to manage your entire site.


How do you link a view into a listing dropdown menu? here are some screenshots i created a new sort view and i have tried to add it to the field collection list and then selected it in the page with the drop down and it does not display the view. Am i doing this right? I am using D7 and the

I am using the nodequeue module

https://imgur.com/a/qj3Tt

I'm not reputable enough to comment so I can only post here as an "answer".  But instead of telling you "how", I'm telling you that it appears you can't do this, not easily anyway.

It looks like the options you have available in the node edit form:

are provided by these field settings:

That screenshot of your field settings shows an error:
There is data for this field in the database.  The field settings can no longer be changed. which means you can't add a new value (a view in this case) to those particular settings.

That means you can't do this.  Everytime you click the save button it fails to actually save and displays that error message.

There are some options:

Edit the database directly -- it's dangerous, don't do it on your live site, only do it on a copy/clone of your site until you're sure it works without breaking things horribly, and you probably shouldn't try this at all.
Create a new field with the settings you want.  Then migrate all the data from the old field to the new field.  Delete the old field once the new one is in use and working.  This also should be tested safely on a breakable copy of your site.

Based on what you've shown in your screenshots, those are two possible solutions and neither of them are very good (the second one is better).

It's possible that there actually is a good solution for you, but you really need to provide more information like like @Christia said.  For example, going on your screenshots alone I don't see how this has anything to do with nodqueue or field_collection modules.  This "Listings" functionality in the vertical tabs is mysterious, does it use dgo.to/viewfield or dgo.to/viewreference or some other module?


Manage node body in git For a new blog, I like to have the post text stored as markdown (or an other suitable format) on github. But I want to have all the nice features of drupal (comments, nodes, captcha, menu syste, categories, etc.) for the whole blog.

What options do I have to make Drupal retrieve the node body from git (path, branch, tag), render it, and show it as it would have been entered directly into the body text field?

I don't mind whether an import task fetches the content every now and then or if this is done online.

I'm actually open for all ideas as long I can have people forking and improoving the content and at the same time not loosing all the nice things of drupal.

Update: If possible I'd prefer a use this module solution. If this doesn't exist coding hints are of course welcome as well.

If the content you are importing is not supposed to be edited, I would suggest to follow the same method used on Drupal.org for some nodes: Implement hook_node_view().
In the Drupal.org case, the hook is used to output dynamic content for nodes that once were written using the PHP filter.

This method would allow showing the updated content without to periodically import the content into the node body, it avoids creating revisions for the node, and it avoids having a node body that is edited, and made different from the Github content.
To improve the performance, you can cache the values grabbed from the github, and avoiding accessing it (through drupal_http_request()) too frequently.


Drupal Custom Comment Module I am trying to create my first module in drupal 6.
I just need to add some new fields to the already existing comment form(comment module).
Eg: City,Email and state fields.

I have created 2 files:
1. mmcomment.module
2. mmcomment.info

Used a function hook_form_alter() like this:

 function mmcomment_form_alter(&$form, $form_state, $form_id) { // form override
 if ($form_id == 'comment_form') {
    // unset the other field elements

    $form['subject'] = array(
      '#access' => FALSE
    );
    $form['comment_filter']['comment'] = array(
      '#access' => FALSE
    );
    // add field to all comments

    $form['Email'] = array(
      '#type' => 'textfield',
      '#title' => t('Email Address'),
      '#maxlength' => 255,
      '#size' => 30,
      '#required' => 1,
      '#weight' => 1,
      '#default_value' => $email
    );
     $form['displayName'] = array(
      '#type' => 'textfield',
      '#title' => t('Display Name'),
      '#maxlength' => 255,
      '#size' => 30,
      '#weight' => 2,
      '#default_value' => $displayName
    );

    $form['_author'] = array(
      '#access' => FALSE
    );
    $form['author'] = array(
      '#access' => FALSE
    );

I need to get the form values and insert into DB.
What Function can I use for the same.
I have tried:
hook_nodeapi(mmcomment_nodeapi).
But can't get the form values.
Any suggestions..
Thanks

In the $form structure you have to add/override the submit (and maybe the validate) handler.


self hosted video player/soution with fallback I use drupal 6 and I am looking for a way to play my own videos (only one per product page).
I use views to display content.
Player should have ability to fallback to browser player for users with javascript disabled.
Similar solution is implemented on zappos page for example here http://www.zappos.com/reef-fanning-brown-lux?zfcTest=fcl%3A0

If I click on video with javacsript disabled, I get a new window with video playing.

Can anybody recommend a solution? Thank you

You could probably use:

https://drupal.org/project/jwplayermodule

  Full support for JW Player for Flash and HTML5.
  Manage multiple custom players.
  Full skin and plugin support with easy to use plugin customization interface.
  A powerful shortcode system for customizations at embed time.
  CCK Field support.
  Integration with the popular FileField module.
  Integration with the Embedded Media Field module.


Drupal 7 & Facebook Connect - Connect Button Problem! Help please? I installed the module Drupal For Facebook. So far it was working perfectly, I enabled Facebook Connect and put the Facebook Connect login block in a sidebar. It was great until I went into configure the Facebook Connect login block and changed text in the body. Now the CONNECT button no longer appears and only text appears saying the words "Connect." I've tried every mix of plain text, full html, and filtered html to include the suggested enter of: Connect to no avail. The only thing I see is the word Connect in plain text every time.

I need to reset this module to default or learn how to properly add the button back. But I am very new to Drupal and have no idea how to do it.

I have the same issue, FB Connect will do this when your site tries to connect to an  FB App and cannot. Check your API and Secret keys first, other possible problems are the URL settings which should match in both FB and Drupal/FBConnect. Lastly in my case, everything was working until I reset an auth key in FB which I should not have done and it created issues for me.


How does the global variable $user work? Here is my scenario:

I create a new user and dynamically create for him some content on which he is the owner.

Each user can log in, see his content and edit his profile. I use a block in which I have a menu links to each content and to his profile.

The theme output of the block function uses global $user; to get the current logged user.

However, the strange thing is that $user->uid return the last created user in the system and not the current logged user. Also the $user->language is of the last created user in the system. Why?

The user logs out with user/logout; this is the command to log out, right? Do I need to do more after user logout such as GLOBAL variable resets?

I would check to see that the block is not getting cached, or that you are not using something like Boost (static caching).

Sounds like the block contents are being cached to me.


How to programmatically get the difference between two entities of same content type? I need to implement a function that checks if there has been a change from the previous existing node. If yes, send the updated changes.

I understand that Drupal has revision system and through diff we can see the difference between two revisions.

I want similar to that, however as an API call or a logic which can facilitate getting the difference.

Either look at:

https://www.drupal.org/project/diff
https://www.drupal.org/project/html_diff

To easily "see" if changes exist. Or look at Migrates module track_changes implementation and implement it in code between revisions. All track_changes does is hash the fields of a content type together to get a unique ID. Different revisions of a node with changes between the body field will of course hash to a different value. Be sure to exclude node fields such as NID, vid, updated_at and other fields that (may) chnage between revisions.

Sample hash code from class MigrateSource:

// When tracking changed data, We want to quietly skip (rather than
// "ignore") rows with changes. The caller needs to make that decision,
// so we need to provide them with the necessary information (before and
// after hashes).
if ($this->trackChanges) {
    $unhashed_row = clone ($row);
    // Remove all map data, otherwise we'll have a false positive on the
    // second import (attempt) on a row.
    foreach ($unhashed_row as $field => $data) {
      if (strpos($field, 'migrate_map_') === 0) {
        unset($unhashed_row->$field);
      }
    }
    $row->migrate_map_original_hash = isset($row->migrate_map_hash) ?
      $row->migrate_map_hash : '';
    $row->migrate_map_hash = $this->hash($unhashed_row);
  }
  else {
    $row->migrate_map_hash = '';
  }


How do I override the mail system? In my application, all mails aren't sent via the Drupal default mail system or SMTP. We have a third-party API which sends all emails. So, whenever the plugin.manager.mail service is called, the class I define in a custom module should be used.

How can I achieve this?

You can achieve this by overriding the service defined from Drupal core.
Altering existing services, providing dynamic services describes the code to use.

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

namespace Drupal\my_module;

use Drupal\Core\DependencyInjection\ContainerBuilder;
use Drupal\Core\DependencyInjection\ServiceProviderBase;

// @note: You only need Reference, if you want to change service arguments.
use Symfony\Component\DependencyInjection\Reference;

/**
 * Modifies the mail provider service.
 */
class MyModuleServiceProvider extends ServiceProviderBase {

  /**
   * {@inheritdoc}
   */
  public function alter(ContainerBuilder $container) {
    $definition = $container->getDefinition('plugin.manager.mail');
    $definition->setClass('Drupal\MY_MODULE\MyMailProvider');
  }
}


How to load a variable through different nodeapi's $op? I have a registration form on which I ask if user want to participate to a certain program ; if he clicks "yes", then i have a conditional field which requires to upload a picture. There are some problems for validating a picture with drupal, so I decided to create my own validation system.

If the user clicks on "yes" but doesn't upload a picture, then there must be an error message. If the user clicks on "no", the user can't upload a picture (thanks to conditional field).

For that, I've written this under a hook_nodeapi() function :

        if ($op=='validate'){
        if($node->type == 'profile'){
            // check if the user accepted or not
            if ($node->field_prof_firstflash[0]['value']=="Yes"){
                //check if there's an image loaded
                    if ($node->field_prof_img[0]['filesize'] == 0)
                        form_set_error('field_prof_img', t('Please upload a profile picture.'));
                }
            }
        }
    }

The problem comes when a user wants to edit his settings, later. If the user said "Yes" before but eventually wants to turn it off, my preceding code won't work anymore since $node->field_prof_firstflash[0]['value'] is still set to "Yes". Then, I thought about loading a variable when $op=='prepare' like :

        if ($op =='prepare'){
        $firstflash = $node->field_prof_firstflash[0]['value'];
        $img=$node->field_prof_img[0]['filesize'];

    }
    if ($op=='validate'){
        if($node->type == 'profile'){
            // check if the user accepted or not
            if ($firstflash=="Yes"){
                //check if there's an image loaded
                    if ($img == 0)
                        form_set_error('field_prof_img', t('Please upload a profile picture.'));
                }
            }
        }
    }

But of course (this would have been too simple :-) ), $firstflash is not loaded when $op=='validate', even with that piece of code...

Does anyone has any idea on how to do that?

At first sight, it looks like you would be better off implementing hook_form_alter, adding a custom validation handler. A form validation handler will give you access to the submitted values in $form_state as well as the previously stored values.


Displaying a text field for the user to embed media, and then enabling rating (fivestar) for that content; listing all of them as separate writings On a given site's page, which is supplied with the "casting" URL alias, I would like to show some embedded videos with a description field, which users have uploaded (embedded) via a simple text field that Embedded Media Field processed. These would appear as separate writings, signing the user who uploaded this stuff.
There would also be a rating/voting opportunity (fivestar, thumbs up/down, etc.) with the help of Rate or Fivestar module (which one do you suggest?!) to let users vote for the embedded video.

When someone logs in, I would like to show the form which helps embedding (or a link to this form) at the top of the page, and below that, there would be the embedded media from the different users.
So the form would be as simple as that: containing a text field, in which e.g. Youtube URLs could be copied (it would be processed by Embedded Media Field module) and a description textarea to write about the embedded stuff.
The result output would contain these: the embedded media, the description, who this post created and when, and a rating/voting opportunity (five stars, etc.).

How could I do that? What do you suggest for creating a form like that?
Maybe it's not too difficult, but I didn't find the perfect solution, and I couldn't restrict content types to these fields (and with the help of Webform I couldn't add a field of Embedded Media Field).

Why don't you just let your users create a node with this field and a fivestar widget and then you use node_view() to display these nodes in your page.

Updated:
To embed the node form in a page, have a look at Embedding CCK content type create form in your page, then create a block and put this code in it (select the php format - you have to activate the php filter module first):

if(!function_exists("node_object_prepare")) {
  include_once(drupal_get_path('module', 'node') . '/node.pages.inc');
}
print node_add('store_review');  //put the content type machine name here.

Then on another page you create a view to retrieve the listing of your videos.

You can also have a look at the Blockify module it may be useful to embed the node form (I'm not sure it'll do the job but can be easy if you're not comfortable with embedding PHP code in a block).


Is Entity Translation module compatible with Internationalization and can they be used to translate menus? I installed the entity translation module for Drupal 7 and it works fine.

However, I also want to translate menus and I found that Internationalization module can do that.

The question is: are they compatible at all? If I install internationalization module will it not break the entity translation one?

Yes, they are compatible.

Entity Translation deals with entity translations, and menus in Drupal 7 are not entities, there's no clash between Entity Translation and Internationalization modules.


Add CSS class to view image_field in twig In my custom view fields twig file views-view-fields--search--product_result.html.twig I try to theme my view item.

{{ fields.field_images.content }}

{{ fields.title.content }}

How do I add a CSS class to my image field {{ fields.field_images.content }}?

This is what worked for me: It's a preprocess function in the .theme file. I wish there was a way to do this directly into the template. This would apply that class everywhere the field appears.

/**
 * Implements hook_preprocess_field().
 * Adds a class to a People image.
 */
function themename_preprocess_field(&$vars) {
  if ($vars['element']['#field_name'] == 'field_machine_name') {
    foreach($vars['items'] as $key => $item){
      $vars['items'][ $key ]['content']['#item_attributes']['class'][] = 'my_class';
    }
  }
}

themename, field_machine_name, and my_class are placeholders for your values.

This produces:

<img class="my_class" src="/your/image/location.png" alt="Your alt text." typeof="foaf:Image" width="458" height="354">


7 - Dynamically changing links based on environment I am working with a Drupal site that is a central hub for several other pieces of software. The Drupal site and the other Software all have their own dev, testing and production environments. Each of these environments have their own url.

What I am looking to do is to change these urls based on the current envrionment by setting a variable/token of some kind. For example:

If the site is in dev, it links to all other dev versions of the software. For example dev-drupal.website.com links to dev-software1.website.com and dev-software2.website.com
If the codebase moves to testing, there is a file (for example the template.php) file that either doesn't need to be changed, or needs to be changed once to change all of the links.

There are over a dozens of these externally linking software pieces, and they are often linked in the content, but there are also menu items, blocks and a few views. Currently we have to do a find and replace to manually change these links one at a time. I'm trying to figure out if there is a better way, perhaps through a template variable or a token. Any ideas? This solution would ideally not be stored in the db, but I'm flexible.

I'm looking for suggestions on the best approach.

I don't think I would try to do this in Drupal. I would setup a small proxy server using Apache/mod_rewrite. You can rewrite your url's based on the source url. There is some good starter information at on the Apache doc site. There is also full on mod_proxy, but I think mod_rewrite would be sufficient for your use case.


How to transfer data from the program's created field to the standard text, while saving the node? Using hook_form_alter(), I created 4 form fields. When saving a node, I want to extract data from them and transferred to a standard field.

Using foreach(), I can form a string and then transfer it to the standard field, but how do I get the data from the form input, while saving material?

I use hook_node_presave($node) but it already takes $node as argument, in which there are no custom fields. I do not know how to transfer them here and already work with hook_node_presave().

$form['field_cadastral_num'] = array(
    '#type' => 'fieldset',
    '#title' => 'test',
    '#attributes' => array(
        'class' => array(
            'field-type-text',
            'field-name-property_node_form'
        ),
    ),
  '#weight' => $instance['widget']['weight'],
);
$form['field_cadastral_num']['cell'][] = array(
  '#type' => 'textfield',
  '#default_value' => '',
  '#size' => 3,
  '#maxlength' => 3,
  '#name' => 'kadastr[0]',
  '#value' => ''
);
$form['field_cadastral_num']['cell'][] = array(
  '#type' => 'textfield',
  '#default_value' => '',
  '#size' => 3,
  '#delta' => 3,
  '#maxlength' => 3,
  '#name' => 'kadastr[1]',
  '#value' => '',
  '#prefix' => ':'
);
$form['field_cadastral_num']['cell'][] = array(
  '#type' => 'textfield',
  '#default_value' => '',
  '#size' => 6,
  '#maxlength' => 6,
  '#name' => 'kadastr[2]',
  '#value' => '',
  '#prefix' => ':'
);
$form['field_cadastral_num']['cell'][] = array(
  '#type' => 'textfield',
  '#default_value' => '',
  '#size' => 3,
  '#maxlength' => 3,
  '#name' => 'kadastr[3]',
  '#value' => '',
  '#prefix' => ':'
);

I would suggest you create the 'cell' fields through the Drupal UI (admin/structure/types/manage/xxxx/fields) so they are registered correctly as part of the content type, then their values will be available in hook_node_presave().


Drupal 7 - HTTP/AJAX/JSON responses at same URL with Accept Header (like D8) Drupal 8 has this new amazing in-built functionality for handling requests from browsers and via AJAX at the same URL using the Accept header, which makes the CTools way of adding "nojs" to URLs, and then changing that to "js" in the JavaScript seems like a clever but antiquated hack.

Is there a cleaner way to do this, that could be considered a "best practice" for Drupal 7 going forward, that is more inline with how things are now done in Drupal 8?   Also, how does a traditional ajax response versus a json response factor into this?

Code examples would be highly useful here.

I am not sure whether this is clean or "best practice" but I am currently using something like this:

  // If the request has the header 'Accept: application/json'
  // return the output in JSON format and stop.
  if ($_SERVER['HTTP_ACCEPT'] == 'application/json') {
    drupal_add_http_header('Content-Type', 'application/json; utf-8');
    print json_encode($strings);
    exit;
  }

To see it in the context, here is the whole function:

<?php
/**
 * Menu callback: translations/search.
 *
 * Search strings and translations using various filters.
 *
 * If the request header 'Accept: application/json' is set, then
 * the output will be in JSON, otherwise it will be an HTML page.
 * For example:
 *   curl -k -i -H 'Accept: application/json' \
 *        'https://dev.l10n.org.xx/translations/search?lng=sq&words=space'
 */
function btrClient_search() {
  // Get the search parameters from the GET request.
  $params = btrClient_get_search_params();

  // Get the strings that match the search params.
  $btr = btr_user_is_authenticated() ?
    wsclient_service_load('btr') :
    wsclient_service_load('public_btr');
  $result = $btr->search($params);
  $filter = $result['filter'];
  $pager = $result['pager'];
  $strings = $result['strings'];

  // If the request has the header 'Accept: application/json'
  // return the output in JSON format and stop.
  if ($_SERVER['HTTP_ACCEPT'] == 'application/json') {
    drupal_add_http_header('Content-Type', 'application/json; utf-8');
    print json_encode($strings);
    exit;
  }

  // Add the CSS and JS files.
  drupal_add_css(drupal_get_path('module', 'btrClient') . '/editor/editor.css');
  drupal_add_js(drupal_get_path('module', 'btrClient') . '/editor/jquery.worddiff.js');
  drupal_add_js(drupal_get_path('module', 'btrClient') . '/editor/editor.js');

  // Add RTL style if the current language's direction is RTL.
  $languages = btrClient_get_languages();
  $lng = btrClient_get_translation_lng();
  if ($languages[$lng]['direction'] == LANGUAGE_RTL) {
    drupal_add_css(drupal_get_path('module', 'btrClient') . '/editor-rtl.css');
  }

  // Set the title.
  drupal_set_title(t('Search Translations'));

  // Add the filter form.
  $output = array(
    drupal_get_form('btrClient_filter_form', $filter),
  );

  // Output the strings.
  if (empty($strings)) {
    drupal_set_message(t('No strings found. Try adjusting the filter options.'));
  }
  else {
    pager_default_initialize($pager['number_of_items'], $pager['items_per_page']);
    $output[] = drupal_get_form('btrClient_translate_form', $strings, $lng);
  }

  return $output;
}

(Or check it out here: http://cgit.drupalcode.org/btrclient/tree/includes/search.inc


put the contents of one field into another field upon form submit how can I add a field to a form submission upon submit that will have the same value as the field name "mail" but with the name "email"

I think it'll work if you implement hook_form_submit() hook for this form, and in that function set the value of one field to another.

E.g.,

FORM_ID_form_submit($form, &$form_state) {
  $form_state['values']['email'] = $form_state['values']['mail'];
}

If your fields are fields of a content then replace the above line with this:

$form_state['values']['email']['und'][0]['value'] = $form_state['values']['mail']['und'][0]['value'];


Prevent directory permissions of sites/default from being protected in a local environment? Drupal automatically changes the directory permissions of sites/default to 555 (i.e. read-only), which means that if I'm editing sites/default/settings.php, even if I've set the permissions for that file to read/write (which it again reverts on a page load), PhpStorm still gives me a permission denied error on the swap file it's attempting to create in the same directory.

Is there a more flexible way to update settings (especially on
a dev machine) other than manually setting the file and directory
permissions every time you need to edit those files?
Do I just have to do it via sudo?
Can I disable permissions checking for a specific environment?

If you are on Drupal 8, you can configure settings.php to include a settings.local.php with a simple environment check (to ensure you are running a local env).

In that file, you can add this:

$settings['skip_permissions_hardening'] = TRUE;

This will allow you to open and write to settings.php without it being locked back down.


Integration with the RDF module I have a module that creates HTML output. Does it need to support the Drupal 7 RDF module?
What are the functions made available from the RDF module that allows a module to integrate with it? What hooks does the module use?

Themes will work with the RDF module if they use the proper attributes variables.

If you are generating HTML outside of the core theming (which seems unusual) system you will need to get this information yourself. The RDF mapping api is quite well documented. Essentially there is a mapping between fields and RDF. So a title field could have a mapping of dc:title.

In summary

rdf_get_namespaces() will show the namespaces that need to be included in your document.
rdf_mapping_load() will show the rdf mappings for an entity type.

You can then add rdfa markup to the fields as you output them.

edit

If you are using standard theme functions, then so long as you stick to the D7 guidelines all of the RDF magic should be done for you. Specifically make sure that you use $attributes $title_attributes and $content_attributes.

If you want to know how to define RDF mappings, then please ask more questions.


Content locking module for Drupal 7 Is there a stable module for content locking (anti-concurrent editing). I found this https://drupal.org/project/content_lock but it's unsupported.
Thanks

This is already built-in in Drupal 6 and 7, in the function node_validate.

The relevant piece of code is reproduced below:

if (isset($node->nid) && (node_last_changed($node->nid) > $node->changed)) {
  form_set_error('changed', t('This content has been modified by another user, changes cannot be saved.'));
}

It doesn't lock anything, but it shows the second editor a message, and prevents the second editor from saving and thereby overwriting what the first has done. The second editor can then copy-paste his/her efforts to Notepad or other temporary buffer, reload a fresh version of the node (i.e. a version that contains the first editor edits), add his stuff again, and save.

This warning message serves the same purpose as locking, but IMHO it does it better and less prone to deadlocks.

The problem with an outright lock is that users may open a node edit page but don't actually do any edits.  If they just abandon it (i.e. don't press "Save") it will remain in that state until reset.  Doing it on save is better because it avoids the deadlock situations that may arise from locking something the user may abandon.


Force authentication for specific IP range on IIS I have a Drupal 6 installation as a corporate Intranet site.  I would like to permit a set of IP ranges the ability to view the site anonymously, and anything that does not match that rule must authenticate (either by form, or by HTTP - either would be fine).

I've looked at httpauth (obsolete) - this could be made to work, but I found it wasn't reliable under IIS.

I looked at securesite (what took the place of httpauth), but was getting issues with the form authentication (didn't look at the http authentication portion in detail).

In both cases, the modules didn't seem to be configurable to configure that behaviour on a per-ip basis, but I expect could be modified to do so.

Anyone know of anything out there that might solve this problem?

Use the Rules module to determine if the user is from a specific IP range, or is authenticated.  If they are not from that IP range or not logged in, redirect to Login page.

Install and enable Rules module.
Create a new Rule that is triggered when Drupal is initializing.
Add a Condition of Data, Text Comparison
Add a Data field of site:current-page:path that matches user, and negate the condition so this Rule requires this Condition to be False.
Add a Condition Or group, set it to Negate, so that if neither condition are positive it will execute an action
Within the Or group, add a condition that executes PHP Code. Enter PHP code that returns True if the IP is in range (learn how to get the visitors IP).
Within the Or group, add another condition of User's role. Configure the condition to return true if the User has the Authenticated User role.
Add an Action of Page redirect, and redirect the user to user, or some other page where they can login.
Save and enable the Rule.


How to show one page over another in custom way I need to show one page over another for non-admin users much like

overlay feature in Drupal7 applicable for admin users. I tried out

overlay module and overlay UI module but not of much help.

All the overlaying pages are custom created and will be invoked on

working page after clicking a link.

Please refer me a solution which should work across all browsers and I

can adjust width and height of overlaying page.I want to implement this

solution for pop up messages, warning and alert also.Please see below

image for reference:

Need your much appreciated help.

I think you are looking for Popup module or Lightbox


How to cancel added product to cart if previous order has same commerce-product creator id I need this rule on before add product to cart react event, not after save commerce order.

I need when user (buyer) klick second button add to cart (for multi order), system check the product creator id first, if the product creator id for the second order clicked is same with previous (where is actually on cart) system cancel the previous clicked order.

With this scenario I want to limit order only from same product creator for one times order. So if buyer want to continue order from different product creator they have to do after first order completed.

Any suggest how to solve this using rule??

tl;dr - Rules is really the place to handle this. You need to hook into the add to cart form's validate/submit handlers and take care of it in there.

The best way to handle this is to look into the answer provided here: How do I prevent a product from being added to the cart?

This answer was originally written to do that very thing: to prevent a product from being added to an order if some criteria were met (and the context was a marketplace multi-cart as well).


Display main menu for logged in users only I'm new to drupal and using the latest version (7.x). I want hide the Main Menu in all pages until user log-in to the site. I set the Main Menu block role set to "Authenticated Users" only. But I can see the Main Menu on all pages as anonymous user.

How could I hide the Main Menu for anonymous user and show them once logged In ?

If you are assigning main menu (as block) to region, you can control it's visibility by "Visibility settings". If you are rendering it in .tpl.php file then you can do it like this: Example (bartik's page.tpl.php):

<?php if ($main_menu && user_is_logged_in()): ?>
  <div id="main-menu" class="navigation">
    <?php print theme('links__system_main_menu', array(
      'links' => $main_menu,
      'attributes' => array(
        'id' => 'main-menu-links',
        'class' => array('links', 'clearfix'),
      ),
      'heading' => array(
        'text' => t('Main menu'),
        'level' => 'h2',
        'class' => array('element-invisible'),
      ),
    )); ?>
  </div> <!-- /#main-menu -->
<?php endif; ?>


Create images defined by image styles on node save In Drupal 7 I wish to create several images defined by image styles when saving a node. There is only one image field, and it is just several styles of that image that I need to generate.

None of these images are displayed when viewing the node, they will be accessed through XML and Services.

I think mabye the hook_preprocess_HOOK and theme_image_style can be used as pointed out in this question: Multiple image styles. Is this correct? And if so, can anyone point me to some examples where this is done? In the link above, images are echo'ed out, but is this how it should be done when saving a node?

I ended up creating a separate content type and a theme template file that solved this specific problem I had. I will update this if I ever find a way to do this in a module or other.

EDIT:

I ended up creating a module that solves this.

in hook_menu:

function mymodule_menu () {
  $items['node/%/generateimages'] = array (
    'title' => 'Generate images',
    'page callback' => 'mymodule_generate_images',
    'page arguments' => array(0, 1),
    'access callback' => TRUE,
  );
}

In the callback function:

function mymodule_generate_images ($arg1, $arg2) {
  $retval = '';
  $path   = drupal_lookup_path ("source", $arg1 . '/' . $arg2);
  $node   = menu_get_object ("node", 1, $path);

  drupal_set_title ('Generate images ' . $node->title);

  global $language;
  $lang = $language->language;
  $files = field_get_items ('node', $node, 'field_image');

  foreach ($files as $key => $media) :
    $url   = image_style_url ('related_thumbnail', $media['uri']);
    $thumb = theme ('image_style', array('style_name' => 'related_thumbnail', 'path' => $media['uri']));
    $retval .= $thumb;
  endforeach;

  return $retval;
}

After node creation, I manually have to go to thenodeurl/generateimages and images defined in the callback function is created.

I wish someone could tell me a better way to solve this :)


Entity Reference Filter: Filter users by role I want to attach managers to site customers. I made Entity Reference "user-to-user" and now I want to select users only with role "Managers".

How can I make such filter?

As far I understood you want to see only "Managers" in Entity Reference widget on user add/edit page.

Entity reference widget can filter values by using "Views" module.

You can just create an "Entity reference view" and get all users with role "Manager" there.

Here is instruction for widget settings: https://drupal.stackexchange.com/a/38917/6309


User Login Form Error Message Problem I'm adding the user login form to the homepage of my site and through printing it out in my page.tpl.php, the validation is getting lost a bit.   The first time I enter in an incorrect username or password, nothing happens, but the second time everything acts as it should. I am confused about why it does not display the first time.

In my page.tpl.php

print drupal_render(drupal_get_form('user_login_block'));

In my template.php

if ($form_id == "user_login_block") {
  $form['links']['#markup'] = ' ' . t('Forgot username or password?') . '';
  $form['name']['#title'] = t('Username'); // Change text on form
  $form['name']['#attributes'] = array('placeholder' => t('Username'));
  $form['pass']['#title'] = t('Password');
  $form['pass']['#attributes'] = array('placeholder' => t('Password'));
  $form['actions']['submit']['#value'] = t('');
}

My Custom Validate Module

function hook_form_alter(&$form, &$form_state, $form_id){
  if($form_id == 'user_login_block'){
    $form['#validate'][] = '_custom_validation';
  }
}

function _custom_validation(&$form, &$form_state){
  $query = db_select('users', 'u');
  $query->fields('u', array('name'));
  $query->condition('u.name', $form_state['values']['name'], '=');
  $result = $query->execute();
  $name = $result->fetchField();
  if(empty($name)){
    form_set_error('user_name', t('Username or password could not could not be found.'));
  }
}

I also have the module "Email Registration" Installed, not sure if this has anything to do with it also.

Would anyone know anything about this?

What is the reason for you adding the form in that manner and having custom validation etc. when drupal already gives you this?

For example, why not just use the drupal block system or the context module to place the login block on your homepage within one of the regions?

Another thing is that your custom module should not have

function hook_form_alter(&$form, &$form_state, $form_id)

it should be

function MODULE_NAME_form_alter(&$form, &$form_state, $form_id)

Where you replace MODULE_NAME with your module's name.
Although maybe you only had it that way for this post.

Also, regardless of the method you use to show the user_login_block form, it already has its own validation functions that come with it. It already has these three validation functions:
http://api.drupal.org/api/drupal/modules!user!user.module/function/user_login_name_validate/7
http://api.drupal.org/api/drupal/modules!user!user.module/function/user_login_authenticate_validate/7
http://api.drupal.org/api/drupal/modules!user!user.module/function/user_login_final_validate/7

With the last of those doing (among other things) essentially the same validation your custom function is trying to do.

You can still use the form alter to add your attributes and change titles, etc.
In this case though the module weight does not matter.
It only matters if two modules are both using hook_form_alter() and are changing the same parts of the form.


imagecache permissions How to allow authenticated users to see all versions of images but prevent anonymous users to see 'large' images created with an imagecache preset?

I've ticked the correct boxes under the permissions tab of imagecache so that anonymous users aren't able to see these images but still they show up.
What am I doing wrong? (I've flushed the cache of the imagecache)

Cheers.

A quick look through the imagecache module suggests that the only time the module itself enforces the "view imagecache [preset]" permission is when it is serving private files.  This makes sense in that once the image derivative is created in the public files structure, it is never called; once a file "really exists" drupal is never bootstrapped up, it is only booted up to create the derivative the first time it's not found.

So, then, what are these permissions useful for?  Well I'd imagine so you could do something like this...

$presets=array('small', 'medium', 'large');

foreach($presets as $preset) {
  if (user_access('view imagecache ' . $preset)) {
    // do whatever your module wants with that preset, create a link, show the image, whatever
  }
}

...in your own module.

As for lightbox2, a quick look there shows it just presents a list of possible Display Field options using all of the imagecache presets.  As to why it doesn't check these permissions when building these links is a question for that module's maintainer on its issue queue on drupal.org.


Different redirect page for registration, login and first time login Im trying to redirect the user to different pages on login, first-time login and registration. I used the Login Destination module but it only has the option to redirect the user to one page on registration login and first-time login. Is there another way of doing this?

I have not tested this but from the documentation page:

  There are no separate triggers for login and registration; instead you
  can differentiate them by specifying the pages that a user comes from:

  user - the user login form.
  user/register - the user registration form.
  user/*/edit - one-time login link, after the user has set the password.
  other - the login block or login forms embedded by other    modules.

It looks like you can specify both three options you ask for.


Session variables and page cache My drupal site uses normal cache system, as you'll probably know, the cache_page table is updated using as primary key the REQUEST_URI. This is great because when an anonymous user requests a page, drupal serves it to the client from the cache_page, and the best part is that all variables in the GET request are part of the cache id for serving that page.

So for example if I have these URL's

http://domain.com/gallery
http://domain.com/gallery?list_mode=thumbs

Both url's are different in the cache_page table.

The problem comes here, I want anonymous users to remember the last option that selected as "list_mode", so the next time they come they'll get one or another list mode by default. So I added list_mode as a SESSION var.
The problem is that accessing

http://domain.com/gallery

as anonymous, the page is served from cache with the default list_mode. (whose value is not "thumbs")

I don't want to stop using cache_page for this url (this was a possible solution), and the ideal thing would be adding some way this SESSION variable to the REQUEST_URI so the page will be served as it should , in this case would consist of translating:

http://domain.com/gallery  TO  http://domain.com/gallery?list_mode=thumbs

before checking the cache, so the user gets the second URL served instead of the first.

hook_boot would be a good place to do that, but I don't think that hacking the request_uri is a good idea, so, is there any other way to do this approach ?

Thanks for your help.

PS: I found a similar issue, the user makes use of the RewriteCond to achieve what he wants, and asks for a better solution, but the only answer advises to disable caching for that pages:
Cache page based on cookie value and URL

On the other answer, the page cache is bypassed on the first hit. Subsequent hits do hit the page cache because the cookie will be set then.

To answer your question, have some client side javascript that sets a cookie called gallery_list_mode. If no selection is made, set it to 0 or delete it. If user selected thumbs, have the javascript set the gallery_list_mode cookie to thumbs. Then inside of your settings.php drop this in

<?php
// Check if cookie is set and user is on a gallery page.
if (!empty($_COOKIE['gallery_list_mode']) && $_SERVER['REQUEST_URI'] == '/gallery') {
  $ok_list = array(
    'thumbs',
  );
  if (in_array($_COOKIE['gallery_list_mode', $ok_list)) {
    // Add cookie value to page cache id.
    $_SERVER['REQUEST_URI'] .= '?list_mode=' . $_COOKIE['gallery_list_mode'];

    // This line might be needed.
    //$_GET['q'] .= '?list_mode=' . $_COOKIE['gallery_list_mode'];
  }
}
?>

This will make http://domain.com/gallery point to the cache entry for http://domain.com/gallery?list_mode=thumbs if the gallery_list_mode cookie is set to thumbs.

As a security feature you should make sure to only accept values for gallery_list_mode that you want. That is what the $ok_list array is for.


Connect Drupal to external data base Is there a specific module or a definied mechanism to connect a given external data base to a view?

settings.php

$databases = array (
  'default' => array (
    'default' => array (
      'database' => 'd3js',
      'username' => 'root',
      'password' => '',
      'host' => 'localhost',
      'port' => '',
      'driver' => 'mysql',
      'prefix' => '',
    ),
  ),

  'NewDataBase' => array (
    'default' => array (
      'database' => 'NewDataBase',
      'username' => 'username',
      'password' => 'password',
      'host' => '131.188.76.40',
      'port' => '3306',
      'driver' => 'mysql',
      'prefix' => '',
    ),
  ),
);

This is the module that is related to the view.

 /**
  * @file
  * D3 views module file.
  */

 /**
  * Implements hook_views_api().
  */
  function d3_views_views_api() {
   return array(
   'api' => 3,
   'path' => drupal_get_path('module', 'd3_views') . '/views',
  );
 }

 /**
  * Implements hook_theme().
  */
function d3_views_theme() {

   return array(
   'views_ui_style_d3_options_form' => array(
   'render element' => 'form',
   ),
 );

}

/**
 * Implements template_preprocess_views_ui_style_d3_options_form().
 */
 function d3_preprocess_views_ui_style_d3_options_form(&$vars) {
   drupal_add_css(drupal_get_path('module', 'd3_views') . '/css/views_ui_style_options_form.css');
 }

/**
 * Theme the form for the table style plugin.
 */
 //declarition of the variables related to form (tree)
 function theme_views_ui_style_d3_options_form($variables) {
 $form = $variables['form'];

 $output = drupal_render($form['library']);

 $header = array(
 t('Field'),
 t('Display'),
 t('Aggregation'),
 t('Data type'),
);
 $rows = array();
 foreach (element_children($form['columns']) as $id) {
 $row = array();
 $row[] = drupal_render($form['columns'][$id]['name']);
 $row[] = drupal_render($form['columns'][$id]['display']);
 $row[] = drupal_render($form['columns'][$id]['aggregate']);
 $row[] = drupal_render($form['columns'][$id]['type']);

 $rows[] = $row;
 }

 $output .= '<fieldset><legend>Data</legend>' . theme('table', array('header' => $header, 'rows' => $rows)) . '</fieldset>';

 $output .= drupal_render_children($form);
 return $output;
}

This module also has and I didn't know exactly where to connect to the database.

You will need to add the following configuration in your settings.php file

$databases = array();
$databases['default']['default'] = array(
  // Drupal's default credentials here.
);
$databases['my_other_db']['default'] = array(
  // Your secondary database's credentials here.
);

Refer to settings.php for the array options.

Now if you are using a custom module you can use the following in  your module to switch between the 2 db's

// Use the database we set up earlier
db_set_active('my_other_db');

and if you want to move back to the default db

// Go back to the default database,
// Remember to go back to the drupal default version or drupal will not be able to access its data
db_set_active();

Also refer to https://drupal.org/node/18429 for more information.

There is one more of doing it if you do not want to do the db_set_Active() all the time.

So you define the connection in your settings.php like in the first step. Then in the module you can directly do the following

$query = Database::getConnection('default', 'my_other_db')
           ->select('source_table', 'st')
...


Is it possible to enable the title field for the module views slideshow? I'm working with the module views slideshow and was just curious if anyone knew how to enable to title field for the images you upload for it. The alt text field is enabled but not the title field.

And no you don't just go to edit the field.

Consider looking at Views Slide show Content title and description modification, which details the steps to do this, such as:

Set the title field to "exclude from display".
Check the option "Rewrite the output of this field".
Put the token in a DIV, and style with CSS as needed.


How do I escape tokens in CKEditor? For documentation purposes, I'd like to write an article with token in it, for example [toc].

How can I can avoid it is processed as token, and replaced?

I achieve it by adding brackets in ASCII code.


Output filter for dates How can I change the output of dates in a long text field based on the locale?

I was looking for a module that might work with WYSIWYG to denote a date within a text field.

My goal was to allow articles to be viewed in several locales that use different date formats, without having to create separate versions of the articles.  All of the article content is the same except for references to dates.

Use the Drupal date module.

Users can set their timezone and date will automatically be converted to the timezone of current user (you are presented with options about this when creating the field).


Form Set Error in custom module I am using Drupal7. I also use ife module.  I also wrote a custom module

Here is my code

function mymodule_validate($form, &$form_state) {
    $name=$form_state['input']['name'];
    $pass=$form_state['input']['pass'];
    if(empty($pass) || $pass=='') {
           form_set_error('name', t('dummy message'));
        $errors=form_get_errors();
        print_r($errors);
        return $form;
    }

I also did some RND. when I check $form_state under complete form I got this array

 [complete form] => Array
        (
            [#action] => /logintest/node?destination=node
            [#id] => user-login-form
            [#validate] => Array
                (
                    [0] => user_login_name_validate
                    [1] => user_login_authenticate_validate
                    [2] => user_login_final_validate
                    [3] => mymodule_validate
                    [4] => ife_form_validator
                )

Here means the sequence of module working functions.

Now  when I print $errors,
it is showing

Array
(
    [pass] => Password field is required.
    [name] => Sorry, unrecognized username or password. Have you forgotten your password?
)

But I am accepting

Array
(
    [pass] => Password field is required.
    [name] => dummy message
)

But I don't know why it is not overwriting custom message..  Can anybody tell me how to resolve this issue.

Thanks a lot.

You can try this  under your hook_validate

Here i added new function name mymodule_soft_block_validate

 function mymodule_validators() {
        return array('user_login_name_validate', 'user_login_authenticate_validate', 'mymodule_soft_block_validate','user_login_final_validate','mymodule_validate');
    }

function  mymodule_soft_block_validate($form, &$form_state) {
        $pass=$form_state['values']['pass'];
        if(empty($pass) || $pass=='') {
            form_set_error('name', t('dummy message'));
            return $form;
        }

}


Share nodes and users across multiple sites I understand sharing databases/tables is frowned upon as a practice, however, I need to share users and some nodes between two websites. What are the alternatives and what are the pros and cons of the most common strategies?

To give slightly more detail. I need to create a website for "staff and authenticated users" that is separate to a main site that the public anonymously accesses. On this secondary site there will be forums and chat functionality moderated by admins for both sites. I would like to avoid having the admin users re-log in when they are managing the second site.

I also need to allow for some future integration where some "logged in" user content appears on the main site.

Are the two alternatives for doing this only,

Make one giant single site
Share databases

or is there some other way?

Sharing users can be done by setting up OpenAuth or something like it.

Sharing nodes can be done using views database connector this tool will let you pull data from a table in another database. To make it work for pulling in nodes, create a MYSQL view (https://dev.mysql.com/doc/refman/5.7/en/create-view.html) that holds the node data you need to share out.  The views connector will be able to read in that table allowing you to create views from your other server without having to duplicate the content.  You can filter on any field in the table. This set up works well for a 1 to Many Content server environment where you don't want to have a new copy of every node on every new install.
 https://www.drupal.org/project/views_database_connector

You can also create a module that pulls data from the other database and present it any way you want.

If you are fine duplicating the content you may want to explore Drupal aggregation it's easy to set up and can all be done through the UI.


drupal_get_form not working when called inside a block I have a custom module installed which displays a form at user/UID/apps/add. So, what this form does is lets user add node/nodes of "x" content type he/she wants in their app.
Form is created using this function-

function devconnect_developer_apps_edit_form(array $form, array &$form_state, stdClass $account, $app_id = NULL)

I'm trying to implement this form on every node so that the user can add that particular node to an existing or a new app on a button click.

Figured out I should be passing this nodeID as a default value to the form using drupal_get_form.
So created a block which renders the said form and to test if the form is being rendered I added it to a page to only see a 500 error.

Here is the block-

 <?php
    /**
     * Implements hook_block_info().
     */
    function sei_useapi_block_info() {
      $blocks = array();

      $blocks['MYBLOCK'] = array(
        'info' => t('My block'),
        'cache' => DRUPAL_NO_CACHE,
      );
      return $blocks;
    }

    /**
     * Implements hook_block_view().
     */
    function sei_useapi_block_view($delta = '') {
      $block = array();

      switch ($delta) {
        case 'MYBLOCK':
          $block['subject'] = t('My block title');
          $block['content'] = drupal_render(drupal_get_form('devconnect_developer_apps_edit_form'));
      }
      return $block;
    }

Don't have a clue what went wrong. Any ideas? Thanks for reading !

The third argument to your form is $account, and it doesn't have a default argument. You aren't passing that block in your argument, which is why it is crashing.


Install Drupal 8 on MAMP: can't detect version of Apache I'm trying to install Drupal 8 on my mac using MAMP Pro. I get this error message when Drupal tries to verify I have the proper configuration:

Apache Version:
Due to the settings for ServerTokens in httpd.conf, it is impossible to accurately
determine the version of Apache running on this server. The reported value is
Apache, to run Drupal without mod_rewrite, a minimum version of 2.2.16 is needed.

I have the latest version of MAMP Pro which is running 2.2.29.

Drupal uses Apache's ServerTokens in system_requirements() to determine the version number. You currently have that set to "Prod", which just reveals "Apache" as the token, without any version number.

For Drupal to detect the major and minor versions, plus revision, you need to update the config setting to one of:

Full - Server sends (e.g.): Server: Apache/2.4.2 (Unix) PHP/4.2.2 MyMod/1.2.
Min - Server sends (e.g.): Server: Apache/2.4.2.
OS - Server sends (e.g.): Server: Apache/2.4.2 (Unix).


Trying to migrate Date values using migrate module. I'm trying to migrate some data from a csv to a field_collection in a user profile. Everythings works fine but not for a field of Date (with range) type.

I'm on Drupal 7.22 and I'm using Migration and Migration Extra modules

I do not receive any error message, but the data is not entered, please help me

My code in the migration class:

[...]
$source_file = drupal_get_path('module', 'module_name') . '/data/user_employments_info.csv';

$columns = array(
  [...]
  array('employment_period_start', 'employment_period_start'),
  array('employment_period_end', 'employment_period_end'),
  [...]
);

$this->destination = new MigrateDestinationFieldCollection(
  'field_usr_bkg_emplo',
  array('host_entity_type' => 'user')
);

[...]

$this->addFieldMapping('host_entity_id', 'user')->sourceMigration('User');

[...]

$this->addFieldMapping('field_usr_bkg_emplo_time', 'employment_period_start');
$this->addFieldMapping('field_usr_bkg_emplo_time:to', 'employment_period_end');

At the base there was a problem: the module dates was patched.
The final code that have worked:

my.info

dependencies[] = migrate
dependencies[] = migrate_extras
dependencies[] = date
dependencies[] = date_migrate

my.make

projects[migrate][subdir] = "contrib"
projects[migrate][version] = "2.6-rc1"
projects[migrate_extras][subdir] = "contrib"
projects[migrate_extras][version] = "2.5"
projects[date][subdir] = "contrib"
projects[date][version] = "2.6"
projects[date][patch][] = "https://drupal.org/files/date-consolidated_migrate-1.patch"

my_migration.inc

$this->addFieldMapping('field_date', 'date_from');
$this->addFieldMapping('field_date:to', 'date_to');
$this->addFieldMapping('field_date:timezone', 'UTC');


Will empty hook definitions slow down a site? I'm working on porting over some Drupal 6 custom modules that another developer wrote, and I'm coming across some hooks that are, with the exception of comments, completely empty. I'm likely going to clean these out, for the sake of readable code, but I was curious if I would get any form of performance increase out of it.

I suspect I have been guilty of deploying code with empty hooks.  Often, I will stub out hooks for debugging purposes, so I don't have to clear cache in order to dpm() something at the point I need.  Ideally, though, dead code should be removed.

If you remove an empty hook, you will

Save a small amount of database space from the hook being saved in the registry.  I think it will save one row.
Save a small amount of memory in APC.
Save some query memory and some PHP memory from reading in that row from the registry
Save a few CPU cycles from having a module_invoke_all() call something that does nothing.
Potentially save you some headache of having dead code in a file.

If you have the time, and have a site that works, there should be no harm in removing these hooks.  Just test it to be positive.

Whether you have a meaningful performance impact is really debatable.

In the case of cached pages, the only hook that fires is hook_boot().  There will be some overhead from the bootstrap process reading in an extra hook from the registry.  I seriously doubt this is measurable, though.

For authenticated access, or non-cached pages, the hook may run if the invoker runs.  In other words, a hook_init() will always run, but a hook_node_insert() will only run if you actually save a new node.  Even in this case, I doubt that you will have any meaningful impacts.  Actually profiling this would be an interesting exercise, though.

TL;DR, there should be no harm in removing them, but you will probably not notice them gone.


How to use custom block view mode in View? We have a custom block type block_countries and we are using a View(my_view_custom) to display the all the blocks where type = block_countries. Under block_countries view mode, we setup a "Full" view mode where we display certain information.

The view is displayed as a block and placed into a region (i.e. content region) from the theme. We want to style the block_countries "Full" view mode and setup a preprocess hook to do some processing, however we cannot find the way to do this.

We need help figuring out the proper twig template and preprocess_hook to call in order to get the desired out below. How can we do this?

Block type fields (block_countries):

body
language
country (Entity reference: taxonomy term)

Full view mode (fields shown):

body
country

View settings:

Format = unformatted list
show: custom block: Full (where full is the view mode)
Filter Criteria: custom block : block type = block_countries

We have tried the following but they do not work

Twig

views-view-unformatted--my-view-custom--block-1.html.twig

Hooks

mytheme_preprocess_views_view(&$vars)
mytheme_preprocess_views_view__my_view_custom(&$vars)

Desired output (per row returned from view):

<div data-country="{{ country }}"> {{ body }} </div>

Don't use custom blocks, use nodes or a custom entity type. Custom blocks are designed to be displayed as a block, not a view inside a block. They don't have a template on their own. See https://www.drupal.org/node/2704331.

Yes, it's not great, but it is unlikely that this will change any time soon.


Breadcrumbs not showing proper path I have Drupal 7.2 installed, in my site there are menu items like Tech Docs, Doc Tree etc.
For example in Tech Docs I have number of nodes.

After going to Tech Docs page, the breadcrumb looks like

Home >> Tech Docs

After clicking on a node in Tech Docs, the breadcrumb appeared like

Home >> node title

instead, I need the full path.

  Home >> Tech Docs >> node title

How can I solve this? Any ideas???

An alternative is to use the Menu Position Module.

This module allows you to create a "rule" that says all of the nodes of type "whatever" go under this menu entry.

So, for your specific case, you would go to Structure > Menu Position Rules and add a new one. Give it a name and location in the menu and specify which content type you want (or pages, or users, or terms).

This is beneficial as it means you don't need to add each node to the menu.


How to configure RDF on fields? I have a type of recipe content and I would like google to display additional information in its results.

There is a built-in module to Drupal 8 "RDF" but I can not find anything to configure it on my fields.

How does it work ?

The Drupal built in RDF module works automatically and cannot be directly influenced from the user interface. There is however the Schema.org configuration tool (RDF UI) module.

  The module enables you to specify mappings between content types and
  fields with types and properties of Schema.org and build Content types
  based on schema.org. Through the rdf module, specified mappings will
  be embedded in HTML as RDFa, to provide semantically rich data.

The video on the module page explains the process quite well.


Disable compass in Zen subtheme I am using a Zen subtheme with Sass. I am using CodeKit to compile the Sass into CSS. In my workflow, I enjoy using CodeKit's visual system for project settings because then I can use autoprefixer and souremaps etc easily.

Zen comes with Compass support out of the box. In CodeKit, settings for the styles.scss file is disabled, saying "To change options & output paths for Sass files in a Compass project, you must edit the Compass 'config.rb' file directly."

I could find no way to edit the file to make it behave the way I want, so I want to disable Compass completely.

I tried deleting the lines which seemed related with Compass from the sass files, deleting the config.rb but there seems to be a setting somewhere which I cannot find. I checked out the project settigns in CodeKit but could not find a 'switch' to turn Compass off.

In short, how can I take Compass out of Zen's css system and use CodeKit to fine tune the compile settings?

So Zen uses zen grids for its grid (in some cases) and that has a requirement for compass/css2/images. if you aren't using zen grids, you can disable that dependency.

Another option could be that you can try to delete/rename the config.rb file entirely, as CodeKit may see that and automatically assume you want to use compass to compile your Sass.

A third possibility could be that in the bottom of _init.scss (STARTERKIT/sass/) it pulls in zen, along with alot of other compass extensions. try disabling zen along with the others you already disabled.


Select the fields of a node using code I'm new to Drupal, and I have some problems.
I need to select some fields from a node (via code), and then process the data.

[Full-size image]

Basically, I want to show the total of column "value", grouped by "category", but as each field's content type is a table, I do not know how to do it.

To get the data from a field in an entity be it a node or something else is pretty straight forward.

It can usually be done doing something like this.

$data = $node->field_name['und'][0]['value']

But it depends on which field type you are using ect. A more convenient way is to use the entity module. With that installed you can do:

$node_wrapper = entity_metadata_wrapper('node', $node);
$data = $node_wrapper->field_name->value();

This giv give you the value, for reference fields like term reference, you will get the actual loaded term instead of the raw id which is pretty handy and allows chaining.


hook_field_schema() does not work I'm creating a module to introduce a new field type. I downloaded the example module by drupal and i start programming.
But when I install the module the .install don't add colums to the dbtable related to new field.

 function field_instagram_field_schema($field) {

   watchdog('start field_instagram_field_schema()', 'We are in!');

   switch ($field['type']) {
    case 'instagram_gallery':
      $columns = array(
        'stream_type' => array(
          'type' => 'varchar',
          'length' => '25',
          'not null' => FALSE
        ),
        'input_tag' => array(
          'type' => 'varchar',
          'length' => '25',
          'not null' => FALSE
        ),
         'thumb_dimetion' => array(
          'type' => 'varchar',
          'length' => '25',
          'not null' => FALSE
        ),
        'thumb_number' => array(
          'type' => 'varchar',
          'length' => '25',
          'not null' => FALSE
        )
      );
      break;
  }

  return array('columns' => $columns);
}

UPDATED
When i install the module and create a field of this new type this function is not runned..

Your code is correct, but nothing will happen when you install the module itself. It will only be invoked when you create a new field of type instagram_gallery.

But that is not all. The only module that will get's it hook_field_schema invoked, is the module that actually defined the field. This is done with hook_field_info, so you need to have the following code in your field_instagram.module file:

/**
 * Implements hook_field_info().
 */
function field_instagram_field_info() {
  return array(
    'instagram_gallery' => array(
      ...
    ),
  );
}

Since you are defining your own field, you also need to use

hook_field_is_empty
hook_field_formatter_info
hook_field_formatter_view
hook_field_widget_info (unless you can use an existing widget)

Update
It's hard to say way you have troubles. What the field module does is this:

module_load_install($field['module']);
$schema = (array) module_invoke($field['module'], 'field_schema', $field);

You can try to load the created field manually and run the hook to see if it works. You need to load the .install file like shown above. My guess is that you have something misnamed somewhere, but it's hard to say where exactly. The above could should with your info look like this:

$field = field_info_field('field_name_here');
module_load_install('field_instagram');
$schema = (array) module_invoke('field_instagram', 'field_schema', $field);

If the above works, you can try to debug the actual field creation, the code is from field.crud.inc line 134.


View date filter using years as an offset Is there a way to use years as a date filter offset?  What I want is to set it so that it it loads all content from the start of the previous year. So >= 01-01-2017 this year, >= 01-01-2018 next year, etc.  Is there a way to do that in the View configuration so that it's dynamic?  I'm sure I could do it with custom code by altering the query, but I'd rather avoid that.

It turns out this was more of a PHP strtotime() question.  I just had to figure out the appropriate phrase to get the time frame I wanted, which is: "first day of january last year". I placed that phrase in the filter's offset value.


How to see which varient is in use? Is there any way to know which Panel varient is being used, when I'm viewing the node or term? I know there is the panel page listing and that shows the varients, but it is difficult to know which nodes are using this varient.

I'm asking because I have a site, node template panel has over 20 different varients, some are in use some are not. Attempting to document them is painful.

Thanks!

There is probably a better way, but when I've had to do this I just change the page title for each variant.  Of course, you probably don't want to do this on a live site, but if you have a test site it's not so bad.

Alternately, you could also add a CSS class, etc.


Dynamically adjust argument or filter to views entity reference filter based on value from select list in form I have a entity reference field that references a taxonomy term from a vocabulary named "fund".  Now I'm needing to add a fiscal year field to the fund terms to allow us to have different budget lines for different fiscal years.  Some of these funds will have the same name, but be from different fiscal years, so I now need to add a fiscal year dropdown list before the autocomplete entity reference field mentioned above.

Say the dropdown has two values FY17 and FY18, I'd like the views entity reference filter view to receive the selected value for fiscal year, and apply that as a filter to the views entity reference filter.  How can I accomplish this?  Alternatively is there a better way to accomplish this?

For example:

I looked at Dynamically change views entity reference filter based on current form value but it doesn't seem like it quite fits what I'm trying to do.  I could be wrong.

The simplest answer ended up being to use Entity Reference View Widget which allowed me to build a view for selecting the entity desired.  This was nice because it allowed me to add some additional information and filtering the the approach I was hoping for in my question didn't allow.  Unfortunately, it also moves me further from being able to update this site to Drupal 8 because this module doesn't exist for Drupal 8 because the maintainer decided to let another module that isn't released yet, cover this functionality for Drupal 8.  I would still welcome answers about how to do this in a more forward compatible way.


'Illegal choice' error while submitting/validating selectbox shown with AJAX I'm making a module where the content type and fields are created by install. Now i want to make one of those fields only to show up when an option is selected. I did this with AJAX, in some way I can't make it work with the field as defined in the module.install file. I have a radio button selector for two options. When selecting the first option there should show up a selectbox with a list of nodes to select. When selecting the second option two textfields should be shown instead. When I try to add content of this type I get the error message (when changing the value from the radio buttons):

An illegal choice has been detected. Please contact the site administrator.

Can someone give me some advice to make this work? Thanks in advance!

Here is my code from the install file:

function _concert_installed_fields() {
$t = get_t();
return array(
  // other fields left out
'venue_node' => array(
 'field_name' => 'venue_node',
 'label' => 'Select a venue from the list',
 'type' => 'list_integer',
 'cardinality' => '1',
 'foreign keys' => array(),
 'indexes' => array(
   'value' => array(
    0 => 'value',
   ),
  ),
 'module' => 'list',
 'settings' => array(
  'allowed_values_function' => '_concert_content_type_venue_options_list',
  ),
),
'venue_radio' => array(
 'field_name' => 'venue_radio',
 'cardinality' => 1,
 'type' => 'list_boolean',
)
);

From my .module file:

 function concert_form_alter(&$form, &$form_state, $form_id) {
 if($form_id == "concert_node_form") {
 $form['venue_radio'] = array(
  '#title' => t("Choose a venue from the database or add one manually"),
  '#type' => 'radios',
  '#options' => array(0 => t('Add a venue from the database.'),
                      1 => t('Add a venue manually.'),),
  '#ajax' => array(
    'callback' => 'concert_venue_callback',
    'wrapper' => 'venue_select',
    'effect' => 'fade',
  ),
);

$form['venue_select'] = array(
  '#prefix' => '
',
  '#suffix' => '
',
  '#type' => 'fieldset',
);
if (!empty($form_state['values']['venue_radio']) && $form_state['values']['venue_radio']   == "1") {
  $form['venue_node']['#type'] = 'hidden';

  $form['venue_select']['location'] = array(
    '#type' => 'textfield',
    '#title' => t('location'),

  );
  $form['venue_select']['venue_city'] = array(
    '#type' => 'textfield',
    '#title'=> t('city'),
  );
}

else {
$form['venue_select']['venue_node'] = array(
    '#type' => 'select',
    '#options' => _concert_content_type_venue_options_list(),
    '#title' => t('venue node select'),
    '#default_value' => '466', // node id is select value
  );
if (!empty($form_state['values']['venue_node']))
$form['concert_venue_node']['und']['#default_value'] = $form_state['values']['venue_node'];
}

function concert_venue_callback($form, $form_state) {
   return $form['venue_select'];
}

The options from the selectbox are populated by a function in a file accessable for both the .install and the .module file:

function _concert_content_type_venue_options_list() {

$results = db_select('node', 'n')
 ->fields('n', array('nid', 'title'))
 ->condition('n.status', 1)
 ->condition('n.type', 'venue')
 ->execute();

$options = array();
  foreach ($results as $node) {
    $options[$node->nid] = $node->title;
  }
return $options;
}

Setting #default_value for the 'venue_radio' form element solved my problem: http://drupal.org/node/1545316#comment-5914060
I also changed my code to how it is described in the Ajax altering node form example. Everything is working now in the way I wanted it to. Issue solved.


How to specify a Rules condition related to select list values? I'm now thoroughly confused about trying to set a Rules Condition on a select list. There are two things I want to do:

(a) On a new node of my content type I want to trigger when a certain checkbox in the select list is checked

(b) When a node of the same content type is edited I want to trigger when the state of the checkbox has changed.

For (a) I start out with a Data Comparison and put the name of the select list (node:field-pbxq-stock-status) in Data Selector. On the next page I choose "Is one of" for the Operator and then my list of Data Values disappears, so I cannot select the one I want. It won't allow "node:field-pbxq-stock-status:In stock" or "node:field-pbxq-stock-status:3" (3 is it's index) in that Data Value/Data Selector field.

Update:

These are two more comparisons I've tried.

Both are: After saving new content of type PBX Quote

Text Comparison

Data selector: node:field-pbxq-stock-status:3

Matching text: In stock

Value: contains

List contains item

Selected list: node:field-pbxq-stock-status

Data selector: node:field-pbxq-stock-status:3

In both of those cases I'm using the '3' because
I -think- thats suppose to be the list offset?
I'd much rather compare without dependency on
offset, eg:

Some type of comparison

Selected list: node:field-pbxq-stock-status

Matching text: In stock

Value: contains

Below is a sample of a rule (in Rules export format) that should allow you to specify a Rules condition relation to a specific value selected via a selection list (and when a new node is created):

{ "rules_new_node_with_special_optionlist_value" : {
    "LABEL" : "New node with special optionlist value",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "node_insert" : [] },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_optionlist" } },
      { "data_is" : { "data" : [ "node:field-optionlist" ], "value" : "C" } }
    ],
    "DO" : [
      { "drupal_message" : { "message" : "A new node got created with option list value = Custom" } }
    ]
  }
}

Some more details to further explain the above above sample:

The Rules event I'm using is "After saving new content".
In my case I have a selection list field with machine name field_optionlist.
This field actually has 3 possible values, like so:

A (=Advanced).
B (=Basic).
C (=Custom).

As a sample, I decided to use as condition "The selected value must be Custom".
If that value is selected, then (as Rules action), a message is shown like A new node got created with option list value = Custom (feel free to change that to whatever Rules action, this is how I often "unit test" new rules I write).

The "clue" to make this rule work is the condition Entity has field. That's also what is mentioned in the Rules UI when you're adding a "data comparison" condition: somewhere it says "The data selector helps you drill down into the data available to Rules. To make entity fields appear in the data selector, you may have to use the condition 'entity has field' (or 'content is of type')". I wouldn't be surprised if that is what you are missing in the rules conditions you tried so far ...

Note that I've not added a Rules condition here about selected content types, that's probably an extra condition you might want to add also. But if the selection list field is only used for the content types you're interested in, then the Entity has field condition should be sufficient already.

For a video tutorial that illustrates the importance of this Entity has field
condition, refer to Data types and data selection, especially what is shown between about 13:30 and 17:30 in that video.