How do I show a view item as grid and view item as list, dynamically? I have created a view to display list of user with their details, and
I want to display a widget on views display page which shows item as view item as grid and  view item as list dynamically.

How do I achieve this?

Install and configure the Views Mode module.

  A Drupal Views display plugin which provides alternate display modes
  that can be switched to for a single View. This allows exposed filter
  parameters or contextual filters to be kept active while switching
  display mode.

To get this module to work, follow these simple steps:

Activate the modules.
Create a view.
Select your view, then create 3 different display, 1 page and 2 modes (one of the mode should be identical to the page display, since it's the 'default' mode).
Within the Advanced settings of the mode displays, you will find a new section called 'mode settings'.

4a. Attach your modes to your page's view

4b. your mode id is a value that'll be displayed within the url, therefore use only lowercase and normal chars (e.g. 'stickers').

4c. your mode name is the one that'll be displayed in your mode changer block, this can be anything.

4d. For consistency, change the system names of your view's mode displays for their mode ID (4b), they'll be easier to identify.
If everything's going well, visit admin/config/search/purl.

5a. You should see 3 tabs (param, modifiers & types).

5b. Select the third tab first (types) and select the 'query string' option.

5c. Within the Settings tab, select the 'Query string' modifier type, and write 'mode' in the 'key' field (this is the word that'll be displayed within your url, in my case it would look like www.site.com/view?mode=stickers).
Now all you need to do is to add the 'Views mode links' block to your view's page (you should see links appearing on your view's page).

This module does not work with an AJAX enabled pager.


how to get the form id of a particular form using Devel execute PHP in drupal 7? I wanted to get the form id of particular forms to customize those forms. I dont want to use form alter hook to obtain the form id every time. I wanted a simple way to acquire the form_id of the forms. Like a simple PHP snippet that can be executed in Devel execute PHP to obtain the form ID. or is there any other way to do it?

I don't think it's possible to do this without something (either your custom module or another module) implementing hook_form_alter(). The Devel execute PHP form is in a block which has no real idea what forms are available on the page.

I'm sure you know the way to get the form ID but just in case this will print it at the top of every form:

function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  if (user_access('whatever permission you want')) {
    $form['mymodule_form_id'] = array(
      '#markup' => '
Form ID: ' . $form_id . '
',
      '#weight' => -10000
    );
  }
}

If you really don't want to do this, though, why not just use developer tools/firebug to inspect the form element on the page itself...you'll find the form id in one of the hidden input fields.


How do I get a nodes authors email address within views? I have a view that list nodes of a certain type. These nodes are created by different users.

In my view, how would I get the email address of the creator of the particular node (I will pass this email to a webform)?

Create the view of content type or use existing view
Go to admin/structure/views and edit your view
Under advanced section tab add relationship Content: Author
Add the relationship.
Add the email field User: E-mail (E-mail) under field section.
Save the view


Flexslider view preview working but not on actual page My block is not working for the flexslider: The images are not appearing, but the view preview does work.

I don't know if it is relevant, but a similar problem would happen with just a slideshow view, although one image would appear and it would not cycle.

Could jQuery be a problem?

The following is the actual page with the block that is not showing any images.

The following is the view preview, which works.

In the config of the 'jquery update' module, select 'Default (Provided by Drupal)' in both of the drop-downs.
i.e. 'Default jquery Version' and 'Default jquery Version for administrative pages'


How to allow users to post content and easily overrule its default access settings? On our website, we have a content type ("news"), which includes both public and private items. Normally, posts will be viewable by authenticated users only. However, I want to allow people to post content that is viewed publicly. The way I would prefer to do this is with a simple checkbox during node creation, which allows the node to be public, and viewable for anonymous users.

So far, I've tried the Content Access module, but the interface it provides is too complicated; I only need a checkmark for "allow anonymous to view".

You can get this to work using a combination of the Rules module and the Content Access module, whereas the Rules module will automatically (behind the scenes) trigger the logic that's needed. The logic itself is entirely hidden for the user (author) and is equivalent to using the interface that you consider too complicated.

Here are some more details to get it to work:

Start from a rule that is similar to the example I included in my answer to "How to specify a Rules condition related to select list values?".
This sample rule uses a field named field_optionlist, with 3 possible values A,B,C. In your case you could use any other fieldname (to fit your naming conventions). And your field only needs 2 values, say Y (= yes, instead of A) and N (= no, instead of B). Some more tips to get you going:

Make sure to define this field (for your content type news) BEFORE importing the rule sample in item '1.' above (if not the import of the rule will fail).
If you use another machine name for that field, also edit the field name in the sample rule before importing it.
Adapt the Rules condition related to "value = C" to "value = Y" (to fit your case), and the message included in the Rules Action.

QA-test the intermediate result after completing step '2.': you should have a Drupal message show up when a news node is created with field value = Y (and not when it is not Y).
Use the integration of the Content Access module with the Rules module to create a Rules Action that updates the access of the node, similar to the Rules Action I included in my sample rule included in my answer to the question "How to revoke edit access to the node's author after publishing a node?". The actual settings to use for the content access module should match with the settings you seemed to already have tried (but which you consider as too complicated to have the node editor set them).

Refinement: if you really want a "checkmark" (instead of such yes/no selection field explained above), create a boolean field and rework the rule detailed above to use that field instead.

Bonus: if you ever need similar logic for another content type, just define the SAME field (with same machine name). After doing so, you should not have to change anything to the Rule as defined above. That's because of the "entity has field" condition ...


#States required not working I'm trying to use "#states". When my checkbox is true, I want to make "required" another field. Drupal prints the "required" asterisk but not correctly.

Here it's the code:

  // Return origin.
  $form['search']['return']['return_ori'] = [
    '#attributes'    => [
      'class'       => ['field-autocomplete', 'ret-ori-name'],
      'data-type'   => 'busstop',
      'placeholder' => t('Write your origin', [], ['context' => 'Backend']),
      'required'    => TRUE,
    ],
    '#default_value' => !empty($_GET['return_ori']) ? $_GET['return_ori'] : '',
    '#prefix'        => '

',
    '#states'        => [
      'required' => [
        ':input[name="search_return"]' => [
          'checked' => TRUE,
        ],
      ],
    ],
    '#size'          => 40,
    '#suffix'        => '
',
    '#title'         => t('Return origin'),
    '#type'          => 'textfield',
  ];
// Return trip.
  $form['search']['search_return'] = [
    '#default_value' => !empty($_GET['search_return']) ? $_GET['search_return'] : FALSE,
    '#prefix'        => '

',
    '#suffix'        => '

',
    '#title'         => t('Search return trip'),
    '#type'          => 'checkbox',
    '#attributes'    => [
      'class' => ['search-return-trip'],
    ],
  ];

The submit button has not specific method, so Drupal should handle it. When I press it, the form is sended ignoring my new required field.

Thanks all for help!!

Check the "name" attribute of your search return checkbox by inspecting it within your browser. You may find the name="" isn't actually name="search_return". It may instead be name="search[search_return]" or something similar. So you need to update your states code to whatever the name is


Override contributed module function I'm wondering if it's possible to override a contributed modules hook_menu function.

/**
* Implementation of hook_menu().
*/ function jquery_ajax_load_menu() {   // Admin settings.   $items['admin/config/development/jquery_ajax_load'] = array(
    'title' => 'JQuery AJAX Load',
    'description' => 'Shows any page on a AJAX link',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('jquery_ajax_load_admin'),
    'access arguments' => array('administer site configuration'),   );   // Only to generate a TAB   $items['admin/config/development/jquery_ajax_load/link'] = array(
    'title' => 'JQuery AJAX Load',
    'type' => MENU_DEFAULT_LOCAL_TASK,   );   // Prefix for AJAX requests   $items['jquery_ajax_load/get'] = array(
    'page callback' => 'jquery_ajax_load_callback',
    'type' => MENU_CALLBACK,
    'access arguments' => array('access content'),
    'delivery callback' => 'jquery_ajax_load_delivery_callback',   );   return $items; }

Essentially I want to override the 'delivery callback' => 'jquery_ajax_load_delivery_callback',  So that it calls a modified version of the same function, as apposed to hacking the module.  'delivery callback' => 'mymodified_jquery_ajax_load_delivery_callback',

Use hook_menu_alter(&$items).

function yourModule_menu_alter(&$items) {
  $items['jquery_ajax_load/get']['delivery callback'] = 'yourModule_jquery_ajax_load_delivery_callback';
}

That's clean and "Drupal way" to solve your problem.


My custom CSS is not taken into account I add a CSS file (mymovies.css) to a custom form (SeenMovies) in a custom module (eric) with this code I inserted at the end of buildForm
$form['#attached']['library'][] = 'eric/mymovies';

and this code in eric.libraries.yml
mymovies:
  version: 1.x
  css:
    theme:
      css/mymovies.css: {}

But my css doesn't override bootstrap.min.css as you can see in Firefox inspector:

How can I fix that?

This question has nothing to do with Drupal but with CSS order of precedence. If more than one identical CSS rules are found, the last one takes precedence.

As @leymannx pointed in their comment, your page is loading first your CSS file, then Bootstrap. Just move your Bootstrap into a new library as you just did with 'mymovies', then add a dependency to 'mymovies'. Declaring it as a dependency, it will load first the need libraries, then the library being called.

Edit - after saying you are using OnePage Zymphonies theme:

If you check 'onepage_zymphonies_theme.libraries.yml' you will see that the Bootstrap library is defined. Following my answer:

mymovies:
  version: 1.x
  css:
    theme:
      css/mymovies.css: {}
  dependencies:
      - onepage_zymphonies_theme/bootstrap


How to get the attachment display of a view to show up in a PDF display (created using Views PDF module)? I have a view with the following displays in a single View on my Drupal 7 website:

Page
Attachment 1
Attachment 2
PDF

The Attachment 1 and 2 displays both are set to be shown on the Page display, based on contextual filters and relationships. This is working great, but I'm not sure how to include all fields from the Page as well as the fields from the Attachments when creating the PDF display (using the PDF Views module), since they are all part of the same View. Is it possible to do so?

I never was able to get the Attachments to show up in the PDF, but here is my workaround:

I was able to get the output that I needed by using the Reference module and the Viewfield module.

