Do not request a billing address during checkout By default, Commerce 2 requests credit card info + address info (name, address, and company name) for all orders.  I want to have users enter their credit card information but I don't want to collect their name, address, or company name. Stripe does not require name/address info so I don't want to require it, either.

As my payment gateway, I am using Commerce Stripe, but this applies to all payment gateways, such as Commerce PayPal, and the Manual (no credit card) payment gateway.

So, how can I safely remove the address form from the checkout page?

I first tried to hack Commerce directly (bad practice, just trying to see how it worked) but I broke the module.

As I looked around, it appeared that the billing info is deeply wired into the Commerce code.  Is there a way to decouple it?  Not all stores (those that sell digital products, etc.) need their customers' physical addresses.

On the checkout "Payment information" screen, I want to remove all of the fields from "Country" down to "Postal code":

It is quite hard to do indeed. One way to do this is by setting a dummy billing address and hide the address form.

You will need to do the following:

In a custom module, add a CommerceCheckoutPane plugin. The plugin class should extend \Drupal\commerce_payment\Plugin\Commerce\CheckoutPane\PaymentInformation.
Override the buildPaneForm() method, in there:

Set an #after_build callback. In this callback, make each address field non-required. The reason that you need an #after_build callback is that else address fields won't be available.
On the commerce_profile_select element, set an #element_validate callback. In this callback, set the address values. The reason that you need an #element_validate is because a general form validation callback is called too late in the validation process to set the address in time. This is because the address element has a constraint and the address is validated against this constraint after #element_validate and before a general form validate. Should you try to set the address in a general form validation callback, then you'll get address field required errors because of the constraint.

You can set the #element_validate callback as well in the #after_build callback, which I've done in the code example below.

To hide the address form, you'll need to set #access to FALSE for the address form. This needs to happen in the #after_build callback as well, because earlier the address form isn't available yet.
On the checkout flow settings, disable the default Payment information pane (and enable the custom Payment information pane if not yet enabled).
To hide the dummy billing address on the 'Review' step, copy the template commerce-payment-method--credit-card.html.twig (and/or commerce-payment-method.html.twig if you are using a non-credit card payment method) to your theme and remove the line {{ payment_method.billing_profile }} from it.

Code example (file name: mymodule/src/Plugin/Commerce/CheckoutPane/PaymentInformation.php):

namespace Drupal\custom_commerce\Plugin\Commerce\CheckoutPane;

use Drupal\commerce_payment\Plugin\Commerce\CheckoutPane\PaymentInformation as PaymentInformationBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Render\Element;

/**
 * Provides the payment information pane.
 *
 * @CommerceCheckoutPane(
 *   id = "custom_commerce_payment_information",
 *   label = @Translation("Custom Payment information"),
 *   display_label = @Translation("Payment information"),
 *   default_step = "order_information",
 *   wrapper_element = "fieldset",
 * )
 */
class PaymentInformation extends PaymentInformationBase {

  /**
   * {@inheritdoc}
   */
  public function buildPaneForm(array $pane_form, FormStateInterface $form_state, array &$complete_form) {
    $pane_form = parent::buildPaneForm($pane_form, $form_state, $complete_form);

    // Add an after build callback in order to make modifications on the address form.
    $pane_form['#after_build'][] = [$this, 'paneFormAfterBuild'];

    return $pane_form;
  }

  /**
   * After build callback for the pane form.
   */
  public function paneFormAfterBuild(array $pane_form, FormStateInterface $form_state) {
    // Get billing form element. Where it is located depends on the payment method that is chosen.
    if (isset($pane_form['add_payment_method']['billing_information'])) {
      $billing_form = &$pane_form['add_payment_method']['billing_information'];
    }
    elseif (isset($pane_form['billing_information'])) {
      $billing_form = &$pane_form['billing_information'];
    }
    else {
      // No billing information found.
      return $pane_form;
    }

    // Get the address form element.
    $address_form = &$billing_form['address']['widget']['0']['address'];

    // Add element validation callback to autofill the address.
    $billing_form['#element_validate'] = array_merge(
      [[$this, 'profileSelectValidate']],
      \Drupal::service('element_info')->getInfoProperty('commerce_profile_select', '#element_validate', [])
    );

    // Set all address fields to non-required.
    foreach (Element::children($address_form) as $key) {
      $address_form[$key]['#required'] = FALSE;
    }

    // Hide the address form.
    $address_form['#access'] = FALSE;

    return $pane_form;
  }

  /**
   * Element validation callback for the profile select element.
   */
  public function profileSelectValidate(array &$element, FormStateInterface $form_state) {
    // Set dummy address.
    $address = [
      'given_name' => 'A',
      'family_name' => 'A',
      'address_line1' => 'Dummy street',
      'postal_code' => '1234 AB',
      'locality' => 'Dummy city',
      'country_code' => 'NL',
    ];
    $form_state->setValue($element['address']['widget'][0]['address']['#parents'], $address);
  }

}


Add attributes to the render array I am trying to add some attributes to a render array. In Drupal 7, we can do this by adding a property in an array like the following.
$items[] = array('data' => $item_data, 'id' => 'someId'); // attribute = 'id'
$variables['subpanels'] = theme('item_list', array('items' => $items, 'title' => NULL, 'type' => 'ul'));

