Print node body removing html entities? Im printing the node body in my tpl file with this:

 <?php print render(field_view_field("node", $node, "body", array(
  "label"=>"hidden",
  "type" => "text_summary_or_trimmed",
  "settings"=>array("trim_length" => 150),
))); ?>

The " and ' characters in the node's content are breaking the page as im putting this in a mailto link. How can I make sure these characters are printed as non html entities eg &#34; instead of ".

You could wrap it in PHP's htmlspecialchars and strip_tags functions:

$body_trimmed = render(field_view_field("node", $node, "body", array(
  "label"=>"hidden",
  "type" => "text_summary_or_trimmed",
  "settings"=>array("trim_length" => 150),
)));
print htmlspecialchars(strip_tags($body_trimmed));

This would give you plain text with special characters encoded.

Alternately, if all you want to do is escape the quote characters and leave the divs in place, you could do a search/replace using str_replace for each, adding the backslash to escape them:

$body_trimmed = render(field_view_field("node", $node, "body", array(
  "label"=>"hidden",
  "type" => "text_summary_or_trimmed",
  "settings"=>array("trim_length" => 150),
)));
$body_trimmed = str_replace("'","\'",$body_trimmed);
$body_trimmed = str_replace('"','\"',$body_trimmed);
print $body_trimmed;


Drupal 6: integer field, how to output the value + a 3% up for a field, programmatically I have a production website with a content type that has 3 integer fields. Now the website owner wants to raise those values in a 3%. Since there are hundreds of nodes for that content type, is there a way to modify the output in a 3% via a PHP snippet?

The actual values can be updated. To increase the values by 3% you could use a snippet like the following and run it once, say in a hook_cron, then remove it after the update is complete.

// Create a list of nodes of the required type
$result = db_query("SELECT nid FROM {node} n WHERE n.type = 'YourContentTpe'");
// Iterate through the list
foreach($result as $row) {
   // Load each node
   $node = node_load($row->nid);
   // Calculate your fields
   $node->field_1[0]['value'] = 1.03 * $node->field_1[0]['value'];
   // .. repeat for each field ..
   // Then save the node
   node_save($node);
}

This assumes that all the field values are set. To be rigorous, you should probably check this on each field before attempting to access them. This method uses Drupal functions to keep track of the updates, but hundreds of node_load and node_save functions could significantly impact your server performance while the code is being run.

To just display the altered information without changing the values in the database, You could create three computed fields, and use each to display the value in its base field incremented by 3% as suggested by Human love. This will probably lead to confusion in the future if new nodes are added and the author forgets to reduce the entered information by 3% to have it display correctly.

As much as I hate to advocate it, if this is a one-time update of the information, the most efficient method both in terms of your effort and of server resources would be direct manipulation of the database. Just make sure you back up the database before proceeding,:

UPDATE node n JOIN content_type_{YourContentType} f on n.nid = f.nid set f.field_field_1_value=(1.03 * f.field_field_1_value), f.field_field_2_value=(1.03 * f.field_field_2_value) WHERE n.type='YourContent_type';

for each of your fields. This assumes that the fields are exclusive to the content type. If the field is shared between content types, the field will appear in its own table and the above query should be modified accordingly.


Scheduling unpublish too complex for existing modules I need a specific node type to automatically unpublish 3 months after publishing, but the date of unpublishing needs to remain constant even if the user unpublishes and republishes the node, unless the date is passed in which case it should start again.

Whenever the timer is reset a notice should be sent to the admins, and the date of scheduled unpublishing should be editable by the admins.

Needless to say this is too complex for any current modules, and when I think of writing a module to do it I don't know how to use the drupal api to schedule things with cron, or how to create an administration settings interface to handle the unpublish dates.

Drupal Scheduler will provide the proper infrastructure. Then in a hook_form_FORM_ID_alter(), you can set the date as follows:

global $user;
$roles = $user->roles;

$plusThreeMonths = date("Y-m-d H:i:s", strtotime("+3 months"));
$form['scheduler_settings']['unpublish_on']['#default_value'] = $plusThreeMonths;
// Disable setting of unpublished date unless admin or user 1
if ($user->uid != 1 && !in_array('administrator', $roles)) {
  $form['scheduler_settings']['unpublish_on']['#disabled'] = TRUE;
  $form['field_package_winning_bid']['#disabled'] = TRUE;
}

Then if you need to update the unpublish date, you can use a function similar to the following:

function _republish_node($nid, $time) {
  $node = node_load($nid);
  // Add time to the publish date
  $unpub = date("Y-m-d H:i:s", strtotime($time));  // pass in a string like "+2 weeks"
  $node->unpublish_on = strtotime($unpub);
  // Set published to true
  $node->status = 1;
  node_save($node);   // Re-save node with updated status
  scheduler_node_update($node); // update publisher fields
  // Add watchdog or other method to alert admins (or use rules)
}


re-triggering hook_user_default_permissions? I build a module that implements hook_user_default_permissions to manage permissions for my site. It's been installed on the site, and its permissions took. But now, a while on, I am making some changes to the permissions, but they aren't taking.

I am trying to figure out how to re-trigger the hook being run. I've tried clearing cache, rebuilding the registry, disabling, uninstalling, and re-installing the module, and rebuilding user perms. None of these have worked. I've looked in the role_permission table to verify, and my changes have not been added.

How can I get the hook to run again?

It turns out that this hook is a part of features, so I needed to do a drush fr my_module.


What is the form ID of a submitted Webform to perform a custom redirect? Once the webform is submitted, I need it to be redirected to edit form page where user can edit that form again.

I know is at webform->components->form settings and choose custom redirect. What is the value I should key in (since form ID is always different)?

There are number of ways to do this:

Use rules on event "After saving a node" -> condition : "node is of type webform" -> action : "add redirect" ; path : node/[nid]/webform. Note: [nid] might not be the exact token, but you'll get the exact token in the replacement patterns in the Rules UI.
Implement hook_node_insert in your custom module which triggers after every new node is created, check for the $node->type if it is of type webform, and use drupal_goto to redirect to the form components page. Path node/{$node->id}/webform.
Alter the node_form for webform to add a submit handler and use
form_state['redirect'] = 'node' . $form_state['nid'] . '/webform';


How to make a Views Filter criteria based on another language version existing? How to make a view that lists otherwise Finnish nodes but if there exists an English translation for the node, list that instead?

Filter criteria would be logically "Language: if there is an English translation, then that, else Finnish".

So when all nodes are Finnish, the list of the node titles would be (these are ordinals in Finnish, just for the example):

Ensimmäinen
Toinen
Kolmas
Neljäs
Viides

And then someone adds a translation to the second and third one, the list would become:

Ensimmäinen
Second <--- now links to the English translation of the node
Third <--- now links to the English translation of the node
Neljäs
Viides

Answer: https://www.drupal.org/project/select_translation. It does exactly what I need and much more.


HTML in data of theme_table() According to http://www.drupalcontrib.org/api/drupal/drupal!core!includes!theme.inc/function/theme_table/8

I created a table in my custom page in Drupal 8.

$build = [
  'table' => [
    '#theme' => 'table',
    '#header' => $header,
    '#rows' => $rows,
  ],
];

return $build;

Example of the first row.

