How to track users actions on a form in my website I read some post about "how to track..." but i didn't find my answer. I don't want to track the user loggin or how many time a user click on a link but what i would like to accomplish is:

Track my user (anonymous or authenticated) to know if they failed to fulfill a form (failed = quit before submitting the form)
Have a rate about each form who tell me, for example : 30% of users who begun the register form, stopped before submiting
And more, knowing which fields were fulfilled before he quit.

My purpose is to help me to:

Understand which process, forms are misunderstood in my website
Maybe, knowing exactly which fields in my form (which label) are misunderstood (thanks to the fact that i could know which fields were empty when he quit)

I'm not a pro of Google analytic but i don't think so he can do that.
What is the better approach for me to do that?

Thanks,

PHP saves data once you click the submit button, so finding which fields they filled before quitting might not be that straight forward.
But you can always see how many times form was loaded and number of submitted entries to find the ratio.


Only one organic group id / name is shown in content listing I want to create a block/page with a general content listing of all the content in the different organic groups.

Problem is the specific nodes only show one group id / group name even though it belongs to multiple groups.

To show the group name I used 'OG membership: Group Node from OG membership' relation.

Is there a way to do is with basic view functions. I suppose it can be done using a PHP field but I prefere the basic methods if they exist.

Found a solution: Include 'Content: group audience'


entityform email multilingual I am using drupal 7 and entityform module and also using this : https://www.drupal.org/node/1679794
instruction to sending email after submitting form.
the only problem I have is I want my email body to be translatable in different languages.
I already translated form labels here :

admin/config/regional/translate/translate

I also should add my form is a custom form not user sign up form ! I already know that I can change email body of sign up email here :
admin/config/regional/i18n/variable

using rules module and After saving a new entityform submission event was also useless. it's like the event is not equal to form submission event . happens nothing after form submission.
I also thought it would be helpful if I just could add some varibles to drupal default variables ! but I don't know how .

This is not answer to your question - but a tip on the way...

There is a good possibility to use Rules + some rules contrib module to do this, maybe in a better way because rules is also able to send node-fields-values trough Tokens id, and also capable to act on site-current-user:language from the users own default language and send mail in preferred user language. Rules can be triggered on different actions at the site.
One of my Rules setting sending mail, where all fields-name are translated together with the fields value, based on user-default-language settings.


Status report: Twitter module using unautheticated api So, I'm getting kind of a strange error in my status report about my twitter module. I get an error that the twitter pull authentication is using an unauthorized api" Below that it says that the Twitter modules doesn't have any authorized accounts, and that I should add an authorized account via the accounts page. The issue is that I have authorized accounts attached.

I'm using twitter module 6.2 and twitter pull version 7-2.0alpha3.

callback url is: twitter/oauth
the host is : twitter.com
and the api is: https://api.twitter.com

Not sure if this an incompatibility between versions, or what the problem is here. How to fix?

Twitter module was misconfigured, not updated.


Programmatically set view header I know there is a post on how to set a view header/footer value here,
but how do I set a view header/footer without having to create it through views UI first?

The reason why I want to implement a view header programmatically is because (a) I want to write php code in it, by leveraging the Drupal's API, something that is not so convenient in a textarea field, like the one that the views UI provides -and any other textarea field- plus the fact that some functions may never get invoked and (b) because I want to conditionally set/unset the view header/footer.

After some research I managed to answer my own question by implementing the hook_views_pre_view in my custom module. The method set_item is used to set the configuration of an item (field/sort/filter/etc) on a given display. The $print variable bares the content to be rendered in the view header, it is just an example and it can be replaced by anything. Apparently now I can take advantage of the Drupal API or even set/unset any view item conditionally.

/**
 * Implementation of hook_views_pre_view.
 */
function my_module_views_pre_view(&$view, &$display_id, &$args) {

  $path = $_GET['q'];
  // Construct the print link.
  $print = l(t('Display a printer-friendly version of this page'), '/print/' . $path . '/print-friendly',  array(
    'attributes' => array(
      'class' => array('print-friendly'),
      'target' => '_blank',
      'title'=> t('Display a printer-friendly version of this page.'),
      ),
    )
  );

  if ($view->name == 'my_view_name' && $display_id == 'my_view_display') {
    // View's header declaration.
    $item = array(
      'id' => 'area',
      'table' => 'views',
      'field' => 'area',
      'relationship' => 'none',
      'group_type' => 'group',
      'ui_name' => '',
      'label' => '',
      'empty' => 0,
      'content' => $print,
      'format' => 'filtered_html',
      'tokenize' => 0,
    );
    // Render the header.
    $view->set_item($display_id, 'header', 'area', $item);
  }
}


How to edit personal contact form e-mail content - Drupal 7 I looked everywhere in my admin for this. Can it be achieved via the admin panel or do I have to make a custom module?

I can't seem to find an adequate code snippet on Drupal Answers. Help would be greatly appreciated.

I don't believe that this can be done through the admin panel though it is quite easy through a module using hook_mail_alter()

if it is the drupal core contact form then use this in YOUR_MODULE.module

function YOUR_MODULE_mail_alter(&$message) {
  if ($message['id'] == 'contact_page_mail') {
    //MODIFY THE MESSAGE HERE
  }
}

(always remember to clear caches after adding a hook)

It is a good idea to get the devel module and add

dpm($message);

see what the variables are that you want to modify and enjoy.


When to use Views attachments vs. content panes? Up until now, I've always used content panes provided by Views in Panels to accomplish tasks like "Related content" and "Additional information about ABC."  I just realized that Views also provides an attachment display, which as far as I can tell seems to be similar to a content pane except it doesn't require Panels.

However, if I'm already using Panels, are there any use cases where I would be better off using an attachment instead of a content pane, or are these basically the same thing?

Attachments can inherit the exposed filters of the display they are attached to.


Logo doesn't appear on the Seven theme on a fresh installation I've got a fresh install of D7.9 and have enabled the 'Seven' theme which has an option to override the default logo in Appearance -> Settings. I have uploaded a logo file and can see it via ftp but it does not show up on the site. Have I missed a step or does this theme not support logos out of the box?

The logo for the theme selected is added to a php serialized array in the system table under the info column. It is advisable to not use FTP to upload the image but instead of the Admin UI under the themes section to do so.

Click Appearence > Seven 7.8 > Settings

Then scroll to "Logo image settings" and uncheck "Use the default logo".

Click "Choose File" and pick the logo image file.

Click "Save configuration" and your logo should show up in the site. If caching is enabled, the caches might have to be cleared.

Edit: The page.tpl.php file for the seven theme does not have a section to display the logo. Not sure if this is a bug or just a design decision. Either way, there is no way to show a logo in the seven theme at this time.


Menu synchronization I am building a site with main-menu at header and side-bar-menu. For each main-menu entry there will be some sub-menus. And same sub-menu will be displayed into side-bar-menu according to the portal we are in. Is it any way (or module) to synchronized main-menu->sub-menu and side-bar-menu so that in case we need to change menu, we can change it in one place and reflects in main-menu and side-bar-menu.

Thank you.

Your main menu can be 1 level deeps links to content. You just maintain these links as your top level content links as needed in the Menu configuration page.

For each main-menu item, make a new Menu where you actually set the link from your node edit pages.

Use MenuBlock and like the Context module (or just default the Block UI, eww) set each sidebar menublock to appear for the appropriate main-menu url path.

-- OR TRY --

You can try to make main-menu your site tree of all links, then use 1 menu-block set to 2-level deep starting point based on the url path.

I usually try to do the 2nd option .... then find its inflexible at some point and need a collection of menus and menu_blocks as I first described which from experience works better. Especially for cross-linked content (you may get the wrong menu block in the 2nd approach, for cross linked content as it shows the first menublock that menu_block finds the link within).


Combining fields in preprocess template I want to combine two fields (say first name and last name) of a particular type of node so that the name displays correctly and I still have the individual fields to work with in different areas.

I saw this post What is best way to combine multiple fields in template preprocess?  that explains how to combine two fields, but one I declare this new combined variable, how to I get it to display as the node?

Do I need to edit my node.tpl file?  Should I have a node.tpl for this particular content type?

Once you have preprocessed your variables in theme_preprocess_node() you can print them in node.tpl.php

The best practices would imply to declare one node.tpl.php per content type like this : node--my-content-type.tpl.php replacing my-content-type by the name of your own content.

In theme_preprocess_node() the best way to get the value of a field would be like this :
In template.php the first function is only here so you can have one preprocess function per content type.

/**
 * Override or insert variables into the node templates.
 *
 * @param $vars
 *   An array of variables to pass to the theme template.
 * @param $hook
 *   The name of the template being rendered ("node" in this case.)
 */
function mytheme_preprocess_node(&$vars, $hook) {
  // Optionally, run node-type-specific preprocess functions, like
  // mytheme_preprocess_node_page() or mytheme_preprocess_node_story().
  $function = __FUNCTION__ . '_' . $vars['node']->type;
  if (function_exists($function)) {
    $function($vars, $hook);
  }
}

Then you can declare your function for your content type and get the value of your fields with field_get_items() and field_view_value() in order to only get the value and not all the divs all around the field value.

/**
 * Override or insert variables into the node templates.
 *
 * @param $vars
 *   An array of variables to pass to the theme template.
 * @param $hook
 *   The name of the template being rendered ("node" in this case.)
 */
function mytheme_preprocess_node_my_content_type(&$vars, $hook) {
  $node = &$vars['node'];
  $first_name = field_get_items('node', $node, 'field_first_name');
  $last_name = field_get_items('node', $node, 'field_last_name');
  $vars['first_name'] = field_view_value('node', $node, 'field_first_name', $first_name[0]);
  $vars['first_name'] = field_view_value('node', $node, 'field_last_name', $last_name[0]);
}

and then in your node--my-content-type.tpl.php you can print your variable like this :

<?php print render($first_name); ?> <?php print render($last_name); ?>


Aggregator with custom RSS field I have a simple RSS feed I am importing via core Aggregator module in Drupal 8.5.  One specific field in the Item can't be accessed by Views, and it's critical for display.  I'm relying on hacky approach right now, but would love to do it right.

