Views webform filter based on the current node field value I have a Webform where it's used to get product comments. This webform is exposed in a node page and has a field that is populated automatically with a value from the current node, lets say "Manufacturer" and this is just a plain text field. So there are multiple products with the same manufacturer. For example Intel i5 2500k and Intel Motherboard Model-No-1.

I'm using the Webform 7.x-4.x for this. What I have done is use the Webform Submission Data field in Views to display the different data but now what I'm trying to do is when I go to a product, I want the view to filter all the Webform submission by the current product's manufacturer. So when I go visit the i5 2500k page, the view will list also the Webform submissions for the Intel motherboard.

So I have found the awesome way to achieve this and it's using Views Contextual Filter, Content pane arguments and Panel pane arguments(automatically added when you add an argument in Views contant pane).

In the View, add a Relationship w/c is Webform Submission Data where it's set to the Webform and field you want to get from the contextual filter.
Add a Contextual filter for the relationship you have created.
Select provide default value and choose Raw value from URL and just choose 1.
Go to the view content pane argument and click edit. You should see a field to reference the contextual filter you have created and add a label you want.
Go to the panel pane's setting you want to get the data from.
Go to it's settings and you will be presented with a field where you can place the tokens provided by you panel page.


Adding an 'All' option to a views exposed filter I have a Views exposed filter, that allows multiple items to be selected. It's based on the 'Allowed values' for a multiselect CCK field.

The exposed filter comes out looking like this:

Option 1
Option 2
Option 3

I need to add an 'All' option to the top, so that it would be:

All
Option 1
Option 2
Option 3

Clicking the All option should have the same effect as holding Ctrl and clicking on Options 1, 2 and 3. ie. return all nodes that have a value of Option 1, Option 2 or Option 3 for this field.

How can I add such an option to my widget? I'm sure it could be done through form_alter somehow, but I can't suss out how.

OK... I think I may have cracked it.

function mymodule_form_alter(&$form, $form_state, $form_id) {
  if ($form_state['view']->name == 'myview') {
    // Add our custom All buttons.
    $form['myfield']['#options'] = array("-ALL-" => t("- All -")) + $form['myfield']['#options'];
    array_unshift($form['#submit'], 'mymodule_exposed_form_submit');
  }
}

function mymodule_exposed_form_submit(&$form, &$form_state) {
  if (!empty($form_state['values']['myfield']['-ALL-'])) {
    $options = $form['myfield']['#options'];
    unset($options['-ALL-']);
    $form_state['values']['myfield'] = $options;
  }
}

So basically I add in my 'All' item at the top of the select. Then I add my own custom submit handler before Views' one.

In my submit handler, I check for the presence of the All option, and if its found, I adjust the selected options so that all options are selected except for the All option.

Seem to work :)


How to break up user roles checkboxes into groups? When editing a user in Drupal 7 (/user/NID/edit), I'd like to break up the roles checkbox options. By default, it is just one list of roles. Instead, I would like to group different roles together to make it easier to read for the admins.

Ideally, there would be a group name header, followed by a certain subset of roles and then another head followed by another subset of roles, etc.

There is no change to the functionality of the roles.  This is purely a theming exercise.

One way to do this would be to use some JS to add a header element in front of the role that starts the group.  Each role has a unique id, e.g. input#edit-roles-2.  You could use some jQuery like:

$("input#edit-roles-2").before("
My Group
");

You would have to order the roles the way you want and find the right ids.

Also, this will probably require using a custom admin theme or a module in order to inject the JS since user editing generally uses that theme and not the main theme.


Removing main content block on frontpage I'm new to Drupal 7 and I'm looking to replace the frontpage's default main content block with an equivalent block generated from Views (gaining more control over the block in doing so).

I have successfully generated the new frontpage block in Views and added it to the content section however now the homepage displays both the original and the new views block.

Attempting to remove the main content block by configuring it to not display on <front> does not work and for now the only workaround I have found is the following CSS:

.front #block-system-main {
  display:none;
}

I'd prefer a less hack-like solution. Can anyone suggest one?

Sorry, but that's not the way to do it.

Instead of creating a block display in Views, create a page display. Choose a path for your views page, for instance "home", and save the view. Next you go to /admin/config/system/site-information and change the value for 'Default front page' (it probably says "node" now) to the path you chose for your view ("home").

When you follow this approach, the main content on your front page will be the view.


How to display messages "properly" when using ajax submit? Here is a simple form:
  public function buildForm(array $form, FormStateInterface $form_state)
  {
    $form['some_text'] = [
      '#type'  => 'textfield',
      '#title' => $this->t('TextValue'),
    ];
    $form['submit'] = [
      '#type'  => 'submit',
      '#value' => $this->t('Submit'),
    ];
    return $form;
  }

  public function validateForm(array &$form, FormStateInterface $form_state)
  {
    if ($form_state->getValue('some_text') != 'Awesome') {
      $form_state->setErrorByName('some_text', $this->t('Please enter "Awesome"'));
    }
  }

  public function submitForm(array &$form, FormStateInterface $form_state)
  {
    drupal_set_message($this->t('The form was submitted'));
    $form_state->setRedirectUrl(Url::fromRoute('<front>'));
  }

And it works as expected:
Case 1A: Submit with no entry gives this (error message in default message location):

Case 1B: Submit with "Awesome" in TextValue gives this (completion message  in default message location and back to the front page of the site):

Now, I add some ajax on the submit button:
$form['submit'] = [
  '#type'  => 'submit',
  '#value' => $this->t('Submit'),
  '#ajax'  => [
    'wrapper'  => 'default_form_wrapper',
    'callback' => '::ajaxCallback',
    'progress' => [
      'type'    => 'throbber',
      'message' => $this->t('Be patient'),
    ],
  ],
];
$form['#prefix'] = '
';
$form['#suffix'] = '
';

and the corresponding callback:
  public function ajaxCallback(array &$form, FormStateInterface $form_state)
  {
    if ($form_state->hasAnyErrors()) {
      return $form;
    }
  }

And it works more or less as expected:
Case 2A: Submit with no entry gives this (almost OK, wrong location of the message):

Case 2B: Submit with "Awesome" in TextValue gives nothing (KO, no message and form is still displayed instead of front page).
And if I refresh the page in the browser, I get this:

As you can see, the location of the message area in case 2A is above form in default_form_wrapper
(to be compared to the default message area location, a div with class="region region-highlighted"):

How can I make it work as I expect?

Have the message in the "default" area?
Have my submitForm work after all?

Finally, after hours digging Drupal Answers, I made it work this way.
My ajaxCallback:
$response = new AjaxResponse();
if ($form_state->hasAnyErrors()) {
  $messages = \Drupal::messenger()->deleteAll();
  $messages = [
    '#theme'        => 'status_messages',
    '#message_list' => $messages,
  ];
  $response->addCommand(new ReplaceCommand('#messages', ''));
  $response->addCommand(new AppendCommand('.region-highlighted', $messages));
}
else {
  $response->addCommand(new \Drupal\Core\Ajax\RedirectCommand(Url::fromRoute('<front>')->toString()));
  }
}
return $response;

and my submitForm is now empty!
Nota: $response->addCommand(new ReplaceCommand('#messages', '')); is here to have a new error message replacing a previous one (without this command, all the messages are displayed one after the other...).


Can Ckeditor use relative paths for images? I am building a drupal 7 site on my localhost with ckeditor (7.x-1.13), HTML Purifier (7.x-1.0).

I realized that when my ip changes on the network, the links to the images I upload from ckeditor are broken. As I checked the html source, I saw that they are absolute urls and are using the previous ip as a part of them. Now that the ip is different, they are broken.

I need to develop the site and enter most of the content on localhost and if I cannot solve this problem, things will get complicated when I move the site to the server.

After reading a related question (D7 - Losing images when moving site location; placeholders point to old absolute path rather than relative path) I tried installing pathologic (7.x-2.11) module, checking the settings for text formats, clearing the cache with no result.

Is there a way to make ckeditor to use relative paths for images? Would it have any disadvantages?

You should always use relative paths in your content to avoid the problem you now have.

If it was me I would fix the links in the database so they are all relative. You can do so with sql queries like this:

UPDATE field_body_data
SET body_value = REPLACE(body_value, 'http://example.com/', '/')
WHERE body_value LIKE '%http://example.com/%';

Followed by:

UPDATE field_body_data
SET body_value = REPLACE(body_value, 'http://example.com', '/')
WHERE body_value LIKE '%http://example.com%';

There are two to catch the case you might have a path to the home page without a trailing slash.

You would have to do this for any text area field that might contain a hyperlink.

The Pathologic module will also help you around this issue.
You add the pathologic input filter for your relevant formats, then configure it with your old domain name.
Also add the domain name /
This will make it change relative paths to use their alias, like /node/10 to be /node-path-alias

That last feature with the aliases is very useful.

See https://drupal.org/node/257026 for more info on configuring pathologic.


What is the order of return value for field_info_instances? I've used field_info_instances function to retrieve all fields info under a content type.

field_info_instances('$entity_type','$bundle_name').

As from API page,

If $entity_type is not set, return all instances keyed by entity
type and bundle name.
If $entity_type is set, return all instances for that entity type,
keyed by bundle name.
If $entity_type and $bundle_name are set, return all instances for
that bundle.

I didn't get the third point here. what is the default order for return output by file_info_instances when $entity_type and $bundle_name given.

Any idea?

This is the query run by field_read_instances():

$query = db_select('field_config_instance', 'fci', array('fetch' => PDO::FETCH_ASSOC));

$query->join('field_config', 'fc', 'fc.id = fci.field_id');
$query->fields('fci');

// Turn the conditions into a query.
foreach ($params as $key => $value) {
  $query->condition('fci.' . $key, $value);
}
if (!$include_inactive) {
  $query->condition('fc.active', 1)->condition('fc.storage_active', 1);
}
if (!$include_deleted) {
  $query->condition('fc.deleted', 0);
  $query->condition('fci.deleted', 0);
}

$instances = array();
$results = $query->execute();

So it's safe to say there's no default order for field instances; they'll be in whatever order they went into the database, or perhaps different depending on your DBMS and settings.


How can I recreate the default frontpage view? I accidentally deleted my default frontpage view I was using on a Drupal 8 site, and I can't find how to either recreate it or which path to set on a new view to have it as front page.

How can I achieve this?