Created Content type A and content types B, C, and D. B, C, and D are all associated with Content type A via Reference fields.
Created contextual/relationshipped views for B, C, and D, relating it to the title field of Content Type A.
Created a Viewfield on Content Type A for each of the sub-content types (B, C, and D).
Created a View for Content Type A, contextualized with Content:Title, and added the Viewfields to this new View (using reverse relationships with the node referenced field). I then added a PDF Page view using Views PDF, and that did the trick!

I can provide more detail if needed. Just let me know...


How do I avoid caching a redirect response from a form? I have a Drupal 8 form used by authenticated users which sometimes needs to redirect based on the presence of absence of something in session. I don't want the redirect to be cached.

My form is displayed directly with a route. i.e., the route has a _form default pointing to the form class.

My buildForm method starts like this:

public function buildForm(array $form, FormStateInterface $form_state)
{
    $form['#cache'] = ['max-age' => 0];

    if (some value not in session) {
        $response = new TrustedRedirectResponse($some_url);
        $response->setMaxAge(0);
        throw new EnforcedResponseException($response);
    }

    // build the form.
}

I have not been able to avoid the redirect response being cached. It redirects as expected if the session variable does not exist but continues to redirect next time when the session variable does exist.

Users are authenticated so it is the dynamic page cache. drush cr or uninstalling the dynamic page cache "fixes" the problem.

I just discovered that it's related to the TrustedRedirectResponse.

A standard Symfony\Component\HttpFoundation\RedirectResponse is not cached.


How to unset the title of a custom form field I'm trying to unset the label of a custom form called email. In which the value is in the #title key.

I've tried {{ value|without('title', 'description', 'email.#title') }}

But it is not working

@Fazeela Abu Zohra try to unset the value in .theme file. write a form alter and kint $form variable .Find your label value