What's the process in getting a specific ATOM Rss field registered so that it appears in Views UI?  Can't find any info on building custom Aggregator plugins for fetcher/parser/processors.

Anyone have other thoughts on how to approach?

Thanks in advance for all insight.

PTG

Aggregator offer the possibility to add custom fetch/parser/process to update/override/remove actions on the global process.

For example I managed to make aggregator deal with enclose url image.
Their are several ways to do it with Drupal 8. I used a very simple one : Annotation.

/**
 * Defines a default parser implementation.
 *
 * Parses RSS, Atom and RDF feeds.
 *
 * @AggregatorParser(
 *   id = "xxxxx_aggregator",
 *   title = @Translation("XXXX parser"),
 *   description = @Translation("Custom parser for RSS enclosure tag.")
 * )
 */
class CustomParser extends DefaultParser {

  /**
   * Override default parser to add the enclosure attribute to feed item
   * {@inheritdoc}
   */
  public function parse(FeedInterface $feed) {

    parent::parse($feed);
    // your code...
  }

}

In this given example, using @AggregatorParser, I allow Aggregator to detect and use another PARSER, my custom, which is extending the aggregator's default.

Do not forget to add it in the correct needed path. Here its : namespace Drupal\xxxxx_aggregator\Plugin\aggregator\parser;

You will be able to see and enable it on the aggregator feed admin page.

For deeper informations you can analyse the aggregation process throught the module's files, this contrib module use plugin management and hooks api. AggregatorPluginManager.php


Clean GET parameters after submitting a 'GET' form How to remove form_build_id, form_id, op parameters that are added to a URL after submitting a form using GET method in Drupal 8?

FormState::cleanValues does exactly that:

  Removes internal Form API elements and buttons from submitted form values.

  This function can be used when a module wants to store all submitted form values, for example, by serializing them into a single database column. In such cases, all internal Form API values and all form button elements should not be contained, and this function allows their removal before the module proceeds to storage. Next to button elements, the following internal values are removed by default.

  form_id
  form_token
  form_build_id
  op

But as you're not POSTing the form you can't really use it. Two options spring to mind:

Implement your own cleaning method. This might be tricky as you don't have the form fields to work with so unless you have a list of known good fields available, there's always the possibility you'll include something you don't mean to
Change your form's flow to Post/Redirect/Get (PRG). The steps are roughly:

Change the form method to POST
In the submit handler:

Use FormState::cleanValues to clean the input
Build a new Url with the desired redirect path, and query options made up of the clean form state values
Use $form_state->setRedirect($url); to redirect the user to the new URL

From the user's point of view, nothing really changes. They still end up at the same URL, just without the undesired query args.


Include a PHP file located in the home directory in a module How can I include a PHP file located in my Drupal's home directory from a module?

Drupal 7 defines the constant DRUPAL_ROOT, which contains the name of the directory where Drupal is installed. It is used from Drupal functions, such as module_load_include() in a way similar to the following one:

if (function_exists('drupal_get_path')) {
  $file = DRUPAL_ROOT . '/' . drupal_get_path('module', $module) . "/$name.$type";
  if (is_file($file)) {
    require_once $file;
    return $file;
  }
}

In your case, you should use the following code:

require_once DRUPAL_ROOT . "/$filename";

The variable $filename contains the name of the file to load.


How to change the theme for a particular admin page in drupal? I have a page with url ?q=admin/settings/history . Is there any way by which I can change the template for this page alone. I tried using hook_preprocess_page but I was unable to change the layout of page. Could someone please lead me in the right direction?

Yet another solution, in a couple of lines of code, is:

hook_custom_theme

  Return the machine-readable name of the theme to use for the current
  page. This hook can be used to dynamically set the theme for the
  current page request. It should be used by modules which need to
  override the theme based on dynamic conditions

e.g

/**
 * Implements hook_custom_theme
 */
function MYMODULE_custom_theme() {
  // Set path specific theme.
  if (current_path() == 'admin/settings/history') {
    return variable_get('custom_theme', 'theme_name');
  }
}

Core example: system_custom_theme

Update: To use a specific template you can override page.tpl.php

copy page.tpl.php to page--admin--settings--history.tpl.php, clear caches (theme registry) and use that.

More info: https://drupal.org/node/1089656


How do I alter/change the "field is required" message? I have below code

$form['name'] = [
      '#type' => 'textfield',
      //'#title' => $this->t('Email'),
      '#size' => 60,
      '#maxlength' => USERNAME_MAX_LENGTH,
      '#default_value' => $form_state->getValue('name', ''),
      '#required' => TRUE,
      '#attributes' => [
        'placeholder' => $this->t('Email'),
        'autocorrect' => 'none',
        'autocapitalize' => 'none',
        'spellcheck' => 'false',
        'autofocus' => 'autofocus',
      ],
    ];

When I comment title it shows blank. I would like to change error message of the required field.

In the validation handler, I tried with this code.

if ($form_state->isValueEmpty('name')) {
  $form_state->setErrorByName('name', $this->t('Email is required.'));
}

It's not showing the error message.

I would like to keep the form element required and alter the error message.

Try this, it might work.

$name = $form_state->getValue('name');
if (empty($name)) {
   $form_state->setErrorByName('name', $this->t('Email is required.'));
}


make the sidebars and the "content" region the same length as each-other? I have a website that has regions that are uneven. the sidebar first is a different length than the content, and the content is a different length that sidebar second. it looks something like this:

I could fix it manually in the css and make them the same length, but then any time I add something to any of them, it becomes uneven again. is there any way (or any module) to fix it so that it will dynamically stay the same length, so that when I add something to the content, and it becomes longer that the sidebars, they will fill with white-space and become the same length as the longest content?

There is the Equal Heights jQuery module.

  This modules implements a jQuery Equal Heights plugin that can equalize the height of the elements of the specified class.


Context.module fires blocks on access denied pages. How do I stop this? The context.module fires block regions on the access denied page if the condition for the context is path. I don't have much of a choice in triggers other than path for these pages. How to do I disable the side blocks? Is doing a page redirect to a custom 403 page a better idea?

Use Context Error, and set the proper condition.


View published content - but only if you posted it I have two different users on my site, content posters and content reviewers.  The posters should only be able to view their own content, but reviewers need to be able to see everyone's content.  I tried to set this up using permissions, but permissions only gave me control over editing and deleting (not viewing, except for the over-arching "View published content" which seems to refer to everything.)   How do I accomplish my goal?  I am using views to present the users with different pages of content... Could I effectively limit content viewing by using views?  How can I prevent an unauthorized person from visiting a views page?

Node view Permissions fits perfectly for your needs and it is lightweight too. Its a drupal 7 module.

  Node view permissions module enables permissions "View own content"
  and "View any content" for each content type on permissions page as it
  was on Drupal 6. It's as simple as that.

  It's implemented in a non-conflict way, so you can use it with any
  other permissions related module.


How do I find a template? How I determine which template or form is responsible for processing node of page with this URL: mysite.com/node/node-number/edit ?

I think, that Drupal find the template of edit in this files:

page-node-edit.tpl.php
page-node- node-number.tpl.php
page-node.tpl.php
page.tpl.php

However, in my theme folder I have only page.tpl.php without the code of edit template, but edit template is worked.

And in template.php i heve this preprodsse_node:

function my_theme_preprocess_node(&$vars) {
    $node = $vars['node'];
    switch ($node->type) {
        case 'page':
            break;
    }
}

Now I think that the CCK module to generate this form. I can change one field or a behavior of the form?

P.S.

I need to change some input in edit form. And I can't use a different version of Drupal :(

If you want to change the default value of fields in node edit form. You should looking on any *.tpl.php files. You have to define your own custom module and use hook_form_alter

You can use this if-statement inside the hook function.

// remember change [nodetype] to the one you want to alter.
if($form_id == 'nodetype_node_form'){
    // your code here
}


Tabledrag in Drupal 7 admin pages only working in Firefox For some reason, in the last couple of days any table that is tabledrag enabled (in core admin interfaces like the menu editor, as well as custom modules) only works in Firefox.

In IE and Chrome there are no errors reported in the console, the row is highlighted on mousedown, but nothing happens when you drag.

Has anyone else encountered this and know of a fix?

There was a regression introduced in 7.52 related to dragging in the admin interface. It's fixed in the 7.53 release. It may be as simple as upgrading to the latest version of core.

The 7.53 release page, https://www.drupal.org/project/drupal/releases/7.53.


Drupal role does not appear in Views Filter According to one post, I added Author uid in contextual filter but user role still does not appear in the filter. Any other lead help?

By default, views of content only get access to the UID of the author. Add a relationship to the user to gain access to all the user-related fields, including your custom ones


How to make the Edit User Profile to have all tabs in one page? If I load this page
http://domain.com/user/1/edit

I have on top more tabs that I have to unify into one page

I've added some custom fields to the user profile that adds some more tabs when I go into

http://domain.com/admin/user/profile

so that adds the tabs that I need to appear in the same page as http://domain.com/user/1/edit

how can I do that?

note that I'm using Drupal 6.19

The One page profile module should do this if you're using the core Profile module.


Use code to automatically fill the form of a content type I have a content type called Event. I advertise events on my website using this form.
I want to advertise automatically using code.
I have this code which when I run automatically add content. But at the moment it adds the title and the body.

ini_set('display_errors','1');
ini_set('memory_limit', '512M');
define('DRUPAL_ROOT', getcwd());
include_once './includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
module_load_include('inc', 'node', 'node.pages');
$node = new stdClass();
//print_r($node);
$title          =  "test post 3";// html_entity_decode($_POST['title']);
// $summary     =   "summarry";//$_POST['summary'];
$body           =  "This is testing of Automated Script";// $_POST['body'];
$node->uid      = '0'; //author
$node->type     = 'event';    //content type
// $node->created  = time() - (rand( 1,240) * 60);
$node->created  = strtotime("now");
$node->changed  = strtotime("now");
$node->field_location = 'Oxford';
$node->title    = $title;
$node->status   = 0;
$node->promote  = 0;
$node->sticky   = 0;
$node->language = 'und';
$node->body['und'][0]['value']   = $body;
// $node->body['und'][0]['summary'] = $summary;
$node->body['format']  = 'full_html';
node_submit($node);
node_save($node);
print "ok";

