How to resolve my Fatal Error after uninstalling Views Chart Tools and Google Chart Tools I'm getting the below Fatal Error after I uninstalled the Views Chart Tools and the Google Chart Tools modules.

  Fatal error: views_plugin_display::destroy(): The script tried to execute a method or access a property of an incomplete object. Please ensure that the class definition "views_chart_tools_plugin_display_dashboard" of the object you are trying to operate on was loaded before unserialize() gets called or provide a __autoload() function to load the class definition in /home/XXXX/XXXX/sites/all/modules/views/plugins/views_plugin_display.inc on line 272

I was working with them but they did not serve my purpose. After uninstalling them I started getting the above error.

I can't clear cache or even view the block admin page. Can anyone tell me what I can do to resolve this?

SOLVED - Used phpMyadmin and selected all cache tables then using the Empty option from the dropdown performed TRUNCATE on all cache fields. At this point cleared the cache that was throwing the error.


How do I remove the tabs from the edit field collection form in Drupal 7? When editing a field collection on a node there are two tabs typically, view and edit. I wanted to remove them. Obviously I can hide them with CSS, but this feels like the wrong way to do it. Is there a better way?

tab tamer has just been ported to D7 a week ago and might be able to remove those tabs as well.


"Call to undefined function fivestar_widget_form()" error I am getting the following error - it's related to the fivestar module. As far as I can tell, it is using an obsolete function call (used in Drupal 6)

Fatal error: Call to undefined function fivestar_widget_form() in /home/SITENAME/public_html/sites/all/modules/contrib/views_php/plugins/views/views_php_handler_field.inc(202) : runtime-created function on line 5

The problem is that I've looked at all references to the widget in the template files, tried to change them.

I've tried the following, as said here, but I keep getting the error.

print render(fivestar_widget_form($node));
print render($content['field_vote']);
print drupal_render($content['field_vote']);
print drupal_render(fivestar_widget_form($node));

What could be causing the error?

There's no function called fivestar_widget_form() in the Drupal 7 version of Fivestar (I've just grepped the module folder).

It's likely that function is a CCK hook remnant, CCK having been incorporated into the core Field module in Drupal 7, and all of it's functions renamed.

As far as I know there's no easy way in Drupal 7 to use a field widget form as a stand-alone form so you might have to look for another way around this problem.


Theme hook MENU_CALLBACK not found I am seeing this error in my logs:

Theme hook MENU_CALLBACK not found

What are the causes? I cannot find this exact phrase in google or d.o. This is an example menu item:

$items['user/%user/integration/%integration'] = array(
    'title' => 'View An Integration',
    'page callback' => 'integration_view_page',
    'page arguments' => array(3),
    'access callback' => 'is_owner',
    'access arguments' => array(1, 3),
    'type' => MENU_CALLBACK,
);

Yes, cleared caches, including menu cache. The actual page appears to load ok.

In my case, this was a mistake on my part. I recently performed a find and replace on my codebase to change all my menu hooks from MENU_LOCAL_TASKS to MENU_CALLBACK.

I clearly did this ignoring case, and also did not check properly as in my template.php, I now had...

$vars['secondary_local_tasks'] = array(
    '#theme' => 'MENU_CALLBACK',
    '#secondary' => $vars['tabs']['#secondary'],
);

instead of...

$vars['secondary_local_tasks'] = array(
    '#theme' => 'menu_local_tasks',
    '#secondary' => $vars['tabs']['#secondary'],
);

Because it was now called MENU_CALLBACK in caps, it confused me and I was looking in the wrong place. It is only when I went back and diff'd my entire backed up codebase did I notice it.

Lesson Learned: Find & Replace is not always a good idea :)


Will forcing validation on a node save result in security issues or data integrity loss? I have a content type containing lots of required and conditional fields. Because it can take a bit of time to properly create these nodes, and not all information will always be available to the end-user, I've implemented the ability for the user to "Save as Draft" while on this node's edit form.

Here's my form alter:

function mymodule_form_node_form_alter(&$form, &$form_state) {
  if ($form['#bundle'] == 'content_type') {
    // If node already exists and is not published, show "Draft" markup.
    if (isset($form['#node']->nid) && $form['#node']->status == 0) {
      $form['draft_markup']['#markup'] = '
Draft
';
    }

    // Add a new validate function to disable error checking on required fields.
    if (empty($form['#validate'])) {
      $form['#validate'] = array();
    }
    array_unshift($form['#validate'], 'mymodule_save_draft_validate');

    // Add 'Save as Draft' button
    $form['actions']['draft'] = array(
      '#type' => 'submit',
      '#class' => 'form-submit',
      '#value' => t('Save as Draft'),
      '#weight' => '0',
      '#submit' => array('mymodule_save_draft_submit'),
    );

    // Change submit button's text.
    $form['actions']['submit']['#value'] = t('Save & Publish');
  }
}

Custom validate function – the magic lies in &drupal_static('form_set_error', NULL, TRUE), where TRUE resets the static form_set_error variable:

function mymodule_save_draft_validate($form, &$form_state) {
  if ($form_state['triggering_element']['#value'] == $form['actions']['draft']['#value']) {
    // Set as unpublished.
    $form_state['values']['status'] = 0;

    // Force validation.
    $errors = &drupal_static('form_set_error', NULL, TRUE);
  } else {
    // Set as published.
    $form_state['values']['status'] = 1;
  }
}

Custom submit function – drupal_get_messages() stops "required" field errors from displaying when a user saves as draft, while a user doing the normal 'submit' will see the errors:

function mymodule_save_draft_submit($form, &$form_state) {
  drupal_get_messages();
  node_form_submit($form, $form_state);
}

Outside of obviously missing field data (which I'm not worried about since status = 0 and I can filter to never display unpublished nodes to the public) does anything stand out as dangerous here for a long-term, production site? Maybe the answer is simply "no", but forcing validation via &drupal_static('form_set_error', NULL, TRUE) makes me wonder if I'm opening the door to bigger security vulnerabilities. Because fields still run their validation, I am unable to get data to save that shouldn't be saved (i.e. if I try and put PHP code in a number input, the integer "0" is saved into the database - cool). Looking for a bit of peer review here...

Looking at Drupal code, I don't see any possible security flaw; there could be any, depending on the code executed from third-party modules.
For sure, I am expecting many errors raised for form fields that are added to the node edit form and whose content is not validated. None of the modules I know (and which alter the node edit form) validate the user input in the validation, and in the submission handlers they add.

Unconditionally removing any error message is not what I would do. I would rather let the users know when the node they are editing has been already changed from another user, which is the error message returned from node_validate().

  if (isset($node->nid) && (node_last_changed($node->nid) > $node->changed)) {
    form_set_error('changed', t('The content on this page has either been modified by another user, or you have already submitted modifications using this form. As a result, your changes cannot be saved.'));
  }

I would also let the users know there is already a translation for a node in a language, which is the error message given from translation_node_validate().

if (isset($translations[$langcode]) && $translations[$langcode]->nid != $node->nid) {
  form_set_error('language', t('There is already a translation in this language.'));
}

Using drupal_static('form_set_error', NULL, TRUE) (you could simply use drupal_static_reset('form_set_error')), you are resetting all the form errors for any form present in the page. See How do I make form_set_error() affect the submitted form only?

If I were to implement that code, I would write it as follows. I don't think that avoiding the validation errors are seen from the users causes anything good.

function mymodule_form_node_form_alter(&$form, &$form_state) {
  if ($form['#bundle'] == 'content_type') {
    // If node already exists and is not published, show "Draft" markup.
    if (!empty($form['#node']->nid) && $form['#node']->status == 0) {
      $form['draft_markup']['#markup'] = '
Draft
';
    }

    // Add 'Save as Draft' button
    $form['actions']['draft'] = array(
      '#type' => 'submit',
      '#class' => 'form-submit',
      '#value' => t('Save as Draft'),
      '#weight' => 0,
      '#validate' => array('mymodule_save_draft_validate'),
      // Change the following line to contain the name of the fields that
      // needs to be validated. As it is, it avoids any form field is validated,
      // when this button is clicked.
      'limit_validation_errors' => array(),
      '#submit' => array('mymodule_save_draft_submit'),
    );

    // Change submit button's text.
    $form['actions']['submit']['#value'] = t('Save & Publish');
  }
}

function mymodule_save_draft_validate($form, &$form_state) {
  $form_state['values']['status'] = 0;
}

function mymodule_save_draft_submit($form, &$form_state) {
  // …
}


Selecting the number of Records from Textbox I am trying to built a text box where I can type in the number of records that I want to select. So if I type in "100" the first 100 records should be selected and then will assign it to user. How do I make built this text box where it would select first 100 nodes and then perform the action of assigning it to user.

IIRC you could build this type of an Entity reference field with the help of Entity reference Views Display in Drupal 7 and the Entity Reference View Widget module.

In Drupal 8 you probably need the wonderful Entity Browser that is usually used to manage media files, but no reason not to use it for any other entity references. So you still need the Entity reference field, you just use the Entity Browser as the widget for that field to control how the choices are presented.

You'll probably want a filter above your results to list a certain number of results (100 for example) and then a "Select all" option to select all the results that have been filtered out (table display may come with that already).


adding multiple content elements to a page? I am coming from TYPO3 and like Drupal a lot so far. Especially how easy it is to define custom content elements with the fields feature.

But what I kind of miss is this:

In TYPO3 you have pages which can be filled with content elements of various kinds (text, text with images, tables, forms,...). I like this a lot. It's versatile and harder to mess something up for the editors compared to simply having a "page" where you have a big text area you have to work in.

What the best way to achieve something similar in Drupal?

Edit:
Here are two example screenshots of the TYPO3 backend:
http://www.aemka.de/fileadmin/_migrated/pics/Backend_2_02.png
http://www.form4.de/typo3temp/pics/faa6f10095.jpg

Yes, it seems like those panels are exactly what I am looking for. Thank you! :)

It seems you are looking for https://drupal.org/project/panels. It gives you the ability to add various types of content.


Can you have multiple groupings on a view? Is there a way to toggle between several different grouping on one view?

I have a view that is a list of nodes and I need to be able to group them by node title or by created date.   Is there a way to do this without having to create two different views?