Find the file /core/modules/node/config/optional/views.view.frontpage.yml

Next import its content by pasting this at /admin/config/development/configuration/single/import


Different views with unique pagination? I have 2 block (column) with 2 different content type. I need to do a unique pagination.
How can I do?

Thx

You must disable ajax on both blocks, in the view advanced options.

In the pager settings of each block you must be sure that both blocks are using the same pager ID.

As both blocks are using the same pager ID, and the page is sent through the URL (not ajax), each block will asume that that is the page it has to show.


how to programmatically set unpublish_on How can I programmatically set the unpublish_on field(scheduler module) for a node entity in drupal 7?

$entity = entity_metadata_wrapper('node', $node);
$entity->language(LANGUAGE_NONE);
$entity->title = 'My Title';
$entity->body->set(array(
    'value' => $body,
    'summary' => $summary,
    'format' => 'full_html',
  ));
$entity->scheduler_settings->set(array(
    '#required' => TRUE,
    '#unpublish_on' => '2018-06-25 12:23:11',
    '#date_format' => 'd.m.Y H:i:s',
  ));

Follow the examples set by the scheduler module when it loads, inserts, and builds the form. Add the unpublish_on property to the node object with the value of the UNIX timestamp (of when it will unpublish). When the node is saved, the scheduler module will save the unpublish date.

$node = node_load(123);
$node->unpublish_on = strtotime("2018-06-25 12:23:11");
node_save($node);


How can we sort view result, depend on cookie set or not I have created a view to display slideshow from specific content type.

Now I have a condition that if visitor is new then slideshow will sort according to custom field "slider order".
And if user visited already then slideshow will sort according to post date.

I have tried this from "hook_views_query_alter" but I want this to be done from view only.

I applied some custom sorting in views but not working (actually I have no idea about custom sorting in views)

Please let me know the conditions.

Fields: title, description, Image

Filter: content type= slider

Sorting: Post date (desc)   [here I need your help]

For any field you want to pull a value from a Cookie you add an exposed filter, here I add a contextual filter for the field, here a node->title:

Then we configure the filter to pull a value from the URL. If none is provided we define how to find the value via PHP code. This is the secret to pulling the value from a $_COOKIE value.

Then we supply a blurb of code to read the Cookie value:


How can I clear all check boxes on failed validation? I have form with check boxes. The user checks the boxes and hits the submit button. If validation fails an error message is displayed. I also want all of the user's checks to be cleared so they can try again. Here's my code, but it does not clear the checks? Thanks.

/**
 * Defines a form.
 */
function my_form($form, &$form_state) {

    $form['alerts'] = array(
        '#type' => 'checkboxes',
        '#options' => $options,
    );

    // the rest of my form

    if (isset($form_state['clear_checkboxes'])) {
        $form_state['values']['alerts'] = array_fill(0, count($form_state['values']['alerts']), 0);
    }
    return $form;

}

/**
 * Form validator.
 */
function my_form_validate($form, &$form_state) {

    // if validation fails set error message

    $form_state['rebuild'] = TRUE;
    $form_state['clear_checkboxes'] = TRUE;

}

You can unset your field in the form .Check for the array which has field array.

unset($form_state['field_checkbox']['und'][0]['value']);


Showing both original base price and calculated price (inc. taxes), when using two price fields and rules Building a webshop for customer with Drupal 7 + commerce. I've defined two price fields for commerce product entity:
1) base price (excluding tax) that is wholesale price
2) retailer price (excluding tax)

There is a rule with a condition "current user has role reseller" and action that sets retailer price as base price. This works perfectly, showing different price for logged in resellers. Also, there's a rule for tax calculation.

Now, the problem comes when trying to show both wholesale price and reseller price on the product pages including taxes. Because prices are overwritten by rules, "original" base price is not available anymore. I've tried to figure out how to do this programmatically since "Commerce price savings formatter"-module does not work with this kind of price structure. (tested price savings formatter module with discount rules, we are also using and it works well)

I'm quite lost where this should be done, should I change it in product node template (or template.php with some hook)? I can find the the original price without tax by going really deep in the content array. But I would need the tax too, at least the percent so I can do the calculations.

Any help, even tiny hints are much appreciated!

EDIT:
The working rule that sets the retailer price is defined as follows:

EVENT:
 * Calculating the sell price of a product

CONDITIONS:
 * User has role (=retailer)

ACTIONS:
 * "Product has special price"-component
   * Parameter:[commerce-line-item] (named as "product line item")

Then I have custom component "Product has special price"-component

CONDITIONS:
 * Data comparison: [product-line-item:type] = Product

ACTIONS:
 * Set the unit price to a specific amount
   *  Parameter:  [product-line-item]
   *  Amount: [product-line-item:commerce-product:field-retailer-price:amount]

I have been thinking of this, but can you delay the setting of the price?

I suppose you are currently overwriting the price when the user is viewing the node? Can't you set the correct price when the product is added to the cart? That would allow you to show both prices next to eachother.

Optionally if you don't want regular users to see the wholesale price, use a module like Field Permissions to prevent certain roles from viewing certain fields.


hook_form being called twice I have a simple form inside a block:

function mymodule_block_view($delta = '') {
      switch($delta) {
        case 'some_name':

          $block['subject'] = t('title');
          $block['content'] = drupal_get_form('mymodule_form');
      }
      return $block;
    }

When I submit the form, the mymodule_form() method gets called twice. In the first run the values I have put into the textfields are correctly stored in $form_state. In the second run, they are not there anymore. Does anyone have an idea why this is the case?

What I would like to do is very simple: I'd like to retain the values I have put into the textfields, so when the form gets submitted, the page gets reloaded, and the values I gave are the new default_values of the form. I know how to do this in the code, but as I said, the form_state is empty in the second run, thus the form takes the 'default' default_values.

Why does mymodule_form() get called twice?

Drupal redirects after form submissions. So you are effectively making two requests, one for the form submission and one as a consequence of the redirect.

See Wikipedia: Post/Redirect/Get for details about why Drupal redirects after form submissions.

Set $form_state['redirect'] = false to prevent redirection.


Text format field missing for minimal installation I installed minimal version of latest stable Drupal 8. It does not include any HTML text formats so I had to add my own custom Full HTML text format next to default Plain Text.

It also doesn't include any content types, so I had to create my own Basic page content type with Body field.

When adding/editing content under body field it doesn't show the Text format field drop-down and I cannot select neither out of two formats, it just loads up some default CKEditor.

Also with minimal installation it doesn't include Administrator role. So I did create my own custom Administrator role and gave it all permissions, including under Filter, but still no effect, even though I'm user/1.

How do I get Text format working/displaying on Minimal installation?

Look in the standard profile:

core/profiles/standard/config/install

In comparision the minimal is rather empty:

core/profiles/minimal/config/install

You can take this yml-file for the text format, put it in the sync-folder and import it:

core/profiles/standard/config/install/filter.format.full_html.yml

But probably you need much more configuration, did you consider to start over with the standard profile?


How does the tmp folder work? It stores lots of junk files and takes space My tmp folder is set to /sites/default/files/tmp/ and I checked what's inside and for example there is folder inside called /update-cache-b2903cc4/ it keeps all modules in .zip that I installed via 'Install from a URL'. So why are those modules .zip files are kept there in tmp folder, isn't it a waste of storage? I don't really like it when the site is full of unnecessary files.

Am I supposed to delete these by myself all the time?

What does tmp mean?

