Use part of the user_profile_form on another page My users enter a phone number on registration. The amount of values that can be entered is set to unlimited. Setting this changes the field so that you can add another field below to add additional phone numbers.
I would like the users to be able to add more numbers after registration without having to go to /user/%user/edit

I am trying to return just the phone number field on another page.
However I cannot seem to get any of that form displayed on another page.
When I have been displaying other forms I have called them like this:

drupal_render(drupal_get_form('user_profile_form'));

This does return part of the form, First Name, Last Name, Country (all custom fields) but not the phone number field. I also get quite a few errors
Undefined index: user_profile_form in drupal_retrieve_form()
Undefined index: #user_category in block_form_user_profile_form_alter
Undefined index: #user_category in overlay_form_user_profile_form_alter()
Undefined index: #user_category in system_form_user_profile_form_alter()
Undefined offset: 0 in uc_roles_form_user_profile_form_alter()

Obviously I am doing something very wrong...

I made this work based on the work by Erik. I guess you could do ['#access']=false for all the values you don't want.

//Provide a custom page at /custom-profile to access our custom profile form
function mymodule_menu() {
  $items['custom-profile'] = array(
   'title' => 'Custom Profile!',
   'page callback' => 'mymodule_custom_profile',
   'access callback' => TRUE,
   'type' => MENU_NORMAL_ITEM,
 );
}

//displays the custom form at /custom-profile
function mymodule_custom_profile() {
  module_load_include('inc', 'user', 'user.pages');

  global $user;
  $user = user_load($user->uid);

  $form = drupal_get_form('user_profile_form', $user, 'account', 'custom');

  return $form;
}

function mymodule_form_user_profile_form_alter(&$form, &$form_state){
  //modifies the form_user_profile DO CUSTOM STUFF BELOW!
  if(isset($form_state['build_info']['args'][2]) &&
           $form_state['build_info']['args'][2] = 'custom'){

   //rename submit button
   $form['actions']['submit']['#value'] = t("dooo it!");

   //remove a few account things from this page
   $form['account']['#access']=FALSE;

   //needs to be there for the picture to work
   form_load_include($form_state, 'inc', 'user', 'user.pages');
  }
}


"Your site was unable to contact the Apache Solr server" We have been using Drupal 6 for 2 years and we wanted to use SOLR to have a better search and index more documents.

I have did everything right with Apache Solr as per the documentation, my Solr was working fine but I am able to access it on http://localhost/solr/admin.

I have different Solr in different servers, and none work with this Drupal. So I think there is an inherent problem within Drupal, which makes drupal not to find the solr properly.

Previously, I had encountered this issue several times configuring different servers, I am used to reinstall Drupal which made solr work fine but I cant do it to this one because its been running for long with lot of content.

Can anyone help me?

There a  lot of apache solr variables set. Can you uninstall the solr module, remove the variables if left over and re-install. Sometimes, when you do a wrong config and it can't connect, it presists this in variable. Un-installing and re-installing should help.


Watchdog message is not proper Used sqlquery to get the error log messages from watchdog table.
Getting message like,

'Sending mail to: @to'.
'%type: !message in %function (line    %line of %file)'
(which seems not relevant).

How can I get error log message similar as shown at SiteReports-->Recent Log Messages  view?

The data is serialised and uses an array of named placeholders, so you'll need to use PHP to assemble the full message:

// Get data from the DB, each record stored in $row, then...
$message = $row->message;
$variables = unserialize($row->variables);

$full_message = strtr($message, $variables);


Entityform is spanning the full width of the browser. Well beyond page margins http://chesapeakeregional.com/volunteer#overlay-context=volunteers

I did not create the form, nor the site, nor do I have any knowledge of Drupal. But somehow I got assigned to make this form fit within the normal width of the site and I'm clueless. If I'm not being clear, I basically just want to wrap the form with a div about 1140px wide and center it horizontally in the browser.

Please help!

The problem lies in the somewhat flawed structured and logic of the theme. The best solution to this would have been to restructure the theme and apply the styles for the container class, which handles most of the content layout, to a wrapper in the page.tpl.php template so that all pages get the same layout no matter content.

However, as the theme is as it is, and you don't have much Drupal knowledge I would instead recommend to apply the "container" class to the form element, or wrap the form in a div with that class. Unfortunately you can't do that in the UI.

The fastest and easiest way to fix this is to add the class to the form using hook_form_alter().

In your /sites/all/themes/chesapeake/template.php file, add:

/**
 * Implements hook_form_alter().
 */
function chesapeake_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'volunteer_form_entityform_edit_form') {
    $form['#attributes']['class'][] = 'container';
  }
}

And then clear the cache at Configuration > Development > Performance. That should add the "container" class to the form and display the page correctly.


Disable caching of attached css/js libraries for custom module? I have been trying to disable caching during development so I followed drupals guide step by step: https://www.drupal.org/node/2598914

After doing this I would assume that the caching is completely disabled but when I am loading a js/css file for a specific module in mymodule/mymodule.libraries.yml I still have to clear all caches for me to see any updates.

How do you disable caching for attached libraries in custom modules?

test_module.routing.yml

test_module.test:
  path: '/test-me'
  defaults:
    _title: 'Testing module css cache'
    _controller: 'Drupal\test_module\Controller\TestController::test'
  requirements:
    _permission: 'TRUE'

test_module.libraries.yml

test:
  version: VERSION
  css:
    theme:
      test.css: {}

TestController.php

<?php

namespace Drupal\test_module\Controller;

use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Render\Markup;

class TestController extends ControllerBase
{
    public function test()
    {
        return [
            "#markup" => Markup::create("
Hello World
"),
            '#attached' => [
                'library' => ['test_module/test']
            ]
        ];
    }
}

test.css

.test-class {
    padding: 40px;
    background-color: blue;
}

If I change the background-color to red for example, and refresh the page (F5, Ctrl+F5, Ctrl+Shift+R, Right click refresh -> Clear cache and Hard Rest), it will not change to red until I clear all caches.

What piece am I missing to make this work? Or is it just not possible?

Note: It doesn't matter if I clear my browser cache at all (I currently have it disabled with devtools open)

You are on the wrong track. Caching of static assets (and CSS files are static assets when you disable CSS/JS aggregation) has nothing to do with Drupal's cache. Disable the caching of *.js and *.css files on your web server instead (e.g in .htaccess if you are using Apache).


Drush downloading to an old version of Drupal I am new to Drupal/Drush. I tried to learn Drupal last year with tutorial that was based on Acquia-drupal (which I downloaded and was using drush there).
Now, i decided to give it another go by installing Drupal on MAMP. I tried to download a few development modules and the operation was a succes, but the modules didn't appear in my list of modules. Than it dawned on me that they must ended up on the wrong location instead at my new MAMP/sites/all/modules...
How do I fix that - do I ought to delete the Acquia, or should I install another instance of drush?

Drush is path-sensitive and can be installed system-wide; no need to install a separate instance.

To run Drush commands in the context of a site, you need to be in the web root of that site.

cd /path/to/mamp/drupal_root;
drush cc all; // Clears cache for the current site only

If you run commands outside of a Drupal root, the effects will vary. Modules will be downloaded to the current folder, cache-clear will clear Drush's internal cache, and some commands simply won't work as they don't make sense without a Drupal boostrap.


Migrating Users from Older Versions of Drupal I'm part of a team that's going to be migrating several older Drupal sites (Drupal 5, Drupal 6) into a new, single Drupal 7 site.  I'm familiar with Drupal from a software architecture point of view, but not as familiar with the day to day running of a Drupal site as I'd like.  Because of this I have a few general questions about this migration.

Are Drupal's password hashing mechanisms consistent across different versions?

If not, are there tools to support migrating user accounts and converting the passwords between versions?

If a no to migrations, are there modules that provide a standard experience for this situation that allows an old user to pick a new password?

Are Drupal's password hashing mechanisms consistent across different versions?

No, D7 and D8 use SHA512 with a salt. Drupal 6 uses MD5 without a salt.

If not, are there tools to support migrating user accounts and converting the passwords between versions?

Yes you can just rehash them.

If a no to migrations, are there modules that provide a standard experience for this situation that allows an old user to pick a new password?

Yes there is a really simple way (one example is). Make sure you BACKUP before you do anything. If this does not work for you, google how to convert drupal 6 passwords to drupal 7. There is a ton of different ways.

<?php
        require_once DRUPAL_ROOT . '/' . variable_get('password_inc', 'includes/password.inc');
        $res = db_query('select * from drupal.users');

