Destination property uri not provided migrating uri I'm working on a file migration from D6 -> D8, and in my case, all the files are already on S3, and they don't need to move, so all I need to do is migrate the URL to a new fid. Based on direction from mikeryan1 in IRC, in my config file I'm just doing

uri: uri

However, when I try to migrate, I get a 'Destination property uri not provided' error. I tracked down the code to EntityFile::getEntity():

// By default the entity key (fid) would be used, but we want to make sure
// we're loading the matching URI.
$destination = $row->getDestinationProperty('uri');
if (empty($destination)) {
  throw new MigrateException('Destination property uri not provided');
}

where getDestinationProperty() is

  public function getDestinationProperty($property) {
    return NestedArray::getValue($this->destination, explode(static::PROPERTY_SEPARATOR, $property));
  }

Tracking the code all the way through to NestedArray::getValue(), I find that the problem is my $ref array does not contain a uri key, so getValue() returns NULL.

  public static function &getValue(array &$array, array $parents, &$key_exists = NULL) {
    $ref = &$array;
    foreach ($parents as $parent) {
      if (is_array($ref) && array_key_exists($parent, $ref)) {
        $ref = &$ref[$parent];
      }
      else {
        $key_exists = FALSE;
        $null = NULL;
        return $null;
      }
    }
    $key_exists = TRUE;
    return $ref;
  }

Here is my migration config file.

id: file_s3
label: Files - S3
migration_group: file
migration_tags:
  - Drupal 6
source:
  plugin: file_s3_source
  constants:
    # source_base_path must be set by the tool configuring this migration. It
    # represents the fully qualified path relative to which URIs in the files
    # table are specified, and must end with a /. See source_full_path
    # configuration in this migration's process pipeline as an example.
    source_base_path: ''
process:
    # If you are using both this migration and d6_user_picture_file in a custom
    # migration and executing migrations incrementally, it is recommended that
    # you remove the fid mapping here to avoid potential ID conflicts.
  fid: fid
  filename: filename
  source_full_path:
    -
      plugin: concat
      delimiter: /
      source:
        - constants/source_base_path
        - filepath
    -
      plugin: urlencode
  destination_full_path:
    plugin: file_uri
    source:
      - filepath
      - file_directory_path
      - temp_directory_path
      - is_public
  uri: uri
  filemime: filemime
  filesize: filesize
  status: status
  changed: timestamp
  uid: uid
destination:
  plugin: entity:file

So what do I need to do to my config file to avoid this error?

Thanks.

It turns out that the problem was that the source data from D6 doesn't have a uri field (it's filename and filepath), so just using a custom plugin to create the uri in the source row gets around it.


Form and gated content UPDATED from earlier:

I am using a simple Drupal form that collect user info before allowing the user access to donwloadable content. NOTE: This is using the form API and I am no longer using a modal; just using a regular page created by a hook. Here is the scenario:

<?php

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

  $items['form/userinfo'] = array( //this creates a URL that will call this form
    'title' => 'Download Form', //page title
    'description' => 'A form that gathers user infomation',
    'page callback' => 'drupal_get_form', //this is the function that will be called w           hen the page is accessed.  for a form, use drupal_get_form
    'page arguments' => array('my_form'), //name of the form
   'access callback' => TRUE
 );

 return $items;
}

function my_form() {
 if (!empty($_COOKIE['Drupal_visitor_downloadbypass'])) {
 drupal_goto('this is where the pdf file will go'); // rest of the page will not execute because drupal_goto ends the request.
}
 $form['name']['first'] = array(
'#type' => 'textfield',
'#title' => t('First name'),
 '#required' => TRUE,
 );
$form['name']['last'] = array(
'#type' => 'textfield',
'#title' => t('Last name'),
 '#required' => TRUE,
 );
$form['name']['title'] = array(
'#type' => 'textfield',
'#title' => t('title'),
 '#required' => TRUE,
 );

 $form['submit'] = array(
'#type' => 'submit',
'#value' => 'Submit',

 );

 return $form;
 }
   function my_form_submit($form, &$form_state) {
 // $form_state['values']['example'] contains the submitted value of 'example' element.
 user_cookie_save(array('downloadbypass' => 1));
  $form_state['redirect'] = 'this is where the pdf file will go';
  }

So here is my question: Now my form page is not showing up and I didnt change the hook except for the form name argument. The form will need to redirect back to the previous page and open the file in a new window upon submission.

Thanks!

phi

You didn't mention whether you are using ctools modal forms or a custom modal form.

For general form API submissions, the submit handler will only be executed when the form validation has passed, including the regular CSRF checks.

Suppose you have a form like this:

<?php
function my_form() {
  if (!empty($_COOKIE['Drupal_visitor_downloadbypass'])) {
    drupal_goto('download/able/file.here'); // rest of the page will not execute because drupal_goto ends the request.
  }
  $form['example'] = ...;// your form building goes here
  ..
  ..

  return $form;
}

function my_form_submit($form, &$form_state) {
  // $form_state['values']['example'] contains the submitted value of 'example' element.
  user_cookie_save(array('downloadbypass' => 1));
  $form_state['redirect'] = 'download/able/file.here';
}

If you are using a ctools modals, you can check the $form_state in your ctools form builder to do the same cookie check and redirect above.

Your ctools form builder can be as follows. Note the $form_state check.

<?php
function my_ctools_form_wrapper($js = NULL) {
  ctools_include('ajax');
  ctools_include('modal');
  $form_state = array(
    'ajax' => TRUE,
    'title' => t('My Ajax Form'),
  );

  $output = ctools_modal_form_wrapper('my_form', $form_state);

  if (!empty($form_state['executed'])) { // is the form submitted ?

    // Add the responder javascript, required by ctools
    ctools_add_js('ajax-responder');

    // Create ajax command array, dismiss the modal window.
    $output = array();
    $output[] = ctools_modal_command_dismiss();
    $output[] = ctools_ajax_command_reload();
  }

  print ajax_render($output);
  exit();
}


Get interface translation LID (Locale Id?) using source string value I'm using User interface translation in English to override system strings like Drupal 7's String Overrides module did. Works great. However, in my custom module, as I edit strings that run through the t() function, the Source string table in User interface translation is filling up with unused strings.

I'm writing a simple function to delete unwanted source strings one-by-one. The post at http://www.drupal8.ovh/en/tutoriels/89/delete-a-source-string-and-target-translations-drupal-8 provides code for deleting a translation once you know the LID (Locale Id?), which it suggests you get by inspecting the HTML of the displayed User interface translation page.

Question: Is there a way to look up the LID for a source string using the text of the source string?

I've read many posts, but don't see any that suggest how to do this.

OK: Figured it out through trial and error. Here's the code:

$db = \Drupal::database();

$query = $db->select('locales_source', 'ls')->
    condition('source', $source_string)->
    fields('ls', ['lid'])->
    range(0, 1);

$lid = $query->execute()->fetchField();

UPDATE: Found a cleaner way. Here's the code:

$storage = \Drupal::service('locale.storage');
$string = $storage->findString(['source' => $source_string]);

if (!is_null($string)) {
  $lid = $string->lid;
}

I'm using this now in a custom module. Seems to be working well.


Create interactive search filter I need to develop a search form with two differents taxonomy (taxo1,taxo2).

When a user selects in taxo1 la term, the second list has to be shown with inside only corresponding taxonomy terms.

Here is a example: if the user selects term departement in the first taxonomy taxo1 (using a select list), then a second select list (with terms from taxo2) should appear with only towns from the department previuously selected.

I can't do that with Views because filters can not interact.

Can anybody give me a way to do this?

What you are looking for is hierarchical list and can be accomplished by using these well-maintained modules below. The difference is Simple Hierarchical Select module provides a simpler implementation for dependent taxonomies [might work for your situation better].

  - Hierarchical select --
  This module defines the "hierarchical_select" form element, which is a greatly enhanced way for letting the user select items in a hierarchy. Hierarchical Select has the ability to save the entire lineage of a selection or only the "deepest" selection. You can configure it to force the user to make a selection as deep as possible in the tree, or allow the user to select an item anywhere in the tree. Levels can be labeled, you can configure limit the number of items that can be selected, configure a title for the dropbox, choose a site-wide animation delay, and so on. You can even create new items and levels through Hierarchical Select!

  Simple hierarchical select Simple hierarchical select defines a new form widget for taxonomy fields to select a term by "browsing" through the vocabularies hierarchy.
  The widget is available in node forms and as Views exposed filter.This module has been inspired by Hierarchical select but is much simpler (hence the name ;) ).Unlike Hierarchical select this module provides a simple widget for taxonomy terms only. As an addition Simple hierachical select works as Views exposed filter.


Redirect user page to user/edit and user/login I want to do page redirect when user access /user page. When user anonymous user access the /user it should redirect to user/login page and when logged in user access the /user page it should redirect to user/%/edit page.

I have tried the following the code

function my_user_menu_alter(&$items){
   $items['user']['page callback'] = 'my_user_page_redirect';
}
function my_user_page_redirect() {
  global $user;
  if (user_is_logged_in()) {
  drupal_goto('user/'.$user->uid.'/edit');
}
 else {
   drupal_goto('user/login');
 }

}

For logged in user it redirects to user/%/edit page. For anonymous user it displays webpage redirect error

How can I do this. Thank You