Create multiple view pages in a single View definition and assign each with the same basic paths, but a different last segment eg. Node/%/Group1 & Node/%/Group2.
For each view select a menu item in the second column and set the type to menu tab.  Provide the name to display on each tab.
Set one of the pages' menu to default menu tab so it will show up first.  set its parent to already exists.

When you enter the path in the URL, you should get the default page displayed with the menu tabs above the view block.


Send newsletter with list of users with specific field value Is there a module to send a newsletter with a list of users with the same interests?

There is the simplenews module which will do the newsletter sending part of your question but similar interests is up to you to define. Drupal can't predict what "similar interests" are!

If you already have a list of users with similar interests, simplenews will enable you to create individual groups/mailing lists which you could add your users to.


Is it possible to change the location and size of the blocks/tabs in Drupal? This is my first time using Drupal. so I am not too familiar with it. My question is that is it possible to change the location, size etc. of blocks/tabs that are available as default through Drupal? The blocks/tabs I am talking about are shown in the following snapshot.

I assume, you are referring to "regions" as  "block/tabs". If that is the case, you can add/change the regions in your theme_name.info file and page.tpl.php file.

You may find this Link useful.


there is no edit option on certain views of drupal site There are certain blocks/views in drupal site where edit option is not coming and i am unable to figure out how to change them.

There is a "Hide contextual links" setting in views to turn contextual links on and off.

Set "Hide contextual links" to "No" as per this screenshot:


How to show 404 page for nodes without translation? I'm using entity translation and I need to show 404 page for a node if it hasn't got a translation available for current language.

For example, the  site runs EN, DE, FR, ES languages. Node 100 is translated to EN and DE. If i set current language to FR and visit the node 100, I'll see EN content due to the language fallback. But I would like to show 404 page.

How can I achieve this?

At first I was tempted to alter menu items responsible for node auto-loader function like this:

/**
 * Implements hook_menu_alter to hijack node auto-loader function.
 */
function et404_menu_alter(&$items) {

  // Remove original node view item...
  unset($items['node/%node']);

  // ... add our own node view item with custom auto-loader
  $items['node/%et404_hijacked_node'] = array(
    // Array items are copy-paste from node.module
    'title callback' => 'node_page_title',
    'title arguments' => array(1),
    // The page callback also invokes drupal_set_title() in case
    // the menu router's title is overridden by a menu link.
    'page callback' => 'node_page_view',
    'page arguments' => array(1),
    'access callback' => 'node_access',
    'access arguments' => array('view', 1),
  );
}

/**
 * Overrides node_load to show 404 page if translation is not available.
 */
function et404_hijacked_node_load($nid = NULL, $vid = NULL, $reset = FALSE) {
  global $user;
  global $language;

  $node = node_load($nid, $vid, $reset);

  // Only anonymous users are refused access
  if (!$user->uid && !isset($node->translations->data[$language->language])) {
    $node = false;
  }

  return $node;
}

Unfortunately this solution won't work correctly, because of menu_get_object() function that is used across drupal. That function assumes that every entity has it's auto-loader function named like ENTITY_TYPE_load(). The _load suffix is hardcoded into the function whereas it should be red from the entity info array provided by the hook_entity_info() (explicitly the load hook parameter).

I decided to use different approach that involves hook_node_access().

Actually instead of showing 404 with drupal_goto() I decided to incorporate drupal core and show 403. It can be turned into 404 anyway with a help of m4032404 module.

Please note that the following code is part of a module that also provides language fallback features similar to those from language fallback module - hence the reference to $language->fallback property that doesn't exists in vanilla D7. I am the author of language fallback patch for entity translation for D7 and D8 but for this particular project I needed something very sophisticated that I couldn't achieve with the language fallback module.

/**
 * Implements hook_node_access()
 */
function et404_node_access($node, $op, $account = null) {

  // We restrict access only to anonymous users so authenticated users can still manage content
  if ($account->uid) {
    return;
  }

  // Basic sanity check
  if (!is_object($node)) {
    return NODE_ACCESS_DENY;
  }

  global $language;

  // Check if translation for current language exists
  if (!isset($node->translations->data[$language->language])) {
    // Check if translation for fallback language exists
    if (LANGUAGE_NONE != $language->fallback && isset($node->translations->data[$language->fallback])) {
      return;
    }

    return NODE_ACCESS_DENY;
  }
}

/**
 * Implements hook_translated_menu_link_alter()
 *
 * This function checks if specific menu item points to the node entity
 * and if it is, checks if node has translation for current UI language.
 * Nodes without translation are hidden.
 *
 * See StackExchange answer for more info:
 * http://drupal.stackexchange.com/a/32024/5982
 */
function et404_translated_menu_link_alter(&$item, $map) {
  // Alter only custom menu items from "main menu"
  if ('menu' != $item['module'] || !isset($item['menu_name']) || 'main-menu' != $item['menu_name']) {
    return;
  }

  // Process only nodes
  if (!isset($map[1]) || !isset($map[0]) || 'node' != $map[0]) {
    return;
  }

  if(!is_object($map[1])) {
    // Instead of loading node manually, use core function for that.
    if (!_menu_load_objects($item, $map)) {
      return;
    }
  }

  // After _menu_load_objects() the $map[1] contains node object
  $entity = &$map[1];

  if (!et404_translation_check_entity($entity)) {
    // There is no translation for this entity in current UI language.
    // Hide the item and quit.
    $item['hidden'] = true;

    return;
  }
}

/**
 * Implements hook_menu_link_alter()
 *
 * When custom menu item is saved, we add 'alter' option to be able to
 * customize this item with hook_translated_menu_link_alter() implementation.
 * See et404_translated_menu_link_alter() for details.
 *
 * @param array $item
 * @param array $map
 */
function et404_menu_link_alter(&$item, $map) {
  // Alter only custom menu items from "main menu"
  if (isset($item['module']) && 'menu' == $item['module'] && isset($item['menu_name']) && 'main-menu' == $item['menu_name']) {
    $item['options']['alter'] = TRUE;
  }
}

/**
 * Check if there is a translation for entity in current UI language only
 * @param object $entity
 * @return boolean|string
 *   FALSE if translation is NOT available; otherwise true.
 *   Note that FALSE is returned also for entities without "translations" property.
 */
function et404_translation_check_entity($entity) {

  // Invalid data?
  if (empty($entity)) {
    return false;
  }

  global $language;

  // Check if current UI language is the same as entity language
  // This is a fail-safe in case "translations" property is missing
  // Note that taxonomy terms doesn't have language property
  if (!empty($entity->language) && $entity->language == $language->language) {
    return true;
  }

  // Check if "translations" property exists.
  // Without it further checks doesn't make sense
  if (empty($entity->translations)) {
    return false;
  }

  // Check if there is a current UI language translation available.
  if (!empty($entity->translations->data[$language->language])) {
    return true;
  }

  // Check if there is a fallback language translation available.
  if (LANGUAGE_NONE != $language->fallback && !empty($entity->translations->data[$language->fallback])) {
    return true;
  }

  // No translation available
  return false;
}

And as a bonus, a fix for language switching links:

/**
 * Implements hook_language_switch_links_alter
 *
 * Function alters language switching links for nodes
 * if there is no translation for currently viewed node
 */
function et404_language_switch_links_alter(array &$links, $type, $path) {

  $translations = array_keys($links);
  $translations = array_flip($translations);

  if (arg(0, $path) == 'node' && arg(1, $path) && !arg(2, $path)) {
    // !arg(2, $path) --> This will make sure we're not altering links like /node/1/edit/LANG

    // Most probably dealing with nodes
    $node = node_load(arg(1, $path));

    if ($node) {
      $translations = array_keys($node->translations->data);
      $translations = array_flip($translations);
    }
  }

  $languages = language_list();

  foreach($links as $lang => &$link) {
    // Check if translation for the language exists
    if (!isset($translations[$lang])) {
      // If not, check if the fallback translation is also missing.
      if (!isset($languages[$lang]->fallback) | LANGUAGE_NONE != $languages[$lang]->fallback && isset($translations[$languages[$lang]->fallback])) {
        continue;
      }
      $link['href'] = '<front>';
    }
  }
}


Content approval by roles here is my question:

I need to implement a content approval process, my client wants content to go through an approval process before being published.

I need to create 3 administrative roles, like Content Editors, Content Publishers and Super Admins.

Content Editors can edit content, but not publish it. Content Publishers can edit and publish content (which includes approving/rejecting any changes made Content Editors). Super Admins would have access to everything in Drupal 7.

Any help is appreciated.

Thanks.

Workbench is a great way to do this if you are OK with installing another module.

Workbench allows you to add moderation states. By default it gives you 'draft', 'published', and 'needs review'. (Drupal 8 also has "archived"). There is also a set of transitions that go with these states (ie, draft -> needs review)