function est_form_alter( &$form, &$form_state, $form_id ) {
  if($form_id == 'your_form_id'){
    kint($form);
  }

and then simply unset the variable.

unset($form['form_id']['#value']);

Here,i assume you find your variable at $form['form_id']['#value'].Hope it  will be useful to you.


how to notificate users about new created referenced nodes I have a content type called "A" and content type called "B". When a user creates node "A" other users can create node "B" referenced to node "A". How can i notify user which created node "A" about newly created nodes of type "B" referenced to his node "A"? I've tried notifications module but as i can understand there's no such options for that.. Tried this solution: how to create rules to send email notification for node reference content?
but it's not working on D7

I think you can accomplish it by creating a custom module. Whenever users create nodes of type B, you can mail and notify those users who created nodes of type A.

You can get the list of users who created nodes of type A with a SQL query like the following.

SELECT DISTINCT uid FROM node WHERE type = 'goals'

In order to send mails when users create nodes of type B, you will have to implement hook_node_insert(), so that you can send notifications after nodes are successfully created. You could also use hook_node_presave(); the only difference is that the latter will send mails before nodes are created.

function MODULE_NAME_node_insert($node) {
  if ($node->type == "B") {
    $params = array();
    $from = variable_get('site_mail', 'admin@example.com');
    $send = TRUE;
    $language = language_default();

    // It is assumed that array od users who created node of type "A" is returned
    // by the following function.
    $users = _list_of_user_created_A_node();
    foreach ($users as $key => $value) {
      $uid = $key;
      $mail = $value;
      $params['node_title'] = $node->title;// The node title of the created node B
      $params['userID_A'] = $uid;
      $params['mail_of_user_A'] = $mail;
      drupal_mail('MODULE_NAME', 'notify_mail', $mail, $language, $params, $from, $send);
    }
  }
}

See hook_mail() on how sending mails.

You could also save the node titles in a database table, and send mails during cron task's execution.


How do I hide "View most recent blog entries" If you enable the contributed Blog module, a link with the anchor text "View most recent blog entries" shows up on every post.  I want to hide this link using PHP (i.e. not resorting to css or javascript).

So far I've tried this in hook_node_links_alter():

unset($links['usernames_blog']['#links']['blog_usernames_blog']);

It doesn't work. I don't think the offending link is in the links array, but somewhere else (I've yet to figure out where).

unset($links['usernames_blog']['#links']['blog_usernames_blog']);

Might be correct, but make sure your module has higher weight, so your hook alter fires after the blog's module.

I suggest using the weight module to give your custom module higher weight. Else, you could run on Devel's Execute PHP module_set_weight('mymodule', 11); to give it higher weight.

If that doesn't work, If you look at the module's code, there is another link that gets added via hook_ENTITY_TYPE_view

Thus, all you gotta do is use hook_ENTITY_TYPE_view_alter

mymodule.module

/**
 * Implements hook_ENTITY_TYPE_view_alter().
 */
function mymodule_user_view_alter(array &$build, Drupal\Core\Entity\EntityInterface $entity, \Drupal\Core\Entity\Display\EntityViewDisplayInterface $display) {
  if (!empty($build['summary']['blog'])) {
    unset($build['summary']['blog']);
  }
}


How to translate Select List options used in exposed filters of a view? I'm having an issue with translation of exposed filters in Views.

I'm using a text list field as an exposed filter in my view. The problem is that even though I translated the list terms via strings (Regional and Language >> translate interface >> translate) the terms always appear in the original language.

I checked but there is not an option in the view to show the translated terms in the filter. There are other exposed filters translated the same way that appear in the correct language, but they're not select lists but taxonomy terms.

I also checked the advanced views settings and the Localization translation method is already on "core". I don't know what else to check.

I'm using Better Exposed Filters and MEFIBS - More exposed forms in blocks for the exposed filters (I'm not sure if this may be related).

I can confirm this issue. While working with BEF, me too faced the same translation problem. Probably this is a bug in BEF module which do not handle translations properly. Meanwhile, to solve this issue I explicitly used a hook_form_views_exposed_form_alter() to wrap the non-translatable string in t().

May this helps you.


$form['redirect'] = "something=$someId"; doesn't work in Drupal 7 I am here again with a problem! I want to make a form redirect usign a url with ids and somethings else as parameter, but when the code is executed something encode my url, so, if I put something like this $form_state['redirect'] = "page=$nid"; I get this in the url "page*%3D*123456789" %3D is the =$. So, how i have to do that? I tested with utf8_encode too.

Can I use a drupal_goto() inside a form? Why yes? Why not?

Thanks people!

What you set in $form_state['redirect'] can be:

a string containing the destination, such as node/1, admin/reports/status, or user/1.
an array of arguments compatible with drupal_goto().

The examples shown in drupal_redirect_form() are the following ones:

This redirect the form to node:

$form_state['redirect'] = 'node';

This redirect the form to node/123?foo=bar#baz:

$form_state['redirect'] = array(
  'node/123',
  array(
    'query' => array(
      'foo' => 'bar',
    ),
    'fragment' => 'baz',
  ),
);

In your case, if you want to redirect to page/$nid, you should use the following code:

$form_state['redirect'] = "page/$nid";

If you really want to redirect to page=$nid, then you should use the following code:

$form_state['redirect'] = array(
  array(
    'query' => array(
      'page' => $nid,
    ),
  ),
);


How to change the site logo in a preprocess function? I want to set my site logo programmatically, so that I can change the logo based on URL args.

I am able to set the $variables['logo_img']['#uri'] with the following code in MYTHEME.theme but still the logo displayed does not change.

I have cleared registry.

I have tried setting my own logo and using default logo settings in theme settings UI:

function THEME_preprocess_page(&$variables) {
  $variables['logo_img']['#uri'] = 'http://newlogo.jpg'; }

I have also tried this:

function THEME_preprocess_page(&$variables) {
  global $base_url, $base_path;
  $variables['logo'] = $base_url . $base_path . drupal_get_path('theme','THEME') . '/images/logos/newlogo.svg';
}

Any help?

How to change the site logo in .theme preprocess function?

The site logo is no longer in the page template. You can change it now in the branding block:

function mytheme_preprocess_block(&$variables) {
  if ($variables['base_plugin_id'] == 'system_branding_block') {
    $variables['site_logo'] = '/newlogo.jpg';
  }
}

Caching

You mentioned you want to change the logo based on URL args. This would be difficult to do this in the system branding block, because the template is not rendering the render array, but transferring only the content of three variables and so any attempt to add cache meta data would be useless.

You have two options. Implement your own site logo block plugin in a module or use this theming only solution:

disable the site logo in the branding block
set a variable with the url for the logo in page preprocess $variables['logo']
add your own markup to the page twig to output the site logo

page.html.twig:

<a href="{{ path('<front>') }}" title="{{ 'Home'|t }}">

By doing this in the page template you avoid caching problems because the page is already cached for each url separately.


How to create custom template suggestion, when there is no hook suggestion? I would like to create different templates for different nodes, but I cannot see any hook suggestion with theme debug. This is the template from quiz module.
So in theme debug it looks like that:

<!-- THEME DEBUG -->
<!-- CALL: theme('multichoice_alternative') -->
<!-- BEGIN OUTPUT from 'sites/all/modules/contrib/quiz/question_types/multichoice/theme/multichoice-alternative.tpl.php' -->

I was searching for the right answer, reading about template suggestions, trying different things, but without any luck so far.
I know, that I can create custom template for the whole block, but is it possible to create that custom template for the element which doesn't have any hook suggestions?
Thanks!

You can do it this way

implement hook_theme_registry_alter like the following:

    /**
     * Implements hook_theme_registry_alter().
     */
    function YourCostumModuleName_theme_registry_alter(&$theme_registry) {
      // Defined path to the current module.
      $module_path = drupal_get_path('module', 'YourCostumModuleName') . "/templates";
      // Find all .tpl.php files in this module's folder recursively.
      $template_file_objects = drupal_find_theme_templates($theme_registry, '.tpl.php', $module_path);
      // Iterate through all found template file objects.
      foreach ($template_file_objects as $key => $template_file_object) {
        // If the template has not already been overridden by a theme.
        if (!isset($theme_registry[$key]['theme path']) || !preg_match('#/themes/#', $theme_registry[$key]['theme path'])) {
          // Alter the theme path and template elements.
          $theme_registry[$key]['theme path'] = $module_path;
          $theme_registry[$key] = array_merge($theme_registry[$key], $template_file_object);
          $theme_registry[$key]['type'] = 'module';
        }
      }
    }

Create Folder called templates inside your custom module folder.
Copy contrib/quiz/question_types/multichoice/theme/multichoice-alternative.tpl.php file into templates folder with the same name multichoice-alternative.tpl.php.
Clear Cache.
Now you have $form and $fullOptions variables.


How can I schedule a rule to always be run at a specific hour of the day? I have a rules component that sends me an e-mail containing a view that contains certain statistics about my site.

I'd like to have this e-mail sent at midnight every day.

The rule looks like this:

Component: Action set

Send e-mail
Schedule the component again for evaluation (+1 day)

I then triggered the rule manually at midnight and waited for it to evaluate again.  This worked for the first several days but now the e-mail is arriving at 3 or 4 in the morning instead of at midnight.  I really want the e-mail to be sent at the same time every day (or as close to the same time as possible every day).  Is there a way to do this?

How about this:

When you're setting the time in the "Scheduled Evaluation Date" section, change it from 'Direct input' to 'Selection mode', and scroll down to where it gives you the option for 'PHP Evalution'

Paste in the following:

<?php
$midnight = strtotime('midnight');
echo date("Y-m-d h:i:s", $midnight);
?>

This should return something like '2013-03-25 12:00:00' // That's what it's returning for today!

You have to include the php brackets.  The strtotime() function should return back midnight of the current day, so it should work for you. I'm thinking since this is based on your cron running, it will not be exact and this should evaluate a little past midnight and 'midnight of the current' day should be exactly what you need.  Maybe you can find a php tweak that makes this better...

Anyway, let us know if that works!


Build page from content type course - use views or custom code I'm looking to build a page like the wireframe below and need help to decide if I should use views or custom code. I haven't really used views before but looks like it could be a nice way to build up the page and add additional functionality (filtering, paging, searching etc) at a later stage.

My concern is the layout and also the links. One titled 'learn more' that links to the actual node and the other 'enrol' which is a course module link.

Should I use view or just custom code in a module?

It's unclear from your post on your knowledge of Views.  However if your referring to the 4 content boxes being shown in the sketch then Views is a great tool for doing this.

Regarding layout there is the functionality to return all fields you require in divs / classes etc and will be able to generate the look you wish.

Also links are no problem; in fields call up [content:path] - you can then add a 'custom text' field with your link

Link

Views can general be viewed as a way of returning data from the database and present it how you wish.  enjoy!


Multiple vocabulary terms filter? I have a vocabulary called category, another vocabulary called author and the content type is videos. I want to display all the authors(unique) by category vocabulary term?

Can any one please suggest me how to achieve this using views?

I ran into a similar situation and hacked up a solution based upon the advanced solution here: http://drupal.org/node/770782.

Addition per commentary...

Basically what I was running into here was a situation where I had node content tagged with a genre as well as a location and what I wanted was a list of all the genres in a location.

A quick description of the view would be "Filter on published content of node type X with an argument (Drupal 6) (now Contextual Filter in Drupal 7) of location and display the genre field of each found."

A difference in my solution is that I kept count of how many nodes were tagged and I sorted on that while in the link given above it was sorted alphabetically.

Doing this with Views created lots of duplicate rows obviously because it was listing each node it found with that genre.

So, basically what I ended up doing was going into hook_views_pre_render() and looping through the results and removing all duplicates, eg:

function YOUR_MODULE_views_pre_render(&$view) {

  if ($view->name=='THE_NAME_OF_THE_VIEW_YOU_ARE_LOOKING_FOR') {

    drupal_set_message('<pre>' . print_r($view->result) . '</pre>'); // to get the correct $result->FIELD_NAMES for your particular View

    // what we are first going to do is go through the results of the View
    // and create an array of unique taxonomy ids that we find.
    // we are going to store that info in array $unique_tids
    // we are also going to keep a count so we can sort on "popularity"

    $unique_tids=array();
    $count_tids=array();

    foreach($view->result as $r => $result) {
      if ($result->term_data_vid != 'THE_VOCAB_WE_ARE_LOOKING_FOR' ) { // looking back, I probably could improve the View substantially by filtering on just one taxonomy vocabulary :)
        unset($view->result[$r]);
      } else {
        $count_tids[$result->term_data_tid]++;  // keep count of how many times we see this tid
        if(in_array($result->term_data_tid, $unique_tids) || !$result->term_data_tid) { // if we have already seen this tid, or it does not exist, delete this row from the results
          unset($view->result[$r]);
        } else { // we haven't seen it, so keep it in the View results
          $unique_tids[] = $result->term_data_tid;
        }
      }
    }

    // at this point we could just return and our View would contain the
    // unique genres, but it would be "sorted" based upon the order in which
    // the node it was first tagged in was created (I think) but we want to
    // get fancy and sort this listing with the most popular genres first
    // based upon how many pieces of content has been tagged with it, so...

    arsort($count_tids); // sort the counts in reverse order so the largest counts come first
    $new_result=array();

    // crude but effective ... curse you for making me look at years old bad code :)
    // but basically go through the counts and find the Views row that corresponds

    foreach($count_tids as $c => $count) {
      foreach($view->result as $r => $result) {
        if ($result->term_data_tid == $c) {
          $new_result[]=$result;
        }
      }
    }

    // we now have our unique results in the order we want so set
    // the View to it...

    $view->result=$new_result;

  }

  // any other pre_render()ing goes here...

}

And that's what I did to present unique genres in a location sorted by how many pieces of content were tagged with a particular genre.  Let me know of any/many typos in the code (I had to clean out a lot of extraneous code to get it down to the basics) and or if you would like any other explanations.  Also looking back (I wrote this in my nube stages of Drupal) I can clean up a lot of it.  Thanks Drupal Answers for making me go back and rewrite totally working two year old code the right way :)

Oh, looking at comments in my code, this created havoc with paging so in my system I just listed everyone on one page since I didn't have all that many genres to worry about.  I think if you did this in hook_views_post_execute() instead it would respect paging.


Fivestar Field Not Showing I've enabled Fivestar and added it to the comments field and made sure its in the comment display as well.

I've allowed anonymous and other users the ability to use Fivestar in Permissions. I've changed comments permissions so users can leave them and see their own.

I've created a new content piece and flushed caches to check if it only provides the field on NEW items.

In firebug on FF it says the rating field is in there but for some reason it's not showing up on the screen. Here's the code from Firebug:

Any idea what might be going on here or ways to fix it?

it'll will work if you change the Widget type on the Comment Fields tab to "Stars (rated while editing)". Give it a try.


Force a page to be rendered in admin theme (overlay mode) Is there a way to force a page to be rendered in admin theme, Like pages that their path begins with 'admin/'?

You can also do this by making a custom module.

Method 1

Use this if you want to theme an existing page, based on Drupal's internal path (aka path source). This example uses hook_custom_theme.

<?php
function MYMODULE_custom_theme() {
  // match node/1
  if (arg(0) == 'node' && arg(1) == '1') {
    return variable_get('admin_theme');
  }
}

Method 2

Use this if you want to theme an existing page, based on URL path (aka path alias). This example also uses hook_custom_theme.

<?php
function MYMODULE_custom_theme() {
  // get arguments
  $arg = explode('/', substr(request_uri(), strlen(base_path())));
  // match {wildcard}/path
  // Using strpos as $arg[1] may end up having stuff like so ?order=title&sort=asc
  if (isset($arg[1]) && strpos($arg[1], 'path') !== false && !isset($arg[2])) {
    return variable_get('admin_theme');
  }
}

Method 3

Use this if you want to theme and create a page. This example uses hook_menu. To learn more, take a look at another great article on hook_menu.

<?php
function MYMODULE_menu() {
  $items = array();

  // match some/path
  $output['some/path'] = array(
    'title' => t('Page Title'),
    'page callback' => 'MYMODULE_page',
    'theme callback' => 'variable_get',
    'theme arguments' => array('admin_theme'),
  )
}

function MYMODULE_page() {
  return 'Hello world.';
}


Change format of webform emails via hook I'm trying to alter the output of webform submissions in emails. At the moment, I'm just looking for the correct function. I can see there is a hook to alter the rendered output, which is being hit, but it is not changing the output of the emails. Am I replacing the Theme function in the correct place?

function seven_webform_submission_render_alter(&$renderable) {
  $renderable['#theme'] = 'seven_webform_submission_table';
  dpm($renderable);
  kpr($renderable);
}

function  seven_webform_submission_table($node, $submission, $email, $format) {
  return 'test';
}

The hook you are looking for is hook_mail_alter.

To modify webform submissions emails your code should look like:

function MYMODULE_mail_alter(&$message){
  if ($message['module'] == 'webform' && $message['key' == 'submission']){
    /*** Place your code here ***/
  }
}

This will alter just the webform submissions emails.


How to add a field to the contact form in Drupal 7? I want to add a phone field and a company field to the contact form. How to overwrite the form in template.php? Thank you

This module http://drupal.org/project/contact_field will do what you want and I have know about it since D6, but the last time I try it in D7 it was buggy.

So far the best alternative I have found that works all the time like a charm is the webform module http://drupal.org/project/webform as you will be able to add or remove fields as need it and the email support works well and you also get the bonus of storing all the contacts attempts in case your email server or service was down for any reason.


How can I override the menu toggle on AdaptiveTheme? The menu renders:

Menu

which is hidden when in a viewport bigger than tablets. I would like to replace the "Menu" part with a  element with an icon instead, How can I override this?

Oddly enough I haven't really seen this issue addressed anywhere else.  I found that the most straightforward solution is to put this in your theme's template.php and then style the span tag:

function your_theme_preprocess_block(&$variables) {
  if ($variables['block_html_id'] == "block-system-main-menu") {
   $variables['title'] = "";
  }
}

Cheers


New image field type for Articles only displaying on the article node itself, not on taxonomy or custom view pages I am having some issues with custom field content only displaying on the individual node. I have created a new field called field_second_image for the Article content type. I am calling it right under the regular field_image with print render($content['field_second_image']); in my node--article.tpl.php file. On the actual article node both images display properly. However, on a taxonomy list page or the custom article view page I have created, the second image does not show up. I think this relates to the general issue I've been having getting custom field content to display on pages other than the individual node page. Is there something I'm completely missing about getting this content to appear on other pages? Any help would be greatly appreciated, thank you.

Yes, the concept is view_modes. See this documentation page as an introduction.

node--article.tpl.php is used to show the Default view mode of a node. The related taxonomy page(s) for terms lists content out by default using the Teaser mode. This view mode is usually a succinct version of your complete node fields (sometimes showing a body teaser, and fewer fields).

Some modules to help you create new "view modes" of your content and easily customize how and what is shown are for instance (a small example list, by NO MEANS all of the possabilities, nor are these necessarily the best options):

Display Suite
Entity View Modes
Panels
Custom Formatters


Manage events among users I'm creating a community site where users should be able to create events and participate in other users events. I guess there are some options, but which modules do you think would work as candidates for building such a site?

It should be pretty simple by creating a content type "events", with the date fields using the Date module http://drupal.org/project/date. Then adding in the signup module for users to RSVP http://drupal.org/project/signup. You can also add in the calendar module for some displays http://drupal.org/project/calendar or the full calendar module http://drupal.org/project/fullcalendar


How can we hit/run the rules using code I have defined a rule in " Configuration » Workflow » Rules".
I have setup this as following...

EVENT : After saving a new account
Conditions : User has role(s)
             And role is (Referral Source)
    enter code here
Actions  Send a HTML mail.

But it's not sending the mail to register user. It's because of the user don't have the role as Referral Source at the same time. I am assigning the role using the PHP code and I would like to run the rule on same time. So how can I do that?

Create first rule "After saving a new user account" action "Add user role" to user and set its priority first(by set its weight 0 in SETTINGS of rule) and create one another rule for the same and set condition for role is(Reffereal source) and action send a HTML mail, set its priority down (by set its weight 1 in SETTINGS of rule) will work for you.


Building custom entities, but using existing modules? I've noticed a lot of useful modules already created such as workflow, ACL, diff, and more. But these only seem to work with "content types". In our project, we have decided that "content types" aren't really well suited for what we need (Entities make more since). Very complex relationships must be modeled. Our entities are just that, entities, not content.

The problem is that when building an entity using hook_schema() and hook_entity_info(), these entities are not available to be used with different modules such as workflow. Is there any way to make them available? Or will we have to code similar workflow functionality by hand?

Workflow does exactly what we need, except only on content types. We need it to work on entities as well.

Especially in Drupal core, Nodes are still something like a Super-Entity with a number of features only supported by them, like revisions and the whole node_access thing. The entity.module tries to implement these features generically for all entities, I'm not sure if everything is covered yet.

Many modules only support nodes both due to these missing features (You can't configure ACL's or workflows if there is no way to limit access in the API, diffing is pointless without revisions) and historical reasons (all of your listed modules are ports initially Drupal 6 versions or even older and have been ported to Drupal 7). The whole concept of entities represents a major shift in Drupal and not all modules have made that step (yet).

I guess that's one of the reasons why e.g. Commerce uses Nodes as the default way to display products.

Work is ongoing in Drupal 8 to unify these features and provide them for all kinds of entities.

This is not really an answer to your question, more an explanation of the status quo. As Alex already mentioned, many of those modules are working on supporting entities or an entity-aware successor is being worked on, like http://drupal.org/project/state_machine.


In a twig, how do I access different fields of a specific content type in a taxonomy term page I have some taxonomy terms like Computer and Accessories, Games, Furniture etc. which I am able to access as /camera-and-accessories, /furniture and so on. These taxonomy terms are associated with my Product content type.

A taxonomy page is always displaying default Product title and Body fields. But I want to customize this page so that it displays additional fields like field_product_price, field_product_photo from my Product content type. I was hoping for something like {{ content.parent }} but I don't think such a thing does not exist (yet!)

Template suggestion by Twig debug

<!-- THEME DEBUG -->
<!-- THEME HOOK: 'taxonomy_term' -->
<!-- FILE NAME SUGGESTIONS:
   * taxonomy-term--1.html.twig
   * taxonomy-term--category.html.twig
   x taxonomy-term.html.twig
-->
<!-- BEGIN OUTPUT from 'themes/custom/ezone/templates/taxonomy-term.html.twig' -->

According to the above output I first overrode default taxonomy-term.html.twig with taxonomy-term--category.html.twig. In taxonomy-term--category.html.twig I did not put anything but just "Hello World!" to check whether this file is being hit. After rebuilding cache the page renders this static text but surprisingly along with that the actual content also got rendered on the page, which I don't know why.

I deleted taxonomy-term--category.html.twig and copied taxonomy-term.html.twig from stable theme to my theme's templates folder. Removed all entries in that file and again tried the same thing with a static text block. Same thing happened again!

Somebody please help with these.
1. How to access fields of a content type on a taxonomy term page
2. Why overridden templates shows taxonomy content when custom template has nothing written in it.

I am sorry if above questions looks stupid or childish. I am a newbie to Drupal.

When you display a taxonomy term the output is produced by this View:

admin/structure/views/view/taxonomy_term

The taxonomy term itself is in the header

HEADER
Global: Rendered entity - Taxonomy term (Global: Rendered entity - Taxonomy term)

and uses the taxonomy term template shown in your question, where you have only access to the fields of the term, not the content.

The format of the content is configured in the main part of the View. Default is to display the content as Teaser:

FORMAT
Format:Unformatted list | Settings
Show:Content | Teaser

If you want to change the fields, you can customize the Teaser in UI:

admin/structure/types/manage/article/display/teaser

Or in this node template (this targets the View, so it would also work, if you changed the view mode):

node--view--taxonomy-term.html.twig

Or switch to a field based View and configure the fields inside of the View.


Site's settings file return blank screen I'm looking through a few of my drupal sites since the recent DRUPAL-SA-CORE-2012-003 security update. I noticed that on a few of them, if I navigate to the settings.php file location through the url. The browser is just a blank page. Does this mean I can access the settings.php file? Or is this the intended functionality due to proper permissions being set?

This is the intended functionality - your web/server user should be able to access the file and serve it over http but the file by itself doesn't do anything unless its included in the rest of the Drupal bootstrap.

The core concern of this security notice  is that there is a vulnerability if the settings.php file is writable or owned by the webserver.


How do I embed a form in a controller response? I have a controller that returns a normal renderable page array. I'd like to embed a form in that page, but the form is not appearing in the rendered output. The form is properly added to the renderable array correctly, but it's not in the final HTML for some reason. What's going on here?

Here's my controller (which extends ControllerBase through BlockController):

use Drupal\block\Controller\BlockController;
use Drupal\Core\Extension\ThemeHandlerInterface;
use Drupal\Core\Form\FormBuilderInterface;
use Drupal\Core\Render\Element;
use Symfony\Component\DependencyInjection\ContainerInterface;

class LayoutController extends BlockController {

  /**
   * @var \Drupal\Core\Form\FormBuilderInterface
   */
  protected $formBuilder;

  /**
   * {@inheritdoc}
   */
  public function __construct(ThemeHandlerInterface $theme_handler, FormBuilderInterface $form_builder) {
    parent::__construct($theme_handler);
    $this->formBuilder = $form_builder;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('theme_handler'),
      $container->get('form_builder')
    );
  }

  /**
   * Overrides the region demo page, adding placeholder elements for sortable
   * lists of blocks, plus a control panel form.
   *
   * @param string $theme
   *   The theme key.
   *
   * @return array
   *   The renderable page.
   */
  public function layout($theme) {
    $page = parent::demo($theme);

    foreach (Element::children($page) as $region) {
      if (isset($page[$region]['block_description'])) {
        $page[$region]['block_description']['#template'] .= '

';
        $page[$region]['block_description']['#context']['region'] = $region;
      }
    }
    $page['layout_control'] = $this->formBuilder->getForm('Drupal\block_ui\Form\LayoutControlForm');
    $page['#attached']['library'][] = 'block_ui/backbone.collectionView';

    return $page;
  }

}

