EntityFieldQuery to search Content Type for text and select matching Nodes I have created Search page which searches Products (Content type) by selecting few option drop down menus (those are selecting taxonomy terms), but also i have an text input field, which is supposed to narrow or define search by keywords.

Now problem is that i need to search several fields at same time.

This script works perfectly (snippet):

$keywords=$_POST ['keywords'];
$query = new EntityFieldQuery();
$entities = $query->entityCondition('entity_type', 'node')
->propertyCondition('type', 'product')
->fieldCondition('field_main_category', 'tid', $category, 'IN')
->fieldCondition('field_sku', 'value','%'. $keywords .'%', 'LIKE');
$result = $query->execute();

I got all the product that are matching user entry, even if partial (those %).
But i need to query some other fields too (description and name), to search for terms that user may enter.

But, problem is that i must have one input field, and user may target 3 different fields, so three fieldConditions for same term will cause nothing to be found, because selection is excluding all  if term is not found in one field.

Could I,some way, write EntityFieldQuery query in a way to tell it to "forget" condition if keyword is not found ? (like in bellow example)

$keywords=$_POST ['keywords'];
$query = new EntityFieldQuery();
$entities = $query->entityCondition('entity_type', 'node')
->propertyCondition('type', 'product')
->fieldCondition('field_main_category', 'tid', $category, 'IN')
->fieldCondition('field_sku', 'value','%'. $keywords .'%', 'LIKE');
->fieldCondition('field_name', 'value','%'. $keywords .'%', 'LIKE');
->fieldCondition('field_description', 'value','%'. $keywords .'%', 'LIKE');
$result = $query->execute();

Other workaround could be to look all three fields in one place, if i could get combined fields in one condition query (this could be done by hand, by adding another field only for search terms that will be filled with tags that will be searchable summary of all 3 fields, but i am hoping to find the way not to create more field and content, if possible).

Any suggestions or experiences with that ?
Thanks!

Do you mean something like this;

$keywords=$_POST ['keywords'];

$query = new EntityFieldQuery();
$entities = $query->entityCondition('entity_type', 'node')
->propertyCondition('type', 'product')
->fieldCondition('field_main_category', 'tid', $category, 'IN');

if(isset($keywords)) {
 $query
   ->fieldCondition('field_sku', 'value','%'. $keywords .'%', 'LIKE');
}
$result = $query->execute();

UPDATE

You can do an OR for each of the field. SO to do this you add a tag to the query which you are building and then you can alter the query using the hook_query_TAG_alter

    $keywords=$_POST ['keywords'];

    $query = new EntityFieldQuery();
    $entities = $query->entityCondition('entity_type', 'node')
    ->propertyCondition('type', 'product')
    ->addTag('something');

    $result = $query->execute();

function modulename_query_**something**_alter(QueryAlterableInterface $query) {
  $or = db_or()
    ->fieldCondition('field_sku', 'value','%'. $keywords .'%', 'LIKE')
    ->fieldCondition('field_name', 'value','%'. $keywords .'%', 'LIKE');

  $query
      ->condition($or);
}

This is just and example and you will have to make changes as per your requirements but this OR will definitely help.

Refer to the following links for a good example;
http://treehouseagency.com/blog/tim-cosgrove/2012/02/16/entityfieldquery-let-drupal-do-heavy-lifting-pt-1
http://treehouseagency.com/blog/neil-hastings/2011/09/06/building-energygov-without-views
http://treehouseagency.com/blog/fredric-mitchell/2012/02/21/or-queries-entityfieldquery


How do I create anonymous emails sent by users and allow other users to reply back to the anonymous email? Would like to create something like Craigslist in terms of its anonymous emails so that Logged-in users can send email from the site. Once they do, their email will be changed to randomtext@domain.com instead of their original email. This is to prevent other users from knowing the real email of the authenticated users.

Other users should still be able to send them email with the randomtext@domain.com as To and that reply would be saved on the Users's profile.

How would you go about implementing this? The module I found that's close, but not sure how it works is Mailhandler with Singlebox . But there's rarely any documentation for it. Do you recommend other solutions?

You could use the following components:

an email server you control to create temporary email accounts, or a mail relay service.
use Relation or a custom user field for a user's anonymous email thru user02193213@yoursite.com. Enforce uniqueness of this field. Relation can do alot of this for you as a developer (create a user <-> anonymous email relation, attach category tags to the Relation Entity itself and use relation_query to build reusable lookup functions.
store a mapping of Drupal uid to anonymous emails. In general this is outlined here: https://stackoverflow.com/questions/8179047/email-piping-in-php-like-craigslist-how-do-i-associate-real-emails
upon content submission use Rules to lookup anonymous email addresses of content owner to logged in user and send the email. Your email server you control can then forward to real addresses.

Questions regarding email setup are not drupal setup and inappropriate here. I've just outlined an approach for the Drupal side of things.


Adding a loading indicator to form submission module I have a custom module that is altering a webform to add custom submission handling using:

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

From the time the user clicks the submit button, until the paymentComplete() function completes it takes 2-3 seconds, but the user experience doesn't really indicate what is going on. How can I add some type of 'waiting indicator' that starts right BEFORE the request to execute paymentComplete()?

AFAIK there are no OOTB features in Drupal yet but perhaps you can implement ProgressButtonStyles by Codrops. See https://github.com/codrops/ProgressButtonStyles for more info...


Error applying patch with Git I have read different SE posts and Drupal.org posts about applying patches using git but I am getting an error message whenever I try any of the following methods. the error is:

  error: modules/callbacks.inc: No such file or directory

I tried:

curl https://www.drupal.org/files/issues/op_update_should_be_create-2807275-2.patch | git apply -
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100   668  100   668    0     0   2278      0 --:--:-- --:--:-- --:--:--  2279
error: modules/callbacks.inc: No such file or directory

Also, I downloaded the patch into Drupal root and tried:

git apply -v op_update_should_be_create-2807275-2.patch

The backstory:
I was getting the following errors on my website, which I found this discussion explaining that it was because of Entity API, and I was trying to apply the patch in #2.

  Notice: Undefined property: stdClass::$custom in
  block_block_list_alter() (line 794 of
  /Applications/AMPPS/www/example/docroot/modules/block/block.module).
  Notice: Undefined property: stdClass::$visibility in
  block_block_list_alter() (line 807 of
  /Applications/AMPPS/www/example/docroot/modules/block/block.module).
  Notice: Undefined property: stdClass::$pages in
  block_block_list_alter() (line 817 of
  /Applications/AMPPS/www/example/docroot/modules/block/block.module).

This is my first time trying to apply a patch.

Place op_update_should_be_create-2807275-2.patch into the module folder, in this case being the sites/all/modules/entity folder.

Then in your terminal cd (change directory) into the module folder.

cd /var/www/drupal/sites/all/modules/entity

then

git apply -v op_update_should_be_create-2807275-2.patch

In the discussion, Fago has commited this patch (2 months ago), but into the 7.x-.1.x only.

So I assume you're trying to patch the stable version, 7.x-1.8.

If you use/download the latest dev (7.x-1.x-dev) version, it will already have the patch.

Note: The rule of thumb, is to use the Stable version rather than the Dev version.


Complete clueless how does Facebook OAuth (FBOAuth) work I follow this video to get my Facebook App Id and secret :https://www.youtube.com/watch?v=wyDXlSUHaE8

Drupal module: https://www.drupal.org/project/fboauth

In the setting I added Facebook App Id and secret

In block: I add in my content page.

When I click on Facebook logo and I manage to register.

As a result, I receive this error.

After that this error message appear as well.
The account with username example and email example@gmail.com is not yet activated.

I not sure do I need to continues change setting in Facebook App or I need to do any setting in drupal. Need help.

Many thanks

The message comes from the FBOauth module:

function fboauth_login_user($account) {
  global $user;

  if ($account->status) {
    $form_state['uid'] = $account->uid;
    user_login_submit(array(), $form_state);
  }
  else {
    if ($account->access) {
      drupal_set_message(t('The account with username %name and email %mail ' .
        'is blocked.',
        array('%name' => $account->name,
        '%mail' => $account->mail,)), 'error');
    }
    else {
      drupal_set_message(t('The account with username %name and email %mail ' .
        'is not yet activated.',
        array('%name' => $account->name,
        '%mail' => $account->mail,)), 'error');

    }
  }

  return !empty($user->uid);
}

So the user you're trying to log in with has not yet been activated within Drupal. Once the administrator has activated the account, the user will be able to log in using Facebook.

This is the correct behaviour; un-approved accounts should not be accessible just because they've been signed up through Facebook.


Commerce shipping by weight and country I'm having trouble finding a solution for combining location & weight-based shipping with drupal commerce.

I need to have three shipping zones (DK, EU, ROW) with individually priced weight steps inside each zone (0-500g, 500-1000g, 1000-2000g, 2000-5000g).

I've gone through a bunch of tutorials and looked at other forums where people have similar requests. But haven't found a solution yet - which should be possible for such a 'simple' problem, right?

To sum up I need advice on how to configure the following shipping calculation rules:

Free Shipping (no weight)
DK Shipping (1-500g)
DK Shipping (501-1000g)
DK Shipping (1001-2000g)
DK Shipping (2000-5000g)
EU Shipping (1-500g)
EU Shipping (501-1000g)
EU Shipping (1001-2000g)
EU Shipping (2000-5000g)
ROW Shipping (1-500g)
ROW Shipping (501-1000g)
ROW Shipping (1001-2000g)
ROW Shipping (2000-5000g)

I can't figure out how to check for a line item's weight in a rule?

I've got Shipping, Flat Rate, Physical Product, Physical Fields and Rules Extra enabled.

I ended up doing 12 rules as @nvahalik suggested. Here's an export of one of them. Doing the others is just a matter of cloning this rule and changing weight, territories and shipping price accordingly