For the three roles you described above, I would give the Content Editors the states to move from published -> new draft, draft -> needs review, needs review-> draft. Content Publishers would have access to all transitions, and super admins could override workflow entirely. This would produce the result you are looking for (and is what we commonly use with clients who don't need something more complicated).

D7 workbench can be a little confusing (very powerful means there's lots to configure!), but here's a good quickstart guide:https://www.youtube.com/watch?v=8nqWLrxH_4M

EDIT: As the OP points out, Drafty is a dependency for Workbench Moderation, which is needed for the above described solution. Drafty is no longer supported under Drupal' security advisory policy.


Drush is not able to bootstrap I installed Drush 7 using Composer, and I created a Drupal 8 running on XAMPP on Windows.

H:\xampp\htdocs\d8_test is the Drupal root.
Location of settings.php file is H:\xampp\htdocs\d8_test\sites\default\settings.php.

None of the drush commands are working. All are failing with the same error:

H:\xampp\htdocs\d8_test>drush pmi
Command pm-info needs a higher bootstrap level to run - you will need    [error]

to invoke drush from a more functional Drupal environment to run this
command.
The drush command 'pmi' could not be executed.                           [error]

Drush was not able to start (bootstrap) the Drupal database.             [error]

Hint: This may occur when Drush is trying to:
 * bootstrap a site that has not been installed or does not have a
configured database. In this case you can select another site with a
working database setup by specifying the URI to use with the --uri
parameter on the command line. See `drush topic docs-aliases` for
details.
 * connect the database through a socket. The socket file may be
wrong or the php-cli may have no access to it in a jailed shell. See
http://drupal.org/node/1428638 for details.

Drush was attempting to connect to:
 Drupal version        :  8.0-dev
 Site URI              :  http://default
 Database driver       :  mysql
 Database username     :  root
 Database name         :  d8_test
 PHP executable        :  php.exe
 PHP configuration     :  H:\xampp\php\php.ini
 PHP OS                :  WINNT
 Drush version         :  7.0-dev
 Drush temp            :  Z:\Temp
 directory
 Drush configuration   :
 Drush alias files     :
 Drupal root           :  H:/xampp/htdocs/d8_test
 Site path             :  sites/default
 Active config path    :  sites/default/files/config_MoeSD5C7JSguok
                          xrBh4-UuwT_r9_jk2Z59QKdN-j9Zx9DIgHBy2dH8n
                          1rGOeKNJpaAAxBi4PzA/active
 Staging config path   :  sites/default/files/config_MoeSD5C7JSguok
                          xrBh4-UuwT_r9_jk2Z59QKdN-j9Zx9DIgHBy2dH8n
                          1rGOeKNJpaAAxBi4PzA/staging

Contents of my settings.php

$databases['default']['default'] = array (
  'database' => 'd8_test',
  'username' => 'root',
  'password' => '',
  'prefix' => '',
  'host' => '127.0.0.1',
  'port' => '3306',
  'namespace' => 'Drupal\\Core\\Database\\Driver\\mysql',
  'driver' => 'mysql',
);

Note that host of my MySQL installation is 127.0.0.1 instead of localhost.

Also note that H:\xampp\php\ is added to my PATH variable, so php.exe refers to H:\xampp\php\php.exe.

The output of drush sql-connect is the following:

  mysql --user=root --password= --database=d8_test --host=127.0.0.1 --port=3306

The output of drush sql-connect is  mysql --user=root --password= --database=d8_test --host=127.0.0.1 --port=3306. Now, when I directly execute this command, it didn't work because mysql.exe was not there in the system PATH. So I added H:\xampp\mysql\bin to PATH (environment variable in Windows) and then it worked!


Pass user_register form field values to Pardot for extra processing I need to pass the values submitted during registration to Pardot using a form handler.

How can I accomplish the task?

First you'd want to add an additional submit handler to your form...

function pardotpost_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'your_form_id_goes_here') {
    $form['#submit'][] = 'send_to_pardot';
  }
}

Then in your new submit handler you post the data to their form handler

function send_to_pardot(&$form, &$form_state) {
  $url = 'http://pardot.com/your/form/handler/url/goes/here';
  $data = $form_state['values']['submitted_tree'];
  $options = array(
    'method' => 'POST',
    'data' => http_build_query($data, '', '&'),
    'timeout' => 15,
    'headers' => array('Content-Type' => 'application/x-www-form-urlencoded'),
  );
  $result = drupal_http_request($url, $options);
}

Lastly you check $result for any errors.
Cheers


Best Practice of Extending Another's Theme? I have a standard theme developed by others that I would like to add a custom view template to.

Is it OK to just create a new "views-view-table--MYVIEWNAME.tpl.php" file in the theme directory itself?

Or, is there a way to create a "sub-theme" for my stuff that inherits everything from the original theme?

Thanks. Bill

This is partly up to developer preference and specific use case but generally, if it is a custom theme, as in this case, you would add templates and modify css/template.php/etc. in the custom theme you already have.

If it is a theme from drupal.org or some other theme source, where updates for that theme may come in future, then it is best to create a sub theme of that theme (which you can do even if that theme is already a sub theme of another theme).


Modify Reference on Taxonomy Field Output I want to modify the output of a 'Reference on Taxonomy Field'.
I created a 'Reference on Taxonomy Field' in a content type that relates to terms in a vocabulary that have a title and a picture.
The content type is displayed by a view that outputs the fields of the content type. I added the field and created the template file views-view-field--kategorieseiten--page--field-produkteigenschaften.tpl.php and it works.

It should be displayed like this:

OUTPUT_OF_THE_TERM_PICTURE

The problem is that I don't know how to address the fields from the taxonomy term, since they are not directly stored in the node.

Thanks for your help!

I managed to load the fields of the taxonomy term with this code:

<?php

/**
 * @file
 * This template is used to print a single field in a view.
 *
 * It is not actually used in default Views, as this is registered as a theme
 * function which has better performance. For single overrides, the template is
 * perfectly okay.
 *
 * Variables available:
 * - $view: The view object
 * - $field: The field handler object that can process the input
 * - $row: The raw SQL result that can be used
 * - $output: The processed output that will normally be used.
 *
 * When fetching output from the $row, this construct should be used:
 * $data = $row->{$field->field_alias}
 *
 * The above will guarantee that you'll always get the correct data,
 * regardless of any changes in the aliasing that might happen if
 * the view is modified.
 */
?>

<?php $taxonomy_term = taxonomy_term_load(54); ?>
<a rel="tooltip" data-placement="bottom" target="_blank" data-original-title="<?php print $taxonomy_term->name; ?>"><img src="<?php print $taxonomy_term->field_icon['und'][0]['filename']; ?>">

But I want to load the terms dynamically from the tid stored in this field:

The field 'field_produkteigenschaften' is part of the content type and is stored in the node object.

How do I now address the tid stored in the field 'field_produkteigenschaften' in this template?


How do I delete custom entity instances? I've create a custom entity content with Drupal console,

 drupal generate:entity:content

Now I want delete (remove) it completely, how can I achieve it with drupal console or drush ?

my drupal version is 8.1.8 and my drupal console is 1.0 beta 5

update
I have serveral Entity in my module and I want to only remove one Content type, uninstalling module cause all Entity Database table dropped.

I know I can looking for entity table in database remove it and all related file manually I looking for a method with Drupal console or Drush

Drush 9 supports deleting custom entities
drush entity:delete my_custom_entity


Supplying current URL to "Path override" in Panels with Views pane Sorry if this is a known bug but I searched and couldn't find a related issue.

I have a view which has a "Feed" display (xml), and a "Views Pane" display.

On the "Feed" display the supplied path/URL for the display is "feed/xml".

The "Views Pane" display has a contextual filter for "Taxonomy term" and also a pager that has "Expose the Items Per Page" set to on.

Now when the "Views Pane" is included in a Panel, the Contextual Filter value (term id) is supplied from the Panel context (Node being viewed: term field on node). So now when you view the panel page and try to change the Items Per Page exposed form, it tries to submit the form to the "Feed" display's path which is "feed/xml" and that's wrong. Ideally the #action of the exposed form should be submitting to the current URL.

So I went back to the view and edited the "Views Pane" display, opened to "Allowed settings" and set "Path override" to on. And then went to the Panel config, and I put %node:url as the "Path override".

All well and good so far, but now when I view the Panel page and look at the exposed form's #action its the correct url BUT with added extra parameter which is the Contextual Filter's taxonomy term id. For example: if my current page is path/to/my/page then the #action of the form is path/to/my/page/115 where 115 is the ID of the taxonomy term currently supplied to the views pane through the panel context. So submitting the form produces a 404 in this case.

What I've tried so far is:
- Preprocessing the panel pane (theme_preproces_panel_pane) which didn't help a great deal as the view was already rendered as HTML in the content key of the $variables array. At this point I realized preprocessing theme functions won't work.
- So I moved on to Views hooks and tried hook_views_pre_render. dpm-ing the $view from this hook, I can see that $view->override_path (string) is the correct URL (without the extra term id), but the exposed form was also already rendered here in $view->exposed_widgets (string, rendered HTML) with the wrong URL (with extra term id).

