Commerce- Show the attribute label instead of product title? Drupal Commerce add-to-cart attribute dropdown list shows product titles, instead of label of the attribute.

One thing that could be causing this is two product types with the same attribute field on the product display. This is required as one product is downloadable and requires a different product type than the second product type used for shippable items.

Is there a way to change the dropdown to contain attribute labels?

Current: https://www.dropbox.com/s/ib03wn7qd7hpwqm/add-to-cart-dropdown.png?dl=0
Desired: https://www.dropbox.com/s/5js29glqqbxuqiz/desired-dropdown.png?dl=0

Drupal Commerce 7.x-1.13

Here's how this was accomplished in a custom module. This will use the taxonomy terms vs the product titles.

function custom_form_views_form_commerce_cart_form_default_alter(&$form, &$form_state) {

$vocabulary = taxonomy_vocabulary_machine_name_load('product_type');
  $terms = taxonomy_get_tree($vocabulary->vid);
  $terms_name = array();
  foreach ($terms as $term) {
    $terms_name[$term->tid] = $term->name;
  }

foreach ($form['edit_attributes'] as $key => $line_item) {
    if (isset($line_item['product_id']['#options']) && $line_item['product_id']['#options']) {
      $options = array_keys($line_item['product_id']['#options']);
      $products = commerce_product_load_multiple($options);
      foreach ($line_item['product_id']['#options'] as $id => $name) {
        $form['edit_attributes'][$key]['product_id']['#options'][$id] =
          $terms_name[$products[$id]->field_product_type['und'][0]['tid']];
      }
      $form['edit_attributes'][$key]['product_id']['#title'] = 'Format';
    }
  }
}

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

if (strpos($form_id, 'commerce_cart_add_to_cart_form') === 0) {
    $vocabulary = taxonomy_vocabulary_machine_name_load('product_type');
    $terms = taxonomy_get_tree($vocabulary->vid);
    $terms_name = array();
    foreach ($terms as $term) {
      $terms_name[$term->tid] = $term->name;
    }

if (isset($form['product_id']['#options'])) {
  $options = array_keys($form['product_id']['#options']);
  $products = commerce_product_load_multiple($options);
  foreach ($options as $key) {
    $form['product_id']['#options'][$key] = $terms_name[$products[$key]->field_product_type['und'][0]['tid']];
  }
  $form['product_id']['#title'] = 'Format'; // added by Lynn. Works on product page, but no in cart
}

}
}


Display the size and format of a file attached to an article I'm trying to display the format and size of a file attached to an article. Its system name is field_file.

So far, I've succeeded to load an article in my my_theme.theme file and the field_file field attached to it:

$article = Node::load($article_nid);
$variables['file'] = $article->get('field_file');

then use its uri in a twig file:
{{file_url(file.entity.fileuri)}}

Now I'm trying to display its format and size. I tried {{file.entity.format}} and {{file.entity.filesize}} without success.

Does anyone have a clue how to do it? I'm still new to Drupal plugins and entities.

Try getSize and getMimeType in your my_theme.theme as in the example below

function my_theme_preprocess_node(&$vars) {
  $node = $vars['node'];
  $type = $node->getType();
  if( $type == "article" && $node->hasField('field_file')){
      //next gets FieldItemList
      //$file = $node->get('field_file');

      //you need get the file entity
      $file = $node->get('field_file')->entity;
      $vars["size"] = $file->getSize();
      $vars["type"] = $file->getMimeType();
  }
}


Know when an order has been paid I need to export some order data to a CSV file. One field is the date (d-m-Y) when the order has been paid. I have search in hook_commerce_*, in the database, but I have not find anything that can help me. Is this data saved in the database, or I need to create a rule that saves this information when the order is payed in full the first time?

I needed to do this in the past. I exported with a View, and used a Representative payment transaction relationship, using Commerce Payment Transaction: Status as the representative sort criteria. Then I just added the Commerce Payment Transaction: Created date field. Assuming that the entire payment is done in one go, I think this method's sound.


Emails sent by actions not using html email formatting I have the HTML email module and it is working for most site emails, however those that are called by actions/triggers don't use the template. How I can I force this behaviour?

When you build an action on the settings page (/admin/config/system/actions) you have 2 options. One is 'send e-mail' and the other is 'send HTML e-mail'. 'Send e-mail' is plain text only, as where 'send HTML e-mail' allows the use of HTML templates. Make sure you are using the 'send HTML e-mail' action.


Problems adding custom field formatter I'm having difficulty getting my custom field formatter to activate. My intention is to allow users to request a 'Copy to Clipboard' button to be added to a text field.

I've tried to follow online tutorials and examples:

http://www.metaltoad.com/blog/drupal-7-tutorial-creating-custom-formatters

https://github.com/SpaceBeers/Drupal-YouTube-Formatter/blob/master/youtube_formatter.module

and I've come up with the following (in a file clipboard.module, referenced from clipboard.info): the formatter_view() function is currently left empty until I figure the other stuff out.

How can I trigger this code? I've tried unloading and reloading the module, clearing the cache, but whenever I add a new text field and then go into the Field Settings for that field, I don't see any form appearing for the custom settings. Should I be setting some other config elsewhere in Drupal in order to enable this?

Thanks in advance for any help.

/**
 * Implements hook_field_formatter_info().
 *
 */

function clipboard_field_formatter_info() {
  return array(
      'clipboard_formatter' => array(
      'label' => t('Copy to Clipboard'),
      'field types' => array('text','text_long','text_with_summary'),
      'settings' => array('show_clipboard_copy_button' => FALSE),
      )
  );
}

/**
 * Implements hook_field_formatter_settings_form().
 */

function clipboard_field_formatter_settings_form($field, $instance,   $view_mode, $form, &$form_state) {
  //This gets the view_mode where our settings are stored
  $display = $instance['display'][$view_mode];
  //This gets the actual settings
  $settings = $display['settings'];
  // Initialize the element variable
  $element = array();
  $element['show_clipboard_copy_button'] = array(
    '#type' => 'checkbox',
    '#title' => t('Enable/Disable Button'),
    '#description' => t('Controls display of Copy to Clipboard Button'),
    '#default_value' => $settings['show_clipboard_copy_button'],
  );

  return $element;
}

/**
 * Implements hook_field_formatter_settings_summary().
 */

function clipboard_field_formatter_settings_summary($field, $instance,     $view_mode) {
  $display = $instance['display'][$view_mode];
  $settings = $display['settings'];
  $summary = t('Enable or Disable a Copy to Clipboard button for text fields', array(
    '@show_clipboard_copy_button'     =>     $settings['show_clipboard_copy_button'],
    )
  );
  return $summary;
}

/**
 * Implements hook_field_formatter_view()
 */

function clipboard_field_formatter_view($entity_type, $entity, $field,     $instance, $langcode, $items, $display) {

  $element = array();
  return $element;

}

You are not supposed to see the settings form in Manage Fields > edit (a specific field) > Field settings as you expect. Formatters are used for managing the display of fields (theming). So, go to 'Manage Display' tab (for your Content Type) and choose the view mode for which you want to manage the button visibility (default, full content, teaser, e.t.c). Find the field(s) you wish this functionality to be applied, and then select as 'Format' option, the label of the formatter you just created, which in this case is 'Copy to Clipboard'. Then if you click on the cogwheel icon on the right, you will see your settings form. Note that this setting will be applicable to all instances of this CT for the specified field for the specified view mode.

If you want other fields of the same CT as well, you need to repeat the process for the other fields as well. If you want this functionality for additional displays of this CT (e.g. teaser view), then you need to repeat the process. And of course, repeat the process for all CTs/view modes/fields as well. This is because Drupal offers much flexibility and variety in displaying content. If you want such a functionality to be applied globally (e.g. for all CTs, for all text fields) then perhaps you should consider another strategy; a new theming function or override of an existing one for example.


How do I check if a block region is empty? I'm wanting to apply some specific CSS on the condition that a block region is empty. How do I make this check?

An update on this. I used the solution at https://drupal.stackexchange.com/a/73685/56728 as follows

  module_load_include('inc', 'block', 'block.admin');
  global $theme_key;
  $blocks = block_admin_display_prepare_blocks($theme_key);
  //test for a named block's (here the help block) visibility
  foreach($blocks as $block){
    if($block['delta'] == 'help' && $block['region'] != -1){
      sdpm($block['delta']. " is visible!");
    }
  }

This detects whether the block is visible or not, but does not quite do what I'm after which is to test for the visibility of a given block on the current "page" for the current user. That to me sounds like what block_list() does, but I'm stumped by block_list() as I mentioned above. My "solution" also very likely not the most elegant way of doing things so any help from experts out there would be greatly appreciated. Nat


Formatting a date field in Drupal rules Is there a way to format a date in Drupal rules? I've got a date timestamp, but obviously that's less than ideal for a client-facing situation.

How do you change a field to a different sort of formatting while in the rules UI?

Can't you use [node:field_calendar_date:custom:l, Fd, gia]? Custom being whatever date format you set up. (like the presets: short, medium, long)

Make sense?


#states not detecting a change to form via ajax_command_invoke I have a form. On an elements I have an ajax call back.
In the callback I use the commands[] to update some elements on the screen.
One of the elements i have updated is used by another form element using the #states. When the ajax call is executed the first time the #states sees that the value has changed and updates.

When I call the ajax event for a second time the #states does not see the same.
One my ajax_commands is invoking the jQuery change().

I have an alert() being thrown when the element is changed and can see that it is being hit every time. However the #states is not updating.

Is there a way to get #states for the form to reevaluate from JavaScript?

For those who might come across this post, I think the problem is related to these issues :

Display Bug when using #states (Forms API) with Ajax Request
FAPI #states: dependent element added via AJAX initializes incorrectly if dependee has been initialized earlier

I found the solution to my problem (close to this one) by reading them.

Actually states may be no longer valid after an AJAX modification because some elements are still flagged as already initialized by the states system. This case produces when just the dependee element or the dependent element is altered by the AJAX request, not both. Only a side of the relation is updated, the other side keeping its old information. Dependee and dependent are therefore no longer linked and the state has no more effect.


