Custom block doesn't work correctly when not logged in So I have a custom block module that displays three links, which then when clicked, reload the page and redirect to checkout based on a GET variable.

function innovista_donate_contents() {
  if(isset($_GET['d'])){
    switch ($_GET['d']) {
      case 1:
        $product_id='6';
        break;
      case 2:
        $product_id='8';
        break;
    }
    commerce_cart_product_add_by_id($product_id, $quantity = 1, $combine = TRUE);
    drupal_goto($path = 'checkout', $options = NULL, $http_response_code = 302);
  }
  else {
    return '

      Link 1
      Link 2
';
  }
}

The issue is that if you are not logged in then often the top half of this function that uses the GET var doesn't work. I thought it might be a cache issue so cleared the cache but this hasn't resolved the issue. Any idea what is going on here?

You block is build on the first page request. The else flow is followed. Depending on you settings the page or block is cached. Logged in users don't have cached blocks.

That it worked now and then for anonymous was probably due to your cache clears.

You should create a callback using hook_menu() like

function innovista_donate_menu() {
  return array(
    'innovista/addtocart' => array(
      'title' => 'Innovisata add to cart',
      'page callback' => 'innovista_donate_add_to_cart',
      'access callback' => TRUE, // Accessible for everybody
      'type' => MENU_CALLBACK,
    ),
  );
}

function innovista_donate_add_to_cart() {
  if(isset($_GET['d'])){
    switch ($_GET['d']) {
      case 1:
        $product_id='6';
        break;
      case 2:
        $product_id='8';
        break;
    }
    commerce_cart_product_add_by_id($product_id, 1, TRUE);
    drupal_goto('checkout');
  }
}

Your block can now contain just the links. You can now disabled PHP input filter probably too.

(Note I changed your drupal_goto and removed tabs)


How to link on block I work on D8. I Create to custom block with display content and Read More option. The URL alias is about_us of node/2,  I want to add read more link with node/2 and show about_us on URL.

If you have created that custom block using a view , yo can easily add link to the respective node.You can add content: link in the FIELDS section


Hide the content while the current user has no access on I written a module to filter the access for country_admin,country_admin can only view and edit the content that have the same country with the country_admin.(Both the country_admin and content have a country field.)
Now I want to hide the content that current country_admin have no access on. Is there a function can hide the content in drupal 7 ?
Will be very appreciate if anyone can help.

if(!isset($target_user->field_role_country) || !$target_user->field_role_country['und'][0]['value']) {
  // The value is false (checkbox not checked) so we refuse access:
  return FALSE;
}
elseif ($node->type == 'clinic'
    && strtolower($target_user->field_role_country['und'][0]['value']) != strtolower($node->field_country['und'][0]['value'])) {
  drupal_set_message('This clinic does not associated with :country, You have no permission to view.', array(':country' => $target_user->field_role_country['und'][0]['value']));
  return FALSE;
}

hook_query_alter() serves this purpose.

The exact query alter you want looks like this:

function modulename_query_node_access_alter(QueryAlterableInterface $query) {
  // Obtain node, if needed
  $node = $query->getMetaData('node');

  // Do some calculations

  // Add condition
  $query->condition( /* your custom conditions here */ );
}

More details on Query alteration documentation page.


How to create dynamic panel column content? Hello i am  new to drupal and trying to make a dynamic column content using panels,
so i had created a two columns the right side one is a menu and left side one is about to be dynamic, so when we click a link in the right side menu the content will be rendered in the left side one and we keep the right side menu visible.

By "dynamic", do you mean "only that panel pane changes and the page doesn't reload"?

If so, check https://www.drupal.org/project/jquery_ajax_load and this tutorial http://www.stevepolitodesign.com/blog/load-content-drupal-ajax-without-coding .

If you don't need that functionality, then enable the panel page that overrides /node/%node and put your fields in the left side and your menu in the right.


Views contextual filters by node title I've created a content type: seller and with pathauto module I've set this content type to be seller/[node:title] so every new seller content will be www.example.com/seller/[name_of_the_seller].

I want to add gmap objects in every seller page with only their objects will be visible. (for this detail I'll open a new thread, 'cos I'm not sure how to filter that)

With Views module I've added a page with url:  /seller/%

and in contextual filters I've added Content: Nid.
In When the filter value is NOT in the URL I've selected Provide default value and in the field bellow I've put seller.
That didn't worked, so I've tried with Raw value from URL and checked Use path alias.
That didn't worked too. I've searched couple of other threads, but I didn't find like my problem.

UPDATE

I've solved the problem by creating a block that is displayed seller/*. The two content types has a same taxonomy terms and with contextual filters  Content: Has taxonomy term ID, Provide default value, Taxonomy term ID from URL, I've marked Load default filter from node page, that's good for related taxonomy blocks and Limit terms by vocabulary and I've selected the seller taxonomy.

Since your contextual filter is expecting an nid (you said your contextual filter is set up as 'Content: Nid') - you really have to provide it with an nid even when that filter is not present in the URL.  You can't give it 'seller' as an argument or anything like that because that's not an nid, so it won't help it pull up the correct node.

So to get it to work in those cases, what you really want for your view to do is grab the nid of the current node it appears on.  It's OK if that page has a custom URL, the nid can still be gotten.

Just select 'Content ID from URL' as the default value when an URL argument doesn't exist!  That'll work even if it has a custom alias for the URL.


How to implement a cron job for every minute and every 5 minutes? In D8 I programmed hook_cron. I tested it several times but I cannot see any log in the watchlog.

The name of the module is nncbt. The code is placed in nncbt.module.

Any suggestions what I should do?

function nncbt_cron() {

    $last_run_per_minut = \Drupal::state()->get('nncbt.last_run', 0);
    // If 1 minutes passed since last time.
    if ((REQUEST_TIME - $last_run_per_minut) > 60) {

        \Drupal::logger('nncbt')->info('Runnning Cron every 1 minut log');

        // Update last run.
        \Drupal::state()->set('nncbt.last_run', REQUEST_TIME);

    }

    // Run the following every 5 minutes
    $last_run_per_5_minuts = \Drupal::state()->get('nncbt.last_run_5_minuts', 0);

    // If 5 minutes passed since last time.
    if ((REQUEST_TIME - $last_run_per_5_minuts) > 300) {

        \Drupal::logger('nncbt')->info("Runnning Cron every 5 minut log");

        // Update last run.
        \Drupal::state()->set('nncbt.last_run_5_minuts', REQUEST_TIME);

    }

}

hook_cron()

  The engine will then call the hook whenever a cron run happens, as
  defined by the administrator.

In other words, hook_cron gets executed after a cron run happens. So if you have cron set to run once a day, then your hook_cron script only gets executed once per day. So you need to set cron to run every 5 minutes or less.

A better alternative, I suggest you use a module like Ultimate   Cron which allows you to schedule different cron run times for different cron tasks. This way, cron doesn't run every single task every 5 minutes and instead it runs your specific task only.


Building a search View that respects access control I'm implementing search on a site using taxonomy access control with search api and search api solr.  Reading the help page node access section, I see:

  Needs details on how to build a View that respects access control.

… which is exactly what I need.  How can I make a search view properly respect the taxonomy access control?  I've got node access turned on in the index settings, and see the field available in the views filter, so I see some items with node_access_taxonomy_access_role:n set up, I could try to filter on this, but it would not affect the facets.

I have

  Additional access checks on result entities

turned on in query settings as a temporary measure, but that only filters the search results, and not any facets, etc.

One possible (though inefficient) solution seems like it could be to make two indexes and the have two displays in the search view, searching the right index depending on whether the user is authenticated or not, but I see no good way to limit the index based on the taxonomy term assigned.

It seems like my question extends beyond the boundaries of the search view, and onto the index itself.

For the Search Views module there's an option that enables further access checks on indexed entities that will enable your Taxonomy Access Control permission check.

You'll find in the Views UI under Advanced > Query settings on via the Settings link. It is enabled via the Additional access checks on result entities checkbox. As a caveat, this option will make result counts, pagination, and other search result details behave oddly since  permission checks can't be made at index time.


How can I make this with the Views module? I am trying to find out how to make a view which, in pseudo code, does this:

  If year = 2005 and month = 04 and page = 2 then display 2 articles

I have Views3 installed, but I can't find out how to make the date filter, and how to make the page filter.

How to show only oldest and newest node in Drupal views?

Check this out, I believe you will definately get answer with views, contextual filters.
and with the content type = Article and display only 2 with help of PAGER..

Extended answer

And when select that option, you will get another pop like below image

After making up a selection, write how many items you want to display.

And if you want to add see the month, why you just add fields to display.
also add a content posted date field below image will help out


Always keep admin UI in English when translating content How can I prevent the admin UI switching to a foreign language every time I translate a piece of content?

i.e. I'm editing a Menu item and I've clicked the Translate tab.
I click 'Add' in the German row to add a translation.

However the link always begins /de, which means all the UI labels change as well - to get back to English I have to manually remove it from the address bar and (it seems) do so every single time.

Is there any way to turn this off?

I tried going to Detection and Selection  (/admin/config/regional/language/detection) and checking 'Account Administation pages', or checking 'User' and promoting it to the top of the list, but this didn't seem to make any difference to the button URL or the form output.

This functionality is partially achievable since Drupal 8.6.4.

Navigate to Detection and selection
(admin/config/regional/language/detection)
Adjust your settings accordingly. Be sure to activate "Account administration pages". Your content language detection methods are optional.

Edit your user profile and set your "Administration pages language" to English.

Now your Admin UI will stay in English no matter what the other language detection methods resolve to. That means while creating a translation, the interface will remain in English.

However, the unsupported part is keeping the Admin Toolbar in English when being redirected to the translated page on saving it. But when going back to the Admin UI it's in English again.

These issues are dealing with that:
https://www.drupal.org/project/drupal/issues/2313309

And if you use the Admin Toolbar module:
https://www.drupal.org/project/admin_toolbar/issues/3004575


Customize the display of error messages from the webform module I am embedding the webform in drupal 6 in my home page but the error messages are shown on the webform page, is there a way to customize it so that 'on unsuccessful submission it still shows error messages on my websites home page instead of the webforms page'?

Thanks.

Message are not disabled on home page. Please check for $messages if it is properly rendered in page template file. If you are using a separate template for home page then check it specially.


How to set 'html' email template for webform email setting? Is there any way to use html email for e-mail template in webform email setting?

In my webform node I go to: node/113/webform/emails/1 to change the setting but I don't see any 'html' option. Look my capture:

HTML Mail will give you that option.  It integrates with Webform. To use HTML Mail you will also need Mail System.

Go to Configuration > Mail System and set the Site wide Default to be HTML Mail and the HTML Mail module to be HTML Mail.

And if the option "Send e-mail as HTML" does not appear while editing a Webform email. Go to: admin/config/content/webform check "HTML mail system".


How do I add field collection unlimited items from hook_form_alter()? I am trying to implement what described in Add unlimited field collections in a from of drupal and Field collection with unlimited cardinality pre-populate fields, but the Add more and Remove buttons don't work. I have issues with drupal_rebuild_form().

The code in hook_form_alter() is the following.

$items_count = 3;
$field_name = 'field_story_technology';
$form_theme = $form[$field_name][LANGUAGE_NONE]['#theme'];
// Remove delete and add more buttons
//~ $form_state['field'][$field_name][LANGUAGE_NONE]['items_count'] = $items_count;
$items = &$form_state['field'][$field_name][LANGUAGE_NONE];
$form[$field_name]['und'][0]['remove_button']['#access'] = TRUE;
$form[$field_name]['und']['add_more']['#access'] = TRUE;
// Generate required number of fields collection
if ($items_count > 1 and $items['items_count'] != $items_count) {
  $items['items_count'] = $items_count;
  $items['field']['cardinality'] = FIELD_CARDINALITY_UNLIMITED;//$items_count;
  $form[$field_name][LANGUAGE_NONE] = field_multiple_value_form($items['field'], $items['instance'], LANGUAGE_NONE, array(), $form, $form_state);
  // Reset theme function, as field_multiple_value_form hijacks it
  $form[$field_name][LANGUAGE_NONE]['#theme'] = $form_theme;
  $rebuild_p = TRUE;
  //~ $form_state['rebuild'] = TRUE;
}
// Fill generated fields with data
for ($delta = 0; $delta < ($items_count-1); $delta++) {
  $form['field_story_technology'][LANGUAGE_NONE][$delta]['field_technology_photo_title'][LANGUAGE_NONE][0]['value']['#default_value'] = 'new value';
}
if ($rebuild_p) {
  $form['#after_build'][] = 'tttttt';
}

function tttttt($form, &$form_state) {
  return drupal_rebuild_form($form_state['build_info']['form_id'], $form_state, $form);
}

drupal_rebuild_form() will change my other functionality.

here in my below example i want to attach 5 images which will save in admin field collection , so here is code for it . here 109is node id in which i want to save field collection value. field_manager_update is my field collection name.

<?php $images = array(//images to attach to node
    '0' => 'http://cf.juggle-images.com/matte/white/280x280/drupal-logo-primary.jpg',
    '1' => 'http://cdn.flaticon.com/png/256/37187.png',
    '2' => 'https://www.drupal.org/files/project-images/logo-128x128.jpg',
    '3' => 'http://guillermocerezo.com/sites/default/files/field/image/drupal-logo_0.jpg',
    '4' => 'http://drupalcrafters.org/sites/default/files/DrupalCraft-logo_0.png'
  );

$node = node_load(109);

$field_collection_value = entity_create('field_collection_item', array('field_name' => 'field_manager_update'));

// Attach to the node
$field_collection_value->setHostEntity('node', $node);

for ($i = 0; $i < sizeof($images); $i++) {
    $file_info = system_retrieve_file($images[$i], 'public://pictures/', TRUE, FILE_EXISTS_RENAME); //storing image inside picture folder
    if ($file_info->fid) {//if fid exist then image is saved from URL.
      //$node->field_prop_land_image[LANGUAGE_NONE][$i]['fid'] = $file_info->fid; //assign
      $field_collection_value->field_prop_update_image[LANGUAGE_NONE][$i]['fid'] = $file_info->fid;
    }
}
// Save field-collection item.
$field_collection_value->save();  ?>

Hope it helps :)