So before I go through all Views hooks, and maybe not even come up with a solution, I wanted to ask this question, if anyone knows when exactly this exposed form is being rendered OR how I can stop the Taxonomy Term ID from being attached to %node:url token (Perhaps a simple configuration that I've missed or.. ?).

Edit

So I went through all the Views hooks. Also implemented a hook_form_views_exposed_form_alter. From the order the dpm's are being outputted, it looks like the order of execution is:

hook_views_pre_build
Exposed form gets built (dpm of hook_form_views_exposed_form_alter)
hook_views_post_build
hook_views_pre_execute
hook_views_post_execute

In hook_views_pre_build the path_override is correct. Form is not rendered yet.

In hook_views_exposed_form_alter the form render array is built, and $form['#action'] shows the wrong path with the extra term id.

So I need to somehow get in between these 2 functions and supply the correct #action...

Although this doesn't answer why exactly the term id is being attached (hoping someone might shed light on that), the simple solution thanks to @Letharion was to use the hook_form_views_exposed_form_alter:

function hook_form_views_exposed_form_alter(&$form, &$form_state) {
  $view = $form_state['view'];

  if($view->name == 'exhibitions' && $view->current_display == 'panel_pane_3') {
    $form['#action'] = $view->override_path;
  }
}


Which hook to use on initial creation of a node? I would like to execute a script once a new piece of content of a specific type has been created, but not updated. Which hook would I use for this?

I basically want to execute a script that will node_load the entity reference field and then email a bunch of users from that referenced node.

You're probably looking for hook_node_insert where $node should contain your node reference field.


commerce product display showing only one product when multiples selected I'm working on a Drupal 7 site using Commerce module.

When adding multiple products to a product display, I'm only seeing a single "Add to cart" button for the first product in the reference field, with no select menu for the additional products.

What's strange is that I did have that showing on the node, but not now - although I've only been changing view templates. Is there some config I should check to make sure this functionality is enabled that I may have inadvertently changed?

How would I ensure that a product display shows multiple products properly?

Check the Display settings for the Product Display type in Structure -> Content -> Product Types, and make sure that the Product field is set to be visible on all view modes.

Set it to "Add to Cart form" and it will display a choice of all applicable products.

Note - I had a duplicate "product" reference field on products which confused the issue, and this was what was displaying the single "add to cart" button.


Is it possible to do calculations like percentage in Views I am using Views module.
The view has three columns.

In the third column, I want a calculated percentage using the first two columns of the view.

You can use global php to acheive this (not recommended)

The best way to do it is by using this hook_views_pre_render(&$view) in your theme template file or in your custom module.


Drush do not autocomplete files and directory names I'm using Linux Mint 18 XFCE. Drush perfectly works, except for this annoying issue that it does not let me autocomplete file or directory names in a drush command.

Lets say that I want to sync my production files folder to my local files folder, so the command is:

drush rsync @site.prod:sites/default/files sites/default/files

When I'm typing the following parts I can pres tab and they are autocompleted:

drush
rsync
@site.prod

But when I'm typing sites/default/files it is not autocompleted, so I have to manually write the whole text, twice in this example.

It should be possible to do it in Linux because that's the normal behavior in Mac.

Just in case, here is the drush status result:

 Drupal version                  :  7.50
 Site URI                        :  http://default
 Database driver                 :  mysql
 Database hostname               :  localhost
 Database username               :  icolma
 Database name                   :  icolma
 Database                        :  Connected
 Drupal bootstrap                :  Successful
 Drupal user                     :  Anónimo
 Default theme                   :  cornelius
 Administration theme            :  seven
 PHP configuration               :  /etc/php/7.0/cli/php.ini
 Drush version                   :  5.10.0
 Drush configuration             :
 Drush alias files               :  /home/juankvillegas/.drush/aliases.drushrc.php
 Drupal root                     :  /home/juankvillegas/git-repositories/icolma
 Site path                       :  sites/default
 File directory path             :  sites/default/files
 Private file directory path     :  sites/default/files/private
 Temporary file directory path   :  /tmp

The problem is caused by the Drush version (5.10.0) that is the one available in Linux Mint repositories.

Once I disabled that version and installed the most recent one following the instructions in http://docs.drush.org/en/master/install/ it started working.


Permission denied for a route implemented by a custom module Hello I have the same problem with the following code:

first_module.routing.yml:

first_module.content:
  path: '/first'
  defaults:
    _controller: 'Drupal\first_module\Controller\FirstController::content'
    _title: 'Hello world'
  requirements:
    _permission: 'access content'

and the Controller:

<?php

/**
 *  @file
 *  Contains \Drupal\first_module\Controller\FirstController.
 */

 namespace Drupal\first_module\Controller;

 use Drupal\Core\Controller\ControllerBase;

 class FirstController extends ControllerBase {

   public function content() {
     return array(
       '#type' => 'markup',
       '#markup' => t('Hello world'),
     );
   }
 }

And I receive the same "Access Denied" error every time I try to access this page.

As suggested to me from @berramou the solution is:

  Add \ to Drupal\first_module\Controller\FirstController::content like
  \Drupal\first_module\Controller\FirstController::content and clear
  cash. – berramou 17 mins ago


Organic group membership request I need help setting up a notification system for when a user requests to join a group.

At the moment, when the user types in their message and click the join button, the administrator receives no email notification of a users join request.

Can anyone help ?

In OG 7.2 you need to enable Rules module then enable the two rules for "Pending" and "Active" memberships


What is best method for token replacement within node content? I am a newbie and have scoured forums (including this one), books, and documentation but cannot find a clear answer to this:

What is the best method (custom module? PHP within node content? other?) to replace a token within the body of a node with the value of a custom user profile field?

Use case: I need to replace text within an external URL with a string specific to the current user. I'm hoping I can put a token string into the URL within the node content, and have the token replaced with the specified value from the current user's profile.

I have not created any custom modules, but am willing to dive into it if somebody recommends a specific path to take.

Token Filter

  Token Filter is a very simple module to make token values available as
  an input filter.


How can I assign a database for each user? I am new to Drupal and facing problems. I want to assign a database for each user where user can edit, delete or make entry to their database table.

For example I want to develop a database management system for doctors so that each doctor has their own patient database with scanned image of report, patient name, address, description, sex etc so that they can keep track of their patients. How can I implement it in Drupal 8?

You could use the Group module for this. Group allows for creating arbitrary collections of your content and users on your site, and grant access control permissions on those collections. The Group module creates groups as entities, making them fully fieldable, extensible and exportable.

Some basics about he Group module to be aware of:

Make sure you enable gnode, a submodule of the Group module.
For each group type you need to define the appropriate permissions (view, edit, delete, etc) for the various Content Types.
Every group can have users, roles and permissions attached to it (refer to "What are the various roles supported by the Group module?" for more details about that).

With the appropriate permissions configured, it's just a matter of assigning a node to a Group: based on how you configured the roles and permissions, the Group module will allowed/deny access for any user.
Refer to "How to create collections of content that can be accessed by users with various access levels?" for more  info about all this.

Resources

Community documentation for the Group module.
Video tutorial "How to use the Group module in Drupal 8 to manage editorial access control to different areas of a web site".


What's the best way to maintain templates for standard pages and a front page? I’m developing a new Drupal 6 theme with a custom front page. My standard page.tpl.php has the entire HTML structure (as it should), including the doctype, HTML head, and HTML body.

When I make page-front.tpl.php, though, I have to duplicate page.tpl.php and modify it, meaning that whenever I need to make changes to the standard page template (add Javascript, modify CSS, etc.), I have to replicate all those changes in the front page template.

What’s the best way to avoid all this duplication? What’s the best way to keep the main page structure uniform? Create a custom function that spits out the HTML head? Put everything in separate PHP files (header.php, footer.php, etc.) and include them in the two template files?

To avoid duplication, creating separate PHP files might work, but the best answer is to you do everything in your MYTHEME_preprocess_page(&$variables) function, in your template.php file.

MYTHEME_preprocess_page(&$variables) {
  if($variables['is_front']) {
    //set variables to X
  }
  else {
    //set variable to Y (or just leave them)
  }
}

Now you probably won't even need page-front.tpl.php

Also, if you are using page.tpl.php and/or page-front.tpl.php you do have the variable $is_front available


One user with several profiles (pages) What modules are available (profile2 would come in handy i guess) to create something like pages on facebook.
Like on facebook each containing description, galleries and some other content i make available.
All handled by user who created pages.

I have idea in theory how would each user create pages, but i have no idea how would he for example when uploading gallery tell Drupal that the gallery he just uploaded belongs to page 3, while this user has 10 pages.

The 'edit own' permission should be all you need. Allow the user to create content of a specific node type. Put a gallery, description and any other fields on it.

A little more detail:

Create a content type 'Pages'.
Make sure users can create new pages and edit own pages.
The user makes as much 'Pages' as he wishes.
Put a gallery and any other fields on the content type.

If you want to use other content types instead of fields, use entity reference.


Apachesolr search results Facet Filter by date range I am using apache solr search with my drupal 6 website and seek a modification in the facets being displayed.

Instead of the yearly facets like this:

to somewhat like this:

last hour
last 24 hours
last week
last month
last year

I found http://searchhub.org/dev/2012/02/23/date-math-now-and-filter-queries/  saying that i can use fq=date:[NOW/DAY-7DAYS TO NOW/DAY+1DAY] in a custom module of my own to do this.

I tried this in my own module and figured out that its the $fq variable of apachesolr.module that should be overriden to achieve this.

I dont think I was able to use it successfully.

Can someone please tell me the exact function and variable to override.

If i clearly understand you will have to use facets date.

And using Solr there's a issue where you cannot do multiple facets on the same field in the same query... This issue is now marked as fixed Solr backlog but the release is not ready yet i believe last time i checked. In my case since the fixed was not ready i created in the schema new field that are copyfields and i do the appropriate query.

Therefore you will have something like that :

Last hour

f.date1.facet.range.start=NOW-1HOUR&f.date1.facet.range.end=NOW&f.date1.facet.range.gap=+1HOUR&

Last 24 hours

f.date2.facet.range.start=NOW-24HOUR&f.date2.facet.range.end=NOW&f.date2.facet.range.gap=+24HOUR&

Last 48 hours

f.date3.facet.range.start=NOW-48HOUR&f.date3.facet.range.end=NOW&f.date3.facet.range.gap=+48HOUR&

Last Week

f.date4.facet.range.start=NOW-7DAY&f.date4.facet.range.end=NOW&f.date4.facet.range.gap=+7DAY&

facet.range=date&facet.range=date2&facet.range=date3&facet.range=date4

Hi hope that helps you!!! Cuz i've look so long to figured out myself ;)


Error when I try to call a form Here is my class:

<?php

namespace Drupal\mais\Form;

use Drupal\Core\Entity\ContentEntityForm;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Ajax\ChangedCommand;
use Drupal\Core\Ajax\HtmlCommand;
use Drupal\Core\Ajax\CssCommand;
use Drupal\Core\Ajax\InvokeCommand;
use Drupal\Core\Form\FormBase;
use Drupal\mais\Form\annuaireForm;
use Drupal\Core\Datetime\DrupalDateTime;

/**
 * Form controller for adhesion edit forms.
 *
 * @ingroup mais
 */
class adhesionForm extends ContentEntityForm {

    public function getFormId() {
    return 'adhesion_form';
    }

   /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    /* @var $entity \Drupal\mais\Entity\adhesion */
    $form['#theme'] = 'adhesion_form';
    $form = parent::buildForm($form, $form_state);

    $entity = $this->entity;

    //pour l'ajax
    if (!$form_state->has('entity_form_initialized')) {
    $this->init($form_state);
    }

    $form['add_annuaire'] = array(
       '#weight' => '-9',
      '#type' => 'button',
      '#value' => "Ajouter une fiche a l'annuaire",
      '#ajax' => array(
        'callback' => 'Drupal\mais\Form\adhesionForm::addAnnuaireCallback',
        'event' => 'click',
        'progress' => array(
          'type' => 'throbber',
          'message' => 'Création du formulaire',
        ),

      ),
    );
  /**
   * {@inheritdoc}
   */
  public function save(array $form, FormStateInterface $form_state) {
    $entity = $this->entity;

    $status = parent::save($form, $form_state);

    switch ($status) {
      case SAVED_NEW:
        drupal_set_message($this->t('Created the %label adhesion.', [
          '%label' => $entity->label(),
        ]));
        break;

      default:
        drupal_set_message($this->t('Saved the %label adhesion.', [
          '%label' => $entity->label(),
        ]));
    }
   //$form_state->setRedirect('entity.adhesion.canonical', ['adhesion' => $entity->id()]);
    $form_state->setRedirect('view.intranet_adhesion.page_1', ['adhesion' => $entity->id()]);
  }
  public static function addAnnuaireCallback(array &$form, FormStateInterface $form_state) {

    $AddAnnuaireForm = \Drupal::formBuilder()->getForm('Drupal\mais\Form\annuaireForm');
    //return $AddAnnuaireForm;

    $ajax_response = new AjaxResponse();
    $ajax_response->addCommand(new HtmlCommand('#div-cible', buildAnnuaire));

   return $ajax_response;

  }

}

In the addAnnuaireCallback function,  the line

$AddAnnuaireForm = \Drupal::formBuilder()->getForm('Drupal\mais\Form\annuaireForm');

return an error:

Error: Call to a member function getEntityTypeId() on null in Drupal\Core\Entity\EntityForm->getBaseFormId() (line 79 of Drupal/Core/Entity/EntityForm.php).

Your form is a ContentEntityForm, so you need to use the entity form builder service, e.g.:

$entity = /** create or load your entity **/
$entity_form = \Drupal::service('entity.form_builder')
  ->getForm($entity, 'default');


How to set Target points to the User group? There is a User Groups in our site (i used og)
Point system for posting nodes
(for this i used userpoints,userpoints_contrib,userpoints_nc)

Since its working fine, Now i need to set target points to the groups, so that the users of that particular groups needs to get the target points. They need to get the alert message like

  You have earned XX points, you need to get YY points to finish your target

How to do this? Is there any modules for this requirement? guide me...

You'll probably have to use the Rules module to make it happen.

Maybe create some kind of custom field (integer) to store the value of your target points value. ie. target points field = 100 points

Now, you can create a Rule to activate on the event "user awarded points", so that every time a user gets points, that rule is run.

Next, have that rule activate a different rule component, which is designed to compare the user's current points total with the value in the target points field. (So, every time somebody is awarded points, the system will check to see if they have met their target.)

You can set a condition such that, if the current point value is "less than" the  target value, run an action "display a message" with some text saying you need XX more points till you finish your target.

(You may need an additional step to run a calculation on the points needed, but I think you get the idea of what you need to do with my example.)


Saving a particular field of a related entities with Entity Reference Using Drupal 7, using entity and entity reference i have created 2 entities: --*Aircraft reservation (date, user, aircraft categorie)
*Aircraft categories (name)

I have created a view (entity reference view) to list all aircraft categories.

Aircraft reservation reference aircraft categories.
In the form subbmission of Aircraft reservation i can see the list of the categories. The reference link with the view work great.

But when i submit the form, instead of having the categorie of the aircraft which i has selected saved, i have the details of the entity that present the categorie which i had selected.

With other words, Instead of saving the value of the field name of the categorie, drupal save the details of the entity.

How can i fix that ? Thanks for all !

I think the content is saved correctly but displayed wrong. Try to change your View which displays the results (the table). On the field for the entity reference, you should have an option to change the Formatter of the displayed entity. I think you have currently "Rendered entity" selected. Try to change to Label to only show the title of the referenced entity.

You could also display a different View mode for the rendered entity to show more/different fields. Check the Display Suite Module for this.


want to display values of content type Article in a page I have following fields in my content type Article:

Year: [have values - 2011,2012,2013,2014,2014,2016]
Volume: [have values - 01,02,03,04,05]
Issue: [have values - 1,2,3,4,5]

Title: [some value]
Description: [some text]

Now I want to display fields values like order below in views-view--archives--page.tpl.php

2013: [Volume3: Issue1, Issue 2, Issue 3] 2012: [Volume2: Issue1, Issue 2]

Maybe you can write a custom template or a custom theme function to output the fields, you will have to play with delta. You can also create multiple content types and link them with a relation field to create the hierarchy. You can also use a specific module that handles this kind of dimensional representation like tablefield or sheetnode.


get all nodes created in a specific month I have a custom search form that I posts a year + month, such as
2014-04
I would like to get all nodes created that month, when I create the timestmap I use:
"SELECT .......         AND changed >= 'strtotime($date)'"

This is the code for form date:

$form['aqar_date'] = array(
'#type' => 'date_select',
'#title' => t('Date'),
'#prefix' => '

Node date
',
'#suffix' => '
',
'#date_format' => 'Y-m',
'#default_value' => date('Y-m'),
'#date_year_range' => '-4:+0',
);

This is the form submit:

$start_date = strtotime($date);
$query = "
SELECT `nid` FROM `node`
WHERE
`type` = 'custom'
 AND `changed` >= '$start_date'";

But I'm not getting, I need a way to specify to only this month period not this month and newer!

Thanks!

Here you go with the code.. I have used entity field query to retrieve results.. Code should be self explanatory..  Let me know if you have any difficulty in understanding below code..

<?php

$year_month = "2014-04";
$date = date_parse_from_format ("Y-m" ,  $year_month);
$num = cal_days_in_month(CAL_GREGORIAN, $date['month'], $date['year']);
$first_minute = mktime(0, 0, 0, $date['month'], 1, $date['year']);
$last_minute = mktime(23, 59, 59, $date['month'], $num, $date['year']);
$entity_type = 'node';
$efq = new EntityFieldQuery();
$efq->entityCondition('entity_type', $entity_type);
$efq->propertyCondition('created', array($first_minute, $last_minute), 'BETWEEN');
$result = $efq->execute();
dpm($result);

?>


Cache sometimes is not being updated on saving operations This is a problem I'm struggling with for a few months already. I'm maintaining a pretty big news website, with a lot of content and multiple editors. The website is using paragraphs (which I don't think is relevant to the core of the problem, but is relevant for the description of it) and Memcache modules. Editors can rearrange the blocks on the front page, add/edit articles etc. The problem is that occasionally (and sometimes pretty often) when editors will do something on the website (edit article, rearrange blocks), change won't be visible on the website. It won't be even visible in the edit form of the just edited node when they will try to edit it again. It will appear after few approaches.

I know that in fact the change is being made after the first time, because I can reappear it with the dmemcache_object()->flush();, which made me think that it is a problem with Memcache. However, I replaced it with Redis and there is no improvement.

Some more information about the problem:

Core cache is basically disabled as we are caching everything in the CDN, but editors have direct access to the website, without CDN, and experience this problem there, so it is not CDN related. Below are website's cache settings.

I cannot reproduce the problem locally, even if I'm also using Memcache/Redis.
Sometimes when they are creating a new node with paragraphs, it appears "empty". During the edit, there are also no paragraphs. However dmemcache_object()->flush(); seems to fix this problem and makes everything appear (I tried it few times).
I tried even to add dmemcache_object()->flush(); to the save/update hooks, but it didn't help.

Any ideas of what can I do to diagnose and fix this problem? It is particularly hard to approach because it happens only on the production server.

Added #1:
When using redis module, and adding to settings.php:

$conf['path_inc'] = 'sites/all/modules/contrib/redis/redis.path.inc';

Problem expanded on paths. Some nodes had paths in the form of node/[node_id], but after removing this line, and clearing cache - proper, aliased paths has been restored.

Note: database is located on the different server.

Try Expire module  instead you try to clear cache manually.

  This module provides configurable actions upon events that will expire
  URLs from caches like reverse proxy caches, internal page caches,
  etc.This module make more sense when Minimum Cache Lifetime setting is
  set to a value other than none.

  There is now integration with the following modules:

Boost - deletes expired pages (files) from the file system.
Varnish - integrates over an administrative socket.
Fastly - Varnish/CDN caching
Purge - expires urls by sending purge requests to Varnish, Squid and Nginx over HTTP.
Acquia Purge - allows Drupal sites hosted on Acquia Cloud to automatically purge pages from their Varnish powered load balancers..
Memcache Storage - allows to delete pages that were cached in a memcached instances.
Akamai - provides an integration with the Akamai Cache Control Utility (CCU) Web Service
Recacher - Page cache warmer.

and Memchache Storage mdoule

Features

This module is an alternative to Memcache API and Integration module focused on different set of features. Available features (D7):

    You can move all cache to the memory.
    You can move users' sessions to the memory.
    You can move lock system to the memory.
    Module can store cached pages for anonymous users as a plain text, so proxy servers (like Nginx with enabled ngx_http_memcached) can get such pages directly from memcached pool and avoid heavy requests to the backend.
    You can clear data from single cache bin, cache cluster or flush all cached data from Drupal UI (screenshot).
    You can find helpful nice debug output (screenshot).
    Integration with Drush
    Integration with Administration menu. Module provides link for flushing memcached data from navigation toolbar.
    Active development and support.


How to link to files using a relative path? My site is in sites/sandbox folder. When I upload to live server, this will change to sites/mysite

In file system settings, the public file system path is set to sites/sandbox/files. When site goes live, I plan to change this to sites/mysite/files

File module is enabled and I am uploading PDF files. When entering content, how can I link to an uploaded file using a relative path that won't break when the site goes live?

Or perhaps the site directory name ('sandbox') should never be changed?

Did you try file_create_url() ?

$file_uri = file_create_url(file_build_uri('images/example.jpeg'));

The above snippet will give the file URL. Besides, I recommend transliteration module for the sites that deals with file uploads.


How to utilise isDefaultRevision() for forward revisioning? Since "Support revisions in different states" went into the core it is now theoretically possible to have forward revisions of nodes. For example publish revision 1 then create revision 2 but keep it unpublished. This is very useful when someone needs to create new version of a node that needs to be approved before publishing.

Sounds great so here's what I did:

I've created a node with title "Published revision". The node ID is 1 and it's revision is 1.
I've created a new revision of node 1 and changed it's title to "Unpublished revision". This node has revision 2 and it has immediately been set as default revision.
At this moment /node/1 shows the node with title "Unpublished revision".
I've used PHP to load node 1 with revision 1 and I've set it to default revision ($node->isDefaultRevision(true)).
At this moment /node/1 shows the node with title "Published revision".

So far so good. However the problem is that I'd like to edit revision 2 but I can't:

/node/1/edit shows edit form of revision 1.
/node/1/revisions/2/edit is of course 404.
And on top of that when I go to /node/1/revisions the revision 2 is listed as "Current" which of course is not true because default revision is 1. (Let's say I can live with that for now)

Questions:

How to edit arbitrary node revision?
How to control which node revision is saved as default revision?

It sounds like you want to use content_moderation experimental module that just went into Drupal Core 8.2.x-dev and will be available in Drupal 8.2.0.

That module should also be a great inspiration how to implement the functionality.

In general you will need to create your own route where you first load the revision of the entity, then save it when you get it back from the form with:

$node->setNewRevision();
   $node->isDefaultRevision(FALSE);

The function name is very misnamed (https://www.drupal.org/node/2706337 has the details).

However I strongly suggest to check content_moderation first and maybe you can just utilize it for your needs directly.


Downloads restrictions through direct URL I am developing one feature in which user will get one pdf from my site, for this I have developed a process below,

1) user will click on the link and form open in popup

2) after submitting the form one link will be  sent to his email address

3) when user clicks on the link one small process of token check will be done and he will get the file

4) second time this link will not work