Cycle comments on field--comment.html.twig I would like to add a div for every comment on my field--comment.html.twig

On the template I've a "comments" variable, but if I cycle in this way, I obtain error (Fatal error: "0" is an invalid render array key in /var/www/html/core/lib/Drupal/Core/Render/Element.php on line 97):

{% for comment in comments %}
      {{ comment }}
  {% endfor %}

I would like to add "odd/even" class to comments.

[EDIT]
If I use a cycle like this:

{% for key,value in comments %}
  {{ dump(key) }}
{% endfor %}

keys are: #sorted, #pre_render, 'pager', '106', '107' (where 106 and 107 are comment ids)

You can try something like this:

   {% set pre_render = comments['#pre_render'] %}

   {% for key, item in comments if key|first != '#' %}
     {% if key != 'pager' %}
       {% set item = { '#pre_render': pre_render, 0: item } %}

{{ item }}

     {% else %}

{{ item }}

     {% endif %}
   {% endfor %}


All of my pages have class "page--node-" on the body element. This doesn't seem right I'm trying to track down the source of some CSS issues I'm having on my site and I noticed that every page has class "page--node-" added to the <body> element. The theme hook suggestions seem to include page__node__%.

This looks weird. Is it supposed to be like this, or is there a problem in a theme hook suggestion generated somewhere? I'm using a subtheme of Zen 5.

Classes beginning with page generally come from drupal core in template_preprocess_html(), which calls theme_get_suggestions() to do the heavy lifting.

That function makes a bunch of suggestions for the classes or template suggestions based on the path of the current page. The % is used as a wildcard for numeric arguments (in this case the node id).

Then back in template_preprocess_html() it passes the suggestions through drupal_html_class(), which in turn runs them though drupal_clean_css_identifier(), which strips out characters not allowed in a class, including the %, so you get a class of page-node- (this seems like a bug but there is a use for it I will explain below).

This theme_get_suggestions() code is the same reason you have the template suggestion with the percent symbol.

This means you can affect all node pages by using the template name page--node--%.tpl.php.

That might not seem necessary because you also have page--node.tpl.php, however if you want a different template for the path /node than you do for individual node pages you need to use both page--node.tpl.php and page--node--%.tpl.php.

This same reason is why the unusual class is useful.
If you want to style the /node page differently from individual node pages you can style page--node differently from page--node-

I agree it is a silly looking class though with pretty limited (or maybe none) documentation.

Also, something I found after writing this that is useful is How Drupal determines page theme hook suggestions based on path, from the "Drupal 7 Template (Theme Hook) Suggestions" documentation page.


Using page field value in a metatag in I would like to edit my html.html.twig template to assign a value to a metatag in <head> according to the value of a field of a page. Is that possible?

I was trying things like {{ page.myfield.value }}, but with no success and haven't found anything helpful online.