$row = [
    'billing' => [
    'data' => $invoice . '<small>' . $label . '</small>',
  ],

In my page the <small> tag is displayed as it and not rendered as HTML tag. I tried to add attributes => ['html'] or this kind of option but it does not work.

How can I render HTML markup in theme_table()?

You can use FormattableMarkup to insert variables into html markup:

use Drupal\Component\Render\FormattableMarkup;

  'data' => new FormattableMarkup('<b>@bar</b>', ['@bar' => $foo]);


How to show/hide a block at some content types using PHP filter? I want to show/hide my block at some content types so I'm using PHP filter. My code in block configuration is:

<?php
if(arg(0)=='eshop') { return true; }
if(arg(0)=='node' && is_numeric(arg(1)) {
  return false;
}
return false;
?>

With this code the block is visible at every page even if it returns false, even if arg(0) is 'node' and arg(1) is 170. But if I use only:

<?php
if(arg(0)=='eshop') { return true; }
?>

It will show the block corectly only at /eshop page.

What is this, a GIANT Drupal bug?

There is another alternative available ... which doesn't require the PHP filter to be enabled (which you should try to avoid whenever possible) ... Just use the Rules block visibility module. Here is a quote from its project page:

  The Rules block visibility module allows Rules components to be used to control block visibility. This provides Drupal administrators and developers extreme flexibility in controlling when blocks should be displayed on their websites, in addition to the default visibility options provided by Drupal.

  The general idea is that if you can do it with Rules, you can use it to control block visibility, so the possibilities are limitless.

  Need to show a block only for users registered more than a month ago?

  Perhaps you have a block that must be shown only between 8am-5pm on weekdays?

  What about displaying or hiding a block based on current weather conditions?

  All of this can be done by using Rules block visibility.

With that, and as per the "if you can do it with Rules, you can use it to control block visibility" above, you've reduced your question to making Rules "check the path of the current page" (so that the block is only shown for the page with an URL like /eshop).

For an illustration of how to use this module, refer to my answer to "How to stop a Views block from displaying to admins, such as user/1?".


If content type with specific field that is not empty has specific taxonomy term attach library I would like to attach a specific library using a taxonomy term to a content type with a specific field that is not empty. The following is not working:

function lehigh_preprocess_page(&$variables) {
// Via taxonomy term: If the landing page is a node and has taxonomy
via a field named field_taxonomy
$current_route = \Drupal::routeMatch();
$node = $current_route->getParameter('node');
$target_taxonomy_id = 123;
   if ($node->getType() === 'standard_content_page') && $node->hasField('field_section') && !$node->get('field_section')->isEmpty()) {
     if ($node->get('field_section')->referencedEntities()[0]->id() == $target_taxonomy_id) {
     $variables['#attached']['library'][] = 'lehigh/financialaid';
}
}
}

Try the following , and don't forget to clear the cache

function lehigh_preprocess_page(&$variables) {
    $current_route = \Drupal::routeMatch();
    $node = $current_route->getParameter('node');
    $target_taxonomy_id = 123;
    if (isset($node) && $node->getType() == 'standard_content_page'
        && $node->hasField('field_section')
        && !$node->get('field_section')->isEmpty()) {
        if ($node->get('field_section')->referencedEntities()[0]->id() == $target_taxonomy_id) {
            $variables['#attached']['library'][] = 'lehigh/financialaid';
        }
    }
}


How to move "Add new comment" link How would I go about moving the "Add new comment" link above certain items in my content type display? Here's an example: http://www.jcpenney.com/women/fall-trend-shop/boyfriend/ana-boyfriend-cardigan-/prod.jump?ppId=pp5002961049&catId=cat100300005&subcatId=cat100250027&deptId=dept20000013&dimCombo=null&dimComboVal=null&colorizedImg=DP0705201317172824M.tif

In the link above you'll see the "write a review" link. This is where I want to place the "Add new comment" link.

You can create the node template for your content type. You can review the template suggestions link for reference.

You can add below code in your template file to generate a link for the comments.

print render($content['links']['comment']);

Kindly see that you need to uncheck 'Show reply form on the same page as comments ' checkbox in the comment settings for your content type.


Disabling auto-removal of 'rel' attributes in full HTML input format My Drupal 7 site , which is using Wysiwyg with the TinyMCE library, keeps removing the 'rel' attributes. Do you have any idea on how I disable this?

I fixed this by changing the formatting library from TinyMCE to Yui as it does not remove the 'rel' tag.


How can I display Drupal comments on a separate page from hook_node_view()? I have a custom implementation of hook_node_view() that changes the display of comments on every node. I would like to know how I can get the result of this improved hook_node_view() to be displayed on a separate page.

Each node should have its own comment page.

I have tried doing this with the Views module, but it seems bypassing hook_node_view(), which makes sense. So I'm still brainstorming on a way that can make this possible.

The Talk module shows the comments for a node in a tab added to the node page.

  The talk module removes comments from the node page and puts them on a separate tab. This style of commenting is very popular on Wiki sites (usually called the "discussion" page) and on news websites where the goal is to separate user generated content from editorial content.

  When installed this module will add a tab to the set of tabs at the top of a node view page like "View | Edit | Talk" and provides a link at the bottom of the node to go to the talk page and view comments.

If you need to do something similar, but on a completely different page, you can look at the code of the module to write similar code.
In short, apart from implementing hook_node_view(), the module implements hook_node_load() to set $node->comment to 0 (after saving its value in another node property). Then it calls comment_node_view() after temporary setting the values of the Drupal variables used from that function.

  global $conf;
  $clone = clone($node);
  $clone->comment = _talk_node_comment_value($clone);
  $recover = FALSE;
  if (array_key_exists('comment_form_location_' . $node->type, $conf)) {
    $original_setting = $conf['comment_form_location_' . $node->type];
    $recover = TRUE;
  }
  $conf['comment_form_location_' . $node->type] = COMMENT_FORM_SEPARATE_PAGE;
  comment_node_view($clone, $view_mode, $langcode);
  if ($recover) {
    $conf['comment_form_location_' . $node->type] = $original_setting;
  }
  else {
    unset($conf['comment_form_location_' . $node->type]);
  }

  // Display comment summary
  $addcmnt = ((_talk_node_comment_value($node) == COMMENT_NODE_OPEN) && (($view_mode != "teaser") || variable_get('talk_addcmnt_teaser', TRUE)));
  if ($addcmnt) {
    $links = $clone->content['links']['comment']['#links'];
    $node->content['links']['comment'] = array(
      '#theme' => 'links__node__comment__talk',
      '#attributes' => array(
        'class' => array('links', 'inline'),
      ),
    );

    foreach ($links as $link) {
      if(talk_activated($node->type)) {
        if (isset($link['href']) && $link['href'] == 'node/' . $node->nid) {
          $link['href'] .= '/talk';
        }
      }
      $node->content['links']['comment']['#links'][] = $link;
    }
  }
  // Add the Talk link if user has access and it's not blank
  if (_talk_access($node) && strlen(variable_get('talk_link', '')) > 0) {
    $node->content['links']['comment']['#links'][] = array(
      'href' => 'node/' . $node->nid . '/talk',
      'title' => talk_title($node, 'link'),
    );
  }


Aggregating Javascript files breaks JS On my d8 site I have AdvAgg CSS/JS Validator, AdvAgg Minify CSS, AdvAgg Minify JavaScript, AdvAgg Modifier and Advanced CSS/JS Aggregation enabled.

I have standard settings used in the AdvAgg config. For JS specifically, I am using JSmin + and delivering gzip'd assets.

Under admin/config/development/performance, if Aggregate JavaScript files is unchecked, my JS files are delivered from the js/optimized/ folder and JS runs correctly. When I check Aggregate JavaScript files on, assets are now placed from /js/ and javascript is broken.

Further, when I paste the optimized file name in admin/config/development/performance/advagg/info, for e.g.: js_nrTZ3IQttmDSsRueLl0pyxRvunHefp0r1WyIh5cFezg.js AdvAgg cannot find the file (but it can when aggregation is turned off).

Perhaps this all makes sense since aggregating JS files is a Drupal feature, but I've been down every related question/comment thread on google (changing .htaccess, adding tmp folders, changing folder permissions etc) and cannot find a fix for: AdvAgg is on with standard config, Aggregating JS files is on and javascript is broken. There are no obvious errors in the javascript console or drupal error log either.

EDIT

Here is what the file paths look like with aggregation on:
<script src="/sites/energyforum/files/js/js_tvBcOK6c8zbgb2_h2fxvH7fqhBBhGUnfOtQvWyXg1AM.js"></script>

The files are actually there, e.g.:

Here is what they look like with aggregation turned off

<script src="/sites/energyforum/files/js/optimized/js_dxIVcwvQ00owLGoUGPTfRYXU-T5rnj8Xi0cXfb3Kn58.0EvW5goc0mi1CLAZ226j56yYkdNjFXiaCYoOaoBMbKg.js?v=3.2.1"></script>

And, of course, there are many more of them (and javascript works)

This is commonly a result of loading theme javascript before it's dependencies.

If your theme lists multiple external js dependencies, or just has multiple custo. Javascript files, you may need to assign weights to establish a load order. Refer to
https://www.drupal.org/docs/8/theming/adding-stylesheets-css-and-javascript-js-to-a-drupal-8-theme

Likewise, if your theme depends on other javascript provided by other modules, be sure to list those dependencies in your theme.info.yml file.

After making any of the above changes, clear Drupal caches with aggregation turned on and retest.


How to sort comments by a new field in the comment table? I'm writing a module which allows users to put comment on each paragraph.

I have added a new field to the comment table, called paragraph_id, and in the comment form I have added a field that asks users which paragraph do they want to put comment on.

So now all I have to do is to alter the comment query. So something like what sort comment module does, it alter the comment query so that they got sorted by date, now I have to sort them by paragraph_id field.

This is the sort_comment.module :

  <?php
  /* drupal@ganovelli.it - blackice78 */
 define('SORT_COMMENTS_OLDER_FIRST', 1); // default
 define('SORT_COMMENTS_NEWER_FIRST', 2);
 /* Alter node type form: allow user to decide comments sorting */
  function sort_comments_form_node_type_form_alter(&$form, $form_state) {
  $form['comment']['comment_default_sorting'] = array(
 '#title' => t('Sort'),
 '#type' => 'select',
 '#options' => array(1 => t('Older first'),
                     2 => t('Newer first')),
 '#default_value' => variable_get('comment_default_sorting_' . $form['#node_type']-           >type, SORT_COMMENTS_OLDER_FIRST),
    );
  }
 /* Alter comments query */
 function sort_comments_query_comment_filter_alter(QueryAlterableInterface $query){
 if ( ($node = $query->getMetaData('node')) && (get_class($query) == 'PagerDefault') ) {
  $sort = variable_get('comment_default_sorting_' . $node->type,           SORT_COMMENTS_OLDER_FIRST);
  if ($sort == SORT_COMMENTS_NEWER_FIRST) {
  $orderby =& $query->getOrderBy();
  $expressions =& $query->getExpressions();
  if (isset($orderby['torder'])) {
      unset($expressions['torder']);
      unset($orderby['torder']);
        $orderby['c.thread'] = 'DESC';
      } else {
       $orderby['c.cid'] = 'DESC';
     }
  }
}

So, does anybody know how can I sort the comments by paragraph_id field?

The sort_comments.module checks if a special value is set to use its' ordering:

if (isset($orderby['torder'])) { /* ... */ }

You likely want to set an sql expression like they do for your own module.

Then in sort_comments.module they just set an SQL order by or leave the default ordering by comment_id (cid):

// ...
$orderby['c.thread'] = 'DESC';
} else {
   $orderby['c.cid'] = 'DESC';
}

You likely want to mimic this functionality in your own vesrion of hook_QUERY_TAG_alter, a specific version of hook_query_alter.


Need a list of terms from a vocabulary machine name How can I get the terms of a vocabulary using vocabulary machine name.

I have used the following code, although it works for me but I am looking for efficient methods.

$vocabulary = taxonomy_vocabulary_machine_name_load('school_courses');
$terms = taxonomy_get_tree($vocabulary->vid);
$courses = array();
foreach($terms as $term) {
    $courses[$term->tid] = $term->name;
}

What you are doing is pretty much the same as Drupal core is doing for the term reference field, so doubt you can improve the code much.

/**
 * Returns the set of valid terms for a taxonomy field.
 *
 * @param $field
 *   The field definition.
 * @return
 *   The array of valid terms for this field, keyed by term id.
 */
function taxonomy_allowed_values($field) {
  $options = array();
  foreach ($field['settings']['allowed_values'] as $tree) {
    if ($vocabulary = taxonomy_vocabulary_machine_name_load($tree['vocabulary'])) {
      if ($terms = taxonomy_get_tree($vocabulary->vid, $tree['parent'])) {
        foreach ($terms as $term) {
          $options[$term->tid] = str_repeat('-', $term->depth) . $term->name;
        }
      }
    }
  }
  return $options;
}


How to fix my problem when trying to create a Drupal sub-theme with Drush? I get the following error when I try to run the "drush fst foundation-subtheme" command.

sh-3.2# drush fst foundation-subtheme
The drush command 'fst foundation-subtheme' could not be found.  Run `drush cache-clear drush`  [error]
to clear the commandfile cache if you have installed new extensions.
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         :  7.32
  Site URI               :  http://default

  Database driver        :  mysql
  Database hostname      :  localhost
  Database port          :  3306
  Database username      :  root
  Database name          :  drupal
  PHP executable         :  /usr/bin/php
  PHP configuration      :
  PHP OS                 :  Darwin
  Drush script           :
  /Users/Marianna/.composer/vendor/drush/drush/drush.php   Drush version
  :  8.1.3                                                    Drush temp
  directory   :  /tmp
  Drush configuration    :
  Drush alias files      :
  Drupal root            :  /Users/Marianna/Documents/Sites/Link-New
  Drupal Settings File   :  sites/default/settings.php
  Site path              :  sites/default

I get the following error when I try to install foundation with drush:

sh-3.2# drush --uri=http://linkengineering en zurb_foundation
Command pm-enable needs a higher bootstrap level to run - you will need to invoke drush from a  [error]
more functional Drupal environment to run this command.
The drush command 'en zurb_foundation' 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         :  7.32
  Site URI               :  http://linkengineering
  Database driver        :  mysql
  Database hostname      :  localhost
  Database port          :  3306
  Database username      :  root
  Database name          :  drupal
  PHP executable         :  /usr/bin/php
  PHP configuration      :
  PHP OS                 :  Darwin
  Drush script           :
  /Users/Marianna/.composer/vendor/drush/drush/drush.php   Drush version
  :  8.1.3                                                    Drush temp
  directory   :  /tmp
  Drush configuration    :
  Drush alias files      :
  Drupal root            :  /Users/Marianna/Documents/Sites/Link-New
  Drupal Settings File   :  sites/default/settings.php
  Site path              :  sites/default

The issue mostly will be with environment/php and this is issue with MAMP (mismatch of path your MAMP-php and Server-php). Follow this link from that article.

  The Solution: A Symlink

  For the sake of ease, let’s just make your terminal sessions use the
  same PHP executable as MAMP. So run this:

$ mv /usr/bin/php /usr/bin/php.bak
$ ln -s /Applications/MAMP/bin/php/php5.5.3/bin/php /usr/bin/php

But you need to check path as per your folders.


i am getting "Error generating image." Files permission is 777 and gd library is installed I had installed gd library and also given 755 permission to the files but i am getting 500 - error generating issue in my drupal

My site URL is http://vestcom.ca/dev/

One of example URL of error is http://vestcom.ca/dev/?q=sites/default/files/styles/cardealer-car-mini-thumbnail/public/property-photos/IMG_1373.JPG&itok=_DfNUQVW

If anybody have any idea about how do i debug this or how can i get image then please let me know.

Check your image toolkit (URI /admin/config/media/image-toolkit). You must see like this


drush: How to upgrade to a stable module release instead of dev? When I use
drush pm-update
it takes always the latest which is usually a dev release. How do I force it to update to the next stable release?

pm-updatecode (and pm-update, which calls it) will not ever switch from dev to stable.  If you're on a dev branch, and want to go to a stable release, use pm-download.  For example:

drush pm-download somemodule-7.x-1.2

OR

drush pm-download --select somemodule

Make sure that the stable release is newer than the dev release you are running, and then run drush updatedb.


Custom node.tpl.php for specific page I have a custom page template (Drupal 7) created from a basic page and I call it page--node-84.tpl.php. I'd like to manually print/render the 'body' field from this page and so I tried that doing this:

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

But that is not working because I believe I can only print a field when using a node template and not a page. Correct?

Could someone help me with a pre-processing function to be able to print a field in a page template. Or maybe using a custom node template is the way to go?

The available variables differ between the page.tpl.php versus the node.tpl.php (see the top of each of those links for documentation of the default variables).

If the default variables in the templates don't meet your needs, you can customize them using preprocess functions. See the documentation for template_preprocess_page to get an idea of how the variables get added. NodeOne has a screencast on "Providing new template variables" that might also be helpful.


How to remove PAGE SUM in Views Calc? How can I remove the Page SUM row in my Views Calc?

I have upgraded Views Calc module to its latest version.

You can achieve this in two ways

1) Add following style in your CSS