To embed a form in a renderable array, you use:

$form_class = '\Drupal\my_module\Form\MyForm';
$build['form'] = \Drupal::formBuilder()->getForm($form_class);

Which is similar to your code.

But the problem is of a different nature. You are extending a special controller, one that returns a renderable array of '#type' => 'page'. It uses the page template to render the output and that template does not contain the {{ layout_control }} variable to output your form. If you use $page['header']['layout_control'] = ... to add the form to the render array, it should show the form in the header region of the layout demo page.


Assign to node all child terms if parent term selected I started to develop my first website with drupal. So far so good, I like this system, but I have one problem:
When creating new node, I want to assign all child terms if I select parent term.

Let's say, I have a vocabulary "Plants".
In this vocabulary, there are terms with this kind of hierarchy:

Fruits
--- Apples
------- Green
------- Red
--- Pears
------- Green
------- Red
Berries
--- Wild berries
------- Red
------- Blue

Now, when I create a node, I'm using Simple hierarchical select to select terms of this vocabulary. I'm using Views to display nodes.
Let's say I want to assign term "Apples" to a node. When I go to view the page and use Filter Criteria Content: Has taxonomy terms (with depth) (exposed) and choose "Apples", I can see my node.

That's OK. But I want my node to appear if I select Green or Red (under term Apples in terms tree). In other words, if I assign term "Apples" in node creation page, I want it to assign all of its child terms also to this node. I.e., if I assign Wild berries, I want terms Red and Blue (childs of Wild berries) to be assigned also. Because right now, by assigning term "Apples" and then filtering by "Apples" gives what I want, but if I filter by Fruits->Apples->Green, I get no results.

You can use the Taxonomy Term Reference Tree Widget module

  This module provides an expandable tree widget for the Taxonomy Term
  Reference field in Drupal 7. This widget is intended to serve as a
  replacement for Drupal's core Taxonomy Term Reference widget, which is
  a flat list of radio buttons or checkboxes and not necessarily fit for
  medium to large taxonomy trees.

How to use this module