You can do it without hook_menu_alter, achieve it in hook_init, try something like  (don't forget changes in hook_init need clear the cache to getting applied)

function yourmodule_init(){
   if(current_path()=="user"){
   global $user;
     if (user_is_logged_in()) {
      drupal_goto('user/'.$user->uid.'/edit');
    }
   else {
      drupal_goto('user/login');
   }
}
}


Aggregated CSS & JS files revert to old version I'm troubleshooting an odd issue on my Drupal 7 site where it seems that old versions of our aggregated CSS & JS files are used some amount of time after a cache clear. How this is playing out is that I'll make some update to our CSS or JS, then clear the cache via drush cc all (I've also used the UI to manually clear the cache). I get an updated version of the CSS / JS for a while. At some point (typically I've noticed it a few hours later), the page serves the old version of the aggregated file.

I've pulled mysqldumps of the site, and can see that the values in the variable table for drupal_css_cache_files, for example, contain a reference to the old aggregate rather than the new.

I found this issue on drupal.org (and I'm not sure it's exactly the same thing), but one of the suggestions involves deleting all files in <root>/cache, which I don't have. Would this be the same as deleting the files in sites/default/files/js/?

Another part of this that may or may not be related is that I see in my site logs "page not found" requests for old aggregated files that don't exist anymore.

I'm hitting a wall in troubleshooting, since it seems like the actual database value for the new aggregated file is being reverted. Anyone know what might be going on here?

Couple things to look into. An external cache (Varnish/Boost/etc...) could be referencing the old files. This issue will help with the variable_set's with css/js aggregation https://www.drupal.org/node/886488#comment-9668583. Also see this issue: https://www.drupal.org/node/1014086. I'd guess it's an external caching issue based off of what your describing but I can't say for sure due to the flaws in core that have still not been fixed.

In all honesty advagg will fix these issue for you. Drupal.org uses it due to issues with deployments https://www.drupal.org/node/1412130 https://www.drupal.org/node/2446971


Is there a way to pass an argument to a view without using the url? UPDATE: Shawn's answer is correct but I'd like to mention for anyone else looking to implement it. The arguments must match the contextual filters you've added, in the same order.

Right now I'm embedding views using

print views_embed_view('customview', 'customblock');

in a block. Is there a way that I can still embed a view in a block and pass in a parameter to it. I'd like to create a filter like this

print views_embed_view('customview', 'customblock', 'customcategory');

Is this possible?

Yes, your example does exactly what you're wanting. Read the docs on views_embed_view...

  "...: Any additional parameters will be passed as arguments."


field.tpl.php available variables According to the documentation, these are the available variables:

$items: An array of field values. Use render() to output them.
$label: The item label.
$label_hidden: Whether the label display is set to 'hidden'.
$classes: String of classes that can be used to style contextually through CSS. It can be manipulated through the variable $classes_array from preprocess functions. The default values can be one or more of the following:
field: The current template type, i.e., "theming hook".
field-name-[field_name]: The current field name. For example, if the field name is "field_description" it would result in "field-name-field-description".
field-type-[field_type]: The current field type. For example, if the field type is "text" it would result in "field-type-text".
field-label-[label_display]: The current label position. For example, if the label position is "above" it would result in "field-label-above".

However, I've attempted doing a print_r($items,1) (and the others above) and it seems none of these are actually available to me within my views-view-field--field-download.tpl.php where download is the name of the field I am templating.

  Notice: Undefined variable: items in include() (line 12 of
  /var/www/sites/path/to/templates/views/views-view-field--field-download.tpl.php).

What am I missing?

EDIT:

I also found this documentation, but am having a similar problem. It mentions I should have $fields, $view, and $row... but I am having trouble accessing some of these.

I am able to get some information I need using $row->_field_data["nid"]["entity"]->..., but how do I output the field as it would normally be output? I have conditionals set up and want to output it as it would normally be on one condition, and output something else on another condition. I am able to get the data for the conditions to work properly... but can't figure out how to output the field as it would normally be.

A views field template only has these variables:

 * - $view: The view object
 * - $field: The field handler object that can process the input
 * - $row: The raw SQL result that can be used
 * - $output: The processed output that will normally be used.

This is the default views field template:

<?php

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

You can see what templates you can use by going to your view, then click "advanced" and then next to "Theme", click on "information". This will show you all available templates you can use and override.

Hope this helps you out.


How to format the raw date formats when using Google Analytic Reports? I am using Google Chart Tools, Views, and Google Analytic Reports to create charts for an admin dashboard.

However the date format (Time Dimensions: ga:date) outputs the date in the YYYYMMDD format.

How can I change that to something like Oct 31?

Note: I have been asking around and apparently NO ONE knows how to do this. Here are some relevant URLs about it:

Date Format in Views, related to the Views Dataviz with Google Charts API module.
Google analytics with views and google chart tools, related to the Google Chart Tools module.
Format time duration (not the exact same issue, pretty close).

Feature request #1900994 (from early 2013), with title "Date Format in Views", seems to have been delivered (fixed) near the end of 2014 via issue #2368159, with title "Add support for datapoints types". Refer to description of the issue for more details about it (the problem description, and the actual solution that got implemented).

Issue #2368159 also resolved the issue about Format time duration, a typical variation of the question here.


Clean url disabling not working For some reason Drupal is parsing my landing pages address with both alias and clean url. Meaning that the landing page for new users becomes /dashboard&destination=node/30 instead of ?q=dashboard or ?q=node/30.

I have tried disabling clean url by unchecking use clean urls (?q=admin/config/search/clean-urls) and clearing the cache, but it still uses them (e.g problem continues). So I was hoping somebody might enlighten me how to force Drupal not to use clean url:s?

Thanks

Try to run drush command : drush vset clean_url 0 --yes

or

Include a line in settings.php : $conf['clean_url'] = 0;

Updated :

Check this LINK. There are many ways to disable the clean url.


Help to understand and fix this entity error message I get this error message:

  Error: Notice: Undefined index: label en EntityDefaultMetadataController::bundleOptionsList() (línea 113 de/Applications/MAMP/htdocs/rooms/sites/all/modules/entity/entity.info.inc).**

The line causing the error message is contained in the following function:

 /**
   * A options list callback returning all bundles for an entity type.
   */
  public static function bundleOptionsList($name, $info) {
    if (!empty($info['parent']) && $type = $info['parent']) {
      $entity_info = $info['parent']->entityInfo();
      $options = array();
      foreach ($entity_info['bundles'] as $name => $bundle_info) {
        /* LINE 113 */ $options[$name] = $bundle_info['label']; /* LINE 113 */
      }
      return $options;
    }
  }

I don't know what other information I can include in this question because I have no idea what the cause could be. I think it is related to the Entity module because the file is inside Entity module.

Why am I getting that notice message? Is there a way to stop getting it?

Looking at the code of the Entity module, I noticed that the $info['parent']->entityInfo() method is the one defined in entity.inc, and it returns the value obtained from entity_get_info(). The reason you are seeing that error is that there is a module defining an entity type and which forgets to define the label for its bundles. The core modules always define the label for their bundles.

  /**
   * Set up the object instance on construction or unserializiation.
   */
  protected function setUp() {
    $this->entityInfo = entity_get_info($this->entityType);
    $this->idKey = $this->entityInfo['entity keys']['id'];
    $this->nameKey = isset($this->entityInfo['entity keys']['name']) ? $this->entityInfo['entity keys']['name'] : $this->idKey;
    $this->statusKey = empty($info['entity keys']['status']) ? 'status' : $info['entity keys']['status'];
  }

  /**
   * Returns the info of the type of the entity.
   *
   * @see entity_get_info()
   */
  public function entityInfo() {
    return $this->entityInfo;
  }

The Rooms module should give a value for the label property for its bundles, or the Entity module should not assume the label is always given. I don't see anything that says the bundle label is always present, even though I suspect it is a required property.


How to load content on different domain with jquery .load() using this code in the drupal block:

<script type="text/javascript">
$('#block-block-16').load('http://nashmir.kz');
</script>

but it won't load content from domain nashmir.kz. With local files it works well. Can somebody throw me a working example on how to load content from another domain?

You can use a local PHP script to pull the external data. Then use AJAX to show it in a block.

      // ajax call to a php script
      $.post("/sites/scripts/my_script.php",
        { "post_parameter" : "post_value" },
        function(data){
          // put the result into a div
          $('#result').html(data);
        }
      );

Then again if you only want to display an external website, you can use an <iframe>.


How do I get the placeholder attribute into a Search API Solr Search field? I'm using Search API Solr Search and can't seem to get a placeholder attribute in it. I've tried using hook form alter as I would on a normal search block, but doesn't seem to work with search api solr.

The id of the form = views-exposed-form-recipe-find-recipe-find-list
The name of the search input field = search_api_views_fulltext

I've placed this function in my theme's template.php...

function marigold_institute_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'views_exposed_form_recipe_find_recipe_find_list') {
    $form['search_api_views_fulltext']['#attributes']['placeholder'] = t('Search by name or ingredient');
  }
}

I'm not quite sure what I'm doing wrong. This is the first time I've tried using hook_form_alter, so I could easily be missing something obvious. I tried the function on a normal search block using "search_block_form" for the id and name, and it worked. I just can't seem to get it working with search api solr search.

The problem is the views exposed filter form always has an ID of "views_exposed_form", nothing more specific. My low-rent way round it was this:

function MYMODULE_form_views_exposed_form_alter(&$form, &$form_state, $form_id) {
  if (isset($form['search_api_views_fulltext'])) {
    $form['search_api_views_fulltext']['#attributes']['placeholder'] = t('blah');
  }
}

That works fine for my use case, but if you need something more specific you should be able to look in the $form or $form_state and find the View object, which you can use to identify which view/display is currently being altered.


When the BigPipe module is installed, the animation does not work On this page :

https://dev.s1biose.com/profil

There is a menu at the top right. It flashes green when the .views-exposed-form class is found with this JS code:

  if ($("#navbar-collapse-second .views-exposed-form").length) {
       $("#block-togglenavigationsecond .icon-navbar-second-alert").removeClass("icon-navbar-second-alert-disable");
  };

When the BigPipe module is installed, the animation does not work (under dev domain).

Here is my site with BigPipe uninstalled (under www domain):

https://www.s1biose.com/profil

The problem is that I do not see any difference in the HTML code.

Why does not the animation work with BigPipe ?

It must work on all browsers. But BigPipe creates problems on some web browser.

Thank you

Here is the complete JS file for my animation:

(function ($) {
  'use strict';

  $('#navbar-collapse-first').on('show.bs.collapse', function () {
       $('#navbar-collapse-second').collapse('hide');
  });

  $('#navbar-collapse-second').on('show.bs.collapse', function () {
       $('#navbar-collapse-first').collapse('hide');
  });

  $('#navbar-collapse-first').on('show.bs.collapse', function () {
       $('body').addClass('overlay-is-navbar-collapse');
  });

  $('#navbar-collapse-first').on('hide.bs.collapse', function () {
       $('body').removeClass('overlay-is-navbar-collapse');
  });

  $('#navbar-collapse-second').on('show.bs.collapse', function () {
       $('body').addClass('overlay-is-navbar-collapse');
  });

  $('#navbar-collapse-second').on('hide.bs.collapse', function () {
       $('body').removeClass('overlay-is-navbar-collapse');
  });

  $('#navbar-collapse-first .form-submit').on('click', function () {
       $('#navbar-collapse-first').collapse('hide');
  });

  $('#navbar-collapse-second .form-submit').on('click', function () {
       $('#navbar-collapse-second').collapse('hide');
  });

  $('#navbar-collapse-first .navbar-nav .dropdown').on('shown.bs.dropdown', function () {
       $(this).find('.dropdown-toggle svg').removeClass("fa-plus-circle").addClass("fa-minus-circle");
  });

  $('#navbar-collapse-first .navbar-nav .dropdown').on('hidden.bs.dropdown', function () {
       $(this).find('.dropdown-toggle svg').removeClass("fa-minus-circle").addClass("fa-plus-circle");
  });

  $('.collapse').on('shown.bs.collapse', function () {
       $(this).parent().find('.panel-heading .collapse-change-icon svg').removeClass("fa-plus-circle").addClass("fa-minus-circle");
  });

  $('.collapse').on('hidden.bs.collapse', function () {
       $(this).parent().find('.panel-heading .collapse-change-icon svg').removeClass("fa-minus-circle").addClass("fa-plus-circle");
  });

  $('.bs-tour-action-trigger').on('click', function () {
       $('#comment-ca-marche').modal('hide');
  });

  $('#block-boutonimportant').on('click', function () {
       $('#navbar-collapse-first').collapse('hide');
  });

  $('#block-boutoncharte').on('click', function () {
       $('#navbar-collapse-first').collapse('hide');
  });

  if ($("#navbar-collapse-first .views-manage-menu").length) {
       $("#block-togglenavigationfirst .icon-navbar-first-alert").removeClass("icon-navbar-first-alert-disable");
  };

  if ($("#navbar-collapse-second .views-exposed-form").length) {
       $("#block-togglenavigationsecond .icon-navbar-second-alert").removeClass("icon-navbar-second-alert-disable");
  };

  $('#navbar-collapse-first').on('shown.bs.collapse', function () {
       $(this).find("#block-menuprincipal .dropdown-toggle").dropdown("toggle");
  });

  $('#navbar-collapse-first').on('shown.bs.collapse', function () {
       $(this).find(".views-manage-menu .dropdown-toggle").dropdown("toggle");
  });

}(jQuery));

Bigpipe's purpose is to load dynamic/uncachable blocks of content (e.g. forms) in via javascript. This is so that the rest of the site can remain cached and just the dynamic parts get loaded in separate.

So the issue here is probably your own javascript is triggering before big pipe has loaded the targeted content in. Have you got your JS in window.load or something like that? You should place it into a Drupal behaviour which will get called each time something dynamic is loaded in by drupal.


Running unit test only for my custom module Is there any way I can run unit testing only for my modules? I know there is a way to run a specific unit test but I want to run unit test for all tests under certain directory (/modules/custom in my case). Is it even possible? I want to do it so that CI/CD automatically runs unit tests only for my code.

Sure, all you need to do is provide a path/file to phpunit and it will be limited to that.

vendor/bin/phpunit -c core modules/custom


Create short link automatically with ShURLy I am using the ShURLy module to create short links for nodes. I would like to be able to create the short links when nodes are published, automatically, without having to do the extra steps of clicking on the Bookmarklet which opens a new page where I create the short link by clicking on a button/link.

How can I achieve this?

update

I am using workbench so I added

function my_node_workbench_moderation_transition($node,
$previous_state, $new_state) {
// Generate the short link when it is published.
  if ($new_state == 'published' && $previous_state != $new_state) {
    $link = my_node_create_short_link($node->nid);
  }
}

and the function my_node_create_short_link with shorten (shorten_url)

function my_node_create_short_link($node_id) {
 // Do not create the short link if already exists.
  $link = my_node_short_link_get($node_id);
  if ($link) {
      return $link;
  }
  else {
    $link = shorten_url(url('node/' . $node->nid, array('absolute' => TRUE)));
    // Insert the link
    my_node_short_link_insert($node->nid;, $link);
    cache_set($node->nid;, $link);
    return $link;
  }

}

As per the current module functionalities it does not seem to have that feature. So I think you need to create custom module.

In your custom module you will require to use hook_node_insert (For Drupal 7) this hook to execute after each node is added. Then Shurly provides API to create short link, using those APIs you can create short link as an when required.

Hope this helps.. :)


Drupal Feeds XPath Parser html parsing form IMDB i have a movie site , i need import movie data from IMDB,
for doing this i installed Feeds and Feeds XPath Parser for scrapping.
i created a content type for movie wiht some field (poster,actors,...)

after that i create a feeds importer called "Movie importer" .
i set Parser to "XPath HTML parser".

in the mapping i added xpathparser:0 ,xpathparser:1 and... for field i created for Movie content type.

in the XPath HTML parser settings i added Xpath like this

context: //div[@id='overview-top']
title:  /h1/span[1]
poster:  /div/a/img
Genre:  /div[1]/a/span
Story:  /p[2]
stars:  /div[3]/a/span
movie rate:  /div[2]/div[3]/strong/span

It's not  working , and i don't know why.

one more thing i am newbie with XPath :(

Here Sample IMDB Page :
http://www.imdb.com/title/tt0773262/

The context XPath expression is for finding a context of all other (variable) expressions. These queries do not have the context prepended, but evaluation starts with (one of the) results as context.

Thus, you may not start your query with /, otherwise search starts at the root again – and the root element is <html/>, not <title/> or any of the others.

For example, the query for the title has to be h1/span[1]. Anyway, I'd better go for the @itemprop attribute instead of a positional attribute: h1/span[@itemprop='name'] or even decouple further from the underlying structure: .//*[@itemprop='name'] and use the Movie schema properties whenever possible, as they are designed for scraping the data and will make it much more robust.


Regenerate image styles I'm currently using Drupal 8.2.3 for my website design. My aim is to use it for publishing my blogs to social media sites, such as Facebook, Twitter, LinkedIN, etc. With that in mind, i'm using image styles to create OpenGraph and Twitter meta tags in my blog posts to properly display content on various platforms.

The problem comes when I make a change to the imagestyle. When I flush the contents, it doesn't automatically regenerate the imagestyle content for my metadata. Is there a way to automatically regenerate the imagestyles and content?

Any help much appreciated.

There is a setting to flush the image style at admin/config/media/image-styles:

Or you can use drush:

drush image-flush --all (flush all styles)
drush image-flush thumbnail (flush thumbnail style)


Different twig template for user profiles of different role I would like to theme user profile pages differently based on the role but I can't figure it out how to do so.

I will need when someone is viewing an administrator profile this twig file to be loaded:
user--administrator.html.twig

and when is viewing an editor profile this:
user--editor.html.twig

Any idea how can I achieve this?

It can done by adding a hook theme suggestion based on roles in your YOUR_THEME.theme file

/**
 * Implements hook_theme_suggestions_user_alter().
 */
function YOUR_THEME_theme_suggestions_user_alter(array &$suggestions, array $variables) {
  foreach ($variables['elements']['#user']->getRoles() as $role) {
    $suggestions[] = 'user__' . $role;
  }
}

Then you can use templates like user--administrator.html.twig, user--editor.html.twig


How can I disable Webform submit button after being clicked I've been trying to resolve an issue with no luck. For some reason there are no submission indicators out of the box with D7 Webforms and from what i've found it doesn't look like they have any plans to implement this as they have already added this 'feature' in D8.
I wrote a handler in javascript that will just replace the input with another, but it doesn't appear that the script is firing because the actual submit is taking priority
var form = document.getElementsByClassName("webform-client-form")[0];
var isValidForm = form.checkValidity();
var submitBtn = document.getElementsByClassName('webform-submit')[0];
function preventExtraSubmits() {
    if (isValidForm) {
        var fakeBtn = document.createElement("input");
        fakeBtn.value = "Submitting...";
        fakeBtn.classList.add('webform-submit button-primary form-submit')
        insertAfter(submitBtn, fakeBtn);
        submitBtn.style.display = 'none';
    }
}
function insertAfter(referenceNode, newNode) {
    referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
}
submitBtn.onsubmit = function(){preventExtraSubmits()}

From what i've seen is that this might need to be handled server side, but I can't seem figure out how to override webforms submit function.
Fairly new to Drupal and this has been a very frustrating battle to get this working
Drupal v 7.77
Webform v 7.x-4.23

You could try this module: https://www.drupal.org/project/hide_submit
Be aware that this module has an issue with Ajax forms and file uploads.


Set destination on comment post Short question:
How do you modify the destination on comment post?

Long question:
Say, my comment limit is set to 10 per page. When I post the 11th comment, Drupal takes me to /node/#?page-1#comment-#. Instead, I want it to take me to the node it was posted to, i.e. /node/#.

I need this because I'm using the More Comments module, which doesn't use pagers and not compatible with permalinks.

I haven't figured out how to manually set the destination on comment post, but I did found the Comment Goodness module that works with More Comments, to remove the ?page-1#comment-# query. And this solves my question.


How can I programmatically copy all blocks of a given theme into the same regions of a new theme? I would like to switch admin themes from a core theme (seven) to a custom sub-theme so I can add some customization without hacking core.

When I install the new sub-theme it creates all the block placement settings and leaves them header or content. I haven't changed any regions between the two themes, and just want to copy all the blocks from the seven theme to the current theme. I know I can check block settings with block plugin manager (plugin.manager.block) but I don't know what blocks to edit. I would like to know how to get a list of all the blocks from the old theme and copy all the placement to new theme programmatically.

You can entity query your relevant block config then create a cloned entity object via Block::createDuplicateBlock() then modify the sub-theme clones before saving the new block config into sub-theme region.

For example:

$block_ids = \Drupal::entityQuery('block')->condition('theme', 'my_base_theme')->condition('region','my_region')->execute();
foreach ($block_ids as $block_id) {
  $parent_block = \Drupal\block\Entity\Block::load($block_id);

  $new_id = str_replace('my_base_theme', 'my_sub_theme', $parent_block->get('id'));
  $child_block = $parent_block->createDuplicateBlock($new_id, 'my_sub_theme');
  // @TODO: set other properties that might need to be unique to this new theme's block

  $child_block->save();
}


My radio buttons in Drupal do not show I have tried to set up an online example of a form using Drupal 7.

When I run it, the radio buttons do not show at all.
I also get the following errors:

  Notice: Undefined index: #title_display in form_pre_render_conditional_form_element() (line 3090 of /var/www/sandbox7/includes/form.inc).
  Notice: Undefined index: #title_display in form_pre_render_conditional_form_element() (line 3090 of /var/www/sandbox7/includes/form.inc).
  Notice: Undefined index: #id in drupal_process_states() (line 4549 of /var/www/sandbox7/includes/common.inc).
  Notice: Undefined index: #id in drupal_process_states() (line 4549 of /var/www/sandbox7/includes/common.inc).
  Notice: Undefined index: #id in drupal_process_states() (line 4549 of /var/www/sandbox7/includes/common.inc).

Is the form running through drupal_get_form? This type of error can occur when using the generic render() fuction on a form that hasn't been prepared by drupal_get_form(). Check your hook_menu settings and make sure your page callback is set to drupal_get_form() with the form id as the page arguments(encapsulated in an array)

if you must use a custom page callback, make sure that you're piping the form based output through drupal_get_form() like so...

$output = drupal_get_form('form_id');


Page--front.tpl.php not working - Tao theme This should be really simple, maybe I'm just having a moment. Why is my page--front.tpl.php not rendering my home page? I'm using a tao subtheme.

Here's my tpl.php file.

(There's no other page--front.tpl.php in the tao folder.)

Here's my front page settings:

And here's theme developer telling me that the front page is using page.tpl.php to load:

I've cleared my cache with drush a couple times and restarted my local server. What else am I missing?

I think I see a Windows specific issue here.

Notice how block.tpl only has the extension tpl and your new file page--front.tpl.php has php as extension in the filename?

Maybe Windows hides the php extension when you list files (and instead shows it under Type)?

Try removing .php from page--front.tpl.php and see if it still under the Type column shows up as php. If so clear cache and carry on :)


How to create a chart about a date range if some dates in this range are missing? I use charts module Charts and I want to create a view that shows the stats from a date range.

I have an exposed filter and this filter has a between range. I want to show all dates from values of exposed filter.

I provided the values 7/10/2015 and 15/10/2015 as my date range and always show the dates if no stats exist for specific days in this range.

For example:
7/10/2015, 8/10/2015, 9/10/2015, 10/10/2015, 11/10/2015, etc. up to 15/10/2015,

Attached an image to understand what I want (how the chart should look like).

How can I do this, with filter, arguments or handlers, please give me a example.

For this moment the module "views between date filter" is not working as I want: it only shows all dates for which some data exist. But always need show the dates that no have results.

I'm assuming you're using the Charts module and that your problem is similar to what is detailed in Comment nr 12 of Issue nr 2052429. Here is part of what that comment includes:

  ... It's not an issue Google Charts could actually fix, as there is no "labels" sent to Google Charts for the chart addons for it to recognise gaps in the data ...

So at a minimum I recommend you to try the most recent DEV version, and apply the patch attached to that comment, to check if that helps in your case. If it doesn't, know that it is a prereq for sure (without that patch you won't be able to get it to work).