taxonomy in block translated I have a custom block code this block return a specific taxonomy in drop down list like this

function manufacturer_country_options() {
  $options = db_query("SELECT name,tid FROM {taxonomy_term_data} WHERE
    vid = 35 ");
  $rows[''] = t('-- Any --');
  foreach ($options as $row) {
    $rows[$row->tid] = $row->name;
  }
  return $rows;
}

but this function does not give me the translation of vocabulary how i can fix it to return the translation

First I'm going to assume that you have enabled/installed Taxonomy translation module.

Second you need to filter taxonomy_term_data by the current language.

So your code should look like the following:

Translation mode: Translate

function manufacturer_country_options() {
  $query = db_select('taxonomy_term_data', 't')
    ->fields('t', array('name', 'tid'))
    ->condition('t.vid', '35');

  if(module_exists('i18n_taxonomy') && i18n_select_mode('taxonomy')) {
    $table_alias = i18n_select_check_table($query, 'taxonomy_term_data', 'tid');
    $query->condition($table_alias . '.language', i18n_select_langcodes());
    $query->addTag('i18n_select');
  }

  $options = $query->execute();

  $rows[''] = t('-- Any --');
  foreach ($options as $row) {
    $rows[$row->tid] = $row->name;
  }
  return $rows;
}

Translation mode: Localize

function manufacturer_country_options() {
  $query = db_select('taxonomy_term_data', 't')
    ->fields('t', array('name', 'tid'))
    ->condition('t.vid', '35');
  $options = $query->execute();

  $rows[''] = t('-- Any --');

  foreach ($options as $row) {
    $term = taxonomy_term_load($row->tid);

    if(module_exists('i18n_taxonomy')){
      $term = i18n_taxonomy_localize_terms($term);
    }

    $rows[$term->tid] = $term->name;
  }
  return $rows;
}


Search API Users filter on roles? While I can filter on content types in Workflow / Data Alterations I do not see anything for roles when adding users. Is it somewhere else or is it something needs to be developed? If the latter, where can I find some pointers, examples on how?

At least from my point of view the API of search api is pretty good documented in the .api.php file. There is a plugin type called "callback" which allows you to filter out stuff with configuration. This and the callback_bundle_filter.inc should give you enough to provide a patch :)

And don't forget to add your include file in the .info file


How to convert a webform into an ordered list? I've tried to preprocess a webform in order to convert the form items into an ordered list. My webform is composed of questions, and I want each question to be a enumerated list element.

The problem is that I cannot find where to convert the <div> following the <form> into an <ol>, and the next nested <div> into an <li>. After navigating webform's source code I could not find a function that says "give me all the webform elements", for example. It all seems to work in the following order:

implement hook node load (load webform components)
implement hook node view (order webform components into a structure that is hard to modify?)
create form
render form using some theming functions

