Database query with notExists I can't figure out how to select all aid's from the areas table that do not exist in the field_data_field_area_parent table.

It almost works, except it returns Windy Ridge with an "aid" of "11".   I am guessing that this is because "IN" is the same as "ANY", and the number "1" is in the subquery results.

How can I use NOT EXISTS instead of NOT IN?

function verb_get_parent_areas () {
  $query = db_select('areas', 'a');
  $query->distinct();
  $query->fields('a',array('name','aid','parent','latitude','longitude','description'));
  $subquery = db_select('field_data_field_area_parent', 'p');
  $subquery->fields('p', array('entity_id'));
  $query->condition('a.aid', $subquery, 'NOT IN');

  $result = $query->execute();
  while ($record = $result->fetchAll()) {
    $areas = drupal_json_encode($record);
  }

  return $areas;
  exit;
}

I've thought of trying this, but it returns nothing.

function verb_get_parent_areas () {
  $query = db_select('areas', 'a');
  $query->distinct();
  $query->fields('a',array('name','aid','parent','latitude','longitude','description'));
  $subquery = db_select('field_data_field_area_parent', 'p');
  $subquery->fields('p', array('entity_id'));
  $query->notExists($subquery);

  $result = $query->execute();
  while ($record = $result->fetchAll()) {
    $areas = drupal_json_encode($record);
  }

  return $areas;
  exit;
}

Here is another approach to write Dynamic queries. We generally write queries in phpmyadmin or mysql command prompt and then convert them to D7 style or dynamic queries using Query coder module.

For example, as per your question, you want to find out all those records in child table which don't exist in parent table.

So D6 style query,

db_query("SELECT c.* FROM {child} c LEFT JOIN {parent} p ON c.p_id = p.p_id WHERE p.p_id IS NULL");

after converting to D7 style query using query coder module would look like,

$query = db_select('child', 'c');
$query->fields('c', array('*'));
$query->leftJoin('parent', 'p', 'c.p_id = p.p_id');
$query->isNull('p.p_id');
$result = $query->execute();


Make Apache Solr return results based on taxonomy term I have Content Type A and Content Type B. They both use the same vocabulary. I want to achieve the following:

Let's say that node1 of content type A is associated with the terms term1 and term2. When a search returns node1 as a result (based on its body or other fields), I would also like to present to the user all nodes of Content Type B that are associated with term1 and term2.

Is that possible with the apachesolr module?

Apachesolr's "More like this" block, that you can display on your nodes, is similar, but not particularly configurable.  It uses both terms and text to determine related nodes, so you can't just base it on a particular term reference field.  Also, it appears on the actual nodes (in your example, it would appear only once a user has clicked on and is viewing node1), not on the search results page.

OPTION 1 ----------

If you're looking to include this type of block on nodes, it'd be possible to do precisely what you want with just a view.

Create a content view that filters out only the node types you want.
Make sure it accepts a term id as a contextual filter to use (i.e. based on the currently viewed node and its terms, it will filter the list of nodes it displays to ones with precisely those terms). To accomplish this, add a contextual filter to your view that is "Content: term_reference_field"!
Then, set the default value of this contextual filter to come from the current node if it's not in the URL: select 'Taxonomy term id from URL' as the default value and then select 'Load default filter from node page'.  Under that, select the vocabulary that your term reference is based on.  Also make sure you select how to handle multiple values (if the current node being viewed has multiple terms selected, do all terms have to match for a related node to be shown, or should just a single value match be enough?).
That should be all you need!  Test your view out by providing some sample inputs in the 'Preview' area and making sure that the resulting nodes match via their terms!

OPTION 2 ----------

Now, if you're looking to do this on the search results page, that is a little trickier, because you have to look at multiple nodes (all the ones in the results) rather than just a single one.

Here's how I would do that:

In your view, from above, make sure you expand the 'More' section at the bottom of the contextual filter, and check that it should be able to accept multiple parameters (if you want to base the 'Related nodes' view on all the nodes from the search result rather than just the top one
Implement a hook_preprocess_search_results() function in your custom theme - this should be placed in your template.php file.

  function YOURTHEME_preprocess_search_results(&$variables) {

  // Get nodeids from search results
  $node_ids = array();
  foreach ($variables['results'] as $result) {
    if (!is_object($result['node'])) {
      continue;
    }

    $node_ids[] = $result['node']->entity_id;
  }

  // Ensure node ids exist
  if (!count($node_ids)) {
    return;
  }

// Now that you have the nids of all the search results on the current page, call the above view with those nodes as parameters
// The second argument should be the display on your view you want to call, could be 'page', 'block' or whatever custom one you have
$view_output = views_embed_view('YOUR_VIEW_MACHINE_NAME', 'block', implode('+', $node_ids));
if ($view_output) {
  $variables['my_view_results'] = $view_output;
}
 }

Finally, now that you've set the variable $my_view_results above (with nodes from the search results at view contextual filters!!!), you can call place that variable anywhere in your search_results.tpl.php template file and place it anywhere: above, below or anywhere on your content

  <?php print $my_view_results; ?>

Sorry that Option #2 is kind of complicated.  Someone may come up with a more straight-forward answer, but I can only think of using a view and providing it with the right parameters by hooking into hook_preprocess_search_results() to grab the right node ids that are appearing on the search page.  Good luck.  Let us know if this works out!


Updated search index display, but old index is still being used I updated the search index display for my content type (eg, from admin/structure/types/manage/page/display/search_index), but the old index is still being used.

How can I fix this?

When you save the settings for the search index display, nodes are not marked as needing to be reindexed.  You can either reindex the full site, or add in your own submit handler to mark them as dirty:

/**
 * Implements hook_form_FORM_ID_alter().
 */
function MYMODULE_form_field_ui_display_overview_form_alter(&$form, $form_state) {
  if ($form['#view_mode'] == 'search_index' && module_exists('search')) {
    $form["#submit"][] = 'MYMODULE_mark_search_index_dirty';
  }
}

function MYMODULE_mark_search_index_dirty($form, &$form_state) {
  $entity_type = $form["#entity_type"];

  $query = new EntityFieldQuery();

  $query->entityCondition('entity_type', $entity_type, '=');

  if (!empty($form["#bundle"])) {
    $query->entityCondition('bundle', $form["#bundle"]);
  }

  $entities = $query->execute();

  $sids = array_keys($entities[$entity_type]);

  $num = db_update('search_dataset')
    ->fields(array('reindex' => REQUEST_TIME))
    ->condition('type', $entity_type)
    ->condition('sid', $sids, 'IN')
    ->execute();

  if ($num > 0) {
    drupal_set_message(format_plural($num,
      '1 item needs to be indexed.',
      '@count items needs to be indexed.'));
  }
}

This will alter the form used to edit the display settings.  It checks to see if you are on the tab for changing the display of the search index view mode, and also have the Search module enabled.  If so, it adds on a new submit handler.

The submit hanlder does an EntityFieldQuery to get all of the entity IDs for the type/bundle pair specified by the $form.  It used EFQ instead of db_query() to be entity-type agnostic.

Then, based off of the code for search_touch_node() (which is called from node-related insert and update update hooks), it updates the search index to mark those entities as needing to be reindexed.  This will leave the old indexed data in place, and subsequent cron runs will reindex.

If you want to remove those from the index until reindexing, then you can replace the query with a loop like:

foreach ($sids as $sid) {
  search_reindex($sid, $entity_type);
}

$num = count($sids);


How do I add a color hex code field to a product attribute using drupal commerce 2? How to add a color hex code field to a product attribute using drupal commerce 2

I can add the form field but do not know how to create the field type: color or the corresponding hex code.

Thanks

For anyone else grappling with this issue in future here is what I did:

****How to add a color hex code field to a product attribute using drupal commerce 2****

see also: https://drupalcommerce.org/blog/44310/enabling-fancy-attributes-commerce-2x

Use the Color Field module to add a color field to your Color attribute.
https://www.drupal.org/project/color_field

Install with Composer: $ composer require 'drupal/color_field:2.x-dev'

+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

Product Attributes  >>  Add Colour Attribute    >>  Manage Fields

Add:

Label:      Color Hex Code

Machine Name:   field_color_hex_code

Field type:     color

DEFAULT VALUE
The default value for this field, used when creating new content.

COLOR HEX CODE

Color       #D3D3D3

Opacity     1

Record Opacity  Ticked

FIELD SETTINGS TAB

Format storage  #123ABC
Choose how to store the color.

Allowed number of values:   Limited     1

+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

Product Attributes  >>  Add Colour Attribute    >>  Manage form display

FIELD   WIDGET

Name        Textfield       textfield size: 60

Color Hex Code  Color default       No placeholder

+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

Product Attributes  >>  Add Colour Attribute    >>  Manage display

FIELD           LABEL       FORMAT

Color Hex Code      Hidden      Color Swatch        Square Width: 40 Height: 40

Note:
Remember to change the attribute selection widget to use the rendered option for your attribute.


best practice: what directory should the theme be located for a site install profile I am building a site install profile. Trying to wrap my head around the file structure.
I am creating a Drupal 7 install profile with a sub theme off of omega.

Is it better practice to put the theme in the

profile/themes

or

sites/all/themes

Normally, the theme would go in:

/profiles/YOURPROFILE/themes/YOURSUBTHEME

Also include the base theme at the same location:

/profiles/YOURPROFILE/themes/omega


Site broken after upgrading with Pathauto < 8.x-1.6 I recently upgraded to Drupal 8.8. Unfortunately I missed the memo on needing to upgrade Pathauto first and now my site is broken. Most pages give the message "The website encountered an unexpected error. Please try again later."

I can get to /user and log in with an admin account, and I can get to /update.php which tells me "The Pathauto module is not compatible with the current version of Drupal core. Update the Pathauto module to 8.x-1.6 or later." and does not give me the option to continue to database updates.

I can't get to many other pages, and notably can't get to /admin/modules where I would normally upgrade a specific out of date module like Pathauto.

Do I have any other options besides wipe my site and restore from a backup? Even if I can figure out how to upgrade Pathauto at this point, I'm not clear if that's likely to fix the issue.

Thanks.

Based on the comments above from leymannx, I've manually uploaded Pathauto 1.6 to my site via FTP. Returning to /update.php, I got the option to update the database and that worked and my site is back up again.

Note: The first time I tried this, I renamed the old Pathauto module folder to "pathauto_old", and uploaded the new version to a newly created folder just called "pathauto", and that did not work. update.php continued to report and out of date Pathauto. After that, I deleted both folders, re-uploaded pathauto 1.6, and then it worked.


Specify destination folders outside of Drupal root using Drush Make Is there a way to configure Drush Make so that it would build a structure like:

project_root

drupal_core
drupal_contrib

So that next in the build process (that this would form a part of) could symlink the sites/all directory to drupal_contrib

It would be set up this way as I would prefer the build process to allow an upgrade of Drupal core by simply removing sylinks, upgrading, then re-adding symlinks

I'm aware the build process might as well just loop through some drush dl x statements, or that if Drush Make was used the folders could easily be re-jigged afterwards. Just interested if there is a non-hacky way of doing it first.

Thanks!

I've noticed how I can get part of the way there without moving the downloaded files around

From my main directory I can run

drush make --no-core --contrib-destination=modules test.make sites

to yield

project_name
  - sites
    - modules
    - themes

then use a standard

drush dl

to get core and then use custom scripts to symlink core/sites/all -> project_name/sites or something like that.

There doesn't seem to be an option for --no-contrib or anything like that (probably because there isn't much point)