This whole process is working fine here my question is I want to restrict the user to get my files when user directly hit the URL link like www.mysite.com/files/downloads/abc.pdf

users can only be able to download it through that link which is in Email.

Thanks for  advance.

Not sure if this will help you, as I have never used it, but worth checking out:
Unique-download

Onetime download link is useful to create one-time download link,
similar to one time login. This will be helpful to send users one time
download links for e-commerce or download entities such as books, mp3
etc etc. considering them as file attachment for initial development.


Is there a way to manage stock levels? Is there a way to manage stock levels with Drupal 8 Commerce?

I am not sure, but I believe Configure product attributes refers to product attributes, but it doesn't outline how to create stock management.

Yes, you are correct: The quantity available for a product is not considered a product attribute. A product attribute is, for example, color, size, weight. The quantity available in store is a value associated with the store, not an intrinsic property of the product.

Using only Drupal Commerce, you cannot manage stocks. There is a Commerce Stock module, but it just has only a development snapshot, for Drupal 8, which has been updated on November, 2017.

  The stock module does two main things

  Maintain stock levels
  Implement validation of stock to prevent users from ordering out of stock items

  The module does the following stock validation checks

  Disable the add to cart button for out of stock products
  Validates the add to cart quantity widget
  Checks current Cart quantity when adding to your cart (so if stock is 10 and you got 6 in your cart you can only add 4)
  Checks that all products and quantities in the shopping cart (/cart) are in stock
  On Checkout if you attempt to enter, continue or complete with out of stock items you get redirected to the shopping cart