Tmp is an abbreviation of temporary. So the tmp folder is a folder intended for temporary files. Every operating system uses such a folder, and in facts needs it. So does Drupal. Drupal by default attempts to store files in your operating system's tmp folder. On Linux this is /tmp, on Windows C:\Windows\Temp. You can check and change this setting in Configuration > Media > File System. If your temporary directory is set to one of these standard paths, you should assume it is not only Drupal's files, but files of the operating system and several other programs (Apache sessions, Drush downloads, installation packages).
If it is on a custom path, or in the case of the OP: /sites/default/files/tmp/ (Drupal's fallback path) it should contain only Drupal files.

So what kind of files does Drupal store there?

In general Drupal stores all uploaded files in the temporary folder first. If something goes wrong (eg. the connection with the client is interrupted) there is a corrupted file on the server. Keeping these files in a temporary folder and only moving them after the whole file was transferred, ensures there will be no damaged or unneeded files in your public files directory sites/default/files.

This also includes modules and translation downloads, some js files (probably used in aggregation) and several other files.

There is no real list of all files Drupal stores in tmp, because contributed modules might choose to store a file there as well. Possible use cases for this could be file generation on demand (eg. a module that packages a custom selection of files into a zip file and offers it as download. It is unlikely the same file will be used more than once and there is no real benefit in storing it).

Can I safely remove the files?

Well yes and no... The idea of temporary files is that they are, well... temporary. They are generally used directly after they are created and might no longer be needed. But since all programs can write to tmp, it is a reasonable assumption not all programmers played by the rules, or some files might in fact still be in use.

Should I remove the files?

Drupal performs several cleanups on its own during cron runs (assuming cron is set up and working). Uploaded files that were not saved permanently will be removed during system_cron().
Old modules downloads are handled by update_delete_file_if_stale() (via update_clear_update_disk_cache() and update_cron()).
These cleanups are set to clean up files older than DRUPAL_MAXIMUM_TEMP_FILE_AGE (6 hours), but the actual time depends on the cron interval. (If cron only runs every 12 hours, it can take up to 12 hours before the files are removed).

In most cases there should be no need to remove the files manually. If in some cases cron doesn't remove (all) files, you might attempt to remove them by hand. But make a backup first!

If your folder is shared with your operating system's folder, you might want to use your operating system's tools for it (Windows users can clean the temporary files with the Disk Cleanup tool. (Some Linux distributions clean the folder during system reboot, some don't.)

When the tmp folder is on a custom (non-operating system) path, as is the case with the OP, it should be relatively save to empty the folder by hand. Make sure your webserver (Apache, Nginx) is stopped, so no user of cron task will be touching the files. Then delete the stale files (older than 6 hours) manually.

Conclusion

If your system is setup properly and cron is working, there should be no need to clean these files, as they are removed automatically. If it doesn't happen, you can remove them manually, but keep above conditions in mind. It might still go wrong, so always make a backup!


View field with JavaScript code in it I have content type which has text field. Each node has its own javascript code which is set in to the text field. Text field is PHP Code format.

When I add this field to Views block site load ONLY the javascript in that text field. Whole other drupal content is not loaded. When I remove this field from views then site works normally.

This script works on full node but not in the Views. What can cause this? What ways to fix it?

Script is from Tradedoubler (third party advert) :

<script type="text/javascript">
  var uri = 'http://url.com' + new String (Math.random()).substring (2, 11);
  document.write('<sc'+'ript type="text/javascript" src="'+uri+'" charset=""></sc'+'ript>');
</script>

Try using the Views PHP module. First, make the field with the javascript be excluded from the display (check the box for this, don't delete the field). Then add a php field to the view, and then have it print the field with the javascript via the replacement pattern. You can also use PHP to manipulate it, write more javacript, etc. This is the only way I have found to add javascript to view rows.


How to create a list of vocabulary names for a widget? I would like to create a customizable filter widget that can be used to filter a view on a page.  One type of filter uses taxonomy terms. While I can easily create a list of terms, I find I cannot create a list of vocabulary NAMES to choose from for the filter.

Ultimately, I'd like to iterate through the terms of the chosen vocabulary name and display that list of terms.  So, in summary, create a widget that users can choose from a list of vocabulary names.  Once that is selected, display the list of terms of that vocabulary name on the page.  Is this possible?

I've tried so many different ways using views, entity references, etc but cannot get a list of vocabulary names in a field.

As the vocabulary is an entity, you can find his name id (taxonomy_vocabulary) in Drupal\taxonomy\Entity\Vocabulary.

To load all the available vocabularies you can use the following code:

$vocabularies = \Drupal::entityTypeManager()->getStorage('taxonomy_vocabulary')->loadMultiple();

To create the dependent taxonomy terms select I recommend you to take a look at the ajax examples in the Examples for Developers module.


How to specify a permission as an access argument? As I understand for a menu access argument I must specify a permission.

So, let say there is a permission for "Profile: Create new content" that is enabled for authenticated users, and I would like to use this as my menu access check.

This is how I put it in my menu callback?

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

  $items['play'] = array(
    'title' => 'Play',
    'page callback' => 'play',
    'access arguments' => array('Profile: Create new content'),
    'type' => MENU_CALLBACK
  );

  return $items;
}

This does not work though, so how do I get the permission name used by the system?

This is based on Drupal 6 but I doubt it has changed.

access arguments returns true if the user has the permission specified in the array, however, it does not make sure to create that permission if it doesn't exist. If you want to use a module specific permission you need to define it using hook_permission (hook_perm for D6). If there already exists a permission that will suit you needs you can simply call that instead, though.


Created a Block of 'Unrelated' Nodes There are plenty of articles on creating 'related content views', but what I need is a view of all content tagged with different terms of a specific taxonomy.

I've tried creating a view with the Taxonomy Term ID Contextual filter set to Exclude under 'More', but I'm still getting related content.

This sounds like the same question I asked here, and for which I got a "sorry, can't do" kind of answer:

How can I show a list of terms from a specific vocabulary that are not assigned to the current node

What you'd be asking SQL to do is check every term in the vocabulary to see whether it is assigned to the current node. The performance overhead of that is potentially huge (imagine a vocabulary with hundreds of terms, and a node with just one of those terms assigned).


Omega Theme Renders a Container inside of a Container I currently have a view listing a set of products via rendered entities as Teasers. However the Omega Theme is taking each teaser and adding the container-24 class to it eliminating the ability for me to have the teasers display inline. Below is an image attached, why is Omega doing this?

http://i.imgur.com/H1izEsp.jpg

Yeah, I have seen that before with Omega 3 - its presuming too much :)
What you can do to work around this, is get the node template file, and create a template file for a teaser mode, and reference it in template.php. One sample of doing that is here: What is the template suggestion for node 'teaser' view mode?


How to theme the register page (mysite.com/user/register) How to theme the register page (mysite.com/user/register). I'm using the Omega theme.

Where do I find the template page user-register.tpl.php ?

I don't need to add fields to the form, I just to theme this page.

To theme that path via a template file, you can use:

page--user--register.tpl.php

copy page.tpl.php to that filename, clear theme registry cache to apply.

Note, you may need to copy page.tpl.php from your base theme to your sub theme /templates folder to bring it into scope.


Checkbox whether display Node title How can I add a checkbox when I create a new page to decide wheter the user want to display the node title or not, as like the hook_block_configure() function ?

There is now also this module:
https://www.drupal.org/project/exclude_node_title


Get field value directly from inside views-view-list.tpl.php Inside views-view-list.tpl.php there is a loop like this:

<?php foreach ($rows as $id => $row): ?>
  <li class="<?php print $classes_array[$id]; ?>"><?php print $row; ?>

<?php endforeach; ?>

I want to be able to access the actual values of the fields inside each item, rather than passing off the rendering of the html to views-view-fields.tpl.php.

In pseudocode, I would like to do this (THIS CODE DOES NOT WORK):

<?php foreach ($rows as $id => $row): ?>
  <?php print $row->$fields['field_my_field_name']; ?>
<?php endforeach; ?>

<?php foreach ($rows as $id => $row): ?>
  <?php print $row->$fields['field_my_second_field_name']; ?>
<?php endforeach; ?>

Would I actually use the $row object, or would I use something else?

took me a while to work this out so sharing the solution i used.

<?php foreach ($rows as $id => $row): ?>
    <?php print $view->render_field('field_my_field_name', $id);?>
<?php endforeach; ?>

<?php foreach ($rows as $id => $row): ?>
    <?php print $view->render_field('field_my_second_field_name', $id);?>
<?php endforeach; ?>


Alternative to the Regcode module? I'd really like to use the Regcode module, but it is not very well maintained and with the progression of depending modules like VBO it becomes rather unstable imho.

So, i'd be glad if anyone can point me in the right direction to solve these problems:

Restrict user registration to "somehow invited" (preferably code-based) people only.
Manage the invites in backend.

I'd also like to know if there's maybe a commercial module that fit my needs...

I think you'll need to do some custom magic voodoo ;)

I built a similar site earlier this year:   The client provided a list of users (with their email addresses) in an Excel spreadsheet.  I created a new column with a unique 8 character registration code for each user.  I then imported that file, including the code, as new users.

The registration code was saved as a plain-text field in their user profile.

Create a custom user login form that only requires the registration code,  mail out the reg codes.


Entity UUID and uniqueness We have a multisite install that will have a few shared blocks. As we spin up more sites we'd like to just take the yml file associated with the block and add it to the config directory of the new site.  The issue though is the UUID.  Do these need to be unique across the entire install or just within a sub-site?

A multisite is really just multiple sites that happen to share the same code base. Unless you do crazy things with sharing prefixes (which I would really, really recommend against), the fact that you are sharing code is completely irrelvant to the running site/configuration.

So, there is no such thing as sub-sites. Just sites. And it doesn't matter if the have the same UUID's in different sites.


I can't render default values on form element in theme_table() For the last few days and some of last week I've been trying to fix up the interface of a page we have on one of our modules since it was difficult to use. I decided to take this data and just display it in a table so that it's simple and organized by column.

Here is a very basic recreation of the code.

function _ss_menu_zone_test($form, $form_state) {

  $formfield = array(
    '#type' => 'textfield',
    '#default_value' => '10' // default value set
  );
  $formselect = array(
    '#type' => 'select',
    '#options' => array(1,2,3,4,5,6),
    '#default_value' => 3  // default value set
  );

  $tablesort_headers =array(
    array('data' => t('Price'), 'field' => 'price'),
  );

  $tablesort_rows = array(
    array('price' => 'test row format 1'), // example of basic string row
    array('price' => array('data' => 'test row format 2')), // example of simple string but using data
    array('price' => drupal_render($formfield)),
    array('price' => array('data' => $formfield)),
    array('price' => drupal_render($formselect)),
  );

  // render the tablesort of menu items.
  $form['category_' . $tid]['items'] = array(
    '#theme' => 'table',
    '#header' => $tablesort_headers,
    '#rows' => $tablesort_rows,
    '#sticky' => TRUE,
    '#attributes' => array('id' => 'zone-items-' . $tid)
  );

  return $form;
}

In this example I have one column for the test data and a couple rows to show the differences. The primary issue I've run into here is if I try to add a form API textfield to a cell somewhere it drops value for the #default_value. the field renders correctly with any other key I've specified.

Does anyone know how to go about getting this #default_value to actually populate the field like it does EVERYWHERE else in the Form API?

In FAPI (and renderable arrays in general), keys starting with a # are considered properties - so not renderable elements. This means their children aren't processed for content properly.

There are several methods to do what you want, but the easiest is probably references. In your specific example, it would look like this (I've trimmed out some stuff to make my changes more clear):

function _ss_menu_zone_test($form, &$form_state) {

  $tablesort_headers =array(
    array('data' => t('Price'), 'field' => 'price'),
  );

  // render the tablesort of menu items.
  $form['category_' . $tid]['items'] = array(
    '#theme' => 'table',
    '#header' => $tablesort_headers,
    '#rows' => array(),
    '#sticky' => TRUE,
    '#attributes' => array('id' => 'zone-items-' . $tid)
  );

  $formfield = array(
    '#type' => 'textfield',
    '#default_value' => '10' // default value set
  );

  //We need to include the field in the form so it's rendered. This wont display because we're using #theme => table.
  $form['category_' . $tid]['items'][] = array('formfield' => &$formfield);

  //These are your rows, note the byreference on the formfield.
  $tablesort_rows = array(
    array('price' => 'test row format 1'), // example of basic string row
    array('price' => array('data' => 'test row format 2')), // example of simple string but using data
    array('price' => array('data' => &$formfield)),
  );

  //Add your rows to the table.
  $form['category_' . $tid]['items']['#rows'] = $tablesort_rows;

  //Since we used references we want to unset the variables we created.
  unset($formfield);

  return $form;
}


Conditionally Hiding / Stopping a view from display I have two views, for taxonomy pages, one displays the products of the current term (using contextual filter "Content:has taxonomy term"), and other display the sub-categories of the term (using contextual filter "Taxonomy term: Parent term").

My problem is that I want to display product view only when I does not get any result in sub-category view.

I would use a block, then create a tpl.php file for the block and inside it put

<?php

$view = views_get_view('view_name_of_subcategory');
$view->set_display('block_1');
$view->execute();
        // results are now stored as an array in $view->result
$count = count( $view->result );

if ($count = 0) { print views_embed_view('view_name_of_products','block_2' }
else { print $view->render(); }

?>

Replace block_1 & block_2 with your actual machine name, you can find it here (see picture)

PS if ($count = 0) does  not work try if ($count = null)


Content Template admin interface for custom content type not displaying I'm trying to work with a content template for a custom content type. The admin interface isn't loading... well, it's not fully loading. Here's what I get:

It should, of course, look something like this... which is another custom content type that I created whose content template loads just fine:

This content type is fairly straightforward. I don't think I've done anything unusual with it... so I'm stumped. Any ideas?

It was PHP file size limit. Weird. It was increased and everything went back to normal.


How can I list only modules which need an update? Drush 8.1.9 & Drupal 7.53.
What I'm looking for is a command like drush ups but without all the modules that are [OK] – so when used with an alias of several sites I don't have to scroll through loads. So all I get is:
aliasname
Name                               Installed Version  Proposed version  Message
     Metatag (metatag)                  7.x-1.19           7.x-1.20          Update available
     Views Slideshow (views_slideshow)  7.x-3.4            7.x-3.5           Update available

I found drush vset update_check_disabled 1 -y && drush -n -p up – it works but here's a sample output, which is not what I want.
media_ckeditormedia_ckeditormedia_ckeditor
views_slideshowmedia_ckeditor

I also want the version info. Is there anything I can do to get a list of all modules which need an update including the version info?

Drush puts that [ok] information out on stderr. So you can actually just dump that by using:

drush ups 2>/dev/null

which for me gave:

 $ drush ups 2>/dev/null
 Name    Installed Version  Proposed version  Message
 Drupal  8.2.5              8.2.6             Update available


How to add the node settings "Exclude node title" to a field group? Since the module does not provide an entry in the manage form settings, how to move "Exclude node title" to a field group in Drupal 8?

In the form_alter function:

  if (isset($form['exclude_node_title']) && isset($form['title']) && isset($form['#group_children']['title'])) {
    $form['#group_children']['exclude_node_title'] = $form['#group_children']['title'];
  }

this will move the exclude title into the same group as title is in


How can I create a custom landing page for a specific taxonomy term? How would I be able to have a customisable page where in it will be a landing page for special taxonomy terms and will display the related articles of a specific taxonomy term.

For instance, mywebsite.com/myspecialtaxonomyterm will display a PAGE, wherein a list of articles related to the tag myspecialtaxonomyterm is displayed, beside it is a custom widget as the sidebar and on top of it is a custom block which may contain videos or banner image. Can this be done by the Views module alone or should I create a module for this to be done?

NOTE: This page will be set to be the landing page of a specific tag, based on my example above. I am really confused on how to approach this.

To display only node content with a specific taxonomy term checked, add Content: Has taxonomy term to the Filter Criteria of your view. Once you add the filter, you will be prompted to select your taxonomy term vocabulary as well as the term you wish to filter your view by. Once completed, you will only see content associated with the desired term.

If you're using Panels, as your post's tags indicate, you can create your landing page using Pages (comes with panels). Make sure the view you create is a block, not a page, and it will be easy to plug into any panel.


Correct AJAX practices I have got content types called 'Online Discussion', henceforth referred to as OD and a content type called 'Online Discussion Reply', henceforth referred to as ODR. Having Entity References (drupal.org/project/entityreference) to eachother.

When one ODR is created (via a front end custom form) it references its "parent" (the OD whose page it was created) and via Corresponding Entity References (drupal.org/project/cer) same thing happens the other way around.

In an OD's page, via theming, a specific amount of referenced ODRs are shown, the 10 latest. They are presented as rendered entities without any View's  or Panel's involvement at the moment but I am open to changing that if necessary.

Each ODR has its own instance of the reply form, enhanced with quoting functionality.

Also, the ODRs can accept comments from specific roles, via a custom front-end form as well.

The requirements:

1) I need some way to load previous (all or in batches) replies with AJAX. Currently I am firing a jQuery ajax callback to a view page that fetches the previous ODRs accordingly and I inject their HTML into the DOM. That works, but in a test-case scenario with over 200 nodes referenced, that seems to take some time

2)I need a way in which after a fixed time interval to look for new ODRs and append them giving the OD a 'livelike' behavior. At the moment I do this in the same way, and it seems to work pretty ok.

3) I need some efficient way to apply Drupal Behaviors to the new elements that come to the site so they have their contextual links functional etc. I've done that using Drupal.attachBehaviors(context); but there are issues.

The issues so far:

I. Multiple instances of the same form on the same page.
Although Drupal handles drupal_html_id() on the initial OD page load, the way I use AJAX breaks the ID uniqueness. If for example I have 10 forms in my initial load, and I bring 2 more via AJAX, IDs for the first 2 will be repeated since I grab the HTML the view generated as a whole.

II. Performance issues in a 'Load all previous ODRs' case. Pretty self explanatory. Pulling 200+ entities and injecting their HTML is pretty heavy lifting.

III. Drupal.attachBehaviors - when using AJAX like the way I described, the HTML for the contextual link is produced just fine. Problem occurs with the javascript involved into it. So after some hours of researching, since there is very little documentation on this, I stumbled upon Drupal Behaviors which pretty much solved that issue, but gave me a new set of problems to deal with:

onLoad events, now in a behavior, run each time an AJAX event is fired causing multiple event binding (unbind before bind solution at the moment)
some onLoad events, like the collapse of the textareas the multiple forms use, cause usability issues. For example, you are typing a reply or comment, a new ODR comes into the site via the recurring ajax call and collapses your textarea.
pretty messy and incrementally difficult to manage code to make sure I handle all the possibilities via jQuery

So, finally, the question:

What are the best practices in a Drupal context with which to achieve the desired described result?

First of all, you have way too many questions in here. I recommend breaking this problem up into smaller chunks and trying to solve them each, rather than dumping this whole novel into stack exchange for someone to solve all your problems for you.

Maybe that sounds harsh, but there's a reason you don't have any replies yet.

I can point you toward the Drupal's once function, which will help you address at least your onLoad conundrum. (Hint: you should not be using onLoad, ever.)

In general if you're building a site in Drupal, and you can't find a module to do what you want, and you find yourself writing a lot of PHP or javascript or custom what-have-you, you might want to consider a new approach.

There are lots of front-end frameworks that probably offer libraries to accomplish the behavior you're trying to achieve. Try finding one that comes close to solving your problem, performs well under load, and then adapt it for your use.


How to add a payment gateway with two different accounts? I want to add two different accounts for a single gateway . Depending  upon Product_id or product_sku value it should use a corresponding account for payment.

How to do it? I have used the Drupal Commerce module.

Use multiple payment method rules for the same payment gateway and add conditions to them that check for the existence of particular products in the order's line items. How you do that is up to you and what your product catalog is like.


How to change Read more option in the front page of drupal 7? I am using drupal7. If we published a content to "promoted to front page". It will act as from the default front page view. I want to change the "Read More" option as "More". Where i can change the option? Please help me?

Thanks,
Sathish

function MODULE_node_view_alter(&$build){
  if( isset($build['links']['node']['#links']['node-readmore']['title']) )
    $build['links']['node']['#links']['node-readmore']['title'] = t('More');
}

You can apply more checks in order to change the link title for some special scenario or for some specific content type.


CSS Junk files in the css folder What are all those junk CSS files in site/files/css with names like css_ZFCUUB6IIfaVQ-erWDr0M0Na1JbxEsU-8zjQrWAtrbU.css? There are hundreds of them.

How do these get generated over time? What do they do?

They aren't junk files, they are aggregated files are generated when you have CSS aggregation turned on. They make your page load times faster, as multiple files are aggregated into a single file, meaning less files have to be downloaded to the browser.


Unable to use Composer (for Drush) on Bluehost - install problem I apparently successfully installed Composer (for use with Drush) on bluehost. See messages below. It does not work, however. When I type composer.phar I get nothing or "command not found" among other error messages. See below.

I am a newbie so it may be that install worked just fine, but I just don't know how to properly execute composer to make sure it works.

I am using instructions found at http://avantidevelopment.com/install-composer-on-bluehost/ & https://www.drupal.org/node/2366283.

columck5@columbiablooms.org [~/bin]# cd ~
columck5@columbiablooms.org [~]# mkdir ~/common
columck5@columbiablooms.org [~]# cd ~/common
columck5@columbiablooms.org [~/common]# curl -sS https://getcomposer.org/installer | /ramdisk/php/54/bin/php54-cli
#!/usr/bin/env php
All settings correct for using Composer
Downloading...

Composer successfully installed to: /home5/columck5/common/composer.phar
Use it: php composer.phar
columck5@columbiablooms.org [~/common]# which php-cli
/usr/bin/php-cli
PHP Version     5.4.24

columck5@columbiablooms.org [/ramdisk/php/54/bin]# cd ~/common
columck5@columbiablooms.org [~/common]# ls -l
total 1164

drwxr-xr-x  2 columck5 columck5    4096 Oct 29 08:37 ./

drwx--x--- 21 columck5 nobody      4096 Oct 28 09:15 ../

-rwxr-xr-x  1 columck5 columck5 1176136 Oct 29 08:37 composer.phar*

-rw-r--r--  1 columck5 columck5     575 Oct 29 08:38 error_log

columck5@columbiablooms.org [~/common]# composer.phar

-bash: composer.phar: command not found

columck5@columbiablooms.org [~/common]# composer
columck5@columbiablooms.org [~/common]# php composer

Status: 404 Not Found
Content-type: text/html

No input file specified.

columck5@columbiablooms.org [~/common]# php-cli composer.phar
columck5@columbiablooms.org [~/common]# php-cli composer

Could not open input file: composer

Content-type:text-html means your script is running from CGI instead of CLI.

so try to fix your install so that the PHP in the path uses a CLI

One simple way to do is to write php path to php-cli instead of php-cgi.

# .bash_profile
export DRUSH_PHP=/ramdisk/php/54/bin/php54-cli


Hiding field groups during registration I worked out a way to hide fields with field permission module on registration. But have not found a way to hide whole field groups. Is there a module or a particular API which can help with this problem.

you can do this with using hook_form_alter

You can do something like this:

function YOUR_MODULE_form_alter(&$form, &$form_state, $form_id) {
    if($form_id == 'your_form_name') {
        //do what ever you want
        //$form is an array of form elements, to delete some of them you can just do:
        unset($form['your-element-name']);
        //or and I think it is more "drupal way" to do things you can hide an element using hide function, e.g.:
        hide($form['account']);
    }
}


Reinstall a patch with composer - update one module only Can I update a patch without running composer update ? In other words: can I update one module only?

Yes, use the following:

composer update --prefer-source drupal/menu_block


Parse feed items into nodes, but also get full html from link by scraping the site I am using feeds to create nodes from an rss feed. I also use feeds imagegrabber to grab the image from the webpage.
But I can't seem to follow the links to each item and scrape it.

The feeds usually only show the teaser text, but I want to scrape the page with the full text and save it.

Can anyone explain to me how this is done?

Here is an example feed:  http://feeds.washingtonpost.com/rss/homepage

This doesn't seem possible at the moment, so I used Yahoo Pipes to create a new rss feed based on the original scraped the full page for each rss item and sustituted the description with the content of the full article.


using drush php-eval db_query() are there differences with db_query() from code? I think the answer should be easy but I can't find it.

maybe I've been put in the wrong direction finding sites telling how to clear my flood table like so:

drush php-eval 'db_query("DELETE FROM `flood`");'

But I think is should be like this so it also works for prefixed tables:

drush php-eval 'db_query("DELETE FROM `{flood}`");'

Or does db_query() works different in drush php-eval?
As far as I know it just executes php but does it has the drupal 'library' available or not?

Now I could just try and see what happens but I think it's good to really know if there's a difference or not in running db_query() from drush or from code.

I don't know this for definite but conceptually speaking, if Drush didn't use a standard Drupal bootstrap to perform these tasks it would have to re-implement all of that functionality itself.

Drush uses your site's settings.php file for the database connection, which leads me to believe it will also have access to things like $db_prefix.

I think it's safe to say exactly the same thing is happening when you run db_query() from Drush as if you run it from any other bootstrapped instance of Drupal.


Should I create a role for every user? On Drupal 7 I have tested many modules, because I simply want in the user view some fields which are public and others can only see friends (user relationship or flag friend, ...).
would be nice if I had a fieldgroup 'open' and 'friends' with the correct permission.

Because it is not running yet, I want by register a new user creating and assign a role named role_userID. These I want do with a rule but I can't do it... After this I can give every friend of this person his role, that they can see the fields.

Or is not a good idea?
How can I do that?
Thanks
Thomy

I seem to understand that for every user with "uid" = "userID", you want to create 1 role like "role_userId" ... That means if you have dozens of users (only), you have dozens of roles. Not to mention that you have hundreds (or thousands?) of users if you'd have hundreds (or thousands?) of roles ... IMO that is not a good idea. I'm not sure what exactly you're up to with that "user view some fields which are public and others can only see friends (user relationship or flag friend, ...)", as in your question, but it does seem to be related to access permission somehow.

Have a look at the Group module, which allows for creating arbitrary collections of your content and users on your site, and grant access control permissions on those collections. The Group module creates groups as entities, making them fully fieldable, extensible and exportable.

In your case you could have 1 Group "Type" (eg: "User Groups"?), and create 1 group for each user. Think of a Group Type as equivalent to a Content Type, and a Group (of a specific Group type) as equivalent to a node of a specific Content Type). You'd probably come close to having something with a 1-to-1 relationship between a specific user and Group permissions related to that user (whereas Group permissions is not the same as standard Drupal permissions ...).