How do I add remaining inputs like City, Country, Event Date, Duration, Email Address using code?

You need to do something similar to what you do to set the body of the note for each of your additional field (City, Country, Event Date, Duration, Email Address). The exact data structure for each filed depends on its type.

The general pattern is

$node->{$field_machine_name}[$language][0] = array(...);

The hard part if figuring the content of the array(...) which is the value of the field. The value of a field is actually always an associative array. Its keys (also called columns) depend on the type of the field. A text field, for instance, as only one value key/column. A taxonomy term reference field has also only one key/column, but named tid.

For instance your city and duration field are a simple text fields whose machine names are field_location and field_duration you can set their values with

$node->field_location['und'][0] =  array('value' => 'Oxford');
$node->field_duration['und'][0] =  array('value' => '2');

You country field is a Taxonomy Term Reference field, its value can be set with

$node->field_country['und'][0] = array('tid' => 1);

Where 1 is the ID of a term in the proper taxonomy vocabulary.

If you were using an single address field name field_location to store the location, the code should be something like

$node->field_location['und'][0] = array(
  'country' => 'GB',
  'locality' =>  'Oxford',
);

The structure to set a date field depends on the date format. If the field uses the ISO format, you can set it with something like

$node->field_date['und'][0] =  array(
  // The start date.
  'value' => '2014-04-02T10:00:00',
  // The end date.
  'value2' => '2014-04-02T11:00:00',
);

To discover the structure of a field, I suggest to use the Devel module. It provides a devel tab on node that let you explore the structure of the $node object for an existing node. You can also check the hook_field_schema() implementation of the module defining the field type.


Route, set meta title in controller I have a route that takes data from APIs, so I would like to set the title in the controller and not in the getTitle function because it would mean calling 2 or more times the same API

I don't think you can, not out of the box at least, but there's no reason to. Just use a static var, it will mean the API is contacted only once per request:

function getTitle() {
  static $title = '';

  if (!strlen($title)) {
    $title = $this->getTitleFromAPI();
  }

  return $title;
}


Generically detecting changed fields in a custom form prior to saving a node I'm adding certain fields from a content type into a custom form using field_attach_form(). When the form is submitted I'm processing those fields by calling field_attach_form_validate() and field_attach_submit() from #validate and #submit callbacks.

At that point, I want to compare the post-submit, prepared node object to the original node and only bother to node_save() it if any of the fields have changed. Therefore, I begin by loading the original node using entity_load_unchanged().

Unfortunately, the field arrays in the original node object don't match the field arrays in the prepared node object which is waiting to be saved, even if no changes have been made to the fields, so a simple "$old_field == $new_field" comparison is impossible. For example, a simple text field appears like this in the original:

$old_node->field_text['und'][0] = array(
  'value' => 'Test',
  'format' => NULL,
  'safe_value' => 'Test',
);

Whereas in the prepared node it appears like this.

$node->field_text['und'][0] = array(
  'value' => 'Test',
);

You might think to just compare the 'value' key, but then you run into fields made up of other elements which don't have 'value' keys. For example, let's look at an address field where there is no 'value' key and there are keys in both the old and prepared nodes which don't have counterparts.

Old node

$old_node->field_address['und'][0] = array(
  'country' => 'GB',
  'administrative_area' => 'Test',
  'sub_administrative_area' => NULL,
  'locality' => 'Test',
  'dependent_locality' => NULL,
  'postal_code' => 'Test',
  'thoroughfare' => 'Test',
  'premise' => 'Test',
  'sub_premise' => NULL,
  'organisation_name' => 'Test',
  'name_line' => 'Test',
  'first_name' => NULL,
  'last_name' => NULL,
  'data' => NULL,
);

Prepared node

$node->field_address['und'][0] = array(
  'element_key' => 'node|page|field_address|und|0',
  'thoroughfare' => 'Test',
  'premise' => 'Test',
  'locality' => 'Test',
  'administrative_area' => 'Test',
  'postal_code' => 'Test',
  'country' => 'GB',
  'organisation_name' => 'Test',
  'name_line' => 'Test',
);

For empty fields, there is yet another discrepancy.

Old node

$old_node->field_text = array();

Prepared node

$node->field_text = array(
  'und' => array(),
);

Can I generically compare any field's old and new value to detect whether it has changed or not?
Is this just an impossibility?

This, at long last, should work as a generic solution. Thanks to Clive and morbiD for all the input.

Pass both versions of the node to the following function. It will:

Pull all of the detected content type's editable fields and their editable columns (i.e. items that could possibly appear on the custom form) from the database in a single query.
Ignore fields and columns that are completely empty in both versions.
Treat a field that has a different number of values between the two versions as a change.
Iterate through every field, value, and column and compare the two versions.
Compare items non-identically (!=) if they are numeric and identically (!==) if they are anything else.
Immediately return TRUE on the first change it detects (since one change is enough to know we need to resave the node).
Return FALSE if no change is detected after all the values are compared.
Recursively compare field collections by loading them and their schema and passing the results to itself. This SHOULD even allow it to compare nested field collections. The code should NOT have any dependency on the Field Collection module.

Let me know if there are any more bugs or typos in this code.

/*
 * Pass both versions of the node to this function. Returns TRUE if it detects any changes and FALSE if not.
 * Pass field collections as an array keyed by field collection ID.
 *
 * @param object $old_entity
 *   The original (stored in the database) node object.
 *   This function may also pass itself a FieldCollectionItemEntity object to compare field collections.
 * @param object $new_entity
 *   The prepared node object for comparison.
 *   This function may also pass itself a FieldCollectionItemEntity object to compare field collections.
 */
function _fields_changed($old_entity, $new_entity) {
  // Check for node or field collection.
  $entity_is_field_collection = (get_class($old_entity) == 'FieldCollectionItemEntity');

  $bundle = ($entity_is_field_collection ? $old_entity->field_name : $old_entity->type);

  // Sanity check. Exit and throw an error if the content types don't match.
  if($bundle !== ($entity_is_field_collection ? $new_entity->field_name : $new_entity->type)) {
    drupal_set_message('Content type mismatch. Unable to save changes.', 'error');
    return FALSE;
  }

  // Get field info.
  $field_read_params = array(
    'entity_type' => ($entity_is_field_collection ? 'field_collection_item' : 'node'),
    'bundle' => $bundle
  );
  $fields_info = field_read_fields($field_read_params);

  foreach($fields_info as $field_name => $field_info) {
    $old_field = $old_entity->$field_name;
    $new_field = $new_entity->$field_name;

    // Check the number of values for each field, or if they are populated at all.
    $old_field_count = (isset($old_field[LANGUAGE_NONE]) ? count($old_field[LANGUAGE_NONE]) : 0);
    $new_field_count = (isset($new_field[LANGUAGE_NONE]) ? count($new_field[LANGUAGE_NONE]) : 0);

    if ($old_field_count != $new_field_count) {
      // The two versions have a different number of values. Something has changed.
      return TRUE;
    } elseif ($old_field_count > 0 && $new_field_count > 0) {
      // Both versions have an equal number of values. Time to compare.

      // See if this field is a field collection.
      if ($field_info['type'] == 'field_collection') {

        foreach ($new_field[LANGUAGE_NONE] as $delta => $values) {
          $old_field_collection = entity_load_unchanged('field_collection_item', $values['entity']->item_id);
          $new_field_collection = $values['entity'];

          if (_fields_changed($old_field_collection, $new_field_collection)) {
            return TRUE;
          }
        }
        unset($delta, $values);

      } else {
        foreach($old_field[LANGUAGE_NONE] as $delta => $value) {
          foreach($field_info['columns'] as $field_column_name => $field_column_info) {
            $old_value = $old_field[LANGUAGE_NONE][$delta][$field_column_name];
            $new_value = $new_field[LANGUAGE_NONE][$delta][$field_column_name];
            $field_column_type = $field_column_info['type'];

            // As with the overall field, exit if one version has a value and the other doesn't.
            if (isset($old_value) != isset($new_value)) {
              return TRUE;
            } elseif (isset($old_value) && isset($new_value)) {
              // The column stores numeric data so compare values non-identically.
              if (in_array($field_column_type, array('int', 'float', 'numeric'))) {
                if ($new_value != $old_value) {
                  return TRUE;
                }
              }
              // The column stores non-numeric data so compare values identically,
              elseif ($new_value !== $old_value) {
                return TRUE;
              }
            } else {
              // Included for clarity. Both values are empty so there was obviously no change.
            }
          }
          unset($field_column_name, $field_column_info);
        }
        unset($delta, $value);
      }
    } else {
      // Included for clarity. Both values are empty so there was obviously no change.
    }
  }
  unset($field_name, $field_info);
  // End of field comparison loop.

  // We didn't find any changes. Don't resave the node.
  return FALSE;
}

Sometimes you are interested in knowing which fields have changed.
In order to know that, you can use this version of the function:

/*
 * Pass both versions of the node to this function. Returns an array of
 * fields that were changed or an empty array if none were changed.
 * Pass field collections as an array keyed by field collection ID.
 *
 * @param object $old_entity
 *   The original (stored in the database) node object.
 *   This function may also pass itself a FieldCollectionItemEntity object to compare field collections.
 * @param object $new_entity
 *   The prepared node object for comparison.
 *   This function may also pass itself a FieldCollectionItemEntity object to compare field collections.
 */