If applying the patch is not sufficient, then I'd recommend what's written in the "Bonus tip" of Steps to create charts using the views UI, i.e.:

  You may find it easier to start with a "Table" display and convert it to a chart display after setting up the data. It can be easier to visualize what the result of the chart will be if it's been laid out in a table first.

In other words: before trying to create a chart, make sure the tabular version of it has the correct data displayed.

Disclosure: I'm a co-maintainer of the Charts module (+ author of its community documentation),
I hope this does not violate the site's policy on self-promotion.


Add meta tag description, page title and abstract programatically I have created a custom page using a tpl.php file and I want to add meta tag page title, abstract and description that page. Can anyone show me how to add these meta tags programatically to custom page?

$description = array(
                 '#type' => 'html_tag',
                 '#tag' => 'meta',
                 '#attributes' => array(
                 'name' => 'description',
                 'content' => 'here all description goes',
               )
 );
drupal_add_html_head($description, 'description');

This is the code I am using to add description to my head.
Thanks in advance.

In your theme's template.php file, you could add something like

/**
 * Implements hook_preprocess_html
 */
function THEME_NAME_preprocess_html(&$vars) {

  if (current_path() == 'my/custom/path') {
    $description = array(
      '#type' => 'html_tag',
      '#tag' => 'meta',
      '#attributes' => array(
        'name' => 'description',
        'content' => 'here all description goes',
      )
    );
    drupal_add_html_head($description, 'description');
  }

}

Clear cache to register new preprocess function.


Allow block display on child nodes but not grandchildren In a block configuration, I would like to show the block on
/programs/* but not on programs/* /*

I have seen a number of questions similar to mine.
Block display using wildcard, non-greedy for example.

The recommendation from the above link to use drupal_match_path() makes the most sense to me.  I have implemented the following,

    <?php
if (drupal_match_path(current_path(), "programs/*") && !arg(2)) {
  return TRUE;
}
?>

expecting the block to appear on /projects/name but not on /projects/name/grandchild-node.  The block doesn't appear anywhere. Just to test the system, I tried this:

    <?php
if (drupal_match_path(current_path(), "programs/*") {
  return TRUE;
}
?>

and still the block doesn't show.
I'm certain that I'm doing something wrong that is very basic. Any ideas?

Hmm.  Are you sure current_path() is returning the alias?  cause I don't think match_path takes that in to consideration at all.

$path = current_path();
$path_alias = drupal_lookup_path('alias',$path);


How can I programmatically delete a custom menu? I'm writing a hook_deploy_N that moves a bunch of menu items from a deprecated custom menu to some newer ones. So far, so good. After moving the items, I want to delete the old menu, but can't figure out how. \Drupal\Core\Menu\MenuTreeStorage has a delete function that may be  what I'm looking for, but the \Drupal\Core\Menu\MenuTreeStorage object is housed inside the \Drupal\Core\Menu\MenuLinkTree, which I can at least load, but has protected status, and I don't see a way to get to it. Plus, I'm not not 100% convinced that's what I want any way.

Since menus are configuration items, my poking into \Drupal\Core\Menu\MenuTreeStorage::delete() was wrong. You delete a custom menu thusly:

\Drupal::configFactory()->getEditable('system.menu.name-of-custom-menu')->delete();

Note that I'm assuming the menu is empty. I don't know what would happen if you deleted a menu that had menu items in it, whether they'd be orphaned or deleted.


Passwordless login in drupal 7 If I use something like hybridauth, can I remove password field from Drupal completely? Or at the very least make it not required during registration?

Hybridauth does remove the need of password, so I probably can remove username and password fields from the user login forms through the hooks


Form submit POST renders page before submit handler is called I have a search form in the header that is simply adding a search term to the current URL. If you are on example.com/list-page and submit a search, it just sends you to example.com/list-page?search=my-term-here.

When I submit the form, I've noticed that the full page has to be rendered before the form's submit handler is called. Since the search modifies the current list page's results, it seems redundant when submitting a search for "my-term-here" on example.com/list-page to have to render example.com/list-page again before the submit handler is called and then render the version I actually want: example.com/list-page?search=my-term-here.

I've hacked around this by doing this in my form:

// Set to the current path so we can redirect back there after submit.
$form['submission_path'] = array(
  '#type' => 'hidden',
  '#default_value' => current_path(),
  '#weight' => -100,
);

$form['#action'] = url('search-callback');

The search-callback does nothing:

function mymodule_search_callback() {
  return '';
}

The submit handler then does a redirect like this to get back to example.com/list-page?search=my-term-here.

// Redirect back to the page that submitted the search.
$form_state['redirect'] = array(
  $form_state['values']['submission_path'],
  array(
    'query' => array(
      'search' => urlencode($search-term),
    ),
  ),
);

Is there a better way to handle this? Can the form's submit handler be called before rendering the page the form is posting to?

You need to add a submit callback that will handle the redirect:

 $form['#submit'][] = 'mymodule_search_callback'

And in that callback:

function mymodule_search_callback() {
   $form_state['redirect'] = current_path() . and your urlencoded serch term;
}

Messing with $form['#action'] is not the right way to do it.


webform alter default value template.php I need to alter the default value of a webform in d6, so in my template.php I insert the following function, but it does not work; I don't like to use $get in webform.

function themename_form_alter(&$form, &$form_state, $form_id) {
  if ('webform_client_form_id' == $form_id) {
    $form['id_of_input']['#default_value'] = $node->field_cck_value[0]['value'];
    return $form;
  }
}

Can you help me?

Webform is a node module. So editing a node even though it contains form can be altered using hook_nodeapi.


7 embed an external website page in a node I have two website one is in drupal 7 the other in rails.
Is it possible to have one page from the rails app to be embedded in a drupal 7 node?
The page have a graph and search form.

An iFrame is the only option that doesn't involve huge amounts of work.

I guess if you really wanted to you you could write an API for the rails app that Drupal could consume and recreate the content off this data.

Technically you could get Drupal to scrape the HTML (file_get_contents or curl) of the ruby app and then cache this locally and embed in the node. This doesn't seem like a good idea as is inefficient and you may have problems with the search action and cache flushing mechanisms.


Adding wysiwyg (ckeditor) to textarea on node edit form I'm trying to add wysiwyg to a textarea added through CCK.

In my hook_form_alter I can alter the properties of the field no problem. Using this it seems like it should be possible to add 'format' to the element and then use filter_format, it's adds the filter select information but seems to break the body implementation of wysiwyg.

Documentation seems to be pretty sparse on this topic, does anyone know the correct way of implementing this or any complete documentation?

I usually do this by installing better formats module.   This give you the option to set the default format for a cck field when you create it.


How to correctly get the twig value I have the following response using kint. How can I correctly get the value of the title.

I tried stream.node_title[0]['#context'].output but getting null result.

Looks like it should be

{{ stream.node_title[0][0]['#context'].output }}

You can get the other two with

{{ stream.node_title[0][1]['#context'].output }}
{{ stream.node_title[0][2]['#context'].output }}

But obviously this would be hard coded. To make all of this dynamic, you can loop.

{% for title in stream.node_title[0] %}
    {{ title['#context'].output }}
{% endfor %}


How to render a weight element? I'm trying to render a weight element but it doesn't works I just have as output an empty string. But when I try to render a checkbox I get the correct output.

For the weight element:

$weight = array(
  '#type' => 'weight',
  '#title' => t('Weight'),
  '#default_value' => 1,
  '#delta' => 10,
);

// For Drupal 7.
dpm(drupal_render($weight));
// For Drupal 8.
kint(\Drupal::service('renderer')->render($weight));

Output: An empty string.

For the checkbox element.

$check = array(
  '#type' => 'checkbox',
  '#title' => t('Dry run'),
  '#description' => t('Test run without deleting revisions but seeing the output results.'),
);
// For Drupal 7.
dpm(drupal_render($check));
// For Drupal 8.
kint(\Drupal::service('renderer')->render($check));

Output:

 <input type="checkbox" value="1" class="form-checkbox" />  Dry run

Test run without deleting revisions but seeing the output results.

So, I think that the drupal_render() function and renderer service are working fine because the checkbox is rendered, but the weight element not, I'm missing something here?

The select element is built in Weight::processWeight():

  /**
   * Expands a weight element into a select element.
   */
  public static function processWeight(&$element, FormStateInterface $form_state, &$complete_form) {
    $element['#is_weight'] = TRUE;

    $element_info_manager = \Drupal::service('element_info');
    // If the number of options is small enough, use a select field.
    $max_elements = \Drupal::config('system.site')->get('weight_select_max');
    if ($element['#delta'] <= $max_elements) {
      $element['#type'] = 'select';
      $weights = [];
      for ($n = (-1 * $element['#delta']); $n <= $element['#delta']; $n++) {
        $weights[$n] = $n;
      }
      $element['#options'] = $weights;
      $element += $element_info_manager->getInfo('select');
    }
    // Otherwise, use a text field.
    else {
      $element['#type'] = 'number';
      // Use a field big enough to fit most weights.
      $element['#size'] = 10;
      $element += $element_info_manager->getInfo('number');
    }

    return $element;
  }