Also, since Group is fully entity based, it integrates perfectly with Rules also. With that in mind, you could use Rules to capture Rules Events about user relationship or flag friend (as in your question), and then trigger Rules Actions to manage various access levels to the Group designated to that user. Important to realize: you wouldn't need like dozens (or hundreds/thousands?) of "roles".

For more details about the various roles and permissions, refer to my answer to "What are the various roles supported by the Group module?".

Resources

Community documentation for the Group module.
Video tutorial "How to use the Group module in Drupal 8 to manage editorial access control to different areas of a web site".


How to hook into field creation (form successfully processed)? I need to act after field has been created (new db table).
Actually I need to use data from the first field form:
field-ui-field-storage-add-form
So ideally I need to hook on this form being successfully processed (and its data).
Is there any way of achieving it?
Something like old hook_field_storage_create_field

Field storage configs and field configs are config entities hand have the standard hook_ENTITY_TYPE_presave/insert/update/delete() hooks.

/**
 * Implements hook_ENTITY_TYPE_insert() for 'field_storage_config'.
 */
function comment_field_storage_config_insert(FieldStorageConfigInterface $field_storage) {
}


Get the node count by its node type and node status in Drupal 8 I was wondering how to get the number of nodes I have, filtered by the node count and status.

For example: how many published articles I have.