function _fields_changed($old_entity, $new_entity) {
  // Check for node or field collection.
  $entity_is_field_collection = (get_class($old_entity) == 'FieldCollectionItemEntity');

  $bundle = ($entity_is_field_collection ? $old_entity->field_name : $old_entity->type);

  // Sanity check. Exit and throw an error if the content types don't match.
  if ($bundle !== ($entity_is_field_collection ? $new_entity->field_name : $new_entity->type)) {
    drupal_set_message('Content type mismatch. Unable to save changes.', 'error');
    return FALSE;
  }

  // Get field info.
  $field_read_params = array(
    'entity_type' => ($entity_is_field_collection ? 'field_collection_item' : 'node'),
    'bundle' => $bundle
  );
  $fields_info = field_read_fields($field_read_params);

  $fields_changed = array();

  foreach ($fields_info as $field_name => $field_info) {
    $old_field = $old_entity->$field_name;
    $new_field = $new_entity->$field_name;

    // Check the number of values for each field, or if they are populated at all.
    $old_field_count = (isset($old_field[LANGUAGE_NONE]) ? count($old_field[LANGUAGE_NONE]) : 0);
    $new_field_count = (isset($new_field[LANGUAGE_NONE]) ? count($new_field[LANGUAGE_NONE]) : 0);

    if ($old_field_count != $new_field_count) {
      // The two versions have a different number of values. Something has changed.
      $fields_changed[] = $field_name;
    }
    elseif ($old_field_count > 0 && $new_field_count > 0) {
      // Both versions have an equal number of values. Time to compare.

      // See if this field is a field collection.
      if ($field_info['type'] == 'field_collection') {

        foreach ($new_field[LANGUAGE_NONE] as $delta => $values) {
          $old_field_collection = entity_load_unchanged('field_collection_item', $values['entity']->item_id);
          $new_field_collection = $values['entity'];

          $fields_changed = array_merge($fields_changed, _fields_changed($old_field_collection, $new_field_collection));
        }
        unset($delta, $values);

      }
      else {
        foreach ($old_field[LANGUAGE_NONE] as $delta => $value) {
          foreach ($field_info['columns'] as $field_column_name => $field_column_info) {
            $old_value = $old_field[LANGUAGE_NONE][$delta][$field_column_name];
            $new_value = $new_field[LANGUAGE_NONE][$delta][$field_column_name];
            $field_column_type = $field_column_info['type'];

            // As with the overall field, exit if one version has a value and the other doesn't.
            if (isset($old_value) != isset($new_value)) {
              $fields_changed[] = $old_field;
            }
            elseif (isset($old_value) && isset($new_value)) {
              // The column stores numeric data so compare values non-identically.
              if (in_array($field_column_type, array(
                'int',
                'float',
                'numeric'
              ))) {
                if ($new_value != $old_value) {
                  $fields_changed[] = $field_name;
                }
              }
              // The column stores non-numeric data so compare values identically,
              elseif ($new_value !== $old_value) {
                $fields_changed[] = $field_name;
              }
            }
            else {
              // Included for clarity. Both values are empty so there was obviously no change.
            }
          }
          unset($field_column_name, $field_column_info);
        }
        unset($delta, $value);
      }
    }
    else {
      // Included for clarity. Both values are empty so there was obviously no change.
    }
  }
  unset($field_name, $field_info);
  // End of field comparison loop.

  return $fields_changed;
}

Sometimes you may want to make it so that changing certain fields of a node do not cause that node's "changed" timestamp to be updated. This could be implemented like as follows:

/**
 * Implements hook_node_presave().
 */
function mymodule_node_presave($node) {
  $fields_changed = _fields_changed($node->original, $node);
  $no_update_timestamp_fields = array('field_subject', 'field_keywords');
  if (!empty($fields_changed) &&
    empty(array_diff($fields_changed, $no_update_timestamp_fields))) {
    // Don't change the $node->changed timestamp if one of the fields has
    // been changed that should not affect the timestamp.
    $node->changed = $node->original->changed;
  }
}

EDIT (7/30/2013) Tightened up field collection support. Added support for fields with multiple values.

EDIT (7/31/2015) Added version of function which returns which fields have changed, and example use case.


Drupal Elysia Cron Max execution time error, in select.inc PHP Fatal error: Maximum execution time of 120 seconds exceeded in /var/www/domainname.com/public/includes/database/select.inc on line 1309

I have an elysia cron command that takes perhaps 10-15 minutes, in the night. The script also starts some jobs with beanstalk, so it takes a while to execute.

When it runs automatically at night I get that above error message. It doesnt make sense, because when I run the command from the terminal it works:

drush elysia-cron run elysia_cron_job_name --verbose --ignore-disable --ignore-running --ignore-time

And on line 1309 in select.inc is this:

public function addField($table_alias, $field, $alias = NULL) {
    // If no alias is specified, first try the field name itself.
    if (empty($alias)) {
      $alias = $field;
    }

    // If that's already in use, try the table name and field name.
    if (!empty($this->fields[$alias])) {
      $alias = $table_alias . '_' . $field;
    }

    // If that is already used, just add a counter until we find an unused alias.
    $alias_candidate = $alias;
    $count = 2;
    while (!empty($this->fields[$alias_candidate])) {
      $alias_candidate = $alias . '_' . $count++;
    }
    $alias = $alias_candidate;

    $this->fields[$alias] = array(
      'field' => $field,
      'table' => $table_alias,
      'alias' => $alias,
    );

    return $alias;
  }

Exactly 1309 is: 'table' => $table_alias,

I've searched the web, and I have no idea where the 120 seconds comes from. I feel like I tried everything. Can someone help?

Please note that Drush can use different PHP configuration file for CLI than your Apache, so you need to increase your time in there (max_execution_time).

To find where is your PHP config file, run: drush status, e.g.

$ drush status
...
 PHP configuration               :  /etc/php/7.0/cli/php.ini
...

then edit the file and increase your max_execution_time to higher value.

Alternatively add the following line in your PHP function which expect to be run by cron for longer time:

ini_set('max_execution_time', 0);


How do I get 2 separate displays of a view in one page that are displaying contents from two different content types? For example, I have a Page view which displays Content Type A Title, Post date and categories. This page will lists out all of the matching contents that this user has published.

Then I created a Block view that displays contents from Content Type B with Title and categories. The similarity between content type A and B is the categories. I want to display the contents of the block under each result in the Page that matches each category chosen for that node.

How would you display this in the view? I have heard of Views Attach or Entity Views Attachment . But the first one is only for D6 while second will probably not work since I'm not using entities ... or am I?

Or can this be done using Panels? How to do this dynamically with the Block view auto populating the Page view with the right amount of results?

I want to be able to display multiple views results for multiple taxonomies in one page. The content types do not have references for each other. But they do share the same taxonomy vocabulary and its terms.

Edit: This is how I want to display the entire page

Page Results Name

Page Result 1: Title    Date Posted     Categories
    Block Result 1 Title     Matching Categories

Page Result 2: Title    Date Posted     Categories
    Block Result 2 Title     Matching Categories

Page Result 3: Title    Date Posted     Categories
    Block Result 3 Title     Matching Categories

...

The Page is populated by Content Type A
The Block is populated by Content Type B

Want Each Block to have 10+ results that matches categories on Content Type A

It's not just placing Block view underneath the Page view. They're embedded together.

Right now, I have the 2 views displaying the correct results separately. But having trouble integrating them together.

Oh and the results for Content Type A should only display contents that the logged in user published. But the Content Type B can be from any author as long as it matches the Categories.

If You are not comfortable with Panels, then

Create one of the required views, a view page (for Content-type A) with proper contextual filters.
Create the other view (Content-type B) as an attachment (attachment Views).

Select INHERIT contextual filters while creating it.
Basically, both the views should have the same contextual filters.

Attach it to the first view created for Content-type A.

This might be an alternate solution.

For overriding the default taxonomy term paths check this tutorial -
Overriding the default taxonomy page with a view in Drupal 7

Hope you are able to manipulate the contextual filters properly in the views.


theme_image_style() doesn't output what is expected I have a module that doesn't seems to work correctly, so I dived into its code, and there is something that I don't understand:

The module does something like this: (I replaced the 'path' key with an hardcoded value to show the problem)

$params = array(
    'style_name' => $presetname,
    //'path' => $image_url,
    'path' => "public://images/image.jpg",
    'attributes' => $attributes,
    );

Then $param is sent to the theme_image_style() hook

$img = theme('image_style', $params);

The problem is that if i dump the output of theme_image_style():

dpm( $img);

then i get

<img typeof="foaf:Image" src="http://mysite.local/sites/default/files/styles//public/images/image.jpg?itok=qZxUAGIS" alt="" data-thmr="thmr_99 thmr_100" />

In admin/config/media/file-system, my public path is set as: sites/default/files

I should have:

src="http://mysite.local/sites/default/files/images/image.jpg

instead of:

src="http://mysite.local/sites/default/files/styles//public/images/image.jpg

Why does the theme function add 'styles//public' and where could I remove this?

Thanx in advance for your help

Drupal 7 provide Image style functionality which allow administrator to set predefined size and can apply image style to any image in site.

  Using image styles you can scale, crop, resize, rotate and desaturate
  images without affecting the original image. By default three sizes
  are defined: 'thumbnail,' 'medium', and 'large'. The thumbnail style,
  for example, is shown with the teaser for image posts and when
  browsing image galleries.

In your code, you have defined $img = theme('image_style', $params); which mean that you are applying image style to your image.

When we apply image style to any image, it will create a new image in styles/[stylename]/public directory and does not affect the original image source.

There is no stylename in your http://mysite.local/sites/default/files/styles//public/images/image.jpg url after style part of url, so I guess $presetname is not properly defined in your code.

You can try below exammple:

$params = array(
    'style_name' => 'thumbnail',
    //'path' => $image_url,
    'path' => "public://images/image.jpg",
    'attributes' => $attributes,
    );
$img = theme('image_style', $params);


How can I set a response URL to use https? I have a json response that I need to force to use https when on the live server.
So I need to detect if the response URL is using http or https.
If it's using http I need to switch it to https.

How can I force the header to use https?

The best way to handle this is when the user requests the JSON over HTTP, redirect it to HTTPS, and then the response will come back as HTTPS.

The Secure Pages module does just this.  It will let you create regex patterns on paths, so you can have portions of your site use HTTPS, but not others.  You would just need to add the paths for your JSON.

Note that the Drupal 7 version requires two patches against core, but I have clients who have these patches on live sites.


How to use form_set_value for a select list field? Drupal 7. in my validate form function, I use form_set_value to set the value for the field "statut_metier" to 'draft'

If my field is a text field, this code works :

form_set_value($form['field_statut_metier'][LANGUAGE_NONE][0]['value'], 'draft', $form_state);

If my field is a list(text) field, with the key for the value 'draft' = 5

