address field hides if country is changed I have used Address field module for storing user address. Also I have used Customer Profile Type UI for adding customer profile. I have added customer profile field in the user page by adding customer profile field in account settings. In the customer profile type I have added address field, name field and etc..
In my case Check box will be available on clicking checkbox an ajax callback happens which renders the customer profile form which has address field and name, for now no problem occurs. In address field all country are available and showing site default county as default one. If user change the country ajax call happens and address field hides. Please help me.

It works as designed.
For some countries there is no need to enter ZIP code.

You can change this behavior by implementing this alter in your custom module:

/**
 * Allows modules to alter the predefined address formats.
 *
 * @param $address_formats
 *   The array of all predefined address formats.
 *
 * @see addressfield_get_address_format()
 */
function hook_addressfield_address_formats_alter(&$address_formats) {
  $address_formats['AF']['required_fields'] = array('postal_code');
  $address_formats['AF']['used_fields'] = array('administrative_area', 'postal_code');
}

Change required_fields and used_fields as desired.
More code you can find in this file:

addressfield/addressfield.address_formats.inc


Huge cache_menu table My Drupal database becomes very huge, it just related to cache_menu table:

~4,291,529 rows and 2.9 GiB

What can I do to prevent this? is there any way to change cache strategy for menu items? or simply I should EMPTY this table every week?

It has been a bug in Drupal, but should be corrected since Drupal version 7.13. See more details here: http://drupal.org/node/1234830

As a workaround, you can empty (truncate) the cache_menu table, since it is just a cache table and will be regenerated. Of cource, you'll have a trade-off in performance, in that case.


Status message appears multiple times on status stream I have user relationship and Status modules installed. Each time a user posts a message on his/her profile it appears 12 times in his/her status stream while it appears once in other users stream.

Please does anyone know what can be wrong?

According to this that module uses Views to create the blocks, so it could be just a matter of "Reduce Duplicates" on the filters, or checking the "Distinct" option on the view itself.


Drupal 7 commerce stripe stripe-php library refuse to load I'm trying to implement commerce on my D7 site and after installing packs of modules I've installed commerce_stripe module to use Stripe payments.

After I created all necessary things(stripe account, products, stripe api keys, latest stripe-php library in sites/all/libraries/) I'm trying to proceed payment and see an error:

Error making the payment. Please contact shop admin to proceed.

Went to reports -> recent log messages and see:

Failure to load Stripe API PHP Client Library.

Hours of googling and I found few ways how to handle it. Updated Libraries module to the latest version, instead of 7.x-3.0-alpha installed 7.x-3.x-dev, clear cache, run cron.
Unfortunately, nothing happens.

trying to locate an error I've found function that trying to load stripe php library. It's commerce_stripe_load_library() in commerce_stripe.module file. Error throws in the beginning of this function:

$library = libraries_load('stripe-php');
  if (!$library || empty($library['loaded'])) {
    watchdog('commerce_stripe', 'Failure to load Stripe API PHP Client Library.', array(), WATCHDOG_CRITICAL);
    return FALSE;
  }

Trying to dpm result of libraries_load() function.
and first condition !$library is passed successfully.
But $library['loaded'] is FALSE.

Any ideas why? Any help appreciated.

Finally found the solution.
There is wrong information about installing library on drupal dot org.
It says

Installation
Install and activate Commerce Stripe and Libraries modules.
Download the latest Stripe PHP release from GitHub.
Extract the contents of the archive into the directory /sites/all/libraries/stripe-php
Create an account at Stripe.com, and insert your API keys from the Stripe
Dashboard into the Commerce Stripe payment method settings at admin/commerce/config/payment-methods.

So the thing is that this is the wrong information. If you go to commerce_stripe.module and find hook commerce_stripe_libraries_info() in 'version arguments' you will see that it tries to locate in file VERSION this pattern:
'pattern' => '/(3.\d+(\.\d+)?)/',
It means that you need version 3 of stripe-php library(depends on your commerce_stripe module version).
So fix for this is to use correct version of stripe-php library
UPDATE
You can check necessary library's status by executing drush library-list
you will see something like this:
Name                   Status        Version  Variants          Dependencies  Provider
stripe-php             Not detected           -                 -             Commerce Stripe

if stripe-php library's status is not detected, then you user wrong version or place the library to the wrong place.


Drupal 7 CDN whitelist issue My Drupal 7 site is working nice and most of my static files are served via CDN. I use CDN module with Origin Pull however CDN didn't pull the files from my misc folder where there are small png icons (came with vanilla drupal installation).

In CSS, I have used url('sites/all/themes/mytheme/img/bg.png') for background and I can see the background, and it is served via CDN. In the same CSS I have url('misc/configure.png') but this one is not working. I see 404 for configure.png while checking from Developer Tool.

So, I added the path in CDN module's whitelist like misc/*.png and did all those flushing and cron for CDN to recognize the file. Still CDN didn't pull the file. I have set the file permissions to 775 too, but nothing changed. Any help would be appreciated.

Edit: the 404 is only for the picture, I checked it via chrome's Developer tool. It shows the path https://myCDN/misc/configure.png (which is missing), whereas for background it shows https://myCDN/mysite/sites/all/themes/mytheme/img/bg.png.

However, the notable difference is in configure.png the name of my site is not present in CDN path. If I change the path via Chrome Developer Tool like https://myCDN/mysite/misc/configure.png It works, the image shows. It also works if I use absolute url in CSS like url('https://mysite/misc/configure.png')

I was doing the wrong practices with Drupal Theme, in CSS whenever I have to use the url() to declare the path, I was using url('sites/all/themes/mytheme/images/bg.png') which is considered as Bad Practice, so I changed that to url(../images/bg.png) and same for Images inside misc folder as url('../../../../misc/configure.png') from CSS and everything is working as expected.

To tell long story in short, don't use absolute url from the root in CSS but use relative paths.


How to get change event working of a taxonomy select box on a node form? I have a taxonomy, which I have added to a content type. Now a select box from the taxonomy appears when I want to create a node of that content type.

That content type have a cck field of type select.

In my module in the hook_form_alter I want to execute the js change event of the taxonomy select box, but it does not work.
And when I try to execute the js change event on cck select box, it works fine.

here is my code.