I was thinking about using Entity Query to get the node count.

This function will give you the count of the node by its status and content type.

Example: if nodeCountState(1,'article');

the count of number of nodes in the article content type which is published will be displayed.

 public function nodeCountState($status, $type) {
    $query = \Drupal::entityQuery('node')
            ->condition('status', $status)
            ->condition('type', $type);
    $result = $query->count()->execute();
    return $result;
  }

Hope this help some one :)


How do I send a variable value from my form to another page using the POST method? In the first page I have the following code:

$form['message1'] = array(
  '#markup' => $this->t('Check Your Details once again !!'),
);

$form['candidate_name'] = array(
  '#type' => 'textfield',
  '#title' => t('Candidate Name:'),
  '#required' => TRUE,
);

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

$form['submit']= array(
  '#type' => 'submit',
  '#value' => t('Proceed To Pay'),
);

return $form;

function submitForm(array &$form, FormStateInterface $form_state){
  drupal_set_message($this->t('@candidate_name! Wow! Nice choice! Thanks for telling us!', array('@candidate_name' => $form_state->getValue('candidate_name'))));
  $form_state->setRedirect('second_page');
}

In the second page I have the following code:

public function buildForm(array $form, FormStateInterface $form_state) {

  $form['name'] = array(
    '#type' => 'textfield',
    '#title' => t('Candidate Name:'),
    '#required' => TRUE,
  );

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

  return $form;
}

How can I get the first page candidate name into the second page candidate textfield?

This is how I send information from one form to another.

In the first page:

use \Drupal\Core\Url;

function submitForm(array &$form, FormStateInterface $form_state){
  drupal_set_message($this->t('@candidate_name! Wow! Nice choice! Thanks for telling us!', array('@candidate_name' => $form_state->getValue('candidate_name'))));

  $params['query'] = [
    'candidate_name' => $form_state->getValue('candidate_name'),
  ];

  $form_state->setRedirectUrl(Url::fromUri('internal:' . 'second_page', $params));
}

In the second page:

public function buildForm(array $form, FormStateInterface $form_state) {
  $candidate_name = \Drupal::request()->query->get('candidate_name');

  $form['name'] = array(
    '#type' => 'textfield',
    '#title' => t('Candidate Name:'),
    '#required' => TRUE,
    '#value' => $candidate_name,
  );

  return $form;
}

EDIT: For POST method I never see it before, but you can create in the first page a session var and use this var in the second var after the redirection. Take a look in Storing Session Data with Drupal 8.

SECOND EDIT: It seems that the correct way todo this is with PrivateTempStore, if you go to see the CommentAdminOverview in Core you will see this:

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
      ...
      $info = [];
      /** @var \Drupal\comment\CommentInterface $comment */
      foreach ($comments as $comment) {
        $langcode = $comment->language()->getId();
        $info[$comment->id()][$langcode] = $langcode;
      }
      $this->tempStoreFactory
        ->get('comment_multiple_delete_confirm')
        ->set($this->currentUser()->id(), $info);
      $form_state->setRedirect('comment.multiple_delete_confirm');
    }
  }

In this page you collect the comment id that you want to delete and made a redirect, and the comment deletion happens in comment.multiple_delete_confirm (ConfirmDeleteMultiple) that have the following code:

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $this->commentInfo = $this->tempStoreFactory->get('comment_multiple_delete_confirm')->get($this->currentUser()->id());
    if (empty($this->commentInfo)) {
      return $this->redirect('comment.admin');
    }
    /** @var \Drupal\comment\CommentInterface[] $comments */
    $comments = $this->commentStorage->loadMultiple(array_keys($this->commentInfo));
  ...
  }

So, we don't have a POST method from one form to another in Drupal 8 but this can be solved in this way.


format_date() seems to ignore the time zone I am having issues with dates and time zones in Drupal 7. I have created a content type that stores the date in $field_event_date. When I use the Views module this works correctly.  However, I am using a template file to manipulate the display of this data. When I output the raw value, it is correct, so is the time zone; when I attempt to format it with the time zone format_date() seems to ignore the time zone value. Is there a proper way to do this in Drupal?

    print '
' . $field_event_date[0]['value']; // outputs 2011-11-04 21:30:00
    print '
' . $field_event_date[0]['timezone']; // outputs America/New_York
    print '
' . date('g:ia', strtotime($field_event_date[0]['value'])); // outputs 9:30pm
    print '
' . format_date(strtotime($field_event_date[0]['value']), 'medium', 'g:ia', $field_event_date[0]['timezone']); // outputs 9:30pm (????)

I have done this with just pure PHP this way:

// Get the timezone offset
$timezone = $field_event_date[0]['timezone'];
$remote_dtz = new DateTimeZone($timezone);
$remote_dt = new DateTime("now", $remote_dtz);
$offset = $remote_dtz->getOffset($remote_dt);

// Get the date
$start_date_string = $field_event_date[0]['value'];
$end_date_string = $field_event_date[0]['value2'];

// Apply the timezone offset
$start_date_string = strtotime(date("Y-m-d g:ia", strtotime($field_event_date[0]['value'])) . " " . $offset . " seconds");
$end_date_string = strtotime(date("Y-m-d g:ia", strtotime($field_event_date[0]['value2'])) . " " . $offset . " seconds");

// Build the date
$start_disp_date = date('l, F j, Y', $start_date_string);
$end_disp_date = date('l, F j, Y', $end_date_string);
$start_disp_time = date('g:ia', $start_date_string);
$end_disp_time = date('g:ia', $end_date_string);

This was working fine until recently a few dates started showing up about one hour off. I would prefer to use a Drupal centric solution (like format_date) since it might help me avoid odd occurrences like this one. Any advice for either approach would be appreciated however. This is all on a production site, so I just need to get it working.