You need to attach the tag in hook_node_view() (which is derived from hook_ENTITY_TYPE_view(), when the view mode is full (which makes the assumption that the full view mode is only ever used on node pages).

You can do that as follows:

function hook_node_view(array &$build, \Drupal\Core\Entity\EntityInterface $mpde, \Drupal\Core\Entity\Display\EntityViewDisplayInterface $display, $view_mode)
{
  // Check if the view mode is full
  if($view_mode == 'full')
  {
    // Create the tag. You can set the content of the
    // metatag from the node
    $tag = [
      '#tag' => 'meta',
      '#attributes' => [
        'name' => 'name attribute of metatag',
        // Note that 'value' will differ depending on the
        // field type.
        'content' => $node->get('field_something')->value,
      ],
    ];

    // Attach the meta tag to the header.
    $build['#attached']['html_head'][] = [$tag, 'some_key_to_represent_tag'];
  }
}


Creating testing local site from online production site I have tried to perform this action several times, only to find that I can never login to the previously created database when I setup my local environment. I have recently picked up the practice to have two sites: development and production, sometimes a third one in between.

Here is my process, maybe I am ommiting a step or two:

Create fresh local Database (same name as online) with PHPMyAdmin
Install Drupal 6 using this database
Setup Drupal installation
Import online Database backup onto new local installation
And here is where I get stuck everytime, with the dreaded:

  Access denied for user 'admin'@'localhost' (using password: YES)*

I have edited settings.php file to work from local to online, so I thought I understood how to do this process in reverse, but apparently I don't.

As a last resource, I have even changed admin's and other user's passwords directly in the database via PHPMyAdmin, and used these in settings.php so I might log in, but it just won't happen.

First, try to do the move the project to your server again but DO NOT go through the installation process. Simple add all the files to the proper directory then move in all the data. After that, just try going to the home page.

If that wasn't it I feel like you probably skipped giving 'admin'@'localhost' permission to access your db.

Try checking admin's priviledges in the MySQL console:

mysql> SHOW GRANTS FOR 'admin'@'localhost';

If admin doesn't have privileges, go into MySQL console and:

Create a user(if you don't have one made): mysql>CREATE USER 'admin'@'localhost' IDENTIFIED BY 'apassword';
Now, give admin priviledges: mysql>GRANT ALL PRIVILEGES ON *.* TO 'admin'@'localhost'
Lastly, flush! mysql>FLUSH PRIVILEGES;

Hope this fixes it!


Views filter (contextual?) by Taxonomy id Have a question.

I have a D8 website for our company. This website contains service pages and now I would like to add a block with reviews on every service page. But the reviews should match the service.
The website has taxonomy vocabulary with all the services. So when I create a service page I have to choose a service from taxonomy (basically, one service page represents one term id from taxonomy vocabulary). And when I create a new review I also have to choose a service from the same taxonomy vocabulary.

So now I would like to add a block with the reviews on the service page. But I have no idea how to make the reviews match with the service page where they are embedded.

Is there some kind of filter what match term IDs from different fields?
Regular filter, contextual filter? Tokens? Unfortunately, nothing worked for me :(

I could create different blocks for every single service ... but there would be a more universal solution.

Would be happy to get any help with that.

Add Term ID as contextual filter.

When filter value is not available, select Provide Default value

For Type, select Term ID from URL

This is automatically pickup the term from your node, your view preview will go blank, because the actual view edit page does not have a term. It will show up when you look at the node.


Where do I find default value for contextual view filters? I'm finding the views in 7 to be much more confusing than in 6! I'm trying to create a block that will filter by the node ID of the page the block is embedded in. When I look at the help for Contextual Filters in the block display, it says this:

  Block displays have no source of contextual filters at all; they
  cannot pull contextual filters from the URL, and often require use of
  PHP code as a default contextual filter. Various default values can be
  applied against contextual filters to use filters in a block view. See
  "Provide default value," under "When the filter value is NOT in the
  URL" below.

  When the filter value is NOT in the URL

  Display all results for the specified field If this option is
  selected, the contextual filter is removed from the view as though it
  weren't there and all results will be displayed.

My question is, where do I find these choices for default values? When I click on the Add button next to Contextual Filters, I get a dropdown list of all content fields, not a list of options like "Display all results for the specified field".

Edited to add

  The Default contextual filter selection is available only if the action to take is "Provide default value" under "When the filter value is NOT in the URL." When that option is selected, a new fieldset will appear that will allow you to choose default contextual filters. Views provides the following default selectors by default

So where is the "When the filter value is NOT in the URL" choice?

You choose a field from that drop down, and the settings you are talking about come up for that field.

These settings are tied to each field, so you can set different fields to come from different sources with different responses if they're not there.


Force trailing slash on every URL? The Global Redirect module has a "deslash" feature. It forces all URLs to not have a trailing slash at the end. If you add a slash at the end of a URL it will redirect you to the correct page.

I'm looking for the opposite of this and would like to have a trailing slash on every URL.

I tried the Trailing Slash module for Drupal 7 but just got a lot of errors. Are there any other methods?

Any help would be greatly appreciated!

Thank you.

Rather than using a module, you can accomplish this via httpd's mod_rewrite as detailed here, here and elsewhere. The appropriate rules can be incorporated into the .htaccess file in Drupal's root. Once you are done, make sure that you check all the various components of the site - CSS & JS files, images, directories, clean URLs on/off, path aliases on/off and so on.


Complicated Views query relationships (for me) So here is what I am trying to figure out how to do. I have a content type of Users and I have a content type of User Programs (Outreach Program, Coaching Program, AA Program, etc) these are being linked by the Entity Reference module as a field on the User content type.

So when I am editing a User, I select the different programs that user is linked to (via the Entity Reference Module). The User Programs content type has taxonomy for the different program categories (Central Sector, North Sector, Western Sector, etc) and you can select multiple categories on the User Programs Node.

What I want to do in Views is this:

 Contextual filter: (User NID) = 40

 User: John Doe

 Programs Related to User --

   Central Sector (Taxonomy) -
     Outreach Program

   North Sector (Taxonomy) -
     Coaching Program
     AA Program

I know how to do simple views, but this one is starting to go out of my comfort zone, and I am getting kind of confused on how I could do something like this. I've tried an EVA view, but I am not too sure if that's what I am supposed to use. Any help would be greatly appreciated!

TIA!

Create your View looking at User records.
Add a Relationship under the Advanced section to link to your Taxonomy.
You then may have to use some Grouping, or Aggregation

Does that help?


Set default title by content type in Panelizer Is there a way to set a default title per content type using Panelizer?  I see that you can use substitutions and change the title after you've created the content, but I would like it to use a specific substitution by default.

I know that I could use the autonode titles module, but I'd rather not add on more modules.  Any ideas?
-JB

EDIT:
Just to clarify, I want to use a substitution for the title (a field from the content type), and the reason I want to set the default is so my admins don't need to change it themselves.

If you're using a custom module already and you want to 'set' the title prior to saving the node then you can use hook_node_presave().

To avoid contributor confusion when creating the node you can also do a form_alter and set the #access of the title field to false.  This will hide the field from the contributor.


How to verify only the email address on user registration? I have a registration form. On the registration form the user can enter his username, email address and password and confirm password.

When the user registered, he/she should receive an email to verify his/her email address before login to the system.

Before email verification he/she should not be allowed to login to the system.

Also he/she should set his/her password on registration, no on email verification.

Is it possible?

I am using the logintoboggan with the Rules module. Through Rules, I set the status of a user to block upon registration. Then through rules with the event When the user account is validated (this event is provided by the logintoboggan rules integration module), I am activating the user.

But the problem is the loggintoboggan module automatically login the user upon email validation, which display an error message that the user is currently not active or blocked although the user has been actived. Because the rule event is triggered after validation of the email address.

Is there any way to prevent loggintoboggan module from automatically login the user upon email validation?

I would NOT block the user at first. That will for sure also not cause that error message you try to get rid of. And instead use the Flag module (in combination with the Rules module) to implement your logic like so:

Use that same event When the user account is validated to flag that user with a flag labeled (say) "Validated".
Any time you want to check if an authenticated user has been validated, you just have to verify if that "Validated" flag has been set for that user (which you can typically do with the Rules module also.

As a remedy to the fact that a user who registers can login to the site without email verification (as in your comment below), you can add some Rules logic like so:

Rules Condition: if this user is not flagged (with that 'Validated' flag)
Rules Action: perform redirect to user/logout

Possibly with an extra message you could set (in the same Rules Action) like "sorry, your account has not been validated yet, please do so and so first".


#states on exposed filter form I have a #states on the exposed filter form as follow:

If field_a == 'b' then field_b show, field_c hidden;

else if field_a == 'c' then field_c show, field_b hidden;

All fields here are Select list.

The states is working fine, problem is the value of the hidden filter is affecting the view result, which i dont want.

Questions:

1) How to change the hidden field value back to default(to -Any- in Select List)? JQuery maybe?

2) How to avoid the hidden filter affecting the view result and to remove the filter (?...&field_b=xxx) in the query string?

updates: working code for states.

 $field_state = array( 'visible' => array(':input[name="field_a"]'
 => array( array('value' => 'a') )),       );

 $form['field_a']['#states']   = $field_state

Though you have custom solutions in place, but a try for views_dependent_filters can be worth, this might be hint as well for your custom solution.

views_dependent_filters module:

  Allows the presence of exposed filters on a view to be controlled by
  values in another exposed filter. Dependent filters are hidden when
  not relevant, and their values are not considered when the exposed
  form is submitted.

  The module is compatible with both the Views basic and the Better
  Exposed Filters form plugins.


How to change the order of banners using the weight module? I have add banners. I want to change the banners order. I have installed the Weight module. I have also added weight in content type but it does not reflect in node.

So how can I change the order of banners?

Check out these modules :
weight

This module adds a weight option to enabled node types. Nodes with
lower weight will float to the top of lists, while heavier items will
sink.

Field_weight

Customise the weight/order in which fields on nodes can be displayed
on a per node basis and not just globally per type. Individual fields
can also be hidden from display.
For any node types that are enabled, a 'Field display weights' tab
will appear on nodes (for users with adequate permissions). From this
page administrators can customise the order in which fields are
displayed on each node by using a draggable table (or manually select
weights).

Nodequeue

The Nodequeue module allows users to collect nodes in an arbitrarily
ordered list. The order in the list can be used for a any purpose,
such as:

A block listing teasers for the five top news stories on a site
A user’s favorite music albums
A group of favorite from which one is randomly displayed

Nodequeue provides a simple drag-and-drop interface
to manually order any queue. Additionally, it allows nodes to be added
and removed from queues without needing edit permissions to the node.
Nodes can be added to queues either from a queue management tab or by
links on the node teaser.


Anonymous checkout doesn't properly work Anonymous users are supposed to have access to Commerce cart/checkout by default. In my current project cart remains empty for anonymous users, even if an order is created. When an anonymous user clicks on Add to cart, a new order is correctly created, with the Owned by anonymous status. This is fine, but:

While the current product page is reloaded as expected, the rule displaying the default message (Foo was added to your cart) is not fired

If I manually go to /cart, I get the Cart is empty message. /checkout returns a 404 error.

$_SESSION remains empty (I precise this because of commerce_checkout_access()).
if (empty($_SESSION['commerce_cart_orders']) || !in_array($order->order_id, $_SESSION['commerce_cart_orders'])) {
  return FALSE;
}

In fact, it seems that in anonymous context, the order cannot be seen.
How do I debug why the cart remains empty, and the order isn't visible  to anonymous users?
My config: clean step by step Commerce install, not Kickstart; some custom line items ;  Access checkout / View own orders of any type / View any product of any type permissions granted for anonymous.

Happy end, and stupid lost time : the lone problem was the Anonymous user was accidentally deleted (don't know how) ! I thank all the gentlemen who tried to help me to debug.

The uid 0 must absolutely be there. If you encounter such case, simply insert an empty row in users table via phpmyadmin or run these 2 queries (for D7) :

insert into users (name, pass, mail, theme, signature, language, init, timezone) values ('', '', '', '', '', '', '', '');
update users set uid = 0 where name = '';

Meanwhile, I've read many things about Commerce checkout to make sure I was doing right. I share some clues below in case it could help somebody else.

A common issue for empty cart page (and other Commerce Views issues where user can't see products) is due to Referenced Product Relationship: 2 solutions may work depending on your config :

In the View's advanced settings fieldset, disable SQL rewriting.
Enable the not-totally-secure View any product of any type permission. This is discussed & patched here. If you have Commons distribution, you’ll have to disable paranoia (disable with Drush only, it's not visible in the module list).

Important permissions to grant (admin/people/permissions) :

Anonymous :

Checkout => Access checkout
Order => Create orders of any type  / Create orders

Authenticated : same ones, plus

Order => View own orders of any type / View own orders

Default behavior in Drupal Commerce :

Anonymous users can add a product to cart, checkout (filling email, name and address), review and complete order. Some documentation to read : Checkout: Anonymous vs. Authenticated  and Anonymous Carts and Logged In Users

An a few useful tips and links to enhance default checkout

How to auto login anonymous user that has completed checkout ? As per duckx answer, you can get this in 3 short steps : checking above rules, enabling Commerce Checkout Complete Registration or Commerce Immediate Login, adding the Login action to the default Commerce "Create new account for anonymous order" Rule.
Use Commerce Checkout Login to provide e-mail validation and an inline login form via AJAX.

  If the e-mail address an anonymous user enters is already associated
  with a user account, the checkout form will expand with an optional
  password textfield and login button for immediate login.

Use the popular Commerce Checkout Redirect  to redirect anonymous users to a page where they can login or create a new account when they try to checkout. Many settings available…
Use Commerce Address book to allow authenticated customers to reuse
previously entered addresses during checkout.
How to set up an Express checkout  (a single page checkout process that any user - including an anonymous user - can complete in a snap)
How to set Different payment methods for different product types  adding a condition to the payment method rule.
How to create an order through Drupal Commerce API
Use Commerce add to cart confirmation to provide an "add to cart" confirmation dialog, shown after the customer has added a product to his cart.
Last, Commerce Extra offers a bundle of features, from which cloning Address information from user's account (instead from previously made orders as Commerce Address book does), and adding an extra step to checkout so that users may log in optionally.


user_delete function is very slow I am writing a script to delete 200+ users. To achieve this, I write a db_select query and got all the UIDs. The I wrote foreach loop to delete users using 'user_delete' function. But this is taking lot of time to delete a single user. It will be very hard to delete 200+ users.

Can someone help me to solve this program to delete bulk users programmatically?

If you want to maintain data integrity, there's not much you can do to speed the process up except upgrade your server's hardware.

user_delete calls user_delete_multiple, and it has plenty to do for each record;
 not just deleting the user record, it deletes fields/data, invokes hooks, clears caches, etc. All of that needs to happen or you're likely to find problems further down the line.

If you're finding that the slowdown is causing the script to timeout, you can process the list with the Batch API and solve that at least.

Incidentally, if you don't care about data integrity, you can just cherry pick the lines from user_delete_multiple that you do need, and execute those directly instead.


Only ONE CSS File for Visitors (and more for Admins) So I just started creating a theme for my first big drupal project, and instantly had to quietly cry in a corner, as I saw how many css files Commerce Kickstart 2 and Omega4 are serving by default.

My plan is to essentially reduce the number of CSS files served to only one, perhaps two (depending on the current page), for the minimum amount of http-requests, without having to manually exclude them all in the theme settings file (which would be an unreliable solution, as new CSS files may get added upon installment of a new module). In addition, exceptions will have to be handled depending on a user role; so visitors should really only get one or two css files, whereas admins shall be served with all CSS files, that are required for the control panel overlay, as well.

Thus my question: Is there a way for me to easily smack those fancy admin- and maintenance-related CSS files back in, only to be loaded for admins?

Basically I want regular visitors to only load my global.css file, whereas admins also get the CSS files of the basetheme as well as commerce_kickstart_menus.css. (For some reason, toolbar_megamenu.css already gets served to admins only.)

Any help or hints as how I could go about this would be super-appreciated!

You can achieve this by extending a hook_css_alter in your template.php for module file.

function hook_css_alter(&$css) {
  global $user;  //  Use this object to check current user roles

  //  The $css variable is an array of all of the css files that will be loaded
}


How to build select lists for search_api views I am building a small website for a charity and am trying to integrate search_api to search the list of projects.

I have a content type named "Project" with the following fields:

Title ( Project Name )
Body
Project Image ( Image field )
Project Countries ( Multi valued taxonomy of all Countries this project operates in )

I need to build a search page that has:

A free text search box that will search Title/Body as a fulltext search
A select list or autocomplete field that allows you to select the country you are searching

So far I have:

Created a new solr search server using search_api
Indexed the Project content type in a new search index
Added all taxonomy values and fields to the search index ( in the hope one would work )
Created a view linked to this index
Added all of the above taxonomy fields as exposed group search filters but none of them pick up the values of the taxonomy.

I can happily freetext search on the indexed fields but if I want to use dropdown filters or even checkboxes to filter the results it just doesn't work.

Clearly I am doing something wrong here, what is the best way to achieve what I am trying to do?

In this case I would create a Facet. You'll need to enable Search Facets (shipped with Search API) and Facet API.

Once you have that in place go to Configuration -> Search and metadata -> Search API and click edit on your Search index. In the dropdown there is a new choice called Facets now.

Enable the facet for you field Project Countries. That field also needs to be indexed under your fields settings for your search index. Facet API will provide a block for you with the Facet that you need to place on your search page.

Facets work in a way that they only show options available in your search result. If "Sweden" is not present in the field Project Countries in any of the nodes you have indexed it will neither be available in the Facet. So facets work in a way that they narrow down search results and usually doesn't show options that will result in an empty search. That's the biggest difference I see between a facet and a normal filter in Views.

Facets are normally displayed as checkboxes or links (see display settings for your Facet). You mentioned in your question that you have it now in the View as a dropdown. You you want to keep it as a dropdown instead of checkboxes / links you could checkout Facetapi select


How do I remove a configuration object from the active configuration? I'm writing a custom module for Drupal 8. It defines a field storage configuration object, in a file called modules/mymod/config/install/field.storage.bloom_stem.bs_twitter_ac.yml.

The problem is that this is not removed when I uninstall the module; it is apparently left behind because, when I re-install the module, I get a crash.

drush -y pm-uninstall mymod
drush cr
drush -y en mymod

  exception 'Drupal\Core\Config\PreExistingConfigException' with message 'Configuration objects (field.storage.bloom_stem.bs_twitter_ac) provided by mymod already exist in active configuration'

So it seems I need to some how manually remove this configuration object. Do I need to provide some more code that deletes it when the module is uninstalled?

The easiest way to do this at the moment is to use drush php (or core-cli) to open an interactive session.

Then use:

Drupal::configFactory()->getEditable('system.menu.devel')->delete();

This functionality will be added into Drupal console as well.


Admin approval notification based on role choose by user on registration form? I need to set admin approval for a particular role. I am using auto assign module to provide user to choose role on registration form.

authenticated users: Do not need admin approval

$form_state['values']['status'] = 1;

$form["account"]["status"]["#default_value"] = FALSE;

Try to use above line on validate function but not getting any success.

I have created a module for this, which addresses my question. It can be found at Select registration roles. Some more details about it (from its project page):

  The Select Registration Roles module adds a role field on the user registration form. Admin can configure roles to be displayed on the
  registration form as, and can set roles which require admin approval.

Here is a screenprint of it also:


How to use a tpl.php file for a theme function I am using LoginToboggan which provides a theme function. You can use this theme function in a template.php file to control the mark up.

However, the code becomes quite unwieldy in template.php. Is there any way to modify the function so it can use a tpl.php file?

More info

This is the function LoginToboggan provides:

function theme_lt_unified_login_page($variables) {

  $login_form = $variables['login_form'];
  $register_form = $variables['register_form'];
  $active_form = $variables['active_form'];
  $output = '';

  $output .= '
';

  // Create the initial message and links that people can click on.
  $output .= '
' . t('You are not logged in.') . '
';
  $output .= '
';
  $output .= l(t('I have an account'), 'user/login', array('attributes' => array('class' => array('login-link'), 'id' => 'login-link')));
  $output .= ' ';
  $output .= l(t('I want to create an account'), 'user/register', array('attributes' => array('class' => array('login-link'), 'id' => 'register-link')));

  $output .= '
';

  // Add the login and registration forms in.
  $output .= '
' . $login_form . '
';
  $output .= '
' . $register_form . '
';

  $output .= '
';

  return $output;
}

Create a template file lt-unified-login.tpl.php in your theme directory and put this function inside template.php to override theme_lt_unified_login_page & return the HTML output of lt-unified-login.tpl.php.

function YOURTHEME_lt_unified_login_page($variables) {
  $template = drupal_get_path('theme', 'YOURTHEME').'/lt-unified-login.tpl.php';
  return theme_render_template($template, $variables);
}


views paging dropdown I need something like a drop down pager for a view with many pages.
Either drop down with all pages listed, or maybe more fancy like this one here:

http://www.zeit.de/2014/18/sextourismus-ostafrika/seite-5

(Scroll down to the comments part. Hovering the comments-pager pops up a grid with page-numbers)

Is there a module for that or an easy way to build it myself? I didn't find a solution.

For now I didn't find any module for this but you can achieve this by playing around with pager CSS. Just like drop down menus. Pager also has an unordered list with ul and li. I tried it and somehow I was able to show pager as a grid on hovering it and it was working.
You have to do some more in it to achieve exactly what you want.

Here I have given you a rough idea and I think this will help you.


How can I log page cache hit rate? I'm running D7 on a php-fpm/nginx stack.

I want to test out some different combinations of cache lifetime and crawler frequency and see how it affects my page cache hit rate. What is the easiest (and reasonably performant) way to create a log with time | url | ip | hit/miss for the built-in page cache.

I figured out how to make nginx do the logging in a rudimentary way. I just added the following after my fastcgi_pass directive.

log_format cache '$time_local $remote_addr $request_uri $sent_http_x_drupal_cache';
access_log /var/log/nginx/cache.log cache;

I'm not going to mark this as answered, because there are some problems with this solution:

Doesn't exclude pages that don't have the X-Drupal-Cache header set (logged-in users)
Doesn't exclude IPs I don't want logged (mine, for example)

For now I'll just deal with those issues when I parse the log file to create my stats, but if someone has a way to exclude them from the log then that would be preferable.


Filter views for same taxonomy term I am using D8. I have two views (articles and videos) sharing the same taxonomy (segments). How can I filter the views based on the view type?
For example, if I am on the articles page, I would need to filter only articles when I select any of the taxonomy term. Right now, by default both articles and videos linked to the taxonomy term are shown.
I am using Taxonomy Menu to display the terms in a block.

Term pages that list all the content that has been tagged with that term are built with "Taxonomy term" Views. You can edit that View to change what those pages show (/admin/structure/views/view/taxonomy_term).

Filter
The easiest change for you would be to add the Content type Filter (from the "Content" Category) to your Views so your visitors can choose manually which types to see listed.
Expose it to your visitors (this option is in the Filter Settings). This will show a filter at the top of each Taxonomy term page that will allow visitors to limit the content to only the chosen content types.
I recommend cloning (duplicating) the Taxonomy term Views, disabling the original and working on the duplicate so you can always refer back to it.

Contextual Filter
For a more automatic solution you can add a Contextual filter instead of a regular one (Contextuals are under Advanced View settings) to filter the results, and build a new Views Display to list the new taxonomy term links that are sensitive to the types of content.
There is already the "Has taxonomy term" contextual filter present there, you need to keep it.
Add another Contextual filter, named Content type, configure it with these options:
When the filter value is NOT in the URL
Hide view
When the filter value IS in the URL or a default is provided
Specify validation criteria
Validator Content type
Case in path Lower case
More
Transform spaces to dashes in URL
Rearrange the Contextuals so the type one comes up first, and the "Has taxonomy term ID" comes second.
Edit the "Has taxonomy term ID" Contextual filter and change its option under When the filter value is NOT in the URL from "Hide view" to "Display all results for the specified field".
This will enable you to add the content type into your path to have it automatically filtered by the type: /taxonomy/term/[ContentType]/[TID], for example: /taxonomy/term/article/5.
There is also an option to override the Title if you need to correct it to name only the content types filtered out.
To test that your Contextual filter is working you can enter the argument for it in the Preview with contextual filters: field and hit the Update preview button if you don't have it set automatically. To view all the results without filtering simply delete the argument or enter all at the Preview or at the end of your path. In this case Views takes 2 arguments so you need to include both of them, separated by /, e.g.: article/5, article/all.

List all links
You can now use Views to build a list of all links to your terms for each content type. It can be a Block Display where you override the "Has taxonomy term ID" to display a Summary, and adjust the Content type Contextual to provide a Fixed Default value, add another Display for your second content type (it doesn't have to be automatic since you only have two types).
There is more than one way of doing this, it's out of scope of this question, but it gives you enough to know which direction to take and learn more.


How can I create a content type in a custom module? I would like to create a content type called announcements for a module that I'm creating, but haven't found much to make this work. I tried this:

    function srl_dash_install() {
    //drupal_install_schema('srl_contactics_monthly_apps');
    $t = get_t(); // runs in both the installer and runtime

  /* Create and save a new content object */
  $announcement = 'announcement'; // machine name of the content type

  // define the node type
  $announcements = array(
    'type' => $announcement,
    'name' => $t('Announcement'),// Display name of the content type
    'base' => 'node_content',
    'announcement' => $t('Announcement'),
    'description' => $t('Add Contactics Announcements.'),
    'custom' => TRUE,
  );

  // set other node defaults not declared above
  $content_type = node_type_set_defaults($announcements);

  // add the body field
  node_add_body_field($content_type, $t('Body'));

  // save the content type
  node_type_save($content_type);
}

but I'm not sure how to make this hook run.

Any help would be appreciated.

That hook is only run when the module is installed, maybe you added the hook during development of your module and when it was enabled?

The hook should be placed in a file called srl_dash.install.

Then disable your module and uninstall it, then enable it again. Now the hook will run.


In a message about a new comment, how to tell if the comment needs approval or not? I am currently using Triggers + Actions to send the node author an email when a new comment is added.

Some of the commentators on my site do not require approval (registered users and repeat commentators).

I would like to indicate in the mail whether the comment requires approval - or send a different message all together in this case. I didn't find any way to configure this.

Answers to a related question suggested the Rules module, but I didn't find a way to make a condition based on whether the comment needs approval.

Edit: I think that the relevant conditions is about comment:status. This field doesn't appear as a data selector in Rules, for some reason.

There is a great tutorial on Rules with a similar use case.


Disable rich text editor by default I am using WYSIWYG module with TinyMce as Rich Text Editor.
I need to make the rich text editor disabled only for a particular text area in a create content page, i.e., when I click Enable rich-text link, it must get activated. How can this be done?I am using drupal 6

There's a solution here http://www.only10types.com/2011/12/drupal-6-enabledisable-wysiwyg-editor.html

Basically, you need to alter this specific edit form. This is what I did for Drupal 7 (the blog post is for Drupal 6):

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

  // Workaround to disable Wysiwyg just in this field.
  if ($form_id === 'FORM_ID_OF_EDIT_FORM') {
    $form['field_CUSTOM'][LANGUAGE_NONE][0]['#wysiwyg'] = FALSE;
  }
}

You may want to use $language->language instead of LANGUAGE_NONE.


How to fix incorrect average ratings for Fivestar? I am using Voting API with Fivestar.  On my site users can comment on a node and leave a rating with the comment.  These are aggregated and an average vote is displayed at the top of the node.  The average rating for some of my nodes does not match what the average would be if you summed up the comment ratings and divided by the number of comments.  Also the count is wrong.

I believe this happened because I manually converted an old Drupal 6 site to Drupal 7 so I manually entered some old reviews.  Because I entered them from the same IP and within the threshold of time I believe the module does not count them.

I'm comfortable running SQL queries to fix this.  I was able to enter the correct average and count records in the votingapi_cache table.  This temporarily fixed the problem, but later I deleted some spam comments, and then the rating was messed up again (I guess maybe deleting causes the votingapi_cache table to be rebuilt?)

What is the correct way to fix this?

UPDATE

So there is more to the story.  I just spent some time manually adding the records into the votingapi_vote table.  Then I added a new comment with a vote through my drupal site.  This caused the votingapi_cache to be rebuilt and I saw the the average vote and vote count were correct.  I thought great problem solved.

Then I deleted my test comment and immediately the average and vote counts went to zero.  Examining the votingapi_vote table which I had just manually added records to, I saw that all records for that node id were gone.  So deleting a comment deletes all records in votingapi_vote table.  Seemed fishy so I searched and found it's a bug in the fivestar module: Deletion of Anonymous Comments with Fivestar rating results in deletion of all votes for entity.

Pretty horrendous bug if you ask me.  Don't think it's fixed in the module but that bug link has a patch for it which I will try out.

Truly correct way to fix it would be to salvage original IP addresses of voters from original database.

If you cannot do it, randomize. Assign each vote an IP from 127.0.0.0/8 range, that way you will not interfere with future votes and large number laws says you'll have pretty small number of duplicates, so averages should be about right.


Print an object value from a twig template? The below object, named 'profile' is available to me in a twig template. I can dump the variables with {{ dump(profile) }}. How do I print the 'created' timestamp? I've tried every variation of code I can think of.

You can get the created value from the entity profile:

{{ profile.created.value }}

or formatted:

   {{ profile.created.value|format_date('long') }}


Why is it easily possible to theme node add forms and not node edit forms? Why can i override:

page--node--add--mycontenttype.tpl.php

and not:

page--node--edit--mycontenttype.tpl.php

What is actually quite the same form?

Have you got the code in your template.php file set up correctly?

It should look like this:

function THEMENAME_theme($existing, $type, $theme, $path) {
    return array(
        'FORMNAME' => array(
           'arguments' => array('form' => NULL),
           'template' => 'page--node--add--mycontenttype.tpl.php',
          'render element' => 'form',
          ),

You can find FORMNAME, by viewing the source of the page and looking for the id of the form.


How to configure the default visibility to "Only the listed pages" when adding a block? When adding a block to the site:

Home » Administration » Structure » Blocks

the default setting for visibility is set to "All pages except those listed." is there a way to set the default setting to "Only the listed pages"?

I'd guess that this possible w/ a custom module but I'd rather avoid that.

Nope. The block add admin form is hard-coded to use BLOCK_VISIBILITY_NOTLISTED (i.e. "All pages.." option) as the default option; there's no configuration setting there. The only way around this is to form alter it with a module.


How can you add a node dropdown list to choose from when adding a link inside ckeditor? We have ckeditor on our wep page which allows users to select text and format it as link by clicking that little chain icon. Users can set the protocol, the target, etc.

We wondered if there is a way to add a dropdown of all nodes (which the user has access to) to pick from? Is there a module/plugin which does that?

You are looking for CKEditor Link - A plugin to easily create links to Drupal internal paths.


Permission base on the administration menu? I have used hook_permission to limit user for some places and to created a permission rule. However, I have not combine two permission from another modules for my custom module.

I'm working on a module that would allow user to used the Administration Menu when user are on a Desktop and used the  Mobile Friendly Navigation Toolbar when the user is on a mobile.

I'm using the hook_page_build to hide the css from mobile or desktop display.

So now I'm trying to limited the hook_page_build to user that only have access to the Administration Menu and the Mobile Friendly Navigation Toolbar.

To be more specific here is the permission that I want user to have enable before this module is been load.

Access administration menu

And the another permission that user need to have is  Use the administration navbar.

Once these two permission have been granted the my custom module is going to be able load. How can I do this ?

I found the solution here is how is done....

function my_custom_module_page_build(&$page) {

    // Check if user have access to the administration menu
    if (!user_access('access administration menu')) return false;

    // Check if user have access to navbar.
    if (!user_access('access navbar')) return false;

     drupal_add_css(drupal_get_path('module', 'my_custom_module') . '/css/mobile.css');

}


Drupal 7, AJAX and browser history I have a website which is AJAX enabled for a great part.

My client now of course wants the browser buttons to behave as expected, which means the page should revert to the previous states when the 'back' button is pressed and so on.

I know there are solutions for this use case, the most interesting one being (seemingly) history_js and its fellow Statehandler module.

I didn't test it yet, because it seems to be heavily based on coding - which I could handle - but I wonder if there is a more elegant (mean : abstract) solution.

The following points are mandatory :

It must work with AJAX Views, including dynamic filters.
It must work with custom AJAX links.
It would be wonderful if it worked with popups (Colorbox style for example), but I think it's a lot to ask for so I could do without it.

What is your experience with AJAX browser history in Drupal 7 ? Any hint on the pitfalls you encountered would be very appreciated. A working solution or a good tutorial would be amazing.

For utilizing browser history and reload buttons with AJAX request, you can use the jquery plugin "jQuery Address"
http://www.asual.com/jquery/address/


Drupal 8 maintenance page theming I want to customize the maintenance page in Drupal 8.

How do I theme it?

In Drupal 8, settings.php contains the following line:

# $settings['maintenance_theme'] = 'bartik';

First, uncomment this setting and change "bartik" to the machine name of your custom theme.

Next, copy the core maintenance template core/modules/system/templates/maintenance-page.html.twig to templates/maintenance-page.html.twig in your custom theme directory.

Lastly, flush the Drupal cache to enable your new maintenance page template. If you need alter the template's variables, you can add the MYTHEME_preprocess_maintenance_page() to your *.theme file.


How to use the flag counter in a twig template of a node? The version dev of the module "Flag" for "Drupal 8" has added a new sub module "Flag Count":

https://www.drupal.org/project/flag/issues/2708291

I copied the code

{% set count = '[' ~ flagcount(flag, flaggable) ~ ']' %}

in flag.html.twig and I copy this file into the templates folder of my theme (I did not cache it).

But after I do not know how to do it. Currently to display the flag link in node.html.twig I put the following code :

{{ content.flag_like_node }}

How to add the number of flag ?

I tested the following code and none works

{{ content.flag_like_node_count }}
{{ content.flag_like_node.count }}
{{ count }}

This will return an array of all the flag counts on a node:

\Drupal::service('flag.count')->getEntityFlagCounts($node)

(For all flags set for that node)
Via: https://www.drupal.org/node/2476349

You can use that in a preprocess function to get your flag counts and send it as a new variable to your template file. Like so:

function yourtheme_preprocess_node(&$variables) {

  $flag_counts = \Drupal::service('flag.count')->getEntityFlagCounts($node);
  $variables['like_count'] = $flag_counts['like'];

}

Then in your theme file you can output:

{{ like_count }}

The problem with this is that it doesn't ajax update when someone clicks the flag link. For that to work you have to put the count in the flag template.


Drupal Filter not working in views? I am trying to filter a development profile in a view where it only shows the developers of the project. I have the filter set on published and only with taxonomy terms "Developers", but the view keeps displaying literally everything published, as if its ignoring the taxonomy filter.

Has anyone ran into this problem and know how to fix it? I am using Drupal 7.

Maybe you can add role. Admin menu --> People ---> Permissions --> Roles

example : "Editor" created

At the views's filter criteria choose: Show campaign for specific roles (field_bcc_specific_user_roles) and select Is equal to "Editor"


Is db_query() closing connections? I recently build a web site with a small-medium profile of user access (around 150.000 pageviews/month) and sometimes, in the middle of the day I get the following error:

  PDOException: SQLSTATE[08004] [1040] Too many connections in lock_may_be_available()

The Drupal application is hosted with the MySQL on the same server, with an 2 CPUs Intel Xeon Quad Core and 8 GB of RAM.

I'm new on the Drupal world, and someone recomended me to use db_query() to throw my queries to the database. I don't know if this is the best pratice or even if this is the root of the problem. Can anyone help me?

You need to make sure the number of MySQL connections (max_connections in my.cnf) is greater than the number of PHP processes (pm.max_children if you use php-fpm, or MaxClients if you're using Apache mod_php).

The default for Apache is often 300, and the MySQL default is only 100, so you can run out of connections pretty quickly if these values aren't tuned.


Replace summary/description with another field in Views RSS output I have a view for an RSS feed which uses the node output (only option it seems when RSS style is selected) so I cant choose custom fields. But, as the body field is 'text and summary' the RSS view uses that summary for the 'description' field but I'd like to use another field for that element in the feed.

Does that make sense?

An option is to just create another field-based view and my own templates to create an RSS output, but it just seems like such a trivial change to require so much work.

Would love to hear some thoughts.

Thanks in advance.

I worked it out. On the 'Manage Display' tab for a content type, there is a 'Custom Display Settings' section at the bottom. Opening that and selecting RSS gives you an RSS Display Fields area where you can change the fields to be used. Looks like it might just work for me.


Add a new colum with a button to field collection I'm trying to add a button or a link (< a href=''>< /a> or a < button>< /button>) in a new column in my field collection. For the moment i have 3 fields added by the administration of my field collection. I searched for add a button by the administration but we can't. what the best tips to add a button in a new column of my field collection ?

Do i need to "foreach" all element of my field collection and add a new element with the HOOK_form_alter ?

Here an example with the actual view (i cut the "delete line button" here so there aren't on the picture):

And now what i wanna create :

The "button" can be a link and after with css i style him.

PS : the button appear on edit content form

Thanks !

Use the Link Module to add a link field to your field collection

  With this module links can be added easily to any content types and profiles and include advanced validating and different ways of storing internal or external links and URLs. It also supports additional link text title, site wide tokens for titles and title attributes, target attributes, css class attribution, static repeating values, input conversion, and many more.

And add the relevant bootstrap class to the output through the manage display UI.


Inline images that can be enlarged I'm re-implementing an old Drupal 4 site with Drupal 8 and I'm stuck with what I thought was a simple task.

I want to insert some images into an article inline and be able to click on them to see a larger version. Preferably the image is shown in some kind of popover/overlay like Lightbox but even loading a new page or just the image in its original size would be OK.

With Drupal 4, I had Gallery 2 integration and this was piece of cake: just enter a placeholder like [G2:1963] in the body text (with 1963 being a Gallery 2 image identifier) and that's it: the image is now shown as thumbnail and when I click on it, the corresponding Gallery 2 page is opened.

I don't need Gallery 2/3 integration (and AFAIK there is none for Drupal anyway as Gallery is going the way of the Dodo). Drupal 8 has support for adding images to an article. But there doesn't seem to be a simple way of adding them inline.

In the CKEditor, I can add an image inline. But there's no way have it shown as a thumbnail and get the large version when clicking on it.

Then there's the image field: it allows me to add images, but they are all shown in some kind of gallery and the end (or wherever you place the field). Not what I want.

The workaround I've come up with is to hide the image field and then add the necessary HTML myself, like:

But this is very cumbersome and feels so very wrong. So, how can I solve this in Drupal 8?

So @NoSssweat's suggestion of using Paragraphs seems to be the best solution to me right now. There seems to be few documentation about this, unfortunately. It took me several hours to figure everything out, that's why I wrote this looong step-by-step guide:

Download and install the Colorbox plugin.
Download and install the Entity Reference Revisions plugin. This is a requirement for Paragraphs.
Download and install the Paragraphs plugin.
Go to Management > Structure > Paragraphs types

First, we need to add a paragraph type. Click the "Add a Paragraphs type" button.
Give it a name and press "Save". I named mine "Text with image (left)".
You're back at the "Paragraphs types" node. You can now see your new paragraph in the table. There's a column "MACHINE NAME", this is going to be important later on when we're theming the paragraph!
We now need to configure the paragraph, so click the "Edit" button next to your new entry.
Click on "Manage fields".
We're going to add two fields. These are the values that you set for your paragraph when you're adding it your content later on. Press "Add field".

In the "Add a new field" drop-down box, select "Image" (in the "Reference" group) and give it a name (for example… "Image"). Press Save and continue.
Now the editor for the "Image" field is shown, with the "Field settings" tab being selected. The default values were fine for me, especially the "Allowed number of values" being 1. So I pressed "Save field settings".
You should still be in the editor for the "Image" field, but now the "Edit" tab is selected. Here you can configure a few things about the image itself, like it's minimum and maximum sizes, which file types to allow and so on. The "Required field" checkbox is notable, it tells whether you must set an image when you're using the paragraph. I'd say yes, so enable this checkbox. Press "Save settings" one you're done.

You're back in the "Manage fields" node. Press "Add field" again.

Now select a text field type, like "Text (formatted, long)" and give it a name (for example, "Body"). Press "Save and continue".
In the "Field settings" tab, there's not much to do. We only want "Allowed number of values" to be 1. Press "Save field settings".
In the "Edit" tab, also enable the "Required field" checkbox. Press "Save settings".

We're back on the "Manage fields" page of the paragraph. In the "Manage form display" tab you can configure how the UI to add content to your paragraph will look like. I just changed the size of thumbnail here, the rest was OK for me.
Go to the "Manage display" tab.

I set the labels for both fields to "-Hidden-" as I don't want them to be shown when the paragraph is rendered.
For the "Image" field, set the format to "Colorbox" and press the gear symbol on the right to configure how the image is going to be rendered. Specifically, set the "Content image style" to a suitable thumbnail size, for example "Medium (220x220)". I don't know yet where you define your own, but the Medium selection suited my need anyway. Press the "Update" button when you're done.

We're now done with the paragraph. Next, we need to add a suitable content type or modify an existing one. Let's set up a new one:

Go to "Manage" > "Structure" > "Content types".
Press "Add content type".

We need to give it a name, for example "Paragraphs page". All the other values were fine for me, so I just pressed "Save and manage fields".
You're now on the "Manage fields" tab. By default, there's one entry in the table named "Body" of type "Text (formatted, long, with summary)". We don't want it, so click on the down facing triangle next to "Edit" and select "Delete". You're asked whether you want to do so, confirm by pressing "Delete".
Back on the "Manage fields" tab, press "Add field".
In the "Add a new field" drop-down box, select "Paragraph" (in the "Reference revisions" group) and give it a name (I named it "Paragraph"…).
Press "Save and continue".
You should now be on the "Field settings" tab of your paragraph field. For "Type of item to reference", make sure "Paragraph" is selected and you probably want the "Allowed number of values" to be unlimited. Press "Save field settings".
You're now on the "Edit" tab of your paragraph field. Do not enable the "Required field" checkbox here as this triggers a bug that prevents you from saving when you add new content (you can't save and get the message "This value should not be null." due to this bug). Just press "Save settings".
In the "Manage form display" tab you can again refine how the UI for adding content will look like. The defaults are fine.
Go to the "Manage display" tab, it allows you to tweak how the content is rendered. I don't want labels so I set the label for the paragraph field to "-Hidden-". Press "Save".

Now we're able to actually create content, although it won't look the way we want it yet. Let's try it anyway:

Go to "Manage" > "Content" and press "Add content".
Select your new content type, in my example it was "Paragraphs page".
Enter a title.
You'll see a message "No Paragraphs have been added yet. Select a Paragraph type and press the button below to add one." Below that message is a button that starts with "Add" followed by a paragraph name. In my example, it's named "Add Text with image (left)". Press it.
You can now select an image (you may need to set the "Alt" field as well) and enter some text for the body. Do so and press "Save and publish".

You can add multiple paragraph per page. Just press the "Add …" button above the "Save and publish" button to add another paragraph.

If everything is alright, you will now see your image and your text. Depending on how you arranged the fields in the "Manage display" tab of your paragraph type, either the image or the text is on top. But we wanted the image to be next to the text. To do that, we need to theme the paragraph.

So the final step is to theme the paragraph. This is under-documented part, IMHO. Here's how to do it:

This needs to be done on the server's filesystem, either by shell or some file transfer software. It depends on your setup.
I'll call the top-level Drupal directory DRUPAL_ROOT. That's the directory with core, modules, sites, … subdirectories.
The Paragraphs module comes with basic template for theming. It's located at DRUPAL_ROOT/modules/paragraphs/templates/paragraph.html.twig.
You'll need to copy that file to the current theme's directory with a special filename.

There might be a better way to do this, please let me know if there is. It feels hack-ish…
Find the theme's template directory: there's some directory that contains *.html.twig files. You need to locate that. I was using the Bootstrap theme, the correct directory for that theme is DRUPAL_ROOT/themes/bootstrap/templates/bootstrap/. For Bartik, it's DRUPAL_ROOT/core/themes/bartik/templates/.

You also need the machine name of your paragraph. I mentioned it above, you can find it by going to "Manage" > "Structure" > "Paragraphs type". Look at the "MACHINE NAME" column.

For my paragraph, that name is text_with_image_left_.

Now, copy the paragraph.html.twig file into your theme's template directory and rename it to paragraph--<machine_name>.html.twig.

My file thus is named paragraph--text_with_image_left_.html.twig. Since I was using the Bootstrap theme, the path thus was DRUPAL_ROOT/themes/bootstrap/templates/bootstrap/paragraph--text_with_image_left_.html.twig.

Edit the file. I don't know what the stuff between {% and %} is for, I didn't need to tweak it. Just edit the HTML to look like this:

{{ content.field_image }}

    {{ content.field_body }}

The content.field_image and content.field_body correspond to your paragraph's field names. You can see those in the "MACHINE NAME" column of your paragraph's field list ("Manage" > "Structure" > "Paragraphs type", press the arrow next to the "Edit" button and select "Manage fields").

Save. Now you need to clear Drupal's cache: "Manage" > "Configuration" > "Performance" > "Clear all caches".
We're done! Reload the test page you've created before and the text should now flow around the image. Clicking the image should open the large version.


Two dependent Flags in my Application I have a rating website and on every node i have two separate flags, one is Like, and another one is disklike, so that i can get a count of how many people likes that particular div and how many of them dislikes them. What i want to achieve is, that say if someone likes a node, the dislike should be disable or even invisible  , and vice versa. I am using a view to show the nodes a the moment, so will i have to uses pre process of views to do it or what is the way going about it?

I would start by looking at the Flag Module Documentation and look into several of the ways you might accomplish this:

You can hook into the Flag Module via PHP, so, in preprocess, you can see if a node has been flagged by either the like or dislike flag (or none yet) and display just the one or both of them when the node is displayed.
You can also hook into the Flag Module via Javascript:  it provides two events you can act upon, so, for instance, after a user has clicked on a flag, you can via jQuery hide the other flag.

And of course, with Views, you can filter on whether or not a node has been flagged by a particular flag or not and then list them accordingly.


Drupal.settings.mymodule is not an object I have implemented a hook_menu() with a callback to check user's privileges and a page callback to create the html. When I am in page_callback(), I retrieve a JSON string from a db and I'd like to pass this string to a JS script that will do some visualization.

function page_callback( $id ){
    $myjson = mymodule_query($id);
    $vars = array('key' => $myjson);
    drupal_add_js(array('mymodule', $vars), 'setting');
    drupal_add_js(drupal_get_path('module', 'mymodule').'/js/myjs.js');
    return '

';
}

In the JS file, I have:

(function($){
    Drupal.behaviors.mymodule = {
        attach : function(context, settings) {
            if(Drupal.settings.mymodule.key !== ''){
                alert('Got it!');
            }
        }
    };
}(jQuery));

When I try to execute this code, I get:

TypeError: undefined is not an object (evaluating 'Drupal.settings.mymodule.key')

Is there any other way in D7 to pass a php variable at runtime to a JS script?

EDIT: trying to follow the advice using render arrays, what is the best way to translate my code? Here's what I have:

function page_callback( $id ){
    $output_data = array(
      '#theme' => 'graph_data', // not sure here...
      '#vars' => array('key' => mymodule_query($id)),
      '#attached' => array(
         'js' => array(
              drupal_get_path('module', 'mymodule') .'/js/myjs.js',
         ),
         'css' => array(
              drupal_get_path('module', 'mymodule') . '/css/graph_data.css',
         ),
      )
    );
    return $output_data;
}

It should be:

drupal_add_js(array('mymodule' => $vars), 'setting');

But ideally you'd be using a render array instead, and loading the settings/files into the page with the #attached method.


How to hide a view programmatically? I need hide a view when some GET param exists. It should be hidden like if you insert 'Global: Null' in contextual filter(It hides view if no results). This view placed in panel*

I tried to find the solution but failed. How to do this?

I am guessing you are adding it as a block to a specific path.
If yes, follow the steps below:

Go to the block configuration
Scroll down to the Visibility Settings
Click on "Pages" tab
Select the option "Pages on which this PHP code returns TRUE (experts only)"
Write your PHP logic to read the GET parameters and return true only if the specific parameter you are looking for is not found.


jCarousel and image zoom I'm using the module image zoom to enlarge an image with the mouse over, also I use jCarousel to get a carousels in different pages.

In the image zoom module you have the option to get the thumbnail of the not selected images.
example :you have a node with 6 images, one will be big and the other will be thumbnails and when you click on one of them automatically it the big image will be swapped with the clicked one.

Now automatically those thumbnail are styled with the jquery carousel, I don't mind but the problem is that I cannot change the configuration of it! I cannot change horizanotal to vertical or other settings.

How do I fix it? Should I create the jcarousel by my self and uninstall the modules or is there a solution somewhere?

Thanks in advance.

As described on the jCarousel module page:

  Note that you will almost certainly need to do custom CSS in your
  theme in order to use this module.

Use Chrome Inspect, Right Click > Inspect aka Chrome Developers Tools or Even use Firebug on Firefox to inspect the applied css properties and override them in your .css file in your theme folder "sites/all/themes/themename"

A basic CSS Knowledge is what you really need.

To Change the Settings of jCarousel, Go to your views and find the "Format" Area. Make sure that the "Format" is set to jCarousel and click on "Settings" beside it. A new pop-up will open. Inside, You will find all the setting related to your jCarousel initiator.

To change from Horizontal to Vertical scrolling, Click on the Advanced, Scroll down then Check the "Vertical" checkbox. See Screenshot

This is the most easy way to do it. If I understod your question rightly.


Drupal 7 MultiStep Form I am trying to implement the Multistep tutorial (Step 9) from http://drupal.org/node/717750 in Drupal 7, however in the following function

function my_module_my_form_new_name($form, &$form_state) {
  $form_state['storage']['new_name'] = TRUE;
  $form_state['rebuild'] = TRUE; // Will cause the default submit function
                                 // to be skipped.
}

I just cant set the $form_state['storage']['new_name'] = TRUE;
therefore i can't catch it in :

 if (empty($form_state['storage']['new_name'])) {
    $form['new_name'] = array(
      '#type' => 'submit',
      '#value' => 'Add another name',
      '#validate' => array('my_module_my_form_new_name'),
    );
  }

I can however declare it in the beginning of the function, which can be executed fine. So how can I set it in Drupal 7?

Helpful links for creating multi steps form are https://drupal.stackexchange.com/questions/135/are-there-any-examples-of-setting-up-multistep-forms http://drupal.org/node/717750, and http://drupal.org/project/examples.

I practiced multi step forms by getting the code of the form tutorial from http://drupal.org/project/examples, and added further steps; it works excellently fine for me.


Create file through services I've been trying to create and update users and their pictures through REST calls using the services module. So far, I've got creating and updating users to work, but creating files to set their profile pictures still doesn't work.

I try to do a POST request to my API endpoint (http://www.domain.com/api/api_name/file), with the following data:

    $data = array(
        'file' => base64_encode($file),
        'filename' => $filename,
        'filepath' => 'public://' . $filename
    );

I POST this using CURL, with the exact same settings (apart from the API endpoint) as I'm using to create a user, which is working. However, I'm getting a HTML 500 as a response, with no response contents otherwise. The following error is logged in the Drupal error log:

Notice: Undefined property: stdClass::$fid in file_entity_access() (regel 1661 van /home/enschede/domains/aegee-enschede.nl/public_html/sites/all/modules/file_entity/file_entity.module).

The function that it errors on, file_entity_access, says that its $file parameter will either be an object, or a string with the file type (e.g. "image") if it is a create action. Apparently, it receives an object, so the create action is not executed properly on the server.

However, at this point I'm stuck. I can't find where these calls are coming from on the server, and I can't find anything I should change in the POST request. The fields I'm posting are the same as a tutorial I've followed. I'm posting the following fields to create a user, with the exact same CURL options otherwise:

    $initialData = array(
        'name' => 'test.user',
        'mail' => 'bogus_email@provider.com',
        'pass' => 'waytoolongboguspassword',
        'status' => 1
    );

If you need to create/update a file alongside the entity posted JSON you need to create the file in your code like:

//Implements of hook_services_request_preprocess_alter().
function my_module_services_request_preprocess_alter($controller, $args, $options) {

switch ($controller['callback']) {
case '_user_resource_create':
case '_user_resource_update':
  if (isset($args[1]['avatar'])) {
    $data = base64_decode(trim($args[1]['avatar']));
    $finfo = finfo_open();
    $mime_type = finfo_buffer($finfo, $data, FILEINFO_MIME_TYPE);
    finfo_close($finfo);
    // get file type png. jpg
    $ext = $mime_type ? str_replace('image/', '', $mime_type) : 'png';
    $file_name = str_replace(' ', '-', $args[1]['name']);

    $file = file_save_data($data, 'public://users/' . $file_name . '.' . $ext, FILE_EXISTS_REPLACE);
    $args[1]['field_field_user_picture'] = array(
      'fid' => $file->fid,
      'width' => 100,//set your own
      'height' => 100,//set your own
      'alt' => $args[1]['name'],//set your own
      'title' => $args[1]['name']//set your own
    );
  }
}

By that way you could create any image field with any entity easily.

From the best practice I advice you to use the module user picture field that let's you deal with the user picture as a field so you could have it in views with different formats instead of just have the file id.

Another tip is to send the image format as It won't be possible to get the mime type from the json decoded file source.

Sure you still be able to create a file through file services but I think you have to make the post request format www/url-encoded instead of json


Why is my Drupal ajax form not populating the radio buttons I have a form which send an ajax request to my server. The form is:

function dokimi_add_to_list_form($form, $form_state) {

  $form = array();

  $options=array(
      'option1'=>'option1',
      'option2'=>'option2'

  );

  $form['private_list'] = array(
    '#type' => 'radios',
    '#title' => 'Private lists',
    '#options' => $options,
    '#prefix'=>'
',
    '#suffix'=>'
'
  );

  $form['add_new']= array(
    '#type' => 'fieldset',
    '#markup' => 'Add a list'
  );

  $form['add_new']['new_list']= array(
    '#type' => 'textfield',
    '#title'=> 'New list',
    '#default_value' => '',
  );

  $form['add_new']['add']= array(
    '#type' => 'button',
    '#value' => t('Add'),
            '#ajax'=>array(
              'callback' => 'add_to_list_callback',
              'wrapper'=>'list_list'
                  // 'wrapper' is the HTML id of the page element that will be replaced.
        )
      );

 return $form;
}

And the callback function is:

function add_to_list_callback($form, $form_state){

    $options=array(
      'newoption1'=>'newoption1',
      'newoption2'=>'newoption2',
      'newoption3'=>'newoption3'
  );
    $form['private_list'] = array(
        '#type' => 'radios',
        '#title' => 'Private list',
        '#options' => $options,
        '#prefix'=>'
',
        '#suffix'=>'
'
  );

    $commands = array();
    $commands[]=ajax_command_replace('#list_list', render($form['private_list']));
    return array(
        '#type'=>'ajax',
        '#commands'=>$commands
    );

}

When the 'Add' button is clicked, a new array of options should be returned, but I get an empty list instead.

The form is rendered in a ctools modal if that is of importance.

Thanks for any help with this - it's driving me barmy.

I think you need to reorganize your code.
First you need two ['Private_list'] at the same function Form and at this same function form you need to declare the array variables for each private list.

$list1_options = array(......);
$list2_options = array(.......);

['Private_list1´]: these are the first choice the user need to do: here you use the ajax call back.

['Private list2']: these one have the choices the user need to pick according to the first selection on ['Private_list1´]: at this 'Private_list2' you use the wrapper prefix and suffix.

the ajax call back function should only look something like this most of the times:

function example_change_callback($form, &$form_state) {
  return $form['private_list2'];
}

Your basicly using the call back to identify wich form you need to update on event change.

I recommend you study this drupal dependent ajax example, dispate the example is using dropdown list, you should be able to aply it to radio buttons, just follow the same structure.

I hope i was hepfull, tell us later how it went...
Have a good coding!


Associating Custom LDAP Query with View Versions:
->Drupal 7.10
->LDAP Authentication/Authorization/Servers/Query/Views 7.x-1.0-beta5
->Views/Views UI 7.x-3.3

I'm attempting to configure a View via the Views UI module to support a custom LDAP query defined in the LDAP Query module. The example they provide depends on the existence of a query with the machine name of "ad_users", and does function when I define a query with that name, but there doesn't seem to be a way to alter this or point a view toward an arbitrary query.

I'm wondering if I'm overlooking something. It seems illogical that the Views plugin wouldn't let one point a View toward an arbitrary LDAP Query. The question is how to do this?

In the Advanced section of the view, click on Query Settings and choose your own LDAP Query from the select list that appears.


Menu doesn't link to alias URL I'm having difficulty on a fresh Drupal installation getting the menu to use an alias (let's say "foo") rather than "node/#" link. The alias works when I type it straight into my browser. When creating the menu, I specified the alias (foo) but it automatically applies the system path to it.

The message that comes up is:

The menu system stores system paths only, but will use the URL alias for display. home has been stored as node/1

This doesn't come up as an error, rather just an information dialogue.

For this installation I did a minimal install as I wanted it to be a fairly simple website. I've never done this before so there were a few modules I had to enable to get it working how I wanted. I'm thinking maybe there's a module or menu setting that isn't enabled by default using the minimal install.

I'm not using any language packs, and none of the solutions on the following questions were successful (most revolve around languages.)

URL Alias does not work in Menu-Blocks with i18n (pathauto also installed)
How do I use URL aliases in menus?

You can use Pathauto and Global Redirect Module.


Why can't I save a value from my form? I have a problem with my module that only creates a form to submit a validation.
The target of this module is to set a variable that I put in a textfield.
The problem is that it doesn't save the variable, it only shows the default value. (I use variable_set and variable_get)

This variable is necessary because I use this form in another module that get this variable from the database. (My variable is id_event)

This is my code of my own module:

<?php
function example_form_form1(){
    $form['id_event'] = array(
     '#type' => 'textfield',
     '#title' => t('Id Event'),
     '#required' => TRUE,
         '#value' => variable_get('id_event', 7), //Here is my dude
    );

    $form['submit'] = array(
     '#type' => 'submit',
     '#value' => t('enviar'),
    );
 return $form;
}

function example_form_submit($form, $form_state){
    $id_event = $form_state['values']['id_event'];
        variable_set('id_event', $id_event);//here is my dude
        drupal_set_message($id_event);
}
?>

Now, this variable is necesary for other module that only get.

<?php
$file_json = $this->options['xml_file'].variable_get('id_event', 1);
//Here don't get the value that i put, only put the value for default.
?>

Thanks :D

The reason your current code isn't working is because your submit handler doesn't follow the correct naming convention (i.e. FORM_FUNCTION_NAME_submit) and you don't explicitly attach the submit handler to the form anywhere so it's not being run.

You can solve this by simply changing the nameof your submit handler:

function example_form_form1_submit($form, $form_state){

Or you could look at system_settings_form() which automates much of this process for you.


Easily Determine if Field Is Required I have a large set of Content Types,each with a fair amount of fields.  IS there a way to programatically report on whether those fields are required or not?  It is tedious to click on each field to check it.

You can make use of Field Info API functions to get this information.

Since the 'required' setting is on the instance level, not the field level, you'll need to use either field_info_instances(), which will get the instance information for all fields attached to a given entity type and bundle:

$entity_type = 'node';
$bundle = 'article';

$info = field_info_instances($entity_type, $bundle);
foreach ($info as $field_instance) {
  $required = (bool)$field_instance['required'];
}

or alternatively, if you only want the info for a single field, the field_info_instance function:

$entity_type = 'node';
$bundle = 'article';
$field_name = 'field_my_field';

$info = field_info_instance($entity_type, $field_name, $bundle);
$required = (bool)$info['required'];


WSOD with Devel module A website I am working on is having a WSOD problem, but only on the permissions page. I narrowed this down to the devel module, because when enable, WSOD permission page, devel module unenabled, clean permission page. Any idea what is causing this?

The solution to this problem was to un-enable the Devel module, uninstall the Devel module, clear the cache, and rebuild permission, then re-enable the Devel module. Not sure that clearing the cache and rebuilding permissions was necessary, but this solution did allow the Devel module to be enabled and view the permission page.


Views: count and filter by entity field value I have many nodes of type 'Players' and 'Match'. In the 'Match' node there is an entity field 'Strikers' referenced to 'Players' which allow multiple values.

I'd like to create a player page that shows information about that player searching all occurrence of that player in the 'Match' nodes (inside the 'strikers' field of each node).

I tried with the contextual filter but I don't know if it is the correct way..

Going of memory here, this might be wrong:

Add contextual filter of node id (nid) (so the player nid goes here)

Add a RELANTIONSHIP of Strikers Referencing Entity and checkmark the box that says, "force relantionship" or something along those lines.


drupal_add_js() does not add .js file from libraries folder I have a page callback where I want to add a colorbox library by this code:

drupal_add_js('sites/all/libraries/colorbox/jquery.colorbox-min.js', 'file');

The file exists, path is right. But in html is this file not included. Why it does not work?

That seems apply to your issue :

  This problem occurs because the path to library is often incorrectly
  set as

libraries\colorbox\jquery.colorbox-min.js

  The solution should be to correct the path. You need to place the
  whole Colorbox plugin directory after unpacking it in
  sites/all/libraries This means the path should look like

sites/all/libraries/colorbox/colorbox/jquery.colorbox-min.js

Source


Services: Getting error 406 Node type is required - but I have specified the node type I'm trying to create a node using jQuery to POST JSON.

I get the following error returned by the server:
Failed to load resource: the server responded with a status of 406 (Not Acceptable: Node type is required)

However, the type is definitely specified in my JSON string:

var data = '{"title":"Sample post ",
  "type":"article",
  "field_link":
            [{
             "url":"http://www.google.com",
            "title":"My title"
            }],
  "body":
            {
             "und":[{"value":"comments about something"}]
             }
  }';

try to observe the order of fields like: type > title > body > fields
that is the widget type of "field_link"?
add "und" to this field

{"title":"Sample post ",
"type":"article",
"body":{
"und":[{
"value":"comments about something"}]},
"field_link":{
"und":[{
"url":"http://www.google.com",
"title":"My title"}]}}


How do I get a freshly updated value (i.e. not the cached value) using entity_metadata_wrapper? In my code I am inserting a new value into the database directly using db_insert (i.e. inserting an entirely new row).  The type of field, however, already exists in Drupal which is called "field_data_field_email_address".  Previous to the insert call no value existed in the database which is associated with an entity.

Later in code I am relying on entity_metadata_wrapper to retrieve the values associated with the entity.  The problem is that the wrapper doesn't retrieve the most recently inserted value but instead returns nothing.  Yet when I look in the database table I can clearly see the existence of the newly inserted value.

As you may have already guessed I narrowed the issue down to a caching issue because if I clear the Drupal cache the wrapper returns the newly created value just fine.

My question is this: How can I force the entity_metadata_wrapper call to not retrieve the cached version but refresh and return to me the actual current values that exist in the database.  I need my wrapper to represent the freshest data and not the cached version.

Thank you in advance!

The cache can actually be cleared using the entity_load function and passing a value of true for $reset which will clear the cache and update future references to it including wrappers retrieved from entity_metadata_wrapper:

entity_load("node", array($nid), null, true);


View contextual filters to work as needed I have content type A with some vocabulary for it and content type B with same vocabulary.
On the node page of type A I want to show block with some content of type B wich has any same terms as node page we're viewing. Is it possible?

Thank you!

This is extremely easy using Panels as Panels is context aware. You can pass this context to the view, which displays the results based upon the contextual filter.

Look at http://nodeone.se/sv/node/702 and the next episode to get the hang of it.


How to contextual filter a view by a field value? QUESTION

I have an address field in my user form, from the address field module.

I have a content type named "project" which also have an address field and users can pick up a country related to the country the project will belong to.

I want to make a view filtering all the projects related to the logged-in user's address country field.

TRY

My trick is to make a user-view with a author-content relationship filtered on the content type project. Now I have the two fields in the view, I'm trying to compare them with a contextual php filter.

I tried to use php filter based on this post

$node = node_load($data->nid);
$user = user_load($user->uid);

$field_user_country = field_get_items('user', $user, 'field_user_address_country');
$country_user = field_view_value('user', $user, 'field_user_country', $field_user_country[0]);

$field_project_country = field_get_items('node', $node, 'field_project_range_country_country');
$project_country = field_view_value('node', $node, 'field_project_country', $$field_project_country[0]);

if ($price_a = $price_b) {
  return TRUE;
}

The fact is field_user_address_country is actually stored under field_data_field_user_address in the database.

Same for field_project_range_country_country which is stored under field_data_field_project_range_country

What is the best way to do this ? Is what I'm trying to do possible ?

UPDATE 1

Clear code which give me an ajax error :

$node = node_load($data->nid);
$user = user_load($user->uid);

$field_user_country = field_get_items('user', $user, 'field_user_address_country');
$country_user = field_view_value('user', $user, 'field_user_address_country', $field_user_country[0]);

$field_project_country = field_get_items('node', $node, 'field_project_range_country_country');
$project_country = field_view_value('node', $node, 'field_project_range_country_country', $field_project_country[0]);

if ($country_user == $project_country) {
  return TRUE;

UPDATE 2

Here the new code which is still giving me an ajax error :

  EntityMalformedException : Missing bundle property on entity of type
  node

$node = node_load($data->nid);
$user = user_load($user->uid);

$field_user_country = field_get_items('user', $user, 'field_user_address_country');
$country_user = field_view_value('user', $user, 'field_user_address_country', $field_user_country[0]);

$field_project_country = field_get_items('node', $node, 'field_project_range_country_country');
$project_country = field_view_value('node', $node, 'field_project_range_country_country', $field_project_country[0]);

if ($country_user == $project_country) {
  return $country_user;
}

Have a bigger ajax error (like 15 lines) if I put

global $user
$node = ($node = menu_get_object()) ? $node->nid : NULL;

At the beginning of my code.

Create a block view of Show: content, in contextual filter add Country.

Add this to your view contextual filter:

  global $user; // gets current logged in user object

  if (isset($user->field_user_address[LANGUAGE_NONE][0]['country'])) {
    $user_country = $user->field_user_address[LANGUAGE_NONE][0]['country'];
    return $user_country;
  }