How to update the page breadcrumb when using theme page I have an entity form(theme page to display it) .
I have used hook_node_view() to handle breadcrumbs for nodes.
But I don't find any place to handle this $breadcrumb when I have a form and a theme page for it.

This is how I got the $breadcrumb for my news.

/**
 * Implements hook_node_view().
 */
function news_node_view($node, $view_mode, $langcode) {
  if ($node->type == 'news' && $view_mode == 'full') {
    //BREADCRUMB ////
    $breadcrumb = array();
    $breadcrumb[] = l('Home', '<front>');
    $breadcrumb[] = l('News', 'news');
    drupal_set_title('News');
    drupal_set_breadcrumb($breadcrumb);
  }
}

I have hook functions like:

hook_init()
hook_menu()
hook_form()
hook_form_validate()
hook_form_submit()
hook_theme()
hook_preprocess_form()

But I don't find a place to work on $breadcrumb, or somehow manage it.

If you are looking for GUI to handle breadcrumbs, take a look at Custom breadcrumbs module.
Otherwise, you can manage your breadcrumbs programatically in lot of hooks. The code you've printed is correct, so you can create for example a function with a switch case like this one :

function manager_breadcrumbs($form_id) {
  $breadcrumb = array();
  $breadcrumb[] = l('Home', '<front>');
  switch ($form_id) {
    case 'my_first_form' :
      $breadcrumb[] = l('Category', 'taxonomy/term/1');
      break;
  }
  drupal_set_breadcrumb($breadcrumb);
}

And then, call this function in a hook_form_alter() like this.

function MY_CUSTOM_MODULE_form_alter(&$form, &$form_state, $form_id) {
  manager_breadcrumbs($form_id);
}


What is the difference between the classes ArchiverTar and Archive_Tar? What is the difference between the classes ArchiverTar and Archive_Tar?  Which one is a Drupal module supposed to use?

The Archive_Tar class is a very-slightly modified version of the PEAR library Archive_Tar. ArchiverTar can be thought of as a wrapper to that library. However, depending on what your module is trying to achieve, you will probably want to call archiver_get_archiver(), since this is agnostic of the specific archive format (the system module supplies tar and zip, and your module could provide additional formats using hook_archiver_info()).


Any way to stop Drupal css from dynamically resizing pages? We recently upgraded from Drupal 5.x to 6.22 and one thing noticed right away was that when the browser was taken off full-page the displayed page content would reformat into a very undesirable order.  Previously the page would not resize and users could focus on only a small portion of the screen when in a windowed mode.  This was true for mobile displays as well.
Is there any 'simple' way to prevent this from happening?  I realize this might be a css issue of which I am no expert.  But because this entire site is generated and delivered via Drupal I thought I would ask others.

You need to add some css to various places in your theme, then. Give a 'width' attribute to the divs that contain the pieces of your page.

You may also be interested in 'min-width' and 'max-width' attributes.

Check out the drupal theming guide, or better yet, the README in your active theme's folder, to learn where and how to add the css. You don't have to be an expert- with just a little bit of time, this should be pretty easy.


How can I refer to a user in a content type using CCK in Drupal 7.7 In a content type I want to let the author select one or more of the site users. It's something like term reference field but I need to refer to a user instead. I can't find a suitable module for that although I can roughly remember that I did that before. I am using the latest drupal version 7.7.

Thanks


Views: how to ASC sort the grouping field #1 and sort DESC its content? I have views grouped by year (grouping field #1) that I want to sort from the most recent to the oldest. I have content referenced to the year.

This returns me a HTML list such as:

2013
- alpha
- gamma
- beta
- delta

2012
- zeta
- gamma
- epsilon

The years are correctly sorted (DESC) but I would like to have the content of each year sorted ASC to have the content listed alphabetically to have a list like this:

2013
- alpha
- beta
- delta
- gamma

2012
- epsilon
- gamma
- zeta

I have of course tried to apply a ASC sort on the content but it affects the years also and they become ASC sorted as well.

I have created a small test setup in Drupal, containing six nodes with each having a year (integer) and a content (text) field.

The view's configuration is displayed below:

The sort criteria is first on the year field (descending) and then on the content's text (ascending). The view generates the following result:

Note that I have excluded the year field from the display. Instead I'm using the grouping option on year in settings of the unformatted list (however, this is not necessary, but the result resembles your question more closely).


Why doesn't this code work? I'm more or lees newbie developing with drupal and now, specifically, I'm trying to create one new entity. I've seen the entity_example given in examples for developers and also I have read this post recomended in the Entity API docs.

I have understood the basics things. I have created the table for the entity, I have defined de entity with the hook_entity_info(), the links for manage page and create one item of this new entity, etc. And it seems to be fine because when I add one item, i can see it on the database.

The problem is when I try to load the entity data. First of all, I have register the url in the hook_menu().

$items['issue/%gissues_issue'] = array(
'title callback' => 'gissues_issue_title',
'title arguments' => array(1),
'page callback' => 'gissues_issue_view',
'page arguments' => array(1),
'access arguments' => array('View Issues'),
'type' => MENU_CALLBACK,
);

Also, I have created the permissions in hook_permission() and two functions, as I have read in docs, for loading one item or multiple items. I show the code of that functions:

function gissues_issue_load($issue_id = NULL, $reset = FALSE) {
    $issue_ids = (isset($issue_id) ? array($issue_id) : array());
    $issue = gissues_issue_load_multiple($issue_ids, $reset);
    return $issue ? reset($issue) : FALSE;
}

function gissues_issue_load_multiple($issue_ids = array(), $conditions = array(), $reset = FALSE) {
    return entity_load('issue', $issue_ids, $conditions, $reset);
}

When I execute the code, I receive this error message:

  Warning: array_flip(): Can only flip STRING and INTEGER values! in DrupalDefaultEntityController->load() (line 173 of /home/user/public_html/formacion/includes/entity.inc).
  Recoverable fatal error: Object of class stdClass could not be converted to string in DatabaseStatementBase->execute() (line 2168 of /home/user/public_html/formacion/includes/database/database.inc).

I think the entity_load function is not receiving the correct data. The function needs an array with the IDs and it's receiving an array of array. This is what the dpm shows:

  (Array, 1 element)
  0 (Array, 1 element)
    2 (Object) stdClass
      issue_id (String, 1 characters ) 2
      bundle_type (String, 13 characters ) general_issue
      [

    entity data

      ]
      rdf_mapping (Array, 0 elements)

So that, I'm quite lost. May be its something simple or maybe not, but I can't figure out what I'm doing wrong o what i'm forgetting to do.

Any help would be appreciated.

If your module name is

gissue_issue

Then you could have a hook namespace collision with

hook_load

In which case the $nodes parameter is being passed to your load function as well.

Just a possibility to consider.


Flags with image instead of link I have two flags defined in my site (false_negative_flag and false_negative_flag_passed). Each flag has different Flag link text.

In views, I have two displays. I have a flag link in each of these views, one with the first flag, the other with the second one. The link text shows correctly on both displays. I wanted to have images instead of the link text so I added the following css:

.flag-wrapper.{false_negative_flag} a.flag-action {
    background: url(http://.../files/failed.png) no-repeat center center;
    border:none;
    width: 18px;
    height: 18px;
    margin-left: 0px;
    float: left;
    color: transparent;
    text-indent:-9999em;
}
.flag-wrapper.{false_negative_flag} a.unflag-action {
    background: url(http://.../files/passed.png) no-repeat center center;
    border:none;
    width: 18px;
    height: 18px;
    margin-left: 0px;
    float: left;
    color: transparent;
    text-indent:-9999em;
}
.flag-wrapper.{false_negative_flag_passed} a.flag-action {
    background: url(http://.../files/passed.png) no-repeat center center;
    border:none;
    width: 18px;
    height: 18px;
    margin-left: 0px;
    float: left;
    color: transparent;
    text-indent:-9999em;
}
.flag-wrapper.{false_negative_flag_passed} a.unflag-action {
    background: url(http://.../files/warning.png) no-repeat center center;
    border:none;
    width: 18px;
    height: 18px;
    margin-left: 0px;
    float: left;
    color: transparent;
    text-indent:-9999em;
}

There are 3 different images I use but in my views I always see the passed and warning ones (the last two entries of the css). Is there any error in my css?

NOTE: I'm using the displays in Panels, don't know if it's relevant.

EDIT after first answer: I got the css I'm using from the link in this answer. I simply duplicated and in the second part I added the second flag machine name. The problem is that now it ignores the first two blocks of the css.

Thanks!

Working with flags u should use "-", not underscores and there are should be class names started with flag-: flag-false-negative-flag-passed


How to display multiple PDF files in a node I want to display multiple pdf files in a single node. I am using PDF module to display pdf files with File Resumable Upload. But I need to display many files in a single node. I wasnt able to find any solution to this.
When I select multiple files to upload, all get uploaded successfully in the uploads directory, but only one gets displayed. When I go to 'Edit' tab on the same newly created node, all the pdf files are present in the designated section
, but only one is displayed on the node (even after saving again).

Check maybe the Field Settings (/admin/structure/types/manage/page/fields/...) of your page if the displayed "Number of values" is set to "Unlimited" instead of 1.


How does drupal send emails by default? I have a site working on drupal 6 , and i uses drupal's default email function drupal_mail() to send emails , but unfortunately its not sending email and gives me "email not send , please contact site administrator" error , is there any smtp settings i need to include ?

When i tried like follows :

$to = "test@example.com"; // to e-mail address
$from = "test@example.com"; // from e-mail address
$subject = "text to display in e-mail subject"; // subject of e-mail
$body = "text to display in e-mail body";
//params is the array passed to hook_mail function
$params = array(
    'subject' => $subject,
    'body' => $body,
    );

if(drupal_mail('test', 'information', $to, language_default(), $params, $from)){
     echo "mail send successfully";
}

it gives me mail send successfully message but mail is not delivered .

Next to drupal_mail you also need https://api.drupal.org/api/drupal/developer%21hooks%21core.php/function/hook_mail/6 to send the mails.

This hooks tells Drupal what to do with 'params'. $params['body'] does not automaticaly becomes the body.

From the example module:

function email_example_mail($key, &$message, $params) {
  global $user;

  // Each message is associated with a language, which may or may not be the
  // current user's selected language, depending on the type of e-mail being
  // sent. This $language variable is used later in the t() calls for subject
  // and body to ensure the proper translation takes effect.
  $language = $message['language'];

  switch ($key) {
    // Send a simple message from the contact form.
    case 'contact_message':
      $message['subject'] = t('E-mail sent from @site-name', array('@site-name' => variable_get('site_name', 'Drupal')), $language->language);
      // Note that the message body is an array, not a string.
      $message['body'][] = t('@name sent you the following message:', array('@name' => $user->name), $language->language);
      // Because this is just user-entered text, we do not need to translate it.
      $message['body'][] = $params['message'];
      break;
  }
}

Take extra notice the body is an array!
Edit: some clarification:
The subject of the message is a string, like you would expect. So you can fill the subject line like this:

$message['subject'] = 'Any string, with '. $param['subject'] .  ' or not.';

The body however is not a string, and can not be filled this way. It's an array of strings. The very least you need one part. e.g.:

$message['body'][] = $params['body'];

In the end, Drupal wil implode the array to one big string.

Putting the body in parts allows for other modules to use hook_mail_alter, to change only parts of the e-mail, e.g. only the heading of the message.

/end edit

However, without this hook your mail should have been sent. But it is very likely it was blocked by a spam filter (empty body and empty subject from, probably, an unauthorized source).


Drupal 7 views page path/url matching? Our former website (that was hooked with Google Analytics) had the following URL (i.e. Example URL) for a staff member:

http://www.example.com/research/teams/staffname.html

I have recently re-designed the website using Drupal 7 (Views 3) and other required modules. While designing the website, the structure of the most URL addresses changed.

Google already had indexed the old website and had/have the old URL addresses. After the complete re-design of the website, I did the following:

Enabled the Google Analytics module (supplied it the same Google Analytics ID used for the former website)
Installed/Enabled the xmlsitemap module, configured the content types to provide URL for and generated a new sitemap.xml file
Created Google Webmaster Tools (and Bing Webmaster account) and uploaded the sitemap.xml

Google has so far indexed 23 URL out of 63 (More indexing to be done!). At the moment googling the site, show up the website with some new links (probably the recently indexed links) and some older links. Clicking the OLD links of course display

"The requested page "/studentships/studentships1.html"

Hopefully by the time Google index all 63 links, there will be no OLD links left however, there happen to be another issue.

In the new website, I have a View page which is composed of a few View Attachments where each attachment lists a group of Scientists/staff. Visiting Research page

http://www.example.com/research

Renders four/five Science types sections and then under each section there is a list of Scientists. Each staff/scientists profile has a custom URL (yes I do use pathauto but, not for staff content type) as follow:

/research/group/{staffusername} hence http://www.example.com/research/group/{staffusername}

If you notice there is a partial match in the URL of old website and new website

  http://www.example.com/research

The problem I am having with the above URL is that, requesting any of the following URL variation would work (View Page is rendered) as if the above URL is requested

  http://www.example.com/research/*
  http://www.example.com/research/*/*
  ....

When I click the old URL for accessing a staff profile which looks as follow :

 http://www.example.com/research/teams/{staffusername}.html

That executes the following

http://www.example.com/research

Even though after /research there is no match (I should see an error there for URL mismatch). Why I want strict URL matching:

Accessing a staff profile using old link and ending up in the research page where all the staff is listed, is not a good navigation
Google bot will never come across a 404 hence, will consider the OLD staff URLs as valid and probably will never get rid of them from their search index/history (Google has listed most of the links of Old website as 404 but, not listed any of the OLD staff profile URLS).

What should I do to instruct the View page to only display /research page when the URL perfectly matched?

The view should run only when the request URL is exactly as follow

http://www.example.com/research

The staff content type nodes has the following Custom URL

research/group/{staffusername}

The Research View Page path is research, this issue of not doing strict URL matching is true for all of the Views of type Page in the new Drupal site. For example, the following is valid Career view URL

http://www.example.com/career (with View Page path as "career"

But any of the following URL requests work

http://www.example.com/career/*

Is this default behaviour of views?

Sorry for the level of details, probably too much. Thanks anyway.

This isn't Views behaviour, it's standard for the Drupal menu system. Extra path components (separated by slashes) are ignored if they don't match a more specific menu entry. So if you have a menu entry for path xxx/yyy it'll also receive requests for xxx/yyy/zzz and xxx/yyy/zzz/aaa.

Rather than a 404, why not serve a 301 redirect? That's better for SEO. If you can't do that at the server level (always preferable for performance) then a module such as https://www.drupal.org/project/match_redirect might help.

See: https://api.drupal.org/api/drupal/includes%21menu.inc/group/menu/7

  When responding to a page request, the menu system looks to see if the path requested by the browser is registered as a menu item with a callback. If not, the system searches up the menu tree for the most complete match with a callback it can find. If the path a/b/i is requested in the tree above, the callback for a/b would be used.


Node Template Panel Node I am using a node template to layout a node and I want to reference content from other nodes.  Obviously I have the current node fields available to me, but I want to select any of the sites nodes.

I understand I can create view blocks and include these in the template but looking at the node tab in the panel content, there is an option to set the node, the only option being 'node being viewed'.  This kind of suggests there may be a way of references any node.

It depends on the type of reference. You can load any node-content with node_load(). The question is simply if you know when to load which nodes. This reference could via Taxonomy or Contentype or User or anything else.


Site Branding Block not appearing in regular page--html--twig template I have a sub theme with the parent theme being the bootstrap theme.  I am able to configure the site branding block to show up on my content type pages and that's because my sub theme has a hook which suggests this full--width--page template.  This full--width--page template has the {{page.branding}} region in it and it works fine.

However it wont appear on the contact page or the user login page? I suspect the boostrap theme or parent drupal engine uses the regular page.html.twig template for contact page and user login page and other pages.  the {{page.branding}} does not seem to work in the page.thml.twig template.

I am looking for possible solutions.  Maybe I ened a hook to tell the theme to use the full--width--page.twig template but I don't know how to write that hook, or maybe I ened to find out what is wrong witht he page--html.twig template.

Any help would be appreciated.

You can probably override the suggestions using hook_theme_suggestions_page_alter in your THEMENAME.theme file

function THEMENAME_theme_suggestions_page_alter(array &$suggestions, array $variables) {

  //the routes to use the specified template
  $use_template = [
    "user.register", // user/register
    "user.login", // user/login
    "user.pass", // user/password
    "entity.contact_form.canonical", // core contact form (website feedback)
    "entity.webform.canonical", // all webforms will have this route
  ];

  // what route are we on ?
  $route_name = \Drupal::routeMatch()->getRouteName();

  if (in_array($route_name, $use_template) ){
    $suggestions[] = 'full__width__page';
  }
}

You should clear the cache and your specific template should take control.

If you have twig debugging enabled and your browser has show html comments enabled you should see something similar to this the page source

<!-- FILE NAME SUGGESTIONS:
   X full--width--page.html.twig
   * page--user--register.html.twig
   * page--user.html.twig
   * page.html.twig
-->

With x indicating the twig template responsible for the particular output.  In this case full--width--page.html.twig is the twig template used.


How to return [error] in a rest api build with view? I have a view which gives has an input:
email
key

The json returns a uid.

I would like to return [error] when the combination email + key is not found. Currently, it is only [].

How to do this?

If you are using Views, I would add a "no results behavior" that outputs the error message of your choice.


Sending Notification Messages My team is working on a simple message notification using the message stack but a bit tricky to implement.

The goal is when a user is subscribed to content, a notification message will be delivered to the user's email address.

We are trying to follow this steps, doing the configuration in the browser. But the last step, we think should be added manually in a certain file as mentioned in this comment.

Questions:

Where should I add the code to properly send the message into email?
Is there a need to create a custom module to achieve it?

Hooks go in the .module file, the only hooks that can also work in the .theme file are preprocess and alter hooks.

So if you want the message to be sent when a node is created or updated, use hook_ENTITY_TYPE_presave.

Create a custom module, lets call it "Send Message"

send_message.info.yml

name: 'Send Message'
description: 'Sends the message when a node of Content type Article is created or updated.'
core: 8.x
package: Message
dependencies:
  - message
type: module

send_message.module

<?php

use Drupal\node\NodeInterface;
use Drupal\message\Entity\Message;

/*
 * Implements hook_ENTITY_TYPE_presave()
 */

function send_message_node_presave(NodeInterface $node) {

   if ($node->getType() == 'article') { // checks if content type is article
      $message = Message::create(['template' => 'foo_message_type', 'uid' => $node->getOwnerId()]);
      $message->set('field_node_ref', $node);
      $message->save();
      $notifier = \Drupal::service('message_notify.sender');
      $notifier->send($message);
   }

}


Create a content node from another content I'm wondering how to create a content from another content. I'll give an example, it will be easier to understand :

We have a content-type "Planning" which has three fields : 2 user references and one date, which can be multiple filled (let's say the dates are appointments). So in result, a planning will link 2 users and this node will display all the dates these 2 are supposed to meet.

Also, we have another content-type "Appointment".

I'd like that after the creation of the Planning, the appointments get automatically created, always linking the 2users.

First, I've looked into the module Flexi-Field but it doesn't create the node. Then I thought about Rules but I don't know how to create the multiple nodes Appointments due to the multiple date fields.

I know I could do it with Rules through a PHP custom code, but if there's any easier solution, I'd like to hear about them :-)

Thanks for any suggestion !

Cheers all !

If both your content types are defined for Plannning and Appointment already, you can easily create appoint nodes on-the-fly when a Planning node is saved.

You want to look at the following 2 references:

hook_node_insert()
Programmatically create nodes

It would look something like this (NOT TESTED):

function mymodule_node_insert($node) {
  if ($node->type == 'planning') {
    foreach (element_children($node->field_appointment_dates) as $a_single_appointment_date) {
      $appt_node = new stdClass();
      $appt_node->type = 'appointment';
      node_object_prepare($appt_node);
      $appt_node->language = LANGUAGE_NONE; // Or your language type ...
      $appt_node->title = 'Some new appointment';
      $appt_node->field_appointment_date = $a_single_appointment_date[0]['value'];
      node_save($appt_node);
    }
  }
}


synchronise development website with live website I'm developing a business website with Drupal 7 that is currently running on a server at my home so that I can just upload  everything to my VPS when it is all ready. I'm only a solo developer so I don't have the resources to have a production/staging site and different stages etc., but I do anticipate that there will be a time when this might happen and there will definitely be times when I need to do a major update on the website. So is there a way I can make changes to content, themes and modules on my server at home, and then once I'm happy 'synchronize' the changes with the actual website so that I don't have to keep putting the site in maintenance mode for long periods of time.

I can't just simply re-upload the site everytime though because it is an e-commerce site so hopefully orders will be flowing and there would be new user accounts since I pulled the database so that I could work on the website etc.

Hope that makes sense

This is a very long topic to cover fully so I will just push you to the right direction to get things rolling and save you from lot of trouble.

You should never sync your local db to production db after you have first installed the site to production environment. The sync process of db is always one way: production -> staging -> local environment. Also when syncing the db from production you should always sanitize the sensitive data (user emails and passwords) for example with Drush sql-sync --sanitize option (yes you can have Drush for Windows too). To able to use this kind of workflow you need to have the configuration of modules, views etc. in code not in db. In Drupal 7 you can use modules like features to achieve this. In Drupal 8 most of this will be covered with cores built-in configuration management. Of course on top of everything you need to use version control system to not go nuts when developing the site. Services like Bitbucket, GitHub and GitLab give you the needed tools and ge you going with VCS in no time. With version control you can compare different versions of code, fall back easily to previous versions in your code and easily take more collaborators in the mix in the future. Doing any size of development without version control system is just plain stupid.

If you can't afford to have a staging environment on a VPS you should use your local environment wisely. Having your local environment as close as possible to the production environment is a wise thing to do in any circumstance. Use a virtualization product like Virtualbox and install the exact same setup on your local computer than you have on your production. When managing several production environments tools like Vagrant, Chef and Puppet can help you to keep configurations in sync and make your life easier :)

Things you should also remember is to have regular automated backups of your production data, know how to fall back to previous versions of code, configuration and db if something fails and to treat production environment always as a production environment. Remembering all of this makes your life a lot easier :)


Upload gallery by ftp Is there a module for drupal7 that can create galleries from ftp? basically I upload a bunch of folders containing images in them by ftp. I want drupal to auto populate from ftp to create galleries.

Have you tried himuesgallery module?

  It implements a new node-type to show all pictures in an specified directory. Descriptions will be automatically generated from the filenames, so there is no need to administer a seperate databse table, etc.
  My gallery works with automated generetated thumbnails so it seems to be fast.
  It can use Lightbox2 or colorbox to simply generate lightshows and naturally it makes use of user configurable css-files to style the gallery. Some styles will be delivered with the module, so users don't be worried about this.


Uppercase module names - what could go wrong, technically? This is a technical curiosity question.

Afaik, it is convention that module names in Drupal should be lowercase, with underscores.

Obviously it is generally good to follow conventions.

But does someone know what could go wrong, technically, if module names are upper case or mixed case? E.g. camel case.

I think to remember to have seen at least one case in contrib where a module was CamelCase, but I don't remember which one.

Update functions, for example, go wrong: The regular expression that looks for them only works if the module name is lowercase only.

I don't remember exactly how it fails, but I used to have a case once where someone wrote a module that had uppercase characters and it wasn't possible to have update functions.

That's the only thing that I'm aware of.


How to add a new line item to existing recurring order? I've managed to get new line items added to a recurring order using hook_commerce_license_billing_order_refresh_alter() and the code is:

$product = commerce_product_load_by_sku($sku);
$li = commerce_product_line_item_new($product, '1');
$wrapper = entity_metadata_wrapper('commerce_order', $order);
$order_needs_save = TRUE;
commerce_line_item_save($li);
$line_items[$li->line_item_id] = $li;

It adds line items and correctly calculates new total and shows on the recurring order page. However, since this is a refresh hook it keeps creating new products, line items and licenses on every refresh. So I tried to attach already created line items the order's data array:

// Add line item objects to order data.
$order->data['lis'][] = $li;
// Add sku to order data.
$order->data['skus'][] = $sku;

and then re-use it with:

if (!empty($order->data['lis'])) {
        foreach ($order->data['lis'] as $key => $li) {
          $wrapper = entity_metadata_wrapper('commerce_order', $order);
          $order_needs_save = TRUE;
          $line_items[$li->line_item_id] = $li;
        }
      }

but, unfortunately, the new line items do not show on the recurring order. If I add commerce_line_item_save($li); line, then the website crashes giving:

EntityMetadataWrapperException: Unable to get the data property line_item_id as the parent data structure is not set. in EntityStructureWrapper->getPropertyValue() (line 457 of /home/username/public_html/sites/all/modules/entity/includes/entity.wrapper.inc).

So my question is: how I should properly add new line items to existing recurring order?

It works even with:

if (!empty($order->data['lis'])) {
  foreach ($order->data['lis'] as $key => $li) {
    $line_items[$li->line_item_id] = $li;
  }
}

However, to avoid re-adding new line item every recurring cycle, the hook_commerce_order_update should be used instead as recommended on https://cgit.drupalcode.org/commerce_license_billing/tree/commerce_license_billing.api.php#n129:

  Modules that need to respond to a license plan or recurring order
  changing should use hook_commerce_order_update instead.


drupal is welcoming other user after login I have website built on drupal 6.26.
Now i am facing a trouble that sometimes when the user logs in, the website is showing him Welcome message to another user!! for example if you login using user X, after reload of the page, it will show you a message of "Welcome Y" and shows the profile page of Y. fortunately, it shows profile Y but without Editing permission. and if you try to visit X's profile, it will be editable!!.
Any idea what could cause such ambiguity??


Specific URL routing I have a custom taxonomy for my posts called "Continents" and they could be:

Europe, Africa, Antarctica etc...

Then I have standard categories like: News, Reviews, Interviews etc.

And 1 subcategory for some categories e.g. for News I have subcategories like (entertainment, politics, sport, science etc.)

My question is how to set up URL permalinks in Drupal, so I have these types of links for "categories":

http://example.com/africa/news/politics
http://example.com/europe/reviews
http://example.com/antarctica

but at the same time I need to access things like:

http://example.com/news/politics

that will include everything from these categories and not taking care of the Continents taxonomy item.

And at that same time I need to access the posts (details) like:

http://example.com/2013/12/17/conflict-in-kongo-continues

Could that be done via Drupal or not?

Summary
I think you just need a couple of different views to create most of the functionality, but because the continent paths do not leave space for a path argument to call the view (eg example.com/viewname/africa/...), you might need to either duplicate the view with several displays or use some .htaccess mod_rewrites to point continent names at the view.
I have inserted a + into the first path (I hope that is alright?)
Suggestions
view: terms_by_continent

http://example.com/africa/news+politics
http://example.com/europe/reviews
http://example.com/antarctica

are presented by a view called terms_by_continent, with a contextual filter on term:name, accepting multiple arguments and defaulting to 'show all'. Create a different 'page' display for each continent so you can change the path to simply, for example, africa
view: terms_by_category

http://example.com/news/politics

would be a view called terms_by_category. The namespace is a bit difficult here because, unlike continents, I would guess this vocabulary might be subject to change, so creating multiple views displays would be tiresome and prone to error. If you are able to insert another path component then this becomes easy, ie category/news/politics would be served by a view of nodes with a contextual filter as above.
Multiple terms would normally be seperated with a + or similar, but if you needed to use / (ie news/politics) you could do a mod_rewrite on category/* to make this presentable
If you could not afford to add the category path component then I would guess you are stuck with using views displays as in term_by_continent to claim the paths that match each of your terms, accepting arguments for additional terms.
node: custom path
Finally:

http://example.com/2013/12/17/conflict-in-kongo-continues

This is the actual path to a specific article (node), so path auto is definitely the way to go. It will allow you to use tokens to construct your path for the appropriate content type, using date components and title.
Other solutions
I had a couple of other suggestions:

look at page manager, which might allow you to have greater control over paths for your views
you could try using pathauto for terms as well as nodes, and then replacing the term display with a view that accepted term:name as argument (as above), You could do this using term display or tvi

For option 2, I believe that (assuming there is not an existing page with this path), africa/news/politics for example, would not find a match, so would look for africa/news. Because that path also does not exist, it would fallback to africa, which (thanks to pathauto) takes you to the africa taxonomy term.
The term page contains a view, which accepts arguments (ie news/politics) and therefore you should get the appropriate listing. The view might need several displays which accept increasing numbers of arguments in order to allow the '/' seperated arguments, ie view/%,view/%/%, view/%/%/%


How do I translate strings in Twig templates? I am working on a (my first) Drupal 8 project witch is a multilingual site. Drupal 8 really delivers in terms of native support for content translation.
However, I have a few strings set directly in some if the theme .Twig template files printed out like ex.

{{ 'Read more'|trans }}

I am really stuck on where to handle the translation for strings like these within the Drupal 8 installation.

What steps do I need to take to be able to translate these strings into the language currently selected for on the site? Do I need any additional modules other than the ones included in Drupal 8 core?

Steps I have taken:

Activated the Content Translation & Interface Translation modules
Added Twig strings like {{ 'Read more'|trans }}
Flushed cache and refreshed pages containing the strings
Checked admin/config/regional/translate for the strings with no result

You need to visit the page in a language that is not English to have them picked up. That should be enough.


Render a webform to another node I have a new text format sample_page with the filter sample_page, I've created using hook_filter_info(). In the callback, I am rendering a webform using depending on the token in the node body, for webform I'm planning to use a token [block:webform:webform-client-form-2423].

I could render the blocks created programmatically, system blocks. But not the blocks created by other modules, I have tried [block:user:login] from http://mine.local/admin/structure/block/manage/user/login/configure to render to login blocks too. But these blocks didnt seems to work. Here is my callback for filter.

System blocks that worked for me, I used the token [block:block:25] from http://mine.local/admin/structure/block/manage/block/2/configure and for blocks created programatically by my own module, suppose my module is my_module,
I have used the token [block:my_module:block_name] from the url http://mine.local/admin/structure/block/manage/my_module/block_name/configure

preg_match_all('/\\[([a-zA-z0-9_\-]+:[a-zA-z0-9_\-]+)+\\]/m', $text, $match);
$matches = $match[0];
foreach ($matches as $token) {
  $token_name = str_replace(array( '[', ']' ), '', $token);
  $type = explode(':', $token_name);
  if ($type[0] == 'block') {
    $module = $type[1];
    $bid = $type[2];
    $block = block_load($module, $bid);
    $replacement = render(_block_get_renderable_array(_block_render_blocks(array($block))));
  }
}

Can any one look into the problem. Any help would be appreciated...

You can add the webform using hook_page_alter().

/**
 * Implements hook_page_alter().
 */
function my_module_page_alter(&$page){

  // Get the webform's nid that you want to display on the current page.
  $webform_nid = my_module_webform_to_display();

  // Load the webform node.
  $webform = node_load($webform_nid);

  // Render the webform using my custom view mode.
  $markup = drupal_render(node_view($webform, 'my_custom_view_mode'));

  // Add the markup to the page element.
  $page['content']['system_main'][] = array(
    '#markup' => $markup,
  );
}


How to add View Translated Version button in Views? My site is multilingual and I have a view page of content type. If node has translation then I want to add a button/link for viewing the translation.

Example

View Row 1
Title 1
Body 1
View in English | View in Arabic

View Row 2
Title 2
Body 2
View Full Content

View Row 3
Title 3
Body 3
View in English | View in Arabic

You can add filter 'Translation Language' in view which can be exposed for user to select the language.


How do you display all the tpl.php template files that are being loaded on the current page? Is there a function to show all the tpl.php template files being loaded on the page? Also showing the overrides too. I'm looking for a specific tpl file, but i have hundreds of the same tpl file that all have the same code and I'm not sure which file is the correct one.

the only thing that comes to mind is to uncomment $conf['theme_debug'] = TRUE; in setting.php. The description for this setting pasted below.

  Theme debugging:
  When debugging is enabled:
  -- The markup of each template is surrounded by HTML comments that contain   theming information, such as template file name suggestions.

  -- Note that this debugging markup will cause automated tests that directly check rendered HTML to fail.    For more information about
  debugging theme templates, see
  https://www.drupal.org/node/223440#theme-debug.

  Not recommended in production environments.

If anyone knows of a better way - please share.


Latest Best Practise: Reusing content/functionality between Drupal 7 sites Many of the Drupal 7 websites I make have the same functionality (e.g. blogs, news section, special offers). At the moment, I have to re-create the content types, fields, blocks and Views each time.
I am looking for a better way of working.

There seems to be a lot of modules that can help me, but I'm not sure which is the latest best practice.

Features - The module seems great for exporting content types, fields, menus and views. However, it does not seem to be able to export blocks, block positions or content.

Features extra - This module is designed for exporting blocks. However, on the project page, it says that UUID Features Integration is the future.

UUID Features Integration - This module doesn't seem to work (although A patch is available to fix things). Apparently, it has been dropped in favor of Deploy.

Deploy - This doesn't seem to work with blocks and is designed more for exporting nodes. I'm not really sure how it is a replacement for UUID Features.

Default Content - Another module that seems similar to deploy. (i.e. exports  nodes)

Apps - This seems to be a completely new approach that is a replacement for features. There is very little documentation on how to use it.

StrongArm - A lot of articles state that this module is essential for getting the most out of Features. However, I'm not sure how it relates.

I have searched quite extensively, but there seems to be a lot of conflicting information,

What is the best practice for what I want to achieve?

I would also like something that would work with Drush or a GUI so I can just select if I want a new site to have a blog, news archive special offer etc when building the new site in the first place.

There are two more options to consider:

User Drush make to create your own distribution:

  Drush make is an extension to drush that can create a ready-to-use
  drupal site, pulling sources from various locations. It does this by
  parsing a flat text file (similar to a drupal .info file) and
  downloading the sources it describes. In practical terms, this means
  that it is possible to distribute a complicated Drupal distribution as
  a single text file.

Run your sites in a multi site environment. This way you can easily reuse all installed modules and themes.

  If you are running more than one Drupal site, you can simplify
  management and upgrading of your sites by using the multi-site
  feature. Multi-site allows you to share a single Drupal installation
  (including core code, contributed modules, and themes) among several
  sites.


field type for True/False/Empty I have a field on a content type which is an optional override for another field. I want the value to only be either 0, 1, or empty, the last meaning "no override". What field type should I use for this? I was looking at a select list for a good user experience, but I was unable to get empty as a value in the list.

I also need another field that can only have values "img", "txt" or "". How should I accomplish this? I want to avoid having users type in "img" or "txt" in case they misspell it.

Select lists have always the option None if they are not set as Required. That said, you can create a List (Text) field  with select list widget and set only two options, 0 and 1, and you will get the None option automatically.


Error after installing and enabling "Rooms-Drupal Booking for Hotels, B&B and Vacations" and dependent modules After installing and enabling "Rooms-Drupal Booking for Hotels, B&B and Vacations" and dependent modules, I get this error when I try to go to the content menu. Does anybody have anything to fix this issue? I had to download multiple modules since they were dependent.

If you don't, can you recommend me a better solution for Room Reservations?

The dr8 part of your table name seems suspicious ... since you're using Drupal 7, while that dr8 might refer to something related to Drupal 8.

If that's not what is causing your problem, and as per the last phrase in your question ("... a better solution for Room Reservations ..."), then have a look at these alternative modules (with a stable release) for managing reservations in D7 (quotes are from their project pages):

Availability Calendars.

  ... allows you to add an availability calendar to entities. Example use cases are tourist accommodation, e.g. bed and breakfast, holiday homes or self catered apartments, and car or motor bike rental.

  An availability calendar shows your customers at what dates your accommodation is still available and at what dates it is already booked.

Simple Reservation.

  ... provides a simple and easy way to reserve items which can be created by the administrator. Examples for it's usage can be hotel rooms, boats, cars, airplanes, basically anything you can think of which can be reserved by one individual.

  The module provides the possibility to create reservations for other users (dependend on the permissions), and provides also restrictions in the maximum number of reservations a user can make and a maximum time a reservation can be made in advance.

  There is NO support for payment, booking and what ever one could imagine beyond the pure and simple reservation, and it is also NOT intended to create more than this simple functionality.

MERCI.

  ... can extend any content type into a list of unique reservable items (like studios) or buckets of interchangeable items (like DV cameras). We followed the approach used by Organic Groups, Feed API, and Scheduler and added MERCI's configuration to the Edit tab of those content types.

Resource Conflict.

  ... allows for users to book resources for use during events. For example, a student can book a microscope for use within their lab.

I've ordered my recommended shortlist above by number of reported installs. Though that is often a good first indicator, it should not be used as the only criterium to pick a module.


How to install latest stable Drupal version from drupal/recommended-project branch? I've forked drupal/recommended-project and run composer install from the default branch (8.8.x), it installed the latest dev version (8.8.6-dev). There's also a tag 8.8.5 (latest stable as of now) which has the same composer.json with the exception of these lines:

    "require-dev": {
        "drupal/core-dev": "^8.8"
    },

I've deleted these lines in branch 8.8.x hoping this would install the latest stable version but it installed the dev version anyway. I don't want to use tags because I forked the upstream and have my own changes.

How can I install the latest stable version of Drupal from the default branch (8.8.x)?

Instead of forking and running composer install, you should run composer create-project drupal/recommended-project <project_root_dir>. This will install the latest stable version of Drupal and you can of course add this to your version control system (don't forget to exclude all files that you don't have to track in your VCS).

When you use the composer.lock file from the GitHub repository directly, Composer installs the software versions as defined in the lock file (in this case the development versions).


How to create a new properties to $node (or $user and so on) I would like to add a properties to the node object (or user, file, etc).

I know that I can use a field, but it could be useful to do this.

Which is the way?

Thanks,
Sergio

In conjunction with the Entity API module, you can use

hook_entity_property_info

  Allow modules to define metadata about entity properties.

  Modules providing properties for any entities defined in
  hook_entity_info() can implement this hook to provide metadata about
  this properties.

e.g:

/**
 * Implements hook_entity_property_info
 */
function MODULE_entity_property_info() {
  $info = array();
  $properties = &$info['node']['properties'];

  $properties['nid'] = array(
    'label' => t("Content ID"),
    'type' => 'integer',
    'description' => t("The unique content ID."),
  );
  return $info;
}

See also entity_metadata_node_entity_property_info for default node property definitions.


Is there any 'advanced' debugging available for Views? I know Views can show you an SQL preview, various performance statistics, and other SQL queries performed for live previews; I'm looking for something a bit closer to the bone.

The use case...

I'm writing some custom handlers for various entity/field properties (doesn't matter which types, it's all very generic stuff). I'm trying to get these handlers applied to fields in a Search API view, and the 'standard' method of implementing hook_views_data_alter() and changing the field handlers to the new ones isn't working. I think perhaps because $data['commerce_product']['title'] (for example) isn't what the Search API view actually ends up using, so replacing the handler for the entry does nothing.

So I need to know what fields are using what handlers, and preferably anything else that would help me to understand why Views has chosen one and not the other.

I know I could theoretically do this by looping through the field definitions in a pre_render hook or similar, but I'd rather have a solution in place for this any time I need it, as opposed to having to write/copy code for it every time. It feels like such a thing should exist and that I just haven't come across it yet.

Is there anything either included with, or that can be tacked on to, Views (version 3 specifically) that will help with this?

The admin/reports/views-plugins show a table with every plugin used by Views, noting which views use them. And if you want to figure it out programmatically, you can check the code for that page.


How to display only Duplicate values with a view Background

My site is very large already and its only in its infancy. The content title table has 14000+ values in it. To make sure there are no duplicate values in the table I am creating a view that will display all of the institutions with the same title and the same address. At the current time I am just checking title to keep things simple.

Problem

The sizeable amount of data means that to return values is very slow.

Logic and Code

I am creating a view with address, type & title in a table with the requirement that the only institutes that come in have the same name.

My thoughts were that on every row I would take the $row->node_title and put it into a query against every other value in title like

$query= db_query("SELECT node.title
                  FROM node
                  WHERE ((node.status = '1')
                  AND (node.type IN ('institution'))
                  AND (node.title=".$row->node_title."))")->rowCount();

This should return a number, if the number is 1 then i want to exclude it with the following statement

if($query == 1){
  return true
}

Question

This is taking so long to calculate I thought there must be a faster way. I'm not even sure if the result from this is returning correctly because I've been waiting so long, Is there a faster way to get a list of all the duplicate values in a table with drupal?

Try using Remove Duplicates

  This module helps the administrator to easily remove duplicate nodes according to one of the node fields.


How can I limit the allowed quantity in the cart to one item? I am using Drupal 8/Commerce 2. How do I limit the quantity in the cart to one item so that users can't order more than one item per order.

Drupal 8 / Commerce have field "Default quantity to add to cart", so you can add default quantity for product is 1 and hide it from product page. After that user can't change quantity of products. Problem is solved!


I am looking for a responsive slider that can take text instead of images Do you know of a responsive slider that can take text instead of images?

I have been using Nivo Slider and have had great experiences with its responsive design. I am using one on the front page. I wanted another, so I used Views Nivo Slider. My client decided to have another with text instead of pictures, but Views Nivo Slider didn't seem to want to do this. I don't think I can hack the Nivo Slider code because it would effect my other sliders on my webpage.

Here are some pictures. With images, the slider behaves normally.

When I add the body content and change the slider to show the body as so,

I get this:

Nothing shows up.

The same thing happens if I try to put the body into the title instead of the image.

There is a smaller group out there Theme Boutique who built a really remarkable slideshow tool called the Revolution Slider.  It's currently out ther and available on their Dawn Responsive theme (I have used their BigWig theme in the past with the same slideshow).  It worked really well and didn't require alot of the gymnastics that I've seen with other solutions.

Here's a demo video of it in action.  https://www.youtube.com/watch?v=zZL2renvh5o


How do I have views exposed filter results in separate block? I know how to expose the Views exposed form on a block but what I would like is for the results from the exposed filter be shown as a separate block.

For example:

User will go to www.example.com/search_names
On this page they will see an exposed filter where they can enter a name and hit Apply
After the user clicks Apply the results are shown in a different block.

Thanks for any help.

I'm thinking that I may be missing a step in the process. Here are the steps I am taking and the order I am doing them:

Add New View and click on CREATE BLOCK on the Add New View page. (Both have display format of GRID)
I add my fields that I want to show in the filter result.
I add my Filter Critea and choose "Expose this filter to visitors, to allow them to change it "
I click on Advanced and under Expose Form In Block I choose YES.
Under Exposed Form Style I choose  Input required.
Under Use Ajax I choose Yes.
At this point, in the Preview section I no longer see my Filter Critea.
I save my View.
I now go to Structure then Blocks and can see 2 new blocks under Disabled: Exposed form: view_name-page and View: view_name
I assume that the one starting in Exposed form is the Filter Critea (where the user can put in the search paramater) and the one starting in View will be where the results of the Filter will be shown.
I place the Exposed Form block in the Content area of my theme and under Pages I input the node where I want this block to ONLY appear in. (In my case node/109).
I go back to the Blocks page and then place the View in the Content Area of my them and under Pages I input a different node where the results will be shown. The reason I have a different node is because on this node I have text that pertains to the filtered result.

I go to the node where I have the Exposed Form (node/109) and see the Filter Request. I type what I am searching for and hit apply. The results IS NOT appearing under the node where I placed the View block. Why is this?

Thanks for any help.

This has worked for me:

Make a View Page with the fields, filters and exposed filters you want. Make the view work with exposed fields in the Views Admin UI. In the view settings assign a page url.
When done with the above step, click the Exposed Form block in the advanced view settings (make a block of the exposed filters).
Then goto the Admin Blocks UI for your drupal site and place the block on whatever URL and theme Region you want. I placed my exposed form block on a Panel page.

When the filter form is used, it POSTS to the Views page URL within your view. You can't just make views block(s) for the display and exposed filter form(s). A block does not know from within Views where the <form action="SOME_URL_HERE" method="POST" /> url of the form should post to.

For example, the exposed form on some page

The result of submitting the form


How to set up a contextual filter or child relationship? Every now and then I'm re-attempting to set up a decent taxonomy explorer/browser. I have already managed to customize a tpl file for that (oh, I know, tpl should not contain advanced logic, some day I'll learn how to do that properly). Now I decided to give it a shot using Views. While I managed to set up a view for the top-level listing, now I'm trying to set up a decent lower-level browser.
I don't think it's possible, but maybe you will prove to me that it is.
My taxonomy has a very simple structure in that at a given level it has only branches or leaves, never are they mixed. Now, at some level (the depth is variable at different branches), the branches end and the leaves are to be listed. Therefore I'd thought this logic would be appropriate:

on page taxonomy/term/%
list items which
(a) belong to vocab X
and ((b1) are either children of parent with tid=%1
(b2) or are published nodes of content type Y with term tid=%1 assigned.)

For (b1) I have defined a parent term relationship and used it as a contextual filter. This alone works, but I don't know how to set up the b2 part. Can I re-use the same part of URL for another or'ed contextual filter. The '%1' string does not seem to work when entered in the filter section. What am I doing wrong?

Thanks.

Apparently there is no way to solve it using contextual filters and relationships. I solved the b2 part by using a separate dedicated view of content nodes as a No results view. It works because the taxonomy has consistent, non-mixed level contents.


Using Highlight Module with Default Search Module I'm trying to use this highlight module to highlight search terms on my site but can't seem to get it to work. I'm using Drupal 7, the basic search module that comes with Drupal, and Views to display the search interface (and results).

I think the main issue has to do with inputting a correct JavaScript syntax (regex) for local searches but the example given in the screenshot on the module page (linked above) only shows regex for apache solr and I'm wondering if anyone know what I should use for the default search, or if its even possible?

Note: I've already changed the 'Highlight area' option on the highlight module configuration page to .search (which is the body class for my search view).

I think, looking at the examples, that something like this expression should work if you have clean URLs turned on and searches have URLs like http://example.com/search/node/keywords.

\/search\/node\/([^?#]+)

But I have never used this module and it looks a bit ropey. You can test your own regular expressions at https://regex101.com/ (use JavaScript mode). Contrary to the examples you should not need to include the domain of your site in the search patterns.


Using #states with field collection I'm trying to use #states in a unlimited field collection (using the field collection module).

I'm adding this functionality to a node add form so am altering form elements using hook_form_alter.

I can get it to work for the first item in the collection using the following code but it doesn't work for items added subsequently.

$form[$k]['field_employee_name']['#states'] = array(
    'visible' => array(
        ':input[name="field_witnesses[und][0][field_person_type][und]"]' => array('value' => 'Employee'),
    ),
);

To get this to work we need to add the #states functionality to every field collection after the ajax callback has taken place.

To do this add an #after_build function to the field collection item in hook_form_alter:

$form['field_witnesses'][LANGUAGE_NONE]['#after_build'][] = 'field_witnesses_after_build';

And then in the after build function loop over the elements to add the #states behavior:

function field_witnesses_after_build($form, &$form_state) {
    foreach($form as $k => $v) {
        if(isset($v['#entity_type']) && $v['#entity_type']=='field_collection_item') {

            $form[$k]['field_employee_name']['#states'] = array(
                'visible' => array(
                    ':input[name="field_witnesses[und]['.$k.'][field_person_type][und]"]' => array('value' => 'Moto Employee'),
                ),
            );

        }
    }
    return $form;
}


How to access link fields (url and text) value separately in views template? My views block has a Link field named field_link, attached to a Content Type named products, and I'm trying access link field values(url and text) separately in views template views-view-unformatted.html.twig.

Following code gives the formatted html.

{{ row.content['#view'].style_plugin.render_tokens[ loop.index0 ]['{{ field_link }}'] }}

formatted html:

View Products

But I want to access the link fields(url and text) value separately. Any help will be appreciated.

I am not able to check row variable via kint/dump as I am getting PHP Fatal error:  Allowed memory size of 1073741824 bytes exhausted

The Easy way in Views UI add field_link 2 times.

in 1) Exclude from display, Select url only, and Show url as plain text.
which will give you the url only.

in 2) Exclude from display, and REWRITE RESULTS -> Strip HTML tags
which will give you the  title only.

Then in a custom field you can use twig  URL: {{ field_link }} Url Title: {{ field_link_1 }}

then in your custom template you can use them ...

Option 2) almost as easy create a custom field formatter based on
Drupal\link\Plugin\Field\FieldFormatter\LinkSeparateFormatter.php


How to use Coder with Drush? I have unsuccessfully attempted to find how to use the Coder module with Drush. Does anyone know how should I use it?

coder.drush.inc exists in module, so yes, it can. Only command available is coder-format. Module provides following examples:

  'drush coder-format sites/all/modules/coder/coder.module' => 'Re-format coder.module according to Drupal coding standards.',
  'drush coder-format --undo sites/all/modules/coder/coder.module' => 'Restore coder.module from coder.module.coder.orig backup file (if existent).',
  'drush coder-format sites/all/modules/coder' => 'Recursively re-format Coder module files according to Drupal coding standards.',
  'drush coder-format --undo sites/all/modules/coder' => 'Recursively restore Coder module files from *.coder.orig backup files (if existent).',


How to change date format of a custom entity in an update hook? In would like to display the created date of a custom entity in the "short" format, whereas currently it displays in some default format. This is in a module that is already in, production so I need to do it as an update. I've changed the custom entity code so that it looks like this:

    $fields['created'] = BaseFieldDefinition::create('created')
      ->setLabel(t('Created on'))
      ->setDescription(t('When the case was created.'))
      ->setDisplayOptions('view', [
        'type' => "datetime_default",
        'label' => 'above',
        'settings' => [
          'date_format' => 'short'
        ]
      ]);

Then I ran drupal update:entities but it did not change. I was not surprised, because I had read somewhere recently (I can't find it now, sorry) that it had become obsolete & custom entity updates now have to be done in update hooks.

But I am stumped as to how to update it in the update hook. I've tried this

function opencase_entities_update_8016() {
  $update_manager = \Drupal::entityDefinitionUpdateManager();
  $definition = $update_manager->getFieldStorageDefinition('created', 'oc_case');
  $update_manager->updateFieldStorageDefinition($definition);
}

... which did nothing, and then I looked at this documentation which helped me understand it's not the field storage definition that needs updating but the view config. So I made another update hook following the suggestion there, but simplifying it for my own case. I must have got it wrong because the date is still stubbornly showing in the default format. Can you help?

function opencase_entities_update_8017() {
  $update_manager = \Drupal::entityDefinitionUpdateManager();
  $field = $update_manager->getFieldStorageDefinition('created', 'oc_case');
  $properties = array(
    'targetEntityType' => $field->getTargetEntityTypeId(),
    'bundle' => $field->getTargetBundle()
  );
  if ($view_displays = \Drupal::entityTypeManager()->getStorage('entity_view_display')->loadByProperties($properties)) {
    foreach ($view_displays as $view_display) {
      $view_display->setComponent('created', array(
        'type' => 'datetime_default',
        'settings' => ['format_type' => 'short'],
      ) + $component)->save();
    }
  }
}

I randrush updb each time and it appeared to complete successfully. No errors in log.

When I changed base fields in the past they always updated in the plugin definitions on a cache clear. Also if this involved a schema update, by the way, which then produced a warning on the status page that there is a mismatch with the database, for which you then would need what you've described in the question.

In your case, though, my guess would be that the new settings are not valid for a timestamp field. The field formatter datetime_default is probably only working for a datetime field.

So try to change the field formatter in the base field definition to:

    'type' => 'timestamp',


Support composer_manager AND drupal-composer/drupal-project with contrib module Motivation / use case

I maintain the module package https://drupal.org/project/cfr, which currently requires composer_manager to be installed, and where composer_manager is required in the *.info files of some of the submodules.

Now I also want to support sites that install all their modules via composer, e.g. using https://github.com/drupal-composer/drupal-project.

However, the auto-generated composer.json files now require composer_manager, because they are generated from the *.info files.

composer_manager is undesirable in this context and even creates a conflict with composer_autoloader which is required by drupal-composer/drupal-project.

One specialty here is that there is no actual module named 'cfr', all the modules in the package are submodules like 'cfrapi', 'cfrplugin', 'cfrplugindiscovery' etc. This may or may not be a good choice, but it is how it is now.

Technical observations

I found, by looking into ~/.composer/cache/repo/https---packages.drupal.org-7/*, that Composer / packages.drupal.org creates "meta packages" for submodules.

Even if the submodule already has a composer.json file, this is replaced with a generated composer.json file that requires only the module dependencies from the *.info file, not the 3rd party dependencies from the composer.json file.

This means:
- The meta packages do require modules like drupal/xautoload and drupal/composer_manager.
- The meta packages do NOT require vendor libraries like donquixote/annotation-parser anymore.
- The main package 'cfr' seems like a combination of the meta-packages, but still does not require the vendor libraries.

Question

What do I need to do in a contrib module to support both composer_manager AND the full-composer scenario?

How can I avoid the 'composer_manager' dependency in the generated composer.json for metapackages for the submodules?

Especially, with the scenario above?

For my taste it is ok if the root package requires all the 3rd party stuff, so then I only need to prevent to require drupal/composer_manager.

Here are the conclusions I will follow for the CFR module package.

I am writing this as guidelines for module maintainers.

The steps may look different for other module packages with a different structure.

Start a new major version.

If the existing version of the contrib module requires composer_manager to work, supporting an alternative method might come with backwards-compatibility-breaking side effects. If this is the case, a new major version should be introduced.

Use the 'alternatives' module.

The alternatives module allows to replace one dependency with another.

In the *.info file:

dependencies[] = composer_autoloader
alternatives[composer_autoloader][] = composer_manager

This means: If 'alternatives' and 'composer_manager' are enabled, then the module in question can be enabled without enabling 'composer_autoloader'.

Depend on composer_autoloader

Let your modules, or one of them, depend on composer_autoloader, but add the alternatives[composer_autoloader][] = composer_manager as mentioned above.

Doing this in a subdirectory module causes the metapackage to require drupal/composer_autoloader.

Additional composer.json file at the top level

Why?

Composer manager will look at composer.json files per (sub)module. If the root dir of the module package contains a composer.json, but no module exists in the root dir of the module package, this composer.json will be ignored by composer_manager.

On the other hand, the project_composer module responsible for packages.drupal.org will extract metapackage information from the *.info file in a subdirectory module, but ignore composer.json files for modules in subdirectories.

Unlike composer_manager, it does look at the main composer.json in the package root dir, even if there is no module in this place.

How?

Put one composer.json at the top level directory of the module package. This has to require the 3rd party libraries from every submodule contained in the module package.

Keep the submodule composerjson files in place.

Replacement composer_manager for the transition.

Goal: Transition from composer_manager to composer_autoloader + drupal-composer.

Problem

If the modules were previously installed with composer_manager and now we want to use composer_autoloader, we are in a bit of a pickle:

At least one of the two dependencies must be enabled at any given time, to allow the dependee module to remain enabled and the 3rd party libraries to be autoloaded.
Downloading both with drupal-composer is not possible, because composer_autoloader declares a conflict with composer_manager in its composer.json.
Assuming we would find a way to download both composer_autoloader and composer_manager at the same time, having both enabled would be possible but would perhaps cause weird behavior due to duplicate vendor directory and duplicate autoload.
Updating code and database at the same time is not possible. We need to call drush en and drush dis, or do the switch via hook_update_N(), in the new codebase.

Solution

Let the site builder create a dummy / placeholder version of composer_manager in sites/all/modules/custom/composer_manager.

The only thing this would do:
- a hook_boot(), which would check if composer_autoloader exists, and if not, it replicate the behavior from composer_autoloader.
- a hook_uninstall() to replicate uninstalling the regular composer_manager.

Then use a hook_update_N() to enable composer_autoloader and disable + uninstall the placeholder composer_manager module.

Perhaps such a placeholder module could be provided on packagist, with an obfuscated name to prevent the conflict with composer_autoloader.


User login through token in URL in drupal 6 I have a drupal 6 website and I would like to implement the functionality to allow user of a particular user role to login into site using the token value in the url.

I have user role "SAP" in the website and will send a link to user in mail "www.example.com/user/token". When user click on this link, I want allow user to login into site automatically.

I have searched through into google and drupal site but I did not find any solution.

Thanks in advance.

urllogin module provides a way to transparently log users into the web site when they follow a link.

Give the “login via URL” permission to users who are allowed to log in with this module.

Alternatively you can try this module also

Easy Login allows the admin to give a permission to users so they are able to log in via an url.

Hope it will match your requirement !!


How to store some info while user is submitting rating with Fivestar module? I want to store this rating on different site and I am doing this with the help of RESTful api. I have altered "fivestar_custom_widget" form with hook_form_alter. My call is not working beacuse it is not removing div which has 'field-name-field-fivestar-rating' class and not adding div which has 'rating-wrapper' id.

function recipe_form_alter($form, $form_state, $form_id) {
  if ($form_id == 'fivestar_custom_widget') {
    $form['#submit'][] = 'fivestar_rest_api';
  }
}

function fivestar_rest_api($form, $form_state) {
   $ch = curl_init("http://www.example.com/");
   curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
   curl_setopt($ch, CURLOPT_HEADER, 0);
   $data = curl_exec($ch);
   curl_close($ch);
   $json = json_decode($data,true);
   $errorMessage = $json['errorMessage'];
   $errorCode = $json['errorCode'];
   $commands[] = ajax_command_remove('.field-name-field-fivestar-rating');
   $commands[] = ajax_command_append('#rating-wrapper', 'Thankyou for your rating.');
   return array('#type' => 'ajax', '#commands' => $commands);
 }

Submit handler was not working so I have decide to do it with validate handler like this

function recipe_form_alter($form, $form_state, $form_id) {
  if ($form_id == 'fivestar_custom_widget') {
    $form['#validate'][] = 'fivestar_rest_api';
  }
}

function fivestar_rest_api($form, $form_state) {
   $ch = curl_init("http://www.example.com/xxx");
   curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
   curl_setopt($ch, CURLOPT_HEADER, 0);
   $data = curl_exec($ch);
   curl_close($ch);
   $json = json_decode($data,true);
   $errorMessage = $json['errorMessage'];
   $errorCode = $json['errorCode'];
   $commands[] = ajax_command_remove('.field-name-field-fivestar-rating');
   $commands[] = ajax_command_append('#rating-wrapper', 'Thankyou for your rating.');
   return array('#type' => 'ajax', '#commands' => $commands);
 }

Now it is working fine form me.


How to check if Drupal user is logged in via htaccess? Is there a specific cookie Drupal uses to determine if a user is logged in or anonymous?

I need to check the cookie, and create a rewrite condition based on whether or not the user is logged in.

In the end, I would like something like this:

RewriteCond %{HTTP_COOKIE} !drupaluser=1 [NC]
RewriteRule ^(.*)$ /$1?no-cookies-for-you=%1 [R,QSA,L]

Thanks.

Drupal does store the session value in the cookie variable after the user is logged in. However, the name of this cookie is not fixed. It is basically a string that comes from the value returned by PHP function session_name; and starts with SESS. It would be hard to find and I would not recommend using regex, as I personally don't like it much.

If you really want to implement a solution with the cookie, I would suggest the following:

Implement hook_user_login() in a custom module:

function MODULE_user_login() {
  // set a new cookie here, with static name and value.
}

Implement hook_user_logout() and delete the cookie by setting an expiry date of past.

You can now use this cookie in your .htaccess!


Autocomplete not working for Search API with Solr - Drupal 7 I have these modules installed with Drupal 7:

search_api
search_api_solr
search_api_autocomplete

There is a view configured for search results with exposed full-text search filter, based on the index in Solr set up via Search API. The view is working well, however autocomplete function isn't working at all, no glimpse of it present. Are there any special settings for autocomplete that may need to be activated for the view?

The README.txt file in the search_api_autocomplete module provides the following information:

Necessary setup

After having installed and enabled the module, you have to do some
administrative steps to activate the autocomplete functionality. Autocompletion
can be enabled and configured for each search separately.

To activate autocompletion for an index's searches, go to the index's
„Autocomplete“ tab. There, you see all available searches for the index and can
enable (and afterwards configure) autocompletion for each of them. All fulltext
key fields on the searches should then become autocompletion fields.


How safely allow untrusted users to use img tag? Following this question, I'm wondering how can I allow users of a social site (which obviously are not all trusted) to upload images while avoiding XSS threats?

The default "Filtered HTML" text filter that ships with Drupal do not allow the <img> tag because image tags can contain attributes that allow for XSS attacks.

If you want to allow images, but also want to prevent untrusted users from using images as a vector for XSS attacks, you need to install and enable the WYSIWYG Filter and configure it to allow images, but disallow all unsafe image attributes.  You use this filter instead of the "Filtered HTML" text filter, not in addition to it.

To create a new text format, navigate to Configuration → Content authoring → Text format and click on Add text format. Select a name for the format (e.g. call it «Wysiwyg»). Enable it for all user roles. Below, I am going to show you how to fine tune the attributes allowed for this text format.  It may be a good idea to also enable the filters Convert URLs into links and Correct faulty and chopped off HTML.

If you use all three filters, make sure the filter processing order is the following:

WYSIWYG Filter
Convert URLs into links
Correct faulty and chopped off HTML

Now configure the WYSYWYG filter:

To make sure that no insecure markup emerges from your editor, you must create a white-list for the Wysiwyg text format. My recommended white-list for HTML elements and attributes is below:

a[!href|target<_blank|title],
div[align<center?justify?left?right],
p[align<center?justify?left?right],
img[src|alt|title|width|height], @[class|style],
h2,h3,h4,h5,h6,
br,span,em,i,strong,b,
u,s,strike,
blockquote,pre,address,sub,sup,
ul,ol,li,hr,br,
table,tbody,caption,tr,td

Creating a white-list of HTML elements and attributes and inserting it into the HTML elements and attributes in the Filter settings for the WYSIWYG Filter is not sufficient. You also need to whitelist the properties that is going to be allowed. By default, all properties are disallowed. To allow images and text to be styled and scaled, check the following properties:

The screen shot above  shows (the part of) the WYSIWYG filter configuration screen with tick boxes that allows the img attributes it is safe to allow untrusted users to use.

Disallow all other attributes.  Attributes that is disallowed will be stripped from the renderable version of the entity by the filter when the entity is saved after editing.

The screen dump below show the entire configuration screen I've used for my setup of the WYSIWYG filter.The text is too tiny to be readable, but I hope it gives you a rough idea about of it is configured.

After configuring the WYSIWYG filter, press Save configuration.

After creating the Wysiwyg text format, allow non-trusted users to access it, and make it the default by moving it to the top of the list of text formats, as shown in the screen shot below.


Javascript hotel price/availability calendar I'm trying to create a Javascript calendar which will show the price and availability of hotel rooms by date. Similar to this example (see Availability tab), however mine needs to show prices and availability for three different room types on each date.

So far I've tried out the Availability Calendars and Rooms modules, but both would require significant work to adapt to my needs.

I've also been looking into using a straight-forward calendar module. First I tried Calendar, however this reloads the page when moving to the next/previous month which won't do. Then I tried Fullcalendar, but I can't figure out how to make multi-day items appear as separate daily items (they appear as one item spanning many days), and there's also a problem rendering the calendar on a quicktab (it only shows the next/previous buttons and not the calendar until you actually click next or previous).

So I'm looking for some ideas on how to proceed...

PS I'm using Drupal 7.15

I figured it out using the standard Calendar plugin. You need to create the view as normal, then I created a custom block which embeds the view 6 times, calling it with a different month argument each time. Then I added some javascript magic to hide and show the calendars as required.

Create the block - PHP

/**
 * Implements hook_block_info().
  */
function viajes_block_info() {
  $blocks['viajes_room_prices'] = array(
    'info' => t('Viajes: Room prices and availability calendar'),
    'cache' => DRUPAL_CACHE_PER_ROLE,
  );

  return $blocks;
}

/*
 * Implement hook_block_view()
 * Display the search form in a block
 */
function viajes_block_view($delta = '') {
   $block = array();

switch ($delta) {
    case 'viajes_room_prices':
        $block['subject'] = t('Disponibilidad de habitaciones');
                    $block['content'] = viajes_room_prices();
                    break;
    }

    return $block;
}

function viajes_room_prices() {
$MONTHS_TO_SHOW = 6;
$hotel_nid = arg(1);

//js is already added by the reservation form code, no need to add it again
//drupal_add_js(drupal_get_path('module', 'viajes') . '/js/hotels.js');
drupal_add_js(array('viajes_room_price' => array('max_months' => $MONTHS_TO_SHOW)), 'setting');

//previous/next controls
$ret =
'

' . t('Previous') . '

' . t('Next') . '

';

//calendars
for ($i=0; $i<=$MONTHS_TO_SHOW-1; $i++) {
    $date = strtotime(date('Y-m-d').' +'.$i.' month');

    $ret .=
    '

' .
            date('F',$date) . ' ' . date('Y',$date) .
        '

' .
            views_embed_view('room_prices', 'page_1', $hotel_nid, date('Y',$date).'-'.date('m',$date)) .
        '

';
}

return $ret;
}

The Javascript

(function($) {
Drupal.behaviors.viajes = {
    attach: function(context, settings) {
           /*
        * Room price/availability calendar
        */

        //next button click
        $('#viajes-rooms-next', context).click(function() {
            var curr = getCurrent();

            //re-enable previous button if we've just left the first month
            if (curr == 0) {
                $('#viajes-rooms-previous', context).removeClass('disabled');
            }

            //disable next button if we've just arrived at the last month
            if (curr == (getMaxMonths() - 2) ) {
                $(this).addClass('disabled');
            }

            //roll the calendar if we're not on the last month
            if (curr < (getMaxMonths() - 1) ) {
                $('#viajes-rooms-month-'+curr, context).addClass('hidden');
                $('#viajes-rooms-month-'+(curr+1), context).removeClass('hidden');
            }
        });

        //previous button click
        $('#viajes-rooms-previous', context).click(function() {
            var curr = getCurrent();

            //disable previous button if we've just arrived at the first month
            if (curr == 1) {
                $(this).addClass('disabled');
            }

            //re-enable next button if we've just left the last month
            if (curr == (getMaxMonths() - 1) ) {
                $('#viajes-rooms-next', context).removeClass('disabled');
            }

            //roll the calendar back if we're not on the first month
            if (curr > 0) {
                $('#viajes-rooms-month-'+curr, context).addClass('hidden');
                $('#viajes-rooms-month-'+(curr-1), context).removeClass('hidden');
            }
        });

        //get currently visible month
        function getCurrent() {
            for (i=0; i<=(getMaxMonths()-1); i++) {
                if (! $('#viajes-rooms-month-'+i, context).hasClass('hidden')) {
                    return i;
                }
            }
        }

        //wrapper for the max_months setting
        function getMaxMonths() {
            return Drupal.settings.viajes_room_price['max_months'];
        }

    }
}
})(jQuery);

Just make sure you have the following classes in your CSS:

.disabled a {
pointer-events: none;
    cursor: default;
color: #979797;
}

.hidden {
    display: none;
}


How is the display in a view renamed? When you make a copy of one of  displays of a view the new display is given a name like Page 2. How do you rename that display? I can't seem to find a way of renaming the pge but I suspect there must be a link to edit it.

I have done it before and wonder whether some module or CSS change may be occluding the link required to change it.

If you want to change its machine name their option available in advance option of view or want to change its display name that will change form display.