Thank you for your time.

EDIT/UPDATE:

My PHP only solution was broken because of daylight savings time. So I replaced that code with this:

// Get the timezone offset
$offset = date('Z', strtotime($field_event_date[0]['value']));

// Apply the timezone offset
$start_date_string = strtotime(date("Y-m-d g:ia", strtotime($field_event_date[0]['value'])) . " " . $offset . " seconds");
$end_date_string = strtotime(date("Y-m-d g:ia", strtotime($field_event_date[0]['value2'])) . " " . $offset . " seconds");

// Build the date
$start_disp_date = date('l, F j, Y', $start_date_string);
$end_disp_date = date('l, F j, Y', $end_date_string);
$start_disp_time = date('g:ia', $start_date_string);
$end_disp_time = date('g:ia', $end_date_string);

Granted, this doesn't solve the problem with format_date(). While I'm going to stick with my PHP centric solution, others might have the same problem. Perhaps I am using the function incorrectly.

Yep, i was having similar problems, but in Drupal 6.

I'm surprised your  $field_event_date[0]['value'] was in New York time. My understanding is that that value comes straight out of the database, and it's pretty standard to keep all times in the db as UTC times, and only use local times when displaying them (since local times go crazy a couple of times a year).

$field_event_date[0]['timezone_db'] will tell you for certain what timezone $field_event_date[0]['value'] is in.

And $field_event_date[0]['timezone'] will tell you what timezone it should be displayed in (according to your site's 'default timezone'). If you look at $field_event_date[0]['view'], it should be in the display timezone.

When i'm trying to display dates from the raw 'value', i do something like...

/**
* @param
*     $date A CCK date field, like you'd get in your node templates,
*     e.g. $field_event_date[0]
*/
function get_display_date($date) {
    $date_convert = new DateTime($date['value'], new DateTimeZone($date['timezone_db']));
    $date_convert->setTimezone(new DateTimeZone($date['timezone']));
    return $date_convert->format('Y-m-d H:i:s');
}

I've yet to find any documentation which can confirm all this, so i may be totally wrong! But it works for me so far. Hopefully Drupal 7 isn't too different.


Facets rendering on all pages irrespective of value dynamicaaly form contextual filter in views I m trying to add facets using facets module in drupal 8. i have created listing of all products using views page. on listing page, facets are showing properly as per brand information added from admin panel.

All products listing Page:

but when i go to the detail page of every individual product,facet blcok show only single value of that brand only. check below image for more reference:

Here on detail page , i want to show complete list of facets as shown in first image. how to do that??? any idea??

I believe, this is the default behaviour, where the facets are filtered based on the result set.
What you want may not be achievable OOB.
But this is not a bug, it is a correctly working behaviour.


Multisite: Share users and user roles for existing set up I have made a Drupal 7 multi-site with 3 sites. Each site is running of the same Drupal install and has a separate database.
The database names are myhost_site1, myhost_site2 and myhost_site 3.  (My hosting provider puts in the myhost_ automatically).

I need the 3 sites to share the users and user roles.  I have read various tutorials and these are the steps I have followed:

Created a new database called myhost_users.
Copied the following tables from myhost_site1 TO myhost_users:
users, user_roles, authmap and sessions
Given the database users for each of 3 main databases access to myhost_users.
Open the settings.php for each site and insert the following code (replacing the existing $databse definition):

$databases['default']['default'] = array(
  'driver' => 'mysql',
  'database' => 'NAME OF DATABASE',
  'username' => 'DATABASE USER',
  'password' => 'DATABASE PASSWORD',
  'host' => 'localhost',
  'prefix' => array(
    'default'   => 'NAME OF DATABASE',
    'users'     => 'myhost_users',
    'sessions'  => 'myhost_users',
    'role'      => 'myhost_users',
    'authmap'   => 'myhost_users',
  ),
  'collation' => 'utf8_general_ci',

);
When I go to my site, I get the following error message:

  Uncaught exception thrown in session handler. PDOException: SQLSTATE[42S02]: Base table or view not found: 1146 Table

For the code posted in (4) I have tried using an underscore suffix for the database names (e.g, myhost_users_), but I still get an error message.

What am I doing wrong? Do I need any settings in sites/sites.php?

I would be open to using a module to do this.

Bakery is no good as it doesn't share user roles.

Account Sync shares roles, but it doesn't  seem to work.

CAS requires phpCAS which I do not have access to.

You don't need additional modules to achieve what you want.

First: Fix you configuration:

'prefix' => array(
'default'   => 'default_db.',
'users'     => 'myhost_users.', //
'sessions'  => 'myhost_users.',
'role'      => 'myhost_users.',
'authmap'   => 'myhost_users.',
),

The dots on the end of 'users' => 'myhost_users.' tells Drupal to query the users table in myhost_users data base (SQL syntax); without dots you'll get an error like "Base table or view not found myhost_usersusers/myhost_users_users or similar.

Now,

'database' => 'db',
'username' => 'db_user',
'password' => 'db_user_pass',

are credentials for the default db where Drupal is installed. To query users db you need to add this user with his password (db_user, db_user_pass) to the myhost_users database. in other words, if you have a site with 2 subsites:

myhost_site1 - user of this db
myhost_site2 - user of this db
myhost_users - (assuming this db stores Drupal users, that you want to share across ites) user of this sb + user of myhost_site1 and user of myhost_site2

To stay logged in on each site it is necessary to share cookies between sites: edit settings.php file of each site, uncomment the line with # $cookie_domain = '.example.com'; and replace '.example.com' with your domain. Don't forget the dot at the beginning ('.mysite.com') -- without it both mysite.com and notmysite.com could be treated as the same domain.


Separate line items when line item details are different As an ability the user might choose gift wrapping option for some of his/her products on add to cart form , what I did is creating a new product type called gift wrapping item, so site operators can add different kinds of wrapping options with different prices. I also altered the add to cart form so a new form item is added which gives the costumer the ability to choose a wrapping type, so far so good, user choice then is saved as a line item property (product ID of wrapping option is save in 'field_wrapping_option' which is added to product line item), and wrapping price is added to line item base price.

The problem is raised when user want to add 2 item from same product but he/she wants wrapping only for one of the two. In this case both products are stored in same line item and wrapping price also is added for them both.

I used hook_commerce_cart_product_comparison_properties_alter to force drupal create different line item when 'field_wrapping_option' are different on line items, but it didn't make things better, now every add to cart operation lead to new line item even when same wrapping option has chosen by user, and even worse situation happens when user first add a product without gift wrapping first and then adds a product with wrapping option which cause the first line item change into a product with gift wrapping.

Now the question is : How to Separate line items when line item details are different?

You could first have a look at Commerce Product Add-on module. That solution would split them per product type e.g. if you add one product with gift wrapping and one without you will have one line item for the product with quantity 2 and one for the gift wrapping with quantity 1. This gives the customer visibility of the exact pricing.

If however you still want to do it the way you described, the hook you mentioned should work.

function MY_MOULE_commerce_cart_product_comparison_properties_alter(
  &$comparison_properties,
  $line_item
) {
  $comparison_properties[] = 'field_wrapping_option';
}

Possible cause of trouble would be if the 'field_wrapping_option' of the line item being added is not set at all. The existing line item would always have the field set, even with an empty value, while you will have to set it for the incoming line item. It is possible that you set the field value only when gift wrapping is selected, try setting the field value to NULL if no gift wrapping is selected.

$line_item_wrapper->field_wrapping_option->set(NULL);

To further debug why line items are not properly combined, look at the 'commerce_cart_product_add' function at the commerce_cart.module file. The following code is the most relevant.

// Loop over each line item on the order.
foreach ($order_wrapper->commerce_line_items as $delta => $matching_line_item_wrapper) {
  // Examine each of the comparison properties on the line item.
  foreach ($comparison_properties as $property) {
    // If the property is not present on either line item, bypass it.
    if (!isset($matching_line_item_wrapper->value()->{$property}) && !isset($line_item_wrapper->value()->{$property})) {
      continue;
    }

    // If any property does not match the same property on the incoming line
    // item or exists on one line item but not the other...
    if ((!isset($matching_line_item_wrapper->value()->{$property}) && isset($line_item_wrapper->value()->{$property})) ||
      (isset($matching_line_item_wrapper->value()->{$property}) && !isset($line_item_wrapper->value()->{$property})) ||
      $matching_line_item_wrapper->{$property}->raw() != $line_item_wrapper->{$property}->raw()) {
      // Continue the loop with the next line item.
      continue 2;
    }
  }

  // If every comparison line item matched, combine into this line item.
  $matching_line_item = $matching_line_item_wrapper->value();
  break;
}


Ajax submission not working for Webform within a node I am working with a feature where a newsletter subscription form (Webform with ajax submission and confirmation type is inline) should appear in a node. The node would be showing as a popup and the contents of popup is being loaded using ajax. When the node is tested in it's own node page the submission is working fine but not in the popup.It is redirecting to another page. Inspecting the two cases, i found that the webform while being loaded in popup, lacks event handler that should refer to form submission.
In the controller where webform being loaded into the popup block, something like this is tried:
  $webform = $this->entityTypeManager->getStorage('webform')->load($formId);
  $view_builder = $this->entityTypeManager->getViewBuilder('webform');
  $build = $view_builder->view($webform);

Where $formId is the id of the webform and entityTypeManager is an instance of Drupal\Core\Entity\EntityTypeManagerInterface.
Later this $build is being saved as the webform attribute of popup class and later being rendered. The fields of the webform appears to be loaded correctly but not the event of submission form.
Any suggestion for solving the issue?

This is a gotcha of AJAX forms.
When you load an AJAX form via AJAX it loses its AJAX functionality.
In order to keep it working, for the form that is getting loaded via ajax, you need to add a url and options keys to #ajax
/*
 * Implements hook_form_alter()
 */
function mymodule_form_alter(&$form, FormStateInterface $form_state, $form_id) {

  // I created a webform called "test"
  if ($form_id == 'webform_submission_test_add_form') {
    $webform_id = 'test';
    $form['actions']['submit']['#ajax']['url'] = \Drupal\Core\Url::fromRoute('entity.webform.canonical', ['webform' => $webform_id]);
    $form['actions']['submit']['#ajax']['options'] = [
      'query' => [
        Drupal\Core\Form\FormBuilderInterface::AJAX_FORM_REQUEST => TRUE,
      ],
    ];
  }

}

Side note: this loss of AJAX issue doesn't occur with the HTML way of opening dialog boxes
<a class="use-ajax"
   data-dialog-options="{&quot;width&quot;:600}"
   data-dialog-type="modal"
   href="/form/test">
   Should load Test webform in a Modal
</a>

because it has the URL of the form and knows its an AJAX request from the class name.


Location Contextual Filter: Distance/Proximity I am trying to create a location-based contextual filter, and it seems like it should be taking four arguments - Lat, Lon, distance (number) and distance (unit).

How should this filter actually be created in the URL? I'm trying the following format:

42.279594,-83.732124,25, 2, miles

and getting nothing.

Would I just create a url with four arguments? Like location/%/%/%/%?

I've never used a contextual filter with multiple arguments before.

The correct answer is this:

?distance%5Blatitude%5D=42.279594&distance%5Blongitude%5D=-83.732124&distance%5Bsearch_distance%5D=1&distance%5Bsearch_units%5D=mile


How can I change the order of vertical tabs? More specifically, I am using Location in Drupal 7 to allow people to add location to nodes, but I want it to appear at the top of the vertical tabs fieldgroup.

An alternative to user842's answer (for those who are interested in a more code-based solution) is to set the weights on all the form items whose group is "additional_settings". The idea here is, higher the weight, lower the tab will appear, where the default is the one with the lowest weight (or one whose weight is not set).

To do this without modifying core code, create a module with a very large weight (see weight module for a module-based, or this post for a DB-based approach). Specifying the weight is important so that the module can be executed later than other modules which may change the order of the tabs. In this module, implement hook_form_alter, or hook_node_form_alter, which exposes the $form array.

At this point, you can look at the $form array, and pick out the indices that correspond to the vertical tabs whose order you wish to edit. One way to look at the $form array is by printing it out (via drupal_set_message($form) in the hook_form_alter or hook_node_form_alter). This array is huge, so you may want to run some kind of browser search to find the items that you want.

The indices that correspond to items on the vertical tabs are items with #group set to additional_settings (so you can search for the string "additional_settings"). For example, you may see the following when you print out the $form array:

Array
(
   ...
   [path] => Array
        (
           ...
           [#group] => additional_settings
           [#weight] => 314159265359
           ...
        )
)

and this is showing that path which corresponds to the location tab in the vertical tabs has a large weight 314159265359, which might be the reason that it is showing last in the vertical tabs.

With this info, you can now change the order of this tab in your hook by decreasing the value of the weight:

// set a small weight for the path tab
$form['path']['#weight'] = -1;

in your hook. Notice that weights can also be negative. You can do this for some/every tab (by going through and changing their weights).

This unfortunately doesn't work for all situations. If the #weight of some vertical tab is unset, somehow, that tab will bubble to the top. You can fix that by giving the tab. The source-code might look something like

/**
   Implements hook_form_FORMID_alter, hook_node_form_alter.
   Changes the $form array to reorder vertical tabs.
*/
function reorder_vertical_tabs_node_form_alter(&$form, &$form_state, $form_id)
{
   // move 'location' to the top (as the default)
   $form['path']['#weight'] = -1;

   // move 'themekey' under 'locations'
   $form['themekey_ui_themes']['#weight'] = 0;

   // move 'published/unpublished' down
   $form['options']['#weight'] = 100;
}

From experience, I do not think you can change the order of the vertical tabs by setting $form['#after_build']. At that point, the order of the vertical tabs are already set.


How to show summary in node view? While adding article, I am having an option to enter summary for article. But this summary is not displaying in node view. I wanted summary to be displayed in full node view.

Any ideas how can I show summary in full node view?

-- Many thanks for your time.

Solved it by overriding node template for my content type.

1) Copied node.tpl.php of my theme and renamed it to
node--content_type.tpl.php.

2) Put the following code at desired place:

<div class="fullmode_summary">
    <?php if ($view_mode == 'full'): ?>
      <?php print render($node->body[$node->language][0]['safe_summary']);  ?>
    <?php endif; ?>
</div>

May help someone having same issue.


Show sql queries when load content I'm working with the data from a Drupal 7 site that I have and I need to extract the data from a table with a relation to another table. The problem is that one of the tables is Node table and the other is field_data_field... that has a target_id.

The queries I have tried are not connecting  the data correctly between this tables. I know this because  when I go to the content page (http://example.com/ca/content/aalto-erick) the data is not the same.

Is there a way to display the SQL queries that executes the server when displays this content page?

PD: I put the url to show that the info is displaying in a content page.

Yes. The Devel module has a submodule called Web Profiler. Once the Web Profiler module is enabled, there will be toolbar in the footer. The toolbar contains a DB inspection button signified by a DB "stack" with the number of queries performed and the time to perform them. Click the button will show you a profile of the DB queries made in the last request.


Use Rules to email all members of a role that is specified within a taxonomy field attached to a node I tried to concisely explain what I am looking to accomplish in the subject, but will go into more details here. I think I'm really close but my Google-fu is failing me.

My question: How can I use the role reference field coming through field_responsible_team in a dynamic fashion opposed to the static fashion I've solved for currently?

Current Setup:

Content Type: Question

-- Taxonomy: Category (attached to Question content type)

---- Taxonomy Field: Responsible Team (user role) / (attached to Category taxonomy)

Example Question node:

Node Type: Question

Category: Training

Responsible Team: Learning & Development

    { "rules_XYZ" : {
    "LABEL" : "XYZ",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "node_insert--question" : { "bundle" : "question" } },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_category" } },
      { "AND" : [] },
      { "entity_has_field" : {
          "entity" : [ "node:field-category" ],
          "field" : "field_responsible_team"
        }
      }
    ],
    "DO" : [
      { "mail_to_users_of_role" : {
          "roles" : { "value" : { "4" : "4" } },
          "subject" : "XYZ [node:workbench-access-sections]",
          "message" : "XYZ"
        }
      }
    ]
  }
}