Enable the Term Reference Tree module.
Go to the Manage Fields tab of any fieldable entity (such as a content type, taxonomy term, or user.
Add a new field with a type of Term Reference.
In the widget select box, select Term reference tree.

Note that you can also change any Term Reference field to use the Term Reference Tree widget, by editing that field and selecting Term Reference Tree on that field's Widget Type tab.


Search Api Solr - Pointing term links inside a view to its facet Using Search Api. Solr as a backened. Search pages built with Views. When adding a term field to a view, that term links to the core taxonomy term pages. That term should instead link to it's facet(not adding to the other facets if the user had previously click on other facets).

I have searched high and wide for any documentation or discussion involving this, and only found a few issues that didn't go anywhere. There is hardly any discussion, which I find odd because I would imagine this would be a pretty common request.

Does anyone have any knowledge on this issue?

Why would you want the fields in the search results to have taxonomy terms that are linked to the facet URL instead of the taxonomy page of the item? It just seems a little redundant, because that's what the facets there are for.

A solution would be to use FacetAPI Pretty Paths and rewrite the output link of the taxonomy term to match the URL of the facet. You'll need the fields term name and id, then format as : www.example.com/search-page/[pretty paths term]/[term name]-[term id]


Average value of Multiaxis FiveStar value configuration Drupal 7.7, FiveStar 2.x-dev, References module, Unique field.

I have node value of Story tale
Every user can write an Review and rate each story tale with multiaxis fivestar like: Idea, Grammar, etc. configures as rating references.
Every user can create only one review per each story tale (unique field module).
Rating is available when User create a Review node (so not ajax).

I can attach average rate of each one from multiaxis like Average Grammar, Average Idea etc for story tale by views.

What I can't do is: how to compute average of all multiaxis values it menas create one number computed from rating of Grammar + Ideas.

I tried create a Fivestar field for overall (average value).
Then I created Computed field which compute overall value of review.

$overall = ($entity->field_style[$entity->language][0]['rating'] + $entity->field_rate[$entity->language][0]['rating'])/2;
$entity_field[0]['value'] = $overall/10;
$entity->field_overall[$entity->language][0]['rating'] = $overall;

Well Problem is that In field_overall is stored requested value, but VotingApi don't register this change created by computed field and it count 0 as stored value.

So.
1. Problem is that fivestar store this value before computed field compute overall rating
2. Or problem is, that fivestar is reading value not from $entity->field_overall but from other value.

The easiest thing to do would be to set the value yourself with either hook_entity_insert/update or in a custom submit handler to the form.

The values are stored in the fields tables and not voting API when you use the five star with fields.


How can I create multiple dashboards with Open Atrium? By default each Open Atrium group has its own dashboard. What I'd like to do is to create multiple dashboards (pages?) for each group. My goal is to create separated dashboards with different contents, just like website's pages. Any idea on how to do this with Open Atrium?

Users with sufficient permissions should see an "Add custom" link on the Dashboard.  This link lets you create additional Dashboards for a single group, each with its own content and layout.


Programmatically set date fields in Drupal 7: Date, Date (ISO Format) and Date (Unix Timestamp) Using the Form API and hook_form_alter(), how can I manually set (force) the values for each of Drupal 7's date field types using a valid Unix Timestamp?

When the form is finally submit the field_date types are always empty arrays.  Below is the broken code I'm working from.

hook_form_alter(&$form, &$form_state, $form_id) {

    // http://drupal.org/node/1455576 - Date
    $form['field_date'][LANGUAGE_NONE][0]['value'] = time();

    // http://drupal.org/node/1455576 - Date (ISO Format)
    $form['field_date_iso_format'][LANGUAGE_NONE][0]['value'] = time();

    // http://drupal.org/node/1455576 - Date (Unix Timestamp)
    $form['field_date_unix_timestamp'][LANGUAGE_NONE][0]['value'] =time();
}

I should mention the fields widget is set to text and it's format is 'Y-m-d H:i:s'

I have also tried date('Y-m-d H:i:s', time()) instead of time().

Example dpm() output.

I should also note that as a workaround I can set the field if I modify it in hook_node_presave().  To do this I set $node->field_date['und'][0]['value'] = date('Y-m-d H:i:s', $my_unix_timestamp); I would still like to understand how to do this using hook_form_alter instead.

Here is a code that treat site timezone right for me:

 $node->field_date[LANGUAGE_NONE][0] = array(
    'value' => format_date(strtotime('now'), 'custom', 'Y-m-d H:i:s', 'UTC'),
    'timezone' => 'UTC',
    'timezone_db' => 'UTC',
  );


common header and footer for all pages in drupal7 i use different layouts for different pages for a large website, which share common header and footer. how can i create common header and footer templates and link the templates to these pages.

The most common is to structure your header and footer using the core block system. Another solution would be to place the structure in the page.tpl.php. If you have a lot of page.tpl.php files and still want to use templates, then it might be better to place the header and footer in the html.tpl.php template.

Personally I would recommend using the blocks system.


Failed opening required 'sites/all/modules/og/og.field.inc I was trying to add the BoWoB Chat module to my site. It doesn't work and the error log file in its directory contain multiple lines like the following ones:

  Failed opening required 'sites/all/modules/og/og.field.inc' (include_path='.:/usr/lib/php:/usr/local/lib/php') in /home/public_html/mysite.com/sites/all/modules/og/og.module on line 16

Lines 15 and 16 are the following ones.

// Load all Field module hooks for Organic groups.
require(drupal_get_path('module', 'og') . '/og.field.inc');

The file og.field.inc is in the same directory as sites/all/modules/og/og.module and its permissions are 644, so it is readable.

This one has me stumped. Do you have any suggestion?

Your file at least needs to have 755.

With 644 it is readable, but is not executable so the file cannot be managed as a php file (executable).


Loop trough a list of referenced nodes in order to get a specific field value I am using Computed Field to get some values;

I have a Template node that holds an Entity Reference multivalues field to a series of other nodes, all referenced nodes of the same type. The referenced nodes have a text field which value I need to get.

Until now I've managed to get the "target_id" of the referenced nodes, but I can't manage to get the values:

$tpl = field_get_items($entity_type, $entity, 'field_plan_tpl_select_trainings');
$nids = array();

foreach ($tpl as $field_item) {
            $nids[] = $field_item['target_id'];
}

What is the next step in order to get the values of a specific field for all the referenced nodes? I mention that the field has only one value.

the "target_id" is the nid (node id) of the referenced entity, now if you want to get the values of a specific field of the referenced entities you can do the following:

$values = array();

foreach($tpl as $field_item){
$values[] = node_load($field_item['target_id'])->field_your_field;
}

you just need to load the entity and then get the field you are looking for. Devel module will make your life easier in that purpose

If the entity you are referencing is not a "node" so you can load the entity using entity_load() and then use entity_metadata_wrapper() for get the fields and all the info you need from each entity.


How to get comment votes using raw sql query? In a D7 site, comments are voted using rate module.

I'm wondering how to get the rating of all comments of 'story' content using raw sql query?

Here you are SQL to get the total vote count for widget type number for each comment od node type "story"

SELECT c.cid,count(v.vote_id) FROM votingapi_vote v JOIN comment c ON v.entity_id=c.cid JOIN node n ON n.nid=c.nid WHERE n.type='story' GROUP BY v.entity_id;

If you want to get the total numer of votes for all "story" nodes then:

SELECT c.cid,count(v.vote_id) FROM votingapi_vote v JOIN comment c ON v.entity_id=c.cid JOIN node n ON n.nid=c.nid WHERE n.type='story'

Or conditional for voting type like you did:

SELECT c.cid, count(v.value) FROM votingapi_vote v JOIN comment c ON v.entity_id=c.cid JOIN node n ON n.nid=c.nid WHERE n.type='story' and v.value_type='points' GROUP BY v.entity_id;


How to use the data from a deleted Field Collection item in a Rule? My 'Article' nodes have a Field Collection, called 'Amounts', that contains an integer field. After deleting a Field Collection item, I'd like to substract some Userpoints from the node's author, based on the sum of the integers in the non-updated and updated node.
In order to do so, I created a Rule with the event "After updating existing content of type Article" in which I'm looping over 'Amounts' for the updated and non-updated node. The problem is that both loops use the data from the updated node (after the Field Collection item was deleted, that is), resulting in identical values.
Here's the Rule's output for a node that has 3 items with corresponding values 1, 2 and 3 after deleting the first item:

Non-updated node: Sum = 5. (This should be 6.)
Updated node: Sum = 5.

Is it possible to run the Rule before deleting the Field Collection item in order to be able to grab the necessary data values? Is there another way to use the deleted data?

Instead of trying to get access to the deleted value with Rules, it's easier to store the sum in a new hidden field, called "Sum". In that way, the 'old value' will always be available in any Rule. Just make sure that you update "Sum" when a new Field Collection item is saved or an existing item is deleted. That can easily be achieved with another Rule.


Which Drupal module support spatial filtering with apache solr module Which Drupal module support spatial filtering with apache solr module.
like either Location,geofield,geolocation,getlocation or any other.

Have a look to the Search API Location module. There is also demo site.

  The Search API spatial module (7.x-2.x branch) adds the possibility of location based searching to the Search API module.
  Currently only Apache Solr is supported as server.
  You can find a demo on http://spatial.mollux.be.


Form / Block / Template I try to theme a custom form in my block.

Here my code :

  boutique.module

/**
 * Implements hook_theme().
 */
function boutique_theme() {

  return array(
        'ajout_panier_form'=> array(
            'render element' => 'form',
            'variables'=> array(
                'form'=> NULL,
            )
  )
  );
}

  AjoutPanierForm.php

/**
 * Class AjoutBlockForm.
 *
 * @package Drupal\boutique\Form
 */
class AjoutPanierForm extends FormBase {

  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'ajout_panier_form';
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {

        $form['#attributes']['oninput']='showPoids.value = poids.value';

        $form['poids'] = array(
            '#type' => 'range',
            '#title' => $this->t('Poids en gramme'),
            '#min' => 500,
            '#max' => 20000,
            '#default_value' => 500,
            '#step' => 100,
            '#attributes'=>array('id'=>array('poids')),
            '#description' => $this->t(""),
            '#required' => TRUE,
        );

        $form['showPoids']=array(
            '#type'=>'markup',
            '#markup'=>'<output id="showPoids" for="poids">500</output>'

        );

      $form['ajouter'] = array(
          '#type' => 'submit',
          '#value' => $this->t('Ajouter'),

      );

    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
drupal_set_message('ok');

  }

  AjoutPanierBlock.php

/**
 * Provides a 'AjoutPanierBlock' block.
 *
 * @Block(
 *  id = "ajout_panier_block",
 *  admin_label = @Translation("Block Ajout panier"),
 * )
 */
class AjoutPanierBlock extends BlockBase {

  /**
   * {@inheritdoc}
   */
  public function build() {

    $form = \Drupal::formBuilder()->getForm('Drupal\boutique\Form\AjoutPanierForm');

    $build = [
        '#theme' => 'ajout_panier_form',
        '#form' => $form,
  ];
    return $build;

  }

}

And my template :

  ajout-panier-form.html.twig

<form{{ attributes }}>
    {{ form.poids }} {{ form.showPoids }}
    {{ form.form_build_id }} {# required #}
    {{ form.form_id }} {# required #}
    {{ form.ajouter }}
    {{ children }}
</form>

My block call my template and my form is display.
But my submit doesn't call my method in my form controller where i put a

drupal_set_message('ok');

How add the actions form into template ?
i have put {{ children }} but he doesn't work like the balise {{ form }} alone.

If you want to theme a form, better override the form.html.twig template, because you don't know what happens in the background of this template and you don't want to do this all from scratch in your own template.

So put the complete form in the block:

public function build() {
  return \Drupal::formBuilder()->getForm('Drupal\boutique\Form\AjoutPanierForm');
}

And copy the form.html.twig in your template and change it.


Is this the right way to do this? Inserting a block into the content body field of a node I'm very new to using Drupal 7 and trying to understand the correct way to insert a book navigation menu block into the content field of a node, or any field/block of content into anything for that manner.

Anyways, one solution I have come up with is this:
In field--body.tpl.php

<?php
$block = module_invoke('book', 'block_view');
//render book menu
if($block){
echo'
';
print render($block);
echo'
';
}
?>

I have no idea if this is the proper/orthodox way to do this; I'm pretty sure a better way would be with a pre-process in template.php. Could someone explain/demonstrate how would this get implemented in that way?

I am not one to say what is a/the best way, but if template_preprocess_WHATEVER() is, you set it up something like this:

function template_preprocess_WHATEVER(&$vars) {
  if ( CONDITIONS YOU NEED IF ANY ) {
    $block = module_invoke('book', 'block_view');
    if ($block) {
      $book_block_view='
';
      $book_block_view.=render($block);
      $book_block_view.='
';
    }
    $vars['book_block_view']=$book_block_view;
  }
}

and now you would have $book_block_view available in WHATEVER to print or use.


How to display a field only if option (x) isn't selected In one of my content types, I have a Status field (field_status) which is a List(text) field displaying 3 radio button options set to the following key|label values:

0|In Stock
1|Under Deposit
2|Sold

I have a custom twig template file for this content type and was wondering how I would display the value if the option isn't 0 (In Stock). In Stock is pretty much the default option so when the item is sold/under deposit, I want a "Sold/Under Deposit" banner to appear in the upper corner of the picture of the item.

Also, I have a view displaying a list of these content types so how would I only show this value again if the selection isn't "In Stock". I don't have a custom template for the view as I did it all in the UI so I'm hoping there's a way to do this there as well.

I feel like this should be a simple solution but for some reason I'm having issues with it.

I figured it would be something like the following but this doesn't seem to work:

{% if field_status is not ['0'] %}
  {{ field_status }}
{% endif %}

I'm assuming my syntax is wrong. What would be the proper way of doing this?

Create a file in template folder : node--articles.html.twig

             {% if content.field_gif_image|render is not empty %}

{{ content.field_gif_image }}

             {% elseif content.field_image|render is not empty %}

{{ content.field_image }}

             {% endif %}
             {{ content.body }}
             {{ content.field_more_on }}

Fields defined are just for reference, hope It can give you a clue of how to do this.


Confusing Widget of inline entity form Inline Entity Form ships with two widgets as Inline entity form - Single value and Inline entity form - Multiple values when I use Inline entity form - Single value, I only get add entity form and when I use Inline entity form - Multiple values I get option to add/edit both.

what I was expecting to see to have both add/edit with Inline entity form - single values with only difference of not allowing to have multivalued field in this case.

Am I missing something?

If you modify your inline entity form by writing a small module, (for this look at README and the ..api.php) you can set your default values by loading them from the entity. So your former entries are available.


How to make full text search case Insensitive I'm using Search api (8.x-1.0-beta3) and Database Search (8.x-1.0-beta3). I have created DBIndex Server and created index for content type 'Test' and then created search index view with filter 'Full text search'. But I observed search is case sensitive. How to make this search as case insensitive.

Thank you in advance.

Please follow the below steps:

Click on Configuration > Search and metadata > Search API
Click on Index and go to Processors format . Enable the checkbox Ignore case Makes searches case-insensitive.

Clear the index and reindex the items


How do I set a variable to the value of a field another field? How do I set a variable to the value of a field another field?

For example, what is the equivalent of the following code, which should set the value of video_Source to the value of the field that is not empty/null?

{% set video_Source = content.field_video_upload or content.field_video_youtube %}

This is something better suited for preprocess in my opinion (I don't like a lot of conditional etc logic in twig files):

$variables['node_video'] = NULL;

if ($node ... field_a has value) {
  $variables['node_video'] = // set to render element for field a in 'content';
}

if ($node ... field_b has value) {
  $variables['node_video'] = // set to render element for field b in 'content';
}

Then in twig:

{% if node_video %}
  {{ node_video }}
{% endif %}

Basically, if this variable is not null, it should point to one of the $variables['content']['field...'] items from the preprocess code, then render it. {{ node_video }} in this case is the equivalent of {{ content.field_name }}, to spare a lot of IF/ELSE/OR stuff in Twig.

But what is likely easier is leveraging Media and Media Youtube with Media Video and using one field. That should scale. Imagine you want to add Vimeo, Twitch, or other supported Media sources in the future, you would have to keep expanding on this code.


How to list all available reviews for coder? I am using drush with Coder (7.x-2.x) and I would like to know what are available options for reviews:

$ drush help coder
...
--reviews Run the specified review(s), "all" runs all reviews, also accepts a comma separated list (no spaces).

Where I can find them?

The list will depend on which modules you have that implemented hook_reviews(); hook implementations return a keyed array that has the name of the review. These items are combined with a default list that come from the coder_review module.
The default list come from that dir is: upgrade47,   upgrade5x, upgrade6x, upgrade7x, upgrade8x, comment, druplart, i18n, i18n_po, production, security, sniffer, sql, style


How to set up Google+ authorship in Drupal 7 How do you set up Google+ authorship in Drupal 7?

So I can link my drupal website to our Google+ account so that our Google+ profile pic can appear in the search engines next to our site.

The easiest way is with the Metatag module:

  The Metatag module allows you to automatically provide structured
  metadata, aka "meta tags", about your website. In the context of
  search engine optimization, when people refer to meta tags they are
  usually referring to the meta description tag and the meta keywords
  tag that may help improve the rankings and display of your site in
  search engine results.

After you install/enable the module, you can edit the metatags at admin/config/search/metatags  The Google+ Author is under Advanced.


How do I set the default values for creating a new content type? This is a follow up to my question in Can I change the Display Settings by modifying the database? which was answered. Basically, I could not get to the 'display authoring and date information' checkbox because of a module installed. Running the command 'drush cedit node.type.article' as given in @4k4's answer allows me to change this setting.

However, when a new content type is created, the type has display_submitted: true set meaning I have to go in and change it whenever a new content type is created, which I sometimes cannot do.

Is there a way to change the default settings so that any new content type has display_submitted: false by default?

For content or config entities you can set default values in a hook_ENTITY_TYPE_create():

use Drupal\node\Entity\NodeType;

/**
 * Implements hook_ENTITY_TYPE_create() for 'node_type'.
 */
function mymodule_node_type_create(NodeType $node_type) {
  $node_type->set('display_submitted', FALSE);
}


Changing default file permissions for group? I'm not super familiar with the permissions structure in Drupal 7 so I'm not sure if this is actually an Apache question or a Drupal question.

I have a style.css file in /sites/all/themes/mytheme/css/ that I need to edit via FTP. That css folder also contains files that are edited via the Omega Tools UI. It appears that each time I use the UI to change style information, Drupal changes the owner of the css folder from ftpuser to www and gives it permissions 754 (group cannot write).

I am okay with the owner changing to www but I need to be able to edit my style.css file via FTP, so I need permissions to be 774. Is there a way I can set a default permissions structure on a folder or on Drupal in general that sets permissions to 774 instead of 754 whenever the system changes the owner of a folder?

I don't believe Drupal or Omega will be setting the default permissions to 754, more likely it's a default that your webhost has configured.  Things I would check would be:

If you upload a file as ftpuser, does it default to 754?  If so, then they have a default permission set to 754.  You could contact the host to see if they are able to change that.
If you manually create a file using PHP, does the file get created at 754? If so, same as above.
If they're created at something other than 754, then it's likely Omega or Drupal that is doing that, but again I don't believe that's the case.

In any event, I've successfully gotten around this problem for many users by integrating a web-based file manager like IMCE, which allows you to manage files without using FTP.


Why does YAML parser strippes out underscore? In my Drupal project I have a yaml configuration file which contains an id with the value 16_9 (more precisely it is part of the Crop module configuration). When checking differences between the active Drupal configuration and this staged one, Drupal lists this config, although it should be identical:

As you can see, the YAML parser processes the id as an integer and stripes out the underscore.

This problem only exists in my Drupal-VM. In our testing and production environment (non Drupal-VM) with the identical code and data base the config sync is fine. It does not show any differences.

There might be different YAML parser (and/or extensions) in use which behave not the same way. But I don't know if this is a Drupal or VM issue. I don't think that it is specific to the Crop Module.

My Environment

Vagrant 1.9.2
VirtualBox .1.18 r114002 (Qt5.6.2)
Drupal VM 4.5.0 (with Ubuntu)

It's actually a native YAML issue. As Saltstack's YAML Inconsistencies page observes:

  If a definition only includes numbers and underscores, it is parsed by YAML as an integer and all underscores are stripped. To ensure the object becomes a string, it should be surrounded by quotes.

It's fairly common practice; Java does it too, for example

So wrap your ID in quotes and it should be fine.


Wrong date field format in Chrome I am working on a form.

I have this date field:

$form['date'] = [
  '#type' => 'date',
  '#title' => $this->t('Date:'),
  '#attributes' => [
    'type' => 'date',
    'placeholder' => 'dd/mm/aaaa',
    'data-drupal-date-format' => ['d/m/Y'],
  ],
  '#date_date_format' => 'd/m/Y'
];

When I set the date to August 30, 2017 I get

Firefox (Excellent!):

Chrome (Wrong!):

How can I set the 'd/m/Y' format in Chrome?

In Drupal 8, the date form element uses the HTML5 date input format by default.  Chrome is one of the browsers that support this.  So, it looks like your browser is using US style dates.

Changing to

$form['date'] = [
  '#type' => 'date',
  '#title' => $this->t('Date:'),
  '#attributes' => [
    'type' => 'text', // <=== CHANGE THIS
    'placeholder' => 'dd/mm/aaaa',
    'data-drupal-date-format' => ['d/m/Y'],
  ],
  '#date_date_format' => 'd/m/Y'
];

should work, but I would recommend using a datetime element and configuring it for date-only inputs.  You can also configure that to not use the HTML5 inputs.


Folderstructure for template files Is there a restriction for template folders?
Like for name or structure ?

No, Drupal doesn't place restrictions on the names of any template file or folder.

Restrictions for file naming are handled at the OS level.


Where are the term tokens gone? I have a hard time setting up URL alias patterns when it comes to taxonomy terms. Especially, I'm stunned that in the Replacement under Content Paths, a term reference field shows just one flat item [node:field_term_name], rather than an expandable set of taxonomy-related tokens. This is the way it used to be (as in the screenshot here: Pathauto url of term for node?)
Have things changed or is it a bug?

Enabling the Entity_Token sub module does help with this issue, however, you need to add a "Term Reference" type field to any of your content types in order to see your taxonomy vocabulary be listed as one of the replacement tokens.
In my case, I had enabled the entity_tokens module but I was still not able to see my vocabulary as one of the replacement tokens.  Then I added a new field to my "basic page" content type.  The field type I added was "term reference" and I selected my custom vocabulary as its default vocabulary.  This resolved my issue.


How to add Google recaptcha to a custom form? I have a form I'm creating programmatically with a custom module, and I need to add the Google recaptcha to it. In the Google reCaptcha module's settings page (/admin/config/spam_protection/google_recaptcha/forms) I only see the login, register and comments forms and no way to add a custom form (like in the captcha module).

I googled as well as looked in the Google Captcha module's files and API file and can't find any hooks or info on how I can add the captcha element to a custom form. Any pointers would be appreciated!

You can use recaptcha module (https://www.drupal.org/project/recaptcha)
and in captcha settings(admin/config/people/captcha) you can add your custom form's form_id and select the challenge type reCAPTCHA(from module recaptcha). This should work.


Alter custom menu links with a session variable I've got a new problem, searched everywhere but was unable to find a solution.

I'm quite new to PHP / Drupal.

To explain :

I would like to use a session variable (got from a form) in my custom menu links, like this :

/path/{year}

So,in a module I have routes and links defined this way :

my_module.routing.yml :

testlink:
  path: '/path/{year}'
  defaults:
    _controller: '\Drupal\my_module\Controller\PageController::init'
    _title: 'Test'
    year: ''
  requirements:
    _permission: 'access content'

my_module.links.menu.yml :

testlink:
  title: 'test'
  description: 'test'
  parent: my-custom-menu
  menu_name: my-custom-menu
  route_name: testlink
  route_parameters: { year: '0000' }

Everything works fine, my menu link is displayed like this :

/path/0000

But I cannot find a way to use my session variable to replace "0000".

Any idea ?

Thanks in advance.

The menu links defined in yaml files are static. For dynamic menu links you have to use a menu link class:

src/Plugin/Menu/CustomMenuLink.php

<?php

namespace Drupal\mymodule\Plugin\Menu;

use Drupal\Core\Menu\MenuLinkDefault;
use Drupal\Core\Url;

/**
 * Custom Menu Link
 */
class CustomMenuLink extends MenuLinkDefault {

  public function getTitle() {
    return $this->t('Test-Link');
  }

  public function getRouteName() {
    return 'entity.node.canonical';
  }

  public function getRouteParameters() {
    $nid = rand(1,10);
    return ['node' => $nid];
  }

  public function getCacheMaxAge() {
    return 0;
  }

}

This example is a menu link randomly selected a node between 1 and 10. For code depending on a session replace the cache max age with a context:

  public function getCacheContexts() {
    return ['session'];
  }

Point the yaml file to this class to replace the static details of the route with the dynamic methods defined in the class:

mymodule.links.menu.yml

mymodule.testlink:
  weight: 10
  menu_name: main
  class: Drupal\mymodule\Plugin\Menu\CustomMenuLink


Load Panel from custom module? Anyone know of a way to export all the data found in a panel layout, context e.g. into a custom module in order to deploy from development to production?

Something like with views via the Implements hook_views_api() ?

You can use features module to export your panel page in form of a module.


Conditional fields module, "OR"-like operator Can conditional fields module, or another module like it, make a field hidden/shown using an "OR"-like operator? For example,

if field A = 'yes' OR field B = 'no', then show field C.

Right now the conditional field module treats everything as an "AND" operator. For example, if field A = 'yes' AND field B = 'no', then show field C. I want field C to show up on either one of those conditions, not both.

Maybe, the Views If Empty module could be of use to you. Here is a quote about it (from the module's project page):

  ...  enables a view to output a field if another field is empty.

  You need Views If Empty when you have a content type with an embedded video and an imagefield thumbnail. The nodes always have the images but occasionally have a video. You want your view to display the image field when the video field is empty, display the video field when available, and never display both.


D7 join on cck fields in views I have 2 content types which are imported via feeds; One is "user" with a cck field referencing its primary key: user.id

The second is "time_entry", which has a cck field for the fk reference to user id: time_entry.user_id

Now that they are coming into drupal, i am trying to create a view which would have:
time_entry.id, time_entry.user_id, and user.fname, user.lname, which are in the user nodes.

I tried a few different things; I am not too familiar with d7 so entities, bundles, the relations module, etc. are confusing me. I got tangled up trying to even create a php field in views which would get the nid of the user referenced in the time entry table and load that user.node. Any help would be greatly appreciated.

Some questions first. What's the data model?

"Time Entry" -> "User Node" or
"Time Entry" -> "User Node" -> "User Entity"

Are you using "User Reference" and "Node Reference" fields for the reference fields? If so, no need to use PHP to do it. You can use the Views UI for this functionality.

First, make sure the View's Row Style is "Fields" the format is Table and the view type is Node. Filter by "Time Entry" type.

Then, on the Advanced Tab, add a "New Relationship" and choose the reference field you use to reference the "User Node". By doing this, it'll enable you to access the "User Node", aside from the original "Time Entry" data.

If you have 3 entities related, you have to add another relation to access the 3rd entity's data. Follow the same procedure as above (adding a new relationship) and use the "User Node" reference field to access the "User Entity" data.

Then you can just add the fields you want, namely user name, last name and so on.

Hope this helps.


Drupal 7, show drupal blocks only on specific pages with PHP code? I were working on drupal 7. In block configuration, under pages i went for an option
"Pages on which this PHP code returns TRUE (experts only)"

Added the following code:

<?php
global $user;
$username=$user->name;
if($username=="admin")
{
   return TRUE;
}
else
{
  return FALSE;
}
?>

It's shows me an error message at the top of the screen:

  Notice: Undefined property: stdClass::$name in eval() (line 3  of C:\xampp\drupal77\modules\php\php.module(75) : eval()'d code).

I don't know, how to fix it out. Please help me out.Thanks

How the $username variable's value will be available there?
If you want to use current logged in user, write it like
global $user;
and check $user->name instead of $username.


How to edit one time login URL? I want to change the one-time login URL, which is the link being sent to the user in order to reset his password.

I want to make it smaller and not have the random letters in its URL.

Is this possible? Where can I change this?

It is possible to do that, but you definitely shouldn't do it.

The "random characters" are there for security purposes. Without them, it would be easier to reset passwords of other users, including the super administrator (uid: 1) for example. The hashes in URL are also longer in order to prevent collisions and make it harder for others to guess.

Password reset URLs are time-sensitive and expire after 24 hours (by default) if not used. Here is the breakdown of the password reset URL:

User ID of the member who is trying to reset the password.
Timestamp of when the password reset has been requested.
Hashed password. This is the element that is checked against the token stored in the database, and verifies that the link is valid. It's a unique hash that is built using the timestamp of when the password reset request has been made, account login information, hashed password and user ID. By doing so, the system makes it almost impossible to generate this information on your own, meaning that only your website is authorized to issue those URLs. And those URLs are issued only if you know the username or email address of an existing account.  See the source of user_pass_rehash() to understand this better if you want.

All of this was made so your users and your site would be more secure.

If you want to fully understand how this process works, open the /modules/user/user.pages.inc file, and check specifically the user_pass_reset() function. That function is responsible for validating the request, and allowing the users to reset their password.

Hope this makes sense; I wrote it pretty fast but it should cover the main points.


drupal2dupal migration add a default taxonomy term I want all of my imported data to have a default taxonomy term, since the source doesnt have this taxonomy term .  I have adde the tid of the taxonomy term in the UI as attached, but the content is being imported without this taxonoy term  . What am i doing wrong?

I was able to do it by typing in the name of the Taxonomy term , not the tid next to the field i wanted to import


How to set the ordering of a taxonomy term's listing page When you click on a tag term (or any other taxonomy term), a page is displayed listing the nodes tagged with that term. How can the nodes be displayed alphabetically?

The only module that looks like it could yield results is this one: http://drupal.org/project/taxonomy_display

But as of yet, can't get this to work as expected.

Using the Views module, enable the Taxonomy view. You can customise the content of the tag results page by adding/ordering fields, just as you would any other view.


Why does a header set via drupal_set_header() revert to text/html? I'm using the views_rss module in Drupal 6. Whenever I build out a View using this plugin, the following header is sent in a template_preprocess function:

drupal_set_header('Content-Type: application/rss+xml; charset=utf-8');

This seems to be ignored, as the page is ultimately sent with a text/html header. It seems that my header is getting appended, but text/html is either sent first or last (whichever is ultimately interpreted by the browser) and thus has no effect.

How can I force a non-text/html header for a page output in Drupal 6?

I think you are too late in the template_preprocess hook. The views display will have set it's header already before your hook gets called.

To test my thought have a look at the return value of the function drupal_set_header. It shows you all headers sent before.

If I'm right: Try implementing a hook which is is called earlier (maybe even before execution of the view query). Then your header will have precedence.


D6 prohibit upload file extensions I'm using filefield module, and it has permitted extension field. Is it possible to disallow certain extensions (e.g. exe, zip, rar) instead of adding permissions for ones that are ok?

Not directly, but you could do that in your own custom form validation.  For example:

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

  switch ($form_id) {

    case 'YOUR_CONTENT_TYPE_node_form':

      $form['#validate'][]='YOURMODULE_valid_extensions';
      break;

    // any other forms here

  }

  // any other form alters here

}

function YOURMODULE_valid_extensions($form, &$form_state) {

  // $whitelist=array('txt', 'doc', 'pdf');
  $blacklist=array('xxx', 'exe', 'php');

  /* I am assuming that this is a single value field ([0] below) */
  $extension=pathinfo($form_state['values']['field_YOURFIELD'][0]['filename'], PATHINFO_EXTENSION);

  // if (in_array($extension, $whitelist)) {
  //   return;
  // }

  if (in_array($extension, $blacklist)) {
    form_set_error('field_YOURFIELD', t('Invalid file extension'));
  }

}

and if you leave the extensions field blank, filefield won't do any validation, but you will in the second function above.  I've also put in //'s basically what filefield is doing if you wanted to incorporate both.  If you do go this route, you will have to put some verbiage in your help section as the widget will most probably say all extensions are valid :)


Get enitity ID after programatically creating one I have a the following code:

// Create an Entity with wrapper
  $node = entity_create('node', array('type' => 'person'));
  $entity = entity_metadata_wrapper('node',  $node);

  // Add a node title
  $entity->title = $person['name'];

  // Add the address information
  $entity->field_person_address->thoroughfare = $person['address'];
  $entity->field_person_address->locality = $person['city'];
  $entity->field_person_address->administrative_area = $person['state'];
  $entity->field_person_address->postal_code = $person['postalcode'];
  $entity->field_person_address->country = $person['country'];

  // Save the entity
  $entity->save();

The data is saved in the DB perfeclty, but I need to get the entity ID of the new save node.

How do I do that?

You can use getIdentifier() method of the wrapper.

$node = entity_create('node', array('type' => 'person'));
$entity = entity_metadata_wrapper('node',  $node);
$entity->save();
$entity->getIdentifier();


Expanded navigation in Books By default the navigation in books is collapsed:

Fruits
Vegetables

Is there any way to make them expanded, so that the entire tree would be visible?

Fruits

Apples
Bananas

Vegetables

Tomatoes
Cucumbers
Carrots

Thank you!

The BookTree module does the job. Some details from its project page:

A simple tree presentation of one book.
What it does is to take as input a series of Book nodes and create a tree-like structure using Book node relationships.
Usage of the module is quite simple and flexible, and options exist to set the root node, the tree depth and to shorten long titles.

The BookTree Example contains a demo of it.


How to group fields in the form without grouping them in the node view? My issue is that using the field_group module will create field groups for the form and the node view. And I don't want to group fields for viewing, I just want to make the form neater.

Here's a failed attempt (seems to ignore the values from body and title fields): https://gist.github.com/9651054

Found it. Turns out the array keys are very important. The first time around, I added the form fields to the fieldset without any keys. It started working just by adding the proper array keys to the fieldset, see the last revision.


How to create a Pie chart using views google chart tools I am using the Google Chart Tools module to create a pie chart of cricketers runs wagon wheel.

I am facing a problem with the creation of a pie chart for creation of wagon wheel. I have cricketer content type which has these fields:

Name
Mid-On-Score
Point score
Mid-off-score
Gully Score

Now I want to create a pie chart (i.e wagon wheel of scored runs by each individual cricketer). So that it shows me a pie chart which will have areawise score.

I have created a view for this and used Google Chart Tools trying to create a piechart for this. But it is not showing the pie chart correctly.

I have done correct configuration but the pie chart shows only first field in whole circle and other fields are not shown.

Here is an image with a Column chart:

And here is a similar image with a pie chart:

In the above pie chart, it should show me colored regions (slices) but it's not showing.

What am I doing wrong or does pie chart not have such functionality?

Note: it is showing other charts correctly.

I had the issue - though not in drupal, but a native php application. While I've read that large differences in values can trigger the "other" slice, this was not the case in my application.

The datatable rendered perfectly as ColumnChart, but failed to show slices as PieChart and only came back with 100% "other".
What resolved the issue for me was casting the values in php to integer with intval().
Apparently the CulumnChart visualization is forgiving, while the PieChart is not when it comes to values other than intergers.
Hope that helps clarify.


How do I prevent accessing a page with /node/37 directly when an alias has been set? I work with Drupal 8.

I've set an url alias for my page to /nice-url.
When I acces it via http://mypage.com/nice-url everything works fine.

The problem is, this page is still accessable via http://mypage.com/node/37 - it's bad for SEO and it produces some mess.

Is it possible to remove that http://mypage.com/node/37 page? I mean I want the content of that page to accessable only via http://mypage.com/nice-url.

You don't want to deny access to it but simply redirect to the aliased URL.

That feature is provided by the Redirect module and there's also a core issue to make core do that automatically.


How to override file_public_path in install profile? I want to create an install profile that creates the files folder in the document root, www.example.com/files, and not the sites/default folder.

I have tried two methods of doing this and both partially works, they create the folder in the correct place, but when the site is finished installing the admin/config/media/file-system is showing "sites/default/files".

Method 1 used:

Added "$conf['file_public_path'] = "files";" to settings.php

Note: This line was actually removed from settings.php after installation finished

Method 2:

added the below code to [myprofile].profile:

function sitebase_install_tasks_alter(&$tasks, &$install_state) {
  $GLOBALS['conf']['file_public_path'] = 'files';
}

In both cases the Verify requirements step was testing for "files".

How come Drupal all of a sudden seems to lose this setting and instead inserting the wrong value in the db? Do I need to also manually insert this in the db in [myprofile].install?

You probably want to look at this very recent blog post from PreviousNext: Collecting and writing configuration settings to setting.php from an install profile for answers to this question and your other about creating your own step in an install profile.

From that blog post regarding their install profiles form submit handler:

  Then we had to do the actual storing of these variables. Now at this
  stage the database connection is not setup so you cannot call
  variable_set(), you have to use another of Drupal's lesser known api
  functions - drupal_rewrite_settings(). This is the function Drupal
  uses to write the $databases variable to your settings.php. But with
  some minor wrangling you can use it to also write $conf variables to
  settings.php, which are from that point forward available for use via
  variable_get(). And therefore available for us to use to define our
  connection settings for the solr server. Because
  drupal_rewrite_settings should only be called once (to avoid having
  your settings overridden) we had to duplicate what the standard
  install does - ie writing the database settings - then we could write
  our own $conf settings.


How to disable caching of a block? Although in Performance, the Block caching is disabled but I've a block created by Clock module(http://drupal.org/project/clock) when accessed as anonymous user it does not update the clock on every page reload.

I've even tried clearning browser cache but it works fine when logged in. For registered users it seems block caching is disabled.

The Clock block is there in this site: http://bit.ly/PKI2M8 - please scroll to bottom-most right block titled 'Rail Time'.

How can I disable caching of this block?

As MPD pointed out, page caching is your problem. Even with block caching disabled, the whole rendered page will be cached with page caching on, which includes any blocks no matter whether block caching is disabled or not.

As far as I know that leaves you with at least the following options:

Take the easy route, and just disable page caching.
Use JavasSript to set or update the time client side, you would
still need an initial time source though, perhaps as outlined
here.
As a much larger project you could see how authcache works for
serving it's blocks of user specific non-cached content while the
majority of the page is cached, and implement it for anonymous users
for just the time block.
Use an iframe and get the contents from somewhere it isn't cached.
There are probably more ways...


Permissions and ownership of /var/www and /var/www/example_drupalsite.com I would like to get some feedback on my setup of permissions and ownerships for the following directoriess:

/var/www/
/var/www/drupalsite.com

Right now I have the following for:

drwxr-x--- 11 root www-data 4096 2012-01-01 00:00 www
drwxr-x---  4 root www-data 4096 2012-01-01 00:00 drupalsite.com

I am a single user on this vps: developer1
in a group called : developers

Is this secure and logical? A default ubuntu install starts with root as the owner and group with permissions of drwxr-xr-x but using those if I set these this /var/www/drupalsite.com becomes unavailable.
What's the best to do if I want to be able to have write permission as developer1 to the files in /var/www/drupalsite.com?

What I do is, on dev machines I make all of my Drupal files owned by my user account (e.g. developer1), and I make the group www-data.  I use chmod g+w to give write access to the web server on the directories that need it (see article quoted above in question comments, http://drupal.org/node/244924).

On production and staging machines, I make all of my Drupal files owned by a special www-admin user, and give sudo access to www-admin to any user account (e.g. developer1) that might need it.  I then can do, for example, sudo -u www-admin git pull if I want to operate on the Drupal files.  (Aside: I usually store my git root at /var/www/drupalsite.com, and point the webserver document root at /var/www/drupalsite.com/htdocs.  This puts the .git directory outside the web root, and also gives me another place to put file and directories that belong with the site, but should not be served by the webserver, e.g. D7 private folder.)  If I am hosting on a small shared hosting site, I sometimes keep only the dev site under git revision control, and use drush rsync @dev @prod to push just the files over.  By making the Drush site alias remote-user www-admin and setting the Drush rsync mode to 'rlptz' (e.g. $command_specific['rsync'] = array('mode' => 'rlptz');), then the filesystem modes will be copied over (so the folders that are g+w on dev will be g+w on prod), but all of the files will still be owned by www-admin on the target site.

I'm supposed to write some docs about this for Drush, but have not yet.  :p  See: http://drupal.org/node/1343892 and referenced issues.

Update: I'm in-progress on working on a Drush command to fix / set permissions.  See http://drupal.org/node/990812. The default values used in that command give some hints on ways to set permissions, although different strategies are possible.