tr.view-subfooter-number{ display: none; }

OR

2) Go to  views-calc-table.tpl.php file under views_calc module directory and find the following code (PAGE SUM row code)

    <?php foreach ($row as $field => $content): ?>
      <td class="view-subfooter views-field views-field-<?php print $fields[$field]; ?>  <?php print $options['info'][$field]['align'] ?>">
        <?php print $content; ?>

    <?php endforeach; ?>

You can comment/remove the above code to hide 'PAGE SUM' row at view output.


How to check if file has changed during (hook) form_validate in a form? I have a custom content type, and the relative form for creating/editing contents. It contains a file field. I need to check, during hook

 function mymodule_myform_form_validate($form, $form_state){...}

if the user changed the file with another (while editing the content). This can be done by checking if the fid has changed, and the fid of the new file can be found, for example, in

 $lang_field = $form['my_field']['#language'];
 $file_fid = $form_state['input']['my_field'][$lang_field][0];

but what about the fid of the old file? Exploring form and form_state array i found several occurrences of the old and the new fid, but i am not sure which i'm supposed to use. I am not even certain that the code above is the correct one for retrieving the fid of the new file... There is a standard (safe) way to retrieve these informations?

There are 2 approach we can look into:

Query the DB using db_query in field table, like if your field machine name is field_image, then its field will be field_data_field_image, and get fid of a particular node, in this case fid will be in field_image_fid

SELECT field_image_fid from field_data_field_image WHERE entity_id=NODE_ID

It will get u previous fid, and u can validate

Load Node from nid, either using node_load or entity_load_single, from here you will get your Old FID, as image has not yet been attached to the node, it has only been saved in file_managed Table.


Change permissions or add roles on the fly Is it possible to add permissions or add a different role to a user on one particular form/page and for those to be removed after the form has been submitted?

It is particularly for when one user creates a new user (using subuser module). They need "Administer Organic groups permissions: Administer all groups and permissions." permissions to set the new users organic group on creation, but they must not be allowed to edit other groups!

Adding permissions on the fly would be hard without writing your own module.

However, maybe there are round-about ways of accomplishing what you need.  Two suggestions:

1) You can add a taxonomy field to your user account that can be set and then use the rules module to automatically add new users to a certain group based on the terms they were tagged with during creation...

2) If you go to: admin/config/group/permissions/node/group, you can see that you can set permissions for members, non-members and admin members of a group, and you can set the 'add user' permission depending on those user group roles.  If you set those to your liking, your workflow can then be a 2-step process: 1) create user account, 2) add user to whatever groups you need.  It's more cumbersome, since it's a 2-step process, but only members or managers of a group will be able to add users to that group.

Final note: creating/editing permissions on the fly like you're thinking may have unintended consequences.  You're saying that users should not be allowed to edit other groups, but if you try granting and revoking permissions based on opening and then submitting a form, you'll actually be giving users the ability to administer all groups until they submit that form!  If they forget and don't submit it or leave it open in their browser for a long time, they'll potentially have that admin-level permission and see all relevant links, blocks and associated admin sections for a long time.  So I suggest you try an approach like the above then attempting to grant 'temporary' permissions.  :-)


Prepopulate CCK ImageField with existing images I have two types of node:

Building, with a CCK imagefield
Apartment, which has a node reference field to a Building node, where one building has many apartments

My goal is to to grab the images from the Building node being referenced. Is there a way to reuse the images uploaded on the Building node and use that on Apartments node?

There are several ways to do this.

I'm supposing that you just want to display the images on the node page, not necessarily filling imagefields on the Apartment node (right ?).

The easiest way is to change the way your reference field is rendered. By default, it should render a title. If you go to Content Management > Content Types > Apartment > Display Fields, you can change the display for the node reference field from a "title" to "teaser" or even "full node". That way you can display the images in your apartment node.