I got excited when this worked, but realized I had limited this to just users of role 4.

Preferred solution: Dynamically pull in the role from the new node created and use that for the role selection in the "mail_to_users_of_role" function. I would've thought I could've used the "node:field-category:field-responsible-team" data selector, but it's telling me that "The data type of the configured argument does not match the parameter's roles requirement." I'm using the Role Reference module.

Secondary solution (solved - see below): Create one rule for each of the roles and specify the categories within the rule set (not ideal).

{ "rules_XYZ" : {
"LABEL" : "XYZ",
"PLUGIN" : "reaction rule",
"OWNER" : "rules",
"REQUIRES" : [ "rules" ],
"ON" : { "node_insert--question" : { "bundle" : "question" } },
"IF" : [
  { "entity_has_field" : {
      "entity" : [ "node:field-category" ],
      "field" : "field_responsible_team"
    }
  },
  { "AND" : [] },
  { "data_is" : {
      "data" : [ "node:field-category:field-responsible-team" ],
      "value" : "4"
    }
  }
],
"DO" : [
  { "mail_to_users_of_role" : {
      "roles" : { "value" : { "4" : "4" } },
      "subject" : "XYZ",
      "message" : "XYZ"
    }
   }
  ]
 }
}

Preface: there is no need for the "AND" in your Rules Conditions (that's the default). Moreover, that "AND" applies to all Rules Conditions following the "AND" (but you only have 1 Rules Condition that follows it). Therefor, start by simplifying your Rules to get rid of the "AND". Refer to my answer to "How to make an OR statement in rules?" for more details about all this.

What you could do for sure is to rework your 2nd Rule (for role "4"), into a rule that performs a (new) Rules Component. To start, at least perform these changes:

Create a Rules Component which uses a parameter named (say) "Selected term". Use a data type of "Taxonomy term".
In your original Rule:

Replace the Rules Action (to send an eMail) by a Rules Action to just execute the (new) Rules Component. While doing so, pass node:field-category as the value of "Selected term".
Remove the last Rules Condition (with the hardcoded role "4").

The above changes will be a good start, but still it won't be sufficient. The remaining challenge (in the rules Component) will be related to the "Data selector" you need to specify for the Rules Action "Send mail to all users of a role" (= the replacement for your hardcoded "4"). That challenge is because the rules Component parameter "Taxonomy term" is a single value, while for the roles to be emailed you need a list (repeat: list!), as indicated also below the roles label, where it says "Select the roles whose users should receive the mail." (note: "roles", not "role"!).

Too bad, if we don't have a list, we'll massage the single value (Taxonomy term) into a "list". What follows is an example of a Rule and related Rules Component, with which I could make it work in my own setup:

Main rule

Here is my sample rule (in which I'm using 2 Rules Events, just to simplify testing and so that the logic is also triggered when updating content):

{ "rules_notify_users_of_selected_role_about_new_content" : {
    "LABEL" : "Notify users of selected role about new content",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "node_insert" : [], "node_update" : [] },
    "IF" : [
      { "node_is_of_type" : { "node" : [ "node" ], "type" : { "value" : { "article" : "article" } } } },
      { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_demo_tags" } }
    ],
    "DO" : [
      { "component_rules_do_something_with_selected_term" : { "selected_term" : [ "node:field-demo-tags" ] } }
    ]
  }
}

Note that I'm using a field like field-demo-tags (instead of field_category as in your case). I'm NOT using the Role Reference module, no need for it. The Rules Action is to only perform a Rules Component, in which the real magic will happen (see below).

Rules component

Here is my sample Rules Component:

{ "rules_do_something_with_selected_term" : {
    "LABEL" : "Do something with selected term",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : { "selected_term" : { "label" : "Selected term", "type" : "taxonomy_term" } },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "selected-term" ], "field" : "field_related_role" } }
    ],
    "DO" : [
      { "drupal_message" : { "message" : "Field \u0022field_related_role\u0022  (for Related role ID) is [selected-term:field-related-role]." } },
      { "variable_add" : {
          "USING" : { "type" : "list\u003Cinteger\u003E", "value" : [ "" ] },
          "PROVIDE" : { "variable_added" : { "list_of_roles" : "List of roles" } }
        }
      },
      { "list_add" : {
          "list" : [ "list-of-roles" ],
          "item" : [ "selected-term:field-related-role" ],
          "unique" : "1"
        }
      },
      { "mail_to_users_of_role" : {
          "roles" : [ "list-of-roles" ],
          "subject" : "Some eMail subject (delivered to all users with role id = [selected-term:field-related-role])",
          "message" : "Some message content related to the term named [selected-term:name] (delivered to all users with role id = [selected-term:field-related-role])"
        }
      }
    ]
  }
}