        if($res) {
                foreach ($res as $result) {
                        $hashed_pass = user_hash_password($result->pass, 11);
                        if ($hashed_pass) {
                          $hashed_pass  = 'U' . $hashed_pass;
                          db_update('users')->fields(array('pass' => $hashed_pass))->condition('uid', $result->uid)->execute();
                        }
                }
        }


Why am I getting undefined is not a function when using jquery? HTML

more code here...

<script type="text/javascript" src="//code.jquery.com/jquery-1.10.2.min.js"></script>
<script type="text/javascript" src="https://example.com/sites/all/modules/ac_modules/ac_exercise/ac_exercise.js?nkuo2r"></script>

more code here...

<div class="form-item form-type-textfield form-item-time-start">
  <label for="edit-time-start">Time Start </label>
 <input type="text" id="edit-time-start" name="time_start" value="11:28:12" size="4" maxlength="8" class="form-text" />
</div>

more code here...

Javascript - ac_exercise.js

$(document).ready(function(){
  $("#edit-time-start").on("change paste keyup", function() {
     alert($(this).val());
  });
});

In Chrome's console I get the following error:
Uncaught TypeError: undefined is not a function - ac_exercise.js?nkuo2r:1 which is this line of code:

$(document).ready(function(){

(function ($) {
  $(document).ready(function(){

  your code here

  });
})(jQuery);


Make download available after purchase of a physical good I am running a UC Shop with Drupal which sells CDs and LPs and most of the time everything works like it should do.

Now I want to improve the service for our customers. For this reason, I want to give them the chance to download a zip-file with mp3s of every CD or LP they bought.

After we received the payment (so we set the order status to "payment received") the customers should get an encrypted link via mail or alternatively have a download button in their profile or so. It's no problem to make that possible only for authenticated users.

Any suggestions?

Sounds like a possible job for the Commerce File module

  This module is an extension of Drupal Commerce that provides the ability to sell file access.

  Ability to limit access to the file with limit settings
  Default limits: duration, download count, IP address count
  Limit default values can be inherited at the product level such that the product always uses the current default value
  After purchase of a file, limits are statically recorded to the line item so that they do not reflect any changes to the product's file limits.
  A user's limits reflect changes to an order, even after order is completed.

You can add a file field to your product entity type, and use the above module + rules to manage access to the file references by granting access licences. The licences are as liberal or as strict as you want to make them, so should be useful for your situation.

I've been using this module for a while and it works great


Why kpr() shows different content than var_dump()? In one vital part of code I started to get "Trying to get a property on a non-object" type of errors. So I wanted to investigate it.

var_dump($download);
die();

Gives:

array(3) {
  [1]=>
  array(5) {
    [5]=>
    object(stdClass)#156 (11) {
      ["idDownload"]=>
      string(1) "5"
      ...
    }
    [6]=>
    object(stdClass)#155 (11) {
      ["idDownload"]=>
      string(1) "6"
      ...
    }
    [7]=>
    object(stdClass)#151 (11) {
      ["idDownload"]=>
      string(1) "7"
      ...
    }
    [8]=>
    object(stdClass)#185 (11) {
      ["idDownload"]=>
      ...
    }
    [10]=>
    object(stdClass)#177 (11) {
      ["idDownload"]=>
      string(2) "10"
      ...
    }
  }
  [2]=>
  array(5) {
    [5]=>
    object(stdClass)#186 (11) {
      ["idDownload"]=>
      string(1) "5"
      ...
    }
    [6]=>
    object(stdClass)#155 (11) {
      ["idDownload"]=>
      string(1) "6"
      ...
    }
    [7]=>
    object(stdClass)#151 (11) {
      ["idDownload"]=>
      string(1) "7"
      ...
    }
    [10]=>
    object(stdClass)#177 (11) {
      ["idDownload"]=>
      string(2) "10"
      ...
    }
  }
  [3]=>
  array(5) {
    [5]=>
    object(stdClass)#184 (11) {
      ["idDownload"]=>
      string(1) "5"
      ...
    }
    [6]=>
    object(stdClass)#155 (11) {
      ["idDownload"]=>
      string(1) "6"
      ...
    }
    [7]=>
    object(stdClass)#151 (11) {
      ["idDownload"]=>
      string(1) "7"
      ...
    }
    [8]=>
    object(stdClass)#185 (11) {
      ["idDownload"]=>
      string(1) "8"
      ...
    }
    [10]=>
    object(stdClass)#177 (11) {
      ["idDownload"]=>
      string(2) "10"
      ...
    }
  }
}

But if I'll switch to kpr() like this:

kpr($download);
//die();

I get this:

Why can it happen? And can how I get kpr() to work? using var_dump() in form debugging is not really an option.