Which is only called in form building, not in normal rendering.


How to delete/remove Views display programmatically? Any idea how can I remove or delete Views display programmatically?

I have a Views that has 5 displays and I want to delete one of them. For the sake of avoiding manual intervention I want to do it automatically via code. Is there a way to do that?

Here is an example you would put in mymodule.install

/**
* Disable workbench views
*/
function mymodule_update_7001() {
    // an array of views (their view name) I want to disable
    $viewnames = array(
      'workbench_current_user',
      'workbench_edited',
      'workbench_moderation',
      'workbench_recent_content',
    );

    // grab the array of views that are already disabled
    $views_status = variable_get('views_defaults', array());

    // add our views to be disabled to the list
    foreach ($viewnames as $key => $viewname) {
      $views_status[$viewname] = TRUE;
    }

    // reset the variable with the new list
    variable_set('views_defaults', $views_status);

    // empty cache now
    if (function_exists('views_invalidate_cache')) {
      views_invalidate_cache();
    }
}


How to create dynamic multi column forms using native form module? I am looking to find out how I can create a form which the definition of the form is coming from a REST API as a JSON object. The form can be 1 column, 2 columns or 10 columns.

I have been able to do this by just using the native table theming option, but I want to be able to do this with the native form options so that I can utilize all the validations and everything else etc.

Does anyone have an idea as to how I can accomplish a multi-column dynamic form?

Thanks in advance!

The way you group form items (as you will need to do to create a single column) is to use the FAPI grouping mechanism, which is described here :

https://www.drupal.org/node/262758

then you can use a loop and some vars to name them, for example :

<?php

  // How ever many columns your rest callback wants to make.
  $col_limit = 10;

  for ($x = 0, $x < $col_limit, $x++) {
    $form["group_$x"] = array(
      '#type' => 'fieldset',
      '#title' => t('Your Name'),
      '#collapsible' => FALSE,
      '#collapsed' => FALSE,
    );
    $form["group_$x"]["first_name_$x"] = array(
      '#type' => 'textfield',
      '#title' => t('First Name'),
    );
    $form["group_$x"]["last_name_$x"] = array(
      '#type' => 'textfield',
      '#title' => t('Last Name'),
    );
  }

  $form["col_limit"] = array(
    '#type' => 'hidden',
    '#value' => $col_limit,
  );

?>

Will create 10 groups, with form items.
You can then use CSS or jQuery to create columns or tabs or format how ever you wish.

The hidden variable is there to tell you submit handler how many coumns there are and therefore how many times it has to loop looking for

$form_state['values']["last_name_$x"]


Where does drupal store all its files? I would like to use FTP to copy my current site to a new server. I obviously know that the bulk of my files will be stored in /var/www/ and the folders inside. I also exported my databases from phpMyAdmin to a localhost.sql file.

Is there any other place I need to pull files from? Is that it for the database?

You should be able to transfer the site wholesale, without too much fuss. After transferring, you may need to alter some paths (eg admin/config/media/file-system in D7) if the sites directory has changed paths relative to your Drupal codebase. Odds are you won't need to, though.

For a simple site, the layout will be something like this -

/var/www/index.php
         modules/                  } don't install modules here
         themes/                   } nor themes here
         includes/
         [many other Drupal core files]
         sites/
               default/            } all installed code
                       files/      } lives in the
                       modules/    } site directory
                       themes/     } and its children

For more complex setups you may need to understand multisite layouts, but for now hopefully this answers your question.


Filtered HTML adding two  tags, not one I have a "Filtered HTML" text field and have the convert line breaks to
 &
 tags option turned on in the configuration but when I'm adding content to a "Filtered HTML" field and use Shift + Enter to create a newline within the same paragraph Drupal seems to be adding in two
 tags rather than one, which I'd expect.

For an example the text

"I'm having
a great day"

gets turned into

"I'm having

a great day"

Is there any way to alter this behaviour to add just one
 tag instead of two?

The only way I've found of resolving this is to replace the two
 tags with one using a str_replace in the field preprocess function. I've placed an example below.