I can't manage to have the form_set_value function work.

Using Devel and dpm() I have search to reach this field value :

I have tried :

form_set_value($form['field_statut_metier2'][LANGUAGE_NONE]['#value'][0], '5' , $form_state);

but it doesn't work.

Any idea ?

<?php form_set_value($form['field_statut_metier2'][LANGUAGE_NONE], array(0 => array('value' => 2)), $form_state); ?>

From the form_set_value() documentation on the first argument:

  you can just pass in the element from the $form array, although the only component that is actually used is '#parents'

Alternatively you can do:

<?php $form_state['values']['field_statut_metier2'][LANGUAGE_NONE][0]['value'] = '2'; ?>

... which is what form_set_value() does anyways.


Autopopulate a different field if node reference autocomplete doesn't have a matching candidate? I've got a form for non logged in users to submit an event, which then goes in to a moderation queue via rules. At the moment, when an authenticated user adds an event, they've got the option to either pick a venue from a list of already populated nodes (field_venue), or specify a venue in plain text if the venue isn't a node (field_venuetext).

I'd like to make this a bit easier for non-authenticated users and just provide one field which is a node reference autocomplete field. If the user just types a venue and doesn't select from the autocomplete, it will populate the plain text field (field_venuetext). Looking at the nodereference.module source, I can see the function I'd like to change (nodereference_autocomplete_validate), and I guess, I'd do something like this:

function nodereference_autocomplete_validate($element, &$form_state) {
  $field_name = $element['#field_name'];
  $type_name = $element['#type_name'];
  $field = content_fields($field_name, $type_name);
  $field_key  = $element['#columns'][0];
  $delta = $element['#delta'];
  $value = $element['#value'][$field_key];
  $nid = NULL;
  if (!empty($value)) {
    preg_match('/^(?:\s*|(.*) )?\[\s*nid\s*:\s*(\d+)\s*\]$/', $value, $matches);
    if (!empty($matches)) {
      // Explicit [nid:n].
      list(, $title, $nid) = $matches;
      if (!empty($title) && ($n = node_load($nid)) && trim($title) != trim($n->title)) {
        form_error($element[$field_key], t('%name: title mismatch. Please check your selection.', array('%name' => t($field['widget']['label']))));
      }
    }
    else {
      // No explicit nid.
      $reference = _nodereference_potential_references($field, $value, 'equals', NULL, 1);
      if (empty($reference)) {
        // *** CHANGE *** At the moment, this generates an error, but I would like to populate the field 'field_venuetext'
        form_error($element[$field_key], t('%name: found no valid post with that title.', array('%name' => t($field['widget']['label']))));
      }
      else {
        // TODO:
        // the best thing would be to present the user with an additional form,
        // allowing the user to choose between valid candidates with the same title
        // ATM, we pick the first matching candidate...
        $nid = key($reference);
      }
    }
  }
  form_set_value($element, $nid, $form_state);
}

However I'm not sure how I'd override it, or indeed how I'd populate the field field_venuetext. I'm new to Drupal, so not 100% sure where to go next. Any ideas?

After some poking around and asking on the Drupal forum, I've found that there's a module that does pretty much what I want


I want to call a mymodule.functions.inc file Hi all drupalers i am new in drupal coding i wrote a new drupal module that works perfecr but my boss wanted to put all my functions of my .module file in a new folder called 'includes' and in a files that called mymodule.functions.inc now i got an error in my code that says called of undefined function... How I can call this mymodule.functions.inc file in my mymodule.module file?? I need a real help hear guys plz help me out :)

You need to use the module_load_include function.

EDIT: As @Darvanen mentions this needs to go in your .module file preferably inside a suitable hook. Have you seen the Including code section of the Coding standards page?


How to create a rule to remove a product by sku, or remove a product to the cart I searched, and searched in many, many articles and and I have not found a solution.
What I want to do is to create a rule to delete a product by sku? Or a rule to delete products.

I show you my problem:

In my installation of commerce, I have two products. The first (the mother) is a "course". The second is a "enrollment". When you buy a course, the enrollment is added by a rule.

Well...but what if the user wants to delete the enrollment?
What I want is that, if a user removes the enrollment, the "course" is removed too and vice-versa.

You are making the assumption a commerce order in cart status contains products. In fact a commerce order consists of line-items that in turn link to products. These line items also contain also the unit price and the amount of the product (and some other details). It can be done but it requires some juggling with Rules as there is not a remove from cart rules.

So your Rules should fire on the event A product is removed from cart. Your condition should be to check for the product SKU, and in the actions you will have to run through all line items and delete the right one.

So you need to add a Loop through each line item on the commerce order to find the right product.

This is the easiest if you create a Rules component where you send the current line-item and the SKU to remove. Then in that Rules component add the following conditions:

Entity had field. (Make sure the line item has a product field)
Data comparison. (Make sure the product SKU matches the input SKU)

Action:

Delete an entity. (Delete the line item to remove it from the order, see Rule action to remove a product from the cart? (using the commerce module)).

On the main Rule, use the following actions:

Set a data value (to set your SKU to remove, this will be sent to the component).
Add a loop (Provide it with the commerce-order:line-items to loop over those)
In the loop, add your component as an action and provide it with the loop's current item and the SKU to remove.

Final note:
As it appears you will always be selling these products in pairs, you might find the Commerce Product Bundle interesting. It allows you to combine two products into one. I suppose it will remove both products also when removed from the cart.


Can we give serial numbers in views to each columns or row in a sequential manner? Can we give serial numbers in a views to each columns or row in a sequential manner from left to right(like:1,2,3----so-on) without any manual work in backend .

I am using views format "content" not "field" in views,so there is no option to add field view result counter in views,i am using view mode in views display.

When format is content

You can override views-view-unformatted.html.twig and perhaps create a twig file for just this particular view.

If your view name is test you can copy from core/modules/views/templates/views-view-unformatted.html.twig to your THEMENAME/templates folder and rename to views-view-unformatted--test.html.twig.  In this twig file you can use {{loop.index}} inside the for loop to give you the row index/count sort of like this:

{% if title %}

{{ title }}

{% endif %}
{% for row in rows %}
  {%
    set row_classes = [
      default_row_class ? 'views-row',
    ]
  %}

    row count: {{loop.index}}
    {{ row.content }}

{% endfor %}

When format is fields

Yes you can add view results counter when the format is fields


Regarding flag actions and rules integration I am using flags by the Flag module. I added two action on that flag through Flag actions:

The first one is to send an email to the site admin whenever the node is flagged.
The second is to do a Page Redirect. This action does not works and gives me an ajax error.

In my search I found this was an issue for flag module for Drupal 6. However, it still does not work. My version of Flag is 7.x-2.0 and I am using Drupal 7.

After trying out with action, I went for the better option, i.e, using Rules. I added a reaction rule with the action: A node is flagged under "my_flag" and the event : Page redirect. And I also checked the forced redirect. Its still not working.

Would really appreciate any help or suggestions regarding this.

I realise this is a long time ago but for anyone else who arrives here: you can't redirect when doing AJAX flagging, because the redirect applies to the AJAX call not the current page.

It's theoretically possible, with D7, to return a page redirect using AJAX commands but I'm not sure off the top of my head how you would achieve that in this case, or whether you'd need some modification to the Flag module code to allow it to occur.


How to create form on users account page? I used hook_user_view_aler() to add some info to user's page.

 $account['summary']['member_five'] = array(
    '#type' => 'user_profile_item',
    '#title' => t('I do'),
    '#markup' => 'Real magic',
  );

  $account['summary']['member_six'] = array(
    '#type' => 'textfield',
    '#title' => t('Name'),
    '#default_value' => '',
    '#size' => 30,
    '#maxlength' => 60,
    '#required' => TRUE,
  );

  $account['summary']['member_seven'] = array(
    '#type' => 'submit',
    '#value' => t('Submit'),
  );

Also I added form elements and they do appear but I couldn't submit it. hook_user_view_aler_submit() obviously is too much and it doesn't work. Is there any way to create form on user's page?

You'll have to define a form function using the drupal form API
See this tutorial for more info on how to make your own forms.

So the actual form function would look something like this

MY_FORM_FUNCTION($form, &$form_state){
  // Build form array here
  return $form;
}

MY_FORM_FUNCTION_validate($form, &$form_state){
  // Validate function here
}

MY_FORM_FUNCTION_submit($form, &$form_state){
  // Submit function here
}

Now in the tutorial they use HOOK_menu to display the form on a page. But you can call drupal_get_form('MY_FORM_FUNCTION') from everywhere and generate a render array for the form.

So this would show your form on the user page via HOOK_user_view_alter

 $account['form'] = drupal_get_form('MY_FORM_FUNCTION');


Creating Feature with content types imported by Feature Exporting several content types (7) from old website and importing them to new one worked perfectly.

After that i have done some basic changes in imported content types (changed widgets in few text fields (all widgets are default type)).

Now i want to make fresh backup of content types.
"Create feature" / Edit components - Content types: node
Now i can only choose "Article" and "Basic page". Content types i imported are not visible as an option.

Any idea ?

If your nodetype is already in a feature, they will not show up in the feature list.
You can disable the feature containing the nodetypes, now the nodetypes should appear.


How can I export Image Crop configuration with an Image Style for custom module? I have a custom module I'm re-using on other projects and I want to include an image style with an image crop configuration.

Under the configuration menu, I export a single crop item:

langcode: en
status: true
dependencies: {  }
label: 'Head Shot Crop'
id: head_shot_crop
description: 'Cropping for image head shot.'
aspect_ratio: '1:1'
soft_limit_width: null
soft_limit_height: null
hard_limit_width: null
hard_limit_height: null

I strip out the UUID value for that to be set on new installs.  However, for the image style export:

langcode: en
status: true
dependencies:
  config:
    - crop.type.head_shot_crop
  module:
    - crop
name: head_shot
label: 'Head Shot'
effects:
  ce7f0752-c37c-4ff6-945d-96c298663365:
    uuid: ce7f0752-c37c-4ff6-945d-96c298663365
    id: crop_crop
    weight: 1
    data:
      crop_type: head_shot_crop