{ "rules_dk_shipping_1_499g" : {
    "LABEL" : "DK shipping (1-499g)",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "TAGS" : [ "Commerce Checkout", "Commerce Payment" ],
    "REQUIRES" : [
      "rules",
      "commerce_physical",
      "commerce_order",
      "commerce_line_item",
      "commerce_shipping"
    ],
    "ON" : { "commerce_shipping_calculate_rate" : [] },
    "IF" : [
      { "data_is" : { "data" : [ "commerce-line-item:type" ], "value" : "shipping" } },
      { "data_is" : {
          "data" : [ "commerce-line-item:commerce-shipping-service" ],
          "value" : "by_weight"
        }
      },
      { "entity_has_field" : {
          "entity" : [ "commerce-line-item:order" ],
          "field" : "commerce_customer_shipping"
        }
      },
      { "commerce_physical_rules_order_weight_comparison" : {
          "commerce_order" : [ "commerce-line-item:order" ],
          "operator" : "\u003E=",
          "value" : "1",
          "unit" : "g"
        }
      },
      { "commerce_physical_rules_order_weight_comparison" : {
          "commerce_order" : [ "commerce-line-item:order" ],
          "operator" : "\u003C",
          "value" : "500",
          "unit" : "g"
        }
      },
      { "commerce_order_compare_address" : {
          "commerce_order" : [ "commerce-line-item:order" ],
          "address_field" : "commerce_customer_shipping|commerce_customer_address",
          "address_component" : "country",
          "operator" : "is one of",
          "value" : "DK"
        }
      }
    ],
    "DO" : [
      { "commerce_line_item_unit_price_amount" : {
          "commerce_line_item" : [ "commerce_line_item" ],
          "amount" : "3300",
          "component_name" : "shipping",
          "round_mode" : "0"
        }
      }
    ]
  }
}


Add icon to menu link that has system.admin as a parent So I have this code in my links.meny.yml file:

webtrack_update_reminder.main:
  title: 'Reminders'
  description: 'Reminders for your project'
  parent: system.admin
  route_name: webtrack_update_reminder.content
  weight: 100

Which adds a link to the "manage toolbar".
Now my question is, how do I place an icon next to the link, just like the other links in the toolbar?

I have been searching but I didn't came up with an answer for Drupal 8.

As per the answer by @mradcliffe, styles for the regular and active states would need to be created.  However you'd want to add them as a separate library which you'd include on admin pages, rather than edit core files.

So take the styles in @mradcliffe's answer, or whatever you determine to be correct, and save it to your module in css/webtrack-update-reminder-toolbar-icon.css.

In your module's webtrack_update_reminder.libraries.yml file, something like this:

toolbar-icon:
  version: 1.0
  css:
    theme:
      css/webtrack-update-reminder-toolbar-icon.css: {}

Then in your module's webtrack_update_reminder.module file, something like so:

/**
 * Implements hook_page_attachments().
 */
function webtrack_update_reminder_page_attachments(array &$attachments) {
  $is_admin = \Drupal::service('router.admin_context')->isAdminRoute();
  if ($is_admin){
    $attachments['#attached']['library'][] = 'webtrack_update_reminder/toolbar-icon';
  }
}

That should be all that's needed to load the library (i.e. your stylesheet) on any admin pages, which will in turn apply your styles to the toolbar item and show your custom toolbar icon.


Redirect to front page after emptying the shopping cart (ubercart) How can I redirect to the front page after emptying the cart. I am making a commerce site using the Ubercart module, but it is not redirecting to the front page after the cart is empty.

You can use drupal_goto function.

drupal_goto('<front>');


How can i display tokens with html tags? On assigning tokens(both custom and exisiting tokens) with values like

$replacements[$original] = "Hello";

and then using that token either in full html or any other text format(all the text formats) it displays on the screen Hello i.e actual tags are being rendered instead of Hello . Same is happening with other html tags i.e entire

 all the html tags get display.
This although does not happen in Drupal 7.

Is there any configuration i am missing? How to render html values properly using tokens?

Try this one -

$replacements[$original] = \Drupal\Core\Render\Markup::create("<b>Hello</b>");

Helpful links:

https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Render%21Markup.php/class/Markup/8.2.x

http://www.drupaldump.com/drupal-8-how-have-custom-tokens-html-them-properly-replaced


How to sync a Drupal calendar with an iphone/ipad Calendar? Is there a way for us to sync our Drupal calendar to an iphone/ipad calendar?

The Date iCal module can be used for syncing a Drupal calendar in both directions. Some more details about it (from its project page):

... your one-stop shop for iCal support in Drupal. It provides a plugin for Views to enable exporting your site's calendar as an iCal feed, and a plugin for Feeds to enable importing external iCal feeds into your site's calendar.
Any entity which contains a Date field can be utilized by Date iCal for import and export of iCal feeds.

So it provides:

a plugin for the Views module to enable exporting a Drupal calendar as an iCal feed.
a plugin for the Feeds module to enable importing external iCal feeds into a Drupal calendar.


WYSIWYG Image Upload in Basic Page (CKEditor and CKFinder) I was able to use CKEditor and CKFinder to add in-body image upload capability for article nodes.
However, the functionality was not transferred to basic page nodes.
What do I miss? Thanks!

If it looks like you can upload nodes to your basic page, but they're not displaying then you're probably using filtered HTML as your page filter. If you don't have the ability to add pictures at all, then look at the configuration of CKEditor and you may need to add the appropriate button for the content type.


Why and what wrapper should I use for my module's JavaScript file? I am defining a d3.js script for my module like this:

test:
  js:
    js/test.js: {}
  dependencies:
    - mymodule/d3
    - core/drupalSettings
d3:
  remote: https://d3js.org
  version: "4.x"
  license:
    name: BSD
    url: https://opensource.org/licenses/BSD-3-Clause
    gpl-compatible: true
  js:
    https://d3js.org/d3.v4.min.js: { type: external, minified: true }

In my controller, I am sending my data (in $data) to the script, like this:

$page[] = array(
  '#markup' => 'foo',
  '#attached' => array(
    'library' =>  array(
      'mymodule/test',
    ),
    'drupalSettings' => array(
      'mymodule' => array(
        'test' => array(
          'data' => $data,
        ),
      ),
    ),
  )
);

It's working fine, but I've noticed that most js files in core have a wrapper - there is some information here.

Should I be using a wrapper for my script? and if so, what should the wrapper be? and why?

There is no jQuery in my script:

(function (Drupal, drupalSettings, d3) {
  Drupal.behaviors.mymoduleTest = {
    attach: function (context, settings) {

      const data = JSON.parse(drupalSettings.mymodule.test.data);

      ...

      console.log(data);

    }
  };
})(Drupal, drupalSettings, d3);

I'm wrapping my code, with these three lines top an bottom, but I don't understand if I need any of it?

There are a couple of different things at play here.

This:

(function (Drupal, drupalSettings, d3) {

})(Drupal, drupalSettings, d3));

is an Immediately Invoked Function Expression (IIFE). Quoting gion_13 from the canonical SO post on the subject:

  This pattern is often used when trying to avoid polluting the global namespace, because all the variables used inside the IIFE (like in any other normal function) are not visible outside its scope.

That's why you'll see it so often in Drupal's (and pretty much any other framework or library's) JS code; it's generally considered good practice.

Ben Alman's blog post is a must read if you're not familiar with this pattern. Yes, it's a good idea to use it in your own code.

This:

Drupal.behaviors.mymoduleTest = {
    attach: function() {

    }
};

is a Drupal "behavior". Quoting the docs:

  Any object defined as a property of Drupal.behaviors will get its attach() method called when the DOM has loaded both initially and after any AJAX calls.

This allows your code to re-run on elements that may have been replaced as a result of an AJAX or other JS event, so you don't need to keep track of that.

Say you had a d3 chart bound to an element in the content area, and an AJAX operation on the page replaces the content area with new HTML; the d3 bindings will be lost, and the chart will no longer show. Assuming the AJAX op was invoked by Drupal's API in some way, your attach method will be invoked automatically, and the chart will be re-bound to the new element in the content area.

It's a good idea to conform to this pattern when writing JS code for a Drupal site, it has the potential to save time and headaches later on.

As always it'll pay to use common sense with stuff like this; if you find yourself using these patterns, then immediately trying to get around them for a couple of specific requirements, those situations may be exceptions where it's best not to use them.


How to customize entity print pdf I've installed Entity Print in order to create PDF files. I've read the documentation to enable a twig template to customize the pdf output, but I don't know how to do simple things, in the twig file, like add a page header and footer, add a front page, etc. Are there any docs about how to customize it?

It depends on which print engine you're using. I am using the following entity-print.html.twig with the dompdf engine.

    <meta charset="utf-8">
    <title>{{ title }}</title>
    {{ entity_print_css }}