Another way, if you really just want the images and not the rest, is to do some coding. For example, in your theme template.php file, you could add the following code (Drupal 6 - because you mention CCK, I guess you're using D6, right ?):

function YOURTHEME_preprocess_node(&$vars) {
  if ($vars['node']->type == 'apartment') {
    $building_nid = $vars['node']->field_YOUR_REF_FIELD_NAME[0]['nid'];

    $vars['images'] = array();

    // If your imagefield can have multiple values OR only one value BUT the same field is present on
    // another content type
    $result = db_query("SELECT f.* FROM {files}
                          LEFT JOIN {content_field_YOUR_REF_FIELD_NAME} cf ON cf.field_YOUR_REF_FIELD_NAME_fid = f.fid
                            LEFT JOIN {node} n ON n.vid = cf.vid
                        WHERE n.nid = %d", $building_nid);

    // If your imagefield can have only ONE value and is ONLY present on this content type
    $result = db_query("SELECT f.* FROM {files}
                          LEFT JOIN {content_type_building} cb ON cb.field_YOUR_REF_FIELD_NAME_fid = f.fid
                            LEFT JOIN {node} n ON n.vid = cb.vid
                        WHERE n.nid = %d", $building_nid);

    while ($image = db_fetch_array($result)) {
      $vars['images'][] = $image;
    }
  }
}


yes/no rating with node reference target I have a review content type that (node) references a product content type. I'm using fivestar ratings for overall rating and specific ratings. With fivestar I can make the product the "vote target".

One of the ratings is a "yes/no" type rating where I want to show the aggregate on the product node (x% of users rated yes).

I tried to use fivestar with a "1 point" rating where 1=yes, 0=no but the problem is that 0 votes are not saved at all, therefore always resulting in a 100% result.

I could probably use a "2 point" rating and then have a custom display formatter to do the math and translate it to the correct %.

Are there any other solutions? I can't use the rate module because I already use it for "thumbs up/down" ratings.

The Rate module allows one to attach multiple rate widgets to a content type.  Create one rate widget for thumbs up/down and second for yes/no.

Drupal Commons Distribution with Commons Q&A includes both a Like and Points system in this manner...

When you add a second widget, choose to attach it to the same content type(s).


Can a Drupal site design (not just colors, fonts, etc -- template stuff) be replicated over multiple drupal sites? I will apologize in advance for using the L word...but in Lotus Notes there is the concept of a Template file that holds all the design elements of a database...fields, views, forms, etc. -- has a .ntf extension.  That template can then be used as the design model for other notes databases which have .nsf extensions.  For instance if I have a business model where all my customers do the same thing - say bands keeping track of songs and tours.  I have one bandmaster.ntf file and band01.nsf, band02.nsf, band03.nsf, etc.  The data in each .nsf file is specific to each band...but the design of the database is exactly the same.  Each db inherits it's master design from the one .ntf file.

If I have say a contact form and need to add a new field to it ... say "Alternate Email" -- I open the design of the .ntf file and add that field to my contact form.  Then I 'refresh' the design of all my bandxx.nsf databases and they all now have the new field.

Is there any way to do something like that in Drupal?  Is there a way to export maybe a site's design and use that as the design structure for one or more sites??  I'm just getting started with Drupal.  Thank you for any information.

ER

Just to be able to replicate additional fields that you may add to bundles on a "master" site to several other sites, you may use Bundle Copy.

This project provides export/import support for:

Node types
Taxonomy
User
Field API fields
Field groups

It will only export/import the bundle definition, not the content.

For a more elaborate export/import module that not only handles fields, but whole features, take a look at Features.

From the module's description:

  Features provides a UI and API for taking different site building components from modules with exportables and bundling them together in a single feature module. A feature module is like any other Drupal module except that it declares its components (e.g. views, contexts, CCK fields, etc.) in its .info file so that it can be checked, updated, or reverted programmatically.


How to access node field content in a custom module? I have a content type called districts and i have created the following fields

district geojson(polygon values)
harzards (list) - heavy rain, freezing rain, storm
Alert level (list) - extreme, high, low

I am displaying in a view as a leaflet map.
Now i would like to write a custom module that can get the field content of a nodes ie harzards and alert level and then pass them to a javascript file that will print specific colors to the districts in the view depending on the alert_level.

What is the best way to get the field content (harzards and alert_level) in to the custom module and then pass them to the javascript file?
Or is there another way of achieving this.
Thanks

Assuming you mean Drupal 7, just off the top of my head, implement  something like hook_node_view() and attach the Javascript via the #attached element. I am frequently silly in my hook options, so someone may have a better one to suggest.


view to work for particular set of taxonomy terms Case: I have a taxonomy vocabulary namely 'categories'. It consists of some parent terms with their child terms as shown.

 Parent1

 -p1child-1

 -p1child-2

 Parent2

  -p2child-1

  -p2child-2

I want to create a view which work only for a particular set.

Suppose in this case I will create 2 views, each for both parent terms and both will have different set of exposed filters and sort criteria.

So if I visited taxonomy/term/parent1 or taxonomy/term/p1child-1 or  taxonomy/term/p2child-2, it would render that specific view of parent1.

is it possible ?

Please help

You can give Taxonomy Views Integrator module a try.

  The TVI (Taxonomy Views Integrator) module allows selective overriding
  of taxonomy terms and/or vocabulary with the view of your choice.
  Using TVI you can easily create custom views to output all terms in X
  vocabuarly.

  TVI will try not to interfere with views or taxonomy/term page
  displays if no TVI views exist for the current page request.


Field widget depending on another field I have two list fields with select widgets and the second select depends on the first one.

How would you do this? Is there a module already doing this at least in code?

You can use the Conditional fields module.


How to Migrate static html files to Book - Migrate Module I have almost 5000 static html files which belongs to different books.Please give me some direction How to migrate this html files to book.

I am able to migrate html files to Drupal.

But how should i update this Nodes to particular Book during migration.

Thanks a lot for the help!!

A full description of this process would fill a lecture series.  However, the broad approach I would take follows. This approach also has some assumptions that need to be met.

You will need to be able to code
You will need to know, or learn (it's not hard) XPath
The files are in a structure that allows you to recognise where they live in a book (either by links from file to file or path/filename or a combination.

If these conditions are met then import_html is where I'd start.  This will require you have the ability to write a module (that will use this module) and there is a bit of a learning curve, but learning this is well worth it.  If you're already able to import the files it sounds like you're up to speed with the skillset needed.

One of the things that import_html will also allow you to do is update nodes if they're already present too.  Although my experience with this has always been with blowing away the content and rerunning the import to see how any changes went.

I've been involved with a few projects that used this and imported many content types and media from static source dumps.


Is it possible to combine contextual filters with regular filters? I would like to take my standard taxonomy term view and add a "meta" category that would show up in addition to the term selected. The result should be that items in the meta category show up as well as those in the term being viwewed.

I tried adding the meta category as a regular filter or an additional contextual filter, but there's no way to add the "OR" logic needed between the contextual term filter and the specified meta term filter. In spite of using them for many many years, I still don't fully understand the all settings of contextual filters. Perhaps there is a right way to get it to do what I want?

Thanks for any leads or suggestions.

You can add "or" conditions to filters -- either regular or exposed -- using Views in Drupal 7 or 8 (in Drupal 6 you need to use the Views Or module).

Add the filters you want -- in your example, a "Has taxonomy term" filter for "meta" and a "Has taxonomy term" exposed filter. Then click the arrow next to the "Add" link to expand the options and select "And/Or, Rearrange".

From there you can add a new group and drag both the "Has taxonomy term" filters into that group and set the operator to "or". (You can also set the operator between groups to "or" for more complicated scenarios.)

To add OR clauses to contextual filters, tick the "Allow multiple values" option and use the "+" or "," characters in the URL to indicate an OR or AND of values.

That should get you what you want.


Adding a css in preprocess view not woking I'm trying to add a css to a view, through the preprocess view as below

function mytheme_preprocess_views_view(&$vars) {
 $view = &$vars['view'];
if ($view->name == 'gallery_view') {
drupal_add_js(drupal_get_path('theme', 'mytheme') . '/assets/js/responsive-image-gallery/gallery.js');
drupal_add_css(drupal_get_path('theme', 'mytheme') .'/assets/css/responsive-image-gallery/style.css');
 }
}

The Following code above is inserting the js file but not the css. Is there a reason why? Or other way to insert css file in certain view?

I have tried the following and its being inserted:

drupal_add_js(drupal_get_path('theme', 'zenon') .'/assets/css/responsive-image-gallery/style.css');

So is there something missing in the drupal_add_css function or it doesnt have read access on the server, is that possible?

the path is wrong!

drupal_get_path('theme', 'mytheme') already provides the path to your theme folder.  no need for '../../../...'

you should probably use

drupal_get_path('theme', 'zenon') . '/css/image-gallery/css/style.css'.


Stop Drupal from encoding '&' as '&' in YouTube URLs I embedded a YouTube video inside a "News" node. The input format in use is Full HTML.

When node is saved, the ampersand symbol in &wmode=Opaque is substituted for &amp;wmode=Opaque.

Is it possible to prevent the ampersand in the URLs of embedded YouTube videos is encoded as HTML entity?

Try disabling the HTML corrector on the text format. Also, though, I don't think URL-encoding amphersands in URLs actually breaks them. & should work as a query string parameter separator as well. If not, though, see my suggestion :)


Convert pot file to array So, what I need to do is to convert the contents of a .pot file to an array.

I know there is _locale_import_read_po(), but when I tried using it with the following code, I got an error.

$translations = _locale_import_read_po('db-store', 'translations.pot');

The translations.pot file is located in the same directory containing the file with the code I wrote.

The error I get with dpm($translations) is the following one.

  Error message

  The translation import failed, because the file could not be read.

This is the code from the _locale_import_read_po() function, that outputs that error.

// The file will get closed by PHP on returning from this function.
$fd = fopen($file->uri, 'rb');
if (!$fd) {
  _locale_import_message('The translation import failed, because the file %filename could not be read.', $file);
  return FALSE;
}

As far as I know the 'rb' file open mode is to open non-text files.

Why do I get that error message?

The second parameter of _locale_import_read_po() is a Drupal file object, which in Drupal 7 is simply a stdClass object.

The quicker way to use that function and pass a file object as it expects is using code similar to the following one.

 $po_files = file_scan_directory('./', '^translation\.po$', array('recurse' => FALSE));
 if (count($po_files)) {
   require_once DRUPAL_ROOT . '/includes/locale.inc';
   $po_file = reset($po_files);
   _locale_import_read_po('db-store', $po_file);
 }

Notice that the second argument of file_scan_directory() is a preg_match() regular expression, not a filename.

Using that code, you don't need to save the file using the file API, which is essentially useless, since there is already a file in the file system.
file_save() stores the file in the database; for a file that is used for a single operation like that, it's not necessary.

I used st() as example for writing the code I shown in this answer.

You could also make the code I show more generic to accept a regular expression and a directory name, and use it to load more files.

function mymodule_import_translations($directory, $pattern) {
  $po_files = file_scan_directory($directory, $pattern, array('recurse' => FALSE));
  if (count($po_files)) {
    require_once DRUPAL_ROOT . '/includes/locale.inc';
    foreach ($po_files as $po_file) {
      _locale_import_read_po('db-store', $po_file);
    }
  }
}


How to programmatically set the front page? I want to set the Drupal front page programmatically at run time.
How can I do this? Is this possible?

You can use variable_set() for that.

variable_set('site_frontpage', $value);


How do I reset my search result link? I created a custom search plugin for a custom entity. I would like to change the link that is presented to the user on the list of results. I had originally set it to the canonical page using $entity->url(‘canonical’), but now I want to use Url::fromRoute(), to a custom controller.

I made the appropriate changes to the plugin class, cleared cache and ran cron a few times and the search results still point to the admin canonical page. Is there something else I need to do to push the change through?

I waited some more, cleared cache and ran cron again and it worked.


Is is possible to call a function inside a .inc file of a module via drush eval? I have a module with additional (.inc) files containing functions I need to run via Drush. I know it is possible to run drush eval, but when I try to do it for those functions I get the following error:

  PHP Fatal error:  Call to undefined function my_module_my_function() in /usr/share/php/drush/commands/core/core.drush.inc(1037) : eval()'d code on line 1

This command works (the function is in the .module file).

drush eval 'my_module_cron();'

This command does not work (the function is in the .inc file).

drush eval 'my_module_my_function();'

Is there any workaround, besides moving the function in the module?

You could add module_load_include() to your eval code like you would anywhere else.

Like this:

drush eval "module_load_include('inc', 'my_module', 'INCLUDE_FILE_NAME_WITHOUT_EXTENSION'); my_module_my_function();"


Taxonomy Terms jump list I have created a jump list with certain taxonomy terms, but it seems impossible to get the url right.

I have a URL pattern setup for these terms: /dealers/towns/[taxonomy_term]

But in the jump list I can't find a way to get this url right, there's no way to select the actual url, how can I do this?

You have to add a new field on the view, which is custom link.
edit this custom link and rewrite the result to be something like

term

after that click on your jump list settings and chose the newly created field


How to translate the search block title? In Drupal 8.1.1 I am able to translate customs block and basic blocks (block type).

The search block seems not to be translatable. But I need to translate the title of the standard search block. I can not find a way to do it. Words like "Search" are translated in all languages but the search block title gets not translated.

This is configuration translation. You have to enable the module with this name and then go to block layout, configure a block and click on the tab "Translate block":

/admin/structure/block/manage/mytheme_search/translate


Exclude nodes present in panel from view pane I have a panel page where a user selects nodes (using IPE) to be displayed, the page also contains a view pane, which must not contain those same nodes.

How do I get the view to exclude the nodes present in the panel?

We had the same issue on a page with a lots of news and user customizable Top News - we used the module views_exclude_previous module and it worked fine for this case.


images missing - wrong base url My website occasionally loses images due to the image url being set to http://default/sites/files/XXXX.jpg. The "default" baseurl is the issue and as i understand drupal 8 has no way of setting this manually.

As this seems to happen sporadically i am assuming it is related to a cron job running under baseurl of "default" and then the page being saved to the cache.

Anyone have any ideas how to diagnose or possible causes? i was thinking something like SimpleSiteMap could be affecting this.

thanks

UPDATE
After some testing it seems likely that its a cron job accessing the pages and the image urls being cached incorrectly.

The cron jobs run under base url of 'http://default' so the chain of events seems to be:
cron starts
clears caches
a cron job attempts to render the page causing the img urls to be cache incorrecly

If i then clear the cache again and navigate to the pages the urls are re-written and cached correctly now.

Have you tried setting

$settings['file_public_base_url'] = 'http://sitename.local/sites/default/files';

In sites/default/settings.php?

I do this for all of my sites both in dev and production and haven't had any issues.

I realise that you may have solved the issue, but just so you know you can set the base url for your files through that setting :)


Is there a plain-text equivalent to the 'html' suffix for [webform_submission:values]? I've written a Drupal 8 webform handler plugin that sends webform submission data to another server via REST. I'm trying to send all the populated fields of the form to the third-party server so that it can be viewed in the "message" field of their UI. I've tried using the [webform_submission:values] token with the 'html' suffix, but it comes out as a unrendered block of html code. Is there a token suffix that will format the webform values as plain text with new line characters after each value?
Here's an example of the JSON I'm sending to the 3rd party server:
{
   "u_user": "[webform_submission:values:user:raw]",
   "u_service": "Foo Service",
   "assignment_group": "Bar Assignment Group",
   "u_service_provider": "Baz",
   "short_description": "[webform_submission:values:subject:raw]",
   "comments": "[webform_submission:values:html]"
}

I need to implement this across nine different forms, some of which have conditional logic, so hard-coding every field into every handler is impractical.
Also is there a resource on the web that lists all the suffixes and prefixes for tokens?

Thanks @leymanx for the suggestion to make my own custom token. That's what I did. I created a hook_tokens function that borrowed code from webform.tokens.inc hook_tokens implementation. I deleted anything that didn't relate to the one token I was after, then created a _module_name_token_get_submission_values function that also borrowed heavily from the corresponding function in the webform module. Finally, I wrote a function that performed a series of preg_replace substitutions on the html code that was giving the destination server problems.
Along the way, I learned a lot about custom tokens and was able to refactor my plugin to eliminate the need for a completely separate plugin through the use of a custom token. :-)


After Upgrading from D7 to D8, D8 does not look like D7 at all I have successfully performed a D7 -> D8 migration of my company site. Everything seemed to go well, but when I'm accessing the Drupal 8 site, the entire design is pretty much gone.

How can I get the old design back again for Drupal 8?

Drupal 8 is very different from Drupal 7, same goes with previous major versions of Drupal.

This means that themes and modules can only work for a single Drupal major version (fx 6, 7 or 8).

When you migrate a site from D7 to D8 you have to re-implement the theme. In Drupal 8 we now use Twig as the template language so you pretty much have to start from scratch (unlike 5 -> 6 -> 7 where the theme differences wasn't that big and a lot could be reused).


"Add another item" using #ajax in hook_field_widget_form I'm trying to create a custom widget for my module which will contain a textfield to hold a question(textfield), Question style (select box), potential answers (typed into textarea).

I'd then like an "add another item" button so the client can add as many questions as they like.

I've got a basic ajax widget working but i'm not sure if I've constructed it correctly because when I want to validate the data in hook_field_validate I don't seem to be able to access each question seperately.

I thought i'd be able to validate each question before the next is added by ajax but this doesn't seem to be working.

Asssuming this code (below) is correct, can you please advise how I can validate each time the "add another item" is clicked.

My hook_field_widget_form looks like this:

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

  $element['question_wrapper'] = array(
    '#type' => 'fieldset',
    '#title' => t('Questions'),
    // Set up the wrapper so that AJAX will be able to replace the fieldset.
    '#prefix' => '
',
    '#suffix' => '
',
  );

  if (empty($form_state['num_names'])) {
    $form_state['num_names'] = 1;
  }
  for ($i = 0; $i < $form_state['num_names']; $i++) {

    //other form elements
    $element['question_wrapper'][$i]['question'] = array(
      '#type' => 'textfield',
      '#title' => t('Question number '. $form_state['num_names']),

    );

  }

  $element['question_wrapper']['add_question'] = array(
    '#type' => 'submit',
    '#value' => t('Add another question'),
    '#submit' => array('ajax_example_add_more_add_one'),
    // See the examples in ajax_example.module for more details on the
    // properties of #ajax.
    '#ajax' => array(
      'callback' => 'ajax_example_add_more_callback',
      'wrapper' => 'names-fieldset-wrapper',
    ),
  );
  if ($form_state['num_names'] > 1) {
    $element['question_wrapper']['remove_name'] = array(
      '#type' => 'submit',
      '#value' => t('Remove one'),
      '#submit' => array('ajax_example_add_more_remove_one'),
      '#ajax' => array(
        'callback' => 'ajax_example_add_more_callback',
        'wrapper' => 'names-fieldset-wrapper',
      ),
    );
  }

return $element;
}

And my ajax callback

function ajax_example_add_more_callback($form, $form_state) {
  $form_state['num_names']++;
  return $form['field_question'];
}

Looks like you're just missing a #tree property:

  Used to allow collections of form elements. Normally applied to the "parent" element, as the #tree property cascades to sub-elements. Use where you previously used ][ in form_ calls. For more information, see #tree and #parents in the handbook.

e.g.

$element['question_wrapper'] = array(
  '#type' => 'fieldset',
  '#title' => t('Questions'),
  // Set up the wrapper so that AJAX will be able to replace the fieldset.
  '#prefix' => '
',
  '#suffix' => '
',
  '#tree' => TRUE,
);

And then in the validate handler:

foreach ($form_state['values']['question_wrapper'] as $key => $value) {
  if (is_numeric($key) && something_is_wrong_with($value['question'])) {
    form_set_error("question_wrapper][$key][question", 'Error');
  }
}


Taxonomy term doesn't show up in admin/structure/taxonomy/manage/tags/overview I migrated a Drupal 6 site to Drupal 8.  Current running version is:  8.5.3
I created 4 terms in the Tag taxonomy and referenced in the content type Article.

The terms, however, do not show up in the overview page.

They are in the database.

They are also visible when creating nodes.

How do I fix this?

It sounds like they are missing parent value of 0 in the term hierarchy table. That will do it. That table just needs the tid and parent value of '0'. Try it by adding one of the tag term tids to that table, clear the cache and reload that page. This is easy to miss in migrations.


image style not applied porgrammatically I create below function to create image style programmatically

function imh_get_image_from_uri($image_uri, $style) {
    $derivative_uri = image_style_path($style, $image_uri);
    $success = file_exists($derivative_uri) || image_style_create_derivative($style, $image_uri, $derivative_uri);
    $new_image_url = file_create_url($derivative_uri);
    return theme_image(array('path' => $new_image_url));
}

and call in my tpl with

 imh_get_image_from_uri($node->field_cast_image['und'][0]['uri'],'215x317');

and  a example of image created path is

http://mydomain.com/sites/default/files/styles/215x317/public/Hugh%20Jackman-2.jpg

I check the images style , as expamle this image image style  set  to scale 215 * 317,every thing seems work good but when I see image directly I see the image in this path not resized ( I call my function with another image style but also they are not resize or scale or ....) ,
The images that use build-in drupal image style work correctly but when I use top function to load image style programmatically the image style action (resize, scale ,... ) not applied, the image create on that path but noting applied on it.

where is problem?

update
Also I try

$build = array(
  '#theme' => 'image_style',
  '#path' => $image_uri,
  '#style_name' => $style,
    );
return render($build);

output
<img src="http://mydomain.com/sites/default/files/styles/215x317/public/Hugh%20Jackman-2.jpg?itok=PcP0uFjT" width="215" height="317">

but the problem exists yet, the file in the image path exists but not resized.
it seems change it by style ( not resized main image)

The solution is

  return  theme('image_style',array('style_name' => $style, 'path' => $image_uri));

but this not work first because the image style for that file created before , first I should remove it then try this  ;)


Bulk assign paths to nodes I have a bespoke content type with a lot of nodes, but alias urls have not been assigned to them. I need to bulk assign them consistent alias. I know on Drupal 7 this is possible to do using pathauto, however I have installed that for Drupal 8 and the batch assignment doesn't seem to be working yet. Is there another efficient way this can be done?

1) Make sure you have set up a working alias for your content type at /admin/config/search/path/patterns

2) Go to /admin/config/search/path/update_bulk