In Drupal 8, there's no #attributes property documented in Render Arrays in Drupal 8. How can I add this id as an attribute in a render array, with Drupal 8?
This is the code I am using so far.
mymoduleController.php
public static function _mymodule_f1($users_online) {
  $user = \Drupal::currentUser();

  $render_array_1 = array();
  $render_array_1['name'] = 'test-name';
  $render_array_1['header'] = t('test-header');
  $render_array_1['contents'] = array('#value' => '
' . ''. '
');

  $items = array();
  foreach ($users_online as $key => $value) {
    if ($key != 'total') {
      $items[] = array('#value' => '' .   $value['name'] . '', 'class' => array('status-' . $value['status']));
    }
  }
  //print_r($items);
  if ($items) {
    $item_list = array(
      '#theme' => 'item_list',
      '#items' => $items,
    );
    $render_array_1['footer'] = $item_list;
  }
  $render_array_1['text'] = array('#value' => t('T1') . ' (' . count($items) . ')');
  $image = [
   '#theme' => 'image',
   '#uri' => drupal_get_path('module', 'mymodule') . '/css/themes/images/loading.gif',
   '#width' => NULL,
   '#height' => NULL,
   '#class' => 'icon'
  ];

  $render_array_1['icon'] = $image;
  $mymodule_subpanel = array(
    '#theme' => 'mymodule_subpanel',
    '#subpanel' => $render_array_1
  );
  return $mymodule_subpanel;
}

mymodule.module
function mymodule_theme() {
  return array(
    'mymodule' => array(
      'variables' => array('mymodule' => NULL),
      'template' => 'mymodule',
    ),
   'mymodule_subpanel' => array(
     'variables' => array('subpanel' => NULL),
     'template' => 'mymodule-subpanel',
   ),
 );
}

function mymodule_preprocess_mymodule(&$variables) {
  $items = array();
  $users_online = mymoduleController::f2();
  $render_items = mymoduleController::_mymodule_f1($users_online);
  $render_items['#attributes'] = array('id' => 'some_id'); //not working; unable to add id='some_id' in the
 tag.
  //print_r($render_items);

  $items[] = $render_items;
  //print_r($items);

  $item_list = array(
    '#theme' => 'item_list',
    '#items' => $items, // array of render arrays.
    '#title' => NULL,
    '#list_type' => 'ul',
    '#attributes' => array('id' => 'mainpanel')
  );
  $variables['subpanels'] = $item_list;
}

Render arrays can contain render elements or theme templates.

Example for a render element:

'#type' => 'link'

and a theme template:

'#theme' => 'item_list'

Render elements have the parameter #attributes. This is defined in the base class Drupal\Core\Render\Element\RenderElement that all render and form elements are extended from.

That is not the case for templates in general.

The template links for example has #attributes and handles this in template_preprocess_links() in /core/includes/theme.inc.

The example from the question is item-list. This template has a variable #wrapper_attributes. You can see in the first line of the preprocess function how wrapper-attributes is transformed in an attributes object, which is then passed on to the twig template where it is placed in the list wrapper:

/**
 * Prepares variables for item list templates.
 *
 * Default template: item-list.html.twig.
 *
 * @param array $variables
 *   An associative array containing:
 *   - items: An array of items to be displayed in the list. Each item can be
 *     either a string or a render array. If #type, #theme, or #markup
 *     properties are not specified for child render arrays, they will be
 *     inherited from the parent list, allowing callers to specify larger
 *     nested lists without having to explicitly specify and repeat the
 *     render properties for all nested child lists.
 *   - title: A title to be prepended to the list.
 *   - list_type: The type of list to return (e.g. "ul", "ol").
 *   - wrapper_attributes: HTML attributes to be applied to the list wrapper.
 *
 * @see https://www.drupal.org/node/1842756
 */
function template_preprocess_item_list(&$variables) {
  $variables['wrapper_attributes'] = new Attribute($variables['wrapper_attributes']);
    foreach ($variables['items'] as &$item) {
    $attributes = array();
    // If the item value is an array, then it is a render array.
    if (is_array($item)) {
      // List items support attributes via the '#wrapper_attributes' property.
      if (isset($item['#wrapper_attributes'])) {
        $attributes = $item['#wrapper_attributes'];
      }

The template item_list has also the variable attributes, which is passed on to the twig template. Here you can see how this all ends up in the html markup, including the attributes of the items, which are collected for each item from wrapper-attributes in preprocess:

item-list.html.twig

{#
/**
 * @file
 * Theme override for an item list.
 *
 * Available variables:
 * - items: A list of items. Each item contains:
 *   - attributes: HTML attributes to be applied to each list item.
 *   - value: The content of the list element.
 * - title: The title of the list.
 * - list_type: The tag for list element ("ul" or "ol").
 * - wrapper_attributes: HTML attributes to be applied to the list wrapper.
 * - attributes: HTML attributes to be applied to the list.
 * - empty: A message to display when there are no items. Allowed value is a
 *   string or render array.
 * - context: A list of contextual data associated with the list. May contain:
 *   - list_style: The custom list style.
 *
 * @see template_preprocess_item_list()
 */
#}
{% if context.list_style %}
  {%- set wrapper_attributes = wrapper_attributes.addClass('item-list--' ~ context.list_style) %}
  {%- set attributes = attributes.addClass('item-list__' ~ context.list_style) %}
{% endif %}
{% if items or empty -%}

    {%- if title is not empty -%}

{{ title }}

    {%- endif -%}
    {%- if items -%}
      <{{ list_type }}{{ attributes }}>
        {%- for item in items -%}

{{ item.value }}

        {%- endfor -%}
      </{{ list_type }}>
    {%- else -%}
      {{- empty -}}
    {%- endif -%}

{%- endif %}

Btw. the wrapper is only placed in the classy theme, the base theme doesn't use this.

Conclusion:

Templates don't have attributes by default. As the examples show, they can handle them like render elements, under a different variable name or not at all.


Fatal Error Call to undefined function SearchApiViewsQuery():placeholder I am using search api and views module
When I add fields Indexed user first name and indexed user last name
and then use field views combine fields filter and add those two fields I get the undefined function error

Basically I want to add a keyword search option to the views which is using index values of a search api
Is there any other option to implement keyword search in drupal

Have you tried using the Realname module on your site? I'd suggest doing it on a copy of the site to test first as it affects quite a lot of things, but if you're doing searches for names it may help, sounds like search api is getting confused trying to join the two fields, so perhaps a different approach may help.

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

HTH

Steve


Cannot create simplenews content I have simplenews module installed on drupal 7.50

When accessing #overlay=node/add/simplenews

I get a NOT FOUND, so I cannot create any newsletter content. Tried to flush cache but didn't work. Any ideas?

I have tested on Drupal vanilla installation 7.50 and simplenews version 7.x-1.1 stable release, the link works perfect to add simplenews nodes.

I would recommend you

 -  Re install simplenews module
 -  Check if you see simplenews content type under structure>>content types
 -  Check if you see any error in your error logs.
 -  Check if you are using dev version of simplenews module


Show full image path D8 I have set a Drupal 8 project into another server with some child directory. This D8 project is working good, But images are not showing due to path missing. E.g

My project is setup:- http://abc.xyz.com/client/development/project-name/

but when I was inspecting element then I got image URL:-http://abc.xyz.com/sites/default/files/images.png

I know client/develoment/project-name/ path is missing into the image path. May you let me know how to get full image path display?

Full path must show:-http://abc.xyz.com/client/development/project-name/sites/default/files/images.png

Thanks

Images are hardlinked inside the body field.

One way to correct it is to do a search and replace inside the database.

Perhaps also pathologic can help correct the problem with broken images.

add pathologic support to your desired text formats (congig > content authoring > text formats)
make sure you check  Correct URLs with Pathologic

when visiting a page pathologic should correct those broken images


Let images work properly online and offline (MAMP) I just started using MAMP to work offline on my drupal-projects.

Because MAMP and working offline is new to me I started today with a test-website.

I installed MAMP, no problems.

I installed a new drupal 7.30 offline in MAMP, no problems.
I imported the CKEDITOR and IMCE for uploading images, no problems.

I created two test-pages and imported in each page a image using CKEDITOR & IMCE, no problems.

After that i tried to upload my offline website online: backup DB, create a new DB online, imported the offline DB, FTP my files online, change the settings-file for connecting instructions DB.

After all those steps my website was showing up online and i could login. Everything seems to work fine.

But then when i clicked one of the testpages, i saw that my images where not showing up...

When i checked the sourcecode i saw something like this:

When i removed /sweetmorning, and saved that code, the image was showing up again.

What is the best practice to still work with CKEDITOR IMCE and let the images showup offline and also after i put the website online.

Any tips, links, info are welcome :-)

Thanks in advance,
Kristof

Part of your code did not go through; however I believe it's pretty clear that the issue is in image paths.

Check out Pathologic module, as it deals with exactly such issues:

  Pathologic is an input filter which can correct paths in links and images in your Drupal content in situations which would otherwise cause them to “break;” for example, if the URL of the site changes, or the content was moved to a different server. Pathologic can also solve the problem of missing images and broken links in your site’s RSS feeds. See more example use cases on the documentation page.


Return both a form and content in a menu callback I have the following code.

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

  $items['mymodules/page'] = array(
    'title' => t('my module settings'),
    'description' => t('change values here'),
    'page callback' => 'mymodule_page',
    //'page arguments' => array('mymodule_page'),
    'access arguments' => array('access administration pages'),
    'type' => MENU_CALLBACK,
   );

  return $items;
}

function mymodule_page() {
  return drupal_get_form('test_form');
}

function test_form() {
  $form = array();
  $brandarray = array('nokia','siemes');

  $form['mymodule_brand'] = array(
    '#type' => 'select',
    '#title' => t('Brand'),
    '#default_value' => variable_get('mymodule_brand', 'nokia'),
    '#options' => $brandarray,
    '#description' => t('Change this.'),
  );

  $form['my_markup'] = array(
  '#markup' => '
Lorem ipsum
',
  );

  return system_settings_form($form);
}

This works perfectly. What I wanted to so is returning a form and page content together, i.e after the page content, in a menu callback function; I tried using the following code:

function mymodule_page() {
  $variable =  drupal_get_form('test_form');
  $variable .= '
here
';

  return $variable;
}

But it prints something like the following:

    Array
    here

How do I return both the form and content together in a menu callback?

In Drupal 7 drupal_get_form() returns a render array instead of a string, so you should return a render array as well:

return array(
  'my_content' => array(
    '#type' => 'markup',
    '#markup' => 'Some markup',
  ),
  'my_form' => drupal_get_form(...),
);


How to print all Drupal commerce order variables available inside the template? I'm struggling to understand how to print out all order information at the order view link, including the order author.

I mean printing it out at  /admin/commerce/orders/XXX/view

I've manage to get the page--admin--commerce--orders.tpl.php working, but how do I find all the variables?

I've tried with dpm($account), and dpm($content), with no luck.

ie. How may I print out the author of the order?

Try using dpm($order) for this.  This will give you most of what you need including the order author's uid:

$order->uid


Autopopulate EntityReference field using rules? I'd like to have an EntityReference field be autopopulated by the node that was just navigated from.

So the workflow would be:

User views page for Business A -> User clicks review link -> User is presented with review form, & EntityReference field is automatically populated with the name/id of Business A.

What I don't know is which action to designate to tell Rules to do this. I have Event set to "before saving content," and Elements set to
"Entity has field, Parameter: Entity: [node], Field: field_venue_reference." These seem like the correct settings for these portions from what I have read, but since I'm new to Rules, I'm not completely sure of that either. Any suggestions?

You want the Entity Reference Prepopulate module.  It's very similar to the Node Reference URL module but the maintainer of that module is stubborn and sticking to only referencing Nodes and not Entities.

Rules has always had a hard time with prepopulating reference fields so please don't go that route.  You can combine Rules and ERP by using Rules to populate other fields and ERP to handle the referencing.

Everything is URL based so you must setup your links appropriately.  The structure is node/add/article?[field_ref]=[id]
So you could have
node/add/review?field_business_ref=457

your link to the form could look something like l('add review', 'node/add/review?field_business_ref='. $node->id)


Change content of views_field_view field using hook_views_pre_render I am using the views_view_field module for embedding a view inside another view.

I want to concatenate some text with that field in hook_views_pre_render based on a condition.

But when I printed the $view->result array, that field is not there.

So How can I do this?

Try using template_preprocess_views_view_fields

If you still can't access that field there then:

Ditch views_view_field
Add a "custom text field" (their field_name will be nothing).
In template_preprocess_views_view_fields programmatically add view to this "custom text field".

/sites/all/themes/THEMENAME/template.php

function THEMENAME_preprocess_views_view_fields(&$vars) {
  $view = $vars['view'];
  foreach ($view->field as $id => $field) {
    if ($something == 'some condition') {
      $vars['fields']['nothing']->content = 'some string' . '

' .
        views_embed_view('view_name', 'view_machine_name', $contextual_filter_value);
    }
    else {
      $vars['fields']['nothing']->content = views_embed_view('view_name', 'view_machine_name', $contextual_filter_value);
    }
  }
}

If your view does not need a contextual filter, then it's:

views_embed_view('view_name', 'view_machine_name');


Send site emails to multiple administrators Simple question, though I cannot find the answer anywhere --

How does one specify multiple addresses for the primary administrator account in Drupal 7?

Put another way -- how does one make Drupal administrator emails go to multiple people, without setting up a bunch of forwarding filters on the mailserver?

Thanks!

This is much similar to Pontus's answer but in a different approach. and I have tested this and it worked on a Ubuntu server email program (not through an external SMTP server but it should work in a decent program). Pontus's solution will work as it seems. But recipient will see both email addresses. A good approach would be to set the BCC address (Blind Carbon Copy) instead of a new CC.

If you are not willing to make a module, I'd suggest http://drupal.org/project/maillog .

function MYMODULE_mail_alter(&$message) {
 if (-- enter your condition here -- ) {
   $message['headers']['BCC'] = $message['headers']['Bcc'] = 'hidden@example.com';
 }
 }

Note that now you have opened a serious security risk that hidden@example.com can now see any email, including password reset email address for the super user. So don't forget  to add some condition using $message['id] that contains the message's ID.

You can make the module fancy and really usable by adding some sort of system_settings_form()'d form and a few variable_get().

Also, if the purpose of this is to send multiple emails on new security releases for modules, don't forget that you can add multiple email addresses in settings out-of-the-box.


How to use search_excerpt() function from core search module? I want to use the function search_excerpt() to generate excerpts. Unfortunately this function is returning exactly same text as I submit. For example I tried this:

$test = (search_excerpt('test', 'this is a test'));
print $test;

This is returning "this is a test".

I was expecting more something like:

  "this is a test"

What is wrong in my code?

Try this code.I have just added a space after the string and this will surely work

$string = 'this is a test';
$test = (search_excerpt('test', $string.' '));
print $test;

In the search_excerpt() if the search text is the last one, then preg_replace omits the search text.In order to overcome this I just added a empty space to the string.

// Highlight keywords. Must be done at once to prevent conflicts ('strong' and '<strong>').
  $text = preg_replace('/' . $boundary . '(' . implode('|', $keys) . ')' . $boundary . '/iu', '<strong>\0</strong>', $text);


How to use Content Complete Module? Tried to read https://www.drupal.org/project/content_complete but that didn't give me much so now I'm stuck.

I've set what Content Type + Fields to use and Rebuilt Cache. Then I keep getting this error "You need to provide a completeness data field in the display 'Master'." when I try to create a View. Don't know what Master means here?

the Master display is the 1st Views page that you edit when making a new View. Typically this is a Page or Block in Drupal7. So you have a View somewhere that if you try to save it the View will say you need to supply at least 1 field for the completeness data field. So I suggest going through all of your Views and trying press Save on each 1 (because you dont know which 1 it is apparently or what exactly we're talking about) -- 1 will complain it cannot be saved until you fix this error in it.


How to uninstall a module that has added a basefield that has data My module adds a basefield 'myfield' to the core 'file' content entity.

I now need to uninstall my module for development purposes, but I can't because drush refuses to uninstall the module, saying "There is data for the field myfield on entity type File".

My understanding is that this is a known issue:

Because my module adds this field to an entity it does not own, this uninstallation will not be taken care of automatically by the core uninnstall procedure,
Therefore my module needs to have a hook_uninstall that triggers field uninstallation using  \Drupal::entityDefinitionUpdateManager()->uninstallFieldStorageDefinition
However, a field can't be uninstalled if it still has data in it, so I first need to remove the data.
But the system to purge field data currently only works for bundle fields not base fields.
There may be other ways to delete field data, but they won't scale to large quantities of data.
Therefore there is no robust way to uninstall my module and Drupal core is correct to refuse to uninstall it.

Given all that, how best can I uninstall it when I need to do so for development purposes (short of reinstalling Drupal)?

Here is how I am creating it:

In mymodule.module:

function mymodule_entity_base_field_info(\Drupal\Core\Entity\EntityTypeInterface $entity_type) {
  if ($entity_type->id() == 'file') {
    $fields = array();
    $fields['myfield'] = BaseFieldDefinition::create('boolean')
      ->setLabel(t('My field'))
    return $fields;
  }
}

In mymodule.install:

  $entity_manager = \Drupal::entityManager();
  $definition = $entity_manager->getFieldStorageDefinitions('file')['myfield'];
  $entity_manager->onFieldStorageDefinitionCreate($definition);

This is a known Drupal Core limitation that looks close to being ready so hopefully will be fixed in D8.5.  In the meantime you could apply the patch linked to the issue.


An AJAX HTTP error ocurred. HTTP Result Code: 500 (while trying to rebuild content access perms) I have installed a module that ask me everytime to rebuild content Access Permissions, but every time I try to do it, it shows me an error I do not have idea why is it happening. Please help

An AJAX HTTP error ocurred. HTTP Result Code:  500 Debugging information follows: Path: /batch?id=172&op=do Status Text: Service unavailable (with message)
Response Text:

Please check the image for more details

The problem with this was the server, the server was refusing the ajax request, maybe a php memory problem I have migrated my drupal website to a VPW


Anonymous cannot see cart in cart page I need to debug an issue and don't know how to start.

If I'm logged in the cart works just fine but, if I log out and put something in my cart I see the object in the cart widget but not my cart page.

And this is the markup in the page.

I need a hint to understand where to start searching the issue because the cart page permission and the view permission I think are fine because I see them, but the content is wrong..

If I go in admin/structure/views/view/commerce_cart_form/edit page and I insert the order ID, I can see the right cart displayed in the right way..

Where can I start to debug this?
Do you have a clue to where can the bug be?

I tried to put a couple of prints in the view header and the cart page remains blank. But why is the empty cart sentence not displayed if the order_id is empty?
And why 2 different carts views in the same page act so differently?

My guess is you're experiencing a common issue with product permissions due to a relationship you've added from the line item to the referenced product. Open your View's advanced settings fieldset, and in the Query settings menu disable SQL rewriting. This will bypass the normal entity access check to see if a customer has the permission to directly view the related product data, which is fine for this View since we know the products in the cart will always come from line items the customer has created through Add to Cart forms.

See also: https://drupal.org/node/1276450


What's the best way to insert a user reference field value into the database? I use the references module. I have a custom form, into which I capture names into a user reference field via the autocomplete widget. So, on the form, if a user types Joe, the following appears in the input box:

Joe [uid: 5]

Now, I do not want to insert this into my database as it is because my 'Name' field is expecting just the uid. So I need to pass '5' to the database, not the string Joe [uid: 5].

To accomplish this, before I write my record to the database I pass the string Joe [uid: 5] through this code:

// * Search for match (integer) to regular expression and put in $integer.
preg_match_all('!\d+!', $form_state['values']['name'], $integer);

// * Return string representation of array elements.
$name_uid = implode(' ', $integer[0]);

$name_uid now contains '5' and is ready to be inserted. Is there an existing function that already does this? or does anyone have a better way?

The downside of my method is that you cannot have numbers in names, like 'Joe 2'. I've looked in user_reference.module, but it's not obvious, to me, how they do it.

Thanks

I couldn't make user_reference_autocomplete_validate() work for me so I turned my own code into a function, which now solves my numbers in names problem. I can't see why it would ever fail, but if anyone has a better solution, please let me know.

/**
 * Search for regular expression matches and return the last match.
 */

function extract_id($subject) {
    preg_match_all('!\d+!', $subject, $matches);
    return end($matches[0]);
}


How do I add a password field during registration? i am using Drupal 8. I want to set the password field and confirm password field during registration. On admin/configuration this option is not available. Is there a setting to achieve this?

Yes. Disabling email confirmation. Which you probably don't want.

Drupal doesn't really have mail confirmation. It just doesn't tell the user his password, and then he gets a password recovery link and can provide a password after that.

I've built a custom module for this that allowed it for a project, you basically need to add a field to users, prevent login if that is not set, set it on the first login through password recovery. Change the user registration submission to send a confirmation mail anyway. And care about some special cases, like admin created users. Not trivial.

There are contrib modules for this, for example https://www.drupal.org/project/user_registrationpassword. there's no official release yet, but maybe someone started porting it.


Can't rearrange menu items on Drupal 6 I encountered a strange situation. I have a Drupal 6 site with a very large menu tree. I can add new menu items but I cannot rearrange menu items. I can move the items, but when I submit the changes, the menu item gets back to the old position.
I tried to disable javascript and set the weight manually, I tried to empty the cache, even disabled it completely. I tried to rebuild the menu with DEVEL, but nothing helped.

I recently upgraded to PHP 5.3.27 so maybe it's related to this. I had some errors about timezone settings, but I corrected this with the timezone set in php.ini. I have no other errors in the log.

If I edit a menu item and set the weight, it works. If I set the weight from the DB, it works. The only thing that doesn't work is the rearranging on the items list page.

Edit: PHP log shows no errors even with E_ALL reporting.
I think the problem is with Drupal, as it only lets weights from -50 to 50 and the rearranging can't put the items where I want them. Whe I set weights of more than 50 in DB, the ordering was correct, just until I wanted to change the order withhin Drupal. Then, the manually set items scrambled. Is there a way I can set it up to allow values in a wider range? I don't want to rearrange everything via DB it's a pain in the ass.

PHP 5.3 enforces a max_input_vars (see the accepted answer in PHP Warning: Unknown: Input variables exceeded 1000) and I've seen it create similar errors (page saves yet nothing is saved) when setting permissions for users on sites where there are lots of permissions and lots of roles, so, most probably the same is happening here with the menu UI when it has lots of menu items.  To resolve it, bump up the value on your system (see php.net documentation for max_input_vars) until things work again.


Moving a change to other servers Is there a way a person can ensure that if he makes a change to a drupal 8 website via the UI (e.g. Adding/modifying a field to a content type, creating/editing a view) that this can be automatically applied to another developers localhost on the git pull or on a staging/production server?

Currently (I have moved from Drupal 7) I am doing this manually which is a pain. I've been told that Features is the way to go from Drupal 8 (and Drupal 7 apparently).

Features in D8 is the way to sync features across multiple sites. And was the default in D7 to import and export database changes. Which in D8 is solved by Configuration management.

Please read the docs (thoroughly): Managing your site's configuration.

You routinely have to drush cex after you've made changes via the UI. This will export database values into multiple (hundreds/thousands) *.yml files. Then your colleagues will have to drush cim after they pulled the latest *.yml files to get the changes imported into their DB.

For a general overview please see Web development structure on multiple devices.


Is there any performance issues in using Omega theme with Context, Delta and Panels modules? Is there any performance issues in using Omega theme with Context/Delta modules and Panels module too? (I mean the context standalone menu, not the one inside panels)

Is there any known issue? I´ve read about some issues with Omega and panels in the past, but now they work just fine.
And I need context for my homepage, to create a slighty different layout than the rest of the site.

it depends on your site and server configuration. if you get alot of anonymous traffic that doesnt require users to login, you should be fine as the cache would handle alot of that load. Also be sure to turn on js / css aggregation. I've built many sites with those modules combined and they run fine. But if your all about performance, you can just do everything by hand and write your own templates/css and not use the bloated ones they have, but you'll be spending alot of time. in that effect you'll have total control over what gets outputted to the user.


Correct views hook to alter contextual filter I am trying to find the correct views hook to alter/add a contextual filter to a views block that's being rendered in a template. (Using drupal_view and the twig tweaks module).
The view is setup to accept a contextual filter that is provided in the URL by default. It works great on that page, however it's been requested that the view also display on a sub-page of this main page, in where the URL does not contain the contextual filter. Therefore, I am trying to find a views hook that I can reliably attach the contextual filter to and have it work every page load.
I have tried using hook_views_pre_view(), however this appears to only work once between cache clears, as if I clear cache it works, then as soon as I refresh the page it stops working again until another cache clear.
Is there a way I can do this from a hook? The way the child-page is structured, I can't easily get it from the template to pass it into drupal_view() as an argument.
The current code I am using is:
function item_types_views_pre_view(&$view, &$display_id, &$args) {
    if ($view->id() == 'existing_copies') {

        $parameters = \Drupal::routeMatch()->getParameters();
        $imcid = \Drupal::routeMatch()->getParameter('imcid');

        $entity = \Drupal::entityTypeManager()->getStorage('item_type')->load($imcid);

        if ($entity->bundle() == 'book_copy') {
            $main_record = $entity->field_book_main_record->getString();
        }
        elseif ($entity->bundle() == 'book_master_copy') {
            $main_record = $entity->field_master_copy_book_mr->getString();
        }

        $args = [$main_record];
    }
}

Which like I said, works great immediately after a cache clear, but no longer works after the page is refreshed.

I was able to use achieved what I wanted by using hook_views_pre_build() as below
hook_views_pre_build(ViewExecutable $view) {
  $args[0] = '1234';

  $view->addArguments($args);
}


How to update role name progammatically in Drupal 8 I am new to Drupal 8. I want to save & update role programmatically in database. I am using below code

    //your data array
$data = array('id' => 'client', 'label' => 'Client');
//creating your role
$role = \Drupal\user\Entity\Role::create($data);
//saving your role
$role->save();

It works fine. Now I want update role name. How to proceed it?

Please anyone suggest to me?

If you already have the role object loaded:

$role
  ->set('label', 'New label')
  ->save();

If you don't:

$role = \Drupal::entityTypeManager()
  ->getStorage('user_role')
  ->load('client')
  ->set('label', 'New label')
  ->save();


Added twig suggestion is not used I have added twig suggestion from .theme file to views__view.html.twig for customizing taxonomy.

   function mediumish_blog_theme_suggestions_views_view_alter(array &$suggestions, array $variables) {
      if (\Drupal::routeMatch()->getRouteName() == 'entity.taxonomy_term.canonical' && $tid = \Drupal::routeMatch()->getRawParameter('taxonomy_term')) {
       $term = Term::load($tid);
       $suggestions[] = 'views__view__taxonomy_term';
     }
   }

I am getting suggestion in twig suggestion display but when i am creating file and applying my custom theme, its not actually displaying output of that file, Its still using the default views--view.html.twig.

Replace the underscore characters with hyphens, and clear the cache.

The template filename should be views--view--taxonomy--term.html.twig.

   function mediumish_blog_theme_suggestions_views_view_alter(array &$suggestions, array $variables) {
      if (\Drupal::routeMatch()->getRouteName() == 'entity.taxonomy_term.canonical' && $tid = \Drupal::routeMatch()->getRawParameter('taxonomy_term')) {
       $term = Term::load($tid);
       $suggestions[] = 'views__view__taxonomy__term';
     }
   }


Drupal 8 Form Redirect On Failed Validation I have a form which, upon failed validation, should query a custom/non-Drupal table, and if that query is successful, to redirect the user to a custom page that is only accessible through a logged-in state (so I need to "fake" successful authentication even if the user does not exist in the official Drupal users table).

The query to the custom table essentially checks a secondary user list in non-Drupal format upon failing to authenticate the official way, and if successful, would redirect the user to another page where they could select a Drupal username and password combination in order to register them in the system / make an official account.

This is the relevant code inside my form validation method:

if ($this->userAuth->authenticate($form_state->getValue('name'), $password) == FALSE) {
    // other stuff
    $uid = $this->userAuth->authenticate($form_state->getValue('name'), $password);
    $form_state->set('uid', $uid);

    $response = new TrustedRedirectResponse('/path/destination');
    $form_state->setResponse($response);
}

I have also tried this instead of the new TrustedRedirectResponse:

    $redirect_path = "/path/destination";
    $url = url::fromUserInput($redirect_path);
    $form_state->setRedirectUrl($url);

If you want the redirect to happen immediately, you can do it like this:

use Symfony\Component\HttpFoundation\RedirectResponse;

$response = new RedirectResponse('/path/destination');

$response->send();


How to get the form field label of a multi-value field In hook_form_user_form_alter I need to get the title of each field. When I dump a normal (single-value) field #title is an array value, like this:

array (size=13)
  '#title' => string 'Name' (length=13)
  '#title_display' => string 'before' (length=6)

but for fields that can contain more than one value, #title is an object that looks like this:

array (size=13)
  '#title' =>
    object(Drupal\Core\StringTranslation\TranslatableMarkup)[1544]
      protected 'translatedMarkup' => null
      protected 'options' =>
        array (size=0)
          empty
      protected 'stringTranslation' =>
        object(Drupal\Core\StringTranslation\TranslationManager)[285]
          protected 'translators' =>
            array (size=1)
              ...
          protected 'sortedTranslators' =>
            array (size=1)
              ...
          protected 'defaultLangcode' => string 'en' (length=2)
          public '_serviceId' => string 'string_translation' (length=18)
      protected 'string' => string '@title (value @number)' (length=22)
      protected 'arguments' =>
        array (size=2)
          '@title' => string 'Name' (length=19)
          '@number' => int 1
  '#title_display' => string 'invisible' (length=9)
  '#description' => string '' (length=0)
  '#field_parents' =>
    array (size=0)
      empty
  '#required' => boolean false
  '#delta' => int 0
  '#weight' => int 0
  '#type' => string 'textfield' (length=9)
  '#default_value' => string 'John Doe' (length=8)
  '#size' => int 60
  '#placeholder' => string '' (length=0)
  '#maxlength' => int 255
  '#attributes' =>
    array (size=1)
      'class' =>
        array (size=2)
          0 => string 'js-text-full' (length=12)
          1 => string 'text-full' (length=9)

If I just refer to #title, for the multi-value field I end up with:

Name (value 1)

What is the proper way of obtaining the title, and what causes the difference?

What is the proper way of obtaining the title, and what causes the
  difference?

The cause is this code in the field widget:

  // For multiple fields, title and description are handled by the wrapping
  // table.
  if ($is_multiple) {
    $element = [
      '#title' => $this->t('@title (value @number)', ['@title' => $title, '@number' => $delta + 1]),
      '#title_display' => 'invisible',
      '#description' => '',
    ];

This t($string, array $args = [], array $options = []) function returns a TranslatableMarkup object.

You can cast the translatable markup as string to obtain the title, but normally you don't have to. See both answers here  How to get the string value from the function CountryManager::getStandardList()?


Generating links from words using an input filter Does anyone know of a D6 module that can do this easily? Really I just want to find certain words in forum posts and link them to other nodes.


the article can't show the image in the full mode in drupal 7 my article can't show images in the full view but only in the teaser view, even go to the article content type setting, in the full mode, it is fine that I allow to show the image.

any idea why?

Make sure to set the display on the content type (manage display link) as it ultimately sets the values of the teaser and full node.


Modifying teaser node comment links I've been at this for a few hours now but can't find a good way to solve this.

Basically what i want to achieve is to trough my template.php file completely override the comment modules output of links when displayed on a node teaser.

So i want to remove the "Add New Comment", "2 New Comments", "2 Comments" for example and have it replaced by only one single button saying something like "Comments (2)" instead.

This specifically answers your question on how to override the comment links. The important part is using the value of $vars['comment_count'] to add the count into your altered link title.

function YOURTHEME_preprocess_node(&$vars) {
    if(!empty($vars['content']['links']['comment'])){
        // Get rid of other comment link with counts
        $vars['content']['links']['comment']['#links']['comment-comments'] = array();
        // Override the title of the add a comment title displaying a count
        if($vars['comment_count'] > 0)
            $vars['content']['links']['comment']['#links']['comment-add']['title'] = 'Comments ('.$vars['comment_count'].')';
        else
            $vars['content']['links']['comment']['#links']['comment-add']['title'] = 'Comments';
    }
}


Migrating into a multi-value nested custom field I have a nested field called released with three values

By
When

A node can have multiple releases. However, in the old dataset (d7), each node only had one release and the fields just a part of the node.

I want to now migrate it to the new format in d8

If it was just one value, I could do this

released/by: field_released_by
released/when: field_released_at

I tried the solution at https://www.freelock.com/blog/john-locke/2017-12/slick-migration-trick-convert-columns-multi-value-field-subfields which didn't help. It tried to look up the dummy fields and caused it to fail.

I can't be the first person to come across this requirement so I am loathe to write a process plugin for it.

Is there a straightforward solution for this? or is a process plugin the only way?

Turns out the answer on that page is correct, just out of date. Instead of Iterator, it needs sub_process. It also needs a nested array

To create the nested array, I start with a temporary field with the two items it needs

tmp_single_published:
  plugin: get
  source:
    - field_published_by
    - field_published_at

I then plug it into another array and process it.

published:
  plugin: sub_process
  source:
    - '@tmp_single_published'
  process:
    uid: '0'
    at: '1'

This worked for me


change customer email address in ubercart Is it possible to to change customer's email address in already created order? I have some customers who type wrong email address and complain that they did not receive any email... I tried to change it in customer's info but new email is not reflected in already created order. Thank you

This is a known issue with ubercart. The only way to change it, currently, is to find the order in the uc_orders table, and to update the primary_email field in the record.


How do I return the output from a callback function unthemed? I have a custom module with a hook_menu() "page callback" function, a custom theme function and a hook_theme() implementation. This module is working fine and the final output of the module is passed to the template of my site.

However, what I would like to do is to have the output of the module to be displayed on its very own - nothing else. That is:

what it does now:

hook_menu --> page callback function --> custom theme function --> hook_theme implementation --> .tpl.php template file

what I would like it to do:

hook_menu --> page callback function --> return a <div> to be displayed on its own

Can anyone help?

This is really easy: instead of returning the output in the page callback, just print it and exit.

Drupal 6

function foo_callback() {
  print theme('foo');
  exit();
}

One thing to keep in mind when doing this is that hook_exit() will not be invoked, as you'll be ending the script before Drupal reaches that point, so make sure you don't need it. If you do, you can invoke it yourself before calling exit():

function foo_callback() {
  print theme('foo');
  module_invoke_all('exit');
  exit();
}

Drupal 7

drupal_exit() was added for this use-case, and will call all the shutdown stuff before exiting. So you just need:

function foo_callback() {
  print theme('foo');
  drupal_exit();
}


Using JCF with dynamic forms I want to use Javascript Custom Forms (JCF) to get more attractive and consistent looking forms on my Drupal 7 site. I've got it working to a degree, however when the form changes with AJAX, the new form element does not have the JCF styling applied.

(E.g. if you have a form file upload, and you press the 'Remove' button, the form changes, without reloading the page, replacing the Remove button with the Browse and Upload buttons. But the JCF styling is not applied to these new buttons.)

This is what I have so far...

In the theme .info file:

stylesheets[all][] = jcf/dist/css/theme-minimal/jcf.css
scripts[] = jcf/dist/js/jcf.js
scripts[] = jcf/dist/js/jcf.file.js
scripts[] = jcf/dist/js/jcf.radio.js
scripts[] = jcf/dist/js/jcf.button.js
scripts[] = jcf/dist/js/jcf.select.js
scripts[] = jcf/dist/js/jcf.checkbox.js

In the theme .js file:

(function ($) {
    $(document).ready(function(){
        jcf.replaceAll();
     });
}(jQuery));

I need to call when the forms changes...

jcf.refreshAll();

I've read up about behaviours, but it seems to be all about creating your own module. Is there a simple way to call the above when the form changes?

You need a behaviour:

Drupal.behaviors.myBehavior = {
  attach: function(context, settings) {
    jcf.refreshAll();
  }
};

That will be called on DOM ready, and every time Drupal.attachBehaviors is invoked (i.e. after AJAX calls)


How to check that an attribute not exists in an element with PHPUnit? I'm trying to test that an element don't exists in a page. I know that exists the elementAttributeExists() method that checks that an attribute exists in an element. But I can't find any method like elementAttributeNotExists() to check that an attribute don't exists in an element.

So, with the following code I can check that the 'autocomplete' attribute is present in the #edit-pass element:

  public function testLoginForm() {
    // Going to the log in.
    $this->drupalGet('/user/login');

    // Checking that the autocomplete is not set.
    $this->assertSession()->elementAttributeExists('css', '#edit-pass', 'autocomplete');
  }

But how I can check that the autocomplete attribute is not present?

You can check if there is a matching element for #edit-pass which has the attribute. Because #edit-pass targets only one element this has the same result when you know that this element exists:

$this->assertSession()->elementNotExists('css', '#edit-pass[autocomplete]');


Users unable to view orders even with permissions set I have a Drupal 7 site with Ubercart.  When users log in, and check their "My Orders" tab, it says there are no orders even when their should be.  Users are showing correctly for admin, and permissions are set correctly for them to view.

Any ideas what could be causing this?

Since you said the permissions are set right you can do a quick test for this using views;

Create a new view with "show" Orders and use the Filters(users) to check if you can find the orders of different users.


How do I include coffeescript and sass compilation steps into managing Aegir platforms? By providing a drush make file, Aegir will create a new platfrom but sites cannot be created or migrated to it until coffeescript and sass files have been compiled.
Generated javascript and css are not suited to being kept under version control as they cause unnecessary conflicts etc.

How to augment Aegir to include these extra steps?

We do our own automation of the drush provision and drush hosting commands that Aegir does, plus we add a couple of extra steps to do the sass and coffeescript compilations before migrating a site to a new platform automatically.

So we still have the benefits of the Aegir front end but also augment the power of the drush backend with our required extra steps. Plus, by tying it in with Git tags we make generating new Aegir platforms an integral part of the site-development workflow.

It was quite a big step to augment our reliance upon Aegir with automating the running of drush provision steps from our own Fabric tasks. However, at the cost of one or two limitations, our solution is giving us much more flexibility in the resulting automated workflow.

These are the components:

A Git post-receive hook that triggers a Jenkins job
A Jenkins job that runs the Fabric tasks
Fabric tasks that drive drush provision and drush hostmaster steps
A YAML configuration file.
A drush .make template file

The solution took quite a bit of effort initially but should be straightforward to copy.
It is a bit lengthy to describe in detail here but a detailed description can be seen here which should give you enough information to tailor our solution to your similar needs using the Fabric program here on GitHub


Using a framework like Backbone I currently have a page http://proctors.org/tv that is driven by several views and attachments with tons of jQuery and hacked-together JavaScript spaghetti, and I would like to clean it up. I understand that newer Javascript "MVC" frameworks make use of templates, and don't strictly store all the data in the DOM as you might do with jQuery.

I believe you would use something like Services and/or Views as the backend, with Backbone on the front.

There is a D.o project for Backbone, and I remember there being a BoF or Session at DrupalCon Denver about it...

I am hoping to discover if it is worth my time to try and rewrite this in a new framework or just clean up what I have here.

I have used both Ember and Backbone along with Drupal - but not in the way you would think.
Ember and Backbone are both fine tools to create a web application - but Drupal is not really a good tool to be used along with them. What you desire when you built a web app is something light and fast. You want it to be fast to be able to give your users the feeling if immediate  response times. You want it to be light to make it scale better. Drupal is not fast - the full Drupal bootstrap takes a long time (compared to a lot of other options) if all you want to do is provide a REST API for your web app. Drupal is PHP, which also makes it quite RAM hungry limiting the number of concurrent users.
So if Drupal is so bad for this why use it?
You should really use Drupal for what Drupal excels at - a CMS. What I've done in the past with projects that needed a web app is to use Drupal to create the CMS around the web app. To build stuff like blogs, content lists and the likes. I also created modules to define some backend stuff - like schema definitions, and other stuff where it made sense to use Drupal - because it made my development much easier.
Instead of using Drupal to create the REST API that the webapp needed - I used Node.js to create the actual REST API and other checks AJAX calls that the webapp needed to make. Node.js excels in doing just this. It's blazing fast (response times as low as 30ms for a list of objects). It's also very lightweight, since JavaScript on the server uses asynchronous actions, a Node.js server can usually handle thousands of concurrent users where PHP can handle maybe 100. In addition to that - since Node.js is JavaScript, you can reuse a lot of the code server and client side. You can literally write the same validation code, instead of having to implement both client side in JavaScript and server side in PHP. If you are going to Drupal con in Münich in a few weeks - you should consider watching the node.js presentation.
So if you are a developer, I would strongly recommend doing a similar setup, and only use Drupal for what it is really good at. If you want to make a simple webapp and you don't expect a lot of user, using Drupal as a backend could be an option if it helps your development time.

Update Drupal 8
So with the release of Drupal 8 some of the above still holds true but not in the same extend as earlier. Drupal 8 is like Drupal 7 not a light weight tool, like Node.js, Rails, Django etc. Since JavaScript apps mainly consume various services, you still should consider if Drupal is the best tool for this.
With Drupal 8 a lot of things have been improved. Services is a lot more native, with Symphony driving the request/response. Drupal 8 has a lot of interesting possibilities with with the advanced caching and all of the great features. But even with all of the greatness of Drupal 8, it still is a lot heavier than light weight applications. It's hard to tell how successful Drupal 8 can be used as a fast webservice provider.
So still, with all being said and done, my general recommendation stays the same. Being a Drupal developer, it's easy to use Drupal for everything, since we're familiar with it. It feels safe and Drupal can be used for just about anything. Remember while it's possible to use Drupal for anything, it doesn't mean that it's the best tool for everything. Doing a sound analysis and understanding the strengths and weaknesses of the tools you want to use on an IT project, will always be a great help and can help you avoid ending in a deadlocked position with a result that doesn't live up to your expectations.


View listing related nodes by taxonomy term I have a content type representing a book. Each book as a genre (SciFi, Fantasy, Thriller ...) and I would like to expose, on the page of a book some books sharing the same genre.

I created a view with a contextual filter on the taxonomy term, but I retrieved the current book so I added a contextual filter on tue current node id to exclude it.

Now I don't retrieve anything from my view.

Each contextual filter on his own his working. If I just use the contextual filter on the content id, I retrieve the list of my books without the current book. If I just use the contextual filter on the taxonomy term, I retrieve the list of my book for that genre (including my current book).

How am I supposed to proceed to have both filter working together ?

Many of the Drupal features seem magical, but sometimes there are more steps to configure to make them work.

How to use Views Preview with Contextual filters

Contextual filters are strictly linked to individual Fields. It isn't enough to use only the NID Contextual filter (in your Preview) that would then be able to "pull" all the other information, no matter if you have the other Contextual filters set up.

What you enter into the Preview field is what Drupal would take from the URL, or the specified default value as if the URL value is available.

If you have two Contextual filters, you need to enter two filter values into the Preview, one for each filter, in the correct order, separated by /.

To test the complete situation you enter a value for both Contextual filters, for example thriller/35 or 21/35 if Thriller has TID 21 and your first Contextual filter is for term ID and not term name, and 35 is the "current node" NID.

Most Contextual filters have the Exception value set to all. This is a sort of a bypass, the Contextual filter behaves as if it weren't there.

So if you have two Contextual filters and you enter all/all you will see the Views results as if there are no Contextual filters at all.

This is useful when you have to test a Contextual filter while making sure the other one isn't in the way. So you enter all/35 to see all nodes but not the current one (if the current one has NID 35). Or you enter thriller/all so see nodes tagged Thriller but the current one is still on the list.

The Views Preview field (arguments) can test only the part of the Contextual filter that has Provide default value or When the filter value IS available or a default is provided options.

Preview does help to test and configure Contextual filters more quickly, but it doesn't gurantee that you have set them up correctly for cases that don't take values from the URL, so you have to test the Block on the appropriate location anyway.


How to print username into url after user logs in? Currently, I am developing a site where I need to add the username to the URL after users log in. I am using the Login destinations module. Usually, users aren't redirected, but they stay on the page they were before logging in, with few exceptions. This unfortunately has to stay, so I cannot redirect them to users/username.

I need to add the username to the URL after users log in. For example, not logged-in users will be at content/main-article; logged-in users will be at content/main-article?username.

I tried that with the Menu tokens module, but the tokens aren't replaced. A relative URL like node/1 becomes node/1/%5Buser%3Aname%5D.

If you ask why, it is for Piwik to easily recognize logged-in users.

I am not sure how and where you append the username, but I assume that you try something like this:

$url = $current_url . '?user=name';

Instead you should try something like this:

$url = url($current_url, array('query' => array('user' => 'name')));

This will produce this URL: current_url?user=name

Another thing: You have %5B and 3%A in your URL. I am not sure, but you want to have your URL look like this: url[user:name]. Queries in URLs should rather look like I did that and how Drupal's query options creates them: url?user=name

If that does not solve it, you could post some code ;)

Cheers,
j


Views pager shows an incorrect current page I have a page view displaying a table of fields with a few exposed filters.  This page view also has a full pager (8 items per page). The view is not using AJAX, nor does it have any caching enabled (currently).

When on the view page, using the pager to navigate to specific pages, or next/last page works fine (since the pager adds the "?page=N" query argument).  However, the issue I am experiencing is that if I try to navigate from any other page back to page 1 (so the view does not pass "?page=" as an argument), the pager is "stuck" displaying the last page I was on as the current page. The results listed are correct (displays the results for page 1), it is just the pager is displaying the wrong page as selected.

On the first page of results, I click on the pager link to go to page 3; page reloads with results of page 3, and the pager shows page 3 as current page. I then click on the pager link to go to "<< first". The page reloads with the results of page 1; however, the pager still shows page 3 as the current page.

A few more details, I am using a custom theme with custom CSS to style the pager (but css should not interfere with the pager). I am not altering the pager at all in my template.php, nor do I have a custom pager.tpl.php.

Has anyone experienced this issue? I am not sure if it is specific to a views pager, or just the Drupal pager in general. I have no idea what could be causing the problem.

I am using Drupal 7.21 and Views 7.x-3.7.

I ran into this issue for a view block when I had caching enabled on the view and block caching enabled under Performance. Try disabling the page caching under Performance.


Programatically Create Nodes with Body and Custom Fields I need to write a module that will fetch remote content via an API and store it as nodes. These nodes have custom fields defined within the module. I have already accomplished this by modifying the Node Example Module.

I can add nodes via the admin end with all the custom fields, but when I'm trying to programatically create the nodes from hook_install(), the body and custom fields are not saving.

The code for creating the fields is largely the same as the example I linked. Here's the function i'm using to create the nodes:

function sm_add_mashup_item_node($remoteId, $site, $text, $image, $time){

    $node = new stdClass();
    $node->type = 'rscg_mashup';
    node_object_prepare($node);

    $node->title = "My Awesome Title";
    $node->language = LANGUAGE_NONE;
    $node->created   = time();
    $node->timestamp = time();
    $node->changed   = time();

    $node->status = 1;
    //$node->uid = 1;
    $node->promote = 1;
    $node->sticky = 0;
    $node->format = 3;
    $node->language = 'en';
    $node->revision = 0;

    $node->body[$node->language][0]['format'] = 3;
    $node->body[$node->language][0]['summary'] = 'summary';
    $node->body[$node->language][0]['value'] = 'dfg sdgdfs gsdg sdfg sdfg sdfg sdfg sdfg sdfg sdgsdf';

    // Try to set your custom field
    $node->rscg_mashup_image_url[$node->language][0]['value'] = "Too many to count...";

    echo "\n Edited: \n";
    print_r(node_load(526));

    echo "\n Pre-Save: \n";
    print_r($node);

    $node = node_submit( $node );
    node_save($node);

    echo "\n Loaded: \n";
    print_r(node_load($node->nid));

    return;

I've tried countless variations of the above.

Here is the debug output from the function:

https://gist.github.com/agroff/1c2c22920c20e3775b0d

This is a screenshot of the field list.

try using  like below

$node->body[LANGUAGE_NONE][0]['format'] = 3;
    $node->body[LANGUAGE_NONE][0]['summary'] = 'summary';
    $node->body[LANGUAGE_NONE][0]['value'] = 'dfg sdgdfs gsdg sdfg sdfg sdfg sdfg sdfg sdfg sdgsdf';

// Try to set your custom field
    $node->rscg_mashup_image_url[LANGUAGE_NONE][0]['value'] = "Too many to count...";


view content filtered by taxonomy children I`m having a view block displayed on node page. In this block i want to show only other nodes that have the same child taxonomy selected.

I tried with contextual Content: Has taxonomy term ID (with depth)

and those settings and is not working https://www.screencast.com/t/b8GJftJSanwA

The taxonomy looks like this

parent term1
- term1
- term2

parent term2
- term3
- term4

And on node are selects both parent and child.

Any ideas?

There are two parts to your question, showing only nodes that have child terms, and getting the Contextual filter to work.

List only nodes that have child terms

This part of the question can be solved by using a regular Filter Has taxonomy term and then select only the 2nd level from the list with the Operator set to is one of.

The same applies if you add a filter Content: YourTaxonomyField instead of the Has taxonomy term.

Contextual taxonomy filter

With the main filter taking care of the depth, you don't need the Depth one as the Contextual filter.

Add Content: Has taxonomy term ID as the Contextual filter. Your example didn't have it set up correctly. It should be:
    When the filter value is NOT available
    Provide default value
    Taxonomy term ID from URL
    Only tick Load default filter from node page, that's good for related taxonomy blocks
    Filter to items that share any term
    Under More
    Allow multiple values if your nodes can be tagged with more than one term at a time.

Don't forget to place your Block and adjust Block settings for the Contextual filter.


Views node author relationships with profile2 owner I have a multi user site, with Profile2 enabled. And I've set up a views block which is only displayed on the Profile2 page, and is supposed to list content/nodes authored by the Profile2 page owner.

Now I've made a similar block for the user-page, which works perfectly, using the Content:Author relationship and a Content:Author UID(providing ID from URL as the default value) contextual filer.

But I just can't figure out which relationship(s) and contextual filter to use for the Profile2 page. Now I'm completely lost and googly eyed from trying random combinations.

Am I doing something wrong, or is it just not possible to filter the Author ID from the Profile ID(i.e does https://drupal.org/node/1834920 have something to do with my issue?)? Any hints or suggestions would be greatly appreciated!

Cheers,

Matt

I managed to get around this by setting up relationships with Content:Author and (author)User:Profiles. Then setting up a Contextual Filter of Content:Author UID, with Raw Data from URL, using Path Component 2, as the Default Value.


How do I insert a user picture's thumbnail on the "Submitted by" field? I want to insert user picture's thumbnail on "Submitted by" field, which is displayed in teaser such as the following.

  Submitted by [some_user] [someuser picture's thumbnail] on xx/xx/xx

How do I do that as effortless as possible?

Hope this will help you.

In Drupal 7 you can achieve this using template preprocess functions - THEMENAME_preprocess_node.

Steps

First add default user picture, go to sites/default/files and create a folder user_pictures and add default user picture by name default.png
Now add default picture URL using admin/config/people/accounts.

Add this code in template.php

    function THEMENAME_preprocess_node(&$variables) {
      $node = $variables['node'];
      if ($vars['view_mode'] == 'teaser') { //check for teaser views
        //get author picture uri
        $author_picture_uri = db_query("
        SELECT uri FROM {file_managed} fm
        INNER JOIN {users} u ON u.picture = fm.fid
        WHERE u.uid = :uid", array(':uid' => $node->uid))->fetchField();
        $author_picture_uri = !empty($author_picture_uri) ? $author_picture_uri : 'public://default_user.jpg';
        $usr_pic = theme_image_style(
          array(
        'style_name' => 'thumbnail',
        'path' => $author_picture_uri,
        'attributes' => array('class' => 'author-pic'),
        'width' => NULL,
        'height' => NULL
          )
        );
        if ($variables['submitted'] && isset($node->uid)) {
          $variables['submitted'] = t('Submitted by !username !userpicture on !datetime', array('!username' => $variables['name'], '!userpicture' => $usr_pic, '!datetime' => $variables['date']));
        }
      }
    }

Where public://user_pictures/default.png equivalent to sites/default/files/user_pictures/default.png


On View Rewrite Results I don't see additional options like Add Read More button when checked "Trim this field to a maximum length" Can anyone help me? Because earlier this options were displayed when I checked "Trim this field to a maximum length". May be it depends on some settings?

I can't upload image to show you what I mean. But try to explain.
I have a view block which displays some articles of the content type. I have some fields of content type to display. One of them is Body. I want to trim it because it can be very long and set "View more" link to the current article. I choose "Trim this field to a maximum length" in the "Rewrite Rules" of the field but nothing happens, additional options aren't shown to me, so I can't set number of characters to display, title of "View more" link, path and etc.

My guess it is a Jquery incompatabilty. I had the same problem this morning while setting up a new site. After activating views there where no accordions and a faulty overlay.

So i set the Jquery-version in Jquery-Update Module from 1.8 to 1.5 and everything turned back to normal.

Edit: here's the issue queue on drupal.org: http://drupal.org/node/1869988


How to tell if a menu link is route: or not? Trying to theme a menu in Drupal 8, running into a case where we need to add classes on certain links.

In the case of a menu link that is route:<nolink> we need to not add any class at all.

Example:

{% if item.below and item.url %}
 {{ link(item.title, item.url, { 'class':['link', 'link--arrow']} ) }}
{% else %}
 // not a link
{% endif %}

How can we tell at this level that item.url is route:<nolink>?

Update:

Current solution so far, is there a better way?

{% if not item.url.isExternal() and item.url.getRouteName() is same as('<nolink>') %}
  {{ link(item.title, item.url) }}
{% else %}
  {{ link(item.title, item.url, { 'class':['link', 'link--arrow']} ) }}
{% endif %}

Might be able to do a toString and if it's not actually a link that will come back empty

{% if item.below and item.url and item.url.toString|length > 0 %}


hook_form_alter building dynamic textfields In hook_form_alter I am fetching data from the database. Some of the data has several textfields, lets say addresses. People can have several addresses.

How can I pass the count of rows to my form, and have it rendered with the row count?

I try to do the following in hook_form_alter

function personalinfo_form_alter(&$form, &$form_state, $form_id) {
    $i = 0;
    foreach ($arr as $value) {
        $form['personal'][$i]['address']['#value'] = $value;
        $i ++
    }
    $form_state['num_names'] = $i;
    }

And in my function personaladdresses($form, &$form_state) , where the texfields are actually build

I want to use $form_state['num_names'] to do a for/while loop to build the textfields with the addresses.

But it seems that hook_form_alter is called AFTER the for/while loop, so it will never get the correct value from $form_state['num_names']

how can I pass a value to my form function before the for/while loop?

You should use following code in the form. It will display the array structure in $form_state['values'] in form_submit.

$form['#tree] = TRUE;


View cache clear on node create I've searched a lot of this but all kind of cache issues appear not related to this. If this has already been asked I apologize.

I just want to know if this is an embedded feature or a module is needed for this.

My homepage has 12 VIEW blocks with very complex queries so you could imagine that non caching them is not an option.

Some of the views retrieve the latest nodes so my question is: when a user creates a new node, is there a way to clear the block cache on new nodes? If I cache the block for an hour, the rest of the users won't see the new node until an hour passed.

Thanks

The combination of Rules module and Cache Actions module should solve your issue.


Website consuming more memory I have nearly 150 Panel pages and different template files. I generated lot of blocks using Node Block module to be used in the Panel pages.

I guess this is causing memory issues in both MySQL and Apache configuration. Any solution for this memory issues?

My global memory_limit is 128M. Only after setting 512M in settings.php, my custom Drupal View is generating the output (otherwise, it generated a 502 error).

Is there a way so that I can set memory_limit only for my custom View?

Refer to the Changing PHP memory limits document, you can use

ini_set('memory_limit', '64M');

which should be in your settings.php file.


Drupal 6 - Core Search Module Not Indexing Node Titles Search is working fine on my site if the search includes text that is in the body of a node, but it appears that node titles are not being indexed.

I'm just using the core search module.

Is this by design in Drupal 6 or is this a bug and how can I fix it?

I was able to fix this issue by changing the Indexing throttle setting for Number of items to index per cron run from 100 down to 10.

Once reindexing was complete all node titles appear to be indexed and appearing in search.


add function on date selected through date popup field I am using Date popup module for selecting a date in a registration form.
Is it possible to fire an event on date select?

For Drupal 7, the datepicker is indeed likely to be the one from jQuery UI, and since you may not know in your own javascript if date pickers have been initialized yet, an easy way to trigger your "custom function" is to listen for selection on any date picker on the page.

  jQuery.datepicker.setDefaults({
    onSelect: function () {
      console.log('date selected');
    }
  });

Refer to the jQuery UI onSelect documentation for more information.


howto set a category for a webform/entityform question ...? I need to have students fill out ~50 questions on their studies abroad -- and show their answers on pages in drupal (form submissions are drupal content). questions can belong to 10 different categories. I'm trying to use either webform or entityform ... but coming up blank here on how to give each question an associated category Views can use.

I can use field_group to group questions under a specific category, but the field_group setting is not useable in Views. I'm aiming for a view of something like this photoshop mockup:

Any ideas are appreciated :)

I have looked into making a Views Filter for the field_group field. But field_group stores the data for a group in a serialized $data field per Group ... I dont think views as an sql-query-builder can do anything meaningful with data in that format (or am I wrong) ... ?

You can do this with the Webform Entity module. It uses Webform to create the forms but the content that is created is a full-fledged entity instead of just a serialized array in the database. That means full Views support etc.

For a category you can use a field list in the webform which can become a taxonomy field or field list in the entity that can be used as an exposed filter in Views.

To set this up just go to "admin/config/content/webform/entities/webform/" and click "Create" to create an entity webform

Then add fields to the entity:

Now, when you create a webform, the fields from the webform entity will appear on your node:

Finally, in Views, create a new view with the webform subsmissions as a base table:

and the fields attached to webforms can be used as exposed filters, fields and all other things views:


Custom theme covering up admin toolbar. I am trying to convert a template to a custom drupal 8 theme and am having trouble with it covering the admin toolbar when logged in. I tried to inspect bootstrap when installed to see what was added but to no avail.  I am trying to create a custom theme from scratch and not a subtheme.  Any help is appreciated to find out what css that I can add that will push the content down while logged in?

Thanks

Drupal 8 admin toolbar z-index value is 502 only, but the bootstrap default static navbar z-index value is 1000, I think, Increase the admin toolbar z-index value would fix the issue,

.toolbar-oriented .toolbar-bar {
 z-index: 1001 /* or more */
}

Place that code in your theme's custom css file :)


How can I register a image_style theme function in my module which only works in my theme's template? Is there a way to tell drupal that my module has a theme function which usually only works in my theme?

If I write in my theme's template.php:

function mytheme_image_style($variables) {

  // Determine the dimensions of the styled image.
  $dimensions = array(
    'width' => $variables['width'],
    'height' => $variables['height'],
  );

  image_style_transform_dimensions($variables['style_name'], $dimensions);

  $variables['width'] = $dimensions['width'];
  $variables['height'] = $dimensions['height'];

  // Determine the URL for the styled image.

  $variables['path'] = image_style_url($variables['style_name'], $variables['path']);

  // do additional stuff

  return theme('image', $variables);
}

everything works fine. If I move this code to a module it does not work, though:

function mymodule_image_style($variables) {

  // code

  return theme('image', $variables);
}

How can I use the theme_image_style function/hook in my module?

You need to use hook_theme_registry_alter() to replace the callback function for the image_style theme. Something like this should do it:

function MYMODULE_theme_registry_alter(&$registry) {
  $registry['image_style']['function'] = 'mymodule_image_style';
}


Required for Publishing For my drupal I want an article always to have an image when it's published, however the authors do no have the rights to upload images (due to copyrighting issues, I only let this be done by a few people who have access to our photo partner, just to be sure that people don't download images from google)

So I want the image field to be required when publishing, but if I put it on required, then the authors have to fill it in during the draft as well, and they don't have the access for it.

I found the following module:

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

But it requires a module "content" which I can't seem to find anywhere.
Does anyone have a suggestion for me?

Thank you very much

You can use the required by role module: https://www.drupal.org/project/required_by_role to make sure the publishers have to add an image. The downside is publishers will need to upload an image, even when not publishing.


Captcha module configuration I am using the CAPTCHA module on my user registration form. I need to alter the error message from What code is in the image? field is required. to My custom text.

Is there any hook to alter the error message, or some other way to change it?

Install the String Overrides module, search for the string, and replace it with your custom one.


rule to remove items from Shopping cart I am having difficulty creating a rule to completely remove items from a Shopping cart.
I have tried Before adding a product to the cart

{ "rules_prevent_salon_professional_xover" : {
    "LABEL" : "Prevent Salon professional xover",
    "PLUGIN" : "reaction rule",
    "WEIGHT" : "-18",
    "OWNER" : "rules",
    "TAGS" : [ "staffmy" ],
    "REQUIRES" : [ "rules", "commerce_order", "commerce_cart" ],
    "ON" : { "commerce_cart_product_prepare" : [] },
    "IF" : [
      { "data_is" : {
          "data" : [ "commerce-product" ],
          "op" : "IN",
          "value" : { "value" : [ "97", "98", "99", "100" ] }
        }
      },
      { "AND" : [] },
      { "data_is" : { "data" : [ "site:current-user:roles:5" ], "value" : "5" } },
      { "AND" : [
          { "NOT data_is" : { "data" : [ "site:current-user:roles:0" ], "value" : "1" } },
          { "OR" : [] },
          { "NOT data_is" : { "data" : [ "site:current-user:roles:4" ], "value" : "4" } }
        ]
      }
    ],
    "DO" : [
      { "commerce_order_update_state" : { "commerce_order" : [ "commerce_order" ], "order_state" : "canceled" } }
    ]
  }
}

as well as After adding a product to the cart

{ "rules_prevent_professional_subscription_purchase_cross_over" : {
    "LABEL" : "Prevent Salon professional subscription purchase cross-over",
    "PLUGIN" : "reaction rule",
    "WEIGHT" : "-18",
    "ACTIVE" : false,
    "OWNER" : "rules",
    "TAGS" : [ "staffmy" ],
    "REQUIRES" : [ "inline_conditions", "rules", "commerce_order", "commerce_cart" ],
    "ON" : { "commerce_cart_product_add" : [] },
    "IF" : [
      { "commerce_product_contains_products" : {
          "commerce_line_item" : [ "commerce_line_item" ],
          "sku" : "salon-owner-monthly , salon-owner-3month , salon-owner-6month, salon-owner-yearly "
        }
      },
      { "AND" : [] },
      { "data_is" : { "data" : [ "site:current-user:roles:5" ], "value" : "5" } },
      { "AND" : [
          { "NOT data_is" : { "data" : [ "site:current-user:roles:0" ], "value" : "1" } },
          { "OR" : [] },
          { "NOT data_is" : { "data" : [ "site:current-user:roles:4" ], "value" : "4" } }
        ]
      }
    ],
    "DO" : [
      { "data_set" : { "data" : [ "commerce-line-item:commerce-unit-price:amount" ] } },
      { "commerce_order_update_state" : { "commerce_order" : [ "commerce_order" ], "order_state" : "canceled" } }
    ]
  }
}

I tried modifying it, by Removing entity - but still have a product in the Shopping cart

{ "rules_prevent_salon_professional_xover" : {
    "LABEL" : "Prevent Salon professional xover",
    "PLUGIN" : "reaction rule",
    "WEIGHT" : "-10",
    "OWNER" : "rules",
    "TAGS" : [ "staffmy" ],
    "REQUIRES" : [ "rules", "commerce_order", "commerce_cart" ],
    "ON" : { "commerce_cart_product_prepare" : [], "commerce_cart_product_add" : [] },
    "IF" : [
      { "data_is" : {
          "data" : [ "commerce-product" ],
          "op" : "IN",
          "value" : { "value" : [ "97", "98", "99", "100" ] }
        }
      },
      { "AND" : [] },
      { "data_is" : { "data" : [ "site:current-user:roles:5" ], "value" : "5" } },
      { "AND" : [
          { "NOT data_is" : { "data" : [ "site:current-user:roles:0" ], "value" : "1" } },
          { "OR" : [] },
          { "NOT data_is" : { "data" : [ "site:current-user:roles:4" ], "value" : "4" } }
        ]
      }
    ],
    "DO" : [
      { "commerce_order_update_state" : { "commerce_order" : [ "commerce_order" ], "order_state" : "canceled" } },
      { "entity_delete" : { "data" : [ "site:current-cart-order" ] } }
    ]
  }
}

This Rule does prevent the role from being added to the user, but the product and its normal product price exists in Shopping cart on the Orders page.

I have created a rule that empty cart before adding any new item. So the only latest item will be in the cart. I think thats what you need to do. Any other conditions can be added one by one.

If you want to clear cart totally then you can use after adding product event

{ "rules_empty_cart_" : {
    "LABEL" : "Empty cart ",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "commerce_cart", "rules" ],
    "ON" : { "commerce_cart_product_prepare" : [] },
    "DO" : [
      { "commerce_cart_empty" : { "commerce_order" : [ "commerce_order" ] } },
      { "drupal_message" : { "message" : "Cart empty event executed.!!" } }
    ]
  }
}

Hope it will help!


Autocomplete won't work for entity reference field unless User > Administer Users permission is granted I have an entity reference field (users) on a node in D8, and the autocomplete suggestions won't show unless the User > Administer Users permission is granted to the role.

I'm trying to let event creators select who is presenting a certain topic, but I don't want them to be able to edit users' settings. Any ideas?

The endpoint that provides AJAX entity reference completion (system.entity_autocomplete in system.routing.yml) is configured with with requirements._access: 'TRUE' property. This should make the /entity_reference_autocomplete/%/%/% path accessible to any user.

As such, check for any module that might be modifying its permissions.


How can I make a Menu Block not auto-expand the current page's menu links? I want my menu block to decide whether to show link children based only on whether the menu link (or the entire menu block) is set to "Expanded", not whether you're currently on the same page as the link that has children. What's the best way to do this?

I'm currently doing this with hook_menu_block_alter() calling itself recursively:

function THEME_NAME_menu_block_tree_alter(&$tree, &$config) {
    if($config['expanded']) {
        return;
    }

    foreach($tree as $link_key => &$link) {
        if(!empty($link['below'])) {
            if(!$link['link']['expanded']) {
                $link['below'] = array();
            } else {
                THEME_NAME_menu_block_tree_alter($link['below'], $config);
            }
        }
    }

    unset($link);
}

But this feels super sketchy and I'm not at all confident that it's the best solution. I could break the foreach() into a separate recursive function, but that hardly seems different, other than my general icky feeling which I'm not sure there's even a logical reason for me to have.


How to interruput ajax request but keep for next possible uses? I want to add simple confirmation box for ajax delete action created via:
ctools_ajax_text_button

JS:

(function ($) {

    Drupal.behaviors.mymod = {
        attach: function (context, settings) {

            Drupal.ajax.prototype.beforeSend = function (xmlhttprequest, options) {

                if ($(this.element).hasClass(Drupal.settings.mymod.confirm_element_class)) {
                    return confirm(Drupal.t('Please confirm your action'));
                }

                return true;
            }
        }
    };

})(jQuery);

It works, but only first time. When I click delete link and choose Cancel option in modal dialog, next clicking doesn't trigger AJAX action at all on this link, so basically makes ajax action inactive.

I've solved it by:

        Drupal.ajax.prototype.beforeSend = function (xmlhttprequest, options) {

            if ($(this.element).hasClass(Drupal.settings.mymod.confirm_element_class)) {
                if (!confirm(Drupal.t('Please confirm your action'))) {
                    this.ajaxing = false;
                    return false;
                }
            }

            return true;
        }


Unit testing on windows I hope this question is not very naive, the problem is that in Drupal 8 there are several unit tests written for modules and I want to test them. But since I am on windows os I am not able to figure out by myself how to run them.Any ideas?

Drupal test runner (simpletest) has a few issues on Windows, including the inability to work with contributed database drivers (SQL Server).

As of today, exactly 3 patches are needed for this #2294731, #2748883, #2605284 (can't post the links due to not having reputation here...).

If you want to see a working example, this post explains how to run the Drupal test suite on AppVeyor that is a Windows based Continuous Integration Service.

http://www.drupalonwindows.com/en/blog/continuous-integration-and-testing-drupal-appveyor

There you will find an example cmd/powershell script with all commands needed to setup drupal and run the test suite (on windows) including commands to automatically apply the mentioned patches.


How to set up multiple occurences of same event with RNG? I am trying to find out what is the easiest way to handle this use case:

We host the same event in different cities. So event A will go to city X then city Y then city Z.

So all the information about the event is the same, just different dates and locations.

It is the same event so nobody will attend more than once. But many people will consider which city to attend the event (it may be the same distance if they go to city Y or city Z).

I assume each event should have its own RNG registration.

But what would be the easiest way to set up this thing with all the shared information?

I think you will need to create new event entities for each city, add a location field (Address?) and a date field, so your users can tell the difference. You will need to make the discovery layer before the event pages show a clear difference between your events: You could have a table view with the city and data in respective columns. Or a Google maps layer with pins for each city. Where each pin is a link to each event entity page.

If you are looking to enforce restrictions on people from attending both events, you can try RNG Conflict. However I don't think that is necessary in your case.


User can change `Moderation State` on content without having permissions to do so - Workbench I am using Workbench, Workbench Moderation and Workbench access.

I have a content manager role, who should be able to only create unpublished content, edit content that is flagged as Needs review and change the moderation state from Needs review to Draft. But as i'm testing the role, the manager can go into the draft and change the moderation state to published, or even needs review, and I do not have the permissions set for the user to change the moderation state.

At least I think. I've followed a couple tutorials and my site is configured the same, but when they go to change the moderation state their drop down select list only has the options they specified, while mine has all states available regardless of permissions.

I've tested back and forth between the roles and there is differences in the permissions and what each user role can do, but I can't set the role to allow users to moderate specific state transitions.

I literally can turn off all workbench moderate state permissions and they still have access to change the moderation state to anything they want.

As you can see in the bottom right hand corner of the image, the permissions for Moderate all content from ___ to ____ is turned off for my content manager role, and I still have permissions to moderate all content from either state. If i sign is as the reviewer role, I can also turn off all permissions and still be able to moderate the content and change the states without permissions.

No I do not have another role enabled for this user, I have cleared every cache and used different machines, same issue.

My questions are:

if I have a setting on that allow the user to moderate the states of content, what is it?

If I do not have the correct permissions enabled, what should I do to correct it?

If the issue does not lie within the workbench permissions then what should I be looking for?

Thank you regardless.

in order to display the moderation states i wanted for a specific role I had to make sure
Administer Workbench Moderation and Bypass Moderation restrictions were turned off.


How to hide webform label from email only? I'm currently using the Webform module to build a warranty support form for Drupal 7.
Here is a screen shot of the webform:

Below is the email output I receive when the form is submitted:

James Blunte.g. Joe Smith (jamesblunt@123.com) has submitted a warranty request.
Order Number: 39840e.g. 1248

I've used the right label to show examples of what to enter in the field on the webform. My question is how do I hide the label from showing on the email template? As you can see the label follows right after the value.
Here is a screenshot of my 'Edit Components' page:

I can see how it's useful for the label to appear, but in my case I don't need it in the email.
Thanks for your time!

It would take quite a bit to edit the email templates. The truth is that this is design behavior, because labels

The better way to do what you want is to put that text in the help/description field of the component and then style it with CSS. That text is not included in the email.


How can I print current user role in Twig? I'm trying to get my user role thanks to a function in my theme.theme file.

function theme_get_user_role(){
  $current_user = \Drupal::currentUser();
  $roles = $current_user->getRoles();
}

then in my view :

{% set roles = theme_get_user_role() %}
{{ dump(roles) }}

But I have this error :

  Twig_Error_Syntax : Unknown "theme_get_user_role" function. dans
  Twig_ExpressionParser->getFunctionNodeClass()

What do I miss ?

You can use below without any function. Because the User module provides the variable in preprocess for all templates: :

{% set roles = user.getroles(TRUE) %}
{{ dump(roles) }}

If you want to do anything only for the particular role then do this:

{% if 'ROLENAME' in user.getroles(TRUE)  %}

The user has the role "ABC".

{% endif %}


How to show new nodes in a Group node view for users who are not a Group member? In my Drupal 8,

Defined New User Role: Manager
Added one user into the role.

I have created a group "Group-x" with corresponding group type "Group-Type-x".

I have updated the permission(view, edit, create) in group type "Advanced outsider permissions" under role Manager.

I can able to create node in group. After creation the node is not listed in the group nodes

While checking it, the user is not a member of the group. If I add the user as a member it works fine.

Since I have some thousands of users, every time I can't add it in the group. Can anyone help me out?

Is there is any possibility to add members dynamically while creating node in the group?

As you mentioned configured the outsider permission too.

... After creation the node is not listed in the group nodes ... While checking it, the user is not a member of the group. If I add the user as a member it works fine.

I'm reading the above like "For users who are not a member of the group, I want the nodes to be listed in the group nodes also". To implement this:

you need to correctly configure the permissions for what in the Group module is called "Outsider".
you should NOT have to "add members dynamically while creating node in the group", as in your question (that's not how the Group module is supposed to work or be used).

And to configure the permissions for Outsider, you can use either of those techniques (using Group-Type-x to indicate the type of group):

Grant permissions to group role at /admin/group/types/manage/Group-Type-x/permissions, so that a user who is not member of a group, receives the Outsider permissions for that group.
If you need to distinguish between outsiders based on what roles they have in the global scope, then (and only then) you should use the "Advanced outsider permissions" page, located at /admin/group/types/manage/Group-Type-x/permissions/outsider. There you'll find all roles as defined in /admin/people/permissions (= the global scope).

With the above in mind, and looking at your question details, it seems to me that there are 2 possible solutions (depending on how you want it to work):

If all outsiders should have similar access Then Tune the Group permissions at /admin/group/types/manage/Group-Type-x/permissions.
If outsiders of selected global roles should have specific access Then  Tune the Group permissions at /admin/group/types/manage/Group-Type-x/permissions/outsider. Note that the image shown in your question (about "Advanced outsider permissions") does not show anything that you already gave some permissions to role "Manager" (there is not even 1 checkmark below role "Manager").

BTW, about your "If I add the user as a member it works fine.": that seems to confirm that you correctly configured your permissions for members of the group. But by "adding a user as a member", such user is no longer considered an "Outsider". So you really need to fix your permissions for "Outsider".

PS: If for Anonymous users you want similar access permissions as for  "Outsider", then you also need to configure those permissions via  /admin/group/types/manage/Group-Type-x/permissions.


superfish settings not visible I'm having a strange problem with the Superfish module. If I go to blocks > superfish menu > configure, I only see Pages, Pages Exclude, and Content Types. There's no other settings. I was somehow able to put the main menu into the Superfish 1 menu, but none of the settings are visible. I have the superfish library in /sites/all/libraries, and the superfish module in /sites/all/modules.

I'm using Navin, a subtheme of Omega.

Thanks for the help

The problem was that the mongodb block module disabled the normal block module. When I re enabled the block module, and disabled the mongodb block module, it worked fine.


How to combine 2 exposed filters (String and Taxonomy field) I need to create a View with a search box for my content type; the search string has to match both title OR a CCK taxonomy field. Is there a Views module that permits to do it? I've tried http://drupal.org/project/views_filters_populate but it only works with 2 string fields.

Yes,by default drupal handled this.
in Filter criteria in your views  click and hold arrow sign beside add.open   menu with And/Or, Rearrange.In this section(Rearrange filter criteria) you can determine gorup for your filter and  criteria between your filters.