{# The footer is repeated on all pages and must be printed first. #}

    {{  footer  }}

{%  if cover_page  %}

    {{ cover_page }}

{%  endif  %}
{# The header is repeated after the cover page for all pages. #}

    {{  header  }}

    {{ content }}

The header and footer must be styled with position: fixed, after which they are displayed on every page.

I haven't found any great combined reference for the entity print module, but searching for what you want to accomplish along with your print engine's name should be helpful.


How to use different sets of fields for unique pages like the home page? Some pages, like the home page, have unique content/layouts that are very different from basic pages. I want the editor to be able to fill in a different set of fields for the home page. Currently, the only way I can achieve this is by making a "Home Page" content type and setting up its fields. However, that feels wrong to make a whole content type for just one page. It would be great if the editor can create a basic page, then choose a layout (maybe a dropdown with the options: Default Page, Home Page, About Page, etc). Each layout would have it's own set of fields.

In WordPress, this can easily be achieved by assigning fields (usually with the Advanced Custom Fields plugin) to different page templates. I would love to replicate this in Drupal.

In Drupal you can achive this using Paragraphs

  Paragraphs module comes with a new "paragraphs" field type that works
  like Entity Reference's. Simply add a new paragraphs field on any
  Content Type you want and choose which Paragraph Types should be
  available to end-users. They can then add as many Paragraph items as
  you allowed them to and reorder them at will.

You can create paragraph types, and these paragraph types you can add sets of fields.

Alternatively, if you just need this type of functionality for the home page only, then just create a block type /admin/structure/block/block-content/types and add fields to it and then create a block of your block type and assign this block to the home page only.


How do I target Ajax Loader Throbber in CSS? I recently installed Ajax Loader and it working great. However, I need some custom styling so, I can display the loading throbber in the center of the screen.

I can write my own CSS, But can't find the target class of Ajax Loader.

Looking forward for any help on this issue. Thanks in advance

To target the overlay you can use .ajax-progress and to target the throbber you can use .ajax-throbber.

Something like this would position the throbber on the center of the screen:

.ajax-progress {
  position: fixed;
  z-index: 99999999;
  background: rgba(255,255,255,0.6);
  text-align: center;
  width: 100%;
  height: 100%;
  top:0;
  left:0;
}

.ajax-throbber {
  left: 0;
  position:absolute;
  right:0;
  top: 50%;
  transform: translateY(-50%);
}


how do I theme rounded corners in Panels 7.x-3.3 I looked through older questions & answers and some examples about styling rounded corners and they seemed valid but when I look into the code in Panels 7.x-3.3 I see an entire function that dynamically generates rounded-corners and tells Drupal where to find the image files.

I have new image files for the rounded-corners. How do I over-ride this function without hacking the module itself?

Ex. (This function is in rounded_corners.inc)

/**
 * Generates the dynamic CSS.
 */
function _panels_rounded_corners_css($idstr) {
  $url = panels_get_path('plugins/styles/corners', TRUE);

  $css = <<<EOF

.t-edge, .b-edge, .l-edge, .r-edge, .wrap-corner {
  position: relative;
  /* hasLayout -1 ? For IE only */
  zoom: 1;
}
$idstr .t-edge {
  background: url($url/shadow-t.png) repeat-x 0 top;
  font-size: 1px;
}
$idstr .b-edge {
  background: url($url/shadow-b.png) repeat-x 0 bottom;
  font-size: 1px;
}
$idstr .l-edge {
  background: url($url/shadow-l.png) repeat-y 0 0;
}
$idstr .r-edge {
  background: url($url/shadow-r.png) repeat-y right 0;
}
$idstr .wrap-corner {
  background: #fff !important;
}
$idstr .wrap-corner .t-edge, $idstr .wrap-corner .b-edge {
  height: 11px;
}
$idstr .wrap-corner .l, $idstr .wrap-corner .r {
  position: absolute;
  top: 0;
  height: 11px;
  width: 11px;
  background-image: url($url/corner-bits.png);
}
$idstr .wrap-corner .l {
  left: 0;
}
$idstr .wrap-corner .r {
  right: 0;
  background-position: -11px 0;
}
$idstr .wrap-corner .b-edge .l {
  background-position: 0 -11px;
}
$idstr .wrap-corner .b-edge .r {
  background-position: -11px -11px;
}
$idstr .wrap-corner .r-edge {
  padding: 5px 24px;
}
$idstr div.admin-links {
  margin-top: -14px;
  margin-left: -12px;
}

$idstr .panel-separator {
  background: url($url/shadow-b.png) repeat-x 0 center;
  font-size: 1px;
  height: 30px;
}

$idstr .rounded-corner {
  margin-bottom: 1em;
}

EOF;

  return $css;
}

The functionality you refer to predates common browser support for rounded corners, when images was the only reasonable solution.

Today, I would most likely no use it, but instead implement it with the modern CSS approach.

If you really want to modify the existing functionality though, it's called a Style. You can see this question for details about implementing ctools plugins: What are Ctools plugin (content type, access, etc), and how does one create them?


How to set up a Weekly Digest I need to set up a weekly email digest of all content from a few particular content types (latest news, latest tech articles etc.) for all users in a particular group.

I have Simplenews installed and it looks like the Simplenews Digest module is not updated. Is there anything else that offers the feature I am looking for?

You can make an RSS feed of the digest and then use Mailchimp to make a newsletter of that RSS feed.
This has to be setup one time and the rest is automated.
Mailchimp module synchronizes Drupal user groups with the mailing lists and groups.


After registration password : Your password is not correct Once i registered my account with email and username, mail from account settings is getting. In that mail Password : Your password is displaying. If i used that password, it shows incorrect. I check ed in my account settings, its shows
username: [user:name]
password: Your password
What i need to change to get the correct password in mail

Try this module : Registration Password Token. It will provide the user register password as a token.

  This small module provides token [user:password] during user registration. Site administrator allowed to customize the text of the e-mail that is sent to the user after registration.


Get url from image field For each user, I created a new field called field_cover, this field is an image.

I want to get the field_cover path, to use it into a background-image property.

I try this but it does not work.

<?php print render (file_create_url($user_profile['field_cover'])); ?>

Thanks for your help !

The function file_create_url() in D7 needs a uri (see this useful article). You can typically access the uri of a file this way:

$user_object->field_name[LANGUAGE_NONE][0]['uri'].

In your case, since $user_profile seems to be an array of fields, try:

file_create_url($user_profile['field_cover'][LANGUAGE_NONE][0]['uri']).

This should return the full URL of the image.

Further information in your question may help me fine tune this answer.


How to add checkbox to existing administration page For a custom module i would love to add a checkbox to "BANDWIDTH OPTIMIZATION" under "admin/config/development/performance". I know how to add a new admin page but this is just one checkbox and i think it would fit more there.

Can anyone tell me how to do that?

To alter a form implemented by another module, you just implement hook_form_alter(). You probably need to change the #weight property of the form element you are adding, to avoid it is rendered in the wrong place.

function mymodule_form_system_performance_settings_alter(&$form, &$form_state) {
 // Add the checkbox to $form.
}


Hide empty results in views caused by entity translation? I have a view generated by Views module and Entity Translation module enabled with the option "Enable language fallback" disabled. This should mean that if the language is not available the post should not be shown.

So if I'm showing the site in English and a post is only available in Italian it should not be considered.

In fact, in the view the post are shown as they have all fields empty.

I tried to check, inside, every field of the view

"Hide if empty"
"Hide rewriting if empty"
"Count the number 0 as empty" and even
"Remove whitespace" in rewrite result.

In the "Format" part of the view I choose "Grid" and "Fields" and in fields setting checked "Hide empty fields"

I tried to apply path 35 and 40, no fortune.

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

Any ideas?

THE SOLUTION: after three days, i got that if you use entity translation in the 'entity' mode, you get some option in Views filters. In my case, only the field "body" in nodes was translatable and there was an option, among filter

Body's language

Setting this to "Current user's language" does the trick.

I heard about an option Node Translation to be set this way, but you don't have that option if you check as translatable only some field and not the whole node.


How can I programmatically enable clean URLs during a SimpleTest? How can I enable clean URLs from the SimpleTest setUp() method?

Which .htaccess will be used during a simpletest?  I needed to make modifications to RewriteBase to get clean URL's working on the 'non-testing environment', will they carry over to the test environment or do I need to modify .htaccess in setUp() as well?

Did a few tests and here is what I found.

Enable Clean URLs in setUp() method:

function setUp() {
    variable_set('clean_url', 1);
}

.htaccess from live site is used during SimpleTest.  Modifications are not required.


Can I add a page without clearing cache? I have written a module by which user can add custom pages. Do I need to clear the cache every time user adds a page? Is there a way to adding pages without clearing cache? If yes what is it? and if no what's the function I should call?

Is hook_menu the only function I should put my code in it?

Does the Views module clear cache after submitting a new page?

It's not clearing the cache you should do, it's menu_rebuild(); if you change router items.


Simplenews Scheduler - only send newsletter when attached EVA view contains results Simplenews Scheduler is working well for me to send a weekly email which contains an attached view (using EVA) of nodes.

I would like the newsletter to only send if the attached view contains nodes, so that empty newsletters are not sent.

I can see that this should be possible using the 'Additionally only create newsletter edition if the following code returns true' field on the Newsletter > Send newsletter according to schedule page.
I am currently using this (which always produces a newsletter regardless of whether nodes are displayed in the view):

if(views_get_view('job_type_c_list')) {
      return true;
}

I have tried using the overall length of the node body to try to work out if a view is present. (I don't know if the tokens can be used in this field or not):

if(views_get_view('job_type_c_list')) {
     $myvar = [node:body:?];
     if(strlen($myvar) >= 30) {
           return true;
      }
}

When i was working with PHP in the body of the node I was able to evaluate whether EVA was returning nodes by using

<?php
    $view = views_get_view('job_type_c_list');
    $printedview = $view->preview('default');

    $myvar = (string)$printedview;

    if(strlen($myvar) >= 1000) {
           print "VIEW ATTACHED";
    }

    else if(strlen($myvar) < 1000) {
           print "NO VIEW ATTACHED";
    }
?>

The above code is clearly not the most elegant, but it worked in the node itself. Unfortunately it didn't work in the 'Additionally only create newsletter edition if the following code returns true' Simple news scheduler field.

I have struggled with this for quite some time and would really appreciate some help.
Code suggestions would be great, but failing that knowing 'If I can use tokens in the field?' and 'why does the PHP in this field behaves differently to PHP the node itself?' would also be very helpful.

I have had an issue open in the module issues page for a few days now, but it has not received any responses.

did you find out a way to do it? In your example, using views_get_view will always return true, because even if the view has no result, the result of the function will be an object, so will not be empty. If you're using views_get_view, you will always have a <div> inside.
You should get the view, then do a preview and then check if there is results or not.

Like this:

 $view = views_get_view('view_id');
 $print_view = $view->preview('display_id');
 if(!empty($view->result)) {
   print $print_view;
 }

I would be happy to know if you found a solution to this because I will face the same problem in a couple of days, thanks!


How to create Stacked area charts instead of Basic area charts using the Charts module? Anyone know how to create multiple stacked area charts vs multiple basic area charts in Drupal using the Views integration of the Charts module (and using Highcharts as the charting engine)?

I would like to create a (stacked area) chart as shown at http://www.highcharts.com/demo/area-stacked, as opposed to the (basic area) chart as shown at http://www.highcharts.com/demo/area-basic.

Also, I would like pop up information to work with multiple stacked charts as it does with single area charts.  It works on the sites included above but does not work with charts created with Drupal Views.

Stacking the charts

The most recent Charts version does not yet support "stacked" charts (of type Area, or Column, etc.).

However, have a look at the support issue (not bug!) about Stacking column/bar charts. Even though that issue is not about "Area", the approach should also work for Area charts. The clue is in comment nr 1 or nr 3 of that issue, i.e. this specific line: $chart['#stacking'] = true;. So if you succeed in passing that, you solved your question. This is what you can see in the example included there:

<?php
function MYMODULE_chart_alter(&$chart, $chart_id) {
  dsm($chart_id); // Need Developer module enabled for dsm to work
  if ($chart_id == 'MYCHARTVIEW__DISPLAY') { // Watch out for those double underscores
    $chart['#stacking'] = TRUE;
  }
}
?>

Obviously, the above requires a custom module, since it's not possible "yet" to so via the Views UI.

You may also want to have a look at these somehow related feature requests, which possibly provide an alternative to what you're trying to get to work:

Pass library-specific options via existing #raw_options.
Add an "Additional raw settings" text area to the config form.

Once we'll have these feature requests committed, we'll have a solution for using options that are specific for either of the supported charting engines (Google Charts or Highcharts). While still not deviating from a key design concept of the Charts module, which is that all supported charting options should work for either charting engines (you should be able to easily swap from one to the other charting engine, without your charts being affected).

Popup information

Refer to "Combination chart without aggregation" for an online demo of a chart (with multiple stacked charts) that shows such popup information (perform a mouse-over for any of the data points to see them at work).

This demo sample using Google Charts as its charting engine (not the Highcharts as in your question). Since nowhere within the Charts module there is some option to specify like "add popup information", my best guess would be that, by default (without specifying any charting engine options about it), the default for Google Charts is that such charts are created with such popups, while for Highcharts they are created without them. As a quick debugging hint: temporary change to the Google Charts engine and revisit your same chart, to check if that makes them show up in that case. So that you know it's really a Highcharts related setting that's missing (and which differs from the default).

If it doesn't seem to work for the Highcharts library, then you'll have to find out what the specific charting engine option for this is to make it work (there are tons of options in each charting engine, nobody knows them all, at least not me). After you know the specific option(s), you could try to use an approach of passing these options as raw_options, similar to stacking the charts.

Disclosure: I'm a co-maintainer of the Charts module.


History of particular content items I want to track the history of particular content items on particular date,
ex: i have saved the node of content on 9/4/2015 and also i have edited the same node on 9/9/15, so when i give the from date 9/4/15 to date 9/9/15 with filter condition field,it should show the all changes that has been done for that particular filter condition field on From to To date mentioned, I tried to create a view of content revisions but it's of no use because revisions are shown for all content items. How do I create a view of the revisions of a specific item?by giving filter condition From to To date.

You can try the Workbench Moderation module.

  Workbench Moderation adds arbitrary moderation states to Drupal core's
  "unpublished" and "published" node states, and affects the behavior of
  node revisions when nodes are published. Moderation states are tracked
  per-revision; rather than moderating nodes, Workbench Moderation
  moderates revisions.


How to track and display selected user activities in a site? I wonder how to track and display user activities in a Drupal site. Examples of such activities are:

posts.
comments.
page posts.

I've found some modules that track the users' activites all over the social media, but I need something much more local (within the site).

I was also thinking about using Views to create a block with this kind of filters, but I have never seen filters as specific as users. Is there a way to achieve this?

There are a few modules that could help you out (quotes included are from their project pages):

Activity:

  ... keeps track of the things people do on your site and provides mini-feeds of these activities in blocks, in a specialized table, and via RSS. The module is extensible so that any other module can integrate with it. The messages that are produced are customizable via the admin interface and are context sensitive.

Heartbeat

  ... displays user activity on a website. This module is an API to log activity. The logged data contains message structures, attributes and variables. Once the activity messages exist in the database, they will be parsed and build into activity streams.

User Activity

  ... calculates an activity index based on a user's logins, page impressions, created nodes and comments. The weight for each value is adjustable by an administrator. It provides an activity-o-meter on the user's profile page, a block with the most active users and an overview page of users sorted by activity.

User Stats

  ... provides commonly requested user statistics for themers, IP address tracking and Views integration.

Which one(s) you choose really depend on what exactly you want to accomplish (use Views or not, display only post info or login stats, etc).  I'm sure there are more out there that I am missing.

Activity stream modules (on Groups.Drupal.org) contains a comparison about the functionality and architecture of some activity modules.


How do I calculate field_1 + field_2 in Twig? I have two fields. {{ content.field_1 }} is 2; {{ content.field_2 }} is 5.

How do I multiply them to obtain 10, in a template file?

In {{ content }} are render arrays which produce the output "2" and "5", but you can't do arithmetics with these render arrays.

You can try to do this with the database values from the node (if it is a node template):

{{ node.field_1.value * node.field_2.value }}


Making a new field via module I've been following the Drupal example on how to create a new field. I can get their example to work fine, but when I try my own it does not seem to store any data, i.e. the field is always blank when I load the node back. I am ultimately attempting to create a field which can hold multiple pieces of information, a bit like the example three field color code. Although I would want a better storage then expanding a value into an array (I have an idea on this, but until I have the basic data storage working I cannot comment on this).

The example is here.

This is my code from the module; I have stripped the example down to the bare minimum, and I have checked it works on the color wheel code.

 function prodlist_field_schema($field) {
  if ($field['type'] == 'prodlist_code') {
      $columns = array(
        'prodcode' => array(
          'type' => 'varchar',
          'length' => 7,
          'not null' => FALSE,
        ),
      );
  }
  return array('columns' => $columns);
}

function prodlist_field_info() {
  return array(
    'prodlist_code' => array(
      'label' => t('Product Code'),
      'description' => t('Used to assign product codes'),
      'default_widget' => 'prodlist_text',
      'default_formatter' => 'field_example_simple_text',
    ),
  );
}

function prodlist_field_widget_info() {
  return array(
     'prodlist_text' => array(
      'label' => t('Prodcode entry fields'),
      'field types' => array('prodlist_code'),
    ),

  );
}

function prodlist_field_is_empty($item, $field) {
  return empty($item['prodlist_code']);
}

function prodlist_field_widget_form(&$form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) {
  $value = isset($items[$delta]['prodlist_code']) ? $items[$delta]['prodlist_code'] : 'emptyonload';

  $widget = $element;
  $widget['#delta'] = $delta;

    $widget += array(
          '#type' => 'textfield',
          '#title' => 'prodcode',
          '#size' => 23,
          '#default_value' => $value,
        );

  $element['prodcode'] = $widget;
  return $element;
}

I found another great example in the book "Drupal 7 Module Development", having worked through this example I am now able to alter it to my own purposes and the data is persistent.

Below is a working 3 field example.

function prodlist_field_info() {
  return array(
    'productorder' => array(
      'label' => t('Product Code'),
      'description' => t('Used to assign product codes'),
      'default_widget' => 'prodlist_text',
      'default_formatter' => 'field_example_simple_text',
    ),
  );
}

function prodlist_field_schema($field) {
  if ($field['type'] =='productorder') {
      $schema['columns']['code'] = array(
        'type' => 'varchar',
        'length' => 10,
        'not null' => FALSE,
      );
      $schema['columns']['description'] = array(
        'type' => 'varchar',
        'length' => 10,
        'not null' => FALSE,
      );
      $schema['columns']['amount'] = array(
        'type' => 'int',
        'not null' => FALSE,
      );

      $schema['indexes'] = array(
        'code' => array('code'),
        'description' => array('description'),
        'amount' => array('amount'),
      );

      return $schema;
  }

}

function prodlist_field_is_empty($item, $field) {
  if ($field['type'] == 'productorder') {
    if (empty($item['code']) && empty($item['description']) && empty($item['amount']) ) {
      return TRUE;
    }
  }
  return FALSE;

}

function prodlist_field_widget_info() {
  return array(
     'prodlist_text' => array(
      'label' => t('Prodcode entry fields'),
      'field types' => array('productorder'),

    ),

  );
}

function prodlist_field_widget_form(&$form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) {
  $base = $element;

  if ($instance['widget']['type'] == 'prodlist_text') {
    $element['code'] = array(
      '#type' => 'textfield',
      '#title' => t('Code'),
      '#default_value' => isset($items[$delta]['code']) ? $items[$delta]['code'] : NULL) + $base;
    $element['description'] = array(
      '#type' => 'textfield',
      '#title' => t('Description'),
      '#default_value' => isset($items[$delta]['description']) ? $items[$delta]['description'] : NULL) + $base;
    $element['amount'] = array(
      '#type' => 'textfield',
      '#title' => t('Amount'),
      '#default_value' => isset($items[$delta]['amount']) ? $items[$delta]['amount'] : NULL) + $base;

  }
  return $element;

}


Specific URL for each kind of content I would like each kind of content to have its own base url, for example, example.com/international-news/friendly-url-of-node-id

How can I manage to get both a friendly url and a base url (friendly-url... and ../international-news/ respectively in the example) with the minimum possible modules (or only those from the core)?

Use Path Auto and Token Module to achieve it. It also supports multilingual functionality!!

  The Pathauto module automatically generates URL/path aliases for
  various kinds of content (nodes, taxonomy terms, users) without
  requiring the user to manually specify the path alias. This allows you
  to have URL aliases like /category/my-node-title instead of /node/123.

Go to admin/config/search/path/patterns path :


Token are not working in my content type fields (they show as they are) I need to have display on all pages a specific token. I have my own content types and I would like fill them with my tokens as well.
I noticed the tokens shows up as they are not as their values.

How can I make tokens display correctly?

You can try using the Token Filter module.

I'm not sure if it will do exactly what you want, but it is a way to have Tokens rendered in your node, if at least in the body text of the node.


Is There A Way To Remove Kickstart Demo Product Types Without Emptying Database? Is there are a (safe) way to delete the demonstration Product Types in Commerce Kickstart 2 without the entire Drupal install?

It appears that the Commerce Kickstart 'Reset' function simply empties the entire db. (yikes).

I've read many discussions on this but they tend to go back to 2011. I was hoping there was a more current (and hopeful) answer. We want to get rid of all the 'Drinks', 'Tops', etc. but keep the Products/Types and other content we've created.

hmm my understanding was that Kickstarter kit was a "hey see what it can do once fully configured!" example of Commerce. Understanding the setup -- you could then go back and install/configure Commerce by hands to your needs.
That being said Commerce content I think is just Entities and Nodes, If you want an non-SQL way to reset a site (i've written ~34 sql Delete statements to nuke content from sites in an sql script for drupal -- it's not that hard you just look at node and field_* tables mostly when clearing content from a drupal site) I'd recommend looking at the Delete All module and the documentation found in drush help delete-all as a GUI means of selecting out types of content to nuke from a drupal site.
EDIT: DrupalCamp Montreal 2014 steps to setting up Commerce ala Commerce Kickstart but Not Depending on the Kickstarter kit
Original source (broken):  http://renaudjoubert.com/en/article/step-step-guide-to-installing-commerce-scratch

Step by step guide to installing Commerce from scratch

The following guide was used in a presentation at DrupalCamp Montreal 2014.
The presentation focused on how to install Drupal Commerce from scratch
(i.e. we won't use the Commerce Kickstart distribution).
This is an elevator guide. So get in now because we're going up!

FIRST FLOOR
https://www.drupal.org/project/commerce
Install required modules
drush dl ctools views entity rules addressfield commerce
drush en ctools views entity rules addressfield commerce -y
Installation instructions
https://www.drupal.org/node/1007434
use the provided drush commands
drush en commerce commerce_ui -y
drush en commerce_customer commerce_customer_ui -y
drush en commerce_price -y
drush en commerce_line_item commerce_line_item_ui -y
drush en commerce_order commerce_order_ui -y
drush en commerce_checkout commerce_payment commerce_product -y
drush en commerce_cart commerce_product_pricing -y
drush en commerce_product_ui -y
drush en commerce_tax_ui -y
Add a few more useful modules
drush dl admin_menu module_filter zurb-foundation-7.x-4.x-dev jquery_update -y
drush pm-disable toolbar
drush en admin_menu_toolbar module_filter jquery_update -y
Create a responsive Zurb subtheme
drush fst Your Subtheme Name your_subtheme_name 'A subtheme of ZURB Foundation.'
Set jQuery update to 1.7+ (admin/config/development/jquery_update)
Enable your new responsive subtheme (admin/appearance)

SECOND FLOOR
Quick tour of what we've got soo far
1 Product type named 'Product'
2 tax types
LOTS of hidden functionnalities
NO visible products
and NO, you don't get a store out-of-the-box
Commerce Kickstart gives you that but you won't know how to get there if you don't try from scratch
Create a new product type 'Download'
add file & image fields
Revisit 'Product', the product type installed by Commerce
add an image field
Let's create products
a physical product (Product)
a virtual product (Download)
Now what? where's the store?
Gotcha!

THIRD FLOOR
Out-of-the-box Store is for wimps! ; )
Commerce products only exist in the backstore
products are like brown boxes in a warehouse: they're only accessible to the store's employees
in order to make products accessible to customers, you need to put them on display in a nice and attractive way
how do we do that in Drupal?
we use content types, of course
Create a content type for displaying products
how does Commerce differentiate & recognize product displays from regular content types?
a product reference field!
create product displays and configure them
Alright, let's shop!
wait a minute, nothing happens when i click Add to cart!
Gotcha!

FOURTH FLOOR
In case you didn't read the fine print: some assembly is required, like Ikea, but without the KISS diagrams
Introducing Rules... doh! where's the UI ?
drush en rules_admin -y
go to admin/config/workflow/rules and add a rule that redirects to the cart
Welcome to the cart
Time to checkout wouldn't you say ?
doh!... something isn't right
where are the taxes?
Like I said, Out-of-the-box taxes are for wimps! ; )
Commerce's taxe model is simple
there are tax types; like there are product types and content types
and then there are tax rates which you create using one of the available tax types
Create GST & PST tax rates (note - these taxes are specific to the Province of Quebec in Canada where the camp was held)
Revisit the checkout
Darn, the taxes are not displayed in the expected order! (i.e. GST on this first row, PST on the second row)
How do we change the order in which taxes are displayed ?
the hard way: by overriding theme_commerce_price_formatted_components() in the theme's template.php (see https://drupal.org/node/1095576#comment-8721217)
the easy way: by creating separate tax types for GST and PST and playing with their respective weight (note that at the time of this writing, the behaviour for tax weights does not follow the convention where lighter weights float to the top; see this issue)
Are we in business yet? Not quite.

FITH FLOOR
Setting up a payment method
for simple tests, use the 'Example payment' module (provided by Commerce)
For serious tests and real sales, you can use Stripe or Paypal or whatever works for you. For the purpose of this presentation,I used Stripe.
www.stripe.com
setup an account
get the API keys (secret and publishable)
Install & configure Stripe
drush dl commerce_stripe
drush en commerce_stripe -y
add both keys to the Stripe payment method rule (admin/commerce/config/payment-methods/manage/commerce_payment_commerce_stripe)
Time for some tests
for this, we use the dummy credit cards provided by Stripe
https://stripe.com/docs/testing
When you're happy that all works like it should you can replace de test API keys by the live API keys.
Done!


entity_load based on language selection I have a node for different language, but I would like to load node for "en" language only using entity_load after firing entity query.

How can I achieve it using this function in Drupal 7

Try to install i18n module then you should be able to create a new content type for this node and set the language to EN under the "Multilingual Settings" tab.


file_save_data() cannot save to private:// I have to write a custom module extension, that saves entityform submission after hitting submit button to a PDF file in the private://pdf/<file_name> uri.

At first step it generates the PDF file to a temp directory via TCPDF and then I try to use file_save_data to save it to private directory and upload the file data to the db.

When I upload the file to the public directory, there are no problems, but when I set the uri to private://<pathname/filename> it sends me an error message:

  "The data could not be saved, because the destination is invalid. More information is available in the system log".

In the system log:

  "The data could not be saved because the destination private://pdf/employee_aontest_richie_2014-06-03_00_00_00_59.pdf is invalid. This may be caused by improper use of file_save_data() or a missing stream wrapper."

The code, that should save the whole thing is this:

$title = $node->title; // TCPDF doesn't let you have spaces or colons in your file name
$title_exploded = explode(' ', $title);
$title_imploded = implode('_', $title_exploded);
$imp_exploded = explode(':', $title_imploded);
$imp_exp_imploded = implode('_', $imp_exploded);
$real_title = drupal_strtolower($imp_exp_imploded);
//end of title generation
$save_path = 'private://pdf/'.$real_title.'.pdf';
$handle = fopen($full_path_tcpdf_output, 'r');
$file = file_save_data($handle, $save_path);
fclose($handle);
unlink($full_path_tcpdf_output);

I think the file saving procedure should work this way as it works if I save to public.

I appreciate any further advices.

Check two things:

The private flesystem is configured: look in
/admin/config/media/file-system.
The destination directory (private://pdf) is created. The exact path
of private:// depends on where have tou configured the private
filesystem.


Views vs Performance I'm designing a huge media site. It would need to have about 20 views on the homepage and should attract about 100,000 visitors daily. The site is hosted on a dedicated server. Other than setting up Drupal caching and Boot module, should I be doing anything else to optimize performance? Should I be worried about using Views?

Performance is very subjective and varies widely from site to site, depending on how much custom code you have, how many logins you have, and what your expected usage patterns are.

The first thing you should do is figure out what your expected usage patterns are going to be, put them in a spreadsheet and estimate how many concurrent visitors you'll have on various pages, etc (for example, how many logins will happen at one time, which pages have the highest traffic, are your users authenticated or not).

The second thing you should do is prepare some kind of load test using something like LoadStorm, or even something very basic like JMeter. Set up some scenarios that mimic or exceed your expected traffic patterns. Then run the tests.

When you start load testing you will very quickly see where the bottlenecks in your site are. You can take cachegrind dumps of your site while you are load testing to see where the performance bottlenecks are using the XDebug profiler. You can also watch your database performance (CPU/memory and disk I/O are easy things to keep an eye on).

Once you've done all that, you can look into the following:

PHP opcode caching to speed up your web server
A reverse proxy like Varnish to take some of the load off
Setting up memcached to take load off of the database
Tuning the database
Setting up load balancing with multiple instances

Drupal has a decent listing of caching modules/options and how they perform for authenticated and unauthenticated users here.


Print the secondary links as expanded in a template file I'm trying to print the secondary links for the main menu as expanded in my template node--products.tpl.php. In my menu I have three levels.

-Products

--Product category

---Product

-Another menu link

The result should be a menu with all product categories with the child items. I don't want to print the root level in the menu; I only want the secondary level, and its children to appear.

I have tried to print the secondary menu like this, but the child items doesn't appear. Any help appreciated.

$secondary_menu = theme_get_setting('toggle_secondary_menu') ? menu_secondary_menu() : array();
print theme('links__system_main_menu', array(
    'links' => $secondary_menu,
    'attributes' => array(
    'id' => 'main-menu-links',
    'class' => array('links', 'clearfix'),
  ),
    'heading' => array(
    'text' => t('Main menu'),
    'level' => 'h2',
    'class' => array('element-invisible'),
  ),
));

In your themes template.php add the following:

function THEMENAME_preprocess_page(&$variables) {

  // Get the entire menu tree (you can replace this string with any menu you want)
  $main_menu_tree = menu_tree_all_data('main-menu');

  // Generate structure for rendering the menu.
  $menu = menu_tree_output($tree);

  // Replace the $menu array with the #below array beloning to the first top
  // level menu item.
  $menu = $menu[key($menu)]['#below'];

  // Add $main_menu_no_top as a variable to use in our theme
  $variables['main_menu_no_top'] = $menu;
}

Then, in page.tpl.php, you can just use:

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


How do I create a custom field storage back end? In Drupal the default field storage is in an SQL database. I am creating a custom field type and want it to have non-SQL storage.

In Drupal 7 there was the Field Storage API, which you could use to define your own storage back ends by implementing a module similar to the field_sql_storage module.

How does one do such a thing in Drupal 8?

To give an example usage, I am interested in implementing something similar to Drupal 7's hook_field_storage_load() so I can have fields that load their data from files in the file system.

If it is too complex a thing to give a code example for, a point in the direction of the relevant API and/or default SQL implementation that I can reference should suffice.

Field types implement FieldStorageDefinitionInterface. In Drupal core, there is FieldStorageConfig and BaseFieldDefinition.

So if the desire is to change field storage to an arbitrary file store, then you should create an abstract class similar to BaseFieldDefinition, and have your Field Type classes extend it.


How to know which file to delete in a submit function? I've got a managed file field in a form like this:

$form['source_file'] = array(
  '#type' => 'managed_file',
  '#title' => t('Source File'),
  '#default_value' => isset($data['source_file']) ? $data['source_file'] : 0,
  '#upload_validators' => array(
    'file_validate_is_image' => array(),
    'file_validate_extensions' => array('png gif jpg jpeg'),
  ),
  '#upload_location' => 'public://imagemerge/merge/',
  '#required' => FALSE,
);

My submit function looks like this so far:

function imagemerge_merge_submit($form, &$form_state) {
  $source_file_fid = $form_state['values']['data']['source_file'];
    if ($source_file_fid != 0) {
      $source_file = file_load($source_file_fid);
      $source_file->status = FILE_STATUS_PERMANENT;
      file_save($source_file);
    } else {
      //some logic to determine previous fid?
      //and then a call to file_delete()
    }
  }

The docs for Forms API under managed_file say that it is up to the module to call file_delete. How do I know when and which file to delete?

Ok I solved this but it will be different for each type of form.  The form I was adding this managed_file upload to is actually the image effect form. (image_effect_form(), I had to do some form_altering to add my submit function.) My goal was to add a new image effect that allows placing a source file onto the destination image.

What I finally did was compare the $form_state variables in the submit function for the following actions:

uploading a file when none was previously there
removing a file and submitting no file
removing a file and uploading a new file

For this particular form I came up with the following variables:

$new_fid = $form_state['values']['data']['myformfile'];
$old_fid = $form_state['image_effect']['data']['myformfile'];

Once I got what the new FID is and what the old FID was It was trivial to put together some logic that deletes the file at the appropriate place. The problem is that this isn't universal logic that works for every type of form that has a managed_file in it. There didn't seem to be a standard way to get what the old file FID was. I found it for this specific form but for the next time I do a managed_file I'll have to examine $form_state again and find out if/where the old file FID is stored.

My code for the submit function is below. I also added some logic for the file_usage table.

$source_file_new_fid = $form_state['values']['data']['source_file'];
$source_file_old_fid = $form_state['image_effect']['data']['source_file'];

if ($source_file_new_fid != 0) {
  $source_file = file_load($source_file_new_fid);
  $source_file->status = FILE_STATUS_PERMANENT;
  file_save($source_file);
  file_usage_add($source_file, 'imagemerge', 'image_style', $form_state['image_style']['isid']);
}

if ($source_file_old_fid != 0) {
  $del_file = file_load($source_file_old_fid);
  file_usage_delete($del_file, 'imagemerge', 'image_style', $form_state['image_style']['isid']);
  file_delete($del_file);
}


Altering UserPasswordForm redirect with a custom submit I want to alter the redirect of UserPasswordForm from Drupal’s core, I did this

function maubl_user_form_alter(&$form, FormStateInterface $form_state, $form_id){
switch($form_id) {
case 'user_pass':
    $form['actions']['submit']['#submit'][] = 'maubl_user_submit_forgot_pass';
    break;
}
function maubl_user_submit_forgot_pass(&$form, \Drupal\Core\Form\FormStateInterface $formState){

  $formState->setRedirect('<front>');

}

It does do the redirect correctly, but the submit  from UserPasswordForm doesnt excute anymore, so the mail doesnt get sent, does anyone know why and how I can fix that ?

By adding a submit handler to the submit element you override the main submit handler attached to the form. The use case for this option is if you want a submit element to have a completely different action.

Append your submit handler to the form and it should work as you have intended:

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


Show a region outside page tpl or check node type to show it I'm developing a new custom theme and I need to show a region of the theme only in a specific sections of the site.

I tried looking about how to render a region outside the page template, but I didn't found anything.

Now, if it is possible, how can I do that?

If isn't possible, how can I check if a node is generated by a view from the Views module from the page template?
So I could show the region from the correct place when I want to.

I hope my question is clear enough.

Thanks in advance,
Mat.

You might also consider using the Context module to define different contexts for the different cases. But as mentioned elsewhere, the simplest and commonest solution would be to use blocks:

Create a block (or blocks) with the content you wish to show conditionally in it.
Assign that block to the region.
Configure the visibility setting for the block so it only displays on pages with the view on it. An empty region is not displayed on other pages, so if no blocks are visible neither is the region.

If there's a lot of mixed content to be displayed in that region you might also use Panels to create a mini-panel which is then effectively a single block with one visibility setting but having various different items within it (which may also be context-sensitive).


Fieldgroup accordion does not open to first field of group I am using the accordion group and item via the Field Groups module. If I open an accordion group, scroll to the bottom of the group and then click on the next one to open, the new group opens in the same place in the browser as I was left at. But the new group header goes to the top of the page. So I'm left in the middle or at the end of the group I'm trying to access, rather than at the top of the new group.

Very confusing to describe!

This is the solution I ended up using. I got it from I got it here: https://stackoverflow.com/questions/3621161/jquery-accordion-will-it-scroll-to-the-top-of-the-open-item.

I tested it at modules/contrib/field_group/field_group.js file at line 66. We then created a patch for it.

Not sure if this is the best solution, but it worked for us, so I thought I'd share the info.

activate: function( event, ui ) {
                    if(!$.isEmptyObject(ui.newHeader.offset())) {
                        $('html:not(:animated), body:not(:animated)').animate({ scrollTop: ui.newHeader.offset().top -150}, 'slow');
                    }
                }


[fixed]Trigger an ajax Submit Form button by clicking on a div I've a form inside a custom template and I would like to trigger the submit button clicking on one div. Then the function submitForm sends the form-data to a webservices using Drupal httpClient.

The twig template is like:

<div class="Rectangle" id="rectangle-div" >
 This is the div containing some stuff that I want to click to submit the form.
</div>

<form id="form-id">
{{ form.elem }}
{{ form.actions.submit }}
</form>

I tried with a simple jQuery function like:

jQuery(function($) {
    $(document).ready(function () {
        $('#rectangle-div').on('click', function () {
            var wrapper = $('#form-id');
            $('.form-submit', wrapper).trigger( "click" );
        });
    });
});

I tried also to write a selector like:

$('button[id^="edit-mod-submit"]', wrapper).trigger( "click");

if I try with a simple submit like

$('form-id').submit();

the js code submits the form but refresh the page avoiding ajax and furthermore doesn't send data to the WS:

(if I use the submit button the data goes to the WS).

Any other ideas?

UPDATE #1: FIXED

I added inside the ajax option of my submit button the event 'click' and now, using jQuery, I am able to send the post request to the WS. The form is like:

 $form['actions']['submit'] = array(
            '#type' => 'submit',
            '#value' => $this->t('Save'),
            '#button_type' => 'primary',
            '#ajax' => [
                'callback' => '::setMessage',
                'event' => 'click',
            ],

        );

The jQuery function is:

jQuery(function($) {
        var wrapper = $('#form-id');
        $('.form-submit', wrapper).trigger( "click" );
    });

Now I should intercept the response coming from the webserver and then execute a JS script, but these are other questions :)

Your code is not triggering an AJAX call, it will just submit the form normally via JavaScript rather than pressing a button, etc. If you want submit the form via AJAX you will need something like:

  var url = $('#form-id').attr('action');
  $.getJSON(url, {
    field1: 'data1',
    field2: 'data2'
  }).done(function(data) {
    console.log(data);
  });

Place this inside $('#rectangle-div').on('click', function () {


How to let a role to change field formatter under view mode? I don't mean to change view modes, I mean to change fields' formatters arbitrarily by some roles under the same view mode.

Your question was a bit unclear.
But for what I understood, try in this page:

  yourwebsite/admin/config/content/formats

To edit permissions of roles, go here:

  yourwebsite/admin/people/permissions


Multiple forms one page always submit with the values of the first I have got a form defined that is displayed multiple times on a single page. For each instance of the form, different values (node ids) are inserted into the hidden fields, which seems to be there once the form is rendered.

However, when I submit any of the forms on the page, the submit handler always gets the values that have been inserted for the first instance and I can't seem to get hold of why this is happening.

One thing that I noticed though is that all of my forms have the same form_id, form_token and only the form_build_id changes.

Any idea why this is happening, I can't find a solution to this problem anywhere.

Thanks a lot.

Code:

I'm attaching the form to the nodes in hook_node_view like this:

$node->processed['add_collection_form'] = drupal_get_form('add_to_collection_form', $node->nid);

when I try to do it in hook_node_load drupal always complains about the memory limit in PHP even though I have set it to a generous 1GB, which is pretty weird.

The form on the page are rendered the standard way:

print drupal_render($node->processed['add_collection_form']);

in node--.tpl.php

To use multiple instances of the same form on a page you need to implement hook_forms(), which allows you to essentially use 'aliases' for your forms.

function hook_forms($form_id, $args)
{
  $forms = array();

  // Check if the form id is of the pattern add_to_collection_form-[NUMBER]
  if(preg_match('/^add_to_collection_form-\d+$/', $form_id)
  {
    $forms[$form_id]['callback'] = 'add_to_collection_form';
  }

  return $forms;
}

The above code tells Drupal that if a form ID has the pattern add_to_collection_form-[NUMBER], to use the add_to_collection_form form callback.

Now you can call the forms on your page like this:

drupal_get_form('add_to_collection_form-1', $node->nid);
drupal_get_form('add_to_collection_form-2', $node->nid);
drupal_get_form('add_to_collection_form-3', $node->nid);


How to download a file from private file system I need a function in my module for users to download a file from a private filesystem.

$file : "private://sample.csv"

Which function should be used, file_download(), or  file_transfer()?

function file_download_page() {
  $file = "private://sample.csv";
  //code for downloading $file
}

Please provide sample code.

You just need to call file_create_url().

It will return an URL that will go through Drupal which will then check the appropriate permiss (if you need custom checks, you need to implement hook_file_download)


Webform as a block only When I crate a Webform I do have an option to make it available as a block as well. But in this case it creates a node as well.
How can I create a Webform as a block only?

You will need to create a webform as node. Edit the node and navigate to:

Webform tab -> Form Settings tab -> Advance Settings (located at the bottom of the page).
Check the checkbox for Available as block and your webform will be a block.


Php libchart with value from my custom table I want select value from my custom table where there are tweets saved.
I have the column for the counter of retweets and I want the sum of the count hourly for 24 hour.

I write this code:

$time = time();
$prev_date = date('d-m-Y H:i:s', $time);

$dataSet = new XYSeriesDataSet();

foreach($req as $val){
 $serie = new XYDataSet();
 $val_id = (int)substr((string)$val, 0, strpos((string)$val, "-"));

    for($i=23; $i>=0; $i--){
        $next_date= date('d-m-Y H:i:s', $time - 3600*$i);
        $prev_date= date('d-m-Y H:i:s', $time - 3600*($i+1));
        $next_date = mysql_real_escape_string(trim($next_date));
        $prev_date = mysql_real_escape_string(trim($prev_date));
        /*$weight_q = db_query("SELECT SUM(`retweetCount` + `favoriteCount`)/2 as peso
                        FROM  `ax_twitter`
                        WHERE (`date` BETWEEN '{$prev_date}' AND '{$next_date}') AND (`ID_request` = %d)", $val_id);
        */
        $weight_q = db_query( "SELECT SUM(`retweetCount`) as peso FROM `ax_twitter` WHERE (`date` BETWEEN '$prev_date' AND '$next_date') AND (`ID_request` = %d)", $prev_date, $next_date, $val_id);

        while($row= db_fetch_object($weight_q)){
            echo($row->peso);
            $serie ->addPoint(new Point($next_date, $row->peso));
        }
        $prev_date = $next_date;
    }
$dataSet-> addSerie($val, $serie);

}
$chart->setDataSet($dataSet);

$chart->setTitle("Andamento dei Retweet e Favorite");
$chart->getPlot()->setGraphCaptionRatio(0.8);
$chart->render($path_image);

}

I tried different ways with query sql but I have the following errors:

  warning: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '18:39:52 AND 01-10-2014 19:39:52) AND (ID_request = 1)' at line 1 query: SELECT SUM(retweetCount) as peso FROM ax_twitter WHERE (date BETWEEN 01-10-2014 18:39:52 AND 01-10-2014 19:39:52) AND (ID_request = 1) in trigger_error() (line 134 of C:\xampp\htdocs\drupal\includes\database.mysqli.inc). =>

When I added the quotes to the parameters of the sql query , however do not get any results for my graph. My question: is right way?...is right query?
With PHPAdmin I get right results if set two dates manually
sorry for the language.

Looking at the error msg, I think the code needs to be adapted, so that the current string (as it is now in the error message) like BETWEEN 01-10-2014 18:39:52 AND 01-10-2014 19:39:52 is replaced by BETWEEN "01-10-2014 18:39:52" AND "01-10-2014 19:39:52". So basically prepend and append a " to the variables $prev_date and $next_date ...

What isn't clear to me in this question though:

What is that 'libchart' in the title of this question?
What's the purpose of the $chart in your code? If it is because you're using some charting module, it'd be interesting to know which module you're using, and you might want to add the charts tag to this question also ...


$(...).find(...).once is not a function Drupal 8.2.5 I just updated core from 8.2.4 to 8.2.5 and now I am getting this error in my console which is causing some other JS items not to work

    Uncaught TypeError: $(...).find(...).once is not a function
        at Object.attach (eval at globalEval (jquery.min.js?v=2.2.3:2), <anonymous>:156:44)
        at Object.Drupal.attachBehaviors (drupal.js?v=8.2.5:168)
        at insert (ajax.js?v=8.2.5:1084)
        at Drupal.AjaxCommands.loadEditorsAjax.commands.insert (quickedit.js?v=8.2.5:523)
        at Drupal.Ajax.success (ajax.js?ojj3xe:155)
        at Object.success (ajax.js?v=8.2.5:505)
        at i (jquery.min.js?v=2.2.3:2)
        at Object.fireWith [as resolveWith] (jquery.min.js?v=2.2.3:2)
        at z (jquery.min.js?v=2.2.3:4)
        at XMLHttpRequest.<anonymous> (jquery.min.js?v=2.2.3:4)

Drupal 8.2.4 was using jquery 2.2.3 and so is drupal 8.2.5 so I am not sure what is going on here.

Any ideas? I tried updating jquery to 3.0.0 but that didn't work. Same error.

As suspected and confirmed this is an issue with the bootstrap theme. My advice would be to roll back to the previous working version and open a bug report in their issue queue on drupal.org.


How to create a fixed width image style for all landscape and portrait images? I have an image style: Scale 580x580px.

When I upload a landscape image it gets a width of 580px.
When I upload e.g a portrait image with 809 (width) x 1100px (height) the width of the image (after image style is applied) on the page is 427 x 580px.

How do I manage the width is always 580px? So for all uploaded landscape and portrait images?

Scale only scales the image so it looks proportionate. It will go with either the height 580px or width 580px, which ever is closer.

If you want your image to be exactly 580px x 580px you could use Resize but you will see your image will look stretched.

The only other option that will give you the exact 580px x 580px is Scale and Crop

If you are afraid that something important will get cut off, you can use this awesome module:

Focal Point by DA's own bleen

  Focal Point allows you to specify the portion of an image that is most
  important. This information can be used when the image is cropped or
  cropped and scaled so that you don't, for example, end up with an
  image that cuts off the subject's head.

Then use Focal Point Scale and Crop as your image style effect.


Tabs in Form Module in Drupal 7 How to create Tabs in form Module using FORM API in Drupal 7 and enable and disable them

The Examples for Developers collection of sample modules includes a sample implementation of vertical tabs in forms.


Custom commerce payment methods based on item In my Drupal commerce website, I have 2 payment methods, Payment Method #1, Payment Method #2

This is working just fine but the thing is I need to make it custom for a specific product type, for example if I'm selling Asus products, I want to get 40% pay with Payment Method #1 and the rest via Payment Method #2.

I'm not a module developer so I thought I can make it happen with some customization and/or rules.

I'd like to know if it's possible without module development,what's the best approach and how to do it properly.

thanks in advance.

An administrator can add two payment transactions to an order using different payment methods from the admin > order > payment area.

However an end-user normally selects a single payment method from the radio button form during checkout.

To support multiple payment methods you may need to send the customer through the payment step of the checkout twice, each time with a different amount and a different payment method selected.

Payment method selection is controlled by Rules logic and can be configured there.
The order status controls whether it can be sent through checkout again so may need to be set to the relevant checkout status.
The order amount to be paid may need to be set in custom code during the payment step process.


Administration Structure to list menu items fails to display When I access admin/structure/menu/manage/main-menu this should show a list of all of the menu items and enable re-ordering, enabling, etc. This has stopped working and will only display the top level menu (without styles) and sometime just a blank page.

I think it is related to the number of menu items I have. Checking the database for menu_links shows almost 500 entries. Is there a way around this?

Possibly I need to think differently. I am not actually displaying all of the items on the user menu just the top two levels. But by adding node and hiding them I get the breadcrumbs for 'free'. Is there a better way to handle the breadcrumbs that would enable me to remove excess items from the menus?

Thanks in advance
Andrew W.

If you want to modify only breadcrumb, then you can use one of below module.

custom breadcrumbs:

  Allows administrators to set up parametrized breadcrumb trails for any
  node type, Views, Panels, Taxonomy vocabularies and terms, paths . This allows node types to have "Home > User
  Blog > 2005 > January" style breadcrumbs on the node view page
  itself, synchronizing cleanly with custom views or pathauto aliases.
  Breadcrumb visibility can be customized via a php snippet.

path breadcrumbs

  Path Breadcrumbs module helps you to create breadcrumbs for any page
  with any selection rules and load any entity from the URL!


Server Error 500 when changing pager of Views to display all items I have a View with 1,000 potential items. When it is paged, it works perfectly, both with Ajax paging or normal paging. But when I try to switch off the display type, the server throws a Server Error 500. No log in the watchdog table of the database or any other registry. I guess that there must be some problem with memory or something, but I would expect a PHP memory allocation error or something. It is not practical to show the 1,000 items at a time for the first time, but if I would want to change to some Page scroll pager like jScroll, I am worried that this is not entirely possible in Drupal.

Answering your last statement displaying multiple nodes at once is totally possible in Drupal. (Bear in mind though the power of hosting and caching is something to consider.) Unfortunately, the 500 error isn't helping a lot; a good approach is checking the error logs for any indications there.

If you are suspecting a PHP memory allocation error, try increasing the memory_limit variable in php.ini to a higher value. This link might be helpful.

Displaying thousands of nodes at once needs caching, so your site can be nice and quick. First, enable the caching in the advanced section of your View UI. Also consider using modules like memcache and boost.

As I said, first check what this 500 error you are getting is, because maybe it has nothing to do with the amount of nodes you are displaying.


Url adds zero at the end and duplicate contents appearing Some of my contents have duplicate contents meaning it creates two path for the same content  and I don't know how it track this and it adds zero(-0) at the end of the url like the below

www.example.com/fully-furnished-one-bed-southridge-area-1061-sqft-0

www.example.com/fully-furnished-one-bed-southridge-area-1061-sqft

now I am manually redirecting the url's using global redirect module for the purpose of SEO. Is this correct way to do this ? or I have to set anything to block those url's in ROBOT.txt  and yes it shows duplicate title in webmaster tool, any idea on how to solve this issue ?

This is a common way how url aliases are generated - if there are nodes with the same title, it appends the "0" (and "1", "2" for more duplicates).

So if you really need nodes with duplicate title, you can edit the path alias manually on node edit form to something else. But from the seo point of view, its not a good practice to have multiple pages with same title.

The best option in my opinion is to avoid such duplicates completely. For your situation, you can use Remove Duplicates module to delete duplicate nodes based on the node title.
(For drupal 6, you have to do some coding - here)

One more idea: if the case is that you have multiple content types and you need two nodes of different types to have the same title, change the alias rules so that different types have different urls (e.g. blog/my-title and article/my-title)


Using a sweet alert with preventDefault() I have an event on a form submit.

I set preventDefault() to stop the form submitting then pop a sweetalert with a confirm callback.  If they decide to go ahead is POSTS the form to Drupal.

The issue is that it does not hit the form_submit method but redirects to the same page with a GET request.  If I simply return true from the jQuery submit event it works.

If they confirm I have tried

form.off('submit').submit()

but it still does not work.

Can anybody help as it is driving me crazy?

I solved this, just in case anybody else comes across it.

Drupal uses a variable called $op == "Update", which is an attribute on the Submit .  When you use preventDefault() this is removed from the Form Data.

The solution is to add this to the sweetalert callback function when they confirm to delete or whatever your use case is.

          formE.off('submit');
          var input = $("<input>").attr("type", "hidden").attr("name", "op").val("Update");
          formE.append(input);
          formE.submit();

Drupal now gets that so hits the form_submit function.


How do I remove this part? I have created a content type, but it doesn't use the following part. I want to remove it without using CSS. how can I doit?

You can implement hook_form_alter() for your content type and then do something like this inside your implementation:

// implement hook_form_alter() for cex_3dr content type:
function cex_3dr_form_alter( &$form, $form_state, $form_id ) {

  if ($form_id == 'cex_3dr_node_form')
  {
    // get rid of form elements that may confuse end-users
    unset( $form['menu'] );
    unset( $form['body_field']['format'] );
    unset( $form['revision_information'] );
    unset( $form['path'] );
    unset( $form['attachments'] );
    unset( $form['author'] );
    unset( $form['options'] );
    unset( $form['comment_settings'] );
    unset( $form['buttons']['preview'] );
  }
}

you can also print out the contents of the form to see what fields are there, and then you know which ones to get rid of via an 'unset()'.

BTW, this is Drupal6 logic. Haven't done D7 modules yet, so the technique may vary a bit, but the concept is 'very drupal' so I'd be surprised if it were no longer possible.


drupal_redirect_form not working with entity I have created custom submit form handler for entity using below

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

but when i used

drupal_get_messages($type = NULL);
drupal_set_message('Thanks for your feedback we will contact soon.');
drupal_redirect_form($form_state);

It redirect correctly but entity is not created.

and even if i use drupal_goto() same thing happening.

If you want to redirect a form submit you should use the redirect parameter:

function app_contact_form_submit_message_alter(&$form, &$form_state) {
  drupal_get_messages($type = NULL);
  drupal_set_message('Thanks for your feedback we will contact soon.');
  $form_state['redirect'] = 'node/23'; // The path you want to go
}

This will call drupal_redirect_form($form_state) byt its self, if you call it directly you are skipping the save step.

More info: https://api.drupal.org/comment/18139#comment-18139


Migrate callbacks() with addFieldMapping for destination_dir i want to switch the destination_dir in a custom file migration class derived from DrupalFile6Migration. The DrupalFile6Migration class is provided by the migrate_d2d module.

For this purpose i think it's necessary to use callbacks for field mappings like it's described here:
https://www.drupal.org/node/1133448

I use successful a callback with the field mapping for destination_file in the file migration:

class FileMigration extends DrupalFile6Migration {
  public function __construct(array $arguments) {
    parent::__construct($arguments);
    $this->addFieldMapping('destination_file', 'filepath')
      ->callbacks(array($this, 'myPath'));
  ...
  protected function myPath($uri) {
    // do stuff
  }
...

But when i try do do this with the destination_dir i can't get success.
XDebug shows, that myDestination() is never called:

  this->addFieldMapping('destination_dir')
    ->callbacks('myDestination');
  ...
  protected function myDestination() {
    if(...) {
       return 'private://';
    }
    else {
      return 'public://';
    }
  }

But i can change the destination_dir with defaultValue, e.g.:

  this->addFieldMapping('destination_dir')
    ->defaultValue('private://');

Any suggestions, knowings if callbacks() in combination with destination_dir is perhaps not possible?

Maybe you can use file_class like this

$this->addFieldMapping('field_yourimage_field', 'fidsarray');
$this->addFieldMapping('field_yourimage_field:file_class')
->defaultValue('MigrateFileFid');

The you have to implement prepare row to get the managed file fids you want to import like this

public function prepareRow($current_row) {
 if (parent::prepareRow($current_row) === FALSE) {
  return FALSE;
 }
 //sample code to get the file ids. it may be different in your case
 $fidsarray= array();
 $fidsarray = explode(",", $current_row->columnwith_file_ids_comma separated);
 $current_row->fidsarray=$fidsarray;
}

if you dont have managed files and therefore fids available other options can be used too.
See https://www.drupal.org/node/1540106


How to get user photo to appear in node panel I'm overriding a node template with panels, I'm trying to add the user photo, but the only thing I can seem to add is the username. Does anyone know how to do this? do I have to do something weird like create a mini-panel that loads the user?

Jumped the gun and posted this question before I really messed around with it. All you have to do is add  "User From Node" as a relationship in contexts, then it will show up as picture in panels


How to create a new role with authenticated user permissions I want to create a new role. New role should have all the permissions of authenticated user as well as the some new permissions.

I used the following code,

$role = new stdClass();
$role->name = 'New role';

// load the authenticated user role
$auth_role = user_role_load(DRUPAL_AUTHENTICATED_RID);
$role->weight = $auth_role->weight + 1;

user_role_save($role);

and I will assign the permissions using user_role_change_permissions() or user_role_grant_permissions()

Now I want to assign the authenticated user permissions to this new role. How to achieve this?

Got it. following code will achieve the this functionality,

$role = new stdClass();
$role->name = 'New role';
// load the authenticated user role
$auth_role = user_role_load(DRUPAL_AUTHENTICATED_RID);
// Give the weight more than authenticate user, so that
// New role will have all the authenticated user permissions
// by default.
$role->weight = $auth_role->weight + 1;
user_role_save($role);
$auth_permissions = user_role_permissions(array(DRUPAL_AUTHENTICATED_RID => 'authenticated users'));
$auth_permissions += array('other permissions');
// Grant permissions to our 'New role' role
user_role_grant_permissions($role->rid, array_keys($auth_permissions[DRUPAL_AUTHENTICATED_RID]));


Exporting block with features I want to export block with features.I have installed features_extra and enabled fe_block and then exported my block into my feature. But there's only hook_default_fe_block_settings. I want to export into code also a content of block. So block viem etc. How can I do that? Thanks for help.

You can use Blockexport

Functionality List

It will import all system specific block into a feature.
Import all custom blocks within a feature.
Import all system blocks associated with content type
Import all block roles
No configuration is required.
This module not create any table in your database to minimise the performance issue as much as possible.


Display a video next to a quiz On my site I have a series of quizzes.

Each quiz has it's own video (an embedded Vimeo video).

The videos are on a custom content type called 'Video'.

I want to display the video next to the questions throughout the quiz.

I used the Entity Reference module and on the quiz node I referenced the video node.

I used page manager to display the video node next to the quiz. This was ok but when I started the quiz, the video disappeared.

I thought I could create a block with mini panels or with views and display the referenced node but I can't seem to get that to work.

Does anyone know how to display a node on a block that is being referenced by the current node? Or is there a way I can use page manager to display the video when the quiz is in progress?

I am using Drupal 7, and the Quiz module 7.4.

I worked out a way to do it.

Create a block with some custom PHP.

<?php

//Find current nid
if (arg(0) == 'node' && is_numeric(arg(1))) $nodeid = arg(1);

//Load that node
$node = node_load($nodeid);

//Get referenced entity if it exists
if (isset($node->field_videolink['und'][0]['target_id'])) {
    $refnid = $node->field_videolink['und'][0]['target_id'];

    //Now load that node
    $node2 = node_load($refnid);

    //Display the body
    print($node2->body['und'][0]['value']);
};

?>

The entity reference field is called 'videolink'. You should enable the block only for the quiz content type otherwise you'll get an error on the home page.

Apologies if the PHP is a little shoddy. I'm not an expert by any means.


Extract info from profile insert into node creation Hey Guys I hope you can help!

In short: User Profile fields should be exported to certain parts of the add new page fields, Text and Taxonomy Terms

For example, User profile will have 2 html codes for pictures and 3 taxonomy terms or just the text and these fields need to be filled in automatically inside node creation so the user doesn't need to do this and all goes well. User should not be able to edit or change it as well.

I don't want users to fill in the following things on node creation since it only makes things complicated for them. But it needs to be different for each user and it needs to be done for every node or else things will get displayed on the wrong pages. So I want to set it up once and then it will be automatically filled in the rest of the times. I think its easiest to have this information stored in the user profile which they get after I create the account for them. They don't need to see this and Drupal should pull in the information from the user profile. But how

text field which will need an image html code which is the same for every node of this user displays a small image for the view that shows up in the panel. (so its needs to be filled every single time with an image link)
text field which will need an image html code which is the same for every node of this user but this one display a bigger image for the node. (so its needs to be filled every single time with an image link)
Taxonomy Term 1.
Taxonomy Term 2.
Taxonomy Term 3.
Text user can fill in
Another text a user can fill in.
Date field a user needs to fill in.

In broad strokes, you could intercept the node edit/add form via hook_form_alter()  to remove the fields from the form and then you could implement their population via the hook_node_presave() to grab all the information from the node owner's profile and save the fields in the new node.

Caveat:  if the user can change this information in his/her profile, it won't automatically update any of the node fields unless you add in that logic as well on the saving of this new information to all the nodes already created.


Let the user add a PDF to a content type, but not as an attachment, content type is the pdf I hope the title is a bit clear but this waht I need/want:
At the moment users that have the right to make content can add a PDF for certain content types, this is added as an attachment so users have to go to the content first and then have to click on the PDF to see it.
Is it possible to let my users add only a PDf to a content type and that the content type IS a pdf only?
So when someone goes to that page and clicks the link the PDF is immediately shown
instead of a page in between with an attachment. So this makes it 1 click to see the PDF and not 2.

This doesn't exactly answer your question (since maybe there is a module for that, but not that I'm aware), but here is what I do.

I have a content type for documents with two fields: summary/abstract and then a file upload field that accepts PDFs. If a PDF has a summary or abstract, I put the summary/abstract in that field and just link to the content's page figuring that the user can read that and then click on the document if they want. Otherwise, I still use this document content type to upload the file, leave the summary blank, and then link directly to the uploaded file itself. It would still have its own page created by the content type, but a site user isn't going to see that.


Contextual Filter Problem in Drupal Commerce Using Indexed Textfield I am trying to filter products by brands, which have been inputed into a text field in Drupal Commerce and indexed.

If I try for instance "Breitling" in the contextual filter it works perfectly and I can see the correct products shown in the Views preview. I am using PHP code for the contextual filter. So as a test I just used the following in the contextual field and it does not work (I have tried both options for using the contextual field)

    return "Breitling";

What I do get is no results.

I think it's because the value that you put into the Views preview will just be a value to pass to the PHP code. So if you enter return "Breitling", your code is going to try and find a brand named 'return "Breitling"'.

If you just need to return all results from the brand Breitling for testing purposes, in your PHP code in the contextual filter, set the value to look for as "Breitling".

Let me know how you get on.