function mymodule_form_alter(&$form, &$form_state, $form_id) {
     if($form_id == 'contenttype_node_form') {
        drupal_add_js("
            $('#taxonomy-select-box-id').change(function(){
                alert('change');
           }) ;

", "inline");
    }

This isn't really a Drupal question, but at a guess I'd say the problem is that you're binding the event to an element before the DOM has loaded...so the element doesn't exist yet. You should use one of the standard jQuery methods to run your code when the document is ready, e.g.:

$(document).ready(function() {
  $('#taxonomy-select-box-id').change(function(){
    alert('change');
  });
});


Form - Show partial form in block then populate full form with partial data I have a content type with various fields.
Now i would like to show a couple of it's fields in a block globally and on submission post that data to the full form page and pre-populate the already provided fields.

Can this be done easily with the drupal core or is there a helpful module you guys can recommend?

As contrib is an extension of core there are always ways to do stuff in core that you can do with contrib, it's just often contrib makes it easier, quicker, and more easily maintainable at the sacrifice of more code.

For this I would look at the prepopulate module which allows fields in most forms to be pre-populated from the $_REQUEST variable:

https://drupal.org/project/prepopulate

If you want to use just core then you know what you're outputting in the block, at a guess you could form_alter the form linked to prepopulate.


Best practice: $this->t() versus t() I'm looking for a best practice: should contributed modules use $this->t() or t()?

Best practice depends on where the code is placed.

OOP Code

Use $this->t().

If you extend a drupal base class like a controller or a plugin the t() function is provided as class method $this->t() out of the box and you should use it. This makes your code testable.

For most tasks you'll find a suitable drupal class to extend from which has $this->t() defined, but if you need to build your own class from scratch best practice would be to use the string translation trait and inject this as service if you use this class in a service context:

use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\Core\StringTranslation\TranslationInterface;
class MyClass {
  use StringTranslationTrait;

  /**
   * Constructs a MyClass object.
   *
   * @param \Drupal\Core\StringTranslation\TranslationInterface $string_translation
   *   The string translation service.
   */
  public function __construct(TranslationInterface $string_translation) {
    // You can skip injecting this service, the trait will fall back to \Drupal::translation()
    // but it is recommended to do so, for easier testability,
    $this->stringTranslation = $string_translation;
  }

  /**
   * Does something.
   */
  public function doSth() {
    // ...
    $string = $this->t('Something');
    // ...
  }

}

Source: https://www.drupal.org/docs/8/api/translation-api-code-text

Procedural Code

Use t().

If you have procedural code, for example a hook, then use t(), which is a global function.

Not best practice would be to use the procedural t() in OOP Code.


Exclude a node field from loading I would like to exclude some of node field from loading while viewing nodes.
I can hide fields currently, but I want to exclude it completly from loading.
I have multivalued fields which have around 2000 records and I don't need to load it on node pages.

On the 'manage display' page of your content type you can set fields as hidden. This will make the field not only hidden also it won't load it at all.


module for ajax username checker Is there a D7 module to do an Ajax based test if a username is available, in the same way done on https://en.wordpress.com/signup/?

A quick search with "drupal ajax username checker" points me to the Username originality AJAX check module. There is a dev version available for 7.
Some more details about this module (from its project page):

This very simple module allows visitors to check username originality quickly using AJAX request during registration (completing registration form). This makes registration process more convenient as you don't need to submit your registration form to find out whether this username is already taken or not. This module is sensible to standard Drupal username validation as well as Access Rules validation.
username_check module provides two ways of user name checking:

Manual (5.x and 6.x) — a "Check availability" button appears on the form and a visitor can press it to verify whether his name is available or not.
Automatic — check is performed automatically when you finish typing and on leaving username field.


How to properly use media (in core)? We are converting all of our images to the image type provided by media.  What I don't really understand is that there seem to be multiple ways to do this.  Am I supposed to give the 'image' media type a file field, and then use that?  Or, should I give the 'image' media type a 'file' media type field, and use that?  Or, is there something I'm missing and the 'image' media type already has support for images?

Based on my understanding, you're supposed to create a file field in the 'image' media type, and then you use that as the source.  Is that right?

You need to add a field to the media entity, that acts as the base for a media provider module (such as images, files, remote videos, google docs, etc.). The various media provider modules dictate the field, that is needed to store and retrieve the essential information (and optionally some meta data)

E.g. for creating image media entity, you select "image" as media source (provider). Then add the image field to the entity, and select this field as base for media provider. Optionally the media provider can extract additional meta data (width, height, EXIF,...) from that field and map it to other fields of your media entity.

For a Youtube video (Video embed field), the base field is an URL field. For a File media entity, the base field is a file field. And so on.


Slow running script in IE8 So I've got this "nice" Drupal 7 site and there is a node with a large (70is) fields that the user fills in. There is a script that hides and shows certain questions depending on the previous answer. It works fine in IE9, FF, Chrome and Safari but in IE8 it gives this error:

A script on this page is causing Internet Explorer to run slowly. If it continues to run, your computer might become unresponsive.
Stop running script? YES/NO

There are only around 10 lines of my code being run, the rest is written out by Drupal. Is there a way to split up the script or speed it up? Or should I avoid using Drupal to write javascript and custom code it?
EXAMPLE
In the node/add I have code like this:
$form['group_section_one']['field_permit_number']['#states'] = array(
        'visible' => array(
            ':input[name="field_do_you_have_a_permit[und]"]' => array('value' => '1'),
        )
    );

To show the "permit number" field if they answer Yes to "Do you have a permit?". I do a similar thing for another 60 fields sometimes they depend on up to 4 field values.
That then writes out javascript which equates to around 100 lines all up. I wouldn't have thought that would freeze up the browser though...

The tough thing here is that IE 8 is notoriously poor in terms of JS performance (compared to recent versions of FireFox, Chrome, Safari and even IE), and there's not a whole lot you can do to fix that.

However, in this case, I would consider one of two options:

Try to use different (faster) selectors besides :input[name="field_name[und]"] with Drupal's AJAX form states. If fields have IDs (they should, if the form is generated by Drupal), use the id instead, like field_name.
(If the above doesn't work) Try coding the visibility yourself (forgoing Drupal's FAPI #states system). You can optimize selectors and overall memory usage and performance by hand-tuning the jQuery or JavaScript yourself.

I'm guessing following #1 could fix your problem, though. For more reading on jQuery selector performance, see:

Your jQuery: Now with 67% Less Suck
jQuery Selector Performance Testing

However, for a form as large as yours, even hand tuning the JS might not be enough to get rid of that warning in IE. I have one form on a site I work on that always pops up that warning, and we sadly just have to tell users to ignore it. It's annoying, but it's acceptable to tell users to dismiss the warning in this particular case.


Blocks overlapping in front page I have a problem with one block in my website, recently I noticed that it gets overlapped by the others, not allowing to be seen correctly and to click the links in it, it's the partner block at the bottom right of this website: http://www.esnbologna.org/

Any hints on how to solve this problem?

The problem is that the <div> with id #views_slideshow_cycle_teaser_section_partners-block for the browser has an height of 0. Therefor, the most simple solution for you would be to set a static height for this element using CSS (i.e., the largest slide is currently 656px).

If you want the 'view all' link to be right below the slide that is shown to the user, in your situation I think the most easiest solution would be to alter the height of #views_slideshow_cycle_teaser_section_partners-block using JavaScript (i.e., jQuery).

For more information on this, see this post: Make absolute positioned div expand parent div height


Narrower zones in Omega I am trying to make the Header and Footer zones a little narrower than the Content Zone in Omega3 & Delta.  Here is an example of how it should look:

How can this be done with Omega3?

You cannot do this with Omega as its not part of the structure of the 960 grid system. Your best bet is to do it via CSS.

First you you would take the largest section, which would be the middle one. Say its 1000px, now the header and footer would also be 1000px. You would then modify the inner div in those regions to be 980px (10px on each side) to get the effect your looking for.


What Causes DatabaseTransactionOutOfOrderException and how do I fix this? I am working on plugin to Drupal Commerce, and I started getting this error:

DatabaseTransactionOutOfOrderException: in DatabaseConnection->rollback() (line 1058 of /Library/WebServer/Documents/includes/database/database.inc).

Can anyone shed some light on what this error means? If I install a fresh drupal and reinstall my plugin, is that likely to clear things up?

Any advice?

Thanks!

The DatabaseTransactionOutOfOrderException exception is part of the rollback() method (DatabaseConnection class) and it is thrown when a rollback() resulted in other active transactions being rolled-back instead of rollback to correct earlier savepoint.

You may debug it checking the backtrace when this exception is thrown.

In example defining the following hook:

/**
 * Implements hook_watchdog().
 */
function foo_watchdog($log_entry) {
  if ($log_entry['type'] == 'php' && $log_entry['severity'] <= WATCHDOG_WARNING) {
    // Old school
    // var_dump(debug_backtrace()); // Optionally add: exit();

    // Devel: Log the backtrace into temporary file: drupal_debug.txt
    // Locate via: $ drush eval "echo file_directory_temp() . '/drupal_debug.txt'"
    function_exists('dd') && dd(debug_backtrace());
  }
}

Don't forget to install Devel module (for dd) and clear the cache before testing it.

Then try to reproduce the problem and then check your /tmp/drupal_debug.txt debug file which should contain something like (section _drupal_exception_handler):

[function] => _drupal_exception_handler
[args] => Array
    (
        [0] => DatabaseTransactionOutOfOrderException Object
            (
                [file:protected] => /var/www/includes/database/database.inc
                [line:protected] => 1071
                [trace:Exception:private] => Array
                    (
                        [0] => Array
                            (
                                [file] => /var/www/includes/database/database.inc
                                [line] => 1933
                                [function] => rollback
                                [class] => DatabaseConnection
                            )
                        [1] => Array
                            (
                                [file] => /var/www/sites/all/modules/contrib/commerce/modules/order/includes/commerce_order.controller.inc
                                [line] => 123
                                [function] => rollback
                                [class] => DatabaseTransaction
                            )
                        [2] => Array
                            (
                                [file] => /var/www/sites/all/modules/contrib/commerce/modules/order/commerce_order.module
                                [line] => 734
                                [function] => save
                                [class] => CommerceOrderEntityController
                                [type] => ->

So based on the above example, you know that something goes wrong in commerce_order.module on line 734 during CommerceOrderEntity save.

If it's still not clear, other suggestion is to enable MySQL query logging and check the suspicious queries which are sent.


How to use the filter flag in drush config:status I am using Drush 10.3.6.
Drush config:status gives me:
# drush config:status
 --------------------------------- ------------
  Name                              State
 --------------------------------- ------------
  webform.settings                  Different
  webform.webform.contact           Only in DB
  webform.webform.example_webform   Only in DB
 --------------------------------- ------------

I am interested in filtering this to display only certain items, however the filter parameter does not work as expected:
# drush help config:status|grep Filter
  --filter[=FILTER] Filter output based on provided expression

# drush --filter='^webform\.webform\..*$' config:status
In OperatorFactory.php line 50:
  Could not parse expression ^webform\.webform\..*$

# drush --filter='webform.webform.*' config:status
In OperatorFactory.php line 50:
  Could not parse expression webform.webform.*

What is format of the expression that needs to be passed to the filter parameter?

If you look at the Consolidation\Filter\OperatorFactory class mentioned with the error, you'll see documentation at the top of the Class that outlines the acceptable syntax.
**
 * Convert a simple operator expression into an Operator.
 *
 * The supported operators include:
 *
 *      key=value           Equals
 *      key*=value          Contains value
 *      key~=#regex#        Regular expression match
 *
 * It is also possible to negate the result of an operator by
 * adding a logical-not operator either before the entire expression,
 * e.g. !key=value, or before the operator, e.g. key!=value.
 *
 */

Using the above documentation as a guide, the following all work for me - examples two and three should work for your example case.
// 1. Use the *Equals* option to show only the config entity with name "webform.webform.contact"
drush --filter="name=webform.webform.contact" config:status

// 2. Use the *Contains value* option to show any config entity with name containing "webform.webform"
drush --filter="name*=webform.webform" config:status

// 3. Use the *Regular expression match* option to show any config entity with name starting with "webform.webform."
drush --filter="name~=#^webform\.webform\.*#" config:status


Advanced sorting question about drupal views I have a content type with latitude and longitude coordinate fields. i have a view that is displayed on each page with this content type, and a google map plotting the location. Is there any way to sort a view using the distance between points?

distance=( ( current_page_lat - view_item_lat) + ( current_page_lng - view_item_lng ) )

You will need help of views_php module. This module will help to sort views rows with a calculation. You need to go through.

But in your case, The calculation has a value from current page. So you have to get the current page value (lang, lat) in sorting field, may be you can use it as a global variable or call a function from inside the php field.

Hope this helps you. :)


How to change $license->product_id? I've setup a Drupal Commerce site selling licensed roles per instructions on https://www.drupal.org/node/2039687 The same pages says:

  The customer receives the role referenced by the purchased license
  product. Changing $license->product_id (from "Basic Membership" to
  "Premium Membership", for instance) changes the owner's role.

However, it is unclear how to change the $license->product_id. Can anyone clarify can this be done in some kind of UI or rule, or if it should be done in custom module then which hook to use?

I'm not sure there is an easy answer to this right now. Product IDs are updated on licenses when a line item is created or updated. This happens in commerce_license_commerce_line_item_presave().

This gets complicated if you're using Commerce License Billing because your order renews according to your billing arrangement. If you are using that, then you'll need to review the code in there and figure out a way to save a new order that will be the one that gets renewed.

Otherwise, you could just create a new order, set the correct product, revoke the old license, and then complete the new order and then a user will have a new license and the old one will be gone.

If you have more questions, the issue queue is probably the best place to get help and provide feedback.


Drupal_render Profile 2 Forms The main Profile can be printed in a basic PHP page using:

print(drupal_render(drupal_get_form('user_register_form')));
print(drupal_render(drupal_get_form('user_login_block')));

but how can I specify a Profile 2 profile to be printed instead?

To print out the the profile2 profile Programmatically, you can do the following:

module_load_include('inc', 'profile2_page', 'profile2_page'); // Include profile2_page module
global $user; // Current user.
$profile2 = profile2_by_uid_load($user->uid, 'profile2_machine_name');
$entity_form = entity_ui_get_form('profile2', $profile2, 'edit'); // Or 'add'
print drupal_render($entity_form);

This should allow you to edit a Profile2 fields from the current logged in user. For registration I'm not sure how to print that other than redirect the user to the specific Registration Path from the Profile2 Registration Path, but for Logging in you can use the default form like in my question:

 print(drupal_render(drupal_get_form('user_login_block')));

P.S: Remember to clear you cache.


How to alter default value of select in webform Using drupal 7 and Webform (both up2date), how can I alter the default value of a "Select options" field?

I tried to do this:

function mymodul_webform_component_render_alter (&$element, &$component) {
if( $element['#type'] == 'select' &&
      $element['#title'] == 'field1' ) {
$element['#default_value'] = 'bar,foo';}
}

But it's not working...

I can make it work with a single default value if I set the field to "Listbox", what I don't want. But I still can bypass this "if" statement... But still can't set the default value to multiple choices

regards

For multiple selects use an array for the default value:

$element['#default_value'] = array('foo', 'bar');


Can't re-import a majority of products in CSV file I have been working on a development site for a long time, so there have been many instances where I have imported, deleted, re-imported, re-imported with tampering, etc. There seems to be a large chunk of products from the CSV file that keep getting skipped during the import, and I can't figure out where there is a record of them in Drupal that could cause them to be "flagged" as already imported.

One possible source of the problem may involve the CSV files. The client is exporting a CSV file of all products on a weekly basis from an incredibly old computer system. The filename is always the same, and I have set up the feed with the File Upload settings set to "Supply path to file or directory directly."

I've used the Commerce Reset module, cleared caches, rebuilt the feeds importers with different machine names - everything I could possibly think of - yet it skips several hundred products that I know I have imported before. Is there something I'm missing, possibly regarding GUIDs, UUIDs, product_id/entity id?

EDIT:

I should also have mentioned that I am using two feeds to import products - one to add the prices, and one for everything else (it's part of the client's DOS-based system, so no flexibility there). The current process involves running a feed to create the product (add the SKU, title, keywords), then running the price feed, which is set to update only.

Last night, I simply switched the settings on the price feed (add new products, overwrite existing, skip hash check, delete non-existing - the same as the other feed) and ran it. I was able to import all of the products. However, I decided to run the other feed to get the descriptions and keywords, and it would only update the products that it had last imported when it was set to create/overwrite/delete. What is happening here?

There is a bug report about Importing Large CSV document (downloaded and processed in the background).

Also, take a look at Feeds large CSV import.

So if your CSV files are too big, parhaps cutting them down into multiple smaller CSV's will likely fix your problem OR You could try using the Drush Feeds sandbox as mentioned in the first comment.


Pager on Widget Form Query The module is a small custom widget for the entity reference field. It creates a list of nodes that allows for multiple selections.

Is it possible to paginate the results of the query even though this is a widget for a field?

function outfit_builder_field_widget_form(&$form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) {

///...Additional Code Removed

$query = db_select('node', 'n');
$query->addTag('node_access');
$query->join('field_data_' . $instance['widget']['settings']['image_field_' . $type], 'fd', 'fd.entity_id = n.nid');
$query->fields('n', array('title', 'nid'));
$query->fields('fd', array($instance['widget']['settings']['image_field_' . $type] . '_fid'));
$query->condition('n.type', $type, '=');
$query->condition('fd.delta', 0, '=');
$query->condition('n.status', 1, '=');
$result = $query->extend('PagerDefault')->limit(21)->execute();
foreach ($result as $node) {
  $options[$node->nid] = theme('image_style', array(
      'style_name'  => $instance['widget']['settings']['image_style'],
      'path'        => file_load($node->{$instance['widget']['settings']['image_field_' . $type] . '_fid'})->uri,
      'title'       => check_plain($node->title),
    )
  );
}

$element += array(
'#type'             => 'checkboxes',
'#options'          => $options,
'#attributes'       => array(
  'class' => array('item'),
),

return $element;

}

I figured it out. After you extend your query:

$result = $query->extend('PagerDefault')->limit(21)->execute();

You'll need to also include the pager

// Attach the pager theme
$element['pager_pager'] = array('#theme' => 'pager',);


Node Access table goes empty I currently have a project where I am inserting mulitple records into Drupal using node_save. Its usually a couple of hundred at a time. For some reason, sometimes the node_access table ends up empty, resulting in the data "appearing" deleted to the users.

Does anyone know what could possible be happening?

I have reviewed the node_save code and notice is does run a call to rebuild the node_access table via node_access_acquire_grants($node). Currently I have no modules implementing node_access hooks.

My one thought was to just call node_access_rebuild() once I've finished inserting. I also run the process a few times every hour.

Side Note: Drupal may not be the right system for the bulk inserts and volume, but that is not the discussion I wish to have on this question.

The only moment where the node access table could be empty is when node_access_write_grants() (or node_access_rebuild()) deletes the content of the table before to repopulate it.
In the case of node_access_write_grants(), the table could become empty only if the table contained the access data for a node; in the case of node_access_rebuild(), the table becomes empty in any cases.

Sometimes the all entry can vanish, as node_access_acquire_grants() adds that entry only if no modules returned access records for the node passed as argument to the function, and node_access_rebuild() adds that entry if no module returned access records.

To notice also that, in the case the $realm passed to node_access_write_grants() doesn't match with the value contained in $grant['realm'] (for all the grants passed to the function), then node_access_write_grants() will delete the access records for the node passed as argument, but it will not save any access records.

// Only perform work when node_access modules are active.
if (count(module_implements('node_grants'))) {
  foreach ($grants as $grant) {
    if ($realm && $realm != $grant['realm']) {
      continue;
    }
    // Only write grants; denies are implicit.
    if ($grant['grant_view'] || $grant['grant_update'] || $grant['grant_delete']) {
      db_query("INSERT INTO {node_access} (nid, realm, gid, grant_view, grant_update, grant_delete) VALUES (%d, '%s', %d, %d, %d, %d)", $node->nid, $grant['realm'], $grant['gid'], $grant['grant_view'], $grant['grant_update'], $grant['grant_delete']);
    }
  }
}

The same can happen if a module calls node_access_write_grants() using the default value for $delete, and there aren't modules implementing hook_node_grants().
In these cases, the node access table can become empty if the table contained data only for the node passed as argument to node_access_write_grants().


How to override supersized.shutter.css I'm not the best in php manipulation that's why I'm asking.

function supersized_libraries_info() {
  $libraries['supersized'] = array(
    'title' => 'Supersized',
    'website' => 'http://www.buildinternet.com/project/supersized/',
    'download url' => 'https://github.com/f3ndot/supersized/tree/3718ae83f0945e327cc09530b959c5a8b049871f',
    'version arguments' => array(
      'file' => 'slideshow/js/supersized.3.2.8.min.js',
      'pattern' => '/Version : (\d+)/',
      'lines' => 4,
    ),
    'files' => array(
      'js' => array(
        'slideshow/js/jquery.easing.min.js',
        'slideshow/js/supersized.3.2.8.min.js',
        'slideshow/theme/supersized.shutter.min.js',
      ),
      'css' => array(
        'slideshow/theme/supersized.shutter.css',
        'slideshow/css/supersized.css',
      ),
    ),
  );
  return $libraries;
}

That's the all code of supersized_libraries_info() function. I wan't to hook that using hook system so for my theme it suppost to be
mytheme_supersized_libraries_info() right?

Then I wan't to just edit css location so that supersized.shutter.css will be in placed in my theme location.

(My code!)

function koko_supersized_libraries_info($variables) {
  $libraries['supersized'] = array(
    'files' => array(
        'css' => array(
        path_to_theme() + '/css/supersized.shutter.css',
        'slideshow/css/supersized.css',
      ),
    ),
  );

I just want to edit the css property of that object. I don't know how to get to there.
Mine edit just doesn't work at all (nothing happends).

I want to clear css array and then set mine values.

To alter the value returned from an implementation of hook_libraries_info(), a module or a theme needs to implement hook_libraries_info_alter(). As with other alter hooks, there isn't a way to override the value returned from a specific module, so the hook name is the usual one: modulename_library_info_alter() or themename_library_info_alter().

As side note, you code contains also an error: The parameter is $variables, but the code is using $libraries.


Is it possible to change how entity reference field is displayed? I have an entity that I has a taxonomy reference in it.  it currently looks like this

and I want this

Is this one of the options in display options array?  Or is it something different?  How do I change this?

This is my code

$fields['category'] = BaseFieldDefinition::create('entity_reference')
      ->setLabel(t('Category'))
      ->setDescription(t('Section this poll is to appear on'))
      ->setSetting('target_type', 'taxonomy_term')
      ->setTranslatable(TRUE)
            ->setDefaultValueCallback('Drupal\poll\Entity\Poll::getMain')
      ->setDisplayOptions('form', array(
        'type' => 'entity_reference_autocomplete',
        'weight' => -10,
        'settings' => array(
          'match_operator' => 'CONTAINS',
          'size' => '60',
          'autocomplete_type' => 'tags',
          'placeholder' => '',
        ),
      ))
      ->setDisplayConfigurable('form', TRUE)
            ->setRequired(FALSE);

You just need to set the cardinality of the field.

->setCardinality(BaseFieldDefinition::CARDINALITY_UNLIMITED)

Note that you need to re-install (to be safe, uninstall before making the change) or write an update function to convert the database structure if you make this change.


Security Review - Untrusted users are allowed to input dangerous HTML tags I am getting the following error in my security review:
Untrusted users are allowed to input dangerous HTML tags.

Is this because in my text formats I've got the following:
Plain text  All roles may use this format

Should I disable  anonymous users from being able to access plain text?

Also, it is saying:
It is recommended you remove the following tags from roles accessible by untrusted users.

img

Should I remove the img tag from authenticated users???? Does this mean that authenticated users will not be able to uploaded images to their site at all?

Plain text is just that, no html tags, so this shouldn't be a security issue.

Perhaps the img tag is considered dangerous because it is possible to use a specially crafted png or jpg to launch an attack against a users browser.


Module Dev: How to attach a button to a field? I would like to build a module whereby a user can enable a button per field, and when the user clicks on it, it gets the field contents and posts it to a service.

If there are any modules like this that would be great as well as an example.

This example comes close: Publishing to Facebook Wall. It shows how to post a facebook message when a node or comment form is submitted, and provide an option to opt-out on the node or comment form.


How do I need to configure my site on AWS with Elastic Load Balancing to force HTTPS everywhere? my site is up and running, but all my form submits get redirected to an http:// link. The redirect from http to https on my Server (Apache on EC2) is configured and you don't see any effect as a user. If i create baseurls directly on the server it also returns http:// links.

It causes troubles on the intern side:

Google Analytics can't track this redirects as the same user and sees every form submit as an new user from a direct source.
the redirect causes a delay for the user (mostly millisecs)

Config:

running an Drupal 8.7.7 on an Apache Server.
http-redirect:

    RewriteCond %{HTTP:X-Forwarded-Proto} !https
    RewriteCond %{HTTP_USER_AGENT} !ELB-HealthChecker
    RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

settings.php:

  $settings['reverse_proxy'] = TRUE;
  $settings['reverse_proxy_addresses'] = array($_SERVER['PROXY_ADDRESS']);

  $settings['reverse_proxy_trusted_headers'] = \Symfony\Component\HttpFoundation\Request::HEADER_X_FORWARDED_AWS_ELB;

This config for setting.php was introduced in 8.7.0:
https://www.drupal.org/node/3030558

I really don't have any clue what to do now, since i tried like thousands of possibilities.

Best Regards
FirstSanny

Got it myself.

Configuration is absolutly correct, but i set the wrong reverse_proxy_adresses to be allowed. I thought, that i can use the beanstalk-url, but it worked perfectly fine with one of the internal IP Configs for AWS: 172.16.0.0/12


URL encoding of en-dash I had a link:

www.example.com/issues/issue-week-2012–2013/poem1

But it is encoded as:

www.example.com/issues/issue-week-2012%25E2%2580%25932013/poem1

This is an URL alias, the en-dash (between "2012" and "2013") is encoded as %25E2%2580%2593, which shows a 404 error. But when I removed the "25" after each % in the URL manually it works.

Please tell me about the issue?

I think there may be a solution using a RewriteRule in .htaccess.

Imagine I have the url /some-page

Now if I go to /someTESTpage

and I put this in .htacess:

RewriteEngine on
RewriteRule ^(.*)TEST(.*)$ /$1-$2 [L,R=301]

Then it redirects to:

/some‒test

Problems still to solve:

1) In the redirect URL that is an en-dash so is still the wrong url. Not sure how to get it to insert the correct character.

2) When I put a percentage sign in the string to be replace the whole thing stops working. Not sure how to escape a percentage sign in a RewriteRule.


How do I get each taxonomy term associated to a node? I'm trying to add a preprocess hook to add classes based on taxonomy name to the body css of my drupal installation.  I've managed to get all the information about the node based on doing some searching around and trial and error, but I'd like to take it to the next step and get all the taxonomy terms based on the particular node id.

The code I am currently using is the following.

function custom_preprocess_html(&$variables) {
  // Add the node ID and node type to the body class.
  $body_classes = [];
  $nodeFields =\Drupal::service('current_route_match')->getParameter('node')->toArray();

  if (is_array($nodeFields) && count($nodeFields) > 0) {
    if (isset($nodeFields['nid'])) {
      $body_classes[] = 'node-' . $nodeFields['nid'][0]['value'];
    }
    if (isset($nodeFields['type'])) {
      $body_classes[] = $nodeFields['type'][0]['target_id'];
    }
  }

  $variables['attributes']['class'] = $body_classes;
}

It works fine and pulls down the information regarding the node. Based on the answer here it seems like all I should have to do is add the following line to get the taxonomy terms: $taxonomyTerms = $nodefields->get('field_yourfield')->referencedEntities(); but when I do so Drupal throws an error. I'll freely admit I'm new to Drupal 8, so any suggestions about where I'm going wrong (is field_yourfield not something that exists, maybe?) would be greatly appreciated.

Don’t convert the node to an array, use the node object itself. Then methods will work.

// top of file...
use Drupal\node\NodeInterface;

function custom_preprocess_html(&$variables) {
  $node = \Drupal::routeMatch()->getParameter('node');

  if ($node instanceof NodeInterface) {
    $type = $node->getType();
    $id = $node->id();
    $terms = $node->get('field_yourfield')->referencedEntities();
    // code here for $terms...

    $body_classes[] = 'node-' . $id;
    $body_classes[] = $type;
    // ... etc ...
  }
}

I assume type is node type.. but this is where you want to be. $terms should be a list of Term objects, so you can iterate and grab whatever data you need.

You should also check that the node type is the correct one before doing anything as well as checking for existence of the field to avoid errors.


How to add only the postal code field to the user registration page? I have a custom template file successfully rendering the user account creation page. I am using the Location Module, which adds a field (which appears to be a field group) to the user. I want to add only the postal code field (zip Code) to the user registration page.

template.php code:

    function responsive_bartik_theme() {
  $items = array();

  $items['user_login'] = array(
    'render element' => 'form',
    'path' => drupal_get_path('theme', 'responsive_bartik') . '/templates',
    'template' => 'user-login',
    'preprocess functions' => array(
       'responsive_bartik_preprocess_user_login'
    ),
  );
  $items['user_register_form'] = array(
    'render element' => 'form',
    'path' => drupal_get_path('theme', 'responsive_bartik') . '/templates',
    'template' => 'user-register-form',
    'preprocess functions' => array(
      'responsive_bartik_preprocess_user_register_form'
    ),
  );
  $items['user_pass'] = array(
    'render element' => 'form',
    'path' => drupal_get_path('theme', 'responsive_bartik') . '/templates',
    'template' => 'user-pass',
    'preprocess functions' => array(
      'responsive_bartik_preprocess_user_pass'
    ),
  );
  return $items;
}

user-register-form.tpl.php code:

<?php
     print render($form['account']['name']);
     print render($form['account']['mail']);
     print render($form['account']['pass']);
     print render($form['captcha']);
     print drupal_render($form['actions']);
     print render($form["form_build_id"]);
     print drupal_render($form['form_token']);
     print drupal_render($form['form_id']);
?>

   Forgot Password

Already have an account? Log in

Use this module Postal Code they can allow to only add postal code in user page

  A very minimal D7 Postal Code (ZIP Code) field with validation for one
  country or a combination of countries


db_insert() execute() without auto_increment primary key is returning 0 I'm trying to determine whether a database insert query was successful or not by checking the return value of execute(), but it seems to be returning 0 even though I can see the data has been inserted into the database. The table I'm adding data to has a primary key but it's not set to auto increment.

$result = db_insert('my_table')
                    ->fields(array(
                      'user_id' => $user_id,
                      'my_value' => $num,
                    ))
                    ->execute();
print_r($result); //Prints 0, even when successful

How can I check to see if the db_insert() was successful or not if I'm not using an auto increment primary key?

Many thanks

That makes sense - if you haven't got an auto-increment field on the table, then you already have the ID that you're inserting, so it would make no sense for an arbitrary column (or primary key, or whatever) value to be returned by PDO.

If the query fails it will throw an exception. That's the best (probably only) way to check that the insert was successful in your case, short of running a separate query.

try {
  db_insert('...')->execute();
  // No exception thrown; PDO thinks the record was inserted correctly.
}
catch (PDOException $e) {
  // Query failed; recover based on $e->getMessage()
}


How to render a block in a template? I installed the module "Shariff Social Media Buttons" for "Drupal 8" :

https://www.drupal.org/project/shariff

This module once installed, add a block in :

/admin/structure/block

I want to display this block in a template :

https://www.drupal.org/docs/8/modules/twig-tweak/rendering-blocks-with-twig-tweak

I tried with the following code :

{{ drupal_entity('block', shariffsharebuttons) }}

But the block does not work (it is not rendered on my page)

drush ev 'print_r(\Drupal::configFactory()->listAll("block.block."));'

you can use Twig Tweak Module, will gives you twig extension called drupal_blockand you can render your block like the following :

{{ drupal_block('shariff_block') }}

Take a look to the module Cheat sheet for more info.

Note : Shariff Module provide block with the id shariff_block not shariffsharebuttons.


Change html tag in template file tpl I have this template file for a view:

views-view--ir-news--page.tpl.php

But right now, I need to use Google AMP only for this view (Machine name: ir_news)
What I want to know is if something like this it's possible:

html-views-view--ir-news.tpl.php

Because I need to change, for this view the html tag from this  to this  only for this view.

Is this possible? Is that the way?
Thanks for the answers.

if you want to use AMP for specific pages, you might want to take a look at the AMP module.

But if you still want to add the amp attribut to the <HTML> tag manually, here's one way:

Overwrite the html.tpl.php template by copying the original tpl file (modules/system/html.tpl.php) to your current theme (sites/all/themes/your_theme/). Then add the following code at the top of the file:

$amp = '';
if (arg(0) == 'node' && is_numeric(arg(1))) {
    $nid = arg(1);
    $node = node_load($nid);
    $amp = $node->type == 'ir_news' ? 'amp' : '';
}

Then, you just print the $amp variable inside the <html> tag.

The amp attribute will only be added to your ir_news pages.


How to hide and/or prevent access to fields in a form,  such as group_audience for organic groups This has been troubleing me for a while.. When i try to hide fields like the group audience field, or the publishing setting from a form, on validation the form set both of these field to a null value, even though the defaut value as been correctly declared.

I tried to use Invisible, #access, unset hidden nothing work! This is very troubleing because for my current project users can edit only small bits of their profile at the time, for instance just the address or the picture, so if i hide group audience the user ends up kicked out of the groups he belongs at every edit.

I ended up using the code below to hide these field while still keeping the user in their group.

$variables['user_edit_about']['group_audience']= $temp['group_audience'];
$variables['user_edit_about']['group_audience']['#prefix'] = '
';
$variables['user_edit_about']['group_audience']['#suffix'] = '
';

Would anyone think of a better way to achieve this ?

Thanks

Edit:

Ok I figured it out.  Put this in your custom module:

function example_form_alter(&$form, &$form_state, $form_id) {
    if($form_id == 'story_node_form') {
        $form['title']['#value'] = 'hot stuff';
        $form['title']['#access'] = FALSE;

    }
}

This will set the title of the story node to 'hot stuff' and it will NOT be render on the page because #access = FALSE;

You can add more granularity control inside hook_form_alter()
like

  global $user;

  // Check to see if $user has does not have the administrator role.
  if (!in_array('administrator', array_values($user->roles))) {
    $form['title']['#access'] = FALSE;
  }

This works for Drupal 6 & 7.

Old Answer (ignore):

Its been awhile since I did something like this,  so I may have it wrong.
If you set the  [#value] of a form item,  it will not be visible on the form.

I did this in Drupal 6,  hook_form_alter() in a custom module.  I don't know if it will work in Drupal 7 and I don't know if you can do it in a preprocess function


Multiple values in creating a new field instance This is the code I actually have:

$instance = array(
    'field_name' => FIELD_PROJECT_TAGS,
    'entity_type' => 'node',
    'label' => $vocabulary->name,
    'bundle' => 'portfolio_project',
    'required' => true,
    'widget' => array(
        'type' => 'taxonomy_autocomplete',
        'behaviors' => array(
            'multiple values' => FIELD_CARDINALITY_UNLIMITED,
        ),
    ),
    'display' => array(
        'default' => array(
            'type' => 'taxonomy_term_reference_link',
            'weight' => 10,
        ),
        'teaser' => array(
            'type' => 'taxonomy_term_reference_link',
            'weight' => 10,
        ),
    )
);
field_create_instance($instance);

What's wrong with this? Why does the portfolio module allways install this field with allowing only one value?

Hope somebody can help. I'm bit frustrated.

Hopefully this will prove useful: To create a field that allows multiple values, you set the cardinality to -1 when using field_create_field.  Then all instances will allow multiple values (provided the widget supports that).

Example:

field_create_field([
  'cardinality' => -1,
  'field_name' => 'field_unlimited',
  'type' => 'special_content',
  'entity_types' => ['node'],
]);


Pathauto alias produces inconsistent aliases I have a content type with its own Pathauto pattern studios/[node:title]. What could be the reason that the alias of the node entitled "Studio A" is studios/studio, whereas for "Studio B" (for the same language) - studios/studio-b. The latter being the desired shape of course.
I tried to resave the node, I tried to bulk delete aliases and re-generate them - all to no avail.

Check settings in  Administration » Configuration » Search and metadata » URL aliases there is a Strings to Remove like this:

  a, an, as, at, before, but, by, for, from, is, in, into, like, of,
  off, on, onto, per, since, than, the, this, that, to, up, via, with

thats why your A is removed i think.


Setup CAPTCHA in Content Types i have configured captcha module in my drupal 7 site.. but can't understand how to show a captcha in content type, so that while adding content user will have to complete the captcha.

Please check README.txt of the captcha module.

  The configuration page is at admin/config/people/captcha,
  where you can configure the CAPTCHA
  module   and enable challenges for the desired forms.   You can also
  tweak the image CAPTCHA to your liking.

Go to the configuration page - admin/config/people/captcha
Select the Default challenge type - Math or Image
In the form list, you can define which form has CAPTCHA, for example
if you want to have it on the register form, select a challenge type
(Math or Image) for the FORM_ID user_register_form

If you want to add CAPTCHA to a content type, for example, blog, add a new FORM_ID "blog_node_form" and click "Save Configuration".

By default, you will not see CAPTCHA on each form when you logged in as administrator, but you can change the option in the configuration page.


What URL do I use to view an OG membership entity? I see one can edit a membership entity by going to:

group/node/204/admin/people/edit-membership/32

What is the URL to view the entity?

I see the membership entity has a display mode that allows you to rearrange the fields but there is no view link in the OG membership (people) admin area.

I don't think that there is a page you can view the membership. I've just skimmed the code of OG module and didn't found any relating part which displays a membership in a separate page.

However, since memberships are entities, it should be possible that you can setup a view which takes a membership id as contextual filter and display it in a selected view mode.

Here is how you do that with views:

Create a new view visiting admin/structure/views/add

Give your view a name like View Membership
Set it to Show OG Membership
Set a Path with a placeholder like view-membership/%
Display format Unformatted list of Rendered entity
Items to display 1, uncheck Use a pager
Continue & Edit

Under Advanced section, add a contextual filter OG membership: Og membership ID

WHEN THE FILTER VALUE IS NOT IN THE URL: Show "Page not found"

Save
Visit the page view-membership/<membership_id> and you'll see the membership entity.


Set a value from one text field from one content type to another text field in another content type using set data value in rules I have two content types A and B and I have two rules. I am trying to add the text put in the A text field of content type A into the B text field of content type B.

On rule two I am using the set data value but it is not working. Have I missed anything or have I setup my rule incorrectly? If anybody can point out where I went wrong it would be much appreciated.

Rule 1 creates a node from content type B when a node is created with content type A.

Export of Rule 1:

{ "rules_ref" : {
    "LABEL" : "Ref",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "node_insert--a" : { "bundle" : "a" } },
    "DO" : [
      { "entity_create" : {
         "USING" : {
            "type" : "node",
             "param_type" : "b",
             "param_title" : [ "node:type" ],
             "param_author" : [ "node:author" ]
          },
         "PROVIDE" : { "entity_created" : { "entity_created" : "Created entity" } }
       }
     }
    ]
} }

Rule2  takes the value from  A text  field in the A content type and adds it to the B text field in the B content Type.

Export of Rule 2:

{ "rules_ref2" : {
  "LABEL" : "Ref2",
  "PLUGIN" : "reaction rule",
  "OWNER" : "rules",
  "REQUIRES" : [ "rules" ],
  "ON" : { "node_insert--b" : { "bundle" : "b" } },
  "IF" : [
    { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_a_text" } },
    { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_b_text" } }
    ],
  "DO" : [
     { "data_set" : { "data" : [ "node:field-b-text" ], "value" : "[node:field-a-text]" } }
   ]
} }

Here is example

Content type Article: field_product - Product reference
Content type Basic page: field_product2 - Product reference

Article creation triggers next actions:

{ "rules_on_article_create" : {
    "LABEL" : "On Article create",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "node_insert--article" : { "bundle" : "article" } },
    "DO" : [
      { "entity_create" : {
          "USING" : {
            "type" : "node",
            "param_type" : "page",
            "param_title" : [ "node:title" ],
            "param_author" : [ "node:author" ]
          },
          "PROVIDE" : { "entity_created" : { "entity_created" : "Created entity" } }
        }
      },
      { "data_set" : {
          "data" : [ "entity-created:field-product2" ],
          "value" : [ "node:field-product" ]
        }
      }
    ]
  }
}

I think you r trying to operate with non existing object. When you r creating node of type B there is no link to any another node in rules.


How I can add an optional parameter in REST API URL How I can add an optional parameter in drupal 8 REST API URL

"canonical" = "/content/get/{id}"

But I have to add value for id here, How I can make this id optional

I experienced the same issue and solved it by adding the current request from the request stack to my resource:

RestBase.php

<?php

namespace Drupal\api\Plugin\rest;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Psr\Log\LoggerInterface;
use Drupal\Core\Session\AccountProxyInterface;
use Drupal\rest\Plugin\ResourceBase;
use Drupal\rest\ResourceResponse;

class RestBase extends ResourceBase {

  /**
   *
   * @var \Drupal\Core\Session\AccountProxyInterface
   */
  protected $currentUser;
  /**
   *
   * @var \Symfony\Component\HttpFoundation\Request
   */
  protected $currentRequest;

  /**
   *
   * @param array $configuration
   * @param type $pluginId
   * @param type $pluginDefinition
   * @param array $serializerFormats
   * @param \Drupal\api\Plugin\rest\resource\LoggerInterface $logger
   * @param \Drupal\api\Plugin\rest\resource\AccountProxyInterface $currentUser
   */
  public function __construct(array $configuration, $pluginId, $pluginDefinition, array $serializerFormats, LoggerInterface $logger, AccountProxyInterface $currentUser, Request $currentRequest) {
    parent::__construct($configuration, $pluginId, $pluginDefinition, $serializerFormats, $logger);

    $this->currentUser = $currentUser;
    $this->currentRequest = $currentRequest;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $pluginId, $pluginDefinition) {
    return new static(
        $configuration,
        $pluginId,
        $pluginDefinition,
        $container->getParameter('serializer.formats'),
        $container->get('logger.factory')->get('rest'),
        $container->get('current_user'),
        $container->get('request_stack')->getCurrentRequest()
    );
  }

  /**
   *
   * @param array $message
   * @param integer $cache
   * @return ResourceResponse
   */
  protected function getResponse($message, $cache = 0) {
    $build = [
      '#cache' => [
        'max-age' => $cache,
      ]
    ];

    $response = new ResourceResponse($message);
    $response->addCacheableDependency($build);

    return $response;
  }

}

TestResource.php (the actual REST resouce)

<?php

namespace Drupal\api\Plugin\rest\resource;

use Drupal\rest\ResourceResponse;
use Drupal\api\Plugin\rest\RestBase;

/**
 * Test resource.
 *
 * @RestResource(
 *   id = "test_resource",
 *   label = @Translation("Test API Resource"),
 *   uri_paths = {
 *     "canonical" = "/api/test-resource"
 *   }
 * )
 */
class TestResource extends RestBase {

  /**
   *
   * @return ResourceResponse
   */
  public function get() {
    if (!$this->currentUser->hasPermission('use ' . $this->pluginId . ' service')) {
      throw new AccessDeniedHttpException('Access denied.');
    }

    $id = $this->currentRequest->get('id');

    $message = [
      'message' => 'Hello, you called service: ' . $this->pluginId,
      'id' => $id,
    ];

    return parent::getResponse($message);
  }

}

In my own base class RestBase I added the current request from the request stack (besides the AccountProxy for permission purposes) by overriding the create method of the ResourceBase class. You can then access query parameters in your REST resource by calling the get($key) method on the request object.

You will need to pass your parameters in the API URI like so: http://localhost/api/test-resource?_format=<your-format>&<parameter1>=<value1>. Considering this example API URI you would access parameter1 via $value1 = $this->currentRequest->get('parameter1').

I guess that it is not possible to have slugs in your resources at the moment. If someone knows how please do tell :).


How know what theme/theme name a Drupal site is using? Like in Wordpress, we can know what theme name a site is using by look at the page source and it will show something like

wp-content/theme/theme-name

Well, how we can know what theme a Drupal site is using? I try to look at the page source of a Drupal site but i cannot figure out what theme or theme name the site is using.

Is there any trick to unlock this?

You can get it from source of any page. Have a look for the javascript array at the top/bottom of the page that begins with:

jQuery.extend(Drupal.settings, {...

There's a setting in that array called "theme" which contains the name of the theme being used for that page.


Action on every nth node creation I have a content type of event. I need to send all users an email after each 5th events saved, listing this 5 recently created events. What would be the most proper way to do that? I am tending to use hook_node_insert but I'm not sure how to check if it is the 5th node after the last email sent.

You could run an EntityFieldQuery on hook_node_insert to count all of the nodes of type event and then see if that count plus one (because the new node isn't saved to the DB yet) is divisible by five. Something like this:

function mymodule_node_insert() {
  $query = new EntityFieldQuery();
  $result = $query->entityCondition('entity_type', 'node')
    ->entityCondition('bundle', 'event')
    ->execute();
  $count = (count($result['node']) + 1);
  if (!($count % 5)) {
    // Generate/Send your email
  }
}

Note that the code above is totally untested.


How to run custom code on rollback? I have write a migration class to enter the value in custom table. But I want to know that how to rollback custom table entry.

I used :

public function complete($entity, stdClass $row) {
  // db_insert in my custom table
}

I want to rollback the above changes. For this I tried the completeRollback method below but it is not working.

public function completeRollback($entity_id) {
  dsm($entity_id);
}

You want to use prepareRollback() because at that point the thing that you are rolling back has not been removed yet.

public function prepareRollback($entity_id) {
  parent::prepareRollback();
  // Code to execute before an entity has been rolled back
}

Take a look at this guide for more info.


How to add more condition to my conditional field im trying to add condition to my fields but it seems it can only accept 1 condition.

example : i have 1 select field for salutation(Mr., Ms., Mrs, Dr., etc) and 1 radio field for gender. if i select Mr. on the select field, the radio will automatically check Male button and other wise. if i select like Dr., Prof. or etc, the radio button will uncheck both button.

You can use jquery to check and uncheck the field

$('#myCheckbox').attr('checked', true); // Checks it

$('#myCheckbox').attr('checked', false); // Unchecks it


Getting Drupal to work with Mercury Mail Server on Local Machine I've successfully set up Mercury Mail Server on my local machine using the XAMPP stack to send mail through a remote SMTP Server by following the configuration directions posted at:
https://www.zoe.vc/2008/mercury-mail-transport-system-fur-externe-mail-konfigurieren/
If mail is sent to either local or external email addresses via a regular mail client, e.g. Thunderbird, Mercury Mail processes the mail appropriately and the mail arrives in the expected mail boxes.

However, sending mail through my local Drupal 7 site does not work.

For example, the site includes a set of rules built with the Rules module that are configured to send mail to a set of email address when triggered.
Drupal reports that it successfully sends mail to the targeted addresses when the rules are fired.
But Mercury Mail doesn't show any evidence that the mail is being processed -- and the mail never shows up in at the addressed mailboxes.

In summary, mail from Drupal is not getting to the server, but Drupal thinks that it has been successfully sent.  Note, as per the directions from zoe.vc, the [mail function] configuration in php.ini is setup as:

[mail function]
; XAMPP: Comment out this if you want to work with an SMTP Server like Mercury
SMTP = localhost
smtp_port = 25

; For Win32 only.
; http://php.net/sendmail-from
sendmail_from = postmaster@localhost.com

; XAMPP IMPORTANT NOTE (1): If XAMPP is installed in a base directory with spaces (e.g. c:\program filesC:\xampp) fakemail and mailtodisk do not work correctly.
; XAMPP IMPORTANT NOTE (2): In this case please copy the sendmail or mailtodisk folder in your root folder (e.g. C:\sendmail) and use this for sendmail_path.

; XAMPP: Comment out this if you want to work with fakemail for forwarding to your mailbox (sendmail.exe in the sendmail folder)
;sendmail_path = "\"C:\xampp\sendmail\sendmail.exe\" -t"

; XAMPP: Comment out this if you want to work with mailToDisk, It writes all mails in the C:\xampp\mailoutput folder
sendmail_path = "C:\xampp\mailtodisk\mailtodisk.exe"

; Force the addition of the specified parameters to be passed as extra parameters
; to the sendmail binary. These parameters will always replace the value of
; the 5th parameter to mail(), even in safe mode.
;mail.force_extra_parameters =

; Add X-PHP-Originating-Script: that will include uid of the script followed by the filename
mail.add_x_header = Off

; Log all mail() calls including the full path of the script, line #, to address and headers
;mail.log = "C:\xampp\php\logs\php_mail.log"

I've spent countless hours trying to figure this one out.  Any help getting this to work via   drupal so that I can continue development will be greatly appreciated. Thanks in advance.

When I used to test sending mail from a localhost (I don't remember the mail server program though), I used to use the SMTP Authentication Support module for its configuration.

  This module allows Drupal to bypass the PHP mail() function and send email directly to an SMTP server. The module supports SMTP authentication and can even connect to servers using SSL if supported by PHP.


Which database schema should I use? I want to create a custom voting module to learn how to write a module. The vote table will contain four fields (id, title, vote_up, vote_down).
Should I create a new table? If I create a new database table, how do I keep the relationship with the node being voted?

If you want to create a voting module you should look into Voting API, it's an API module that offers common functions and database storage for voting modules to use.

However, since this is a learning excercise, you might want to do it all yourself, in this case:

Use hook_schema() to define your database schema (the example on the documentation page is pretty self-explanatory!)
In Drupal 6 you need to manually specify which schema to install so implement hook_install() and hook_uninstall():

function mymodule_install() {
  drupal_install_schema('mymodule');
}

function mymodule_uninstall() {
  drupal_uninstall_schema('mymodule');
}

An example of a hook_schema might look like this:

/**
 * Implementation of hook_schema()
 */
  function mymodule_schema() {
    $schema['mymodule_votes'] = array(
      'description' => 'Your schema',
      'fields' => array(
        'vid' => array(
          'description' => 'vote id',
          'type'        => 'serial',
          'unsigned'    => TRUE,
          'not null'    => TRUE,
        ),
        'nid' => array(
          'description' => 'node id',
          'type'        => 'int',
          'unsigned'    => TRUE,
          'not null'    => TRUE,
        ),
        'vote_up' => array(
          'description' => 'number of votes up',
          'type'        => 'int',
          'unsigned'    => TRUE,
          'not null'    => TRUE,
          'default'     => 0
        ),
        'vote_down' => array(
          'description' => 'number of votes down',
          'type'        => 'int',
          'unsigned'    => TRUE,
          'not null'    => TRUE,
          'default'     => 0
        ),
      ),
      'primary key'     => array('vid'),
      'indexes'         => array('node id' => array('nid'))
    );
    return $schema;
  }


Views block in custom region rendered outside of page.tpl I have custom regions rendered inside of the node.tpl.php file which work as expected, but results in a php error when blocks created by the views module is placed in them.

 [:error] [pid 2563] [client 127.0.0.1:35606] PHP Fatal error:  Maximum execution time of 30 seconds exceeded in /filepath/sites/all/modules/devel_themer/devel_themer.module on line 333

Other blocks all work fine the regions and the views blocks work fine in all regions called by page.tpl.php. The error only occurs when the two are put together. There are no other log messages and the page just returns a blank screen so I'm not quite sure what the problem is or how to go about fixing it. I'm using the code below in template.php to make the region available outside of page.tpl.php

function smark_design_theme_preprocess(&$variables) {
  if (block_get_blocks_by_region('region_name')) {
    $variables['region_name'] = block_get_blocks_by_region('region_name');
  } else { $variables['region_name'] = FALSE; }
}

And this to call the region in node.tpl.php

<?php if ($page): ?>
  <?php if ($region_name): ?>
    <div id="region-name">
      <?php print render($region_name); ?>
    </div>
  <?php endif; ?>
<?php endif; ?>

Searh your php.ini and change the value of max_execution_time to:

max_execution_time = 300

By default php.ini have 30 seconds and PHP needs more time to process it, in this case you have 300 seconds.

EDIT: As you say in your comment that your problem persist, you can use the following solution, but you need know that your site can take a lot of time to process your request.

Edit the file YOUR_SITE/sites/default/settings.php and add this in the second line and save the file:

set_time_limit(0);

Read more about this function at php.net


Change entity reference field widget type based on role? EDIT: See the original post below for context. I think I've figured out how to target the field's widget, and to do this based on the admin role, but the module doesn't seem to be recognizing the widget type for some reason. The reason I say this is that when the module is enabled, the targeted field disappears in the node edit form. I figure this means it's getting targeted correctly, but can't define how to display itself. I think this might be because the autocomplete widget is defined by the Entity Reference module itself, and not by Core. Do I have to tell the module where to find this widget type? Or is there another reason that this might be happening?

<?php

//Assign role that will be affected by the module
if(user_access('administer')) {
  function entityreference_widget_field_widget_properties_alter(&$widget, $context) {
    // Change entityreference widget
    $field = $context['field'];
    if ($context['entity_type'] == 'node' && $field['field_name'] == 'field_review_band') {
      $widget['type'] = 'entityreference_autocomplete';
    }
  }
}

ORIGINAL POST: I have an entity reference field that I'm using in a "Review" content type. When users create a "Review", they are given options for this field in a select list based on Bands (another content type) that they have created. If a submitted review needs to be moderated, then an admin must go in and edit the "Review". When the review is edited by an admin, I need the band field to stay the same as it was when originally submitted. However, because of the nature of the how the options for the field are populated, the only options that appear when editing as an admin are "Bands" created by the admin user.

There is a second widget type that can be chosen for the entity reference field, which is autocomplete. Is there a way that I can change the widget type from "select list" to "autocomplete" only when the content is being edited by an administrator? This way, users still have the select list for their bands, and administrators are not limited to only their bands. Otherwise, is there a way to that I can leave this specific field unaltered when editing the content?

I ended up getting this to work after finding hook_field_widget_properties_alter. This allows you to, as the hook implies, target the various properties of the widget directly. Global $user seems to provide the $user variable, which allows you to select the role that you want to apply the module to. You can change it from 'administrator' to 'authenticated user', 'anonymous user', or any other needed role to fit your needs.

<?php
function entityreference_widget_field_widget_properties_alter(&$widget, $context) {
  //Assign role that will be affected by the module
  global $user;

  if (in_array('administrator', $user->roles)) {
    // Change entityreference widget
    $field = $context['field'];
    if ($context['entity_type'] == 'node' && $field['field_name'] == 'field_review_band') {
      $widget['type'] = 'entityreference_autocomplete';
      $widget['module'] = 'entityreference';
      $widget['settings']['match_operator'] = 'CONTAINS';
      $widget['settings']['size'] = '60';
    }
  }
}

To find out exactly which pieces of the widget needed to be altered, and what to, I created another test field of the type that I wanted to alter my current field to. I then inserted dsm($widget) within the hooks curly brackets of the hook, and then inspected the page with the field on it.

Explanation of dsm() and dpm() for anybody who needs it:

There's so little help anywhere on how to use dsm() or dpm(), and working through this module finally made me understand it. Basically, modules target different elements, and in order to figure out what to target, or what you will be altering, you need to inspect the elements. What dsm() lets you do is view the properties of any given variable (e.g. $form_id most commonly it seems, or in this case $widget or $context) in each of the elements on the page that include it. If anybody stumbles on this and still needs clarification, feel free to ask. It took me forever to figure out how the heck to use dsm().


How to create a google map block to display number of nodes for a content type I have a content type "Houses".

I added 3 nodes as follows.

Node 1 for county X and state A
Node 2 for county X and state A
Node 3 for county Y and state B.

I like to create a google map block which will show 2 in County X in google map and 1 in County Y section in google map.

Below is an example

Google doc

Update 1

https://docs.google.com/document/d/1q9uLBQpWY_a3du6HbWH3s0Gz2k_F4gJDYQDpeX9mcaw/edit?usp=sharing

Use Geofield_map module:

  Geofield Map is an advanced, complete and easy-to-use Geo Mapping
  solution for Drupal 8, based on and fully compatible with the Geofield
  module, that lets you manage the Geofield with an interactive Map both
  in back-end and in the front-end.

  It represents the perfect solution to:

  geolocate (with one or more Locations / Geofields) any fieldable
  Drupal entity throughout an Interactive Geofield Map widget; render
  each Content's Locations throughout a fully customizable Interactive
  Geofield Map Formatter; expose and query Contents throughout fully
  customizable Map Views Integration; implement advanced front-end
  Google Maps with Marker Icon & Infowindow advanced customizations,
  custom Google Map Styles and Marker Clustering capabilities; customize
  Map Geometries properties (Lines & Polylines, Polygons, Multipolygons,
  etc.), based on Google Maps Polygons APIs;

Take a look at Demo.

So, in summary, you need to install this module and add it to your content type.
then with creating a custom view, you can achieve what you want.


How do I filter entity reference fields based on language? In a Drupal 8 site I have a node content type "page" that references a custom entity type using inline entity form. "Page" also has a paragraphs field usig the Paragraphs module.

The site have multiple languages and therefore the following scenario appears:

I have an existing "page" node in both english and german containing entity references and paragraphs.
On the english node I add a new paragraph and a new entity reference and save the node.
When viewing the node in english I see the  added content.
When viewing the node in german I also see the new content, which is in english.

I don't want number 4 to happen. That is, I don't want the new untranslated entity and paragraph to be visible on the german translation of the node. The entity reference and paragraph fields are not set as translatable but the target entities are translatable. From what I understand, this means that the newly created entity will be in english, the same is true for the paragraph.

To solve this I'm thinking I should be able to filter out the untranslated entities and paragraph items when viewing the node so that any item that is not in the current language is not shown. The they won't be visible until I go and edit the german node and resave it, which will create translated versions of the entity and paragraph item.

But I am unsure how to go about filtering the fields. Is there any suitable hook that can be used? Or am I going about this in the wrong way?

The logic that defines if entities should be shown is in \Drupal\Core\Field\Plugin\Field\FieldFormatter\EntityReferenceFormatterBase::getEntitiesToView()

As you can see, translation is checked there, but the API doesn't directly support skipping something, the hooks behind that only allow to control applicable fallback languages and their order.

It's possible that you can use entity access, which is checked after that. Implement hook_paragraph_access(), for the view operation, check if the paragraph has a translation in the current content language and if not, forbid access. The same should work for your other entity reference, it's the same could, just implement hook_ENTITY_TYPE_access() for that too.

If that doesn't work, you can write your own field formatter plugin and override that method.


Why isn't my feature overridden after I change a rule in it? I've exported a feature that contains a rule —

// my_feature.info
features[rules_config][] = rules_my_rule

// my_feature.rules_defaults.inc
$items['rules_my_rule'] = entity_import('rules_config', '{ "rules_my_rule" : {
   ...
  }');

When I modify the rule with Rules UI, I'd expect the feature to be marked as overridden, but it's not. I've tried disabling a rule and editing a rule's conditions. Neither change affects the feature's status (Default).

I've tried clearing all caches (drush cc all) and reinstalling the feature (drush dre my_feature).

Am I missing some step needed to make features detect changes to rules?

Edit: If I update the feature (even though it doesn't say "overridden"), the changes to get written to my_feature.rules_defaults.inc. But reverting the feature  (even with drush fr --force) has no effect.

Rules UI shows the rule as "overridden". If I click "revert" on that page, the rule reverts to the state saved in my_feature.rules_defaults.inc.


How to filter content by taxonomy term? I'm using Drupal 7 and trying to filter my content based on taxonomy, but it looks like I can only filter based on status and type. Is there a setting or module that would offer more options to filter content by?

Thanks!

It is easy to expose taxonomy term as filter in views. Unfortunately, in Drupal 7, the content list is not built by views.

Administration Views is a module which can replace it with the views Administration: Nodes.

In the views, you can add Content: Has taxonomy term filter and expose it. But it only support ONE vocabulary.

How about having a term filter on more then vocabulary? It is quite tricky, but not impossible.

First, add a relationship Content: Taxonomy terms on node, and check the vocabularies. In example, they are tags and topics.

Then, now you can add filter Taxonomy term: Name, this filter only appear when you added the taxonomy term as relationship.

In Operator, there are many options, you can pick a suitable one for your case. I chose Contains in my example.

  Note:

  With this method, you will have a ordinary text field rather then autocomplete field. It is the only downside.


How to load terms in alphabetical order or in the same order they are in CMS? I am loading terms programmatically but I am hoping to load them in the same order as they show in the CMS (weight). If not that, I just want them to load in alphabetical order.

This is what I am doing:

$vocabulary = taxonomy_vocabulary_machine_name_load($name);
$terms = entity_load('taxonomy_term', FALSE, array('vid' => $vocabulary->vid));

Any idea how to achieve that?

For getting all child terms in a vocabulary try the following code.

$cc=array();
$tax=taxonomy_vocabulary_machine_name_load($name);
$vid= $tax->vid;
$child_terms = taxonomy_get_tree($vid);
foreach($child_terms as $values) {
  $tname=$values->name;
  $cc[] = $tname;
}

The above code will give you child terms of that vocabulary in array $cc. For sorting in alphabetical order use asort($cc);

Hope this will help you.


Build and update a form based on another form On the checkout page, I wish to load a form on a modal whose data depends on the uc_addresses select address drop-down.

I have declared a form through hook_form and add the form to the checkout page through mymodule_form_uc_cart_checkout_form_alter:

  $form['panes']['delivery']['modal'] = drupal_get_form('form_id');

My question is: how will I rebuild the form when a different drop-down option is selected? Note that I have tried to add a parameter in hook_form:drupal_get_form('form_id', 'address_id') my problem is the form rebuild when the option is changed.

You could possibly use the #states API to react upon another option in the dropdown is selected, this will work without submits on the client side.

If you want to change your form after submission has happened only you'd have to add conditions in your custom form function that will change your form dynamically according to what is contained in the $form_state['values'] of that dropdown field.


Text inside Search box How could I add a default text inside drupal's search box? I have done this with jquery but I need the text to be translated.

I know this can be done with the Custom Search module but it is a little overkill to add a module for such a small feature. Hopefully this can be achieved using my theme's preprocess function. Any ideas on how this can be done?

Use Drupal to communicate a translated string to Javascript:

drupal_add_js(array('my_string' => t('Default Text')), 'setting');

Then, have your jQuery read the value:

var str = Drupal.settings.my_string;


Complex View Contextual Filter with User Relationships — how would I achieve this? As I mentioned in the question I raised earlier this week, I'm using User Relationships to create unidirectional friendships between users on my site.

The friending paradigm is like Twitter, where Alice may follow Bob and that does not imply that Bob also follows Alice. That said, Bob is able subsequently to choose to follow Alice.

Looking in the database table user_relationships, I can see that this situation results in two rows for a reciprocated relationship:

mysql> select * from user_relationships where requester_id in (187767, 190348)
  and requestee_id in (187767, 190348);

+--------+--------------+--------------+------+----------+------------+------------+-------+
| rid    | requester_id | requestee_id | rtid | approved | created    | changed    | flags |
+--------+--------------+--------------+------+----------+------------+------------+-------+
| 200726 |       187767 |       190348 |    1 |        1 | 1331657565 | 1331657565 |     0 |
| 200723 |       190348 |       187767 |    1 |        1 | 1331656437 | 1331656437 |     0 |
+--------+--------------+--------------+------+----------+------------+------------+-------+
2 rows in set (0.00 sec)

For ease of discussion here, let's talk about a specific View — that of "users who follow you but you don't follow back". For these users, there will be a row in user_relationship with requestee_id being $current_user‑>uid, let's say this has a requester_id of $follower‑>uid. There will be no row, however where $current_user‑>uid is the requester_id and $follower‑>uid is the requestee_id (which would indicate that the current user had reciprocated by following back). So if we're looking at the output above, it would be the situation where only the first row (rid = 200726) exists, from the perspective of user 190348.

This is slightly easier to explain with a Venn diagram that I've hastily knocked-up:

; my View here is of the area labelled C.

Now in my View (of which there is a now out-of-date screenshot), I have two Contextual Filters:

"User relationships: Requester user", bound to the "requester" Relationship and set to Exclude; and
"User relationships: Requestee user", bound to the "requestee" Relationship, not set to Exclude.

So far so good. Except this shows me all users who follow $current_user, not just the ones that $current_user does not also follow back — B ∪ C. If I want to show only the users in C, then I also need to check that no reverse row exists. If I go to add a new Contextual Filter, I don't have any option to check something like this (as it is not a property of the individual row I'm showing).

So how do I achieve this? I guess I'm going to have to write some PHP to prevent displaying users where this is the case and there are custom modules in my site already, but I don't understand Drupal well enough to know what hook I'm looking for or where to intercept the processing of the rows being displayed.

Help, please?  :o)

Fixed it.

Last night I noticed that I have the ability to add PHP Filter Criteria (which I'd somehow not noticed before!), coming from the Views PHP Module. It turns out that this allows me to enter arbitrary PHP and it will take anything that returns TRUE as meaning the row should be removed from the resultset.

So I added a Filter Criterion that checks the SQL query Select * From user_relationships Where requester_id = :current_uid And requestee_id = :follower_uid and I return TRUE; if that query results in more than zero rows.

To do this, I needed to add new Fields, both set to be "Excluded from display":

User: User ID (bound to Requester), with an administrative title of "Follower UID (not displayed)". This gets passed as the variable $row->uid
User: User ID (bound to Requestee), with an administrative title of "Current UID (not displayed)". This gets passed as the variable $row->uid_1

Then in a new PHP Filter Criterion, I created a filter as follows:

$filter_result = db_query('Select * From user_relationships '.
  'Where requester_id = :current_uid And requestee_id = :follower_uid',
    array(
        ':current_uid' => $row->uid_1,
        ':follower_uid' => $row->uid,
    ));

$count = $filter_result->rowCount();

return $count > 0;

Then those superfluous rows no longer appear in my output.

For some reason, I do need to assign $filter_result->rowCount() to the variable $count; trying return $filter_result->rowCount() > 0; directly didn't want to work for some reason.

But problem solved. At last  :o)

Edit: I've just corrected the Field bindings, having noticed I was doing it differently in two different places and  I'd put the wrong one in my answer here. Note that the User Relationships fields "UR: Requester user ID" and "UR: Requestee user ID" do not output user IDs, so do not work in this query; you do have to use two different "User: User ID" Fields, one bound to each end of the relationship. (Irritatingly, this means they have the really unhelpful variable names of $row->uid and $row->uid_1 when passed to the PHP Field; I haven't yet found a way around this.)


How to output every second grouping in views? I have a view that outputs a list of nodes and their taxonomy terms. I use taxonomy field as grouping field. So I get:

Tax1 (article1, article2, article3 )
Tax2 (article4, article5, article6 )
Tax3 (article7, article8, article9 )

etc.

View makes markup for each group like this:

Question:

How is it possible to output every second grouping?

I would like to have 2 columns with 2 views, first view would output every second grouping and second view would show other groupings.

I'm using Views 3.

This seems like a good use-case for a theme override.

If you click the "advanced" section in the view and click "Theme Information" at the bottom, you'll get a list of theme names. Click on "Style output" and copy the code, and paste it into a file in your theme folder with the most specific name possible (at the end of the list starting with "views-view-unformatted.tpl.php").

Not sure if there's a more elegant way to get a row count (it doesn't seem to be an available tpl variable) but you can DIY like so:

  <?php function count_this_view() {
    static $count = 0;
    return $count++;
  }?>

Then wrap your tpl in a conditional like

  <php if (count_this_view() % 2) :?>


Saving existing node doesn't update automatic alias I have a node with pattern /route/[node:title]. Whenever I save a new node with automatic alias checked it saves perfectly.

Whenever I edit an existing node with Generate automatic alias checked it doesn't update the URL to the new title but instead keeps the old one. When I go back to editing I see that Generate automatic alias is unchecked all of a sudden and an alias is in place(The old title).

I'm using Pathauto and Pathauto persist but can't seem to find the problem, even when disabling and uninstalling Pathauto persist.

Have you checked your settings at "admin/config/search/path/settings"?
There you can config what to do with your alias, when an entity is updated.


Add Last changed date to search results I'm trying to override the search--results.html.twig file.

And it says i can use info_split.date to render the dates.

But when I try

{% if info_split.date %}
  {{ info_split.date }}
{% endif %}

It does nothing, and kint says it's an empty array.

If someone is facing exactly same issue, Here is what i did.

In my .theme file I've preprocessed search results like this

function YOURTHEME_preprocess_search_result(&$variables){
  $result = $variables['result'];
  $info = array();
  if($result['node']){
    $info['date'] = format_date($result['node']->getChangedTime(),'short');
  }

$variables['info_split'] = $info;
  $variables['info']['#context'] = array(
    'info' => $info,
  );
}

After this the date will be available in info_split.date variable and it will be automatically rendered as in the twig file all the info is rendered you can optionally render o hide some parts of the search listing.


New API version for every release? Since my company still focuses on D7, I haven't yet had time nor need to use Drupal 8. I am planing to step into it soon, so I browsed around to read up about it. While clicking through current API pages, I figured that there is a new link for every 8.x release.

Since Drupal 7 ended up with over 40 Releases, do we have to expect the same amount on API versions for Drupal 8? Shouldn't it be one link for all 8.x releases like it was on Drupal 6 and Drupal 7?

Drupal 8 has a new versioning system, with the following format:

Major.minor.bugfix

Minor versions are expected every 6 months (8.1.0 was recently released), and will contain backwards compatible enhancements and new features, but will remain compatible with code written for earlier releases of the same major version.

So Drupal 8.1.x contains new features and API enhancements, but remains compatible with modules developed for 8.0.x.

This will allow Drupal to be more agile in future, and new features won't be limited to major releases, but compatibility with modules should be maintained.


Pathauto taxonomy term alias for content paths I am trying to make my nodes URL aliases use taxonomy term aliases through Pathauto, but I cant seem to figure it out if there is an alternative.

For example, I am trying to use questions/[term:url:alias]/[node:title], but I am getting an error because taxonomies are not in content patterns.

Pathauto taxonomy terms in content paths
there is a comment to the answer on this post that links to a drupal.org issue.

http://drupal.org/node/741914#comment-3714746
This is a patch for Token. It seems to be for an older version than the latest beta I've got installed... So I had to hand apply the patch to token.tokens.inc "by hand".

It gave me taxonomy for content paths. stuff like [node:term], [node:term:tid], [node:Term:vocabulary], etc.

I don't have files in front of me atm but I will post the token.tokens.inc later if need be. (would post the text, but it's more than the limit for a post here)

Token.tokens.inc - 7.x-1.0-beta


How to change the price componnents order in the order total field view I have a commerce site, I want to change the price componnents order of total order field in the order view page.

In the edit order page the last added line item -fee in my case , I add them manually- become the first in the in the price componnents field, I want do the inverse.

I didn't find any view to edit the added line items order. So I want to ask if there is a way to do that.

Implementing hook_commerce_price_component_type_info_alter hook you can change weight of price components to change sequence. Check following example:

<?php
/**
* Implements hook_commerce_price_component_type_info_alter()
**/

function <MODULE_NAME>_commerce_price_component_type_info_alter(&$components) {
  if (!empty($components['tax|tax_on_shipping'])) {
    $components['tax|tax_on_shipping']['weight'] = 30;
  }
}


Can I group fields by their Field Group in Views? I'm using Field Group module to manage field in content type and I want to display field as table in views, but group field not showing properly. What should I do?

I attached an example below.

e.g.

Field group doesn't actually do anything with regards to data storage or grouping, it only provides fieldsets and formatters for data entry and grouping fields together on display.

It seems to me that you'd find either Field Collection or Tablefield more useful for this use case.

With TableField, you can just output the field in Views, as it's already a table.

With regards to Field Collection, it's a little more work, but much more flexible. You should be able to add a relationship in Views to the the field collection entity that contains your fields, and then group by the entity ID of said field collection in views.

You will also probably have to use something like Views Field View to embed your grouped Field Collection fields into your original view if the other fields aren't to be laid out like tables..


How do I display a link as an embedded player? I want to create a field as a link.  I want this link to be displayed as a custom embedded player.

I have checked out How do I add embedded YouTube videos in a field? and the Embedded Media Field module however this solution does not work for me.

I do not like the admin interface/configuration.
The module does not support my flash player.

Any suggestion would be great.

Another method is to create you own module.   Checkout Media Link

Below is the code you would need. This module adds a podbean audio player display for your link field.  Modify the theme code for your embedded player.  Another good place to look at is the field example module.

Again, this module requires the Link module

<?php

/**
 * @file
 * Defines a display format for a link that will embed a player.
 */

/**
 * Implements hook_field_formatter_info().
 */
function media_link_field_formatter_info() {
  return array(
    'audio_player' => array(
      'label' => t('Audio Player'),
      'multiple values' => FIELD_BEHAVIOR_DEFAULT,
      'field types' => array('link_field'),
    ),
    /*
    'video_player' => array(
      'label' => t('Video Player'),
      'multiple values' => FIELD_BEHAVIOR_DEFAULT,
      'field types' => array('link_field'),
    ),
    */
  );
}

/**
 * Implements hook_field_formatter_view().
 */
function media_link_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
  $elements = array();
  foreach ($items as $delta => $item) {
    $elements[$delta] = array(
      '#markup' => theme('link_formatter_'. $display['type'], array('element' => $item, 'field' => $instance)),
    );
  }
  return $elements;
}

/**
 * Implements hook_theme().
 */
function media_link_theme() {
  return array(
      'link_formatter_audio_player' => array(
          'variables' => array('element' => NULL),
    ),
  );
}

/**
 * Theme function for 'audio player' link field formatter.
 */
function theme_link_formatter_audio_player($vars) {

  $url = $vars['element']['url'];
  return "<div>" .
  "<object classid='clsid:d27cdb6e-ae6d-11cf-96b8-444553540000' codebase='http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,0,0' width='210' height='25' id='mp3playerlightsmallv3' align='middle'>" .
  "<param name='allowScriptAccess' value='sameDomain' />" .
  "<param name='movie' value='http://www.podbean.com/podcast-audio-video-blog-player/mp3playerlightsmallv3.swf?audioPath=" . $url . "&autoStart=no' />" .
  "<param name='quality' value='high' /><param name='bgcolor' value='#ffffff' /><param name='wmode' value='transparent' />" .
  "<embed src='http://www.podbean.com/podcast-audio-video-blog-player/mp3playerlightsmallv3.swf?audioPath=" . $url . "&autoStart=no' quality='high'  width='210' height='25' name='mp3playerlightsmallv3' align='middle' allowScriptAccess='sameDomain' wmode='transparent' type='application/x-shockwave-flash' pluginspage='http://www.macromedia.com/go/getflashplayer' /></embed>" .
  "</object>" .
  "</div>";
}

?>