3) check "Content"

4) Submit

I have just tested this on my local dev environment by going in the db and deleting the alias to one node:

delete from url_alias where source = '/node/2940'

and running the bulk operation generated an alias for all unaliased nodes (which just happened to be the only one I deleted).

So if the bulk operation isn't working for you, it may be that you don't have a pattern set up for your content type (node bundle).

Check at /admin/config/search/path/patterns and make sure you have a working pattern set up for your content type.


hook_form_alter() "og_group_ref" editable field's #options? I've hit a problem using one og_group_ref field over multiple content types. I need to have the field editable for one content type in a view and provide the select list options from another view.

At the moment, I have the editable field in the view showing all nodes for all content types as options which isn't acceptable. A new field isn't an option.

Editable Fields
Content type: course_students
Field: og_group_ref
View: resources > panel_pane_2
View providing nodes: abc > def

I've been away from Drupal for a couple of months and am completely lost so any help with a custom module to give this functionality would be greatly appreciated.

The below image shows the current problem where two content types are in the drop down list. This list instead needs to have nodes provided by a view.

It's not a form alter but it's an easy solution using rules.. I added a second entity reference field that only listed the nodes I wanted. Then I used two rules to make sure the two fields always match, whichever is updated.

This is one of the rules for when og_group_ref changes. The other one is the same except for when the second entity reference field changes.