The field field_related_role is an extra field I added to my taxonomy term I'm using (single value, data type integer), instead of field_responsible_team as in your case.

Some more details about this Rules Component:

Rules Conditions:

Check the type of node (in my case "article", adapt to fit your needs).
Check that the entity (node being created or updated) has a field field_demo_tags (the term I'm using).

Rules Action:

Show a message on the site (just for QA-testing purposes, omit if not needed anymore).
Add a variable, i.e. a "list of integers", which will become the "List of roles" we'll need in a subsequent Rules Action.
Add to this list, the value of selected-term:field-related-role (part of the Rules Component parameter).
Send mail to all users of a role, whereas we use the newly created "List of roles" to get it all to work (adapt eMail subject, message, etc to fit your needs).

The above works like a charm, at least in my case/setup: I have 3 users with a role related to a taxonomy term I used while updating an article, and each of those 3 users did receive an eMail as in my last Rules Action.

Voilà ...


How to set paths for menu items in hierarchy to make it work with Superfish I'm confused about what to do with the menu items whose sole function is 'to be parent' i.e. no content attached to them. One way I wanted to solve this is to set the path to <front> for those items. But then subitems just won't fly out anymore.

Similarly, if I set the path of a parent item to the node that belongs to a child item, the parent just totally disappears out of the menu, leave alone that there would be a child to pop out of.

Weirdly enough I've just stumbled across the Special menu items module, which is:

a Drupal module that provides placeholder and separator menu items.
A placeholder is a menu item which is not a link. It is useful with dynamic drop down menus where we want to have a parent menu item which is not linking to a page but just acting as a parent grouping some menu items below it.

I'm pretty sure that's just what you're looking for, and it has a stable release for Drupal 7 :)


Overriding views-view-grouping.tpl.php when grouping by only one field I have a view being grouped by one field. I'm trying to theme the groups as a whole (wrap divs around the whole thing, essentially) and I did so by overriding views-view-grouping.tpl.php. However, nothing happens. Out of curiosity I added another grouping and voilá, my template override is being picked up now. Only problem is, I don't need to group by two fields, just one.

Why is it doing this? Is there a separate override for single-grouped views? What is going on and how can I get Views to pick up my override of views-view-grouping.tpl.php when grouping by only one field?

I've had the same issue. At first I though it was connected to the current theme I was using, but after testing with a few different themes I discovered that not to be the case. I still do not understand that behavior.

As a workaround I've used views-view-unformatted--YOURVIEWMACHINENAME.tpl.php template where you can give a wrapper to a group in a single-grouped view. Here's what I had in the template:

<?php

/**
 * @file
 * Default simple view template to display a list of rows.
 *
 * @ingroup views_templates
 */
?>
<?php if (!empty($title)): ?>
    <?php
        //open group wrapper
        print '
';
    ?>

<?php print $title; ?>

<?php endif; ?>
<?php foreach ($rows as $id => $row): ?>
  <div<?php if ($classes_array[$id]) { print ' class="' . $classes_array[$id] .'"';  } ?>>
    <?php print $row; ?>

<?php endforeach; ?>
<?php if (!empty($title)): ?>
    <?php
  // close group wrapper
    print '
';
    ?>
<?php endif; ?>

You can even assign a custom class to each group by taking a certain field from $view object and transforming its value into a class name.

Of course, this method will only work for a single-grouped view. If the view will be grouped by more than one field, only the most inner group will be wrapped. Hope this helps.


Add an additional custom submit handler to default search api Solr view filter? I would like to run an additional submit handler every time a user searches a term with the default view filter provided by the search_api_solr module.

Here is my form altering code:

/**
 * Implements hook_form_FORM_ID_alter.
 */
function my_module_form_views_exposed_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  if ($form['#id'] == 'views-exposed-form-solr-search-content-page-1') {
    $form['#submit'][] = 'my_module_handler';
  }
}

**
 * Custom submit handler.
 */
function my_module_handler(array $form, FormStateInterface $form_state) {
  drupal_set_message($form_state->getValue('keys'));
}

The problem is the that submit handler executes twice. It executes when the page loads (I think) and when the 'Search' button is clicked. Any ideas why this would be?

(I am trying to write all the terms searched by users (strings) to a database table.)

Thanks.

The solution was to enable AJAX on the view. This stopped the page refreshing and the double form submission.


Change in URL for social networking I am using Drupal for running a website. I have integrated the "Share bar" module to share the current page in social networking sites. I know from the plugins code of Facebook that the share count of the website is 200+ But the share bar module shows only 20+ count.

I could find out what the problem is, the code for sharebar is:

   <fb:like href="[url]" send="true" layout="box_count" width="450" show_faces="true"></fb:like>

In the code above, [url] token actually gives out http://www.indiansnakes.org/frontpage instead of http://www.indiansnakes.org. I think the [url] token refers to hyperlink before redirection is completed.

How can I modify the script above so that I get the count for www.indiansnakes.org instead of www.indiansnakes.org/frontpage

Looking at the source code on your live site, I see that the code for the fb:like section becomes:

<fb:like href="http://indiansnakes.org/frontpage" send="true" layout="box_count" width="450" show_faces="true"></fb:like>

...so I assume [url] is a token. Assuming that's true, I'd recommend using a more specific URL token.


How to force user to change password? I am using Force password change module to give a facility to user to reset the password after their first login. So far, I have installed the module and after creating the user, when I click on edit link, I could see the force user to change password check box option. But I am unable to see the same option in add user page (while creating user).

Any suggestions about how to enable same option on add user page?

You can navigate to this url admin/config/people/force_password_change
and check Force password change on first-time login option or you can configure based on roles too.

In that case you will get a option in both create and edit user as shown in screenshort.


preprocess_page if front I have a preprocess_page function that applys classes to my content if there is a sidebar or not.

  if ($vars['page']['sidebar']) {
    $vars['content_classes'] = 'cool-class';
  }

  else {
    $vars['content_classes'] = 'super-cool-class';
  }

Can I do a similar with adding class if its the front_page. I want it to be included into this one but I do not seem to find the right way to do it.

Thank you very much,

Need to add both condition for sidebar and front page like this.

if (drupal_is_front_page() && $vars['page']['sidebar']) {
      $vars['content_classes'] = 'cool-class';
}

else {
      $vars['content_classes'] = 'super-cool-class';
}


How do I redirect to www and https in settings.php? I want to include code in settings.php which would handle redirects to the www alias and also https.

Because it is for a distribution I would prefer not to have hard-coded URLs and I would also prefer not to be changing the .htaccess file so that core updates are easier.

I am using the code below, and I just want to be sure it doesn't have any security issues. Does it have any security issues, and I should therefore use different code?

// Redirect to www
  if (substr($_SERVER['HTTP_HOST'], 0, 4) !== 'www.') {
  header('Location: '.$protocol.'www.'.$_SERVER['HTTP_HOST'].'/'.$_SERVER['REQUEST_URI']);
exit;
}
// Redirect to HTTPS
  if($_SERVER["HTTPS"] != "on")
{
  header("Location: https://" . $_SERVER["HTTP_HOST"] . $_SERVER["REQUEST_URI"]);
exit();
}

The caveat to the settings.php approach is 2 issues:

Your redirect requires that Drupal be bootstrapped to work. If there's a resource that bypasses Drupal (e.g. any hosted files), you're not going to see the www redirect occur.
It's arguably bad practice. settings.php is for Drupal settings; depending on your intent this might be considered a web server setting. A developer working on your project in a local environment might have trouble understanding where the redirect is coming from as standard Drupal configurations use the .htaccess file for this.

An alternative to prevent .htaccess overwriting would to be place the rewrite directive in an Apache configuration (e.g. vhost.conf if you're using virtual hosts) that defines your host.


Render whole entity inside a controller I am trying to print an entity reference field (from paragraphs module) into a controller.
I learned from this ticket that you can use
{{ teacher.field_classrooms.entity.field_in_paragraph.value }} to get the value of one field from  the entity, but what I really need is to print the whole entity not just one field from the entity.

I was hoping to do something like {{ teacher.field_classrooms.entity }} rather than {{ teacher.field_classrooms.entity.field_in_paragraph.value }}
{{ teacher.field_classrooms.entity.field_different_in_paragraph.value }}.

You can do that by setting a variable in your controller or in template_preprocess_teacher in your .theme file, like:

function template_preprocess_teacher(array &$variables) {
  $classrooms = $variables['elements'][0]->get('field_classrooms')->referencedEntities(); //probably a bit different for paragraphs ..

  foreach($classrooms as $classroom) {
    $variables['classrooms'][] = \Drupal::entityTypeManager()->getViewBuilder($classroom->getEntityTypeId())->view($classroom, 'optional-view-mode');
  }
}

And then access it in twig like this:

{{ classrooms }}

If you're looking for a twig only solution use the twig_tweak module, then it comes down to this:

{% for field_in_paragraph in teacher.field_classrooms.entity %}
  {{ drupal_entity('classroom', field_in_paragraph.value, 'optional-view-mode') }}
{% endfor %}


Add a condition on dropdown selection I have a dropdown in a node and the id of the dropdown is "field_b_status".
I want to add condition in a rule if the drop down value is equals to one of the value "Complete" then send email.
When i try to add that, i see the error.
Data selector field_b_status.value for context Data to compare is invalid. Unable to get variable field_b_status, it is not defined.
Please see the screenshot:

Can you please help me how to add dropdown "field_b_status" in the condition?

Rules in Drupal 8 doesn't have much flexibility.
So in your case, you will do the following to achieve it.

Under Data selector, you will type: {{node.field_b_status.value}} and choose Direct mode instead.

And rest will be similar to your screenshot.


What does 'op' exactly mean in an submit button? In the form_state['values']['op'] = t('Save');

What does 'op' exactly mean and do ?

I'm pretty sure it's shorthand for the word operation.

It doesn't 'do' anything as such, it's the name assigned to all submit inputs so that the form processor can identify which button has been pressed (and perhaps fire off different submit handlers based on that).

And it looks like it's gone in Drupal 8 (in favour of $form_state['triggering_element']), so enjoy it while you can :)