How do I access the parameters fields of hook_mail_alter(&$message)? I am using hook_mail_alter in drupal 8 to alter the email messages sent  through contact form .
How can I access $message['params'] fields in hook_mail_alter()?

I am getting the following values with print_r(array_keys($message['params']));.

Array (
  [0] => contact_message
  [1] => sender
  [2] => contact_form
)

Can anyone suggest how I access the contact form fields?

When I access the values with print_r($message['params']['contact_form']);die; I don't get anything displayed.

The message entity is stored in $message['params']['contact_message'] and it contains all the values from the contact form. Given that it's an entity of type contact_message, you can operate with get() method to get the values of any field that your contact message might have. Example:

/**
 * Implements hook_mail_alter().
 */
function mymodule_mail_alter(&$message) {
  if (isset($message['id']) && $message['id'] == 'contact_page_mail') {
    /** @var \Drupal\contact\Entity\Message $contact_message */
    $contact_message = $message['params']['contact_message'];
    // Get sender's name.
    $sender_name = $contact_message->getSenderName();
    // Get sender's mail.
    $sender_mail = $contact_message->getSenderMail();
    // Get subject.
    $subject = $contact_message->getSubject();
    // Get message.
    $message_body = $contact_message->getMessage();
    // Get the value of "field_request" field.
    $request_value = $contact_message->get('field_request')->getValue();
  }
}


File to import not found or unreadable [omega 4] Windows OS I have installed omega 4 theme successfully with the help of this link on Windows 7 machine. Working with the theme is awesome, however when I enabled the sub theme ohm, there I am getting issues. I have made a change to the following line in ohm/sass/layouts/hero/hero.layout.scss

.l-constrained {
  width: 95%;

to

.l-constrained {
  width: $desk;

$desk is a variable declared in sass/variables/_grid.scss file.

Afterwards I am getting following error.

  sass/layouts/hero/hero.layout.scss (Line 1 of sass/variables/**/*:
  File to import not found or unreadable: ../../variables/_colors.scss

I can see there is slolution mentioned here, buit don't know how to implement it in omega 4 config.rb file.

Edit:

This is the problem of gem sass-globbing on Windows. If you are using it on Windows version having this issue, than try following solution sass-globbing does not support Windows 7. If it does not work, try the following alternative (not the best solution but it works). Add following line in ohm/sass/layouts/hero/hero.layout.scss

// Globbing from within sub-folders only works with relative paths.
@import "../../variables/colors";
@import "../../variables/grid";
@import "../../variables/legacy";
@import "../../variables/typography";

You can fix this by editing your Gemfile and changing:
gem 'sass-globbing'
to
gem 'sass-globbing', '1.1.0'

Then go back to terminal and type:
bundle

All should be fixed


Testing site with login access AND login inside I know it is counterintuitive, but I need to make my testing site secure and within it I need to test the user login module, so apparently I would be needing two login modules.

Is there a module that allows me to have two separate login systems? The "outer" one could be different from the "inner" one, of course. The "outer" one would only be for accessing a subdomain. The "inner" one would deal with user names and passwords.

Any idea and suggestions are welcome.

Thanx in advance.

Use the Secure Site module. This module allows you to authenticate users with a browser-based password (HTTP Auth). Giving you the "outer" authentication layer. Then use Drupal core's login for the "inner".


How to set available/unavailable dates in date webform component? I have a webform with a date component.

Then the visitor is able to select a date in a popup calendar. So far so good.

I need to show available and unavailable dates in the calendar, then visitors only can select an available date. Look my capture:

I'm trying with the availability_calendars which is a great modules. But I have 2 problems with it:

1) it is a 2 steps process, you choose the date in the calendar and then you are directed to the webform to fill the rest of information (name, phone,...)

2) the calendar allows the visitor to select 2 dates: Arrival and Departure dates. I only need one date.

How can I accomplish this?

You may want Date Restrictions module. It restricts allowed values in date fields, and datepicker popup widget, based on several criteria.

The module is still under initial development but may fit your needs. In any case please submit an feature request in the modules' issue queue if there's some missing functionality you find useful.


Making tags in Taxonomy-view appear dynamically? Background

I've created a Taxonomy-view that shows about 5 terms each time from a vocabulary of about 40 terms.

My desire

I need that in every page refresh, 5 different tags will be shown Randomly/dynamic, and not the same tags that appear there time and again.

I want to do it with the Views module itself, without further contribs.
I don't want to customize anything manually, rather using only the UI.

Clarification note

I'm not talking about random sorting of the existing 5 tags, rather I mean that each page refresh will bring different 5 tags, that are (generally) different from those in the previous refresh.

Add Sort Criteria: Global: Random in view

Change the pager limit according to your requirement


Drupal Search - Not searching for menu items The default search module inside Drupal works perfect my project but the client wants to search for menu items too. The search module won't find menu items and I can't find a normal description or tutorial that demonstrates how to search them.

Has anyone done something like this?

As a work around I would try to creat a "funny" content type for each Menu Item and them redirect it to the original page link of each Menu Item.


Trying to override the default taxonomy behavior, from a module Tried to catch the routes used for taxonomy display, didn't work, which leads me to believe that I'm not taking the right approach.

  $items['taxonomy/term/%'] = array(
  'title' => 'Activities',
  'page callback' => 'activities_route',
  'page arguments' => array(1),
  'access arguments' => array('access content'),

I'm using aliases which is why i'm trying to catch the system path.

My ultimate goal is to assemble & display three views into one page, based on the vocabulary of term that is passed in. Some views are shared, while others are separate and only need to be returned for a specific vocabulary.

I'm a PHP dev, but still learning about the Drupal stack.

Don't implement hook_menu() to override menu items of other modules. Implement hook_menu_alter() for that.


Drupal in sub directory, still not clear My drupal project is in directory /var/www/MY_ORGANIZATION/MY_PROJECT/current, and apache2 is configured to point the web subdirectory of the above location. When I access the site, it is of course under http://www.myorganization.it/. Now I need to move it to http://www.myorganization.it/myproject, both for organization policies and to allow it to be more easily reached through a reverse proxy. I searched around and I found a couple of interesting links, like this and this and a few more. Inspired by them, I tried to move the contents of web/ to web/myproject, but when I accessed http://www.myorganization.it/myproject I got blank page. The error in the logs is crystal clear:

Failed opening required '/var/www/MY_ORGANIZATION/MY_PROJECT/current/web/myproject/../vendor/autoload.php'

So I put back the installation in web/ and renamed it to myproject, changed apache configuration to point /var/www/MY_ORGANIZATION/MY_PROJECT/current, and that worked like a charm. But I am not sure this is an advisable configuration, since, well, since all Drupal installations I saw were in a web directory. Also, from my research I had understood that Drupal installation can be moved to arbitrary subdirectories, but I didn't find any official documentation. It would appear that I should at least configure a path for vendor.

So, the concluding question is, would you recommend simply renaming web to myproject, or should I do it another way?

EDIT: a symlink from myproject to web seems an elegant solution, it works fine in apache (dev environment), while I'm getting errors with nginx+php-fpm (staging environment); still, it may be the way to go.

Apache can handle this. You can leave the Drupal code where it is.

Have a look at the Apache documentation for Mapping URLs to Filesystem Locations. In particular, the differences between DocumentRoot and Alias.

In the absence of any other information, Apache looks for files/scripts in the document root. For a Drupal site located at https://www.myorganization.it/, it's enough to point DocumentRoot at the web directory. Apache will find index.php there.

But myproject isn't a directory in the filesystem. So you need to explicitly tell Apache about it, that any URL starting /myproject refers to the web directory. You can do that with the Alias directive:

Alias "/myproject" "/var/www/MY_ORGANIZATION/MY_PROJECT/current/web"

You'll also want to point DocumentRoot somewhere else to stop Drupal being visible at the root too (an empty directory will do).


How to publish referenced nodes at the same time node is published? I have a product content type and a review content type. A user can create a product node and then several users can review it. There is a node reference field in the review content type that links the product type using the node reference url widget.

The user can create and edit the product node but it is not published. However, there are links from the node reference url widget that allows for reviews to be attached that get published immediately. Now I have views on other pages with reviews that link to an unpublished node. This doesn't work.

How do I allow for reviews to be made but are not published if the product is unpublished and published if the product is published? Are there techniques using Rules?

Rules Views Bulk Operations is being worked on which will hopefully allow a change in a node trigger, through a Views argument, a VBO reaction that will, for example, unpublish a set of  referenced nodes.

However, I just needed to hide Reviews in Views that were spread around the website. This is done by using the Relationships content: reference and adding a filter content: published that uses the referenced node relationship to test if it's published.

The reviews will always remain published. They can be viewed if people know where to look which doesn't make a difference. However, now an anonymous user doesn't land on the front page sees a view with a new review that links to a product which isn't published resulting in a page not found error.


Display one recent comment in node teaser? Trying to find the easiest way to include the first most recent comment in my view that is using the 'teaser' mode. I am using the rate module to display number of votes in the view as well which doesn't have a 'field' to add so that is why I need to use teaser mode instead of fields mode.
Thanks

Add Views, Token, and Viewfield modules.

Make a new view. The first page gives you most of it: Show comments, newest first. Make a page, limit the number to 1. Continue & Edit, and set the contextual filter to Content: Nid. Be sure and save it. :-)

Edit your content type. Add a new field, of type Views. Set the default view to be the 'recent comment' one you just made. Under 'Default Values,' have it always use the default view, and have [node:id] as an argument. Save that.

Now you can manage the display of this field in the 'manage display' tab, and place it in the 'teaser' view.

You might find that showing the whole comment under the teaser looks wrong, so then it's time to go back to the view and tweak it so it uses fields instead of the whole comment.

HTH.


Taxonomy terms with image? Can I associate an image field to a taxonomy term? I need to do this in my panel that lists the children terms (with images to make it look nice) of a parent term page. I have already added image field in vocabulary thus images for each terms.

I'm on D7.

In D7 Terms are "entities", which means you can set an image field right on them, just like you could have with CCK in Drupal 6.

Just go to manage fields on whatever vocabulary you want, and you can add the image field.


How to collect and display visit statistics for a Views page? I wonder if someone can point me in the right direction for the following:

I'd like to collect and display statistics for a Views page.

I wonder what's the best approach for collecting basic 'hit' statistics for a views page (essentially a visitor counter for that view). The view uses contextual filtering (i.e. nid) to render content. Ideally, each path (i.e. viewpath/12, where 12 is the nid) has separate statistics.

Any guidance is appreciated.

Have a look at the Visitors module. Here are some reports you get from it:

  View pages that have recently been visited.
  View pages that have been hit frequently.
  View pages count per month, day of month, day of week, hour.
  ...

Especially these reports should be what you're looking for (it includes hits for paths corresponding to a view):

Top pages (table with columns Title, Path and nr of Hits).
Recent hits (table with columns Date of visit, Title, Path and User ID of the visitor).

Checkout the above (source) links to get an idea of which data are available.

Extra reporting features can be enabled via these sub-modules:

The Visitors GeoIP module, to also report about countries and cities.
The Visitors Browscap module, providing statistics on visiting browsers.

The demo site contains some sample reports (charts) available to anonymous users also. This demo site also shows some additional blocks with reports also created by the Visitors module module.

You may also want to look at the visitors_schema to get an idea of the data that actually get logged (recorded) by this module.

In case it's not a perfect fit, it's probably a very good starting point for some custom reporting. Either via a custom module that would simply have to query the data maintained by the Visitors module. Or via a straight forward custom report created with the Forena module.

Disclosure: I'm the maintainer of the Visitors module,
and co-maintainer of the Forena module.


Alternative to Simplenews, or a way to send formatted mailing lists to subscribers? I have installed simplenews on Drupal 7 but it seems all the related modules: Simplenews Content Selection (to build up the newsletter using nodes or views) and Simplenews Template are outdated (Drupal6).

Is there another way to use the nodes in the sites or at least creating a template to reuse with this module?

Or is there a way using other mailing list modules or custom code to build up newsletters from nodes?

br. onirio

Check out the new Newsletter module.

Features

Multiple newsletters lists configurable on terms, not vocabularies
Plain text or HTML out of the box
Multiple schedules Each newsletter can have more than one schedule, e.g. Daily, Monthly, Weekly, manually or even custom, eg after 10 new posts for this term.
Centralized administration and configuration on single page.
Users can customize the terms in the list they subscribe to
Custom template per list
Statistics (CTR and Open-Rate)
Drupal 7 only


How to restrict entity reference displaying values? I have a requirement which I feel quiet complex. I am using Entity reference in X content type to reference a content type(assume Y). This works fine by displaying all the values of Y in X.
  Y content type is having one field that is true or false type. So I want to display values in select list of X content type only which is having true value in the Y content type.So how can I achieve that, any suggestions will be appreciated.

You'll have to dynamically create that select list based on the field's values which are TRUE from the CT Y. I suppose that this select list belongs to a from, and what a convenient hook hook_form_alter is!

/**
 * Implements hook_form_alter.
 */
function module_name_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'node_xyz_form_id') {
    // Find all referenced items
    $target_ids = $form['field_reference_to_ct_y'][LANGUAGE_NONE][0]['#options'];
    // Load all referenced items
    $nodes = node_load_multiple(array_keys($target_ids));
    foreach ($nodes as $node) {
      if ($node->field_to_check_if_true[LANGUAGE_NODE][0]['value']) {
         // Alter the select list options
         $form[field_select_list][LANGUAGE_NONE]['#options'][$node->nid] = $node->title;
       }
    }
  }
}