Why am I posting this as a solution when it's different to the question? Because it's very quick, most people use rules and it's applicable in many situations.


How can I make the summary field required? Is there a way to make the summary field required by default in the node form?

It might be easier to create a new field for the summary and just manage it that way, you will then have to remove the summary option from the body field. Otherwise I think you will have to write some code and use hook_form_alter.


Views exposed filter between label AND replace with - how do I change exposed filter BETWEEN label? There is default "AND"-text and I need to change it to  "-"

You have to use a hook_form_alter() to edit the form programmatically. This will go in a custom module.

Here's some boilerplate code:

function test_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id !== 'views_exposed_form') {
    return;
  }

  if ($form_state['view']->name !== '<your_view_name>') {
    return;
  }

  $form['field_<your_field_name>']['max']['#title'] = '-';
}

Replace the view and field names with your particular ones. Hope it works for you.


Understanding page-title.html.twig and/vs field--node--title.html.twig This question is based on the desire to have only one wrapping tag around the title value. (I am utilizing the block system to render the page/node title)

Both of the templates utilize some sort of attribute array on the wrapping element, so I am not sure it is safe to remove either.

I am hoping to better understand why there are two levels to this elements theming, and maybe more importantly, would it be detrimental to remove the attributes from the field--node--title.html.twig?

page-title.html.twig:

{{ title_prefix }}
{% if title %}
  <h1{{ title_attributes }}>{{ title }}</h1>
{% endif %}
{{ title_suffix }}

field--node--title.html.twig:

<span{{ attributes }}>
  {%- for item in items -%}
    {{ item.content }}
  {%- endfor -%}
</span>