When I use the node preprocessor to alter the components (and attempt to insert a #type = item_list somewhere), it doesn't work. And when using one of the webform theming functions, the data structure comes in a way that is hard to modify. Example:

That variable that I tried to modify was the $variables['elements']['webform']['#form']['submitted'] in a hook_preprocess_node.

Install Theme Developer and look for theming function name.


WSOD on node edit/view pages only after migration - subdomain multisite just migrated my company's website, foo.com, to a new server.  It is a multisite installation with an intranet, intranet.foo.com, installed at /sites/intranet.foo.com.  Everything migrated successfully except for one thing: node view and edit pages are not loading on the intranet (whereas admin pages, view pages, etc., are loading perfectly).

I tried a blank node.tpl.php and the page still didn't load, so the error must be elsewhere.

I have php error reporting enabled in index.php –

but I don't see any php errors (is this even possible - for some types of error?  Anyway I have a ticket open asking the host to enable error reporting in php.ini).

I don't see any WSOD documentation on drupal.org that pertains to this specific predicament (node page WSOD only).

Does anyone have any ideas about server settings that could be causing this to happen on the new server?  Or database issues that could be affecting node pages only?  Or if it is a php code error, where would it be such that it would break only node edit and view pages?

You have to also turn on display_errors (see the examples section of http://php.net/manual/en/function.ini-set.php ).

Usually when display_errors is off php is configured to log errors to some file. You might want to find that file and look at it.

My guess would be that some php-module is missing on that server and some drupal-module that is active on node-edit forms tries to use a function from that php-module.


How to assign user ranks based on their userpoints? I am using the User Points and User points Nodes and Comments modules to calculate user points when they publish an articles or comment on a node.

On these points I want to assign some rank to the user. Like for example

    Upto 100 – Junior Member
    100 to 300 – Senior Member
    300 + - Premier Member

Can someone give me some idea about this?

Your question seems like a perfect usecase for the Goals module (disclosure: I'm its maintainer). It can be used in combination with the userpoints module, though you'd use that combination by granting user points "after a goal is completed".

Here is a possible configuration for your specific case:

Define 3 goals like so:

Junior Member
Senior Member
Premier Member

To achieve goal "Junior Member", define the Task(s) to be completed. E.g.:

Publish 1 (or some other amount of) articles.
Post 1 (or some other amount of) comments.

To achieve goal "Senior Member", define the Task(s) to be completed. E.g. publish 10 articles and post 20 comments.
To achieve goal "Premier Member", define the Task(s) to be completed. E.g. publish 25 articles and post 50 comments.
Write the appropriate rules, using the Rules module, to track process on completing the various tasks. Basically you'd only need 2 (extremely basic) rules, which would be triggered like so:

After publishing an article.
After posting a comment.

Note that these very 2 rules can be re-used to measure progress on each of the 3 rules. If you want, you could expand these rules (with an extra rules action) to also assign userpoints, to implement your userpoints design you have in mind.

Refer to my answer to "How to implement gamification in a Drupal site and award incentives?" for way more details about the Goals module.

Note: Using Goals only requires typical administration tasks (configuration), though it does come with various hooks also for custom module development (if you want to).


Add line item showing total cost How can I add a line item in Ubercart 2 that adds up the total cost of all items, not the sell price? I have tried to clone the generic line item hook, and add something like this for the callback:

for each($op->products as item){
  $cost += $item->cost;
}

I need this line item to appear in the cart (I'm using the ajax cart), in the order pane before the user completes checkout, and in the emails that the store owner and user get. Do I need to create a little module for this code outside of uc_order? I don't remember the code exactly as it's on my work computer, but I think I'm putting it in the wrong place. Thanks for any pointers.

I created a line item using hook_uc_line_item() then added the line item in the hook_uc_order().

Final products looks something like:

/*
 * Implement hook_uc_line_item()
 */
function my_module_uc_line_item() {

  $items[] = array(
    'id' => 'handling_fee',
    'title' => t('Handling Fee'),
    'weight' => 5,
    'stored' => TRUE,
    'calculated' => TRUE,
    'display_only' => FALSE,
  );
  return $items;
}

/**
 * Implement hook_uc_order()
 */
function my_module_uc_order($op, $order, $arg2) {

  // This is the handling fee. Add only if the user is a professional and there
  // are shippable products in the cart.
  if  ($op == 'save') {
    global $user;

    if (in_array('professional', array_values($user->roles))) {

      // Determine if the fee is needed. If their are shippable items in the cart.
      $needs_fee = FALSE;
      foreach ($order->products as $pid => $product) {
        if ($product->shippable) {
          $needs_fee = TRUE;
        }
      }

      $line_items = uc_order_load_line_items($order);

      // Determine if the fee has already been applied.
      $has_fee = FALSE;
      foreach ($line_items as $key => $line_item) {
        if ($line_item['type'] == 'handling_fee') {
          $has_fee = $line_item['line_item_id'];
        }
      }

      // If the cart does not already have the fee and their are shippable items
      // add them.
      if ($has_fee === FALSE && $needs_fee) {
        uc_order_line_item_add($order->order_id, 'handling_fee', "Handling Fee", 9.95 , 5, null);
      }
      // If it has a fee and does not need one delete the fee line item.
      elseif ($has_fee !== FALSE && !$needs_fee) {
        uc_order_delete_line_item($has_fee);
      }
    }
  }
}


Button act as submit button in form API I have a button element in form builder as follows

$form['fieldset']['add_new_event_btn'] = array(
  '#value' => t('Add new event trigger'),
  '#type' => 'button',
  '#attributes' => array(
    'style' => 'margin-top:20px;width:200px;margin-right:275px;float:right',
  ),
  '#ajax' => array(
    // Function to call when event on form element triggered.
    'callback' => '::enable_event_trigger',
    // Effect when replacing content. Options: 'none' (default), 'slide', 'fade'.
    'effect' => 'fade',
    // Javascript event to trigger Ajax. Currently for: 'onchange'.
    'event' => 'click',
    'progress' => array(
      // Graphic shown to indicate ajax. Options: 'throbber' (default), 'bar'.
      'type' => 'throbber',
      // Message to show along progress graphic. Default: 'Please wait...'.
      'message' => 'loading',
    ),
  ),
);

But this button is act as the submit button , and there for the validation for other elements works and shows the error message on the next reload when i leave the page as it is, How can i rectify this problem ??

As mentioned in the comments, this is not supported yet but it might at some point: https://www.drupal.org/project/drupal/issues/1671190

What you can do is return false in the onclick event. For example:

$form[button] = array(
  '#type' => 'button',
  '#name' => 'button',
  '#value' => "Do some JS",
  "#attributes" => array(
    "onclick" => "doJs(); return false;",
  ),
);


How to output a large amount of html markup I need to output an entire region of a page from within my custom module.

I know I can output markup to be rendered with this code:

$page['region'] = array(
    '#type' => 'markup',
    '#markup' => t('markup here'),
);

This is good for small amount of markup but is there a better way to output a large amount of html from within my module?

You shouldn't output large amount of markup from your module without using the theme layer (unless your markup is actually editable content or large chunk of static content). So, the best is probably to define a theme function or template for your markup, and use it from your module. This way, any theme can change your markup without affecting your module logic. Even if this is supposed to be a single-project custom module, chances are that someday you, or somebody else, will have to update this site. Properly separating your module logic from its presentation will make things easier in the future.

// Rendering code
  $page['region'] = array(
      '#theme' => 'custom_foo',
      '#foo' => t('foo)',
      '#bar' => t('bar'),
      '#count' => 42
  );

/**
 * Implements hook_theme().
 */
function custom_theme() {
  return array(
    'custom_foo' => array(
       'variables' => array('foo' => NULL, 'bar' => NULL, 'count' => NULL),
     )
  );
}

/**
 * Default theme implementation for custom_foo.
 */
function theme_custom_foo($variables) {
  $output[] = '';
  for ($i = 0; $i < $variables['count']; $i++) {
    $output[] = array(
      'type' => '#markup',
      'markup' => ($i % 2 == 0) ? $variables['foo'] : $variables['bar'],
    )
  }
  return $output;
}

For static content, you can use a template (.tpl.php) instead of a theme function. This allow you to keep it outside a your .module (or .inc) file code. Again, this will be easier to maintain in the future.

Also, most of the time you shouldn't put markup into t(). t() is for translatable strings and most markup are not to be translated. One common, an acceptable, exceptions is (simple) link markup.


Extract field from content type in View and have it appear as a block next to appropriate node I need to pull a field from a content type and have it appear as a view in the sidebar next to the node it belongs to. I can't figure out what parameter to use in Views to indicate that my view block should appear by the node it was extracted from. Maybe something to do with relationships?

This can be done with contextual filters.

Set up the view to display whatever information you need; put the view in a block that only displays on the page for that content type
Add a contextual filter, selecting a field that contains the NID.  For example, this could be content: nid
For "when filter is not available" select "provide default value", then "content ID from URL"

After doing this, the view will only display the single result, where the NID field matches the NID of the node currently being viewed.


Workbench Moderation: Published data overriding draft data on draft view Moderation's draft content not showing on the front end.

When a node has both a published and a draft, the data from the published overrides the draft data on the front end when viewing the draft.

For example www.example.comnode/6
and www.example.com/node/6/draft
will display identically.

Does this require a special hook in the theme?

It was a two-part solution.
There was a bug that needed patch #16 from here:
https://www.drupal.org/project/workbench_moderation/issues/2021903

I also needed to add vid to node_load:
    When I combined the
    $vids = $node->vid;
    $node = node_load( $nid, $vids );
    with patch #16 from:
    https://www.drupal.org/project/workbench_moderation/issues/2021903 it solves the issue.


how to Display author and date information according to my requirement? I am created a content type with field Title, Project code, Advertise and Body.

I want to display Author name and date information after Project code but by default it showing after title field so please let me know how to display according to my requirement.

Steps to change the order

Override node.tpl.php in your theme template.
Rename it to node--[content_type_machine_name].tpl.php if you want this for a specific content type.
Remove

code and place it after the Project code field is rendered.

Clear the cache after making the change.

Hope that this helps.


Is there a non-WYSIWYG-module that lets me use Media ver. 2 images with multiple image styles? I have a library of images that I access for reuse via the Media (ver. 2.0) Browser and attach to nodes using the file field. When I use an image inside a node, I want to indicate a specific Image Style (e.g. "Thumbnail", "Medium", etc.).  The out of the box setup of D7 let me specify one (1) image style to be used for a field in each display mode (i.e.  "Default" and "Teaser"). I want to be able to choose between image styles.

I may want to use the "Medium" style for the first image field in one node, and "Large" in for the first field in another.

After some googling, I've found some suggestions for doing this, but they're all based upon using WYSIWYG for image insertion, and I don't want WYSIWYG.

Looking at the answer to Multiple image styles, I see that I can do get access to different image cache versions of an image through either template file or hook_preprocess_node() - so I should probably be able to do this with a custom module that manipulates the image field render object during preprocessing.

However, before I embark upon writing such a custom module, I want to ask if this module (or something similar to it) already exists?  I have searched for it, but so far found nothing that does not use WYSIWYG.

As I can see Entity Image Style can be used with the Field collection module to achieve this task. However the Entity Image Style module is not yet a stable module. As per the logic this should achieve your goal.

Other resources:
Formatter Field module


Is there a module for scalable input / output for unlimited value fields? In a field with unlimited values a user may easily enter 100+ items. While the db does allow unlimited entries, the client side input does not seem too scalable since it shows all values on the same page. Perhaps some kind of paging or Views would be great. Is there such a module?

You could of course write both a formatter and a widget to implement some sort of paging, but that doesn't change the fact that Drupal will always load all 100+ field items when loading the node and saving (by doing a DELETE first and then an INSERT) of all 100+ field items when saving that node.

There isn't really a nice way to do this properly using fields. In case of references (node, user, ..), a possible workaround is to reference those entities to the current one, so that each one only has one (or a few) references, instead of 100%. Then you can display them on the referenced entity using a view.

Using a non-relational field storage implementation like MongoDB can help with the storage performance problems because it's a single load/save operation, no matter how many fields and field items you have. But it's still one global operation for all field items at once.


How to enable comments on drupal default user profile page? I am pulling my hair out trying to find an answer to my question. I am creating a community site and one of its main feature is to comment and rate other users. For some reason it seems this is not possible on Drupal 7 since I haven´t found a clear answer to this question. Could you please please please guide me on this?

Thank you very much.

To stay in Drupal language: The problem is that User account pages are not "nodes" (no normal content type like you may expect) nor full "entities" (bundles of fields grouped as type in Drupal 7 world). This missing is a big left over from earlier days of Drupal and not really wanted as-is in the Drupal community since it is against the field-able framework idea behind Drupal. Plus that comments are sadly sticky to nodes (not usable elsewhere).

There are many efforts to change this and (from what I know) solved in D8. And the user accounts are fieldable now in D7 already, but still not really "known" everywhere in the system and that's why the system provided "comments" bundle can't be activated here. User pages are not nodes. The concept of "Entities" is another one of the efforts to have fieldable bundles everywhere, one of these steps away from the inconsistency and to get a more general reusable logic of field-able "groups of elements" everywhere, not only on nodes or user pages. Comments are already entities but not known by user pages. And so on and so forth.

Some work arounds for Drupal 7 could be now to use modules like profile2 (a little bit limited, but fully field-able entity), or "Reply" (will be awesome, but new and needs some more help!), or to build own "entities" or content types (my suggestion) which can be made relative to users (like blog already is) using modules like entityreference or relation (awesome but for this usecase allone maybe too powerful). This gives you more than comments as an option, plus the complete freedom about how to field your custom "user pages". And you can even show them apart from the user account page, like on facebook profiles or in tabs. (advanced views and menus knowledge needed here)

Another way could be to use the manage fields settings dialog of Drupal core and "bow" them as fields with multiple values to a kind-of-comment behaviour. I already did this very successful on project, where the clime was limited and to choose this way was less effort to achieve. But for more complex needs I would rather suggest my earlier solutions.

Aaand ... an outsourcing comment solution would be: the Disqus module. Surprise: it also works on profiles. (sorry, but I am limited to less than 3 links ATM, it's a new DA account.)

But as you can see: as always in Drupal, there are more than 2-3 ways to achieve a wanted behavior in Drupal projects.

Hope it helps a 'lil bit. Best regards...


Add description and title field to each image I am creating an image Album. For this I have created one content type with "Album Title"(title), "Album Description"(body) and Image field which can take unlimited number of images. Now I want to add a title and description to each image.
Please help me to short it out.

You can add the title field and alt field, but not sure about the description field.

Go to admin/structure/types and then click manage fields for the particular content type and then click edit under operations for image field you want and then check the title field as shown in the below image.


How to change core search result snippet? I want to change core search result snippet. I tried with preprocessor theme_preprocess_search_result(&$vars) but in $vars['result']['node'] there coming basic fields values and rendered content array. In my node, content is with paragraph bundles and field collections. I want to display one of my bundle value in search snippet.

$vars['result']['node'] values coming in array key 'rendered'

stdClass Object
(
    [vid] => 1039
    [uid] => 1
    [title] => What are the cut off times for funds transfers to an external bank?
    [log] =>
    [status] => 1
    [comment] => 0
    [promote] => 1
    [sticky] => 0
    [nid] => 235
    [type] => support
    [language] => und
    [created] => 1444988988
    [changed] => 1446531922
    [tnid] => 0
    [translate] => 0
    [revision_timestamp] => 1446531922
    [revision_uid] => 1
    [field_support_type_ref] => Array
        (
            [und] => Array
                (
                    [0] => Array
                        (
                            [tid] => 16
                            [taxonomy_term] => stdClass Object
                                (
                                    [tid] => 16
                                    [vid] => 4
                                    [name] => Internet Banking
                                    [description] =>
                                    [format] => filtered_html
                                    [weight] => 0
                                    [vocabulary_machine_name] => support_type
                                )

                        )

                )

        )

    [field_paragraph] => Array
        (
            [und] => Array
                (
                    [0] => Array
                        (
                            [value] => 1102
                            [revision_id] => 7916
                        )

                )

        )

    [name] => orangedigital
    [picture] => 0
    [data] => b:0;
    [workbench_access] => Array
        (
            [28] => 28
        )

    [entity_view_prepared] => 1
    [rendered] =>
Type:
Internet Banking
Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet.

Lorem ipsum dolor sit amet.

Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet.

)

You could build your own search result .tpl file inside your theme and take control over what displayed and the markup by creating a file named like search-results--[searchType].tpl.php After that you have to clear the cache in order to be recognized in theme registry

In your case you could limit the number of words displayed or divide based on empty line which mean a pragraph.

Take a look at D7 theme suggestions


Target Bundle with hook_element_info_alter Using the following hook you can alter form elements

function EXAMPLE_element_info_alter(&$type){
  // Increase the default weight range
  if (isset($type['weight']['#delta'])) {
    $type['weight']['#delta'] = 120;
  }
}

How can I target a bundle  with this hook?

Bundles are defined in hook_entity_info(), so the complementary alter hook is hook_entity_info_alter()

Alter the entity info.
Modules may implement this hook to alter the information that defines an entity. All properties that are available in hook_entity_info() can be altered here.

hook_element_info_alter() is for altering form elements (which a bundle is not), so it can't be used in that context.


CSS still requiring clearing cache after following steps to switch caching off I have followed the steps detailed in this tutorial and many others -> https://knackforge.com/blog/rajamohamed/disable-drupal-8-cache-during-development

I have copied and renamed the sites/example.settings.local.php file as sites/default/settings.local.php

Opened settings.php file in sites/default directory and uncomment these lines:

if (file_exists(__DIR__ . '/settings.local.php')) {
  include __DIR__ . '/settings.local.php';
}

I have uncommented the following lines in settings.local.php to disable the render cache and dynamic page

$settings['cache']['bins']['render'] = 'cache.backend.null';
$settings['cache']['bins']['dynamic_page_cache'] = 'cache.backend.null';

I have opened development.services.yml in the sites folder and added the following lines (to disable twig cache)

parameters:
  twig.config:
    debug : true
    auto_reload: true
    cache: false

I have then cleared cache, this has worked for twig it seems as I am able to make changes in my page.html.twig and these update on a standard browser refresh.

However, any changes to by CSS files are requiring a clear cache every time, slowing development down quite a lot over time.

Hoping for some help here.

Written by @Clive in the comments

  Are you using chrome? Asset caching got way more aggressive recently
  for some reason, if you're using it try opening the Network tab in dev
  tools and selecting "Disable cache"

This solved me the problem.


Facet block is not getting display on search page created by view I am using the Search API module with an Apache SOLR server. On my search page, the search results are rendering properly, but the content type facet block is not getting render in any defined region.

I followed the same steps as mentioned in Enable facets.

Is there any version compatibility issue?

I am using the following versions of the dependent modules.

drupal/search_api 1.14
drupal/facets 1.4
drupal/search_api_solr 3.7
drupal/search_api_autocomplete 1.2

It's working now. There was an issue with context which was overriding block layout property and that's the reason facet block was not rendering on the page.

Summary: If you are using context on the page then block layout property will not work for rendering the block. So need to configure block in the context.


Default image is not generated I have a case content-type that has an image_field. I have configured the field to use a default image in cases when no image is upload for a case.
I then try to render the image using the following code:

<?php $view = node_view($node); ?>

<?php print t('Publicerad'); ?>: <?php print date('d - M - Y', $node->created); ?>

    <?php print render($view['field_image']); ?>

If the case has a connected image then the field is rendered as expected, but in other cases nothing in displayed. When I check under recent log messages I see this:

Location   http://localhost/test/sites/default/files/styles/case_170x107/public/default_images/default_case_pic_0.png?itok=CWr6R4Rs
Referrer   http://localhost/test/search/node/case
Message    Unable to generate the derived image located at public://styles/case_170x107/public/default_images/default_case_pic_0.png.

I don't understand why it fails to generate a style for my default image when it works fine with user supplied images.

I have checked the permission on the folder and everything seems fine, so I really don't understand why this is not working?

Notice that all other images that is uploaded gets their image styles generated without any problem. The error only gets triggered in case of a default image connected to the field_image field.

For what it's worth and consideration. Make sure your php.ini is configured correctly and that your. upload_max_filesize and max_file_uploads settings are adequate. My numbers are arbitrary, but I've had similar issues that require this general adjustment.

Maximum allowed size for uploaded files.
; http://php.net/upload-max-filesize
upload_max_filesize = 200M

; Maximum number of files that can be uploaded via a single request
max_file_uploads = 200


Put off loading my theme banners to speed up Drupal I'm currently using the Marinelli theme for a project.  It loads ALL the top banner pictures before showing the page.  Very slow.  Results in a big download size for the home page.  Is there a way to get Drupal or the theme to put off loading all but the first banner pics when it displays the page.  See my screen capture of pingdom.com

Dave

I think you're looking for a technique called "lazy-loading" to implement on your pages. Lazy loading means that the images are only loaded upon viewing them.

You can use the Lazyloader module as a start to implement it, however how it will exactly work for your site is completely dependent on your Drupal theme and module(s) configuration. One useful example (and starting point) is this blogpost, which explains how to implement the layloader module in combination with a slideshow.


How to add a default taxonomy term to all nodes in a migration? For a Drupal 7 to Drupal 8 migration, we're taking what was a Quotation content type and migrating it into an Article content type, joining a ton of nodes that are staying as Articles.  To distinguish, I want to add a taxonomy term "Quotation" to the field_categories (which exists on Articles D7 and D8 but not on Quotation).

So i'm "simply" trying to add a value not from a source, but hard-coded.  My source plugin is d7_node (namespace Drupal\node\Plugin\migrate\source\d7).

I'm flailing a bit; tried entity_generate but couldn't figure out how to tell it to use a constant and/or default value rather than looking for something from source.

Even this didn't work, when i tried to test the simplest thing i could think of when already knowing the term ID of an existing term:

  field_categories:
    plugin: iterator
    source: field_categories
    process:
      target_id:
        -
          plugin: default_value
          default_value: 10838

Can one use the default_value plugin or something like it for the 'source:'?

I'm about to stick my non-source value into what comes from the source with a prepare row hook, but it seems there ought to be an easier way.

Note that in this case there is nothing from field_categories in the source to worry about, but i'm also interested in the case of adding a new, hard-coded-into-the-migration term into a field that will have content, in my case field_tags.

Well, i don't like it, but this works:

<?php

use Drupal\migrate\Row;
use Drupal\migrate\Plugin\MigrateSourceInterface;
use Drupal\migrate\Plugin\MigrationInterface;

/**
 * Implements hook_migrate_MIGRATION_ID_prepare_row() for upgrade_d7_node_quote.
 */
function portside_upgrade_migrate_upgrade_d7_node_quote_prepare_row(Row $row, MigrateSourceInterface $source, MigrationInterface $migration) {
   $term_name = 'Portside Quotation';
   $term_array = \Drupal::database()->select('taxonomy_term_field_data', 't')
     ->fields('t', ['tid'])
     ->condition('vid', 'categories')
     ->condition('name', $term_name)
     ->execute()
     ->fetchCol();
   if (isset($term_array[0])) {
     $row->setSourceProperty('field_categories', [['tid' => $term_array[0]]]);
   }
}

I create the taxonomy term with default content, so it's there after site install and ready for the migration.

In the migration's YAML file (for upgrade_d7_node_quote), there's simply a plain mapping as if field_categories were a real thing:

  field_categories:
    plugin: iterator
    source: field_categories
    process:
      target_id: tid

And remember, there is no field_categories in the source.  The migration doesn't mind at all and works fine with one inserted into the source in this prepare row hook.


Views Filter by View Field I've created View with list of entity registrations. This list display users registered for events with info, like conference name (node title), user name etc.

Is it possible to add filter, which contains list of all existing conference names by default? Because right now I have to add values manually.

You can use the Views Reference Filter. You can create an entity reference view which will contain the all existing conference names, and then use this view as a filter for the main view.

  This module provides the views filter for entity ID or entity
  reference fields such as node ID, user ID, taxonomy term ID, term
  reference field (Drupal core) and entity reference field (Entity
  reference module).


How to change File field icons (without changing core)? The generated markup for displaying a file field is (PDF in this example):

<img src="/modules/file/icons/application-pdf.png" title="application/pdf" alt="" class="file-icon">

I'd like to use a different icon image. How could I do this without changing the content of /modules/file/icons?

I guess I could hide the default image and display a different one with CSS, but seems a bit messy.

You can override theme_file_icon in your theme, and specify different icon images. See file_icon_path for reference regarding how core determines which icons to use.

You can also set the "file_icon_directory" variable to the path to your icons, as the file_icon_path function looks for the path in that variable.


How can I translate the Profile 2 field labels? I can't find a way to translate the fields labels for the Profile 2 fields. I have activated the Profile 2 translation module, but I don't want to translate fields of the entity, I just want to show the labels translated in the user page and the user edit form.

Does anyone know how to do it?

EDIT: the following description describes the steps for Drupal 8, but they are similar for Drupal 7:

You need the potx module to extract a translation template which you can translate. Unfortunately there isn't an official Drupal 8 release available, but you can use this github fork, which works fine for my needs.

Here is a short procedure to handle translations of my modules:

1. extent your module with the Interface Translation Properties (only Drupal 8)

Example my_module.info.yml:

name: My Module
description: ''
type: module
core: 8.x

'interface translation project': my_module
'interface translation server pattern': modules/my_module/translations/%language.po

Now your module is available for the locale module and translation can be handled with drush locale-check resp. drush locale-update.

2. create a subfolder for your translations

In the subfolder ./modules/my_module/translations I put the generated template and the *.po files. Fore more information have a look at the documentation on drupal.org.

3. create your template

I'm using drush to create the template. The best way for me is the creation with

drush potx single --folder=modules/my_module/ --api=8

It generates a general.pot file at the root directory of your Drupal installation. I move it into the translation folder but it's not necessary.

4. create your translation

To create a translation I'm using Poedit as editor. You can create different language files from the general.pot template. The free version of Poedit is quiet useful for editing *.po files. Save your language files in the translation folder.

5. import the translations

Run the following commands to import the translations:

drush locale-check && drush locale-update

And clear the cache:

drush cr

That's it ;)


How can we synchronize Nodes from Staging to Production Server My Question is there any way we can track the node changes on Staging Server and Push the same to the Production Server. Best use case will be,

Customer does not want to change the content on Production server.
He wants to first change on Staging server get it tested and push the content to live server.
Have revisions for changes so that he can revert back any time using node re- visioning system !

Can we do this maintaining the node id's same across staging and live servers ? Is there any out of the box solution for this like feature module does for configuration changes tracked using modules?

For Node changes, you can use node export  module to migrate node between drupal installations. for Tracking Configurations changes there is another module configurations , i haven't tried yet. Be sure cos the module release is still in dev


Where in Drupal database do I store additional file properties? I have an (architectural) problem with D7 and don't know what would be a good solution to it. Here is what I'm trying to do: I have an article with a sound sample attached to it. I thought it would be great to calculate sound sample duration and bitrate and store it somewhere in the database. What would be the proper place for that? I thought of node fields first, but number of sound samples for one article is not restricted and it seems I'll need to define a field with unlimited number of values to hold durations and then somehow match samples with their respective durations. Don't think it's a proper solution here. So what's the common practice in such cases?

You might want to look into the Media project which provides bundles for files and allows to add fields to them.

Another approach would be to use a module like Field collection which allows you to group a number of fields into a group that you can add as a field to another entity. That field can then have an unlimited amount of values which allows you to attach n fiels + meta information to your node.


Display suite's adding custom fields loads eternally In "Manage display" page of my product content type, I have the custom fields tab. In that tab I have some buttons... None of these buttons works. I tried both but the popup div loads eternally there.

Anyone with the same problem with any clue?

Thanks

all these are the view modes like teaser,full content etc.whenever you create any panel ,there will be tabs of full-content etc...then u can edit the settings displayed below these tabs..here these buttons would be visible...


Inserting a field to multiple regions I have a content type with field_slides and I want to use it on multiple region in the same page. its a slide show using light gallery, at mobile view I want to hide the first div and show it on the second one.

 {{content.slides}}

{{content.slides}}

The issue is the slides works fine on the first div but if i try to open it on the second div it keeps scrolling  to the top ( first div )/reloading the page sometimes. However if I removed the region from the first div it works fine on the second div, I want to have it working on both the divs. Is this possible ?? please help

I also tried this

Its not working either ---

Here is the actual twig template

{% set slider2 = content.content_2_project %}

              {{content.content_1_project}}
              {{content.content_1_punch}}

                  {{content.content_2_body}}
                  {{content.content_2_body_details}}

                    {{content.content_2_project}}

                {{ slider2 }}

i'm using Fullpage.js on the drupal 8 site.

Try this tricky method

{% set slider2 =content.slides %}

 {{content.slides}}

{{slider2}}


Multistep registration form for two roles Goal:

I have two different user roles:

Borrower
Provider

There are 5 categories for these users to choose(they can select all if they want):

Market 1
Market 2
Market 3
Market 4
Market 5

Each roles have different registration forms depending on the categories they picked. Let say:

For Borrower role:

If Market 1:
  step one:
    form A
  step two:
    form B:

If Market 2-5:
  step one:
    form A:
  step two:
    form C:

For Provider role:

If Market 1-4:
  step one:
    form A:
  step two:
    form D:

If Market 5:
  step one:
    form A:
  step two:
    form E:

Where:
  form A = generic registration form
  form B = specific for Borrower role selecting Market 1
  form C = generic form for Borrower role selecting Market 2 to 5
  form D = generic form for Provider role selecting Market 1 to 4
  form E = specific form for Provider role selecting Market 5

Question:
  Is there any module that can do this? Any thoughts how can I achieve this using Drupal API's?

These modules might help you:

Profile2 for creating different user profiles based on role
Profile2 registration path to have separate registration pages
Formflow to connect multiple forms in a single "workflow"


How to create a simple vote button I'm trying to create a voting option for the nodes in my website. I want the voting to look like this

The users click on the vote button and the number increases.

I have tried using the Rate module but it's not working with views or display suite. Is there any other module that I can use which will help me achieve this.

The Plus One Module (in conjunction with the Voting API) should do what you're looking for.

  [This module provides] a simple digg-like voting widget for content that uses Ajax.

Here is a demo I put together for another question.


Impossible to add new content I migrated my web to webhosting. There is a problem when I want to add new content, it's not able to add new content with images or files. Do you know where to look to solve it? Does it relate to access rights to directories where Drupal stores those files or is it something else?

When I want to upload an image, it writes:

Warning: move_uploaded_file() [function.move-uploaded-file]: Unable to access public://image.jpg in file_save_upload() (line 1528 of /web/www/x.y.com/includes/file.inc).
File upload error. Could not move uploaded file.

thank you

review permissions in the /sites/all/files directory. you can test inside files directory, changing permissions to test the correct permissions. for example you, for test, can change to 755 in recursive mode: chmod 755 files/ -R. also review the owner of directory. According my experience, the owner can be a cause.

(According I remember, permission 777 number is the most higher number, but not is recommended).


How to delete a view programatically in D7? How to delete a view programatically?

It's crazy I can't find proper answer for such a simple question.

Give a try to the following code to delete the view:

// Check the view id the one that you are looking for.
if ($view = views_get_view($name)) {
  // Delete the view if it is the one that you are looking for.
  views_delete_view($view);
}


How to add a page redirect in Drupal htaccess file or otherwise? I've built a Drupal website to a replace an old website (not in Drupal) and some of the pages changed urls. I need to create redirects for those pages.

I've thought of using Drupal's .htaccess file and have the following:

RewriteCond %{HTTP_HOST} ^www.example.com/old-page-name$
RewriteRule ^$ http://www.example.com/new-page-name [L,R=301]

But that didn't work.

I've added those lines inside the redirect block in Drupal's htaccess:

<IfModule mod_rewrite.c>
</IfModule>

Just under these rules:

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !=/favicon.ico
RewriteRule ^ index.php [L]

This will be a temporary solution until I install the redirect or some other module.

I'd suggest you consider the Rules module as that "other module" you are looking for. Using an approach as described in my answer to the question "How to use the Rules module to implement a custom redirect for an outdated URL?" ...

Using that technique, you can also solve your requirement about it being "temporary" (that's just a matter of some appropriate rules Condition to be added in your case).


Get parent menu item of a current node I'm trying to get the parent menu item of node I am currently on:
$node_id = // some id
$menu_link_manager = \Drupal::service('plugin.manager.menu.link');
$menu_link = $menu_link_manager->loadLinksByRoute('entity.node.canonical', array('node' => $node_id));
$parent = $menu_link->getParent();

but for some reason it always fails with this error:
Error: Call to a member function getParent() on array

When I inspect $menu_link I can clearly see it is there:

Also the method of getParent() seems to be correct: Docs
Would appreciate any help!

I think you need to reset the collection first, as the ::loadLinksByRoute() annotation states that it returns an array of MenuLinkInterfaces[].
See /core/lib/Drupal/Core/Menu/MenuLinkManagerInterface.php:

  /**
   * Loads multiple plugin instances based on route.
   *
   * @param string $route_name
   *   The route name.
   * @param array $route_parameters
   *   (optional) The route parameters. Defaults to an empty array.
   * @param string $menu_name
   *   (optional) Restricts the found links to just those in the named menu.
   *
   * @return \Drupal\Core\Menu\MenuLinkInterface[]
   *   An array of instances keyed by plugin ID.
   */
  public function loadLinksByRoute($route_name, array $route_parameters = [], $menu_name = NULL);

So do something like:
/** @var \Drupal\Core\Menu\MenuLinkManagerInterface $menu_link_manager */
$menu_link_manager = \Drupal::service('plugin.manager.menu.link');
$menu_links = $menu_link_manager->loadLinksByRoute('entity.node.canonical', array('node' => $node_id));
// Reset collection by retrieving the first item.
$menu_link = reset($menu_links);
// Now call the parent method.
$parent = $menu_link->getParent();


Migrate d2d – Problem with duplication of thumbnails In order to be able to copy all files to certain specific subfolders in site/default/files during my migration från D6 to D7 I use the file class MigrateFileUri (as far as I understand MigrateFileFid does not care about destination directories). So, in prepareRow() I fetch the filepath from the legacy db for the main image and likewise for the thumbnail of that same product.

The problem occurs when there is only a main image and no thumbnail in a product node. What happens is that the thumbnail field gets the previuos thumbnail path used. This is my prepareRow():

public function prepareRow($row){
    // Always include this fragment at the beginning of every prepareRow()
    // implementation, so parent classes can ignore rows.
    if (parent::prepareRow($row) === FALSE) {
        return FALSE;
    }

    $fid = (isset($row->field_sensorimage) && !empty($row->field_sensorimage[0])) ? $row->field_sensorimage[0]: FALSE;

    if($fid != FALSE){
        $filepath = Database::getConnection('default', 'legacy')->query('SELECT f.filepath FROM {files} f WHERE f.fid = :fid',array(':fid' => $fid))->fetchAssoc();
        $this->addFieldMapping('field_sensorimage_newsite')->defaultValue($filepath);
    }

    $fid2 = (isset($row->field_thumbnail) && !empty($row->field_thumbnail[0])) ? $row->field_thumbnail[0]: FALSE;

    if($fid2 != FALSE){
        $filepath = Database::getConnection('default', 'legacy')->query('SELECT f.filepath FROM {files} f WHERE f.fid = :fid',array(':fid' => $fid2))->fetchAssoc();
        $this->addFieldMapping('field_thumbnail_newsite')->defaultValue($filepath);

        dsm($fid2);
        dsm($filepath);
    }

    return TRUE;
    }

This happens: if let's say the 100 first nodes has no thumbnail, it works as expected. No thumbnails are copied to the destination directory. But after the first node with a thumbnail all the following nodes that did not have a thumbnail in the D6 legacy site, gets the previous nodes' thumbnail all the same in the new D7 site.

Thanks to the 2 dsm() near the end of the snippet above I can confirm that no thumbnails gets duplicated within that if statement. There are about 50 thumbnails mapped. But the end result is that several hundred nodes gets duplicate thumbnails from other nodes.

So once the first thumbnail is migrated, that thumbnail path is inherited by all the following nodes and renamed with a number extension *_1.jog, *_2.jpg .... *_30.jpg as long as there is no thumbnail in the legacy field.

Now, where does this happen and how can I stop it from happening? I have rewritten the prepareRow() many times, but always with this same result. I am really stuck... Please help :-(

Finally found a workaorund… by deliberately giving the destination field an empty value instead of not doing anything when $fid2 is FALSE, I got rid of all the duplications :-)

if($fid2 === FALSE){
    $filepath = array();
    $this->addFieldMapping('field_thumbnail_newsite')->defaultValue($filepath);
} else {
    $filepath = Database::getConnection('default', 'legacy')->query('SELECT f.filepath FROM {files} f WHERE f.fid = :fid',array(':fid' => $fid2))->fetchAssoc();
    $this->addFieldMapping('field_thumbnail_newsite')->defaultValue($filepath);
}


How to associate multiple profiles per user with Profile2 I'm running a Drupal 7 site that has different profile types (created using the Profile2 module). Each user is associated with a profile, so at the time of registration, a potential user can choose a specific profile, and based on that, a different registration page is displayed.

I was wondering, is it possible to allow a normal user (not admin) to associate more than one profile for itself? So that he/she can see the fields of each specific profile to which is associated?

At present, the Profile2 module allow to have one User: one Profile relationship, and only the admin can add multiple profiles to a user. Is there a patch for Profile2 module to permit this kind of feature?
Thank you!

I was able to achieve the solution with this module, and by setting the right permissions offered by this module.


Access multivalued field collection tokens in webform email I tried this token [webform_submission:source-entity:field_campaign_email_collaterals] but this results in following html

field_campaign_email_collaterals 0 (Edit|Delete),
field_campaign_email_collaterals 1 (Edit|Delete),
field_campaign_email_collaterals 2 (Edit|Delete)

How can I get actuall value of this field collection, or else if there is any way to get individual field inside this field collection?

Try using the [webform_submission:node] to access field related tokens.  I think you might need to try [webform_submission:node:field_campaign_email_collaterals:0] or [webform_submission:node:field_campaign_email_collaterals:0:html]


Class 'views_plugin_display' not found Getting this

PHP Fatal error:  Class 'views_plugin_display' not found in ../sites/all/modules/contrib/media/includes/media_views_plugin_display_media_browser.inc on line 18, referer: ..

Any ideas how I can fix that?

Thanks,
Dmytro

If you have Views enabled, this might be an issue with Media.  This has been previously reported the issue queue for the project, and there it was suggested to reinstall the latest version of the Media module, in case the files had become corrupt.


Submit form to 3rd party site, receive response to update original form What I want to do

We have a simple form that people fill out to attach documents for review.  We want to monetize it, using a specific vendor we currently use for non Drupal sites.

What we want to add is when someone saves their form, go to a confirm page, stating the price, then submit this to the 3rd party site.  They process the payment and post a response back to our site, which we then modify the node to update the status to paid.  We currently do this using Google app scripts on many other sites.  We want to keep this site in Drupal for other reasons.

I'm very new to drupal, and am having some trouble with how to submit the form, and especially how to receive the post from the 3rd party vendor.  I feel this isn't a crazy way to do this, but the lack of modules that

We've looked at Drupal Commerce and Ubercart, etc, but they seem pretty large for our needs.

There are a variety of ways you can do this using the 3rd party API and the hooks provided by Webform such as

http://www.drupalcontrib.org/api/drupal/contributions%21webform%21webform.api.php/function/hook_webform_submission_presave/7


How can i export single content node (or) selected content nodes using drush command I am using drupal 7. i created three basic pages name it as node1, node2, node3 when i export node using node-export-export command all pages(node1,node2,node3) as in one xml file. my intention is to export and import each node (or) selected nodes at a time. Please help me. Thanks for your help.

Drush command node-export-export accepts arguments ... You can see documentation of any drush command using below syntax..

drush help command-name

In your case

drush help node-export-export

Arguments:
 nids                                      A list of space-separated node IDs
                                           to export.

For Example

drush node-export-export 45 46 47

export nodes with node IDs 45, 46, 47


Batch delete users and the content they created When I received this Drupal 7 site to manage, it has had years of being open for people to make accounts and now I have ~ 300 PAGES of users with names like ismehacker1234568 and such, with under a dozen legitimate accounts I need to keep.
Once, on another site long ago I tried removing the users from the database table using a SQL query.  That was a disaster and broke the entire site.  I want to avoid that this time around.
I also need to delete any content they made, but not anything the legitimate users made.

As stated in the comments, Views Bulk Operations provides helpful functionality. You can use the "select all" checkbox on the /admin/people page to select all the users, then deselect the few you want to keep. From the dropdown, you can then choose "Cancel user account". After submitting, you will select the method by which to cancel the accounts in bulk (such as Delete the account and its content, or Delete the account and make its content belong to Anonymous).


How to change field_tags in hook_form_alter? I have the field_tags set to be a select box (not auto-complete). Inside hook_form_alter, how can I change the default value of the field_tags select box? So far, I have:

function autotag_custom_form_alter(&$form, &$form_state, $form_id){

    if($form_id == 'article_node_form'){
      //change default value here
    }

}

But I don't know how to access the field_tags element and then change the default value. Please help! Thanks.

The field_tags element is likely a widget from the Field API. You can surely alter it from a form alter hook, but be aware that it would not be your average Form API element. The Field API adds post-processor, pre-rendered, etc. functions of its own. These functions may expect things you may want to alter.

You can however, change the default value of the field from the configuration interface of your content type (you need to enable the Field UI module for this). You should also be able to select a different widget (ie. a select box) from there.


Benefit of running custom query over views I have a content type and some nodes. I am displaying latest 10 nodes from these content type through views block display. Is there any benefit if i add a custom SQL query to display latest 10 items. I will use the same SQL query that i got from view.

Not really. you should stick to using Views; it will provide you more benefits. To name a couple:

Less custom code to maintain; it's one of the mostly heavily used modules and will be part of D8 core. There's much less worries of security holes, bugs, etc.
The versatility of the Views features: caching, multiple view displays, filtering, a UI to change all this, etc.

I'd say the only exception to this would be the instances where your query is going to be hit very often, in which case you'd might be able to squeeze more performance out of an optimized SQL query.

For your needs, a block of 10 latest nodes, views will do everything you need it to, not be a burden on performance, and will take much less time to complete than creating & maintaining possibly bug ridden custom code.


Combination of AJAX Views and infinite pager In Drupal 7, I load an AJAX View (in response to user clicking a link) with the following code (source: How to load and display a view with Ajax in Drupal 7?)

 jQuery.ajax({
    url: Drupal.settings.basePath + "/views/ajax",
    type: "post",
    data: {
    view_name: "books",
    view_display_id: "page", //your display id
    view_args: identifier, // your views arguments
  },
    dataType: "json",
    success: function (response) {
    if (response[1] !== undefined) {
      jQuery("#bloque-" + identifier).html(response[1].data);
    }
   }
 });

However, I cannot combine AJAX Views with Infinite scroll module, and even a basic pagination does not work, as it does not override the pager link code.

You can try this -

On your page template where you want to load this view use following sample code (with your view specific values such as arguments etc.) which will add all the required JS to your page -

$view = views_get_view('books');
$view->set_display('page');
$view->set_use_ajax(TRUE);
$view->set_arguments(array($tid));
$settings = array(
    'views' => array(
        'ajax_path' => url('views/ajax'),
        'ajaxViews' => array(
            array(
                'view_name' => $view->name,
                'view_display_id' => $view->current_display,
                'view_args' => check_plain(implode('/', $view->args)),
                'view_path' => check_plain($_GET['q']),
                'view_base_path' => $view->get_path(),
                'view_dom_id' => 1,
                'pager_element' => $view->pager['element'],
            ),
        ),
    ),
);
drupal_add_js($settings, 'setting');
views_add_js('ajax_view');

In your JavaScript code use Drupal.attachBehaviors() which will attach Infinite Scroll to your View's HTML -

jQuery.ajax({
    url: Drupal.settings.basePath + "/views/ajax",
    type: "post",
    data: {
        view_name: "books",
        view_display_id: "page", //your display id
        view_args: identifier, // your views arguments
    },
    dataType: "json",
    success: function (response) {
        if (response[1] !== undefined) {
            jQuery("#bloque-" + identifier).html(response[1].data);
        }
        Drupal.attachBehaviors();
    }
});


PDO Exception Error - How to resolve this? After integrating Google Custom search in Drupal 7, I am getting this error page. What should I do to resolve this error?

Could be a MySQL configuration issue - see http://dev.mysql.com/doc/refman/5.5/en/too-many-connections.html

Or, quoting after http://drupal.org/node/930876#comment-4519490:

  If MySQL connections are not closed
  properly, then you might have an error
  within the code somewhere, that leads
  the script to end prematurely.

  In standard cases, connections are
  properly closed.

  Look at the detailed error log of your
  server, or activate on page error
  reporting if you're on a develpment
  site. You might find something useful,
  such as a forgotten dsm() somewhere
  with the devel module not being
  activated.

  The error might not be displayed and
  leads the site to look as usual, but
  the PHP process is not ended properly,
  leaving MySQL connections opened.

Start with checking your error logs and try to find out why this could be happening there.


Getting the available template variables in a custom module I'm making a custom module that will hook into the default theme and override a template file. Like you can do in a custom theme. At this moment I can already use the template that was made in the custom module with the hook_theme() function, it shows in my page. But the available variables are not showing in here. (for example: content, attributes, ...).

Probably because the module does not recognise these variables? How do I pass these variables to the template in my custom module. I read about the function hook_preprocess_HOOK() but no luck so far.

This is the implementation of hook_theme().

/**
 * Implements hook_theme()
 */
function episode_data_theme($existing, $type, $theme, $path) {
        return [
        'paragraph__episode_content_question_slider' => ['variables' => [] ],
    ];
}

This is the content of the template.

{#
/**
 * @file
 * Default theme implementation to display a paragraph.
 *
 * Available variables:
 * - paragraph: Full paragraph entity.
 *   Only method names starting with "get", "has", or "is" and a few common
 *   methods such as "id", "label", and "bundle" are available. For example:
 *   - paragraph.getCreatedTime() will return the paragraph creation timestamp.
 *   - paragraph.id(): The paragraph ID.
 *   - paragraph.bundle(): The type of the paragraph, for example, "image" or "text".
 *   - paragraph.getOwnerId(): The user ID of the paragraph author.
 *   See Drupal\paragraphs\Entity\Paragraph for a full list of public properties
 *   and methods for the paragraph object.
 * - content: All paragraph items. Use {{ content }} to print them all,
 *   or print a subset such as {{ content.field_example }}. Use
 *   {{ content|without('field_example') }} to temporarily suppress the printing
 *   of a given child element.
 * - attributes: HTML attributes for the containing element.
 *   The attributes.class element may contain one or more of the following
 *   classes:
 *   - paragraphs: The current template type (also known as a "theming hook").
 *   - paragraphs--type-[type]: The current paragraphs type. For example, if the paragraph is an
 *     "Image" it would result in "paragraphs--type--image". Note that the machine
 *     name will often be in a short form of the human readable label.
 *   - paragraphs--view-mode--[view_mode]: The View Mode of the paragraph; for example, a
 *     preview would result in: "paragraphs--view-mode--preview", and
 *     default: "paragraphs--view-mode--default".
 * - view_mode: View mode; for example, "preview" or "full".
 * - logged_in: Flag for authenticated user status. Will be true when the
 *   current user is a logged-in member.
 * - is_admin: Flag for admin user status. Will be true when the current user
 *   is an administrator.
 *
 * @see template_preprocess_paragraph()
 *
 * @ingroup themeable
 */
#}
{% block paragraph %}

        {% block content %}
            {% set sliderDescription = content.field_slider_description|render|striptags %}
            {{ content.field_available_for }}

                {{ content.field_slider_question }}

{{ sliderDescription|length > 200 ? sliderDescription|slice(0, 200) ~ '...' : sliderDescription }}

                {{ 'Got it'|trans }}

                    {{ content.field_slider_question }}
                    {{ content.field_slider_description }}

        {% endblock %}

{% endblock paragraph %}

This is the debug output I get on the page.

According to your code, you are creating a custom template for a paragraph.

As you are trying to access variables, that will be added by the paragraph module, you'll have to tell the theming system that it is a paragraph.

You can do so by adding the 'paragraph' base hook. This way the template will get the variables provided by the paragraph (pre-)processing:

/**
 * Implements hook_theme()
 */
function episode_data_theme($existing, $type, $theme, $path) {
  return [
    'paragraph__episode_content_question_slider' => [
      'base hook' => 'paragraph',
    ],
  ];
}


Where are the "local files" for the Localization Update module stored? I'm using the Localization Update module in Drupal 7.  As the "update source", I can choose "Local files and remote server".  I'd like to add some .po files that I created locally; where do I place them so that l10n_update can pick them up?

I don't see any options on the module's configuration page (/admin/config/regional/language/update).

On the bottom of the module's configuration page you have to set a path for the local files.

  Store downloaded files A path relative to the Drupal installation directory where translation files will be stored, e.g.
  sites/all/translations. Saved translation files can be reused by other
  installations. If left empty the downloaded translation will not be
  saved.


Advanced forum how to change the html without modifying the core I want to change the html for the topics list in Advanced forum module. I use a custom style. I foond that the file which displays the html is

  sites\all\modules\advanced_forum\styles\mystyle\advanced-forum.naked.topic-list-view.tpl.php

If I edit this file the changes are displayed. But I don't want to modify core files in order to be able to upgrade. So I tried to copy this file to my custom style's folder. But the changes are not displayed. Is it possible to change the html without modifying the naked style and if yes how?

Thanks in advance

The easiest way to find the correct file name for your custom template files is to use the Theme Developer moduel. It allows you to point and click on anything in the browser and it tells you which part of the theme framwork rendered it and what options you have to override it.

Please note: You have to clear the theme registery after you added new templates, otherwise they are not shown.


How to create a single View with 2 different, optional contextual filters? I need to check whether there is already a registered user having the same user email or username. Right now I have two Views (one with passing the username and one with passing the user email as contextual filter). When there is no user with the username, the second view is called.

There is the "allow multiple values" setting for the contextual filter, but this allows me to pass 2 emails, but not an email or a username for instance.

Is there a way to create one View where the user enters a value (name or email) as filter?

SOLUTION:

As suggested by Marco that works well:

You can create a view with a context filter for username and a context filter for usermail.

Then check the input of the user, if it is a email adress. If it is a email you can redirect to the view and set the context filter for the username to "all" and the context filter for the mail to the user input.

If it is no mail adress you can set the context filter for the usermail to "all" and the context filter of the username to the userinput and redirect to this path.


Product reference field (autocomplete) length limitation I use taxonomy based pricing calculations with rules. There are 4 differrent taxonomy vocbularies used as taxonomy reference field. So  when I "bulk generate" the products, I become 1152 product variations. The field "product reference" on product display node is limited to 2048 characters so it is not possible to reffer all my 1152 variations. How to extend the limitation of product reference field?

This limitation takes affect only when the product reference field widget ist set to "autocomplete". Set up the "product reference field" to checkboxes, list or turn of the widget when you use "bulk add" product


cache keys $cid naming practices (cache_set and cache_get) For using cache_get and cache_set

According to this comment

  The convention seems to be to use colons to create a sort of
  namespacing. So your module may want to do something like $cid =
  'mymodule:mything:50';

so:

is ':' the recommended delimiter?
should the module name go first? (seems sensible)?
are there characters to avoid?
are there other considerations?

is ':' the recommended delimiter? I haven't heard that : is recommended over anything else, but since it's definitely used all over core, it would make a lot of sense. All cache backends that work with Drupal will be handling : well.
should the module name go first? (seems sensible)?
Yes, this is general practice, not just cache keys.
are there characters to avoid?
None that I've heard of. In general, in 2013, if any system doesn't properly handle any character in a string properly, I would find really bad to be honest. With that said, we'll always be dealing with one form or another of legacy software. So stick to a-z, numbers and : if you're feeling risk averse.
are there other considerations?
Can't immediately think of any.


Multiple attribute selection sets Can we implement multiple attribute selection sets such as color, size and
quantity multiple times for a single product.

Suppose i have a product display that renders 4 products with colors red and
blue, sizes XL and L.

So in this case, i can add 4 different selection sets. red-XL-quantity,
red-L-quantity, blue-XL-quantity and blue-L-quantity.

Pls check the image for clarification.

I implemented commerce extras with views but it dsnt match my requirement.

I need a link to add multiple sets if necessary.

Thanks :)

I figured this out myself..

So the basic idea is that we build the form based on the setting of $form_state['num_names']. The custom submit functions for the "add more" button increment and decrement $form_state['num_names'] and then force a rebuild of the form.
We then iterate over the fields for the product and search for entity reference fields to a commerce option set.
(This takes into account that the commerce_product_option module has been properly configured and option sets have been set.)
We create a new blank option set each time and add a quantity field with an extra key to attach it with the current option set.

For the submit callback,i had to dig deeper into the module and tweaked a bit for these specific attributes.

<?php

 function multiple_option_sets_form_alter(&$form, &$form_state, $form_id) {
if ((strpos($form_id, 'commerce_cart_add_to_cart_form_') > -1)) {
    multiple_option_sets_add_more_form($form, $form_state, $form_id);
    $form['#submit'][] = 'multiple_option_sets_add_more_submit';
}

}

function multiple_option_sets_add_more_form(&$form, &$form_state, $form_id) {

$form['field_extra_attributes']['#prefix'] = '
';
$form['field_extra_attributes']['#suffix']= '
';

// Build the fieldset with the proper number of names. We'll use
// $form_state['num_names'] to determine the number of textfields to build.
if (empty($form_state['num_names'])) {
    $form_state['num_names'] = 0;
}

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

    //lets add all the fields we want in the set
    // Because we have many fields with the same values, we have to set
    // #tree to be able to access them.
    $form['#tree'] = TRUE;

    // Get the current product. Is added in the cart module.
    if (isset($form_state['default_product'])) {
        $product_id = $form_state['default_product']->product_id;
    }
    elseif (isset($form_state['default_product_id'])) {
        $product_id = $form_state['default_product_id'];
    }
    elseif (isset($form_state['products'])) {
        $current_product = reset($form_state['products']);
        $product_id = $current_product->product_id;
    }
    else {
        return;
    }

    $current_product = commerce_product_load($product_id);

    $someFieldIsAdded = FALSE;

    // Iterates the fields of this product. We search for entity reference fields
    // to a commerce option set.
    foreach ($current_product as $field_name => $field) {
        $field_info = field_info_field($field_name);

        if ($field_info['type'] != 'entityreference' || !isset($field_info['settings']['target_type']) || $field_info['settings']['target_type'] != 'commerce_option_set') {
            continue;
        }

        // Do not display our options if this field has been marked as an attribute field.
        $field_instance_info = field_info_instance('commerce_product', $field_name, $current_product->type);
        if ($field_instance_info['commerce_cart_settings']['attribute_field']) {
            return;
        }

        $lang_code = field_language('commerce_product', $current_product, $field_name);
        if (!isset($field[$lang_code])) {
            continue;
        }

        // Create a new blank option set.

        foreach($field[$lang_code] as $key => $data) {

            $option_set = commerce_option_set_load($data['target_id']);

            $values = array(
            'set_id' => $option_set->set_id,
            );

            $option = commerce_option_new($values);

            $form_state['commerce_option'][$field_name][$key+1+$i]['option'] = $option;

            $form[$field_name][$key+1+$i] = array(
            '#parents' => array($field_name, $key+1+$i),
            );

            field_attach_form('commerce_option', $option, $form[$field_name][$key+1+$i], $form_state);
            $someFieldIsAdded = TRUE;

        }
    }

    $form['field_extra_attributes'][$i+1]['quantity'] = array(
    '#type' => 'textfield',
    '#title' => t('Quantity'),
    '#prefix' => '
',
    '#suffix' => '
'
    );

}

$form['actions']['add_more'] = array(
'#type' => 'submit',
'#value' => t('Add more'),
'#weight' => 50,
'#submit' => array('multiple_option_sets_add_more_add_one'),
'#ajax' => array(
'callback' => 'multiple_option_sets_add_more_callback',
'wrapper' => 'ajax-attributes-wrapper',
),
);

return $form;

}

/**
* Callback for both ajax-enabled buttons.
*
* Selects and returns the fieldset with the names in it.
*/
function multiple_option_sets_add_more_callback($form, $form_state) {
return $form['field_extra_attributes'];
}

/**
* Submit handler for the "add-one-more" button.
*
* Increments the max counter and causes a rebuild.
*/
function multiple_option_sets_add_more_add_one($form, &$form_state) {
$form_state['num_names']++;
$form_state['rebuild'] = TRUE;
}

/**
* Submit handler for the "remove one" button.
*
* Decrements the max counter and causes a form rebuild.
*/
function multiple_option_sets_add_more_remove_one($form, &$form_state) {
if ($form_state['num_names'] > 1) {
    $form_state['num_names']--;
}
$form_state['rebuild'] = TRUE;
}

function multiple_option_sets_commerce_cart_product_comparison_properties_alter(&$comparison_properties) {
// Force separate line items when the same product is added to the cart from
// different display paths.
$comparison_properties[] = 'field_color';
}

/**
* Cart submit callback function. This is required to create / update
* the option related to the line item.
*
* @param $form Form array
* @param $form_state The form state array.
* @return void
*/
function multiple_option_sets_add_more_submit($form, $form_state){

// Get current product, taking into account different Commerce versions behavior.
if (isset($form_state['default_product'])) {
    $product_id = $form_state['default_product']->product_id;
}
elseif (isset($form_state['default_product_id'])) {
    $product_id = $form_state['default_product_id'];
}
elseif (isset($form_state['products'])) {
    $current_product = reset($form_state['products']);
    $product_id = $current_product->product_id;
}
else {
    return;
}

$current_product = commerce_product_load($product_id);

// Iterates the fields of this product. We search for entity reference fields
// to a commerce option set.
foreach ($current_product as $field_name => $field) {
    $field_info = field_info_field($field_name);

    if ($field_info['type'] != 'entityreference' || !isset($field_info['settings']['target_type']) || $field_info['settings']['target_type'] != 'commerce_option_set') {
        continue;
    }

    $lang_code = field_language('commerce_product', $current_product, $field_name);
    if (!isset($field[$lang_code])) {
        continue;
    }

    foreach ($form_state['values']['field_extra_attributes'] as $delta => $set_id) {

        $option = $form_state['commerce_option'][$field_name][$delta]['option'];

        // Notify field widgets and populate option with values.
        field_attach_submit('commerce_option', $option, $form[$field_name][$delta], $form_state);

        // Check if our option is empty. If yes we shouldn't save anything.
        // Cannot use field_get_items() because it calls field_language().
        $option_extracted = commerce_option_get_valuables($option);
        $ow = entity_metadata_wrapper('commerce_option', $option);
        $empty = TRUE;

        foreach (array_keys($option_extracted) as $option_field) {
            $value = $ow->$option_field->value();
            if (!empty($value)) {
                $empty = FALSE;
                break;
            }
        }

        if ($empty) {
            continue;
        }
        global $user;
        if($delta != 0) {
            $new_line_item = commerce_product_line_item_new($current_product, $form_state['values']['field_extra_attributes'][$delta]['quantity'], $form_state['line_item']->order_id, $form_state['line_item']->data, $form_state['line_item']->type);
            $new_line_item = commerce_cart_product_add($user->uid, $new_line_item);
            //var_dump($form_state['line_item']);
            //var_dump($new_line_item);
            //die();
            $line_item_id = $new_line_item->line_item_id;
        }
        else {
            $line_item_id = $form_state['line_item']->line_item_id;
        }
        $product_id = $current_product->product_id;
        $match = FALSE;

        // Check if the newly created options exist on this line item already.
        // If yes we needn't save anything, commerce will just increase the
        // quantity.
        $query = db_select('commerce_option', 'co')
        ->fields('co', array('option_id'))
        ->condition('line_item_id', $line_item_id, '=')
        ->condition('product_id', $product_id, '=');

        $result = $query->execute()->fetchCol();

        if (!empty($result)) {
            $commerce_option_entities = commerce_option_load_multiple($result);
            $option_extracted = serialize($option_extracted);

            foreach ($commerce_option_entities as $commerce_option) {
                $commerce_option_extracted = commerce_option_get_valuables($commerce_option);
                $commerce_option_extracted = serialize($commerce_option_extracted);
                if ($commerce_option_extracted == $option_extracted) {
                    $match = TRUE;
                    break;
                }
            }
        }

        if ($match) {
            continue;
        }

        $option->line_item_id = $line_item_id;
        $option->product_id = $product_id;

        // Save the option.
        commerce_option_save($option);

    }
}
}
?>


Make global results header in a view appear below exposed filters I need to make the text in a global results header appear below the exposed filters on a view and it doesn't give me an option to wrap the header separately from the exposed filters so I can move it below. How can this be done?

You could create a custom block and execute php. Something like this:

$view = views_get_view('my_view');
// get global header
$view->execute();
$objects = $view->result;


What code should .htaccess of files directory hold in drupal 7.25? The module Security Review gives the report my .htaccess in files directory is a security risk because says it has insufficient code to protect the site from anyone wanting to make php edits. However, have checked it with drupal org docs and I can see the .htaccess in files directory matches up with correct security script to keep out any such attempts.

Anyway I am trying to ascertain correct code input for .htaccess in the files directory. I remember there was a bug with this so maybe the security module is picking it up, I don't know.

# Turn off all options we don't need.
Options None
Options +FollowSymLinks

# Set the catch-all handler to prevent scripts from being executed.
SetHandler Drupal_Security_Do_Not_Remove_See_SA_2006_006
<Files *>
# Override the handler again if we're run later in the evaluation list.
SetHandler Drupal_Security_Do_Not_Remove_See_SA_2013_003
</Files>

# If we know how to do it safely, disable the PHP engine entirely.
<IfModule mod_php5.c>
php_flag engine off
</IfModule>

The .htaccess you show is correct - it is actually the default .htaccess that Drupal versions above 7.24 (including the current 7.28) will generate for the files directory if the .htaccess file is missing.

In other words, the warning you get from Security Review is a false postive. There is no malicious alteration.

Your issue is a known bug with Security Review that has already been raised in the module's issue queue at Drupal.org. There is a also a patch that is supposed to fix this issue in the module's issue queue.

You may help the community by applying and reviewing this patch.