Field API - defining a field, attaching it to privatemsg, and populating it "behind the scenes" This is actually related to a previous question ( Appending markup to privatemsg message body ) but as it's a slightly different issue I figured I'd start a new question.

In my original question, tenken's suggestion is to create a new module implementing hook_field_info(), then use field_create_field() and field_create_instance() on hook_enable() to attach the custom field to the privatemsg bundle.

I have sort of figured out the gist of defining a custom field and attaching it to a bundle, but I'm stuck with a few things despite extensive googling, searching drupal.org and documentation as well as searching for video tutorials on YouTube. Specifically:

when populating arrays to use with field_create_field() and field_create_instance(), I'm not sure what I should specify for the entity_type value. I know typical examples for these functions usually refer to 'user' and 'node', but what should it be for privatemsg?
I don't want the field to be visible on any forms as it's only intended to be populated "behind the scenes". I understand that I need to define a custom field formatter for that. How do I do that?

I think those are my only obstacles at the moment. Sorry if I appear lazy at all, but I only have very limited experience with Drupal module development, much less the field API, and this is my first D7 module. Needless to say I have searched for specific answers to the above but they continue to elude me!

Thanks

There is no need to define your own field type, just use a simple text field. You are storing a string after all, no need to re-invent the wheel.

The entity_type of privatemsg is privatemg_message. Note that you are not required to specify this property as the purpose of it is to limit the field for certain entity types. Leaving it empty means that instances of it can be attached to any entity.

To hide the field, you could use a module like Field permissions which gives you fine-tuned permission-based control over all fields. What that module actually does is provide a user interface for hook_field_access(), so you can alternatively implement that hook yourself and simply return FALSE for the field you created based on the field name.


What's the explanation for my product permission issue in a Drupal Commerce view? I'm very confused with some permissions and product displays in Views. Maybe you can help me to understand it.

I'm trying to make a view of product displays. In the view I include a relationship for the referenced product field, so I can get fields of the referenced product like for example Image, SKU, price, ...

I save the view, and if I go to the view's page as admin I can see the view correctly, but if I visit the view as authenticated user or anonymous no items are displayed in the view.

So I went to the permissions config page, and I checked the permission "View any product of any type" for anonymous and authenticated users.

After doing so, normal users and anonymous can see the view correctly. But while configuring that permissions it says:

"Warning: Give to trusted roles only; this permission has security implications."

So I do not know if I'm doing things correctly. And I wonder how to make a view of product displays and also get the referenced product fields and make it visible for anonymous and normal users?

Below is another recommendation to address your "... I went to the permissions config page, and I checked the permission "View any product of any type" for anonymous and authenticated users" ... and your "So I do not know if I'm doing things correctly".

Have a look at the (old) Drupal Commerce issue "Views results empty for unprivileged user when using Relationship: Content: Referenced Product". Especially what's written in comment nr 158, i.e.:

  edit your View: > "Advanced" > "Query settings" : check "Disable Query Rewriting"

So instead of granting that permission (so that "normal users and anonymous can see the view correctly", as in your question), it may be sufficient to just adapt these advanced query settings as mentioned above. If it does, it'll be way better then granting that permission with that scary warning.

If you want more info about what the real issue is (and why this is only a work around), then have a look at comment nr 101 of the same issue, which states:

  The issue is not with Commerce. It's a node access issue, and it's triggered when you use a Views Relationship with a node access module (such as OG or Domain Access), and there's no related item the user has access to. The quick work-around is to disable SQL rewriting, which allows the view to get all results and ignore the node_access rules -- of course, this will show content the user should not otherwise have access to.


Solr search not returning content type I have a site set up with Solr search. Drupal says 100% of the site is indexed, and the Search appears to work for most content types and their fields. However, the search does not seem to be searching all fields of the "Publications" Content Type.

For example, the second item in the list of publications (Title = "Bibliography of dry valleys...") has the following text in the "Bibliographic Citation" field:

  Mead, Kay L. Bibliography of dry valleys publications produced under
  the aegis of the New Zealand Antarctic Research Program 1959-1976 1977

However, when I search "Mead" in the Solr search I get "no results found". The same with "overseas", which appears in the abstract of the publication.

Yet, if I search "aegis" which appears in the title, the publication is returned.

How can I get Solr to index the other fields?

You have to tell Search API exactly what it should index:

Go to Admin -> Configuration -> Search and metadata -> Search API
For the relevant index, choose "Fields" from the drop down
Add your desired field(s) to the index and configure appropriate data types
Re-index all content


Rate Module: Display the rating in the comment user added to the node Is there a way to display the rating in comment given by a user in the node? For example, in this page http://www.yelp.com/biz/ikes-place-san-francisco at the top we can see the total rating, but in comments we can see the rating given by the user.