function theme_preprocess_field(&$vars) {
  switch($vars['element']['#field_name']) {
    // When pressing Shift + Enter in WYSIWYG editor to create a new line it outputs two
 tags, not one.
    case "field_description":
      $vars["items"][0]["#markup"] = str_replace("

", "
", $vars["items"][0]["#markup"]);

      break;
  }
}


How do I include composer.libraries.json in root composer.json without using the wikimedia/composer-merge-plugin plugin? In the recent update to Composer 2.0 the advice is to get rid of the wikimedia/composer-merge-plugin, which was even removed from the dependencies of Drupal core.
There is documentation on how to include custom module's composer.json in the root composer.json, for example Managing dependencies for a custom project, but I cannot find documentation on how to include composer.libraries.json in the root composer.json.
Can anyone explain how to get the Webform module compatible with Composer 2.0?

here is a specific way how to do it for webform module.

run composer require wikimedia/composer-merge-plugin
in composer add

  "merge-plugin": {
            "include": [
                "web/modules/contrib/webform/composer.libraries.json"
            ]
        },

run composer update --lock and verify the files

Reference https://www.drupal.org/docs/8/modules/webform/webform-frequently-asked-questions/how-to-use-composer-to-install-libraries
Reference 2 https://www.drupal.org/docs/8/modules/webform/webform-cookbook/using-the-composer-merge-plugin-to-download-libraries-with
Github issue https://github.com/wikimedia/composer-merge-plugin/issues/184


How can I lead to 404 Page Not Found when View page has no result? How can I lead to 404 Page Not Found when View page has no result?

I tried this code from http://drupal.org/node/1295824#comment-5192868in "empty text" but the View page still exist with only page title eve if it has not result to list.

<?php
drupal_set_header('HTTP/1.1 404 Not Found');
?>

You should use the drupal_not_found() function. It sets the correct headers, omits blocks from the page output to conserve CPU and bandwidth, and is the correct way to set a 404 through code in Drupal.

Also see drupal_access_denied() which might be useful.


How do I load a php library? I'm writing a wrapper module for a php library, and for some reason, can't get to actually doing something. When I try to call

libraries_load($library_name);

I get an error message:

PHP Fatal error:  Call to undefined function libraries_load()

I do have set

dependencies[] = libraries (>=2.x)

in the module_name.info file
and module_name_libraries_info() seems to be okay.
When I run drush libraries-list, I do get the library listed correctly.

The version of the libraries api I have installed is 7.x-2.2

How do I fix this?

It's very rare to need to use the Drupal API outside of a hook/callback function.

That's what's causing the problem in this case - your module file is simply being included before that of the libraries module, so the interpreter doesn't know what libraries_load() is yet.

I'd recommend moving your code into an appropriate function that gets invoked when Drupal is properly bootstrapped, and all enabled modules are loaded.

Failing that, you might get some joy out of tweaking the weight field in the system table for the modules in question. If your module has a higher weight than Libraries, you might be able to get it working. But moving the code to a more reliable place would arguably be better.


Is theme('pager') designed to work only with dynamic query? I have a custom callback function that queries data from a custom table.

The trimmed version of code that I have been writing looks as below,

function cb_user_cashback_orders($account) {
  $sql = 'SOME SQL QUERY';
  $results = db_query($sql, array(':uid' => $account->uid));
  //date, Merchant name, commission, status
  $header = array(t('Date'), t('Merchant Name'), t('Commission'), t('Status'));
  $rows = array();
  foreach ($results as $result) {
    $rows[] = array(
      format_date($result->timestamp),
      $result->status ? l($result->title, "node/{$result->merchant_nid}") : $result->title,
      $result->commission,
      $result->status,
    );
  }
  pager_default_initialize(count($rows), 10, 0); // Pager doesn't appear without this call
  $output = theme('table', array(
    'header' => $header,
    'rows' => $rows,
    'empty' => t('You have not made any purchase yet.'),
    'attributes' => array('class' => array('cb-user-orders')),
    )
  );
  $output .= theme('pager'); // as a replacement for pager_query() in D6.
  return $output;
}

I'm trying to figure out how I could get the pager work as expected.

With the code above I'm able to get the pager links (first, next, last, etc.) however the table always show the same set of items (infact all items) irrespective of pager argument (?page=1,2 OR N).

Would like to hear some input to fix this. Is theme('pager') designed to work only with dynamic query?

theme('pager') is not designed to work only with dynamic queries. The documentation for page_default_initialize() shows example code where dynamic queries are not used.

  // First find the total number of items and initialize the pager.
  $where = "status = 1";
  $total = mymodule_select("SELECT COUNT(*) FROM data " . $where)->result();
  $num_per_page = variable_get('mymodule_num_per_page', 10);
  $page = pager_default_initialize($total, $num_per_page);

  // Next, retrieve and display the items for the current page.
  $offset = $num_per_page * $page;
  $result = mymodule_select("SELECT * FROM data " . $where . " LIMIT %d, %d", $offset, $num_per_page)->fetchAll();
  $output = theme('mymodule_results', array('result' => $result));

  // Finally, display the pager controls, and return.
  $output .= theme('pager');
  return $output;

The other example given in that documentation page shows code that uses an external service to retrieve information which is shown. Also in that case, dynamic queries are not used. (The external service could not even running Drupal.)

The only difference I can see between that code, and the PagerDefault class is that PagerDefault uses a unique ID that passes as last argument of page_default_initialize().

/**
 * The unique ID of this pager on this page.
 *
 * @var int
 */
protected $element = NULL;

$total_items = $this->getCountQuery()->execute()->fetchField();
$current_page = pager_default_initialize($total_items, $this->limit, $this->element);
$this->range($current_page * $this->limit, $this->limit);

The other difference is that, as PagerDefault uses dynamic queries, its query can be altered with hook_query_alter(). In this case, as the added tag is pager, the query can be also altered with hook_query_pager_alter() which is a hook_query_TAG_alter() hook.

  public function __construct(SelectQueryInterface $query, DatabaseConnection $connection) {
    parent::__construct($query, $connection);

    // Add pager tag. Do this here to ensure that it is always added before
    // preExecute() is called.
    $this->addTag('pager');
  }


Ctools content types- What do I need to do to get my content to render in the right place? I have some panels on my site.  Previously, I was using custom content panes with the PHP filter to call functions in a custom module.  The custom function had lots of print() statements and I simply dumped a bunch of HTML to the screen.

Now, I am trying to reform my bad programming practices by moving the custom content panes into Ctools content types.  I successfully created a content type, but when I call my function (in my custom module) full of print() statements, all of the HTML gets dumped to the top of the page, instead of where the content type has been placed within the panel.

Reading through articles online, it appears this is because the content pane expects me to return something it can render, not directly print() the HTML.  Is there another PHP function I can use to gather up all the HTML I was previously using print() for?  What is the correct way to output a bunch of HTML in a ctools content type?

(If this seems obvious, please bear with me.  I'm not a programmer by training and I'm probably in a bit over my head.)

From the top of my head you should simply be able to do:

$pane = new stdClass();
$pane->title = 'Check this out!'; // Optional
$pane->content = '
My content
';
return $pane;

It's also worthwhile to review What are Ctools plugin (content type, access, etc), and how does one create them? which contains an example content type.

The question
Correct way to render a modules output through a template? shows an example of rendering through a template, so you can strip the markup out from your pane and have it contain only the relevant content.


How to insert 2 answers using Quiz submodule Short Answer? I am using the Quiz module and enabled its submodule Short Answer.

How can I insert two answers instead of one?

Note: Multiple choice is fine, but my problem is at Short Answer: I'm only able to add 1 correct answer, but my Quiz question has 2 correct answers.

I guess no solution, so I just hack the module.

/public_html/testserver/the-exaple.com/sites/all/modules/contrib/quiz/question_types/short_answer

public function evaluateAnswer($user_answer) {
  ...
  switch ($this->node->correct_answer_evaluation) {
  case self::ANSWER_MATCH:
    if ($user_answer == $this->node->correct_answer) {
      $score = $this->node->max_score;
    }
    break;
  case self::ANSWER_INSENSITIVE_MATCH:

   ////////////////edit your code here

    break;
  case self::ANSWER_REGEX:
    if (preg_match($this->node->correct_answer, $user_answer) > 0) {
      $score = $this->node->max_score;
    }
    break;
}
...
}

Since I chose my answer is insensitive, I will edit second case.


Rating for all images in a singular node? Setting up a private gallery for a photographer, so that their clients may log in, see images specific to a certain photoshoot, and check a box, or click a star to favorite different images. Any ideas of how I would set something like this up? An example of this currently being done would be Adobe's Lightroom.

You can take a look on FiveStar module : https://www.drupal.org/project/fivestar


Zebra stripping each block in a region I'm trying to apply this to each block in a region:

http://figure-w.co.uk/zebra-striping-in-php/

He is generating zebra striping per div here, which is fine, but I'm wondering how I would apply this to each block in a given region.

Would I use something like block_list($region)?

This code is supposed to go in template.php

function likemind_zebra($id = 'global',
                     $odd_class = 'odd', $even_class='even') {
  static $cursor = array();
  if(!isset($cursor[$id])) {
    $cursor[$id] = 1;
  }
  return $cursor[$id]++ %2? $odd_class: $even_class;
}

I'm just trying to figure out how I would get it to apply to each block in a region, rather than the whole region.

A $block_zebra variable is defined within the block templates to allow for the ability to zebra stripe them in a region.

See hook_preprocess_block() for more info.


I can't filter list term under admin/content I can't filter list term under admin/content.

There is not filter option for list term, just the types (taxonomy)

This is Drupal 7, ther is no category option.

This is Drupal 6, it can filter category.

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

Installed Admin Views and add the following settings to /admin/structure/views/view/admin_views_node/edit

But term list still not appearing.

admin/content page doesn't list taxonomy terms, it shows content nodes. Those options in the select list are actually Content Types you can filter by.

To view taxonomy terms, the link is admin/structure/taxonomy.

Anyway, in the remote case you do want to have better filtering options for nodes, I recommend the module Admin Views.

After enabling Admin Views module, you can go to /admin/structure/views/view/admin_views_node/edit to edit the view that's responsible for displaying the admin node list. Here you can add as many exposed filters you need, in your case, the term reference field.

Admin Views also requires Views Bulk Operations module which allows you to execute operations on multiple nodes at once.

Edit: Your taxonomy vocabulary filter needs to be exposed to appear in the form (click on the filter, then click on 'Expose this filter to visitors, to allow them to change it'). Then all vocabularies should appear in the filter form.


Adding Vue.js to my theme with Webpack not working I am trying adding Vue.js into my Drupal 8 theme with my Webpack setup (which I had already working).

It's all compiling fine with Webpack, without errors after my npm script npm run build.

In my index.js I have:

import './styles.css';
import Vue from 'vue'
import App from './App.vue'

Vue.config.productionTip = false

new Vue({
  render: h => h(App)
}).$mount('#app')

In my App.vue I have:

<template>
  <div id="app">
    <HelloWorld msg="Coming Soon: Near-Earth Objects"/>
  </div>
</template>

<script>
  import HelloWorld from './components/HelloWorld.vue'

  export default {
    name: 'app',
    components: {
      HelloWorld
    }
  }
</script>

<style>

</style>

In my ./components folder I have HelloWorld.vue

First I am trying now to render my Vue component inside header.html.twig like

<hello-world></hello-world>

My thoughts are, by the element  in page.html.twig I can show, arrange and position all my Vue.js components where I want. Is that correct?

But why is my component not showing up?

Update:

I figured out. My webpack.config.js is splitting Vue into /themes/custom/my_theme/dist/vendors~main.bundle.js. By this setting:

config.optimization = {
      splitChunks: {
        chunks: "all"
      },

What is the purpose of this? Isn't it better to compile it all into the same file main.bundle.js?

I recommend looking into the Decoupled Pages module which can make integrating Vue.js simpler.


Migrate multiselect taxonomy values from node with csv I want to import companies with csv into Drupal 8 with migrate_source_csv module.

CSV:

company_name,company_categories,company_size
"Dummy Name","Category 1";"Category 2","2 people"

How to accomplish?
Do I need an other plugin: explode?

    process:
      field_categories:
        plugin: explode
           source: company_categories
           delimiter: ';'
        plugin: entity_generate
        source: company_categories

I also found this: https://www.drupal.org/node/2129651#handling_multiple

I found it myself.
This is working for me:

process:
  title: title
  body: body
  field_company:
    -
      plugin: explode
      source: categories
      limit: 100
      delimiter: ;
    -
      plugin: entity_generate
      ignore_case: true
  type:
    plugin: default_value
    default_value: company

and a CSV like this:

id,title,body,categories
6,company,body text,"cat1, some text;cat1, some other text"


Is there a way to display SCALD image and have it link to outside website: Drupal 7 I have created a content type that uses a SCALD atom image field.  When that content type is displayed on my site, I want the image to link to an outside website if it is clicked upon.  I don't want to use a view to make this action happen.

I can easily add a URL field to my SCALD Image atom, but I don't know how to make this link work when the image is clicked on ONLY in the full node view.

Could someone suggest a solution?

I gave the module Image Link Formatter a try, but I could not get it to work and I filed this bug report: https://www.drupal.org/project/image_link_formatter/issues/2970937

Instead I used the Linked Field module:https://www.drupal.org/project/linked_field plus Token: https://www.drupal.org/project/token.

To make this work, I have a content type that uses a SCALD Atom for the image field and I have a separate field to add a URL.  Under the Manage Display tab for your content type, go to the Link to Content section (click on the gear wheel) and opt to Link this Field. You will be presented with a Destination field.

You'll need to browse the available tokens to find the destination field that pertains to your content type.  Make sure to use the one with dashes instead of underscores and in the case of a URL, you'll need to append the token with :url.  Mine looked like this:

[node:field-default-content-link-url:url]

If the field on my content type is populated, it links to the website.  If it is empty, the image is not formatted as a link.


How to produce markup from a custom views field (FieldPluginBase based) render method in D8? I've created a custom views field following the excelent Creating a custom Views field in Drupal 8 guide. The render method returns the desired output, except that it's being sanitized somewhere down the line and thus the html markup comes out as plain text on the page.

I'd rather put the html markup into the theme, but there doesn't seem to be such thing as

views-view-field-<fieldname>.html.twig

in Drupal8 ?

I can output HTML using my render method. Take a look:

  /**
   * {@inheritdoc}
   */
  public function render(ResultRow $values) {

    $field_abnormal_category = $this->view->field['field_abnormal_category']->original_value->__toString();

    if($field_abnormal_category == 'No') {
      $field_category_image = $this->view->field['field_category_image']->original_value->__toString();
    }
    else {
      $field_category_image = '';
    }

    return [
    '#type' => 'inline_template',
    '#template' => $field_category_image
    ];

  }


drupal 7 comment moderation modules I am looking for modules that can extend drupal 7 comment admin.
For example, I want to be able to set different statues for comments, like Approved, pending, spam and unapproved.
And maybe comment moderation history, in comment admin it should show a log of who changes the text, who changes status of a comment. the only module i can find is for drupal 6.

You should be able to "set different statuses for comments, like approved, pending, spam and unapproved" using Flags, which are D7 only.

I could not find anything that adds revisions to comments, or comments to flag changes.

The workflow module allows you to assign states to nodes, and comment each state change, but the comment_workflow module is available only for D5. Hopefully someone else might have better news.


Date Time field machine name/view mode for theming using paragraphs I am using Drupal 8 core DateTime Range module and Date module in core to list date start and end date.

I have set various criteria and allowed content editors to set date/time under certain ranges with paragraphs module for events.

Event only has date.
Created a date field using paragraphs module.
Event has date with start and end time.
Created a date field and datetime range field with only time ranges using paragraphs module.
Event has start and end date.
Created a datetime range fields using paragraphs with date ranges using paragraphs m.
Event has start and end date with time.
Created two datetime field one with date ranges and another with time ranges using paragraphs.

Now for theming I need to target each field separately as each field represents different format and style. However while using paragraphs inside node and adding any one of datetime field to node using paragraphs does not allow me to determine which field it is or what view mode that datetime field is using.

This makes it difficult to theme those fields individually/seperately.

Also, while using views pages and rendering those datetime field on a pager based page view, same, it does not show what machine name/view mode its using for paragraphs.

I implemented hook_theme_suggestions_time_alter function to determine the machine name and view mode, but no information was available for said field.

I would like to each part of field in datetime field separately and differently while rendering using views and differently while rendering in full view mode of node.

The best way to Debug this is to enable twig debug
open up or create sites/default/services.yml

change

 http.response.debug_cacheability_headers: true
 twig.config:
   auto_reload: true
   cache: true
   debug: true

once done run drush cr or clear your cache

then go to the page with the paragraphs on them and inspect the element in chrome
you will see ...
some thing like

<!-- FILE NAME SUGGESTIONS:
  * field--paragraph--field-range--event.html.twig
  * field--paragraph--field-range.html.twig
  * field--paragraph--event.html.twig
  * field--field-range.html.twig
  * field--daterange.html.twig
  x field.html.twig
  -->

then theme the new field templates to your liking


Restrict comments on nodes of a content type based on user role I am building a site in Drupal, where there are 2 different types of registered users. Let us call them basic users and premium users. These could be roles, or groups, or something else.

Authorized users will be able to publish pages with simple content and comments underneath. All pages are viewable publicly, even by non registered users and so are the comments.

Only registered users should be able to post comments.

What I would like is for some pages to allow comments only from premium users. So, there would be two categories of pages. Again let us call them basic pages and premium pages.

The permissions would be as follows:

Basic pages
READ: all
COMMENT: basic users, premium users

Premium pages
READ: all
COMMENT: premium users

Any help/pointers would be appreciated, as I have limited experience with Drupal.

You can perform a hook_form_alter on the comment form in a custom module. This will allow you to change the form so it checks if the current user has a premium role. If the acting user has the premium role the option to submit a comment is displayed. If they do not show a message like "only premium members can comment".

MODULENAME_form_alter(&$form, &$form_state, $form_id) {
if ( $form_id == 'comment_form') {
  global $user;
   if (!user_role('Premium'){
    // Form alter here to unset comment form and show "only premium members can comment"
    unset($form['author']);
    unset($form['subject']);
    unset($form['comment_body']);
    unset($form['actions']['submit'] );
    unset($form['actions']['preview'] );
    print "Only Premium members can comment";
  }
 }
};

You can look in comment.module for the default code for comments....


Node create progrmatically with multiselect I am creating a node progrmatically.

here is my code..

     $node = new stdClass();
      $node->type=$type;
      $node->status = 1;
      $node->uid = $uid;

        foreach($_POST as $field_name=>$field_value) {
          $node->$field_name=array('und'=>array(0=>array('value'=>$field_value)));

        }
node_save($node);

this is working fine. if we have a single value for each field.. Now i have a filed having select box with multiple select. How to save them.

Thanks

You just need to keep adding new values underneath the language array, for example:

foreach ($_POST as $field_name => $field_value) {
  $node->{$field_name}[LANGUAGE_NONE][]['value'] = $field_value;
}


How to check validity of one time login url by Drupal 7 Services module? I am developing a client side application and using AngularJS for this. I successfully registered a user.

Now my problem is that I cannot find a way to check the validity of one time login url or any end point provided by Services module?

Anybody an idea?

Note: I have not tried this solution myself, but think it should work.

Some concepts about one time login URL

You cannot just visit the URL (or even request it via a service, or any other request like curl or wget) to check if it is valid. As the name it is for one time use only.
It is valid for 24 hours from time it is generated.

These couple of things need to be taken into consideration while validating the login URL.

The URL where the check (and login) of a user happens is user/reset/%/%/%, where the dynamic arguments are in order : user id, timestamp of the one time login url creation, and the hash of the password.

To implement your solution, I suggest you to create a custom service endpoint and implement the logic which is implemented in user_pass_reset.
You can just skip the part where the function actually logs the user in.


How to use jquery ui tooltip in Drupal7? I want to use jQuery UI tooltip in my Drupal7 website.

I have installed 'jquery-update' and 'jquery-plugins' module and added

$(function() {
   $("a").tooltip();
});

in js file of my template. But firebug gives this error to me:

$(...).tooltip is not a function

that show the website doesn't find tooltip js file.

Should I do something more to use tooltip jquery ?

Try adding:

drupal_add_library('system', 'ui.tooltip');

in your theme template.php file

/**
 * Implements hook_preprocess_html
 */
THEME_preprocess_html(&$variables){
  drupal_add_library('system', 'ui.tooltip');
}

That should ensure the library is available. You can add various conditions to make it page specific as required.


Unable to save title after hook_form_alter() I have a node form for a specific content type that has many fields.  I want to move these fields into field sets, and wrap that in a class to make it work with my theme.  I've done this with hook_form_alter(), and everything is fine, for the most part.  I am able to save fields, and the form is displayed correctly.

However, whenever I submit the node edit form, the title flips back to 'Array' and gives me the following errors:

Warning: mb_strlen() expects parameter 1 to be string, array given in drupal_strlen() (line 478 of mysite/includes/unicode.inc).
Notice: Array to string conversion in devel_watchdog() (line 531 of mysite/sites/all/modules/devel/devel.module).
Warning: htmlspecialchars() expects parameter 1 to be string, array given in check_plain() (line 1565 of mysite/includes/bootstrap.inc).

Here is my implementation of hook_form_alter().  It's very simple; all it does is set up the fieldsets, copy the needed form elements into them, and then unset the original element:

/**
 * Implements hook_form_id_alter()
**/
function my_module_form_alter(&$form, &$form_state, $form_id) {
  switch ($form_id) {
    case 'my_content_type_node_form':
      $form['fieldset1'] = array(
        '#type' => 'fieldset',
        '#title' => t('Fieldset 1'),
        '#collapsible' => TRUE,
        '#collapsed' => FALSE,
        '#prefix' => '
',
        '#suffix' => '
',
      );
      $form['fieldset2'] = array(
        '#type' => 'fieldset',
        '#title' => t('Fieldset 2'),
        '#collapsible' => TRUE,
        '#collapsed' => FALSE,
        '#prefix' => '
',
        '#suffix' => '
',
      );
      $form['fieldset3'] = array(
        '#type' => 'fieldset',
        '#title' => t('Fieldset 3'),
        '#collapsible' => TRUE,
        '#collapsed' => FALSE,
        '#prefix' => '
',
        '#suffix' => '
',
      );

      //move elements into fieldset1
      $form['fieldset1']['title'] = $form['title'];
      unset($form['title']);

      $form['fieldset1']['field_origin_location'] = $form['field_origin_location'];
      unset($form['field_origin_location']);

      $form['fieldset1']['field_task_override'] = $form['field_task_override'];
      unset($form['field_task_override']);

      //move elements into fieldset2
      $form['fieldset2']['field_equipment'] = $form['field_equipment'];
      unset($form['field_equipment']);

      //move elements into fieldset3
      $form['fieldset3']['field_additional_troubles'] = $form['field_additional_troubles'];
      unset($form['field_additional_troubles']);

      $form['fieldset3']['field_resolution'] = $form['field_resolution'];
      unset($form['field_resolution']);

      $form['fieldset3']['field_repair_parts'] = $form['field_repair_parts'];
      unset($form['field_repair_parts']);

      $form['seperator'] = array(
        '#type' => 'markup',
        '#markup' => '

',
      );
    break;
  }
}

When I run a debugger and step through it at the time of the error, I see that $form_state['node']->title is set to 'Array', but otherwise I can't determine what is setting it to an array.

The error disappears when this form_alter function is commented out or the module is disabled, so I know that something within this function is triggering the error.

Does anyone have clues of where to start looking to solve this issue?  Is there, perhaps, some other thing that I need to do in order to move the form elements?  Maybe I am missing a step?  Or, is this maybe coming from another module's code and if so, is there a method to find that module?

Solved.

When I posted my code on here, I realized that I had a typo in Fieldset 2, where I was using '$form['device']['title'] = ...' instead of '$form['device']['field_equipment'] = ...'

After fixing the typo, everything is working as normal.


Using custom author name in a node instead of author field I have a display name field I created for my users (available in account settings). I'd like to display the display name in the node if the person authored that node. I see I have an author field I can use... but that displays the login of the user, while I want to display their pretty display name that I setup instead. Is there a way to include this field instead of the author field?

In views it's easy to do, but I'm trying to use the field in a node.

There is a module for it. You can choose which custom user field to use. This module only works for drupal 6 and drupal 7 https://www.drupal.org/project/realname


How to change the widget of a multimedia asset from media browser to multiupload On Drupal 7 I installed and enabled the multiupload_imagefield_widget
Now I would like to alter the widget type for the news articles from "Media Broswer" to "Multiupload".
I understand that I can add a new field and delete the old one, but I have a lot of previous articles with uploaded images to them.
Or maybe I'm looking at this the wrong way?

Any help would be greatly appreciated.

Edit: screenhots

Did you check the field widget and change it from media browser to multiupload?
You can change your widget without affecting the other nodes which has already images on it.

hope it helps.


Override of commerce-order-receipt.html.twig template not working? My theme is using Bootstrap barrio theme (bootstrap_barrio) as a base theme. I'm trying to override Drupal commerce template modules/contrib/commerce/modules/order/templates/commerce-order-receipt.html.twig and it's not working for me. Even I copied that file to drupal/web/themes/my_theme/templates ,cleared the cache, Commerce is still using original template file from commerce module.
What puzzles me is that base Barrio theme also has that template and it's also not used?!?
Do I have to set somewhere what theme should be used for email templates or something? Overriding other modules templates (including commerce templates) works fine. Documentation says "The email can be customized by overriding the Twig template in your theme just as you would any other template".

Figured out what was the problem. I had to select my theme for sending emails on
Configure the Mail System admin page.
/admin/config/system/mailsystem
Other way some other theme is used.


using hook_node_submit to create an alternate upload method We have a problem where we are uploading a number of files on a regular basis, the files need to be kept outside of the document root.

Each file is attached to a node.

I created a folder /documentstore and all the files are uploaded to there.

To enable submission of documents I added a symlink sites/default/files/documentstore -> /documentstore

Unfortunately drupal does not allow files uploads to a symlinked folder :( I have modified core to solve the issue as a temporary fix.

For a more permanent fix I'd like to add a module hook node submission and then copy the file to the symlinked folder avoiding drupals core upload function. I am trying to use hook_node_submit().

I would like some hints as to how I can go about this or whether there is a better way to store files outside of the docroot (yes it must be done that way)

Please use the copy function to store the files to different location other than drupal root or files folder.

Alter hook_node_submit function using copy instead of file_save_upload.

Try referring Drupal S3 module code, which copies the files to AWS S3 storage.


How can I exclude content older than... with Views I'm trying to get my head around a Views setting, I can't find how to exclude older than two years old content from Views. I know it has to be somewhere in the Filter section. I would expect this to work, but it doesn't...

Content: Date (field_publication_date) - From date <= now + 2 year

I'm doing something wrong, can someone please help me out?

Thanks a lot!

PS: I'm on Drupal 6...

The Show nodes relative to a date with Views page explains how to do it. Did you try post date on Filter criteria with the following configuration?

?


Amazon S3 for Stage / Production only? Is it possible to use the Amazon S3 module for stage / production only? The site I'm building, is using features. So when I export my fields for the content types, I either have the option to select Local File Storage, or the S3 File System.

I thought I had a solution, where on stage / prod, I would hide the local file system wrapper, but the issue turns out, that unless I select the S3 checkbox when editing a field in the content type, it doesn't default to S3.

I could go thru and select this option for all file fields, but then on the downside, dev will be broken.

My only other option, which I haven't tried, is setting a global variable via settings, and then using a if/else logic in the features for each file field, to pre-set the upload location for that field.

Ahhh, so messy.

Anyone come up with a clever solution in the pasts? That allows me to force files to be uploaded to S3 for stage/prod and local file system when running via local or dev?

Update:

Okay, so I noticed that features has the following hook:

hook_field_default_field_bases_alter()

So, in my module, I'm using that hook, determining if the env should be serving the files via local storage, or s3. If it's s3, I then alter it from 'public' to 's3'

I went and just to be safe, re-exported all my features, and made sure that by default, it was set to public, an not s3. Now, all my env's are using the correct storage location. I'm still not sold that what I'm doing is the best solution, but it is working. Any thoughts?

$use_s3f3 = variable_get('image_save_s3f3', FALSE);

// Only on stage/uat/prod, do we want to use s3 as the file storage engine.
if ($use_s3f3 === TRUE) {
 foreach($fields as $key => $item) {
   if (isset($item['settings']['uri_scheme']) && $item['settings']['uri_scheme'] === 'public') {
     $fields[$key]['settings']['uri_scheme'] = 's3';
   }
 }
}

I made a similar patch to the Amazon S3 module: "New variable to override file field URI scheme per environment"  https://www.drupal.org/node/2422977#comment-9602981
This patch was adopted by the module, and is now the approved way of solving the OP's problem using the Drupal 7 Amazon S3 module. This is the issue I wrote on Drupal.org.

Problem/Motivation
When using Features (or hook_field_default_field_bases() directly) to export file field definitions, the Upload destination is included. This can already be handled in a custom module by implementing hook_field_default_field_bases_alter(), and checking $conf (set in env-specific settings files, etc). But it would be nice to include support directly in amazons3.module.
Proposed resolution
Implement hook_field_default_field_bases_alter(), and check for a namespaced variable amazons3_file_uri_scheme_override. This variable can be added to environment-specific sites/*/settings*.php files to allow certain environments to upload to S3 while other environments upload to whatever the defined/exported (public or private) URI scheme is.
User interface changes
The only change in the UI would be that the field settings reflect the URI scheme defined either by the exported field bases or the variable (on environments where that's present).
API changes
No API changes, but the patch documents usage of the variable.

Note the module's README.md also now contains this additional line:

When using Features to export field definitions, the Upload destination is included. If you want to override this (for example, in a multi-environment workflow), use the 'amazons3_file_uri_scheme_override' variable. See amazons3_field_default_field_bases_alter() for documentation.

Here is the relevant documentation of amazons3_field_default_field_bases_alter that README note is referring to:
* Allows a variable to override all exported field bases to use 'Amazon S3' as
* the Upload destination. For example this can be added to environment-specific
* Drupal settings files, to allow certain environments to upload to S3 while
* other environments upload to the exported (public or private) URI scheme:
* @code
* $conf['amazons3_file_uri_scheme_override'] = 's3';
* @endcode

Also note the variable is not deleted by amazons3_uninstall() because it's only valid use case is being defined in $conf (otherwise just change the field setting).


The directory public://xmlsitemap was not found or is not writable by the server I have just installed XML Sitemap on a EC2 drupal 8 instance. I am seeing the following error message in the admin report status page:

XML sitemap cache directory
Not found or not writable
The directory public://xmlsitemap was not found or is not writable by the server.
See http://drupal.org/node/34025 for more information.

The provided link is broken. I have done some reading and created a /xmlsitemap directory in /var/www/html (which is the root of my drupal installation). I chmod it to give rwx access to everyone (a+).

But, the issue remains. I cannot generate the cache files.

How can I solve this issue?

I found the file_public_path value from the /admin/config/media/file-system page. It was set to sites/default/files, relative to the installation path.

I checked permissions and noticed some writting permissions were missing (the directory was already created). I sudo chmod a+w xmlsitemap/ and that solved the issue.


How to configure Trusted_Host_Settings for subdomains? How to configure Trusted_Host_Settings for subdomains?

The documentation does not give an example of a subdomain.

For example, I have an Add-On domain that points to website.info, but the subdomain is mainsite.com/website.info

It's actually documented in settings.php file as in examples:

Drupal 8.5.x
https://cgit.drupalcode.org/drupal/tree/sites/default/default.settings.php?h=8.5.x#n712

<?php
$settings['trusted_host_patterns'] = array(
  '^example\.com$',           // Matches naked domain only.
  '^.+\.example\.com$',       // Matches any subdomains.
  '^subdomain\.example\.com', // Matches a specific subdomain.
);

You can easily define any naked or sub-domain, as long as defined regex pattern matches them correctly.


Location of data directories under AEgir on Debian I've got an out-of-the-box AEgir installation (Apache2, MySQL) running on Debian on a VirtualBox machine. I'd like to move the site data directories off the virtual drive onto my host's drive and use VirtualBox's shared folders to access them.

Which directories do I need to move?

/var/aegir/platforms is already on the host.

/var/lib/mysql holds the sites, so I will move that.

/var/aegir/clients would also need to be moved.

Are there any others?

/var/aegir/config and /var/aegir/backups

Or you could just move the entire /var/aegir/ tree


Error programmaticaly adding image to node using file_copy I am trying to add an image to the article content type in Drupal 7, When I create a simple note i.e. article it works , but when I try to add the image to the article it gives an error

  The specified file
  E:\WS_IntPOC_Test4\sites\all\modules\my_module\errorwinmobilesdk.jpg
  could not be copied, because the destination is invalid. More
  information is available in the system log

In log I can see the message as

  File
  E:\WS_IntPOC_Test4\sites\all\modules\my_module\errorwinmobilesdk.jpg
  could not be copied, because the destination is invalid. This is often
  caused by improper use of file_copy() or a missing stream wrapper.

I have checked the wrapper public and private is there. As if I created the Article from GUI. It is created with image loaded in public folder. Please help

$body_text = 'node body text';

  $node = new stdClass();
  $node->type = 'article';
  node_object_prepare($node);

  $node->title    = 'Node Created Programmatically on ' . date('c');
  $node->language = LANGUAGE_NONE;

  $node->body[$node->language][0]['value']   = $body_text;
  $node->body[$node->language][0]['summary'] = text_summary($body_text);
  $node->body[$node->language][0]['format']  = 'filtered_html';

// Some file on our system

$path ='E:\WS_IntPOCTest4\sites\all\modules\my_module\errorwinmobilesdk.jpg' ;
$file = (object) array(
          'uid' => 1,
          'uri' => $path,
          'filemime' => file_get_mimetype($path),
          'status' => 1,
 );

//$file = file_copy($file, 'public://'); // Save the file to the root of the files
$file = file_copy($file);
$node->field_image[LANGUAGE_NONE][0] = (array)$file;
//associate the file object with the image field:
node_save($node);

You can try this code:

//$filepath = drupal_realpath('misc/image.jpeg');
 [**UPDATED ANSWER**:]
 $filepath =  $_SERVER['DOCUMENT_ROOT'].base_path() .drupal_get_path('module','payment_details').'/MDSO_20.jpg';

$file = (object) array(
       'uid' => 1,
       'uri' => $filepath,
       'filemime' => file_get_mimetype($filepath),
       'status' => 1,
  );
  $file = file_copy($file, 'public://');
  $node->field_image[LANGUAGE_NONE][0] = (array)$file;
  node_save($node);

Hope this works for you :)

For me it created a node as you below :)


Duplicate view results when adding a filter related to field with multiple values? I have a view to list the Voucher content type. I added a filter: Configure filter criterion: Content: Voucher codes (field_voucher_code) NOT EMPTY.

The idea is to show the node only if its field field_voucher_code is not empty

The field_voucher_code is field which has set the Number of values to 10 at admin/structure/types/manage/vouchers/fields/field_voucher_code

The problem is that the view is duplicating each as many time as values has in its field field_voucher_code.

How can I eliminate the duplicates?

You can do this by enabling Aggregation or set distinct in Query settings

Go to your View->Advanced->Use Aggregation -> set YES
Next in your field filter criteria chose - Count DISTINCT

One more way -
  1. Go to your View->Advanced->Query Settings -> check DISTINCT