I strip out the UUID value as well, but the associated crop configuration seems to be tied to the image style via UUID under the effects key, which also has a UUID value.

How can I pair an image style configuration with a crop configuration configuration so they exist on new module installs?

Please see: https://www.drupal.org/project/drupal/issues/2247257

The uuid under the effects array is used as a "unique ID" for the effect.

Seems technically it "works as designed", but as you can see from the linked project task, there is talk about if it's designed correctly.

Fortunately, the uuid under the effects array is scoped to that effects namespace, so it is safe to have the same uuid under any effects array you have regardless of the image style.

Example:

langcode: en
status: true
dependencies: {  }
name: 136x91
label: '(35mm Film 96dpi) 136 x 91'
effects:
  42cf8d4f-246c-4a6d-835f-868e5bcea297:
    uuid: 1cfec298-8620-4749-b100-ccb6c4500779 // <- could be any uuid value
    id: image_scale_and_crop
    weight: 35
    data:
      width: 136
      height: 91
      anchor: center-center

Just note that if you have two effects in one image style, they will each need a unique uuid key.

Example:

langcode: en
status: true
dependencies: {  }
name: teaser_290x163
label: 'Teaser Image 290 x 163'
effects:
  bdd99645-b55a-47b4-9337-89453c12658e:
    uuid: 1cfec298-8620-4749-b100-ccb6c4500779 // <- same as above
    id: image_scale_and_crop
    weight: 1
    data:
      width: 290
      height: 163
  4f4a1ff4-f127-4693-af57-d8f0cf3c9de0:
    uuid: 1cfec298-8620-4749-b100-ccb6c4500780 // <- needs to be unique
    id: image_resize
    weight: 2
    data:
      width: 290
      height: 163

So remove the uuid from the first line for the image style itself, but leave the uuid under the effects array when you export.