$download[1][6] and $download[2][6] are the exact same object (object(stdClass)#155), not just two objects with equal values. To avoid potential infinite recursion, Krumo (the k in kpr()) only display a single object once. The screenshot shows this, $download[2][6] is displayed as "∞ (Recursion)" because the object is already displayed (but collapsed in the screenshot) above as $download[1][6].

var_dump() does not have this limitation as it does not try to prevent infinite recursion.


User Role creation in module overridden by configuration import I'm creating a user Role in a .yml file like user.role.myrole.yml.
This works fine when this module is installed manually and the Role is created.
When I enable this module via configuration import though, only the roles defined in this configuration set are installed and not what is in the config/install folder of that module.
Tried putting that file in config/optional folder and writing a hook_install() for the user creation also with the same results.
I would like to have this only in the module, the module may or not be installed via config, so I need this role only when this module is enabled. How can this be achieved?
Thank you

Docs for installing default configuration in a custom module
However, putting a role in the configuration of a module is probably a bad idea.  I can't think of an example of a major contrib module that does this.
Imagine this situation: you install the module, and then the role gets enabled.  Next, the user adds some other permissions to the role (created by the module) unrelated to your module.  Then the user uninstalls the module.  Now what should happen?  Usually, the expectation is that module config will be cleaned up on uninstall, but this won't happen for roles.
What you probably want to do is add some permissions and allow the user of the module to add those to the role of the user's choice.


How to load a node title of different language? In my case the noads are stored in three different languages. How can add a condition, where I specify the language for the title that need to be loaded?

foreach($references as $reference){
    if($node = Node::load($reference->nid)){
      $url = Url::fromRoute('entity.node.canonical', array('node' => $node->id()))->toString();
      $link = ''.$this->t($node->getTitle()).'';
      $render .= '
'.$link.'
';
    }

Where $references is an array of nids.

You can load the translation separately with ContentEntityBase::getTranslation, e.g.:

if ($node->hasTranslation('es')) {
  $translation = $node->getTranslation('es');
  $translated_title = $translation->label();
}


How to display a block for some paths but not if they match some other path also? Let's say I have nodes with the following paths:

/chapters/university-of-florida/classrooms/class1
/chapters/university-of-chicago/classrooms/class2
/chapters/ucla/classrooms/cla

I'd like to display a custom block I created on these URLs, but I don't want it to show on:

/chapters/university-of-florida/
/chapters/university-of-chicago/
/chapters/ucla/

Any ideas how to accomplish this? Note that there will be new chapters and classrooms being added all the time, so I don't want to have to manually specify the paths.

I think the Context module could work here, but I am not sure how to specify the exclusions...

Any tips?

The block control for "Show block on specific pages" supports wildcards and should work here, iirc.

Show only on these pages:

/chapters/university-of-florida/classrooms/*


Issue in clearing cache i have added modules to my website , but now when i want to open modules from admin section its showing blank and i am getting PDOException: SQLSTATE[42S02]: Base table or view not found:

Check in your database

1.If cache_views table is exist or not .if not exist  import this table

CREATE TABLE IF NOT EXISTS `cache_views` (
  `cid` varchar(255) NOT NULL DEFAULT '' COMMENT 'Primary Key: Unique cache ID.',
  `data` longblob COMMENT 'A collection of data to cache.',
  `expire` int(11) NOT NULL DEFAULT '0' COMMENT 'A Unix timestamp indicating when the cache entry should expire, or 0 for never.',
  `created` int(11) NOT NULL DEFAULT '0' COMMENT 'A Unix timestamp indicating when the cache entry was created.',
  `serialized` smallint(6) NOT NULL DEFAULT '0' COMMENT 'A flag to indicate whether content is serialized (1) or not (0).',
  PRIMARY KEY (`cid`),
  KEY `expire` (`expire`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='Generic cache table for caching things not separated out...';


When to use custom nodes? How to display custom fields? I am a newbie to Drupal.
I have a custom content type blog_post, with some custom fields, like subtitle.

I have the following two divs, which I want to render for this blog_post like that:

+--------------+--------------------------------+
| 9 Sept 2013  | Good weather on the West coast |
|    2013      |           (title)              |
|   (date)     | Winds are blowing hard in NY   |
|              |          (subtitle)            |
|              | According to the Department... |
|              |          (content)             |
+ -------------+--------------------------------+

My solution: amend node.tpl.php like that:

    <?php print $date; ?>

  <a href="<?php print $node_url;?>">
    <?php print $title; ?>

    <?php print $subtitle; ?>

  <?php print render($content); ?>

How do I pull $subtitle from the database? Best way I found so far, looks somewhat ugly:

<?php
  print $field_subtitle[LANGUAGE_NONE][0]['value'];
?>

Best suggestion, don't start doing custom template overrides. With site building tools like Display Suite, you no longer have to continue writing custom node templates. By using Display Suite, you can set a view mode you defined to a two-column template, and then set the fields you'd like into each region.

You can see in the example below how easy it is to achieve something like this without having to build custom templates. Of course if you need to do anything extra, you can always customize on top of that.


Drush not recognized and internal or external command When I update Drush to Drush 9.1.0, the following error now appears:

'drush' is not recognized as an internal or external command, operable program or batch file.

This issue has occurred on three different machines: two running Windows Server 2016 and one running Windows 10. I've read that it could be due to mismatched global and site Drush versions, but both versions are at 9.1.0. When I downgrade to Drush 8.x.x, it functions as normal. Both the global and site-specific Drush installs were installed with Composer. Are there any fixes for this error?

Did you install Drush Launcher? This seems like a PATH issue -- your command lines doesn't know where to find Drush 9.

  To be able to call drush from anywhere, install the Drush Launcher.
  That is a small program which listens on your $PATH and hands control
  to a site-local Drush that is in the /vendor directory of your
  Composer project. If you skip this step, run Drush from Drupal root
  via ../vendor/bin/drush. In that case Drush's bash integration and
  custom prompt won't work.

from: http://docs.drush.org/en/master/install/


How to alter the output of a file-field as a custom field-widget I am implementing a custom field-widget for the file-field in Drupal 8.

I extended the FileWidget class as my widget uses most of the file-field-widget functionality.

There is just a small part I want to theme/customize from the file upload form, the part I marked in the following screenshot:

What is the best way to alter the output from a field-widget?

I want to add some surrounding container elements and similar things you do in a theme function.

The file field for uploading is defined in the render callback of ManagedFile:

public static function processManagedFile(&$element, FormStateInterface $form_state, &$complete_form) {
  ...

  // The file upload field itself.
  $element['upload'] = [
    '#name' => 'files[' . $parents_prefix . ']',
    '#type' => 'file',
    '#title' => t('Choose a file'),
    '#title_display' => 'invisible',
    '#size' => $element['#size'],
    '#multiple' => $element['#multiple'],
    '#theme_wrappers' => [],
    '#weight' => -10,
    '#error_no_message' => TRUE,
  ];

So one way to change the output of the field is to define a custom form element which extends File. The element can be themed as wanted.

And in the process callback of the custom widget the type of the upload element can be overwritten to use the newly defined element:

public static function process($element, FormStateInterface $form_state, $form) {
  $element = parent::process($element, $form_state, $form);
  $element['upload']['#type'] = 'myCustomFileElement';
  return $element;
}


menu_navigation_links() generate a error I'm try listing a menu navigation links with menu_navigation_links() function, but is generate a follow error:

  Notice: Undefined index: localized_options in menu_navigation_links() (line 1860 of /home3/xptoboxc/public_html/drupal/includes/menu.inc).

My code:

$html .='
';
foreach (menu_navigation_links('navigation') as $menu => $link) {
    if(!empty($link['title']))
        $html .= '
' . $link['title'] . '
';
}
$html .= '
';

Are you using the navigation menu as the secondary menu for the site?

The cause could be a bug in drupal core. See http://drupal.org/node/1018614

There is a patch in #83, which I think is for drupal 8 but the fix should be the same for drupal 7.


Drupal commerce get All product variation for list of product I have a color variation for my products...
Not every product does have multiple colors.

I would like to let the user know that one item comes in multiple color (or even show every color available), in the product-category view...

If I add the color field in the "node: product list" in the manage display of the product, it only gives me the color of the first added color variation.

How can it be done ?

If you could provide more information on version of Drupal and if you are using Commerce modules?

We have done this in the past using Commerce Fancy Attributes module to display colors for products : https://drupal.org/project/commerce_fancy_attributes

From module page:

Example usage:
0) Enable this module.

1) Create a Color vocabulary, add a text field called "Color" that will hold hex values.

Go to the "Manage Display" screen of that vocabulary, click the tab called "Add to Cart form - Attribute", enable only the color field (with the label hidden, and using the "Color" formatter).

2) Create several terms with matching hex colors (Black: #000000, White: #ffffff, etc).

3) Add a Color taxonomy_term_reference field to a product type.

4) When you add the color field on the product type, tick the checkbox "Enable this field to function as an attribute field on Add to Cart forms." and select "rendered term" as option of the "Attribute selection widget".

The Add To Cart form will now show the colors.
Of course, imagefields can be used instead of "textfields holding hex values" rendered as images.


How can I export and import users and their content (preferably as code)? I've been using the features module successfully to manage configuration changes in content across my dev and production sites.

However, I have a site that is heavily focused on user relationships and I have created a large number of dummy users to test it.  I can't use the devel module to do this because I need to create content for each dummy users as well that cannot be random.  So, creating this collection of users and nodes has taken a fairly significant amount of time.

I was hoping to find a way to export this set (of users and associated nodes) similar to the way features works, but I haven't been able to find any way to do this.  I'd like to export them in order to manage the changes in git as well as to more easily use them across a number of different test sites.

Any ideas on how I can import and export sets of users, preferably as code?

You could use backup and migrate to just export the "users" table and if you have additional fields all those "fields" tables.


How to only display languages in language switcher block where a translation exists? I need to enable thousands of languages on my Drupal 7 site, but I do not want to incur the rendering overhead of creating the language switcher sidebar for every language. The default behavior for the language switcher block is to show languages which do not have translations in gray font and struck out.

How would I modify the language switcher block to only show active links, i.e. only display the languages for which a translation exists? I looked at this code from this post but need help adjusting it for my needs:

<?php
  function YOURTHEMENAME_links__locale_block($variables) {
  foreach($variables[links] as $key => $lang) {
    if (isset($lang['attributes']['class']) && in_array('locale-untranslated', $lang['attributes']['class'])) {
      $variables['links'][$key]['href'] = '<front>'; // Set here any page link...
    }
  }
  return theme_links($variables);
}

What should the code be, and where do I put the code in my theme?

To adapt the solution you tried, you would just have to unset entries for languages where no translation exists, so no link will be printed for them in the theme_links() call. So:

function YOURTHEMENAME_links__locale_block($variables) {

  foreach($variables['links'] as $key => $lang) {
    if (isset($lang['attributes']['class'])) {
        if (in_array('locale-untranslated', $lang['attributes']['class'])) {
            unset($variables['links'][$key]);
        }
    }
  }
  return theme_links($variables);
}

You would put this code into the template.php file of your theme, adapting the YOURTHEMENAME part of the function name above according to how all the other functions in your theme start. Means, you always start the function name of all your theme functions with the so-called "machine name" of your theme.


Views Different Sort Orders I have a content type called events (obviously it keeps a list of events (conferences, meetings, etc).

I have a views-view--events-list.tpl.php file where I render a list of events.  All of this is working perfectly.

What I need to do is sort events differently based on the event date.  In specific, events that have passed (earlier than today's date), should be sorted descending - that is the most recent past event first and the event that is furthest back in history should be shown last.

For events that are still pending (in the future), the sort order is exactly the opposite - the event that will happen next should be first in the list and the event that is furthest in the future, should be shown last.

For example (assume today is 1/4/2016)

event 4: 5 April 2016 (future, the next date we will encounter)
event 6: 15 May 2016
event 5: 25 Dec 2016 (future, the last future event we will encounter)
event 1: 25 Feb 2016 (past, this was the most recent past event)
event 3: 2 Jan 2016
event 2: 24 Dec 2015 (past, this is the furthest past event)

I need to do this in one view (I do not want to create two views in code with different date ranges and sort orders; I know how to do that - I am trying to do it using just a clever sort order and the default views-view--events.tpl.php) template file.

My question then - how do I create different sort orders for different nodes (based on a field value such as date) in one view?  Is this even possible?

I'm pretty sure this can't be done in the standard Views UI.

A bad solution would be to use the Views PHP module to programmatically alter the order of the view results, or perhaps the Views Raw SQL module to insert some sorting statements into the SQL, although I haven't ever tried that.

A good solution would be to implement hook_views_query_alter() in your own custom module and add your custom sorting order to the SQL query.

Going by this answer I think something like this might work, although I haven't tested it:

function mymodule_views_query_alter(&$view, &$query) {
  if ($view->name == 'my_view') {
    $query->orderby = array(
      0 => array(
        'field' => 'my_date_field < CURDATE()',
        'direction' => 'ASC',
      ),
      1 => array(
        'field' => 'greatest(my_date_field, CURDATE())',
        'direction' => 'ASC',
      ),
      2 => array(
        'field' => 'least(my_date_field, CURDATE())',
        'direction' => 'DESC',
      ),
    );
  }
}

You would obviously have to substitute in the names of your view and your date field.

Note that this code overwrites any sorting already defined by the view. You could of course add to the $query->orderby array rather than replacing it.


Question about steps to convert from Ubercart to Drupal Commerce After running into some discount functionality/module install issues with Ubercart for Drupal 7, my client has agreed to try Drupal Commerce. Do I need to completely remove everything related to Ubercart before Drupal Commerce can work, or can I unpublish the existing Ubercart content and disable the modules to allow my client to give it a test drive?

I see that there are some machine names that are the same from one to the other, which could pose a problem.

The two projects are incompatible because of the lack of name spacing in Drupal 7. Your best bet will be to completely delete all of the Ubercart related content and uninstall all of its modules. For obvious reasons, I'd recommend not doing this on your client's live site. Create a copy from a backup and perform your test / research in that.


Query D6 db from D7 module I want to import a content type data from D6 db to D7.
I have db in settings file like....

    /**
     * Database
     */
    $databases['default']['default'] = array(
      'driver' => 'mysql',
      'database' => 'd7',
      'username' => 'root',
      'password' => 'root',
      'host' => 'localhost',
    );
    $databases['d6']['default'] = array(
      'driver' => 'mysql',
      'database' => 'd6',
      'username' => 'root',
      'password' => 'root',
      'host' => 'localhost',
    );

I am trying to query nid's from D6 db from D7 module using db_query, but cant use node_load for D6 db then.

    function import_schools() {
      db_set_active($key = 'd6');

      $result = db_query("SELECT nid FROM {node} WHERE type = :type AND nid         = :nid", array(
        ':type' => 'classified',
        ':nid' => '77307',
      ));

      while ($record = $result->fetchAssoc()) {
        print_r($record);
        print_r(node_load($record['nid']));
      }

    }

How can I chang API from d7 to d6 on fly while switching db using db_set_active.

If you are looking to Migrate D6 Content (Nodes) to D7 system then you can use Drupal-to-Drupal data migration module.

Project page says

  migrate_d2d provides a framework based on the Migrate API for
  migrating content from Drupal 5, Drupal 6, or Drupal 7 sites into the
  Drupal 7 site where it is installed.


Mollom module blocks non-spam content I am building a site using Drupal 7 and the Mollom module

Mollom really helps me to block spam on my site.
Even spam bot that succeed on passing the captcha module and register to my site, never post any content on my site - so that's great!

But, the problem is when a quality user try to write relevant good content in the site - Mollom is "unsure" and shows the user a captcha to validate that he is a human. This is a quality content without any spam words (e.g. "Viagra").

I tried writing by myself good content as an authenticated user, Mollom was "unsure" and showed me the captcha after I tried to save. I tired it again few times, and always mollom display the capatcha after I am trying to save.

Is there any way to make Mollom less strict? Am I missing something in the settings?
Can I use also the Honeypot module together with Mollom (and even remove mollom)?

I have used very successfully used honeypot and Mollom together with very positive effects.

I am not sure about lowering the sensitivity of Mollom however or improving its ability to recognise a quality post. I can only assume they have increase the strictness to ensure they maintain there high number of correctly classified ham messages.
for more information check out: https://mollom.com/blog/spam-vs-ham


What may cause the text of a message created with the Message module to be empty? I have installed the Message module to log activities, and set it up following these instructions.

All steps look good, and message (admin/content/message) is created after I added new content. But, the message's TEXT field is empty.

Also, Message: Render message (Get text) field in related View is also empty, and SHOW NO RESULTS BEHAVIOR is triggered.

I enabled message_example module come with message, same result.

Is there anything wrong with my options?

This is a rather typical issue in multi-language sites. A variation (not duplicate) of your question is what is described in "Rules - Set language of message notification".

A possible solution (work-around?) is what you wrote in your own comment below your question, i.e.:

  I checked Message class, and it turns out that I have a wrong language code, 'cause I set administer language to English other than default language. It works now after I set language back to default.

Another solution is to indicate the language in which the message is to be created.


Force a new line item on cart I'm developing my own module for a customizable bundle of commerce products.

I'm saving the subproducts in a field collection in a line item field.

For some reasons I'm doing this with my module, not using "Include this field on Add to Cart forms for line items of this type" in the line item field settings.

Well, when I use my module I use

$form['#submit'][] = 'commerce_custom_bundle_add_to_cart_form_submit';

inside a

commerce_custom_bundle_form_commerce_cart_add_to_cart_form_alter

(is hook_form_BASE_FORM_ID_alter)

Then my function is executed after the product is added to the cart.

The problem is if I choose to add to cart the same product no new line item is created and the existing quantity is increased in 1, obviously.

But I need a new line item, because my custom field changes and I need to not merge the values chosen in the existing line item. I don't know How to force the creation of a new line item.

I tested, if I not use my code and I expose this field in the add to cart form enabling the "Include this field on Add to Cart forms for line items of this type" in the line item field settings. If the same product is added to the cart with a different value in my custom field, is created a new line item.

How do I force the creation of a new line item?

To force to create a line_item for every same product added to the cart you just need to uncheck the option "Attempt to combine like products on the same line item in the cart." in the Add to cart form settings  of your product reference in your product display content type.

In other words. You have to change the content type that you use to show your product, you had added a product reference to this content type. Then you just has to change in the "Manage display" of your content type, the settings of the "Add to cart Form" of the product reference field, and you have to uncheck "Attempt to combine like products on the same line item in the cart."

This is a screenshot of the manage display page:


How to overcome a database error on field deletion I have read the other SQLSTATE[42S22] questions here, and they seem to all be about modules that have not completed setup properly, but I think my issue is different.

Whenever I try to delete a field the following error shows up:

PDOException: SQLSTATE[42S22]: Column not found: 1054 Unknown column
'field_data_field_doc_file0.field_doc_file_value' in 'where clause':
SELECT field_data_field_doc_file0.entity_type AS entity_type,
field_data_field_doc_file0.entity_id AS entity_id,
field_data_field_doc_file0.revision_id AS revision_id,
field_data_field_doc_file0.bundle AS bundle FROM
{field_data_field_doc_file} field_data_field_doc_file0 WHERE
(field_data_field_doc_file0.field_doc_file_value = :db_condition_placeholder_0)
AND (field_data_field_doc_file0.deleted = :db_condition_placeholder_1) ;
Array ( [:db_condition_placeholder_0] => 61531 [:db_condition_placeholder_1] => 0 )
in field_sql_storage_field_storage_query()
(line 652 of /path/to/drupal/modules/field/modules/field_sql_storage/field_sql_storage.module).

It seems that perhaps some previous field deletion went awry or something?  If I hit the back button it does appear that my field has been deleted, but I fear that if I keep deleting fields, I may be digging myself into a much worse problem to untangle.  What would be the best course of action to resolve this issue, and get rid of these db errors?  I'll start by looking at the field_sql_storage module, but suspect I'm not familiar enough with drupal yet, to quickly ascertain what is going wrong via that route.

UPDATE: Line 652 of that module is the last line of the field_sql_storage_field_storage_query method:

return $query->finishQuery($select_query, $id_key);

UPDATE 2: I found the entity with the id in [:db_condition_placeholder_0] in a table called field_deleted_data_143, but I haven't find a column named field_doc_file_value anywhere yet (The deleted table has a field_doc_file_title_value table).  The FROM portion of the query is FROM {field_data_field_doc_file} field_data_field_doc_file0, but I don't know what table {field_data_field_doc_file} represents here.  Is it field_data_field_doc_file (which is an empty table), or are do those curly brackets mean that name is being replaced with something else?

I guess maybe the next step is to try adding the column to the table.

I tried manually adding a column with the missing name to the table in question.  Now a cron run spits out a series of 20 sets of error messages like this:

Notice: Undefined property: stdClass::$fid in file_usage_list() (line 649 of /path/to/drupal/includes/file.inc).
Notice: Undefined property: stdClass::$status in file_field_delete_file() (line 363 of /path/to/drupal/modules/file/file.field.inc).
Notice: Undefined property: stdClass::$fid in file_usage_delete() (line 728 of /path/to/drupal/includes/file.inc).
Notice: Undefined property: stdClass::$uri in file_delete() (line 1273 of /path/to/drupal/includes/file.inc).
Notice: Undefined property: stdClass::$uri in file_delete() (line 1274 of /path/to/drupal/includes/file.inc).
Notice: Undefined property: stdClass::$uri in file_delete() (line 1278 of /path/to/drupal/includes/file.inc).
Notice: Undefined property: stdClass::$uri in file_delete() (line 1280 of /path/to/drupal/includes/file.inc).
The specified file could not be deleted, because it is not a valid URI. More information is available in the system log.

At the same time I notice the number of rows in my various deleted_data tables seems to decrease by 10 with each run.  Deleting a field likewise triggers 20 errors and a decrease in the number of rows in the deleted_data tables.

I'm hoping that this has been the fix.  It makes sense that it can't delete the files as they come in via a migration, and I've started bringing the files in on  a different field, so I rolled back and imported.  I'll update this once cron has run enough times that I can see if my deleted data logjam has cleared and fields can be deleted again.

UPDATE: It seems like there was a tremendous amount of backlog building up behind this database error.  I set a system cron job to trigger drupal cron once a minute (dev site, so no performance concerns) and over the course of many hours, the rows in the deleted_data and deleted_revision tables have started to go away, followed by the tables themselves.  A few empty tables and one with three rows in it remain, and I'm not sure if they will eventually be cleared, or if they aren't in whatever queue is being run through.  If someone knows how to check what tasks drupal has queued up to run in the background, please do comment and let me know.

IN CONCLUSION: In this particular case, where the system was trying to make a selection and not finding the column it expected to find, it seems like the only possible solution was to add the column in, so the select would return 0 rows instead of an error that stopped things from moving on.  I'm not sure what caused the discrepancy between expected columns and actual database schema, but I suspect it has something to do with an earlier struggle to get the media module working for me, that involved switching back and forth between the 7.1.x and 7.2.x branches of that module.  Somewhere along the way I think drupal lost track of what version was currently installed, and stopped being able to properly run the right database upgrades on install and update.  I'll read up some more on how to check if this is something I need to address, but if you've had a similar experience, that may be a place to start on debugging the source of your woes.


Elysia cron Execution time vs Shutdown time While looking to the Cron Status Tab, I can see this information above every cron channel :

Last run: 14/06/2013 - 02:00
Last execution time: 597s (Shutdown: 597s) (Avg total: 307.16s, Max total: 834s)
Execution count: 137

What does the Shutdown seconds stands for ?

The documentation surrounding that variable is pretty much non-existent. This is how it's calculated, in elysia_cron_completed():

time() - $cron_completed_time

Where $cron_completed_time is a global, presumably a timestamp indicating exactly when an associated cron job ended.

I'm afraid you'll need to infer exactly what that timestamp is from the above; I think it refers to the gap between when a cron job was completed, and the time it was logged in the database.


Form API Radio Button Submit I'm building a form that is being built by pulling information from an api and loops through it. The issue I'm having is I cant seem to pass the information to the submit page.

Here is a snippit of my code, let me know if you need more:

// Loop through resources and make fieldset for each.
for($i = 0; $i < count($resources['subscriptionResources']); $i++){
  $resource = $resources['subscriptionResources'][$i];

...

  $form['resources'][$resource['resourceID']]['add-qty'] = array(
    '#type' => 'radio',
    '#title' => t('Upgrade'),
    '#return_value' => 1,
    '#default_value' => 0,
    '#disabled' => FALSE,
    '#prefix' => "

",
    '#suffix' => t("	"),
    '#attributes' => array(
      'name' => 'upgrade',
    ),
  );

...
So the outcome is, I get three different forms each with a radio button. They are all connected due to the 'name' attribute, so only one can be selected at any given time.

But when submitting, the default_value stays 0 and return_value stays 1 for all three. I'd like some way to display the information of the 'checked' radio to the submit page. Currently I'm seeing nothing (if default_value is 0) or everything is default_value = 1.

Again, let me know if you need more information.

Thanks!

$resourcids = array();
 // Loop through resources and make fieldset for each.
    for($i = 0; $i < count($resources['subscriptionResources']); $i++){
      $resource = $resources['subscriptionResources'][$i];
      $resourcids[$resource['resourceID']]=$resource['resourceID'];
    }

      $form['resources'] = array(
        '#type' => 'radios',
        '#title' => t('Upgrade'),
        '#options' => $resourcids,
        ),
      );

you dont need to use name attributes. drupal form api give name attributes by form name.

when you submit form you get resource id in form_state['values']['resources'] of which is selected. then you identify which radio button is selected.

and By default disabled is false. so you dont need to add disabled.

dont add t() in before t("

")

'#suffix' => t("</td>"),


Custom label and value multiple field Is there any module that provides a way to implement a custom multiple field that enables user to enters both label and value?
For instance I have a product that has a list of features, ie:

Color: Red
Size: Large

And I have another product that has completely different features, like:

Style: Tuxedos
Gender: Male

So I like to be able to make these flexible for the editor to enter as many as features as they need mentioning the labels as well.

Thank you in advance

Using Field Collection module must serve your purpose.

After installing the module, create a field collection with two text fields - label and value.

Now attach this field collection to a content type and set its value to unlimited.

in essence what you will have is:
 1. When the form loads, you have two fields, a label and a value
 2. An add more button, which when clicked will generate another set of label value pair.

Hope this helps.


Fetching node field values programmatically I have figured out how to query the node table programmatically without using the deprecated db_query() function. However, I soon discovered that the actual content fields are not held in the node table, but in a separate revisions table.

I can't figure out how to select fields from the content nodes.

So for example, I can get a count of the number of nodes of type "entity", by using the following code.

use Drupal\Core\Database\Database;
$connection = Database::getConnection();

$sth = $connection->select('node', 'x')
->fields('x', array('nid', 'type'));

$executed = $sth->execute();
$results = $executed->fetchAll(\PDO::FETCH_OBJ);

$type_entities = array();

foreach ($results as $row) {

    // COUNT ONLY ENTITIES
    if ( $row->type == "entity" ) {
        $type_entities[] = $row->nid;
    }
}
echo "Total: ".count( $type_entities );

This code works fine, because I am not referencing any data from the node, just counting the node id's.

But say I also have a field entitled "color", and I want to return that field too, so I can count the number or red, green, blue, etc? The following code won't work, because the "color" field is not in the node table, so can someone please help me to create a working version of the following:

use Drupal\Core\Database\Database;
$connection = Database::getConnection();

$sth = $connection->select('node', 'x')
->fields('x', array('nid', ['type', 'color'] ));  // <-- ADDED color FIELD

$executed = $sth->execute();
$results = $executed->fetchAll(\PDO::FETCH_OBJ);

$type_entities = array();
$is_red = array();
$is_greed = array();
$is_blue = array();

foreach ($results as $row) {

    // COUNT ONLY ENTITIES
    if ( $row->type == "entity" ) {
        $type_entities[] = $row->nid;

        // COUNT COLOURS
        if ( $row->color == "red" ) {
            $is_red[] = $row->nid;
        } else if ( $row->color == "green" ) {
            $is_green[] = $row->nid;
        } else if ( $row->color == "blue" ) {
            $is_blue[] = $row->nid;
        }
    }
}
echo "Total: ".count( $type_entities );
echo "Red: ".count( $is_red );
echo "Green: ".count( $is_green );
echo "Blue: ".count( $is_blue );

So how do I do that, only fetching the "color" field properly using ->fetchField() or ->fetchCol() maybe?

Thanks for looking!

I think you should leave the database structure and focus on the entities concept.

This brings you to a simpler approach using entityTypeManager  to get nodes and filter them by whatever you want.

$query = $this->entityTypeManager()->getStorage('node')->getQuery();
$nids = $query->loadByProperties(
    [
        'type' => 'content_type',
        'status' => 1,
        'field_name' => 'value'
    ])
    ->execute();


Adaptively Displaying Images Inline Drupal 7 For Drupal 7.14 I've been trying to display images inline adaptively to a content type. In my content type I have a long text and summary field and an image field. I'm using the Adaptive Image Styles (ais) module. I upload the image and then insert the image using the insert module. I'm using full HTML without any text editor. But when I insert the code it does not display adaptively.

I was finally able to get AIS working for adapting with inline images and shadow box. It can be done through Wysiwyg (see here for instructions: http://drupal.org/node/1555376)  or I just insert this code in the image tag: class="adaptive media-image attr_typeof_foaf:Image img_fid_1172 img__view_mode__media_adaptive attr_format_media_adaptive" typeof="foaf:Image". From what I can tell none of the other adaptive modules can do this. I checked it in Adaptive Image and it does not do inline images. An example of this working can be seen at: http://173.236.7.153/~ssanalyt/drupal/consulting-areas/business


Pathauto URL alias Node taxonomy term translation How can i get pathalias to get the translated taxonomy term for the path alias?

The pattern:

[node:field_glp_product_types]-[node:field_glp_address:city:?]

[node:field_glp_product_types] is a taxonomy reference field.

The following tokens are available, but only the node:field_glp_product_types token gives output, but not translated.

That is a bit complicated and is not possible with the normal translation methods.

You will need to use Entity Translation Module and Title module

Once you have the above modules configured you should have an option to include translated token for all the entities.


How to make a user not being able to publish his content? how is this possible to make a user/role not being able to publish content he has created ,but to be able to create new (unpublished) content?
thanks

How about [implementing hook_node_presave($node)][1] in your custom module,so as example code consider the following

function mymodulename_node_presave($node) {
  global $user;
  // check if user has role and checking node->original is not set ensures it works only when insertion of node happens not when it is edited
  if (in_array("your_user_role",$user->roles) && (!isset($node->original))) {
    // keep the node unpublished
    $node->status = 0;
  }
}


What does 'set breadcrumb' do in Rules? One of the actions that comes with the Rules module is 'set breadcrumb'.

When trigger this action, however, nothing seems to happen to the breadcrumb.

What is supposed to happen? Does it set the breadcrumb on the page that the user was on when it was triggered, or on the page whose path is used in the action? Why isn't it doing anything, or is it doing something, and if so, what is it doing?

To use the "Set breadcrumb" rules action you should add it to the event "Content is viewed", for example

Event: Content is viewed
Condition: Content is of type article
Action: Set breadcrumb: Title: Articles\n[node:title] Paths: articles\n[node:url]

rules_action_breadcrumb_set basically goes through those title and path values and uses drupal_set_breadcrumb to set the breadcrumb.


Drupal Commerce - Update profile on order without cloning? I understand the reasoning behind preserving integrity of data for existing orders tied to profiles, however...

I have a page where the user can edit the order contents and change their billing or delivery information. Instead of create a new profile, I would like to save the data directly to the order being viewed. I don't want it to affect new orders created later, either.

How can I do this? It would seem that every time commerce_customer_profile_save is called, a brand new profile is created.

This isn't a standard commerce workflow, but most of the fundamentals are there. A customer can have many open orders at any given time, and I want the flexibility for them to change the delivery address ON a specific order and save it for that order only. Someone out there has to have done this I would believe.

How about something like this leveraging Drupal's Entity API:

//assume we retrieved the $order_id via a page callback argument or something similar
$my_order = entity_load('commerce_order', array($order_id));

$billing_profile_id = $my_order[$order_id]->commerce_customer_billing[LANGUAGE_NONE][0]['profile_id'];
$billing_profile = entity_load('commerce_customer_profile', array($billing_profile_id));

// **replace this comment with PHP logic to update the profile values**

//save our customer profile object using the updated values from logic above
$success = entity_save('commerce_customer_profile', $billing_profile[$billing_profile_id]);

This allows us to directly edit the customer profile object associated with a particular order, and leaves the rest of the profiles unaffected.


How to remove link to profile under title, when rendering a profile as block in the module Profile2 I'm rendering a user customer profile in a form using the code:

$profile = profile2_load_by_user($account, 'customer');
$form['customer_profile'] = array(
    '#type' => 'item',
    '#markup' => render($profile->view('block')),
);

which works rather well, except that the title (in H2 tags) is rendered as a link back to the profile.

I want to get rid of that link, but as there seems to be no obvious property, to specify if you do or do not want a backlink. Not in the $build array parameter of hook_entity_view_alter, nor in the $elements parameter for a '#pre_render' callback. In a '#post_render' callback, it's too late because the link is already inserted into html.

So, how do I get rid of it?

This link is part of template file profile2.tpl.php defined as $title and it appear for non page display modes as described by the template code.

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

<?php endif; ?>

The short possible solution can be to unset title variable implementing hook_preprocess_profile2. But to remove whole markup you will have to overwrite theme registry implementing hook_theme_registry_alter(&$theme_registry) to replace template against profile2.

$theme_registry['profile2'] = array(
  'render element' => 'elements',
  'template' => 'profile2_custom',
  'path' => path_to_theme(),
);


Drupal 7 vbo, is there an option to input text to operations? Im using VBO with drupal 7. If I have an action which creates a new node/update a new/create a comment etc. How can I manually type the title/body text or what ever it is I'm setting?

Thanks for any help.

You can do this with Rules for example, every "Action set" Rules component that you create is exposed to Views Bulk Operations and all the parameters you configure for your action set will be available for use in the view.

I've created a simple view listing all nodes and an action set that exposes the title so you can modify it with a textbox.

Here's the view:

$view = new view();
$view->name = 'vbo_test';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'node';
$view->human_name = 'VBO_Test';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'VBO_Test';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'full';
$handler->display->display_options['pager']['options']['items_per_page'] = '10';
$handler->display->display_options['style_plugin'] = 'table';
$handler->display->display_options['style_options']['columns'] = array(
  'title' => 'title',
  'views_bulk_operations' => 'views_bulk_operations',
);
$handler->display->display_options['style_options']['default'] = '-1';
$handler->display->display_options['style_options']['info'] = array(
  'title' => array(
    'sortable' => 0,
    'default_sort_order' => 'asc',
    'align' => '',
    'separator' => '',
    'empty_column' => 0,
  ),
  'views_bulk_operations' => array(
    'align' => '',
    'separator' => '',
    'empty_column' => 0,
  ),
);
/* Field: Content: Bulk operations */
$handler->display->display_options['fields']['views_bulk_operations']['id'] = 'views_bulk_operations';
$handler->display->display_options['fields']['views_bulk_operations']['table'] = 'node';
$handler->display->display_options['fields']['views_bulk_operations']['field'] = 'views_bulk_operations';
$handler->display->display_options['fields']['views_bulk_operations']['label'] = '';
$handler->display->display_options['fields']['views_bulk_operations']['element_label_colon'] = FALSE;
$handler->display->display_options['fields']['views_bulk_operations']['vbo']['entity_load_capacity'] = '10';
$handler->display->display_options['fields']['views_bulk_operations']['vbo']['operations'] = array(
  'action::node_assign_owner_action' => array(
    'selected' => 0,
    'use_queue' => 0,
    'skip_confirmation' => 0,
    'override_label' => 0,
    'label' => '',
  ),
  'action::views_bulk_operations_delete_item' => array(
    'selected' => 0,
    'use_queue' => 0,
    'skip_confirmation' => 0,
    'override_label' => 0,
    'label' => '',
  ),
  'action::system_message_action' => array(
    'selected' => 0,
    'use_queue' => 0,
    'skip_confirmation' => 0,
    'override_label' => 0,
    'label' => '',
  ),
  'action::views_bulk_operations_script_action' => array(
    'selected' => 0,
    'use_queue' => 0,
    'skip_confirmation' => 0,
    'override_label' => 0,
    'label' => '',
  ),
  'action::node_make_sticky_action' => array(
    'selected' => 0,
    'use_queue' => 0,
    'skip_confirmation' => 0,
    'override_label' => 0,
    'label' => '',
  ),
  'action::node_make_unsticky_action' => array(
    'selected' => 0,
    'use_queue' => 0,
    'skip_confirmation' => 0,
    'override_label' => 0,
    'label' => '',
  ),
  'action::views_bulk_operations_argument_selector_action' => array(
    'selected' => 0,
    'skip_confirmation' => 0,
    'override_label' => 0,
    'label' => '',
    'settings' => array(
      'url' => '',
    ),
  ),
  'action::node_promote_action' => array(
    'selected' => 0,
    'use_queue' => 0,
    'skip_confirmation' => 0,
    'override_label' => 0,
    'label' => '',
  ),
  'action::node_publish_action' => array(
    'selected' => 0,
    'use_queue' => 0,
    'skip_confirmation' => 0,
    'override_label' => 0,
    'label' => '',
  ),
  'action::system_goto_action' => array(
    'selected' => 0,
    'use_queue' => 0,
    'skip_confirmation' => 0,
    'override_label' => 0,
    'label' => '',
  ),
  'action::node_unpromote_action' => array(
    'selected' => 0,
    'use_queue' => 0,
    'skip_confirmation' => 0,
    'override_label' => 0,
    'label' => '',
  ),
  'action::node_save_action' => array(
    'selected' => 0,
    'use_queue' => 0,
    'skip_confirmation' => 0,
    'override_label' => 0,
    'label' => '',
  ),
  'action::system_send_email_action' => array(
    'selected' => 0,
    'use_queue' => 0,
    'skip_confirmation' => 0,
    'override_label' => 0,
    'label' => '',
  ),
  'action::node_unpublish_action' => array(
    'selected' => 0,
    'use_queue' => 0,
    'skip_confirmation' => 0,
    'override_label' => 0,
    'label' => '',
  ),
  'action::node_unpublish_by_keyword_action' => array(
    'selected' => 0,
    'use_queue' => 0,
    'skip_confirmation' => 0,
    'override_label' => 0,
    'label' => '',
  ),
  'rules_component::rules_vbo_test' => array(
    'selected' => 1,
    'use_queue' => 0,
    'skip_confirmation' => 0,
    'override_label' => 0,
    'label' => '',
  ),
);
$handler->display->display_options['fields']['views_bulk_operations']['vbo']['enable_select_all_pages'] = 1;
$handler->display->display_options['fields']['views_bulk_operations']['vbo']['display_type'] = '0';
$handler->display->display_options['fields']['views_bulk_operations']['vbo']['display_result'] = 1;
$handler->display->display_options['fields']['views_bulk_operations']['vbo']['merge_single_action'] = 0;
$handler->display->display_options['fields']['views_bulk_operations']['vbo']['force_single'] = 0;
/* Field: Content: Title */
$handler->display->display_options['fields']['title']['id'] = 'title';
$handler->display->display_options['fields']['title']['table'] = 'node';
$handler->display->display_options['fields']['title']['field'] = 'title';
$handler->display->display_options['fields']['title']['label'] = '';
$handler->display->display_options['fields']['title']['alter']['word_boundary'] = FALSE;
$handler->display->display_options['fields']['title']['alter']['ellipsis'] = FALSE;

/* Display: Page */
$handler = $view->new_display('page', 'Page', 'page');
$handler->display->display_options['path'] = 'vbo-test';

And here's the action set:

{ "rules_vbo_test" : {
    "LABEL" : "VBO_TEST",
    "PLUGIN" : "action set",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : {
      "node" : { "label" : "Node", "type" : "node" },
      "title" : { "label" : "title", "type" : "text" }
    },
    "ACTION SET" : [ { "data_set" : { "data" : [ "node:title" ], "value" : [ "title" ] } } ]
  }
}

More info can be found in this nodeone screencast: http://nodeone.se/en/using-rules-components-with-vbo

If you need to update the value of a field that is not available in the action set, you can expose "Rule sets" as well to VBO, that allows you to use conditions, particularly the Entity has field condition that will pull the field out of the entity and make it available to Rules UI:

    { "rules_test_rule_set" : {
    "LABEL" : "Test Rule set",
    "PLUGIN" : "rule set",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : {
      "node" : { "label" : "node", "type" : "node" },
      "text" : { "label" : "text", "type" : "text" }
    },
    "RULES" : [
      { "RULE" : {
          "IF" : [
            { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_options" } }
          ],
          "DO" : [
            { "data_set" : { "data" : [ "node:field-options" ], "value" : [ "text" ] } }
          ],
          "LABEL" : "my rule"
        }
      }
    ]
  }
}

You can do this with arbitrary fields based in a data type that rules have info about, what I don't think you can configure is the widget exposed for this operation.


How to upload enterprise blog picture programatically in drupal 7 I used "enterprise blog" module for user blog postings. From external php file, I have to upload user picture programatically (i.e., for App). I have configured bootstrap perfectly and user_load($uid) is working, means drupal functions are working properly, but when I am trying to upload picture programaically "file_save($file)" is not working. Please check the below code and give me any suggestions to upload enterprise blog picture.

 $tmp_photo_realpath = "images/".$userimgname;
      $tmp_photo = "images/".$userimgname;
      $file = new stdClass();
      $file->uid      = $uid;
      $file->status   = 0; // mark the file as temporary
      $file->filename = basename($tmp_photo_realpath);
      $file->uri      = $tmp_photo;
     // $file->filemime = image_type_to_mime_type(exif_imagetype($tmp_photo_realpath));
      $file->filesize = filesize($tmp_photo_realpath);
     $infofile = explode("/",$tmp_photo);
    $infoext = explode(".",end($infofile));
    $imgext = end($infoext);

  // The file should be an image
  $errors = array();
  $errors += file_validate_is_image($file);
  $errors += file_validate_image_resolution($file, variable_get('user_picture_dimensions', '100x100'));
  $errors += file_validate_size($file, variable_get('user_picture_file_size', '30') * 1024);

  // Make sure file extension is a valid image
  if (!in_array(strtolower($imgext), array('jpg', 'png', 'gif'))) {
    $errors[] = ' invalid image file extension.';
  }

  if (count($errors)) {
    drupal_set_message(t('Profile Image Import:') . ' ' . $errors[0], 'warning');
    // Clean up (set fid to avoid error messages)
    $file->fid = 0; file_delete($file);
  }
  else {
    // We'll need a valid file id on the file object; file_save() will give us one
    $file = file_save($file);
    // Update user account (fid is not empty, status is temporary -- image
    // will be moved to proper directory and assigned to the user)
    $fields['field_enterprise_blog_picture'] = $file;
    $account = user_save($account, $fields);
}

Ok, here is my testing example. I can't say that it works perfectly but in my case it works fine. And, of course, you can modify/customize it by your needs if you want (add validation, check file path, directories, and so on..):

function _executeFile($uri, $uid) {

  $file_url = file_create_url($uri);
  $file = system_retrieve_file($file_url, NULL, TRUE, FILE_EXISTS_REPLACE);

  if ($file) {
    $user = user_load($uid);
    $file = file_load($file->fid);
    $file->status = FILE_STATUS_PERMANENT;
    file_save($file);

    // file_usage_add($file, 'MY_MODULE', 'enterprize_picture', $file->fid);

    $file_info = image_get_info($file->uri);

    $user->field_enterprise_blog_picture[LANGUAGE_NONE][0]['fid'] = $file->fid;
    $user->field_enterprise_blog_picture[LANGUAGE_NONE][0]['alt'] = '';
    $user->field_enterprise_blog_picture[LANGUAGE_NONE][0]['title'] = '';
    $user->field_enterprise_blog_picture[LANGUAGE_NONE][0]['width'] = $file_info['width'];
    $user->field_enterprise_blog_picture[LANGUAGE_NONE][0]['height'] = $file_info['height'];
    $user->field_enterprise_blog_picture[LANGUAGE_NONE][0]['uid'] = $file->uid;
    $user->field_enterprise_blog_picture[LANGUAGE_NONE][0]['filename'] = $file->filename;
    $user->field_enterprise_blog_picture[LANGUAGE_NONE][0]['uri'] = $file->uri;
    $user->field_enterprise_blog_picture[LANGUAGE_NONE][0]['filemime'] = $file->filemime;
    $user->field_enterprise_blog_picture[LANGUAGE_NONE][0]['filesize'] = $file->filesize;
    $user->field_enterprise_blog_picture[LANGUAGE_NONE][0]['status'] = '1';
    $user->field_enterprise_blog_picture[LANGUAGE_NONE][0]['timestamp'] = $file->timestamp;
    $user->field_enterprise_blog_picture[LANGUAGE_NONE][0]['rdf_mapping'] = array();

    user_save($user);
  }
  else {
    // SET VALIDATION ERROR
  }
}

and call it like this:

define('DRUPAL_ROOT', getcwd());
require_once './includes/bootstrap.inc';
require_once './includes/file.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
_executeFile($uri /* e.g.: 'public://OTHER-OpenSourceSystem_1600x1200.jpg' */, $uid);

First function gets two variables as arguments and loads user object
and creates file object from URI, and sets file object properties to
user file field and saves it;
Second piece of code bootstraps system and just calls that function.. You can set your validation rules here


How can I use the same render cache but for json? I am working on REST API and I would really like to be able to use the same mechanism for responses as Drupal uses for cached content.

Unfortunately there is no render cache, everything is JSON responses. So there are no #ccache setting or page cache policy to be applied out of the box.

So I wonder if it is even possible and if so how should I approach it?

What I'm after basically is to cache the responses in the same manner as entities for example. So if the context is specific user and I am displaying entity information I would like to get fresh information if the entity is changed but the same content if not and the user is the same..and so on.

You have to use a cacheable response and then you can add cacheable metadata from a render array or from an object directly:

use Drupal\Core\Cache\CacheableJsonResponse;
use Drupal\Core\Cache\CacheableMetadata;

  $response = new CacheableJsonResponse($json, 200);

  $response->addCacheableDependency(CacheableMetadata::createFromRenderArray($content));

  $response->addCacheableDependency($entity);

If you use the core REST API this should already be implemented.


Enabled SSL - Login Doesn't work Followed the instructions on enabling SSL on Drupal 7 installation.

The SSL loads fine, all pages/links work but I'm unable to login.

When I try to login the screen just resets, go back to http and all works fine.

Any ideas what I may have missed?

Tried following the instructions twice now.

Regards,

Richard

It was a cookie issue. When I deleted all the cookies from browser it was fine.


Duplicate home / front page - available on two urls I have the Views module installed on my site, and have created a Views page and set it as the home page. The url is /front.

The home page works via the web root (it's set in 'Default front page' of configuration -> site information), but it is also accessible via /front. Is there a way to prevent this?

It shouldn't link from anywhere, and I've added it to the robots.txt file just in case, but I would prefer a cleaner solution.

It's normal Drupal behavior to have front page accessible by it's original path.

What I would recommend in the case is installing the Global Redirect module and configuring it to 301 redirect from /front to /.


Can a view and a content type share the same alias pattern? I'd like to have this URL structure on a Drupal 8 site:

/schools/usa -> handled by custom view
/schools/europe -> handled by custom view
/schools/school-name -> handled as a normal node

So basically when the users makes a request for a URL like /schools/%, Drupal first checks if it finds a node with that alias and, if it doesn't exist, passes on to the view (or vice-versa, view first and then node if the view argument doesn't validate).

Is this achievable?

If I try, the view gets the precedence and throws a 404 on /schools/school-name as "school-name" fails to validate as a taxonomy term (it's a node title after all...)

Yes, you can do this. The key is in the Action to take if filter value does not validate option of your Contextual filter.

Set that option to Display contents of "No results found".

Then under No results behavior add Rendered entity - Content enter schools/{{ arguments.name }} or which ever correct token is in your case.

This will make your views work with regular terms, but if the term doesn't validate it will go to the page with the argument. In your case if the argument is school-name then it will lead to the node page with that path.

What you should additionally consider is what an argument is entered that isn't neither, a term nor the appropriate part of a node path. You'll just get a blank page with View page title.

Maybe you can solve that by adding another No results behavior for that case, maybe a block with a message that the term doesn't exist and a link back to the Views page, then hide the Block on your node pages that share the starting path string.


How to add categories to content I'm still new to Drupal 7. I've read a couple of things on how Drupal works, but I don't quite get some things though.

How do I create articles for different categories? I would like to make articles that can be listed under graphics, painting, or 3D etc. How can I categorize them in the main menus? How different is this to the blogging module or book module?

I know this may have been posted similarly here, but I would just want a simple explanation not found in long chapters. Thanks guys.

You're probably looking for taxonomy. Create a vocabulary and name it something like "categories". Add terms for each category you want like graphics,3D,ect. Then just add links in your navigation menu. Under your content type, add a term reference field and choose your "categories" vocabulary. That way your users can choose a category when they submit something.


Regcode/OG Issue - Need D7 Equivalent of og_all_groups_options() I'm trying to use the Registration codes module to automatically assign users to an organic group when they login with a registration code.

For Drupal 7, it appears that the Registration codes module is still using a Drupal 6 function (og_all_groups_options()) that is supposed to list all organic groups on a form.

I need to know the D7 equivalent of this function; I can't seem to find it.
Do you have a suggestion for how I could print out a multi-select option list of organic groups like og_all_groups_options() did?

The closest one seems to be og_get_all_group() in og.module.


Get image's URL as a token for use in Views' replacement pattern I need to get an image's full URL path as a token that I can use as a replacement pattern in Views.

I'm trying to have one thumbnail image link to a larger image.  I have the larger image excluded from view so I can use it as a token.  When I try to export the thumbnail image as a link using the larger image's token, the token is apparently the <img> tag instead of the path.

I think I can do this if I change the field type of the larger image to a File, but I want the benefits that come with the Image type (cropping, scaling, etc).

I ended up using a module to create a custom formatter.  Image URL Formatter http://drupal.org/project/image_url_formatter .  It created a new formatter option called "Image URL," and I can use that as a token.


Drupal 7 subfolder multisite I'm trying to setup a drupal 7 multisite using subfolders for example:

example.com/site1

example.com/site2

In my drupal sites folder I have sites1 and sites2 according to sites.php I should be able to set it up as the following:

$sites['example.com/site1'] = 'site1';
$sites['example.com/site2'] = 'site2';

However this doesn't work, I can definitely see a site at example.com but am unable to see any of the sites in the sub folder.

If you want to do it this way then you have to symlink the folder to the root of the drupal install:

cd /var/www/drupal
ln -s . site1

Then within sites.php use the following:

$sites = array(
    "example.com.site1" => "site1",
);


Showing comment form under each paragraph In node.tpl.php, I have done some changes, like creating an array of paragraphs:

    $paragraphs = explode("
",render($content));

So, I have a for loop for showing the paragraphs, like:

$number = count($paragraphs);
if($page){

 print render($paragraphs[0]);
  for ($i=1;$i<$number;$i++)
      {
         print render($paragraphs[$i]);

      Put comment for Paragraph <?php echo $i?>

<?php  } ?>

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

As you can see I want to create a hyperlink under each paragraph, so when user click on it, they can put comment on the paragraph, But right now, when they click on the hyperlink, it will  jump to the end of the page, which has the comment form.
 If you check the CommentPress website, in the right column, you can see for example, it is said: 5 Comment on Paragraph 1, and when you click on it, it will show the comments and the comment form under that link, I want to have the same thing, I mean, when users click on the link under each paragraph, the comment form displays under that link instead of jumping to the end of the page.

I think you will need to do a couple of things. First is to create a comment form under each paragraph:

Drupal 7:

$comment = new stdClass;
$comment->nid = $nid;
$form = drupal_get_form('comment_form', $comment);

print render($form);

Then I would suggest using some jQuery to hide the forms, showing it only when the user clicks on the link. You can assign a unique class to the $form (see form API reference for more info) so that only the comment form for the specific paragraph shows, instead of all of them when any given link is clicked.


How to get the mock of current user in PHPUnit test? I'm trying to get a mock of current user.

$user = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id());

For this I extend UnitTestCase class and loading the methods of class User.

$methods = get_class_methods('\Drupal\user\Entity\User');

Now, as load function also exists in this User class, I have created a mock of this User class and disabling its constructor and setting all methods of this class including load method which I actually need.

$user = $this->getMockBuilder('\Drupal\user\Entity\User')
      ->disableOriginalConstructor()
      ->setMethods($methods)
      ->getMock();

Since the method is set now, I'm trying to call this method once and not sure what it will return exactly.

$user->expects($this->once())
      ->method('load')
      ->will($this->returnValue('admin'));

Now, while running this test, I got 1 error:

  Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException:
  You have requested a non-existent service "entity.manager".

Now, my question of interest is what's the need of injecting service entity.manager?? Although load is a method of entity storage interface and also it exists in User class too. Then why this error coming up?

Can I load current user without mocking entity.manager class or entity storage interface?

Actual function for which I'm doing unit testing is:

public static function get_ctype_field_value($field) {

    $user = user_load(\Drupal::currentUser()->id());
    $ulm = get_type_id($user); // another function in some class, return value 445
    $local_market = \Drupal\node\Entity\Node::load($ulm);
    $llf = '';
    if ($local_market) {
      // Get the field value from the LM.
      if ($local_market->hasField($field)) {
        $localmarket_field = $local_market->$field->value;
      }
    }
    return $localmarket_field;
  }

In Drupal, unit tests (UnitTestCase or \PHPUnit_Framework_TestCase, sometimes) are really best when you have a class that doesn't have a lot of dependencies or when you can really predict what the dependencies do so you can mock them.  Typically, you mock individual methods, and not try to do everything.  When you find yourself mocking too much, or with complicated mocks, it is best to rework your test as a kernel test (KernelTestBase or KTB for short).

A KTB will boot a minimal Drupal environment, and then you can enable modules and choose which config and schema you want installed (enabling the module doesn't automatically do this).  These are still PhpUnit tests, so you can run that that way and have full access to providers and other PhpUnit features.  Many modules in core also define extensions of KTB to provide setup and additional features (eg, EntityKernelTestBase and ViewsKernelTestBase).

KTB tests are not as fast as UTC tests, but still quick and not as slow as functional tests (BrowserTestBase).  Core has tons of examples.

In your case, since it seems like you need users and nodes, you really want a KTB.  Since both are entities, there is really a lot you would need to mock and you will go down the rabbit hole quickly trying to do this because of the dependencies.

See also Types of tests in Drupal 8.

A few answers to your specific questions.

Users are content entities (so are nodes), which use a lot of services.  And, they aren't all properly injected (the base Entity class uses a lot of helper methods that access the global \Drupal class to get services).  In addition EntityManager is deprecated and got broken up in different services; so a lot of its methods are really helper functions for the other services.  To to a UTC, you would have to start mock these helper functions.  I do not think there is a way around this.

Based off your test snippet, you are really best starting off with a KTB.


How to add classes to comments? I've put the following code above print render($content['comments']); in comment-wrapper.tpl.php of our theme to add question or answer class to every comment:

    foreach($content['comments'] as &$c) {
      if(is_array($c) && array_key_exists('#entity_type', $c) && $c['#entity_type'] == 'comment') {
        $uid = $c['comment_body']['#object']->uid;
        $c['#attributes']['class'][] = $uid == 1 ? 'answer' : 'question';
      }
    }

The generated HTML however has no question or answer classes. Please help me to correct the error.

I think your ternary statement is off in that code.

I would also suggest an alternative approach.  You can use hook_preprocess_comment() in a template.php file or in a custom module.  With this you can hook into the comment before it's rendered to the page, run each comment through an logic test and add a class to the entire comment, or add an html chunk before or after the comment's html.  See more on hook_preprocess and render arrays.


Why not all menus are available in context settings page? I want to put main-menu to certain block via context.

But only few menus are available:

I've 3 contexts already, but none of them uses any menu.

In the context module, blocks in the Blocks reaction are grouped by the module that creates them. In this case, it is the System module that provides the Main Menu that you're looking for.


How to create on mouse over dropdown menu in drupal 7? Am working on drupal 7.x and using pixture reloaded sub theme 2.x. Under the Main Menu, am creating a menu with the menu name "Development". On mover over the menu "Development", in drop drop, list of sub-menus should list out. I installed a nice-menu module, but i don't know how to use. Please give a step by step tutorial to create a sub menu on mover over. Thanks

You can use nice menu or super fish menu
nice menu will create two blocks called nice menu 1 and nice menu 2 you have to choose on of them as a block and in configuration you will choose a menu to display

also superfish module will create 4 blocks (it is a dynamic number form config menu) and give you more options to style your menu also option to choose which menu you want to display


Is there a module that will add an image field that displays an image from an off site source? Im on d7. I'm looking for a way to have images displayed on my site from another image hosting site such as imgur or imageshack. Right now I've been using the media module for uploading images to my site and it works great, but I don't want to store the image on my server. I need the ability to "source" where the image came from, but the media module doesn't store that info, it just downloads the file. thanks for your suggestions.

You should take a look at the remote stream wrapper module and this issue that explains how to do it.


Menu added not showing I have added a menu item in main-menu using following code

$item = array(
    'menu_name' => 'main-menu',
    'link_path' => 'my-profile',
    'link_title' => 'Services',
    'module' => 'menu',
    'weight' => 0,
);
menu_link_save($item);
menu_cache_clear_all();

this code is placed in lcp_theme function, lcp is custom module and is working properly except this added menu item.
I cant see this menu at top of the site in main menu.

As per the documentation I can use this function anywhere in module.

If all you are trying is to add a menu item in main menu, you can implement hook_menu, code something as below.

function my_module_name_menu() {
  $items['test'] = array(
    'title'           => 'Tes Page',
    'description'     => t('Test'),
    'menu_name'       => 'main-menu',
    'weight'          => 8,
    'access callback' => TRUE,
    'page callback'   => '_my_module_name_test_page',
    'type' => MENU_NORMAL_ITEM,
  );

  return $items;
}

function _my_module_name_test_page() {
  return "hi";
}

Key is to have 'menu_name' => 'main-menu', in menu item declaration.


Writing alternative File Widget Okay, so I looked inside of the Managed File element and the FileWidget code and I am pretty overwhelmed.  I don't think I need anything quite so complex, but it seems like there is so much that can be done with a file widget that I don't want to do things in a way that could cause problems in the future.

I have some javascript that will upload a file to a remote server and return a url, so I want to send that url to a custom controller and save it in Drupal.  Is writing a file widget the right way to go here?

Any guidelines on where to go to find a good example of a file widget, or an explanation of how it works?

I've found that at the moment, there is no example more helpful than the Plupload module.  It integrates with the Plupload_widget module and extends the FileWidget from core and also has a lot of comments that I wish core would have included, explaining what the core file widget does.


Custom url is not working with drealty listing I am using Drealty module in Drupal 7. I have created custom url for properties.

I am getting path using;

<a href="<?php print drupal_get_path_alias("drealty_listing/$id"); ?>"><?php print t('More Detail'); ?>

This code is not working for me properly. For some properties it gives page not found but Property exists.

Using the url() function should give you what you need:

<a href="<?php print url("drealty_listing/$id"); ?>"><?php print t('More Detail'); ?>

The url will be converted automatically to the alias.


How to show block based on browser language? In Drupal 8, I would like to show a block to a visitor based on their browser language (I guess based on the Accept-Language HTTP header).

The page should stay in English but there should be something like "this site is available in your language, click here" (translated into the relevant language, of course).

I don't think this is possible without custom code if you want to do this differently from the current language.

However, you don't need to do all the heavy lifting yourself. See LanguageNegotiationBrowser and the code there, you should be able to more or less copy that 1:1.

Then it will only do it if the language actually exists, respects language mappings and so on. You just have to call that, check if it's different from the current language and if so, display something.

However, properly caching that is going to be fun:

You need a cache context for an arbitrary http header, similar to CookiesCacheContext. so something like http_header:HTTP_ACCEPT_LANGUAGE as a cache context.

That will however not work for anonymous page cache, since that doesn't check cache contexts at all. To work around that, you need your own page cache implementation, that caches by that header, which will obviously result in lots and lots of variations.

So.. maybe you should just do this completely in JS?


Adding Divs in Blocks I've created a custom block with Div and P tags in which some have id and class attributes. I've tried use FULL & Filtered html formats for the block body however the id and classes don't show up once I've added the block.

In admin/structure/types/manage/your_content_type/display  (drupal 7 path) make sure field Body has format "Default" selected. If you have any other format those will remove the div ids and classes from the body.


How to populate nodes with imagefield programmatically? I'm trying to do a mass import of images to drupal nodes in D7 and ended up with lots of funny entries in the table {files_managed}.

This is the code I use:

  chdir('/path/to/drupal/root');
  define('DRUPAL_ROOT', getcwd());
  require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
  drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

  $node = node_load(123);

  $dir = '/path/to/files';
  if ($handle = opendir($dir)) {

    while (false !== ($file = readdir($handle))) {
      $file_ext = pathinfo($file, PATHINFO_EXTENSION);

      switch ($file_ext) {
        case 'jpg':
        case 'gif':
        case 'JPEG':
        case 'jpeg':
        case 'png':
          $name_explode = explode("_", $file);
          $image_location =  $dir .'/'. $file;

          $file_temp = file_get_contents($image_location);
          $file_temp = file_save_data($file_temp, 'public://' . $file, FILE_EXISTS_RENAME);
          $node->field_ep_image = array(
            $node->language => array(
              0 => array(
              'fid' => $file_temp->fid,
              'filename' => $file_temp->filename,
              'filemime' => $file_temp->filemime,
              'uid' => 1,
              'uri' => $file_temp->uri,
              'status' => 1
              )
            )
          );
        break;
      }

    }

    closedir($handle);
  }

What is the correct way to populate an imagefield programmatically in D7?

I don't have the exact answer to your question, but you could check how other modules do it. Devel Generate for instance (part of Devel) can populate image fields. Check out devel_generate_fields() in devel_generate.fields.inc and image_devel_generate() in image.devel_generate.inc.

Hope that helps.


Rewrite rules for Development & Production Environments I'm having trouble with the file path when I upload my development environment to the server.

The problem is actually quite simple.
Development is working on the root folder ( development.tld )
Production  is working on the sub-folder ( production.tld/sub-folder )

When I manually add a image in node content on the development environment, the path to that file is /sites/default/files/test.jpg

That path will not work in the production environment because of the sub-folder.

Sample node content:

RewriteBase /sub-folder method works properly in general but I need to remap requests for the manually added assets
( /sites/default/files/* to /sub-folder/sites/default/files/* )

Is there a Rewrite rules for this process?

Thank you.

Try changing (or assigning) the base url in sites/default/settings.php


Drupal Commerce does not allow any payment if payment pane is not in review order page If I do not put the Payment pane in the Review Order page, then no payment method works and it just goes to checkout complete. Even if I check Require a payment method at all times it makes no difference.

Is this a bug or is it something I'm missing?

The attached image works but not when payment is in payment when it is it skips payment entirely.

I guess 'payment' means 'choose payment method'


How to set up a 'review-like' view that connects users to nodes? I want to be able to add to my panel, described here, a view of an 'advocate' that 'endorses' an item.

Each item (unique by NID) has one Advocate (a user, unique by UID) and each User can have multiple endorsements (but still one per item).

In my view I have these settings:

Click to view

I've annotated them to show how I think things link together

NID from the URL connects to the, 'Entity Reference: Endorsement'.
The Entity Reference: Endorsement connects to the '(Content entity referenced from field_tech_endorsement) Entity Reference: Endorser'.
The (Content entity referenced from field_tech_endorsement) Entity
Reference: Endorser connects to the 'User: Name (Name) and User:
Picture'

These settings all seem 'right' to me. but I'm getting no output on my panel.

I think the crux is in the Argument input, that it feeds from the NID selected on the panel (see link), and the UID of the associated (via the relationship Entity Reference: Advocate). But I don't know if I'm doing the 'feeding' right at all.

Nothing comes up on the preview, and nothing come up on the page.

This is what I'm hoping for:

What am I doing wrong on this view? Is my set up right at all?

What I'm trying to do is reflect this set up:

Here is the SQL generated by the query.

<!-- lang-sql -->

SELECT      node.nid AS nid, #The node of the item that has this endorsement (?)
            users_field_data_field_endorser.name AS users_field_data_field_endorser_name, #The username of the advocate who has endorsed the item
            users_field_data_field_endorser.uid AS users_field_data_field_endorser_uid, #The UID of the advocate who has endorsed the item
            users_field_data_field_endorser.picture AS users_field_data_field_endorser_picture, #The picture of the advocate who has endorsed the item
            users_field_data_field_endorser.mail AS users_field_data_field_endorser_mail, #No idea why this is generated
            node.created AS node_created, #No idea why this is generated
            'node' AS field_data_body_node_entity_type #No idea what this is
FROM
            {node} node #A Table of all nodes?
LEFT JOIN   {field_data_field_tech_endorsement} field_data_field_tech_endorsement ON
                    node.nid = field_data_field_tech_endorsement.entity_id AND
            (field_data_field_tech_endorsement.entity_type = 'node' AND
            field_data_field_tech_endorsement.deleted = '0')
            #Left Join our endorsements, where they're not deleted, and they're NID matches their NID (well duh)
LEFT JOIN   {node} node_field_data_field_tech_endorsement ON
                field_data_field_tech_endorsement.field_tech_endorsement_target_id = node_field_data_field_tech_endorsement.nid
             #Left join on Where the NID of the target matches the endorsement (????) That's not right
LEFT JOIN   {field_data_field_endorser} node_field_data_field_tech_endorsement__field_data_field_endorser ON
                node_field_data_field_tech_endorsement.nid = node_field_data_field_tech_endorsement__field_data_field_endorser.entity_id AND
                (node_field_data_field_tech_endorsement__field_data_field_endorser.entity_type = 'node' AND node_field_data_field_tech_endorsement__field_data_field_endorser.deleted = '0')
              #Left join on the endorser/advocate where the Endorsements NID is the same as the NID of the endorser/advocate's endorsement AND where the endorserment is endorsing the right kind of node, AND where the endorser is not deleted
LEFT JOIN   {users} users_field_data_field_endorser ON
                node_field_data_field_tech_endorsement__field_data_field_endorser.field_endorser_target_id = users_field_data_field_endorser.uid
            #Left join on the user details that match the endorser
WHERE (( (node.nid = '13' ) )AND(( (node.status = '1') AND (node.type IN  ('endorsement')) )))
ORDER BY node_created DESC
LIMIT 1 OFFSET 0

I think my understanding of what it's doing it right, but it seems like what it's doing is wrong. What do I do to fix it?

I've created these types:

Item (node) : has entity reference field to node of type endorsement.
Endorsement (node) :  has entity reference field to user (which I guess has role advocate in your case)

The View:
Base table of nodes, filtered by type 'Endorsement'

Two relationships:

A bridge to the Content entity that is referencing Content via field_endorsement (as we have nodes of type endorsements in our base table, we need to link it to 'Item'. 'Item' has the entity reference field containing endorsement, hence we go in reverse: ie referencing)
A bridge to the User entity that is referenced via field_advocate (as we have nodes of type endorsements in our base table we need to link it to User. Endorsements has an entity reference to user, hence it is a simple forward relationship, ie referenced)

Now add the Contextual filter of type nid. Set its relationship to 'Content referencing Content from field_endorsement', which was the first relationship added. The nid we are passing it is of type 'item', hence we must link it via the relationship to 'items'. Set 'hide view' 'when filter value is not available'.

For argument input: From panel argument, First argument.

Add your fields as you want. There is no need to add nid as a field unless you need to do so for a specific reason.

done with the view, back to the panel: add the view to the panel content for the page, and tick 'Send arguments'