Is there some way to do this? Thanks!

I achieved a similar thing with the Fivestar module. The trick is to let the users vote when they comment. You can find a whole description for the set-up at https://drupal.org/node/1308114. Here is an adapted version of the documentation:

  Setting up the content type

  Go to admin/config/content/fivestar and create a new tag, e.g. called Vote or Rating.
  Go to your content type and add a new Fivestar field, e.g. called "Rating".
  Select the widget type Stars (rated while viewing) and tag the Rating.
  Select the number of stars. Make sure it will be the same on both the content type and the comments.
  Go to your content type's display settings and click the settings button for the Fivestar field.
  Set Value to display as stars as Average Vote.

  Setting up the comments

  Go to the comment field settings for your content type.
  Use Add existing field and add the same Fivestar field you created for the content type.
  Widget: Stars (rated while editing).
  Select the number of stars, equal to the amount that's used in your content type.
  Select the voting tag you created earlier and set the voting target to Parent Node.
  Go to the comment display settings and click the settings button for the Fivestar field.
  Set Value to display as stars as User's Vote and change Text to display under the stars to User's vote.

I asked a question about how to display the average rating as stars before: How to display the average rating of a node as stars in a view?. Maybe that can help you too.


Ajax http request terminated error while installing a Drupal 8 site I have installed WAMP Server for Postgresql and during the time of installation of Drupal (version 8), I got this error:

  Drupal\Core\Config\UnmetDependenciesException: Configuration objects
  (block.block.bartik_search,
  core.entity_form_display.node.article.default,
  core.entity_form_display.node.page.default,
  rdf.mapping.comment.comment, rdf.mapping.node.article,
  rdf.mapping.node.page, rdf.mapping.taxonomy_term.tags) provided by
  standard have unmet dependencies in
  Drupal\Core\Config\UnmetDependenciesException::create() (line 89 of
  core\lib\Drupal\Core\Config\UnmetDependenciesException.php).
  Drupal\Core\Config\UnmetDependenciesException::create('standard',
  Array)
  Drupal\Core\Config\ConfigInstaller->checkConfigurationToInstall('module',
  'standard') Drupal\Core\Extension\ModuleInstaller->install(Array, )
  install_install_profile(Array) install_run_task(Array, Array)
  install_run_tasks(Array) install_drupal(Object)

How can I solve this?

The UnmetDependenciesException is something you get when Drupal tries to install a configuration that depends on other modules/configuration which are missing.

You shouldn't see this error installing one of the standard install profiles. My hunch is that the source to your errors is PostgreSQL which is not fully supported by Drupal 8 at this time of writing.

See more in the issue queue: https://www.drupal.org/node/2157455 for running Drupal 8 on postgreSQL.


How to dynamic change the size of the icon marker when using Leaflet maps and views I am using the module Leaflet and its sub-module "Leaflet views" and IP Geolocation Views & Maps (IPGV&M for short), which provides a nice way to assign icon images to, in my case, content type in order to get a map displaying markers. I have set it up so to show different markers depending on the content type. I have also a field linked to the nodes, displaying a number, which is the number of users subscribed to that node.

What I need is to change dynamically the size of the marker, so that the nodes with more people subscribed (bigger int) will appear bigger than others with lower number.

I am using a view to display the map and the markers.

Any help would be greatly appreciated!

Maybe the Leaflet Extension module "Leaflet Label" helps to implement what you are trying to do? It provides a light-weight alternative to marker popups for Leaflet maps using labels, provided by the Leaflet Label javascript plugin.


Drupal 7 to D7 Migration I wan to migrate taxonomy terms from a D7 install to another.
The taxonomy terms have fields added to them and also translations.
Drupal Migration module would be the only option?

Use Taxonomy CSV import/export module. I used it once, works great...


What is the correct way to handle caching with custom modules? I'm experimenting with creating a custom module in Drupal 8. I have created a module that has some custom database tables. One of these tables, "mymodule_tickets" gets populated via admin forms that I have created within the module.

On the public side of the website, I have another custom page setup ('/booking'), which displays a form containing the available 'tickets'. For the mostpart, this works really well, but I am having some trouble understanding caching.

The '/booking' page uses the drupal form api to create a 'number' field for each available ticket. The '#title' of each form field is the name of the ticket as setup in the admin area. When anonymous users view the /booking page, the titles of these form fields cache. If I change the title of the ticket in my admin area, this does not get reflected on the public site for anonymous users.

My first attempt at remedying this was to add this when building the form:

$form['#cache']['max-age'] = 0;

But unfortunately this did not make any difference. Changes to the titles of form elements were still not reflected to the user.

In the end I had to add the following to my routing file:

  options:
    no_cache: TRUE

While this did work and stopped the form titles from caching, it feels like a very heavy-handed way to fix the problem. To me the correct solution would be to cache these pages for anonymous users, but to correctly invalidate the cache after making changes in the admin area.

Are there any guides or code snippets or articles about how to do this? From searching the web I haven't been able to find any relevant information or examples.

In your page controller for /bookings, set a cache tag in the build array:

$build['#cache'] = [
  'tags' => [
    'booking_page_settings',
  ],
];

Or since it's a form:

$form['#cache'] = [
  'tags' => [
    'booking_page_settings',
  ],
];

Then when you submit the admin form that has the settings for the page, invalidate the tag:

Cache::invalidateTags(['booking_page_settings']);

You can also add to your cache tags the nodes that display on your booking page, such as 'node:123', or you can add 'node_list' to invalidate the caching when any node is updated.


After every cron job, the Media tags in WYSIWYG markup change to https upon a robot crawl My site doesn't use https certificates.

The Media WYSIWYG markup changes the images protocol and caches them as https and therefore they don't display as there is no certificate on the website!!

The only thing I could do is re-save the affected pages if I spot them and then it's all good until another robot crawls them again in https after a cron job, which will revert the Media WYSIWYG markup from http to https and we are back to square one.

What is the solution for this?

Can the Pathologic module solve this?

If you don't want HTTPS, simply turn it off. And if, for some reason, you want HTTPS links to still work, you should redirect HTTPS to HTTP - but that's out of scope of this site. Just never leave https on without proper certificate.

That said, you have some serious bug in your caching configuration, and data you provided is not enough to identify it. Luckily, there is no need to do so.


How to use ctools modal to popup some fields of a node on node view? I want when a user is viewing a node, some of the node fields will be shown as a popup (without any buttons). How can I do it?

Thank You!

I know that there is no codeWriting service here, but I can try to explain (with example) the process (not a universal way.. Will work only with the content the same type and same structure (suppose we have a content type with body, field_description and field_something)):

You need to customize (override) template of the content type:

example (node--MY_CONTENT_TYPE.tpl.php):

<div id="node-<?php print $node->nid; ?>" class="<?php print $classes; ?> clearfix"<?php print $attributes; ?>>

    <?php print render($content['body']); ?>

    <?php print ctools_modal_text_button(t('Click to see DescriptionField'), 'show-as-a-popup/' . $node->nid .'/field_description/nojs', t('DescriptionField'), 'ctools-modal-custom-modal-style'); ?>

    <?php print ctools_modal_text_button(t('Click to see SomethingField'), 'show-as-a-popup/' . $node->nid .'/field_something/nojs', t('SomethingField'), 'ctools-modal-custom-modal-style'); ?>

Create custom module
Create a function in my_module.module file which includes ctools' libraries and sends javascript settings:

example:

function _myModuleIncludesModal() {
  static $added = FALSE;
  if ($added == FALSE) {
    $added = TRUE;

    ctools_include('modal');
    ctools_include('ajax');
    ctools_modal_add_js();

    $customModalStyle = array(
      'custom-modal-style' => array(
        'modalSize' => array(
          'type' => 'fixed',
          'width' => 800,
          'height' => 'auto',
          'addWidth' => 20,
          'addHeight' => 20,
          'contentRight' => 20,
          'contentBottom' => 20,
        ),
        'modalOptions' => array(
          'opacity' => (float) 0.6,
          'background-color' => '#000000',
        ),
        'closeText' => 'Close',
        'loadingText' => 'Loading...',
        'animation' => 'fadeIn',
        'animationSpeed' => 'fast',
      ),
    );

    drupal_add_js($customModalStyle, 'setting');
  }
}

Implement hook_menu() hook:

example:

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

  $items['show-as-a-popup/%node/%/%ctools_js'] = array(
    'title' => 'Node Field',
    'page callback' => 'nodeFieldPopupCallback',
    'page arguments' => array(1, 2, 3),
    'access callback' => 'user_access',
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
  );

  return $items;
}

Create a callback function:

example:

function nodeFieldCallback($node, $fieldType, $js = NULL) {
  if (!$js) {
    drupal_access_denied();
    drupal_exit();
  }

  ctools_include('modal');
  ctools_include('ajax');

  $nodeWrapper = entity_metadata_wrapper('node', $node);

  $output = $nodeWrapper->{$fieldType}->value();

  $return[] = ctools_modal_command_display(t('PoPUp'), $output);
  print ajax_render($return);
  drupal_exit();
}

Finally call our _myModuleIncludesModal() in "specific" node pages:

example (template.php):

function MY_THEME_preprocess_node(&$variables) {
  if($variables['type'] == 'MY_CONTENT_TYPE') {
    _myModuleIncludesModal();
  }
}

Modal settings/options, templating and throbber templating can be found in ctools' help directory;
Don't forget to flush the cache;


How can I make content type appear as a table? How can I make content type appear as a table each time I add content through it or its easier to make it in Views?

I am trying to make a website for students and each students will see some numbers and statistics only for him (absence, degrees, home works, etc). So how can I make a table in specific content type to fill the data instead of making a table for each student?

Use the Views module to show all your Students in a view and then with the help of the Views link area module create a link to Create Students.

  The Link Area module provides an "area plugin" for Views 3. It allows
  customized links to be placed in the header, footer, or empty text of
  any view.

  The obvious use case is to create a list of all nodes of type "foo"
  and then add a header link to the node/add/foo page. By making it a
  real link rather than just a blob of HTML in a header text area it
  gets all of the special handling and clean URL friendliness and
  base-path portability that any Drupal link gets.