Why do I need to enable the Drupal Bootstrap theme when using a Bootstrap subtheme? I'm trying to learn how to use the Drupal Bootstrap theme to create my own subtheme.  I've added the Bootstrap theme to my drupal/themes directory, and chosen SASS as my sub-theme starterkit (i.e. I've copied drupal/themes/bootstrap/starterkits/sass to drupal/themes/mynewtheme).

I understand the concept of how sub-themes work: the sub-theme inherits the parent theme's resources.  But I don't understand how it works in the case of the Drupal Bootstrap theme.  Once I install the bootstrap framework into my sub-theme (per the instructions on the Drupal Bootstrap sub-theming instructions page), what resources is the sub-theme inheriting from the main theme?

I do not why, but bootstrap sub-theme requires bootstrap theme also enableled in order to inherit all settings, in D7 theme and sub-theme must be to be in sites/all/themes folder, D8 theme and sub-theme in /themes folder, just do it and all will work fine.


Why would I get a 404 on "Authoring Information" autocomplete? Below is a screenshot of a 404 I'm receiving on the standard author autocomplete, and I can't figure out, for the life of me, why this would be happening.

Most likely because your autocomplete isn't actually using the standard path for the user autocomplete.

From the image, your autocomplete is pointing to /login/autocomplete, a path that doesn't exist in a standard Drupal installation (or indeed one with about 200 contrib modules enabled, I just grepped a couple of large projects).

The correct path for the user autocomplete is /user/autocomplete.

Presumably there's some custom/contrib code changing the autocomplete to a different path, but failing to actually implement that path.

The best thing to do would be to search your codebase for the string login/autocomplete and go from there.

UPDATE

The change might be being made by the User Tweaks module:

function user_tweaks_form_alter(&$form, &$form_state, $form_id) {
  if (user_access('view login autocomplete')) {
    switch ($form_id) {
      case 'user_login_block':
      case 'user_login':
      case 'user_pass':
        $form['name']['#autocomplete_path'] = 'user/login/autocomplete';
        break;
    }
  }
}


Multiple taxonomy views do not work I got taxonomy menu 'Categories' which list all Terms as menu links, so when clicked, it would open a list of items tagged with that term:

So if you click on Hats & Visors, it would open the list of hats and visors. The problem is, that it doesn't, only the first view (in this case t-shirts) works. In the rest of the views it only generates empty views container. Also if I changed filter in the T-Shirts view to filter Hats & Visors, it would work, the Hats & Visors section would show hats, but then T-Shirts section would stop working. I do not understand the problem.

My views settings:

Non-working views:

Boy this is a big one. Got solution with Commerce Search API, simply re-created Kickstart's Collection view and got same result. View looks like this now:

As you can see it all runs in one Display only. Each taxonomy term menu link generates a view display for its category term listing product display nodes rendered via entities.

Also following this Commerce Search API video tutorial really helped to understand the basics how it works: http://vimeo.com/53404289


Fatal error: Cannot use object of type stdClass as array in I get an fatal error on the 'add content page'.

Fatal error: Cannot use object of type stdClass as array in

function mymodule_form($form, $form_state){
    $form['mymodule'] = array(
        '#type' => 'textfield',
        '#description' => t('Please enter your text here.'),
        '#required' => TRUE,
    );
    $form['mymodule_submit'] = array(
        '#type' => 'submit',
        '#value' => 'Submit this form'
    );

    return $form;
    return node_content_form($node, $form_state);
}

The problem's happen when I add my form, when I use only the

return node_content_form($node, $form_state);

it is working fine, what do I wrong?

There are two related but distinct concepts that seem to be conflated in your code, i.e. hook_form, and the notion of a drupal form builder function. Hook_form uses the template explained by @gisleHannemyr.

The template for a form builder function is:

function mymodule_example_form($form, &$form_state) {
  ...
  return $form;
}

Use hook_form to create or override node creation forms, and a form builder function for any other (non-node-related) form.

If you simply want to alter an existing (node or other) form, you should use hook_form_alter, instead.


Drupal callback :: Less CSS file with variable_get()'s I am trying to create a custom module that programmatically creates a LESS file.

I created a menu callback that is a file. Here is hook_menu()...

$items['sites/all/themes/universal/less/dynamic.css.less'] = array(
  'page callback' => 'jobs_universal_lessvars',
  'access arguments' => array('access content'),
  'type' => MENU_CALLBACK
);

Here is the callback.

function jobs_universal_lessvars(){
  header('Content-type: text/css');
  $output = '
    @color: #4D926F;
    body.notaclass {
      color:@color;
    }
  ';
  print $output;
}

And I call this to add it.

function universal_preprocess_html(&$variables) {
  drupal_add_css(drupal_get_path('theme','universal').'/less/dynamic.css.less');
}

I uploaded a static file to the above ^^ path, disabled the menu callback, and it processed/applied correctly. When I try to run this module, it's not included and I get an error saying

  LESS error: load error: failed to find
  sites/all/themes/universal/less/dynamic.css.less

Before you answer...

I have the LESS module installed
I have the LESS library uploaded correctly
I have tested that I can include a static .less file and have it process
I have tested the menu callback by manually going to the URL
I have tried it with and without calling header('Content-type: text/css');

I get it... it's not a file. But it "is", right? I could just call this function and have it create a new CSS file that's added, but it doesn't fulfil the requirements of the module. Help me? :) Programmatically creating files is very new to me!

It may appear like a file to the browser if you were to directly request that path in the browser, but drupal_add_css() and the LESS module deal with the file system directly and does not attempt to resolve file paths through Drupal's menu system.

drupal_add_css() will not add files that do not exist on the file system.

If you are attempting to have programmatically assigned variables within a .less file I would suggest checking out the Variables functionality that is available within the latest version of the LESS CSS Preprocessor module, documentation here: https://drupal.org/node/2139603

If you are truly trying to create a dynamically composed .less file, you first need to create the file in the files directory of the drupal install and then add that file with drupal_add_css().


Install a theme with its demo content -- via command line? The tutorials I've seen all want me to use phpMyAdmin. Here is an example that's very apropos since my theme is Zircon.
https://www.weebpal.com/guides/step-step-guide-install-drupal-8-theme
AFAIK I don't have MyPHPAdmin and I don't have access to it. What I do have is sudo access on the Ubuntu 16.04 server.
I'm using Drupal 8

You can import the database using drush rather than phpMyAdmin.

Create a standard drupal 8 site, go to the /sites/default directory and run

drush sql-cli < databasefilename.sql

See the importing database section here http://tylerfrankenstein.com/code/use-drush-export-import-drupal-mysql-database-dump-file


I can't access private files in CKEditor I have this site someone else has worked on and they've asked me to see if I could fix something.
This site has private files available to users after they've filled in a form (they then get a email with a link to the private file). This all works the way it should.

Now what they want is to be able to add a link or image that is private.
When doing this the image doesn't show or the link to the file gives a 403 error.

What is the best way to fix this or make this work.

Search for picture through ckeditor

picture doesn't show

If I'm understanding the situation correctly, then the issue is that, by virtue of bring a private file, they would need the right permissions in order to view the file in their browser.

On the sites I work on, we use elFinder, and the permission to allow access is called Access private files.

If you're not using elFinder, then there is probably a similar permission that you'll need to enable.

Hope that helps!


Quick filter tabs on top of content listing page I've downloaded and installed the Content Management Filter, but I think that the interface is a bit ugly still with all the drop downs, and it doesn't actually achieve what I had hoped.

Basically, I'm looking for a way to put a row of tabs at the top of admin/content/node so that a managing user can easily select to display just one type of node (or all nodes).

Is there a module for this?

If not, what's the best strategy? How do I tie in with the filtering already in place on this page?

View Bulk Operations (VBO) is a module that, through Views, allows you to create a page similar to the page visible in /admin/content/node. As the module allows to replace the content of that page with the content of a view, you can filter the list of the nodes following all the criteria that Views allows you to set.

The features of the module are not just those; the module allows you to select all the nodes listed in the view, and apply to them the action that is selected under "Update." The module is very useful for administrators, and it allows also to change the page that lists all the user registered in a Drupal site with a view with similar functionalities.


Show news articles only by the year selected I am working on porting a static site over to Drupal 7, and one of the pages I am porting is a Newsroom page that starts off by listing news articles (which are internal site pages, not links to other sites) and then below that are links to different years. The way the old site works is that when a year is clicked it hides the articles that are up and then shows the articles for that year. Is there a module/plugin that can do this or is there some other way than using javascript to hide and show the different articles?

You could create a view using Views and allowing an exposed filter on the year to the user to select the year or dates.  That would then submit the request to the server and reload the page with only the selected year.  It wouldn't be pretty like using Javascript, but it would do the job.


Intermittent Access Denied errors for anonymous users I'm running into seemingly random Access Denied errors that occasionally come up on most (but not always all) node pages for anonymous and low-level users (anyone without the "Bypass content access control" permission).

I've rebuilt permissions a few times, which fixes it for awhile too, but the behavior returns.
I've scoured user permissions and don't think there's anything incorrect in there.
We are not using any contrib node access modules.

Clearing the site caches fixes this, but it comes back after awhile, so I suspect this is cache-related. We use Redis.

This is a pretty new Drupal 8 site that used the Lightning install profile. We use Panels/Panelizer for layouts. We have a bit of custom code in place (a few form alters, a few blocks, a few redirects, nothing particularly complex - but it's certainly possible there's something off in there).

Anyone seen this before or have troubleshooting suggestions?

Figured this one out, not particularly efficiently (never really found a good way to backtrace this), but got there nonetheless.

The issue was coming from the Custom Permissions module, which I'd incorrectly written off as innocent early on in troubleshooting since I use it on other sites without issue. Whoops.

That module lets you create permissions via a UI for any path you'd like. We had one in place that created a permission that was already defined by core (managing blocks -- accessing admin/structure/block). Removing this redundant permission fixed our problem here. (Uninstalling the module also fixed the issue.)

I'll post an issue in that module's queue if it's reproducible with a clean install.


How to set a different theme for editing one's account I read somewhere that editing account information can be done a different theme or in the admin theme but can't for the life of me find it neither on google.

If you go to admin/settings/admin you can select your admin theme as well as using it for content editing.


Print full node url escaping special characters? How can I print the full node url in a tpl file escaping special characters?

So im using this:

<?php print $base_url . $node_url ?>

Which gives me a url like http://time.com/3525666/ebola-psychology-fear-symptoms/

However I need the url to be like http%3A%2F%2Ftime.com%2F3525666%2Febola-psychology-fear-symptoms%2F

The proper way to generate a URL is with the url() function, and the absolute option:

$absolute_url = url('node/123', array('absolute' => TRUE));

You then need to encode it:

$encoded_url = rawurlencode($absolute_url);

This work should be done in a preprocess function, and the variable added to $variables, and not done in the .tpl.php file directly:

function MYTHEME_preprocess_node(&$variables) {
  $absolute_url = url('node/123', array('absolute' => TRUE));
  $encoded_url = rawurlencode($absolute_url);

  $variables['encoded_url'] = $encoded_url;
}

and then printed in the template.

<?php print $encoded_url ?>

However, you more than likely want to use the query option or drupal_http_build_query  for whatever you are trying to use this for.  What you are describing typically isn't needed directly.  Giving the proper advice, though, is a little hard without more context.


How to disable multiple cardinality for a custom field I've made a custom module that creates a new field type. Any single-cardinality instances of this field work fine.  However, multi-cardinality instances of this field will not pass my #element_validate function; see https://drupal.stackexchange.com/questions/86745/element-validate-function-is-called-on-sub-elements-of-a-form-form-items-are-c

Since I don't need this field to ever be multi-value, I want to disable multiple values for this field entirely.

Is there a way to do this?

Just alter the cardinality selection with this hook and provide only one value:

function <my_module>_form_field_ui_field_edit_form_alter(&$form, &$form_state, $form_id) {
  if ($form['#field']['type'] == '<my_field_type>') {
    $form['field']['cardinality']['#options'] = array(1);
  }
}


Drupal Image and GalleryFormatter I am using the Image and the Galleryformatter module. I am getting these two errors on configure media page:

Warning: Division by zero in theme_image_style_preview() (line XXX of /.../modules/image/image.admin.inc).

Warning: array_intersect_key(): Argument #1 is not an array in theme_image_style_preview() (line XXX of /.../modules/image/image.admin.inc).

I found @Sohail to be almost right. I did:

chmod 777 drupal/sites/example.com/files/styles

and the error went away and my drupal 7 new image-style worked. I did not have a styles or even a files folder in druapal/sites/all/files


Views Grid, Image link to content In my content type I have a thumbnail where I put the link to the image I want to embed into a view.

For the fields I have
Content: Title [hidden]
Content: Thumbnail

In views for the Content: Thumbnail I check "ReWrite Results" and add

{{ title_1 }}

This displays the YouTube thumbnail in my view. The problem I am having is trying to make it so the user can click on the thumbnail to get to the content instead of having to click on the title which I display below.

I know twig can be used in the "Rewrite Results" but I wasn't sure what to call in there to add it to an href tag

You should be able to select the Path as a field as well. Then use that as a replacement token.

.

Optionally you can use the title as anchor title or alt attribute, but then you have to make sure to uncheck the "Link to Content" box.

.


How to avoid appending incremental number to filename I don't want Drupal to add incremental numbers to my file names to make them unique. I want to always have files stored with the same name they had when I uploaded them.

If the file with given name already exist, "Replace already existing file?" prompt should appear instead of default behaviour.

The Upload File Replace module should do the trick:

  Module Page Description

  This is a small utility module that automatically stops Drupal from
  renaming new files upload via filefield CCK. When 2 files with the
  same name exist, the older files will be renamed.

Edit: Sorry, I missed the part where you are expecting a prompt. According to the comment below, it is not possible.


Unprocessed in wordpress migrate I migrated Wordpress to Drupal 7 using wordpress migrate

What does this mean unprocessed -444?

Is that I have 444 articles are failed imported to Drupal?

Yes, as you guested unprocessed show the number of items that this module detected but couldn't import .


How to disable link on a node title? I'm using Drupal 7. I want disable link on some node-title.

Like disable ''Link this field to the original piece of content'' in Views.

How can i do this? For example, via template.php?

The code that makes that happen is in node.tpl.php:

<?php if (!$page): ?>
<h2<?php print $title_attributes; ?>>
  <a href="<?php print $node_url; ?>">
    <?php print $title; ?>
  </a>
</h2>
<?php endif; ?>

So to override it, you just need to re-create node.tpl.php somewhere in your theme's folder, remove the <a> tag surrounding the title, and clear Drupal's caches. Then you won't get links on title for node teasers any more.

If this is too 'all-encompassing' and you just want to do it for a specific content type then as well as copying the original (unchanged) node.tpl.php into your theme's folder, create another one called, for example, node--article.tpl.php (for the article content type), and make the alterations in there instead.


Using sticky-enabled Table Headers causes IE10 to crash on printing A customer complained that printing a Views page on my Drupal 7.23 (Marinelli 7.x-3.0-beta11) Site causes IE10 to error ("Internet Explorer has stopped working").  And he's right.  Works fine on Firefox, Chrome, Opera, even IE9 (but not IE 10 Browser Mode IE9).  It does work in IE10 in Document Mode 'quirks'.

On investigation it boils down to using sticky table headers - use them fail, turn them off fine!  I found that code in misc/tableheader.js lines 12-14 (below) 'helps' IE10 create the problem.

So, I have a crude workaround, but would prefer to do something more elegant. Anyone encountered this problem and have a workaround (short of not using IE10?).

$('table.sticky-enabled', context).once('tableheader', function () {
  $(this).data("drupal-tableheader", new Drupal.tableHeader(this));
});

Update - I guess it is naïve of me to expect someone to identify the error either in Drupal core, the theme, Views or my code which causes this problem. Certainly not without providing more information.  I was hoping it might 'ring a bell' and thus satisfy my curiosity.

Can I ask for more specific advice?  I found elsewhere the code below to include in template.php as a more elegant way of disabling sticky headers than no-oping the function in drupal tableheaders.js.  Can anyone please suggest how I can restrict this to print requests only? Thanks Ron

function marinelli_js_alter(&$js) {
  unset($js['misc/tableheader.js']);
}

In the last paragraph you talk about hook_js_alter.

Basically the first part should be a name of your template or custom module, so if your module will be named ie_workaround.module function should look like this:

function ie_workaround_js_alter(&$js) {
  unset($js['misc/tableheader.js']);
}

It's important to do your best to have this hook executed when this element is already set by the module or theme that sets it. You can do this using hook_module_implements_alter and placing your hook at the end of hooks array.


How can I control the order of Drupal.behaviors? I want the JavaScript code from module X to run only after the one from module Y has run. Whats the best way to do this?

The JavaScript code used by Drupal 7 is the following:

Drupal.attachBehaviors = function (context, settings) {
  context = context || document;
  settings = settings || Drupal.settings;
  // Execute all of them.
  $.each(Drupal.behaviors, function () {
    if ($.isFunction(this.attach)) {
      this.attach(context, settings);
    }
  });
};

Drupal 6 uses similar code:

Drupal.attachBehaviors = function(context) {
  context = context || document;
  if (Drupal.jsEnabled) {
    // Execute all of them.
    jQuery.each(Drupal.behaviors, function() {
      this(context);
    });
  }
};

If JavaScript would guarantee that object/array properties are always traversed in the same order they are added, then the values would be passed from jQuery.each() to the function used as its second parameter in the same order they are inserted in the array passed as first parameter.
This would mean that the first behavior inserted in Drupal.behaviorsis executed first.
In this case, to allow the behaviors defined by your module to be executed first you could use a lighter weight for it. If you want they are executed before the other ones, the module weight should be set to -50; other values can work too.
If you are using Drupal 7, drupal_add_js() allows to associate a weight to the JavaScript code; JavaScript code with a lighter weight appears first in the HTML output. This is not possible with Drupal 6, thought.

JavaScript doesn't guarantee that properties are traversed in the same order they are added. This means that different JavaScript implementations would present the same properties using a different order; it also means that the same order could change in different versions of the same browser.


Deny location based access to nodes I need to restrict access to a node based on the distance of the current user to a location attached to the node (with Location module). The distance to decide, if access is allowed is node based and stored in a field of the node.
Currently I achive this feature with hook_node_access(). I get the current location of the user through the Smart IP module and are able to calculate the distance by passing the coordinates of the user and the node to location_distance_between(), which is provided by the Location module.

Because hook_node_access() isn't considered by Views I think about accomplishing this feature with hook_node_access_records() and hook_node_grants(). Since the distance is dynamically, I have no idea how to achive this. In my understanding hook_node_grants() is called before the database query, so I have no chance to get the distance right?

Any ideas?

Thanks, Daniel

Option 1

I use the Geofield module, which provides a similar function to the Location module.  It provides the concept of a proximity filter.  This allows you to implement views such as "show all nodes within 50km of specified point".  I don't know whether the Location module has a similar function, or whether you might be willing to change modules.  The Smart IP module claims some Views integration but D6 only, so you might need a bit of code to integrate with views.

This approach would not use access control at all - so that if the user specifically navigated by URL to a far away node, they would still see it.

Option 2

If you definitely want access control, then I think you will have to give up exact distances.  You could divide your target area into regions, maybe around 50-500 of them - most simply using a simple grid.  In your hook_node_access_records, you decide which regions are close enough to the node (calculate distance to the region centre).  Finally in hook_node_grants, you need code to take the output of the Smart IP module and calculate which region it is in, and set the appropriate grant.

If you need some more help with the details of either approach, feel free to edit your question to say which approach you prefer, what you have working and where you are stuck.


Trying to use drupal_http_request to get an admin page I would like to render an admin page in a popup, I thought I'd use the ctools api to render the popup and drupal_http_request to get the data for the page, however even when logged in all I get is an 'unauthorized' error.
Looking deeper, I think there might be a way, as the function is reputed to support basic authentication, but I can't figure out how to make it work.
This is for Drupal 7.x
Or if there's a different way to render an admin page in a popup that'd be nice too. It's for a client who doesn't want to go back and forth between admin pages so the popup would solve the problem.

The Overlay module in the core is built to do exactly this, to open admin pages in an overlay popup.  You can enable it directly from /admin/modules.


Content types versus custom block types I'm trying to understand how to create content for a site and place it somewhere.  The two methods I want to compare are:

Content type

Create custom content type (with fields)
Create instances of content
Create view of this content type
Create block from view
Place block in region

Custom block type

Create Custom Block Type (with fields)
Create and place instance of custom block in region

Whats the pros and cons of each approach?

As an example scenario, lets say I have a home page with 4 sections of the same content type (for example product features).  These 4 sections need to be ordered down the page.  There will be other content on this page.

From what I have seen so far, the Custom Blocks require less effort up front to setup, I don't need a view, and I can arbitrarily order then in the block layout page (drag/drop).  However, I feel like I've now 'hidden' content somewhere else that doesnt appear in the main content summary page, and a content manager would need to know to look there, also the default view to manage Custom blocks has less options than the content filter (i know you can add some filters to that view though).  Also if I add each item as new instance of a custom block type to the block layout page, that list is going to start getting pretty long.

I guess adding the content as a content type means its created as node (and via the custom block type it isnt?)

Edit: The sites we build are big, and always multi language.  This might affect any answers.

In Drupal, content is made with nodes. Blocks are used to give more information that could be related to content (such as the nodes that are part of the same book the viewed node is part of, or the nodes that are in some other way related to the currently shown one), to the users (e.g. the last users who logged in, or the users who saw the current node), or to the site in general.

Drupal offers more feature for nodes, starting from the permissions associated to them. While for blocks a plain Drupal installation just has the administer blocks permission, which allows to create new blocks, but also delete the existing ones, for nodes a plain Drupal installation has permission for editing, deleting, viewing, and creating nodes.
Nodes have a more complex system to assign permissions to user for operations on nodes, which involves three hooks (hook_node_grants(), hook_node_records(), and hook_node_access()), while for blocks there is just a hook for that purpose.

You aren't forced to create a view for nodes, in the same way you aren't forced to create a block with a view. In both the cases, the Views module (which is now part of the Drupal core modules) helps you in making a list of entities. For example, when you enable the Views module in Drupal 8, there are some administrative pages that are served from a view, allowing the administrator users to extend those pages easily.

Also, for what I recall, you cannot add comments to blocks, but you can have comments for nodes. In a similar way, there are things that third-party modules implement for nodes, but not for blocks.


how to use function arg() in drupal to call .tpl files? I have 3 .tpl files, how can i call these tpl files by using function arg().
 actually i want to show 3 different .tpl files to user when he request from a dropdown options.

The detail description is i want to create a page which render list of nodes in a page but i like to give option to user that weather he wants all the node in single column layout or 2 column layout or 3 column layout. For these layout i'm creating 3 different .tpl files so now i want to call them on the request of dropdown list.

If I understand it correctly you are looking for a way to render .tpl.php files on certain paths, this article explains how to do it.

In the article they define only one path and show you how to make sure a .tpl.php is rendered. You can easily adjust the code to make it work with 3 different paths and 3 different tpl.php files.

Hope this helps!


Bartik Home link to be uppercase How can I make "home" link on bartik menu uppercase and instead name it "front page"?
I tried by going to edit it at structure-menus-main navigation and i cannot because it says
"This link is provided by the Standard module. The title and path cannot be edited."
I created a subtheme of bartik. What should i write there in order to change it?
Thank you.I am using Drupal8.

This is related to the Q Remove default “Home” link?. You can not alter that menu item. The only way to fix this is to disable the existing "Home" link, and create a new one instead according to your specifications.

To do this, follow these steps:

Go to admin/structure/menu/manage/main and disable the Home menu item
Add a new menu item at admin/structure/menu/manage/main/add and fill in the options like this:

Click Save and you're done


Pods created after the first try to load the private files using the same path as the first one I'm currently working on deploying Drupal8 on Openshift to achieve horizontal scaling, but I hit a problem.

On a single pod (ie: "server" running drupal"), everything seems to be ok so far. But when I'm deploying a new pod, it tries to load the private files (/sites/default/files) using the same path as the first pod.

I guess it's because something is cached in the DB since "Clearing all cache" fixes it.

Is there something in the configs I can do to prevent this behaviour ? And do you think of something I should be warned about when trying to achieve horizontal scaling ?

Posting my comment as an answer.

sites/default/files needs to be on a shared file system so that Drupal can work correctly. This contains uploaded and generated files (e.g. CSS/JS).

If you do this, you probably want to move twig to a local temporary folder, see Can I change the location of the cached Twig templates?. Note that you then need to take care of emptying that folder on all servers when you do a deployment (Unless you do something really special, this cache only needs to be updated when you change your template files).


Is there a token for the cron token? For internal use by editors I would like to get cron link into a custom menu, but I need to do this dynamically, such that it can used across multiple sites.
Editors do not have access to Admin Toolbar which is why I need a link instead.
Why do I need this? I want allow editors to make a quick backup with Backup Migrate, but I don't want to give them full access and the module permissions are not granular enough to just make a quick database backup.
A colleague suggested letting editors run a cron job instead. This seems like a solution.
I already have Menu Token module installed, so I am wondering if there is a token for a site's cron token?
If not. Is another approach recommended?

The cron key is generated by Drupal core then stored as state data (system.cron_key) when Drupal is first installed. system_token_info() doesn't expose this key as a token.
You could just make a static menu link with the /cron/$KEY path as the key will remain static as long as the system.cron_key entry remains in the state table.
If the end goal is to only envoke the Backup Migrate cron handler and custom development is an option, creating your own custom route that invokes the specific backup code (e.g. backup_migrate_cron()) would be a more direct method and have a less chance of side effects from regular arbitrary runs of all cron handlers


Register for an event and create an account on one page It's been a while since I've used Drupal and I now need to implement the following but can't seem to determine how. I have a site that's set up for event registration and need visitors to be able to sign up for an account as part of that one-page process. They'll then need to be able to edit their registration details and such but that part is in hand. What I'm not seeing is a way to combine account creation with the submission of non-profile form data all in one go.

Any pointers would be greatly appreciated.

Based on this existing answer, I could find the Inline Registration module. It lets you register while creating a node at the same time (one form). Since this is node-specific, this may allow a "event registration" content type to be defined then assigned to the user registration form.


Cannot connect to Amazon S3 Whenever I try to save the bucket name I get these errors:

Notice: Use of undefined constant CURLOPT_CLOSEPOLICY - assumed 'CURLOPT_CLOSEPOLICY' in RequestCore->prep_request() (line 626 of /Applications/MAMP/htdocs/clickbus-cms/sites/all/libraries/awssdk/lib/requestcore/requestcore.class.php).
Notice: Use of undefined constant CURLCLOSEPOLICY_LEAST_RECENTLY_USED - assumed 'CURLCLOSEPOLICY_LEAST_RECENTLY_USED' in RequestCore->prep_request() (line 626 of /Applications/MAMP/htdocs/clickbus-cms/sites/all/libraries/awssdk/lib/requestcore/requestcore.class.php).
Warning: curl_setopt() expects parameter 2 to be long, string given in RequestCore->prep_request() (line 626 of /Applications/MAMP/htdocs/clickbus-cms/sites/all/libraries/awssdk/lib/requestcore/requestcore.class.php).
Notice: Use of undefined constant CURLOPT_CLOSEPOLICY - assumed 'CURLOPT_CLOSEPOLICY' in RequestCore->prep_request() (line 626 of /Applications/MAMP/htdocs/clickbus-cms/sites/all/libraries/awssdk/lib/requestcore/requestcore.class.php).
Notice: Use of undefined constant CURLCLOSEPOLICY_LEAST_RECENTLY_USED - assumed 'CURLCLOSEPOLICY_LEAST_RECENTLY_USED' in RequestCore->prep_request() (line 626 of /Applications/MAMP/htdocs/clickbus-cms/sites/all/libraries/awssdk/lib/requestcore/requestcore.class.php).
Warning: curl_setopt() expects parameter 2 to be long, string given in RequestCore->prep_request() (line 626 of /Applications/MAMP/htdocs/clickbus-cms/sites/all/libraries/awssdk/lib/requestcore/requestcore.class.php).

And the configuration is not saved.
The bucket name contains "-", would this be a problem?

Just got the answer. After PHP 5.5, these constants were removed!

https://bugs.php.net/bug.php?id=68147