Every page has a title, but not every page has title field (views pages, settings forms,...). Only fieldable entities (like node, user, taxonomy term,...) can use a field--ENTITYTYPE--FIELDNAME.html.twig template.
Very often the title field of an entity is NOT the title of a page (imagine a views page showing 10 nodes), that's why the h1 is in page-title.html.twig
Modules or field formatters might use those attributes. Removing it is no showstopper, but it might have side effects depending on the modules you use. (e.g. core's QuickEdit module will not work without {{ attributes }}).


Theming a node reference field in a template file I have two content types:

Course
Subject

The Course nodes have a field reference field which references a Subject node.

In the Course node display, I want to have access to the variables from the corresponding Subject node. I've set the field to render as 'rendered node', but I need to rearrange the fields from both nodes to construct a tabbed interface out of all of the fields available.

What's the best way to proceed?

Hi you can use theme_render_template() function like below.

$subject_node_object = node_load('node/' . $node_id_from_ref_filed);// Pass your node ref here.
// Use below code in your course node template.
print theme_render_template(drupal_get_path('theme', 'YOUR_THEME_NAME') . 'PATH_TO_TEMPLATE/subject-node.tpl.php', $subject_node_object);

You need to create a template for you subject content type fields.


how to call/using geofield in a custom module I`m trying to use the geofield module, and load it with google maps widget in one my custom forms.

Yet i can't find any way to use the form api to display this field.

$form['geofield'] = array(
'#title' => 'geofield',
'#type' => 'geofield',
);

Any suggestion is welcome, i don't mind reading some docs.

Geofield module is rather complex module which adds a lat/long fieldset and so many other stuff such as adding new fields, validation, etc.
Anyway, you can create a latitude and longitude input field using the #type => 'geofield_latlon'.
$form['geofield'] = array(
  '#title' => 'geofield',
  '#type' => 'geofield_latlon',
);

Note that this will return a generic longitude latitude form. NOT a Google Maps choose-location field.
See geofield.elements.inc for more information on how this element is validated and themed.
Update: I forgot to mention that the above element is available in the 7.x-2.x branch.


Make an exposed node reference filter to show only nodes created by current user I am having a little problem I cannot figure out how to solve.

I have a 3 content types:

campaign
post
publication

Post contains a node reference to campaign. Publication contains a node reference to post. I am making a view that lists all publication and I would like to give user an option to filter them by campaign.

However when I am making an exposed filter that allows a user to select a campaign to filter and it works just fine, but I am not able to figure out how to limit exposed filter options to campaign nodes created only by current user?

I know how to do this through code, but I'd like to figure out if this is possible to do via UI.

Either it's a bug by the references module or works as designed.

You can accomplish your goal using the Entity Reference and Views Reference Filter modules.

In Views, add relationship of Referenced Entity.

Click the +Add button and add an entity reference view.

Add relationship of Referenced Entity (this is probably already done as it clones your current view) and make field title have a relationship. Remove all other unnecessary fields, if you have them, and just leave the title (make sure you select for This entity reference (override), so it doesn't affect your page view).

In settings, checkmark ☑ content title.

Now go back to your page view and add your entity reference field as a filter.


What is the correct way to get the link url? We have a Basic Page content type with a link field (field_link). When we call the mymodule_preprocess_node(&$variables) hook in a custom module we use ksm($node->get('field_link')->first()) and it returns a Drupal\link\Plugin\Field\FieldType\LinkItem. We need to extract the URL from this fields and have found two ways to do it (see below). What is the correct way to get the URL from the field?

The reason for extracting the URL is that we need to wrap a set of custom fields with the link so we can have a HTML structure similar to below.

HTML structure:

   Some title field

mymodule.module

...
function mymodule_preprocess_node(&$variables) {
  $node = $variables['node'];
  $node_field_link = $node->get('field_link')->first();

  // Do we use this?
  $node_field_link_url = $node_field_link->getUrl()->getUri();

  // Or do we use?
  $node_field_link_url = $node_field_link->get('uri')->getValue();
}
...

I find the best way to get a url especially when I'm using it in cases where I need to wrap custom html around it is to get the url object and then use the toString Method.

$node_field_link_url = $node_field_link->getUrl()->toString();

The getUrl() method of the LinkItem object returns a Url object. See https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Url.php/class/Url/8.2.x
And Url objects have a toString method that returns the string representation of that url.


Views Sort Criteria: Sort by Taxonomy terms I have a view that lists team members of a country that are referenced by an Entity reference field.

Now these team members can have different functions and job titles. I assign them through a taxonomy vocabular called "Functions" with the following terms:
- Office Head
- Partner
- Client Partner
- Consultant
- etc.

Usually team members only have one function but the Office Head always has two (Office Head and e.g. Partner).

When I now choose the above taxonomy field as a sort criteria, the office head always appears twice since it has two taxonomy terms assigned. But I only want the office head to show up only once.

Any suggestions how to do this would be greatly appreciated.

Check out Views Distinct module. Once you enable this module, for every field there will be a setting Views Distinct Settings where you can choose to filter repeats.


Combine photos from parent node and referenced nodes into a single list (for slideshow) Drupal 8
I have two content types. Department and Employee.
Department has an entity reference field that references Employee(s).
Department and Employee both have a field called “field_photos”. (Same field name in both).
In views (or via Twig in a node template), I’d like to display all “field photos” from both the Department Node AND Employee(s) nodes referenced by that Department… into a single list output.
So the end output will be a slideshow for each department showing all “field_photos” from that Department and referenced Employees.

As always there is more than one way of solving problems in Drupal. There is a way you could build a DB query with only Views that would combine the ER reference through Relationships.
But there is a way to solve this that is (arguably) "more Drupal", and that with the help of Content View Modes. They are not to be confused with Views module, we will actually combine the two separate features, View modes and Views (module), to build your solution.
Use View Modes on ER Fields in Views
View modes are different combinations of entity fields visibility and output settings. With View modes you can create many different "views" of the same content. For example, "Full" and "Teaser" are ubiquitous View Modes.
In your case you want a special View Mode of the Employee CT that shows their photos. Create a new View mode on the Structure > Display modes > View modes (you can also get to this page through each CT "Manage display" page).
Enable that mode, visit it (it becomes a sub-tab) and disable all Fields you don't need, configure the photos field to your liking.
In Views create a list of all Departments, add the Photos and Employees ER Fields.
When configuring the Employees field set the Formatter to the View mode you had created especially for this. ER fields usually only show ID of the referenced entities, exceptionally their titles, but with View modes you can pull any info from the referenced item.
This is how you get a list of all Departments with all the Department and referenced Employees photos listed.
Slideshow
The slideshow part of the Q depends on how you plan to build that in. You'll probably use some external library with a module that implements it into Views.
Depending on how a particular library and module work you will be able to apply it to each Views row, or to each Field.
To combine photos from both fields use the Exclude from display on the top field and Rewrite results on the bottom field. Use Replacement patterns to construct the HTML output that your slideshow library can use. In some cases you'll need to override with twig templates.


Static field of taxonomy term I have a content type with a static field that I want to reference a specific TAX term.  When a new node is added, I want the term to default to a specific reference, and I don't want the author to change it.  I was thinking that a STATIC FIELD could work, but not sure how to hard code the term reference.

put another way, I want to Hard code the TAXONOMY term into a field of another node type.

any other ideas on how this would be done or alternatives?

One alternative could be adding a regular term reference field that has the particular taxonomy term you want referenced set as the default value. Then in a hook_form_FORM_ID_alter call the node edit form for the specific content type and set the #access value to FALSE for that field.


Programmatically get a form in Drupal 8 The documentation states:

  The argument passed to the getForm() method is the name of the class
  that defines your form and is an implementation of
  \Drupal\Core\Form\FormBuilderInterface.

How do I find out the name of the class that defines the website feedback form provided by the core contact module (the form id is: feedback_contact_message_form).

When I dpm() the form I can see that there is a class defined:

$input array(30)
  →'#attributes' => array(1)
    →'class' => array(3)
      string(29) "feedback-contact-message-form"
      string(20) "contact-message-form"
      string(12) "contact-form"

I tried various forms of this as the parameter to pass to:

\Drupal::formBuilder()->getForm();

but no luck. Thanks

This renders within a block plugin:

class myModule extends BlockBase {
  public function build() {

    $default_form = \Drupal::config('contact.settings')->get('default_form');
    $entity = \Drupal::entityManager()->getStorage('contact_form')->load($default_form);

    $message = \Drupal::entityManager()
      ->getStorage('contact_message')
      ->create(array(
        'contact_form' => $entity->id(),
      ));

    $form = \Drupal::service('entity.form_builder')->getForm($message);

    return $form;
  }
}


Drush download, what port does it use? I work on a Drupal 7 intranet site for a large company. The firewall on the server it is housed on currently does not allow any access to the Internet. I've been upgrading Drupal core and modules by downloading them to my pc and accessing the server with remote desktop client.
What are the most minimal holes that we'd have to punch in the firewall for Drush to be able to download updates from drupal.org.
Would just opening up port 22 do the trick?

For Drush 8.x (the last version compatible with D7), the drush command, drush pm-download, can either use HTTP (wget) or SSH (git@git.drupalcode.org) depending on your --package-handler argument. It defaults to HTTP.


How do I resolve missing content type references from uninstalled modules? In my previous setup of my site, I installed a bunch of modules and had them uninstalled. But now I have many orphaned or missing content types that still resides in the database somewhere. Below is what is displayed on the Field list page where its trying to reference these non-existent content types. Is there a place where I can go to clean this up? Which tables would I be looking into? And if I were to delete these entries where else would I have to delete it?

this probably is happening because you've deleted the module from sites/all/modules before uninstalling it correctly via drupal / or the module you have installed did not provided the code to uninstall it from database. Based in this, you can try to install the module again and then, disable it first, then uninstall it, and then delete it from the sites/all/modules. And don't forget to clear the cache

If the problem persist, i think you can always delet the tables individually from phpmyadmin.
Let me know if the problem persists. So, then i can analyze it with you


The link of "Pdf version" on node page does not appear in chrome I have installed the the print module on my drupal 7 site. I configured the the print module pdf settings.

Now the link "pdf version" is displaying with each node on the content area at bottom. When I click on the link, it save the node in pdf format.

But this only works in firefox. In chrome the "pdf version" link in not displaying.

What is the problem?

It was the permission issue. I granted the permission to the authenticated and anonymous users and it works for me.


Override specific configuration keys in settings.local.php I'm trying to learn the Drupal 8 configuration override system based on the documentation here:
https://www.drupal.org/docs/drupal-apis/configuration-api/configuration-override-system
As a simple test, I have disabled the Shield module and exported config. Here's a diff:
diff --git a/config/sync/shield.settings.yml b/config/sync/shield.settings.yml
index 3f7482f18..d9f019ca4 100644
--- a/config/sync/shield.settings.yml
+++ b/config/sync/shield.settings.yml
@@ -1,4 +1,4 @@
-shield_enable: true
+shield_enable: false
 credential_provider: shield
 credentials:
   shield:

Now, in my settings.local.php I have attempted to override this config key:
/**
 * Disable Shield (HTTP Basic Authentication).
 */
$config['shield']['shield_enable'] = FALSE;

This approach does not seem to work.
Do I need to do anything else to override the configuration?
NOTE: This is a contrived example. I could use configuration splits to disable HTTP basic auth in the production environment, even if it's enabled in the active database configuration. In fact, I am hoping this approach will allow me to use environment variables to provide environment-specific values for authentication tokens, API keys and other secrets that may change in sandbox and production environments, but details are irrelevant to the question.

The key for $config is the config name, not the module. This should work:
$config['shield.settings']['shield_enable'] = FALSE;


Adding the is_front variable to a Paragraphs template Is the is_front variable not available in a Paragraphs template override?

I'm trying to do the following:

          {% if is_front and content.field_section_title %}

{{ content.field_section_title }}

          {% elseif content.field_section_title %}

{{ content.field_section_title }}

          {% endif %}

          {{ content.field_text }}

          {{ content.field_section_image }}

However, when I set a node that uses this paragraph type as the homepage, it doesn't take the is_front condition and just uses the h4 tag instead of the h2 which is what I would like for it to do.

Is there a way for my paragraphs templates to use the is_front condition? Or is there a different way to go about this?

You should be able to add this with a preprocess function in mytheme.theme of your theme.

/**
 * Implements hook_preprocess_paragraph().
 * @param $variables
 */
function mytheme_preprocess_paragraph(&$variables) {
  $variables['is_front'] = Drupal::service('path.matcher')->isFrontPage();

  // Ensure the cache varies correctly.
  // Drupal 8.2.x or lower
  $variables['#cache']['contexts'][] = 'url.path';

  // Ensure the cache varies correctly.
  // Drupal 8.3.x+
  $variables['#cache']['contexts'][] = 'url.path.is_front';
}

This should add is_front as a variable to any paragraph twig template. Clear cache after adding this code.

Per 4k4's comment, if this is Drupal 8.3 you will also need to add a cache context.


Get Organic Group roles of the current user It seems a few different versions of this question exist so apologies if it seems I am repeating but I dont think I am. I am trying to use the api to get the og role(s) of the current user, not just which groups the user belongs to. I hope to able to create an array that looks like this for the current user:

Array
(
['Group 1'] => Array
    (
        [0] => 'OG Admin'
        [1] => 'OG Member'
    )

['Group 2'] => Array
    (
        [0] => 'OG Moderator'
        [1] => 'OG Member'
    )

['Group 3'] => Array
    (
        [0] => 'OG Member'
    )

)

Here is the data structure I ended up with:

Array
(
// Index 0 will be site-wide rid and roles
[gid] => Array
    (
        [rid] => 'OG Role Label'
    )
)

Here is the code I hacked together to get it to work. I placed this code into a custom module but I can't seem to get the function to get called from the desired location. I have a file ../sites/all/themes/THEME/templates/includes/toolbar.php. The function call is inside this file but for some reason is never executed. Any ideas on how to make the function call correctly??

function _MYMODULE_get_user_roles($scope=ALL) {
    global $user;
    $user_roles[]=$user->roles;

    if ($scope==ALL || $scope == SITE_ONLY)
    {
        $user_roles['SITE'] = $user->roles;
        switch (true) {
            case in_array ( 'System Administrator', array_values ( $user->roles ) ) :
                //drupal_set_message ( '
Load System Administrator Toolbar
' );
                break;
            case in_array ( 'Site Account Admin', array_values ( $user->roles ) ) :
                //drupal_set_message ( '
Load Site Account Administrator Toolbar
' );
                break;
            case in_array ( 'Site Content Admin', array_values ( $user->roles ) ) :
                //drupal_set_message ( '
Load Site Content Administrator Toolbar
' );
                break;
            case in_array ( 'authenticated user', array_values ( $user->roles ) ) :
                //drupal_set_message ( '
Load Member Toolbar
' );
                break;
            default :
                //drupal_set_message ( '
No Member roles found: Do Not load a toolbar
' );
                break;
        }
    }
    if ($scope==ALL || $scope == OG_ONLY)
    {
        $groups=og_get_groups_by_user();
        foreach ($groups['node'] as $group )
        {
            $roles = MYLEGACYMODULE_get_user_roles($group);
            $group_string = node_load($group)->title;
            $group_string .= ' (gid: ' . $group . ')';
            $group_string .= ' as ';
            foreach ($roles as $role )
            {
                switch ($role)
                {
                    case 7:
                        $role_string = '"Group Content Manager"';
                        $role_string .= ' (rid: ' . $role . ')';
                        $user_roles[$group]=array(
                                $role=>'Group Content Manager'
                        );
                        break;
                    case 8:
                        $role_string = '"Group Account Manager"';
                        $role_string .= ' (rid: ' . $role . ')';
                        $user_roles[$group]=array(
                                $role=>'Group Account Manager'
                        );
                        break;
                    default:
                        if (empty($role))
                        {
                            /*  Note: Note that in PHP the switch statement is considered a looping structure for the purposes of continue.
                             *  continue accepts an optional numeric argument which tells it how many levels of enclosing loops it should skip to the end of.
                            *   The default value is 1, thus skipping to the end of the current loop.
                            *   --http://www.php.net/manual/en/control-structures.continue.php
                            */
                            continue 2;
                        }
                        $role_string = '"Unknown Group Role"';
                        $role_string .= ' (rid: ' . $role . ')';
                        $user_roles[$group]=array($role=>'Unknown Group Role');
                        break;
                }

            }
        }

    }
    return $user_roles;
}


How do I change the default value of a field with AJAX? Related to my previous question: Form fields created via Ajax are missing element attributes

I have a date field and a series of text and number fields which need their default values to change based on the value of the date field. I've updated my code so it functions this way:

public function buildForm(array $form, FormStateInterface $form_state) {
    $form['date'] = array(
        '#type' => 'date',
        '#ajax' => [
            'callback' => '::dateCallback',
            'wrapper' => 'wrapper',
        ],
        '#default_value' => date("Y-m-d")
    );
    $form['wrapper'] = [
        '#type' => 'container',
        '#attributes' => ['id' => 'wrapper'],
    ];

    //insert logic to determine value of a variable called $field1
    $form['wrapper']['options'] = array(
        '#type' => 'fieldset',
        '#attributes' => array('class' => array('options'))
    );
    $form['wrapper']['options']['field1'] = array(
        '#type' => 'textfield',
        '#title' => "Field 1",
        '#value' => $field1
    );
    $form['wrapper']['table'] = array(
        '#type' => 'table',
        '#title' => t('Table'),
        '#header' => array("H1", "H2", "H3"),
        '#attributes' => array('class' => array('custom-table'))
    );
    //insert logic to generate table rows
    return $form;
}

/**
 * Implements callback for Ajax event on date selection.
 *
 * @param array $form
 *   From render array.
 * @param \Drupal\Core\Form\FormStateInterface $form_state
 *   Current state of form.
 *
 * @return array
 *   Date selection section of the form.
 */
public function dateCallback(array &$form, FormStateInterface $form_state) {
    return $form['wrapper'];
}

There are 2 problems I am having with this:

1) Implementing it in this way, such that the #value property is changed when the date field is changed, technically works, however if the user then chooses to modify any of the textfield values, that is not reflected in the $form_state object and is overridden by whatever #value was last set to in buildForm().

2) I have also tried using #default_value instead, but the value in the field will not update if it already has something in it (which it usually does from the first time #default_value is set in buildForm()). I have seen some threads like this one suggesting to unset the value in $form_state before setting #default_value again, however all such suggestions are for Drupal 7 where $form_state is a completely different data structure.

Is there a known way to do what I am trying to accomplish?

Update: I tried method 2 again by adding $form_state->unsetValue('field1'); before declaring $form['wrapper']['options']['field1'], but this did not change the behaviour.

Method 1 setting #value does indeed make it impossible for the user to input data.

So the method 2 setting #default_value is I think still the best approach. As the old trick from D7, unsetting the value in $form_state, doesn't work anymore, you can try this one:

Create the field in a subkey, which is incremented for each request. Set the property #tree on the first level of the field, so you get back the field value as array [$key => $value]:

$form['wrapper']['options']['field1']['#tree'] = TRUE;

if ($form_state->hasValue('field1')) {
  $key = key($form_state->getValue('field1'));
  $value_field1 = current($form_state->getValue('field1'));
  $key++;
}
else {
  $key = '0';
  $value_field1 = NULL;
}

// insert logic to determine new field value
// but check, if there is user input in $value_field1, that you don't want to overwrite

$form['wrapper']['options']['field1'][$key] = [
  '#type' => 'textfield',
  '#title' => 'Text 1',
  '#default_value' => $value_field1,
];


How to pre-populate fields in checkout? We have a product that is being sold with Drupal Commerce (using Drupal 7). This specific product is going to be advertised in more ways than just the Drupal site (e.g. email, other sites).

These other sites can have a form in which the user enters some basic information (Name, phone, email). This data is sent to Drupal (curl), a cart and session is created (anonymous unless the user is logged in our site) and the session ID is sent back to the calling website.

The user is redirected to our Drupal site, and the session is restored using the id that was passed.

Everything is working fine, but the user has enter the name, phone and email twice because Drupal tries to pre-populate the checkout fields with the user data, and in this case the user is anonymous, even though I have the user data from the first call.

Is it possible to add this information (name, email, phone) after calling commerce_cart_product_add() for anonymous users? The fields in checkout should get pre-populated even if the user is anonymous.

You can do one of two things: store the incoming data in the session somehow and alter it into the appropriate fields via hook_form_alter() or immediately create the relevant customer profiles for the session and reference them from the cart order you create. Default rules in Drupal Commerce will handle assigning those customer profiles to any user account that gets created during checkout for your anonymous sessions.


Getting data out of Profile2 with field_get_items() I am trying to access my profile2 fields in template.php. I get profiledata, but I also get an error message:

  EntityMalformedException: Missing type profile2. in entity_extract_ids() (row 7663 of /includes/common.inc).

Should not the entity type in field_get_items() be 'profile2', or is it another value?

$profiledata = profile2_load_by_user($variables['comment']->uid);
$lastname = field_get_items('profile2', $profiledata, 'field_lastname');

As @Clive mentioned profile2_load_by_user() takes user account object not uid, but you also need type name as second argument to retrieve field_lastname using field_get_items function.

I recommend you to use this function profile2_by_uid_load instead of profile2_load_by_user

So your code should look like the following:

$profiledata = profile2_by_uid_load($variables['comment']->uid, 'profile_type_name');

$lastname = '';

if($profiledata) {

  $lastname  = field_get_items('profile2', $profiledata, 'field_lastname');
}


Migrate multiple source data rows Has anyone tried migrating fields with multiple source data rows? In my case, Im migrating values of commerce file field (https://www.drupal.org/project/commerce_file). It only migrated 1 id where it should have multiple id's. I've checked the query in the source database, it outputs correctly, my problem is upon migration.

Here's what I did.

$query->addExpression('GROUP_CONCAT(file.field_file_fid)', 'file_id');

/* … */

$this->addFieldMapping('commerce_file', 'file_id')
        ->sourceMigration('PrivateFile')
        ->separator(',');
$this->addFieldMapping('commerce_file:file_class')
        ->defaultValue('MigrateFileFid');
$this->addFieldMapping('commerce_file:preserve_files')
        ->defaultValue(1);

I found out that sourceMigration() doesn't allow multiple data source data rows (but please correct me if I'm wrong). So, I made a custom query in my prepareRow() that somehow works like sourceMigration. Here's what I did:

// group concat code
$query->addExpression('GROUP_CONCAT(file.field_file_fid)', 'file_id');

// in field mapping
$this->addFieldMapping('commerce_file', 'file_id');
$this->addFieldMapping('commerce_file:file_class')
      ->defaultValue('MigrateFileFid');

// in prepareRow()
public function prepareRow($row) {
  if (parent::prepareRow($row) === FALSE) {
    return FALSE;
  }

  // get the values of the file_id where you used group concat function
  $product_id1 = explode(",", $row->file_id); //convert csv to array
  $product_id1 = array_values($product_id1); //redeclare it to clear its index / optional
  $newsIds = array(); //array where the ids will be stored

  foreach ($product_id1 as $i) { //loop through array
      $getEquivalentId = db_select('migrate_map_privatefile', 'p') //'migrate_map_privatefile' is the migrate map table where the ids of the files are stored
              ->fields('p', array('destid1'))
              ->condition('p.sourceid1', $i);
      $resultOfId = $getEquivalentId->execute();
      foreach ($resultOfId as $id) {
        $newsIds[] = $id->destid1; //store result to $newsIds
      }

    }

    $row->file_id = $newsIds; //the values of file_id will now be $newsIds

  }

Hope this would help someone, someday.
Cheers!


How to display blocks as a toggle? I am displaying a list of Views blocks on the user page.

I want to create a menu/list of links on the sidebar of the page, and when I click the link "Block 1" it shows only the "Block 1". When I click "Block 2" it shows the block 2 and so on... All the other blocks must be hidden.

I could create several pages with the views and could link to those pages, but the thing is: I need to be in the user page, because the views have filters related to the user URL. So it has to be all in the same page.

What is the best way to do this?

Please see the picture explaining how I want the page.

The Quick Tabs module may meet your needs.

  The Quick Tabs module allows you to create blocks of tabbed content, specifically views, blocks, nodes and other quicktabs. You can create a block on your site containing multiple tabs with corresponding content... Once created, the Quick Tabs blocks show up in your block listing, ready to be configured and enabled like other blocks.

You would create a Quick Tabs instance (Admin > Structure > Quicktabs) with the views blocks you want to display. You are able to configure URL arguments to pass to the block's contextual filters.

Then display the block of the Quick Tabs instance on the user page.

There are various tab styles offered by the module or you can style the tabs with your own CSS.


How can I improve running repeating background tasks? I ran into an issue recently, where I have a piece of code that accesses content from an external source. The content generation from this source is quite slow (3-5 seconds), but it only needs to be refreshed every 30-60 seconds.

Currently it's a bit of a Russian roulette. Every minute a user will receive a generally slower page load, while the content is refreshed and cached, and then other people will receive the cached version. Naturally, this is a headache for the users and for our apdex score.

I was trying to find a way to refresh the content in a non-obtrusive way, either automatically via scheduled action sets, or in background process when the user load the page, but I've failed with both. Normally it would not be an issue (simple enough using Elysiacron), but on Pantheon I don't think it's possible to manipulate the crontab in the fashion I require it.

Did anyone face a similar issue on Pantheon so far? Is there any solution that would solve my problem within Pantheon? Can something like this be achieved with AJAX?

I have an idea for a workaround, which would involve a third party machine requesting the part of the module that generates and caches content every 30 seconds, but that is a really ugly and inelegant way to do this.

Thanks for any input regarding this!

Instead of updating a global cache of remote objects (which a visitor might see a stall on while data is being fetched ...)

Simply use 2 caches. 1 cache is what visitors see data from from say a Drupal cache bin. The second cache bin is another private drupal cache bin updated by your module from the remote host. You could make custom cache tables in Drupal or simply use raw MySQL tables without the Drupal API if you're not familiar with it.

Then on occasion do a database table flip (eg, truncate cache2; select cache1.* INSERT INTO cache2;, or sync from 1 Drupal cache bin to the other. This local cache store updating should be faster than the remote server.


embed flexslider in fields I need to create several nodes of the same type and all have to have an image carousel similar to what flexslider does in Views.
I already deleted the Views example but cannot replicate the behavior in a field in spite that I formatted the field with flexslider full, I just get the images displayed one below the other.

Check the following:

What version are you using? There was an issue with Fields and alpha 2.
Are the libraries downloaded to the correct location? Check the project page for instructions.
If the libraries are there, does the webserver user have permission to read the libraries?


How to change query target when using EntityFieldQuery I'm using EntityFieldQuery and want to change the query target to something other than 'default' (because I'm using DB replication with the help of autoslave module).

It's easy to do that when using db_select or db_query by setting 'target' key on third $options parameter.

EntityFieldQuery class doesn't have any method for that and I tried to use hook_query_alter but no luck there too.

This is currently not possible (Drupal 7.43). EntityFieldQuery doesn't have any options for using a slave/replica database, nor does the module that actually executes the query, which is field_sql_storage.module in field_sql_storage_field_storage_query().

Ultimately that function calls db_select():

$select_query = db_select($tablename, $table_alias);

But it doesn't pass the 3rd parameter which is where the slave database would be targeted, so it will always use the master. It's also not possible to alter the query to add new options, as the Query->queryOptions property is protected.

I filed an issue against Drupal core, if it gets fixed the solution will be posted there: https://www.drupal.org/node/2714021