Features + user permissions: what are the pros and cons of all in one versus separate? I need to carry out a review of our user roles and permissions. Currently some roles and permissions are already bundled into existing features (usually custom content types), but most are not. I would like to get everything committed into features to kick-start the review.

What are the pros and cons of either of these approaches:

Have one 'roles and permissions' feature that collects all of the roles and permissions? (This adds a lot of modules as dependencies.)
Include roles and permissions into other features when needed? (This might still require a separate feature for the permissions that don't fit into other features.)

Alternative methods (eg to help reduce the amount of roles/permissions) welcome too!

Note: a lot of our custom content types share reusable fields, which will need to have user permissions defined for them.

In terms of the user experience, listing the permission along with the feature is the better option. You will need to be searching a very long list if your permissions are complex and extensive.

The even more compelling reason to keep the feature and permissions together is for exporting. If you only plan to export a particular feature, it takes a long with it dependencies from a bunch of other modules.


Error during Taxonomy CSV import I am using the Taxonomy CSV import/export module to import and export taxonomy from my local installation to a fresh install on the staging. I export it on local, and import it using the same settings on staging. However, for each entry it imports, it throws an error:

  Notice: Undefined variable: format in
  _taxonomy_csv_vocabulary_import_process() (line 421 of /var/www/vhosts/example.com/drupal-7.34/sites/all/modules/taxonomy_csv/import/taxonomy_csv.import.api.inc).

However, the import is successful. Does anyone else encounter this? Is is safe to ignore it?

This notice is a known issue. You can solve it by implementing one of these patches:
https://www.drupal.org/node/1535942
or
https://www.drupal.org/node/2196065

If you do not know how to apply a patch, follow these instructions:
https://www.drupal.org/patch/apply


How to delete or autodelete unused images in a Drupal site? Every time I remove or replace an image in my Drupal 7 site (via image-field or CKeditor) it remains stored in the site's folder (x3 times at least for every style). Almost always it takes me about 3 MB of storage and creates a mess in the "styles" folder.

Is there a way (or module) to issue a command to remove all image files which are not being used (anymore) at my site?

The following drush command:

drush image-flush

may be used to remove all the image style copies generated as image styles via image-field or CKeditor. This is completely safe, as it will not touch the originals.

Those still in use will be regenerated when needed.  Those no longer used will not not be regenerated.

As noted in a comment by cptstarling:

  If you don't have access to drush, you may consider the Image style flush module.


How can I parse php code from another file during nodeapi function? I am embedding html and loading javascript onto a page with the nodeapi function.

I use it in this form:

 function first_order_decay_nodeapi(&$node, $op, $a3 = NULL, $a4 = NULL) {
     if($op == 'alter') {
         $path = drupal_get_path('module', 'first_order_decay');
         $path .= '/';
         $code = file_get_contents($path . 'templates/first_order_decay-static.tpl.php', false);
         $code = preg_replace("/[\r\n]*/","",$code);           //make $code one line of text
         $code = preg_replace("/<!--EMBEDREMOVE-->.+<!--EMBEDREMOVE-->/","",$code);  //remove stuff in between these comments. This is stuff I don't want
         $pos = strpos($node->body, '[FLOT](kinetics1)');   //search node->body for this command
         if ($pos !== false) {     //insert my html if we found my embed command "[FLOT](kinetics1)"
             $node->body = substr_replace($node->body, $code, $pos, strlen('[FLOT](kinetics1)'));
             //add in js
         }
     }
 }

The question is.... How can I parse php into html from $code variable? It seems that because the page is already in the rendering process, Drupal ignores the php. Is there another phase of nodeapi I can use to do this?

Thanks!

As i get you, you need to implement hook_theme and use it, instead parsing php code.

Please, see anwser here: https://stackoverflow.com/questions/12985689/how-to-implement-hook-theme-in-drupal-7


How to add a term image to node I have a nodes, and a few vocabularies to choose terms from. I would like to show images of terms from specific vocabulary in nodes (If node is associated with term from specific vocabulary, it would show image from that terms field). What would be the best (most "Drupal") approach to this? :)

One way to do it -- if you don't want to create/mess with the theme template files for your content type, would be to display the corresponding tag image via a view.

Here are the steps to doing that:

I'm assuming you already have your vocabulary set up properly and you have the image field added to it (can be done at admin/structure/taxonomy/[YOUR VOCAB ID]/fields) and some terms have been populated with their corresponding images.
Create a new view with a block display, and set it to apply only to the relevant content types

Add a term relationship to your view, so you can access the vocab/term fields, and not just the node fields!!

Once you've done that, go into the fields you want to pull for each node.  I'd remove the 'Title' field that's added by default and only add the field that represents the image associated with your term.  It should be somewhere under the 'Taxonomy term:....' section of the field list.
Make sure that you set it to use the relationship you created above

Finally, since we'll want this block to take its cue of which image to display based on which node it's on, let's add a contextual filter.  Under the 'Advanced' section --> 'Contextual filters', add the 'Content: Nid' one and make sure you set it up to take its NID from the page it appears on if a filter isn't present in the URL

All done!  Go to one of the relevant pages and test.  Of course, you'll have to enable the block via contexts or the block admin page (admin/structure/block) first, since it's not placed anywhere by default.  Display the block on the second sidebar, in the actual content section -- anywhere you want.

Let me know if this helps!!

================ EDIT =====================
Solution 2 (upon request)

To do this through your template file, go ahead and copy your regular node.tlp.php file and rename it node--[YOUR CONTENT TYPE MACHINE NAME].tpl.php

Then, right under or above the content, insert the following code:

$term=taxonomy_term_load($node->field_thats_term_reference['und'][0]['tid']);
$image_field=field_view_field('taxonomy_term', $term,'field_main_image');
print render($image_field);

Just substitute 'field_thats_term_reference' with the name of your term reference field, and substitute 'field_main_image' with your image field name.

That'll do the print out.  You can place this anywhere you want.  If you want to customize how the print out actually looks, just do a dpm($image_field) once you've set that variable (must have the devel module installed), and you can see all the parts of that field and how to get to them if you want to print them out separately as opposed to the default way render() prints it all out.  I think that part is beyond the scope of this question, but it should get you started!


How to create variations in commerce file? I am creating a ecommerce site selling downloads. Currently, I am trying to get product attributes to work with commerce file. I have created a select list taxonomy for operating systems, so the user uploading the file would be able to select operation systems. I need a way for users to be able to upload different files depending on operating systems they selected, for the same product. Thanks in advance! (I am using a normal Drupal with commerce installed I.e. Not kickstart 2, just a standard Drupal installation)

The set up should be:  a single product display whose product reference field has both the (I'm assuming) Windows file and Mac file.  The relevant product attribute being that taxonomy term.  So, in your product type, place that taxonomy term.  It sounds as if you put that taxonomy term on your product display, which is a node type.
Note:  products entities = variations in Kickstart 2.  Products I believe refer to product displays.


Omega theme responsive grid two break point I want to make responsive grid with Omega 3 theme. Grids will be 4 columns in large. 2 columns in normal width. 1 column in narrow devices. Is there a way with omega 3 with css classes?

Omega 3 uses the 960 grid, but you can alter it adding a custom 960.

Go to http://grids.herokuapp.com/ and design your grid and override the default one (on a sub-theme).

But I strongly recommend going with Omega 4. Is far more powerful and it is designed to give you the freedom to use any grid or presentation framework you like! If you don't like sass (bad for you) you can just alter the css directly.

Edit: As @Clive mention it, the Omega 5 alpha is out there! It's fantastic and follows all the html/css best practices + complies with D8 standard. Go test it, it's almost stable and your themes will be ready for D8.

Disclaimer: It has been ages since I use the Omega 3.


What are valid entity_id and entity_type values for node content? I'm trying to track down some performance issues on a Drupal 7 site where out of nowhere the site will stall rendering content or dealing with administrative duties like updating a piece of content. Checking the logs, I've found errors when cron runs for:

EntityMalformedException: Missing bundle property on entity of type node
Notice: Undefined property: stdClass::$nid in node_build_content()
Notice: Trying to get property of non-object in _node_index_node()

This prompted me to create a view to look at all content types and return

title,
node_id,
entity_id
entity_type

This view shows the majority of site content has entity_id = 0 and entity_type = null (nothing).

Out of roughly 400 nodes, less than 20 have proper entity_types and entity_id values. Even creating a simple basic page with a title and body results in entity_id = 0 and no value for the entity_type.

You would think that the content wouldn't render however, all of this content will render at /node/xxx or pulled up in views and can be edited as usual.

I think this is one of the causes of the poor performance if not the cause so I'm looking to repair the broken nodes and and prevent this site from continuing this odd behavior. I'm pretty sure the entity_id should equal node_id and I'm pretty sure the entity_type should equal node.

Drupal 7.34

This error can be caused by having a term reference field that references a deleted term. This reference is not deleted when a term is deleted.

You can check if this is the case using this query

SELECT nid, title from node WHERE nid
   IN (select entity_id from  field_data_field_some_ref
   WHERE field_some_ref_tid not IN (select tid from taxonomy_term_data))

https://www.drupal.org/node/1778572#comment-7256200

There are other cases where this error can occur. Read the issue comments in the link for more info.


How to create a user with custom profile fields for a SimpleTest How can I programmatically create a new user for use during a SimpleTest?  The user must have certain custom fields populated during the registration.

I'm using $this->drupalPost('user/register', $edit, 'Create new account'); to create the account currently as I do not see a way to populate custom profile fields with drupalCreateUser().

$edit = array(
      'name' => $this->randomName(17),
      'mail' => $this->randomName(17) . '@example.com',
      'field_owner_first_name[und][0][value]' => $this->randomName(17),
      'field_owner_last_name[und][0][value]' => $this->randomName(17),
      'field_owner_title[und][0][value]' => $this->randomName(8),
      'field_business_name[und][0][value]' => $this->randomName(17),
      'field_business_phone[und][0][value]' => mt_rand(200, 999) . '-' . mt_rand(200, 999) . '-' . mt_rand(1000, 9999),
      'field_business_email[und][0][value]' => $this->randomName(17) . '@example.com',
      'field_business_website[und][0][value]' => 'http://' . $this->randomName(17) . '.com',
      'field_business_address_1[und][0][value]' => mt_rand(1, 9999) . ' ' . $this->randomName(12) . ' ' . $this->randomName(2),
      'field_business_address_2[und][0][value]' => 'Apt ' . mt_rand(1, 999),
      'field_city[und][0][value]' => $this->randomName(8),
      'field_state[und]' => 'HI',
      'field_zip[und][0][value]' => mt_rand(10000, 99999),
      'field_request_website[und]' => 'Yes',
);
$this->drupalPost('user/register', $edit, 'Create new account');

The code above successfully completes and posts the registration form.

How can I automatically approve and login as this newly submitted user for testing?  Do I need to write tests to login the admin account, find and then approve the user?

Additional Thoughts and Clarification:

Looking at other options, can I somehow use variable_set() to accomplish the automated user approval above when the setUp() method is called?

in the setUp() method I simply added: variable_set('user_register', 1);

This way I could drupalPost a new account and login immediately without approval.

$this->drupalPost('user/register', $edit, 'Create new account');

Account is successfully registered and the required additional fields were collected during registration.


Access denied when enabling or setting by default a theme (on Nginx) I get an Access denied error page when attempting to enable or set by default a theme. It is kinda weird as I am allowed to perform other admin tasks.

I checked that my user is an administrator and it has all the permissions granted. I also made other checkings that I found in Drupal's forums and Drupal Answers but everything seems to be OK.

I have a standard install with no additional modules. Watchdog logs show the access denied warnings from http://drupal-testing/admin/appearance/enable?token=<...>&theme=encoreweb. In addition to check the permissions of my user, I reviewed settings.php to verify $cookie_domain was commented.

I've found that I'm not the only one with this problem, but I couldn't come to a conclusion.

I've got a solution after several hours working on it.

I am using Nginx instead of Apache and I did not configure it to add the query string in the rewriting to index.php. So neither the token nor the theme parameters were reaching the script and system_theme_enable()/system_theme_default() (located in /modules/system/system.admin.inc) always returned MENU_ACCESS_DENIED, which I consider to be a very confusing behavior by the way.

This is how the server config looks like now and makes it work:

location / {
    try_files $uri $uri/ /index.php?$query_string;
}


Rendering the Fivestar widget I am trying to render the Fivestrar widget programmatically. I have tried the following code, without success:

$settings = array(
  'content_type' => 'parce',
  'content_id' => $nid,
  'stars' => 5,
  'autosubmit' => TRUE,
  'allow_clear' => FALSE,
  'required' => FALSE,
  'tag' => 'vote'
);

print drupal_render(drupal_get_form('fivestar_custom_widget', $field_rating['0'], $settings));

I do get the widget form to print, but on submission the votes don't register; plus in this way I do not have the vote summary.

Am I missing something?

Are you in a node template ? If so you can do:

print render($content['field_vote']);

Source: Display fivestar in template (node--*.tpl.php)


how using mysql CAST in db_select I want to try doing Mysql Casting in my query by db_select but face to error,

$q=db_select('node','n');
          $q->join('field_data_field_cinema_type', 'fct', 'fct.entity_id = n.nid');
          $q->condition('n.type',array('movie'),'IN');
          $q->condition('fct.field_cinema_type_tid',11095,'=');
          $q->condition('cast(n.nid AS SIGNED )',11517,'>'); // also $q->condition('cast(n.nid AS SIGNED INTEGER )',11517,'>');
          $q->fields('n',array('nid','type'));
          ym((string)$q);
     $res= $q->orderBy('nid')->execute()->rowCount();

and query string

SELECT n.nid AS nid, n.type AS type FROM {node} n INNER JOIN {field_data_field_cinema_type} fct ON fct.entity_id = n.nid WHERE (n.type IN (:db_condition_placeholder_0)) AND (fct.field_cinema_type_tid = :db_condition_placeholder_1) AND (castn.nidASSIGNEDINTEGER > :db_condition_placeholder_2)

My question is how can I use Mysql Casting in db_select?Is that supported in db_select or I should use db_query on EntityQuery ?

You can use the where() method for a SelectQuery:

...
$q->where('CAST(n.nid AS SIGNED) > :nid', array(':nid' => 11517));
...

So the choice is yours which type of query to use.


How do I programmatically show a view block? I created a view block, whose machine name is "news."

How do I display it using module_invoke() and the machine name of the view?

Use views_embed_view():

echo views_embed_view('view_machine_name', 'block_1');

You can find out the display name by clicking the tab and check its name in the address bar of your browser: #views-tab-block_1 gives you block_1.


How can I group view results based on the week of the year using a date field? I have a list of events (custom content type event) shown in a view.

There are several events each week.  Each event has a date field, date, that records the date that the event will be held.

I would like to group the events by the week of the year that they occur.  For example:

Next week
Two weeks from now
Three weeks from now
Four weeks from now

Is there a fancy way to compute the week using the date field and views grouping?

You can do this without using a PHP field (or similar). Those modules are usually bad practice to put PHP into the database like that.

You can create a date format in Drupal for 'Week'.  Then you add the date field to the View and use this week format.  That will output the value of the date as a week #.  Then you group on that value.

A views filter can also help restrict the view to now + 4 weeks.  And some views theming can make each week header be whatever you need it to be.


Admin module for content managers I am building a drupal website for a customer (=content manager) of mine. Normaly I would just adjust the permissions for the content manager so he can change what he needs to. But it would be much simpeler if I could provide a menu with shortcuts of the actions he needs.

To keep everything clean I would like to use rubik and the admin menu.

Is there a way to hide all the "admin" links for the content manager and add some custom menu links my own ? So I can provide a "custom" content management system for his needs without all the drupal possibilities (which I only need).

Try the Quickbar module.

This is a simple administration toolbar. It allows you to take any menu and assign it to a role. This menu will be displayed at the top of your page as an administration toolbar.

Most of this module is taken from [the] Admin [m]odule version 1.x. It also uses some features from the Toolbar module.


Unique file system for multiple domains in Domain Access I have created five domains using domain access module like

test1.com
test2.com
test3.com
etc,

Now i want each users from different domains have to use unique file system in order to upload media.
From that i don't what users from other domains can access remaining domain's file system.

for example test1.com users can access only their own file system called test1.

Is there any way to do this in Domain Access Module? or any other module & Coding is needed?

There is a sandbox module that appears to do what you need: https://github.com/markwk/domain_files

Essentially it extends the DrupalPrivateStreamWrapper class to provide a file path for each domain.

There is more discussion on d.o here with other methods people have tried: https://www.drupal.org/node/198131


How can I pass more resource IDs with a single request? I've been using the Services module with the REST module from quite some time now.
I want to make a single PUT application/json request with an appropriate JSON raw body for it, passing more than a resource ID, instead of making different requests. So far as I read, I found I can use PUT request: http://.../resource_endpoint/resouce_name/resource_id.

Implement hook_services_resources().
function example_services_resources() {
  $resources = array();
  $resources['einvoice'] = array(
    'actions' => array(
      'search' => array(
        'access callback' => '_example_resource_access',
        'callback'        => '_example_resource_search',
        'help'            => 'E-invoice online checker.',
        'file'            => array(
          'type'   => 'inc',
          'module' => 'exmaple',
          'name'   => 'resources/exmaple.resource',
        ),
        'args'            => array(
          array(
            'name'        => 'input',
            'optional'    => FALSE,
            'source'      => array('data' => 'input'),
            'type'        => 'string',
            'description' => 'Put the query string to get some data.',
          ),
        ),
      ),
    ),
  );
  return $resources;
}

In the example.resource.inc file, you put the functions declared  in that hook.
function _example_resource_access() {
  return TRUE;
}

function _example_resource_search($input) {
  // To do something you want.
}


Extending forms (or views, or something else?!) If creating something like a form, but also perhaps any piece of front-end UI, what is the correct approach for adding things like extra Javascript (or HTML, or anything)?

I'm putting together a registration form using the Entity Registration module and would like to know if, say, I wanted to have a 'Delivery address is the same as invoice address' checkbox that dynamically hid/revealed the delivery address part of the form, what would be the Drupal way of achieving that?

You could implement hook_form_alter for adding a checkbox field to your form.

The most simple thing to do after that is to handle the display of the form elements with JS/CSS (checked or not). You have to handle the validation of the different submissions of the form (with or without the delivery address part).

Here you can find a tutorial for adding custom validation to a form.

For the JS/CSS part, you can put your code in the main files of your theme, or add specific files for this form. Check this answer for the second solution.


How to show a view inside another view on only first row? I need to display a view inside another view and I'm using Views field views module, It works well, but I need the field (view) only appears in the first row result of the view page, like the following.

View page - results

Title node 1
Image node 1
View field 1 (this should appear only here)
Title node 2
Image-node 2

I'm not sure if Views nodes split module will be useful for your situation as @DnBase mentioned.

However, because you're using Views Field View; you can follow the following steps to achieve what you're looking for:

Edit field view actual view (referenced view)
Add Global: Null from CONTEXTUAL FILTERS menu

From the next dialog box that appear, select Hide view from WHEN THE FILTER VALUE IS NOT AVAILABLE fieldset.
Then from WHEN THE FILTER VALUE IS AVAILABLE OR A DEFAULT IS PROVIDED fieldset, check Specify validation criteria and select PHP Code from validator dropdown menu
Then add the following code in PHP Validate code field
From Action to take if filter value does not validate dropdown menu select Hide view

Code:

if($argument == 1) {
  return TRUE;
} else {
  return FALSE;
}

Now edit the main view
Add Global: View result counter from FIELDS menu, then from field configuration dialog box, check Exclude from display
Then edit Global: View field, from field configuration dialog box, add this replacement pattern [%counter] into Contextual filters field

By applying these steps, you'll notice that view field will only appear on first item.


Drupal 8 override administration theme node form css I need to override some of the styles on the Seven node form. My initial thought is to alter the form and add a custom css file. Is there a better Drupal 8 way to achieve this?

Thanks,

Dave

If you only has to add some custom css form alteration will does it.

If you also have to make some changes in field templates, or some theme function alteration, I suggest you to create your custom theme, and add Seven as a base theme


How do I programmatically set up multiple default flags? How do I programmatically set up multiple default flags?

The documentation shows how to create a single flag using mymodule_flag_default_flags(). If I need two or three default flags for my custom module, how could I achieve it?

Figured it out. To have multiple default flags you simple do this:

function mymodule_flag_default_flags() {

$flags = array();

$flags[‘FLAG_NUMBER_1’] = array(
    'content_type' => 'node',
    'title' => '',
     // Rest of flag data
);

$flags[‘FLAG_NUMBER_2’] = array(
    'content_type' => 'node',
    'title' => '',
     // Rest of flag data
);

return $flags;

}

where [‘FLAG_NUMBER’] is the machine name for the flag.


Remove custom link in teaser In drupal 7 I created new content type and also created new view to display nodes of this content type. After playing a bit with Calendar module I managed somehow to put link to calendar to node teaser links. Now I can see "Read more" link inline with "Calendar" link. It's pointing to calendar view which no longer exists.

Could you please advise me how to get rid of this "Calenar" link in teaser links? When I uncheck "Display links" in view settings (Edit View -> Format -> Show -> Content | Teaser), it disappears together with "Read more" link. But I'd like to have "Read more" link without "Calendar" link.

Thanks for any suggestions.

Uncheck the Display links and add the below line in your node.tpl.php present under your themes folder sites/all/themes/yourtheme

<a href='<?php print $node_url; ?>'>read more..


How do I run queries against a view configuration Where is all the config for Views stored? I am working on a Drupal site with a very large number of Views. What's the easiest way to find "All the Views which have a Relation of a certain type", or "All the Views which output a specific field?"

It would be nice to do this with some SQL but I'm stumped as to how.

Just expanding a bit on @Clive's answer. Load all views, iterate through them and check what you need.

Views has a function that will help, views_get_all_views(), https://cgit.drupalcode.org/views/tree/views.module#n1536

From there, you can go through them and get what you need.

Basically,

  $views_list = views_get_all_views();
  foreach ($views_list  as $view) {
    //Logic operating on the $view object
  }

This will probably be useful as well, https://api.drupal.org/api/views/includes!view.inc/class/view/7.x-3.x


Drupal 7 Add user delete tab in user profile I would like to show the user delete confirmation form as a tab in user profile, just near View and Modity. I am trying the following code in a custom module but it is not working, I'm not sure I am calling the right callback and arguments:

function custom_morebuttons_menu_alter(&$items) {
  $items['user/%user/cancel'] = array (
    'title' => 'Cancel profile',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('user_cancel_confirm_form', 1),
    'access callback' => 'user_cancel_access',
    'access arguments' => array(1),
    'type' => MENU_LOCAL_TASK,
    'weight' => 10,
  );
}

You need to use hook_menu() instead of hook_menu_alter() because you are adding a new menu item rather than altering an existing one.

function YOUR_MODULE_menu() {
  $items['user/%user/cancel'] = array(
    'title' => 'Cancel profile',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('user_cancel_confirm_form', 1),
    'access callback' => 'user_cancel_access',
    'access arguments' => array(1),
    'type' => MENU_LOCAL_TASK,
    'weight' => 10,
    'file' => 'user.pages.inc',
    'file path' => drupal_get_path('module', 'user'),
  );

  return $items;
}

Don't forget to return $items at the end of the function, since it is not passed by reference.

Though I'm not sure if the page callback and arguments are right, I didn't check that, I've just copied from your code.


Webform populate text component with encoded url values How to populate a webform component with encoded values. For exampmple my url http://example.com/abc?submitted%5Bthis%5D=1

I tried to use token [current-page:query:this] but it doesnt work.

You're on the right track. It looks like you have a syntax problem with your URL param itself. If you're trying to get the value of ?this, remove the sumbitted and  [ (%5D) and ] (%5B). So your URL with the param will look like this:

http://example.com/abc?this=1

With that URL, [current-page:query:this] should return 1 (or TRUE).


schema_fields_sql empty on entity_get_info I'm trying to debug why Drupal Commerce License Billing isn't working on existing install but works fine on fresh install.

The difference I can see between the two when adding a new billing type is after entity_get_info is ran (after saving a new type) the clean install has two array elements complete the existing install does not.

Those two elements are "base table field types" and "schema_fields_sql".

So for some reason those elements aren't set in the existing install.

Any ideas why those elements wouldn't be populated or where they are set so I can further debug?

Thanks

My first guess would be that the cache is somehow corrupted. To fix that you'll need to clear the drupal caches

If that doesn't help you'll need some more in-depth debugging.

For further debugging you'll need some easy way to execute code in your drupal environment. I'd suggest to use drush ev or drush php-script for that. -- Here is some information on how to install drush if you don't have it installed already.

At this point I think there are only two causes left:

entity_get_info() only populates schema_fields_sql if the base table key is present. So it might by that somehow the base table is not set. To check that take a look at the return value of module_invoke_all('entity_info'). For debugging you'll need to take a look at all modules in module_implements('entity_info').
If the original data in module_invoke_all('entity_info') includes a base table the only other way to corrupt the information is some implementation of hook_entity_info_alter(). Use module_implements('entity_info_alter') to find all modules you need to check.

If you need further help please provide at least the dump of entity_get_info() and module_invoke_all('entity_info').


Add a class to an element after AJAX I have a view of nodes with an AJAX on scroll set up. Everytime a person scrolls down the page new elements inside a view show up (e.g. nodes).

I'm trying to add a new class only to new nodes that show up after each AJAX call. So far I've only managed to add a class to all nodes inside a view using drupal.behaviors, even the ones that were originally visible in the DOM(before AJAX call).

What am I missing?

My current code:

 $(document).ready(function($) {
    $('.views-infinite-scroll-content-wrapper').find('.views-row').addClass('i-was-here-first');
});

  Drupal.behaviors.testing = {
    attach:function (context, settings) {
      $('.views-infinite-scroll-content-wrapper', context).find('.views-row').addClass('i-was-here-second');
    }
};

Taking a blind guess: Your context matches the entire parent container, so you can't filter by "new ones only" with context. But as a workaround you could specify a more explicit find to filter only new ones:

This will add .i-was-here-first to every views row present on document ready:

 $(document).ready(function($) {
    $('.views-infinite-scroll-content-wrapper').find('.views-row').addClass('i-was-here-first');
});

Now use that class to filter sub-sequent behavior calls by using a more explicit find():

Drupal.behaviors.testing = {
    attach:function (context, settings) {
      $('.views-infinite-scroll-content-wrapper', context).find('.views-row:not(.i-was-here-first)').addClass('i-was-here-second');
    }
};

Side note:
I'd recommended not to use $(document).ready() at all in Drupal because this might cause problems when using BigPipe module, which is active by default. Drupal will initially trigger all behaviors with document as context, so you should use something like this instead:

Drupal.behaviors.instead_of_document_ready_do_this = {
  attach: function (context, settings) {
    $(document, context).once('my_unique_name').each( function... );
  }
}


DatabaseScheme Error when trying to install Jabber PROBLEM: Got the following error when trying to install Jabber. This seems like a generic error. I have a feeling that the issue is similar to this post. I created a bug report so the maintainer can either help or include what ever fix comes from this.

  DatabaseSchemaObjectExistsException: Table jabber already exists. in DatabaseSchema->createTable() (line 657 of public_html/d7/includes/database/schema.inc).

BACKGROUND: I have an OpenFire server running and was curious as to the integration with Drupal 7 and O.F. This post talks about the very same thing expect.. XMPP Framework Module is for D6. The alternative for D7 is Jabber.

I've tried both the DEV & BETA branches and both throw the same error on install. On uninstall of the module, there is another error but I've removed all entries into the DB for jabber myself.

If I try to goto the admin/settings/jabber page. It doesn't show up. Thus telling me it wasn't installed right.

How can I fix this error so the jabber module will install properly?

EDIT: After installing the DEV version. I just realized the Jabber settings page does show, although the previously mentioned error still pops. There are also additional errors but those are not relevant to this question.

Run database update then try reinstalling the module.

Also do keep backup of your database before running the update.


Drush 8.0.3 is unable to update D7 modules I have Drush installed via Homebrew on my Mac. I am currently unable to execute "drush up" in a Drupal web site. When I attempt, I get the error:

Destination directory [...] already exists.

Is this normal? Do I need to use a different version? Do I need to stop using Homebrew?

You could be hitting this issue - there is a bug if you have a version control system such as SVN installed.

If it is this bug, the error should go away if you pass --version-control=backup.  Of course you will then lose some integration with your version control system.


Simplest way to create a Commerce shopping cart icon showing the number of items I'm looking for the simplest way to implement something similar to Amazon's shopping cart icon which shows the number of items in the cart, which then links to the cart:

I've found several options through browsing various support requests etc, most of which are at least 3 years old and sound surprisingly complex in terms of overheads relying on many features (e.g. this suggestion from 2012 of creating an entire custom Views view to generate one number and one static link).

Obviously, the icon is the easy part, can be done in CSS very easily, it's the number of line items that I'm most interested in. Particularly having it integrated such that it updates when a new item is added to the cart.

I thought this would be something Commerce would do out of the box, or with an add-on module, but if it is I can't find it.

Is there any simple way?

The way I would do it, is that I would make the total number of products in the shopping cart available in the page.tpl.php file, and print it there directly.

Here's example code:

function YOUR_THEME_preprocess_page(&$variables) {
  $cart_count = 0;
  $order = commerce_cart_order_load($variables['user']->uid);
  if ($order) {
    $wrapper    = entity_metadata_wrapper('commerce_order', $order);
    $line_items = $wrapper->commerce_line_items;
    $cart_count = commerce_line_items_quantity($line_items, commerce_product_line_item_types());
  }
  // Make the number of products in the shopping cart available to our template.
  $variables['products_in_shopping_cart'] = $cart_count;
}

Then in your page.tpl.php you would use this code to show the number of products in current user's cart:

<?php print $products_in_shopping_cart; ?>

Note: second argument passed to the commerce_line_items_quantity() is updated per Clive's note.


Different way for users to add content on pages On my website each user can only edit the existing main content via the 'edit' button on the page.

I don't want each user to see what was added previously on the page like it happens on my website:

Is there a way the user can add their own new content and be displayed on the page in ascending order (new content on top of the previous one) WITHOUT modifying/ viewing the previous post? E.g. like on this example I found online:

Yes. You can use the built in content types and the default 'node' page which allows this for just the front page or if you want more complex uses with multiple pages you will need something like views and a custom content type with a taxonomy term to tie the content pages to the view.


Is it possible to show views exposed filters in the facet current search block? I have a facet search with Facet API, Search API, and a Solr backend with the Search API Views integration.  I am using the Current Search block (part of the Facet API module) to display the currently selected facet options.

However, I am also using Views, and I have two exposed filters with the autosubmit button on the page.  The problem is that users can select one of the views exposed filters and it will not appear in the Current Search block, so it is not obvious to the user that the results are being further filtered.

I am also using Facet API Pretty Paths, so I have a path that looks like this:

  myexample.com/s/n/1/b/2&items_per_page=8&jp=1&d=-

n/1  and b/2 are facets, &items_per_page=8 is the views pager, and &jp=1 and &d=- are the views exposed filters.

My goal is to somehow make it clear to the user that Views exposed filters are affecting the results.  If it's possible to modify the Current Search block, I would like to do that, but if not, creating a separate block/ctools content type to notify the user that the exposed filters are applied would also be acceptable.

I'm not aware of any modules that show the applied exposed filters, so I'm thinking about writing code to check the query string for jp and d and then printing messages based on the results.  If there is an easier approach, I would be glad to hear it.

This wouldn't add it into the Facet block, but you could just do the exposed filters in a block and put the exposed filters block near the Facet block (screenshot from the Advanced section of the View):


How to display nodes on front page with Search API? I have installed the Search API, Facets API, along with Search Pages.  When the user goes to the front page, I want to display some default node results.  How can I do this with just the node results for a particular view mode, without the user setting filter criteria?

I have very good experience in search api and the easiest way to display the search results is use module search_api_views (included into search_api).

Just create view for your search api index and select there required view mode and filtering criterias. Put this view on your front page and it will work.


ob_start() error running Devel on Search API + Search views page How can I run Devel on search pages?  I keep getting an ob_start() error.  How can I run debug on these search pages.

The error is:

Fatal error: Unknown: Cannot use output buffering in output buffering display handlers in Unknown on line 0

I just ran my Devel debug on blocks and that worked.


How to display the average rating of a node as stars in a view? The users on my website can rate an article with the Fivestar module while they comment. I'd like to create a view with the 5 articles that have the highest average score.

I've nearly been able to achieve what I want with a 'Vote results' relationship and a 'Vote results: Value' field. The problem is that the average score is displayed as a number, but I'd rather like it to be shown as stars. I achieved this in the past without custom coding (thanks to a deleted video that was situated here), but I forgot how to do it.

Can you help?

This is what I came up with:

Create a Views template for this specific field and put it in your theme (or module if you have Views templates already there and enabled via the Views api hook).

In my case it was called views-view-field--top-content--page-1--value.tpl.php for just the included and now enabled top content View.

In there, do the following:

<?php
  $data = $row->{$field->field_alias};
  $path = drupal_get_path('module', 'fivestar');
  print theme('fivestar_static', array('rating' => $data, 'widget' => array('name' => 'basic', 'css' => $path . '/widgets/basic/basic.css')));
?>

And if all is well in the world of copy and paste, you should now have a View with basic stars displayed instead of the number.  If you don't like the basic stars, just look in the widgets directory and you can take your pick of any of the other styles there.


Extracting UID information from a URL and sending email to this user As a beginner, I would be grateful if this community could help me out to solve the following problem, by giving me some pointers.
This is the scenario I would like to implement in Drupal (I guess I need to create my own module):

A user (“U1”) enters a URL which looks like this:
www.mywebsite/Foo/UID2
Note that U1 does not need to be registered on my web site ( = anonymous), although he / she may be, to access the page which will be invoked through this URL.

U1 is then automatically redirected to a web form page where he / she will enter text: “Hello my name is Bob…”, an email address: “u1@example.com, a phone number “123 345 67 89”.

An email containing this information will be sent to the user that has UID2 as his / her user ID. U1 will not see U2’s email address.

The information that U1 sent an email to U2 will be kept in a “from-to” table which manages the following information:

UID_from (if it exists)
U_from First Name
U_from Last name
Text_from
Email_from
Telephone_from
UID_to (note: this UDI always belongs to a registered user)
Date & time

Can someone give me some indications of the various functions invoked? If a ready-made module exists (which I did not find), the better.

I suspect hook_menu will be used; but how to extract UI2 from the URL and send it to a web form, which later is handled by an email module?

Thanks so much,

Peter

You can solve your problem using Out of the box Webform Module.

  Webform is the module for making surveys in Drupal. After a
  submission, users may be sent an e-mail "receipt" as well as sending a
  notification to administrators. Results can be exported into Excel or
  other spreadsheet applications. Webform also provides some basic
  statistical review and has and extensive API for expanding its
  features.

You can read uid value from URL .. Webform has support for tokens. You need to create a field to collect UID and configure default value.

For Example:
%get[key] - Tokens may be populated from the URL by creating URLs of the form http://example.com/my-form?foo=bar. Using the token %get[foo] would print "bar".

Your URL should be http://example.com/my-form?uid=value .. You will configure default value as %get[uid]
Webform has Email support out of the box.
You can see user submitted results in webform you created.
It automatically creates schema for you, and it has lot more features...


Override alter.inc in child theme Bootstrap.js is breaking a menu plugin I'm using. It's called with this

  $bootstrap = $theme_path . '/js/bootstrap.js';
  $js[$bootstrap] = drupal_js_defaults($bootstrap);
  $js[$bootstrap]['group'] = JS_THEME;
  $js[$bootstrap]['scope'] = 'footer';

in themes/bootstrap/theme/alter.inc. I tried putting a modified alter.inc inside themes/child_theme/theme/ but it doesn't work. Is there a function I can use to override it?

If you really want to remove bootstrap.js you can do it this way:

function YOURTHEME_js_alter(&$js) {
  $bootstrap = drupal_get_path('theme', 'bootstrap') . '/js/bootstrap.js';
  unset($js[$bootstrap]);
}

It might fix your menu plugin but it'll remove every drupal specific bootstrap js code (tabs, popovers, tooltips and anchors stuff).


How to insert a theme table form inside an existing form? I would like to put form fields and submits inside a table (generated with theme_table) of an existing form (callback of a hook_menu entry).

The form_id (container) :

  // Part of the existing form having a $form_id,
  // where I want to put form elements into a table :
  ...
  $data = mymodule_get_content_list();

  $form['mymodule_content_list'] = array(
    '#theme' => 'table',
    '#header' => $header,
    '#rows' => $data,
  );

Table builder function :

function mymodule_content_list() {

  ... Running queries to get a $content_list

  $data = array();
  foreach($content_list as $content_data) {
    $operations = array(
      'update' => array(
        '#type' => 'submit',
        '#value' => 'Update',
        '#submit' => array('mymodule_page_edit'),
      ),
    );
    $content = array(
      '#type' => 'textfield',
      '#value' => $content_data->content,
    );
    $data[] = array(
      'content' => drupal_render($content),
      'operations' => drupal_render($operations),
    );
  }

  return $data;

}

With something similar to the above, I currently get the HTML of content textfields and submit buttons in place, but they aren't used as real form elements:

When I click the submit above ('Update'), the submit function used is the first declared within the form container but not the declared array('mymodule_page_edit').
Using a debugger, I found out that textfields declared in the table's rows aren't passed as $form_state['values'] within the (wrong) submit function.

So the question is, how to insert form elements (fields and submits) into a drupal table, inside of an existing form (hook_menu callback) ? Is it possible ?

Here is sample example where form and tables are used together.

Step1: Gather whole data, going to use in table.

$sample_data = array
(
  array('id' => 1, 'first_name' => 'jay', 'last_name' => 'chris'),
  array('id' => 2, 'first_name' => 'clo', 'last_name' => 'jason'),
  array('id' => 3, 'first_name' => 'len', 'last_name' => 'ken'),
);

Step2: Create table header.

$sample_header = array
(
  'first_name' => t('First Name'),
  'last_name' => t('Last Name'),
);

Step3: Create table rows and columns data.

$options = array();
foreach($sample_data as $data)
{
  $options[$data['id']] = array
  (
    'first_name' => $data['first_name'], // 'first_name' was the key used in the header
    'last_name' => $data['last_name'], // 'last_Name' was the key used in the header
  );
}

Your data should be something like this:

Array
(
  [1] => Array
  (
    [first_name] => jay
    [last_name] => chris
  )

  [2] => Array
  (
    [first_name] => clo
    [last_name] => jason
  )

  [3] => Array
  (
    [first_name] => len
    [last_name] => ken
  )
)

Step4: Use drupal function(tableselect) for table

$form['table'] = array
(
  '#type' => 'tableselect',
  '#header' => $header,
  '#options' => $options,
);

Here is complete form for you.

function my_form($form, $form_state)
{
  $sample_data = array
  (
      array('id' => 1, 'first_name' => 'jay', 'last_name' => 'chris'),
      array('id' => 2, 'first_name' => 'clo', 'last_name' => 'jason'),
      array('id' => 3, 'first_name' => 'len', 'last_name' => 'ken'),
  );

  $sample_header = array
  (
    'first_name' => t('First Name'),
    'last_name' => t('Last Name'),
  );
  $options = array();
foreach($sample_data as $data)
{
  $options[$data['id']] = array
  (
    'first_name' => $data['first_name'], // 'first_name' was the key used in the header
    'last_name' => $data['last_name'], // 'last_Name' was the key used in the header
  );
}

  $form['table'] = array
  (
    '#type' => 'tableselect',
    '#header' => $header,
    '#options' => $options,
  );

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

There can be some TYPO mistake, so do change in code accordingly.


How to display User from Access Log in Views The statistics module documentation says that user name is logged in the Access Log: "This access log is used to store data about every page accessed, such as the remote host's IP address, where they came from (referrer), what node they've viewed, and their user name. "

I have enabled statistics Acces Log and created a view which shows Access Log. Available fields are:

I can't find any field related to user.

You have to add a relationship to Users to be able to display user fields in the view.

Click on Add next to Relationships.
Check "Access log: User" then click Apply.
Click Add next to Fields then you should see the User fields including username.


How do I render the page to add products into my custom module? Here is my code

<?php
namespace Drupal\mymodule\Controller;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Controller\ControllerBase;
class HelloController extends ControllerBase
{
  public function content() {

       $form = \Drupal::formBuilder()->getForm('\Drupal\commerce_product\Form\ProductForm');
}
}

I want to render the default add to product page(product/add/default) in my custom module controller file .

  Error: Call to a member function getEntityTypeId() on null in Drupal\Core\Entity\EntityForm->getBaseFormId()  (line 79 of core/lib/Drupal/Core/Entity/EntityForm.php).

You need to create an empty product and use entity.form_builder service to generate the form.
Try the following.

<?php

namespace Drupal\mymodule\Controller;

use Drupal\commerce_product\Entity\Product;
use Drupal\Core\Controller\ControllerBase;

class HelloController extends ControllerBase {
  public function content() {
   $product = Product::create([
     'type' => 'default',
   ]);
  return  \Drupal::service('entity.form_builder')->getForm($product);
  }
}


Using MYTHEME_page_attachment_alter does not alter the favicon Based on other similar stackexchange questions and documentation, I've implemented the following in the MYTHEME_page_attachment_alter function in MYTHEME.theme file to change the favicon based on the url (inside a condition statement):

    foreach($page['#attached']['html_head_link'] as $k => $v) {
        if (array_key_exists('rel', $v[0]) && $v[0]['rel'] == 'shortcut icon') {
            unset($page['#attached']['html_head_link'][$k]);
            $page['#attached']['html_head_link'][$k] = array(
                array(
                  'rel' => 'shortcut icon',
                  'href' => '/themes/fu/favicon_urbana.png',
                    'type' => 'image/png',
                ),
            );
        }
    }

Using Kint::dump($page) confirms that the shortcut icon is indeed updated.  Why then will the tab for the page not show the updated favicon?  I've cleared the cache, ran drush cr multiple times, etc yet the page continues to show the theme's favicon.

Am I missing something?  Any advice would be greatly appreciated.

On a side note, we had this working successfully in Drupal 7 in MYTHEME_html_head_alter() and I am migrating this to Drupal 8.

If its not a browser cache issue perhaps you should try modifying it with a hook called later namely THEMENAME_preprocess_html

function THEMENAME_preprocess_html(array &$variables) {
  $test = "";
  $variables["page"]["#attached"]["html_head_link"][0][0] =
    array(
      'rel' => 'shortcut icon',
      'href' => '/themes/fu/favicon_urbana.png',
      'type' => 'image/png',
    );
}


Mulitple image upload field widget working on custom content nodes but not on user nodes Using Drupal 7.39 and the MultiUpload FileField Widget module.

It works fine for articles, and custom content types I create, but it doesn't work for user fields. Even if I take the existing field from article, and add it as a field to user, it doesn't work.

You can select multiple images, and they show as "2 images selected", you click upload, and nothing happens.

Any idea why this is happening?

It was an administration template problem...

It works in bootstrap, but not with 7 theme, but it does with Stark.

I thought that the Drupal 7 theme would be bullet proof, I guess not...

So always best to test various admin themes to see if that is the problem in the future.


Tableselect with columns of checkboxes I've a simple tableselect with 4 columns, in the 3 last columns a want to populate all the columns with checkboxes, anyone can help me to do that ?

here is my actual code :

function liste_sections($form, &$form_state){
$form = array();

$header = array(
        'sections' => t('Sections'),
        'affichable'=>t('Affichable'),
        'new'=>t('New'),
        'online'=>t('Online'),
);

$resultat = db_select('taxonomy_term_data','tax');
$resultat->fields('tax',array('tid','name'));
$res = $resultat->execute();

$rows = array();
    foreach($res as $sql){
        $rows [] = array(
            'sections' => $sql-> name,
          // Time to put checkboxes for other columns
            );
    }

$form['liste_sec'] = array(
        '#type' => 'tableselect',
        '#header' => $header,
        '#options' => $rows,
        '#empty' => t('empty ! '),
);

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

Thank you all

I got it, in my liste_sections($form, &$form_states)

$checkbox_col1 = array(
    '#type' => 'checkbox',
    );

$checkbox_col2 = array(
    '#type' => 'checkbox',
    );

$checkbox_col3 = array(
    '#type' => 'checkbox',
    );

after that, add those variables to the rows :

$rows = array();
    foreach($res as $sql){
        $rows [] = array(
            'sections' => $sql-> name,
            'affichable' => array('data'=>$checkbox_col1),
            'News' => array('data'=>$checkbox_col2),
            'online' => array('data'=>$checkbox_col3),
            );
    }


Pager doesn't work in views block if views php field is used I have a views block that shows nodes in some conditions. The views has pager and normally it works but if I use Global: PHP field the pager doesn't work and it only show the first page.

The Global: PHP field is as below:

Value Code: emtpy
Output Code:

->

<?php if ($row->type == 'book') { ?>

<?php }
elseif ($row->type == 'article') {
?>

<?php }
elseif ($row->type == 'thesis') {
?>

<?php } ?>

UPDATE:

I'm listing the nodes in this views block. There are 3 different content types and what I want to do with this PHP field is to print an icon according to content type. The code checks the content type with if ($row->type == ...).

(End of update.)

The PHP field works correctly and gives what I want but I wonder if I do something wrong in the PHP structure.

Do you have any idea what can cause this problem?

There is a patch for that: Pager disappears when Global: PHP used in Views 3.8

  After upgrading from Views version 7.x-3.7 to 7.x-3.8, the pager was
  missing from all views that used Global: PHP fields.

If patch#6 does not work for you, just follow the links in comment#27


Feeds for the module information of drupal.org http://simplytest.me/ has a nifty autocomplete option for the module suggestions. Screenshot attached.

I did a little digging and figured it out that ajax call being made is to the following url.

  http://simplytest.me/simplytest/projects/autocomplete?string=views

I could be use the same end point but I need to get the permission and also the data available is not sufficient for my use case. I wanted to know if Drupal.org provides any authentic feeds of modules so that I will be able to list other details, say the download url for the tarball file.

The official Drupal.org feeds available can be found at https://www.drupal.org/api/rss.  There is a feed for projects, but to get the information about releases you'll need to parse the JSON of an API request like
https://www.drupal.org/api-d7/node.json?field_project_machine_name=media

You can read more about the APIs available and how to use them at https://www.drupal.org/api

UPDATE:  If the goal is to a list of all projects and pull their releases, this cannot be done with just an official "feed".  It requires scraping the list of projects from Drupal.org and writing code to get the release into, but the code to do that already exists.  Lin Clark's ScraperWiki code still works (http://lin-clark.com/blog/2011/07/22/writing-scripts-clone-contrib-projects-gitdrupalorg/).  Export the scrapper output as SQL, import that into a custom table, write some code to loop those the projects calling Drupal.org's API to get the release information you are looking for, and save that response.  Not as easy as just pulling the information from a feed provided by Drupal.org, but it can be done.


CKEditor using the website CSS What I want, is that the CKEditor will use the website css, as you can see here:

it is not the same as:

I am using less css. I have tried to define the main less css file which imports all the other less css files together. This didn't work. Also the automatically generated css file by drupal doesn't has a solid path to put into the CKEditor CSS settings underneath the CSS file path settings.

Is there a way to make my editor use the same style as I use for the website?

LESS like SASS has to be compiled to real CSS-files.

Find out where the compiler put the CSS-files eg. by disabling css-aggregation and check the source-output of your site.
Add the paths of the css-files to your CKEditor-settings.


Add data to JSON generated by views_datasource I'm using "views datasource" to output a view as JSON - for each views row it's creating a JSON object with the fields as string/value pairs - all those objects are in an array which is the value to a string specified by the "Root object name" in the view's format settings. It looks like this:

{
  "nodes":[
    {
      "nodeid":"1",
      "title":"foo"
    },
    {
      "nodeid":"2",
      "title":"bar"
    }
  ]
}

Now I need to add another string/value pair to the main JSON object so it looks like this:

{
  "nodes":[
    {
      "nodeid":"1",
      "title":"foo"
    },
    {
      "nodeid":"2",
      "title":"bar"
    }
  ],
  "total_nodes":"2",
  "some_other_stuff":"here"
}

In another question I found out how I could add elements to the view's results but now I need to add elements "next to" the view's results. I just don't know where I need to put my code. Can anyone point me to a hook that would do the trick?

You could implement something in the view template for the JSON display.

The correct file to modify seems to be views-views-json-style-simple.tpl.php.

You have to copy it to your theme's template folder (usually template's root directory, or template subdirectory) and add the necessary data to the $json variable before the correct print $json statement.


Possible to pull the validate hook on forms not in form api Is it possible to utilise the validate hook from within a node rather than a module? The code below works within a module calling a form with the form API. But if i was to have a variable in a node page, could i utilise the same function within the nodes html/php? if so how? or a similar validate function?

$mynumber= $_POST[mynumber];

e.g.

function form_example_form_validate($form, &$form_state) {
      if (!is_numeric($form_state['values']['mynumber'])){
form_set_error('mynumber', t('Validation: You must enter a valid number for the number field.'));

The validate handlers for forms aren't hooks as such, they're just functions that use a naming convention provided by the FAPI (small point, but worth mentioning).

Technically speaking, you might get away with putting said function in PHP in the body of a node. If you have a form called MYMODULE_form_test, and declare a function called MYMODULE_form_test_validate in the body of a node, the processor might well pick it up in time, and Drupal might call it during form validation. But you'd probably get some strange, incorrect results when you turn caching on.

Either way, I wouldn't rely on it working forever more; it's certainly not an advisable workflow, and keeping code in the node body is considered very bad practice.

Creating a module only takes a couple of minutes, and this sort of functionality is exactly what they're designed to contain.


Why are not all stylesheets in mytheme.info being loaded? I have a strange issue, when I include the last CSS file (assets/fonts/montserrat/style.css), then the assets/css/style.css doesn't get loaded. It seems to have to do with duplicate naming of files, when I rename the stylesheet to montserrat.css, the issue is gone.

How do I solve this issue while keeping the naming of files intact?

mytheme.info:

name = mytheme
description = My custom theme
core = 7.x

stylesheets[all][] = assets/plugins/bootstrap/css/bootstrap.min.css
stylesheets[all][] = assets/plugins/font-awesome/css/font-awesome.min.css
stylesheets[all][] = assets/css/style.css
stylesheets[all][] = assets/css/custom.css
stylesheets[all][] = assets/fonts/montserrat/style.css

the answer is in the drupal_get_css doco page:

  Themes may replace module-defined CSS files by adding a stylesheet with the same filename. For example, themes/bartik/system-menus.css would replace modules/system/system-menus.css. This allows themes to override complete CSS files, rather than specific selectors, when necessary.

If you look at the source code at the bottom of the page, the array that contains the css has the basename of the file as the key. So this is an intentional feature.

You will just have to keep the renamed file.

Hope this helps. :)


How to have multiple exposed filters in a block that affects multiple views content panes in a panel? I have a view with multiple content panes. One shows a table, other shows a chart and so on. On every content pane I have the same exposed filters and it's exposed as a block.

In a panel I add all thosse content panes and on top of the page I show the exposed block. How can I make the filter to affect all the content panes and not one individually?

Select one of your displays (lets say table1) and add (or recreate) the other displays as attachments.  Then only display table1 on your page and all other displays should tag along with it. Then expose the filter for table1.

Here's a good overview:
http://nmc-codes.blogspot.co.nz/2012/10/views-attachment-in-drupal-7.html

UPDATE:

If you just want disconnected views to pick up on one exposed filter then this might do the trick:
https://www.drupal.org/project/global_filter

It gives you configurable blocks with filter options. These options are made available as contextual filters so your views don't need to have the exposed filters.


How to create 2 or more different registration pages in Drupal 7 I'm trying to create (on this, my first project) 2 user registration pages, one for free, the other one could be a 'paid' subscription sign up via UberCart. I'm using AutoAssignRole, Profile2, Views, roles.
I'm sure it is really very easy, but I seem to be going around in circles and not getting anywhere. Maybe I can't see the 'logic' for the 'trees'.
The Drupal forums lack any specific answers.

I'm running a Dev machine on an Ubuntu localhost (without WAMP) prior to any.
It's all very frustrating and I'm trying to learn ASAP as to get back in to work. Does any one have a simple answer, or any suggestion for a tutorial on the above?
I'm a newbie to Drupal 7 and web programming, but I have 25 years of experience in IT, previously on Microsoft platforms.

Could Rules and Webform suffice for what you need to accomplish with the second registration form?

I actually did something similar recently, using a webform as a second registration form. I used the original registration form for the basic registration and on the second form I used Webform Rules to perform actions when the webform was submitted. Of course, this could also be done with a simple fielded node and Rules, but I liked the extra features that webform offered in doing this. If this project can be accomplished with nodes/Rules or Webform/Webform Rules then that can certainly offer you a lot of flexibility in updating the forms in the future as well.


How to create a message with message stack when user becomes a member of a group module group? Hi currently I try to code a custom module for notification based on message stack module.
Now I'm searching for the event or hook to perform some custom code when the user becomes a member of a group.
I want to create a message based on the message stack like "the user John Doe became a member of group xxx. Visit group xxx."
Unfortunately I didn't found something like that in the module docs, so I ask here.
Thanks in advance for your help

It looks like the membership relationship is stored as a GroupContent entity, so in theory you would use something like hook_ENTITY_TYPE_insert()as your event:
function MODULE_group_content_insert(\Drupal\group\Entity\GroupContentInterface $group_content) {
  // This will fire for all types of group content so make sure to filter
  if ($group_content->getContentPlugin()->getPluginId() == 'group_membership') {
    $account = $group_content->getEntity();
    $group = $group_content->getGroup();
    // Create the message
  }
}

This is untested so may need tweaking, but it should be close enough to get going.


Show users pictures who have flagged a node I have a event node and a flag to join the event.
I want to show the user pictures who have flagged "Join event"

This is what I have done so far

1.Created a Node View

2.Added a relationship Flags: Node flag (select the required flags
    and tick "Include only tagged Nodes"

3) Added another Relationship Flags : User

4) Added Relationship "Content Author"

4) Added contextual filter: Content: Nid >
Content id from URL > Specify validation criteria > Flaggable = Join Event

5 ) Add field User Picutre

Many thanks for your help

I think you'll have to create a user view, displayed as a block, and use the flag relationship to the nodes. Then use a contextual filter, taking the node NID from the URL as default.


How to check field value against same field on existing nodes of same content type I wonder if it possible to check the value of a filed against same field in already existing nodes of same content type.

My case: I have a content type property where people advertise their properties, inside property content type I have a field Phone number. I would like to have a rule to check the value of phone number filed against all the existing properties when user click save on creating new property page and send email to administrator with value of the phone number field.

For my experience the Rules module should be able to do that, but I can't figure how.

How dose Unique field module work?

Knowing about the way Unique field module functionality i can customise the module/create my own to send email if there was a any other content with same phone number

I don't know how to achieve that with rules, but you could use EntityFieldQuery, in a custom submit callback of property_node_form.
Something like that :

/**
 * Implements hook_form_FORM_ID_alter().
 */
function mymodule_form_property_node_form_alter(&$form, &$form_state, $form_id) {
  $form['actions']['submit']['#submit'][] = 'mymodule_property_node_form_submit';
}

function mymodule_property_node_form_submit(&$form, &$form_state) {
  $phone_number = $form_state['values']['field_phone_number'];

  $query = new EntityFieldQuery();
  $query->entityCondition('entity_type', 'node')
    ->entityCondition('bundle', 'property')
    ->propertyCondition('nid', $form_state['node']->nid, '<>')
    ->fieldCondition('field_phone_number', 'value', $phone_number)
    ->range(0, 1);

  $same_phone_count = $query->count()->execute();

  if($same_phone_count > 0) {
    // send mail
  }
}


Is there a way to edit views fields in place? I haven't tried the Editview or editablefields modules for Drupal 6, but neither is available yet for Drupal 7 anyway.

I'd like to provide a way for my users to edit lots of nodes and node fields on one screen, presented preferably to views. I'd rather they don't have to keep following a link (contextual or otherwise) to another edit form.

Any suggestions?

Try editablefields-d7; as reported by the project page the module is a Drupal 7 port of editable fields.
The project is a sandbox project, which means it doesn't support releases, yet, and drupal.org doesn't automatically create the archive containing the module code; this means the code should be considered experimental, and you get the code using git, using git clone http://git.drupal.org/sandbox/damz/1130436.git editablefields_d7 or the link to the snapshot archive.


How to display single fields in multiple line in VIEWS? How to display single fields in multiple line in view.

Example : Address contain multiple lines so each items show on line by line.


Where in the page generation pipeline can an HTML beautifier be placed? I need to view the HTML generated by Drupal and it is pretty hard. If I want to the final output to be put through an HTML beautifier before sending it off to the client where would I do that?

I am sure some of the page optimization utilities on the admin/config/development/performance or the advagg module are at the right place in the pipeline. What stage or APIs would I have to hook into to accomplish something this?

Are there any APIs which can be hooked into to accomplish this or even modules to this?

Yes, in advagg is a good example, you have to get the response content with $response->getContent() in a response subscriber http://cgit.drupalcode.org/advagg/tree/src/EventSubscriber/ResponseSubscriber.php?h=8.x-3.x

  public function onResponse(FilterResponseEvent $event) {
    // Only care about HTML responses.
    if (stripos($event->getResponse()->headers->get('Content-Type'), 'text/html') === FALSE) {
      return;
    }

    $response = $event->getResponse();
    $html_markup = $response->getContent();
    // modify html markup
    $response->setContent($html_markup);
  }


SearchAPI & FacetAPI: search box above I need to have layout like this:
[search box]
[facet - taxonomy 1]
[facet - taxonomy 2]
[search results]

But there is no block for the search box itself and no block only for the results.  Or can I somehow manipulate it in the template? I'd rather not use JS to move the components around.

You can use a view to display the search results, and exposed filters for the search box.
You should set exposed filter of this view as block (in the view settings). Then you can set the form above the search results.


Show only rows with highest values Drupal 8.x

I have a view returning:

UID: 1, NID: 1, VALUE: 9
UID: 1, NID: 3, VALUE: 8
UID: 1, NID: 2, VALUE: 7
UID: 2, NID: 9, VALUE: 5
UID: 2, NID: 5, VALUE: 4
UID: 2, NID: 7, VALUE: 3

I would like to only return:

UID: 1, NID: 1, VALUE: 9
UID: 2, NID: 9, VALUE: 5

My goal is to show only one row per UID which contains the highest VALUE. For this view, NID does not matter, but it is a part of the Database table and query being sent to views with hook_views_data() and is used elsewhere.

Can the Views module accomplish this?

In Drupal 7 there was the Views Reference Filter.

Basically, what you're after is filtering one view with another (if you have to go through the interface and not code a custom solution). Those database queries can be quite slow so you're advised to use caching.

Views Field View has the D8 version. The strategy is to create two Views displays, one listing Users, the other Views listing only one node sorted by Value descending and with a contextual filter for UID. Then you insert the second view into the first one (as an additional field).

This way you get the one node that has the highest value for the particular user.


Request::create is not working in EventSubscriber service class Drupal 8 doesn't allows changing the current page in hook_init as we could do it in drupal 7 using following way :

$_GET['q'] = '/my-url';

But according to documentation we can do it using following way :

$request = \Drupal::service('request_stack');
$current_request = $request->getCurrentRequest();
Request::create('/my-url', 'GET', $current_request->query->all(), $current_request->cookies->all(), array(), $current_request->server->all());

But it still doesn't work.

Note: I have successfully converted the hook_init to EventSubscriber and other code is working fine.

You forgot to assign the value returned from Request::create() to a variable, and the rest of the code. The code shown in that documentation page, merged with the code shown in one of its comments is the following.
$request = \Drupal::service('request_stack');
$current_request = $request->getCurrentRequest();
$sub_request = Request::create('/my-url', 'GET', $current_request->query->all(), $current_request->cookies->all(), array(), $current_request->server->all());
return Drupal::service('http_kernel')->handle($subrequest, HttpKernelInterface::SUB_REQUEST);

Since you want to write code to redirect users to a different page, the equivalent of what you would write in Drupal 7 hook_init(), check also hook_init() removed; it contains example code for that case.
namespace Drupal\mymodule\EventSubscriber;

use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

class MymoduleSubscriber implements EventSubscriberInterface {
  public function checkForRedirection(GetResponseEvent $event) {
    if ($event->getRequest()->query->get('redirect-me')) {
      $event->setResponse(new RedirectResponse('http://example.com/'));
    }
  }

  /**
   * {@inheritdoc}
   */
  static function getSubscribedEvents() {
    $events[KernelEvents::REQUEST][] = array('checkForRedirection');
    return $events;
  }
}

See also the LocalRedirectResponse class.
The event subscriber for the example is described with the following, in mymodule.services.yaml.
services:
  mymodule_event_subscriber:
    class: Drupal\mymodule\EventSubscriber\MymoduleSubscriber
    tags:
      - {name: event_subscriber}


Patching .htaccess file I need to patch .htaccess file which is located in project's root (docroot in this case), my project is written using composer and I created a patch using git, added it to the /patches directory and wrote a composer.json entry:

"drupal/drupal": [
          {
            "title": "htaccess patch",
            "url": "docroot/profiles/laeg/patches/redirects.patch"
          }
        ]

Sadly after running composer update my patch doesn't appear in the patches list therefore it is not applied. I was told that I should patch drupal/drupal but it seems to not be a case, has some done anything like this and could suggest me something? Project is running Drupal 7.

For drupal 8, use the following.
In the 'scripts' section of your composer.json, add

"post-drupal-scaffold-cmd": [
  "patch -p0 < patches/htaccess.patch"
]


Listen and respond to ajax_command_replace() I have a page where a block is dynamically reloaded when the user clicks a link. Rather than writing my own js, I'm trying to do this the Drupal way and using Drupal's own ajax_command_replace() like so:

function page_callback($type = 'ajax') {
    if ($type == 'ajax') {
    // Load block
    // ....
    $commands[] = ajax_command_replace('#block-watch-notifications', $output);
    $page = array(
       '#type' => 'ajax',
       '#commands' => $commands,
    );
    ajax_deliver($page);
}

And all this works just fine.

The problem is that I need to respond to this event on my page. The js event DOMSubtreeModified would work here if it were reliably implemented by browsers, but it's not.

However, jQuery's AJAX command also issues its own series of global events, including ajaxComplete. The problem is that, however Drupal is doing its AJAX magic, it isn't raising this event.

How can I listen for ajax_command_replace() having done its work on my page?

From what I can tell, Drupal behaviors are simply callback functions that are called in two cases: 1. when the page is loaded initially, and 2. when content is added/removed via ajax.

You add your callback function to the global js object Drupal.behaviors (US spelling), namespaced by your module's name. My module is called 'watch' so I attach my callback functions to Drupal.behaviors.watch. Drupal.behaviors.MODULE_NAME is itself an object and has two elements that may be named 'attach' and 'detach'.

'Attach' is called during the initial page load and whenever Drupal's ajax adds new content. 'Detach' is called when is Drupal's ajax removes content, either before adding replacement content or removing it forever.

For the record my javascript looked like this:

(function($) {
  Drupal.behaviors.watch = {
    attach: function(context, settings) {
      // This code is fired both when the page is 'ready'
      // in the jquery sense, and when new content
      // is 'attached' via Drupal ajax. The settings
      // values that are available to us here
      // are provided in the third parameter of
      // ajax_command_replace() as an associative array.
      // My new content is already part of the dom
      // so I can act on it here.
    },
    detach: function(context, settings, trigger) {
      // Example detach callback.
    }
  }
})(jQuery);

I'm guessing Drupal behaviors can be extended to include all sorts of other behaviors beyond attach and detach and is probably very flexible besides, but that's beyond me right now.


D7 - Ckeditor buttons get messed up when moving a site from one server to other I just moved a D7 site from one server to another and the Ckeditor buttons get messed up. Look my capture. How can I fix this?

I use the Adminimal Theme but it is not the problem. If I switch to Bartik the problem persist.

I already cleared caches and run Cron several times.

Have you checked Css settings on Ckeditor profile page?


How do I capture an audit trail of changes made to a view? What would be the best way for me to log any administrative changes that might have been made on a view? E.g. a new filter added or a field removed. The audit entry should include a user stamp and a time stamp and the change that was made. Doesn't look like any of the conventional options seem to capture this information.

You may use Features module to save your view in code and add version control system (Git, SVN) to your project. Every time when you will change the view you will need to update feature with this view and commit your changes into version control system. Then you will have a history of changes


Using variables in an expression I am checking for a specific block in a specific theme region.

{% if page.header_first.blockmachinename %}
   // Show stuff
{% endif %}

This works when I have the right machine name. But I want to be able to use a variable in place of blockmachinename.

Something like this, which of course doesn't work.

{% if page.header_first.{{ the_variable }} %}

This also didn't work, as expected

{% set block_name = 'page.header_first.' ~ the_variable %}
{% if block_name %}

Any clues?

Since the dot syntax can mean a lot of different things, try to make it more clear by using the array syntax:

{% set the_variable = 'mytheme_myblock' %}

{% if page.header_first[the_variable] %}


Why the label of "subject' field in comment-form not be translated and how can I do the translation in a better way? In the baseFieldDefinitions of Comment Entity, the subject field is set to be translatable, but I can not find such a translation in User interface translation(admin/config/regional/translate) that can make it take effect when comment on a content.

$fields['subject'] = BaseFieldDefinition::create('string')
  ->setLabel(t('Subject'))
  ->setTranslatable(TRUE)
  ->setSetting('max_length', 64)
  ->setDisplayOptions('form', [
    'type' => 'string_textfield',
    // Default comment body field has weight 20.
    'weight' => 10,
  ])
  ->setDisplayConfigurable('form', TRUE);

I now use the code to translate it in my module:

function mymodule_preprocess_form_element(&$variables) {

  if (\Drupal::routeMatch()->getRouteName() == 'entity.node.canonical') {
    if($variables['label']['#title'] == 'Subject') $variables['label']['#title'] = t('Subject');
  }
}

I don't think it's a good way since the translation is already defined.(And I've defined Hook_Comment_presave, this two function seems will effect each other,which I don’t want it happen either.)

Is there a better way to do that?

I finally found a solution to enforce translation of 'Subject' label in hook_form_alter which can make code more clear:

function mymodule_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {

  if($form_id == 'comment_comment_forum_form') {
    $form['subject']['widget'][0]['value']['#title'] = t('Subject');

  }

}


Get the field data in email body whenever user creates content, I want to get the few fields data of content in the mail body and trigger mail,, as of now i have created rule to trigger mail with text comparison condition for specific field.

ex: I have content with user id, pancard Id fields etc,now i want to get this content field data in mail body and send mail to user.

Depending on the kind of rule event which I expect to be "When a new content is created" in your case.

When you choose action of rule as "send email" it allows you to use tokens, as declared by token modules. You will see the node tokens for the field as well, use it and those will get automatically replaced.


user registration redirect for custom form drupal 6 I have worked on a solution which will redirect from the user registration form to my own form. My own form can be reached by typing the website name testweb/my_module/form. Here is the code of my module using a form_alter. When I run the function it doesn't redirect to my own form. Could someone advice me why it is not working?

function redirect_custom_reg_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'user_register') {
    $form_state['redirect'] = 'my_module/form';
  }
}

It is $form['#redirect'], not $form_state['redirect'] in this case because user_register_submit() unsets $form_state['redirect'] (well, sets it to '') when it is confident that all is good with its part in the registration process...and hence allowing an alter to add in a #redirect.


Show AJAX throbber during AJAX call I created custom module to make simple Ajax call. This module looks like this:

<?php

/**
 * Implements hook_menu().
 */
function module_ajax_contact_menu() {
  $items['node/get/ajax/%'] = array(
    'page callback' => 'module_ajax_contact_ajax_get_ajax', // Render HTML.
    'page arguments' => array(3),
    'type' => MENU_CALLBACK,
    'access arguments' => array('access content'),
    'delivery callback' => 'module_ajax_contact_ajax_callback',
  );
  return $items;
}

function module_ajax_contact_ajax_get_ajax($nid) {
  $node = node_load($nid);
  return node_view($node, 'default');
}

function module_ajax_contact_ajax_callback($page_callback_result) {
  // Only render content
  $content = drupal_render($page_callback_result);

  // Add CSS and JS files, add some markup
  $html = '<title></title>' . drupal_get_css() . drupal_get_js() . '' . $content . '

The throbber has a class of .ajax-progress-throbber.

Before the Ajax call, add an element with that class to wherever you want it in the DOM, and simply remove it again when the Ajax request completes. Drupal doesn't have any helper methods for this, just use jQuery.


how to resize image programatically with theme image i need to resize image in my module output, but this code seems not working

$file = file_load($fid);
$image = theme('image', array('style_name'=> 'small', 'path' => $file->uri, 'alt' => 'user picture'));

i am getting my image from database. i have created media type small to scale my image,
but style_name does not work.

You need to use theme_image_style() for that one:

$image = theme('image_style', array(
  'style_name'=> 'small',
  'path' => $file->uri,
  'alt' => 'user picture'
));


Cube portfolio pop up image went wrong I am using Cube Portfolio to display portfolios.

The "View Larger" button link shows the correct link.

But when I click on the button,

the pop up image went wrong.

How do I find out the problem?

I look into the code, there is a weird link.

The portfolio section was created in Views. Drupal version is 7.

The image path changes to absoulute path.


After logging off, user is able to see the workbench page by pressing back button of the browser I am using workbench module to show the entry made by some particular user with some role when user is logged in he redirect to my workbench page and  as the user log out it redirect to home page and after pressing back button it redirects to my workbench page

Used this in custom module and it works

<?php
/**
 *Implements hook_init().
 */
function MY_MODULE_init() {
  drupal_add_http_header('Cache-Control', 'no-cache, no-store, max-age=0, must-revalidate, post-check=0, pre-check=0');
}


What are the template variables to identify that a page is a term or user? I'm trying to modify a theme so that when the term page or user profile page are displayed it doesn't generate the title at the top.  I figured out how to do it on nodes but I just can't figure out what variable is used in the following code to identify a user or term page.  Any thoughts?

Here's the code from my page.tpl.php in a Bootstrap v3 theme:

<?php if (!isset($node)): ?>

<?php print $title; ?>

<?php endif; ?>

The above example suppresses the title when the page being viewed is a node.  I'd like to get this to work for user and term pages as well.

I think a better way to hide the title on user and taxonomy term pages would be to use a preprocess_page function in your themes template.php. This way you are keeping your page.tpl.php cleaner and separating logic.

/**
* Implements hook_preprocess_page
*/
function MY_THEME_preprocess_page(&$variables) {
    if( (arg(0)=='user' && arg(2)=='') || (arg(0)=='taxonomy' && arg(1)=='term' && arg(3)=='') ) {
        $variables['title'] = FALSE;
    }
}

This will only hide the title on the view pages, but it will still be there when editing content. This is done by checking that arg(2) is empty on user pages and arg(3) is empty on taxonomy term pages as if editing content these would contain the string "edit".

As pointed out by clive the line in your page.tpl.php would need to read:

<?php if ($title): ?>

<?php print $title; ?>

<?php endif; ?>

Once you have added this code then you will need to clear the cache to see the changes.


How can I call hook_user_presave() only when an account is updated, not created? I want to call hook_user_presave() only when an account is updated, not created.  However, the API docs state:

  A user account is about to be created or updated.

Is there a way to check whether I am getting a new account or an update to an existing account?

On creation $account will have is_new set to true. And other minor differences, like it'll not have created property set yet.

object(stdClass)#92 (18) {
  ["uid"]=>
  int(0)
  ["hostname"]=>
  string(3) "::1"
  ["roles"]=>
  array(3) {
    [2]=>
    bool(true)
    [3]=>
    int(0)
    [4]=>
    int(0)
  }
  ["cache"]=>
  int(0)
  ["administer_users"]=>
  bool(true)
  ["name"]=>
  string(7) "test"
  ["mail"]=>
  string(14) "test@example.com"
  ["pass"]=>
  string(3) "aaa"
  ["status"]=>
  string(1) "1"
  ["notify"]=>
  int(0)
  ["timezone"]=>
  string(13) "Europe/Warsaw"
  ["signature"]=>
  string(0) ""
  ["picture"]=>
  NULL
  ["picture_delete"]=>
  int(0)
  ["picture_upload"]=>
  string(0) ""
  ["signature_format"]=>
  string(13) "filtered_html"
  ["init"]=>
  string(14) "test@example.com"
  ["is_new"]=>
  bool(true)
}


How to conditionally not load js for anonymous users? We have a situation where our contrib modules are being loaded for the anonymous user, but they are not needed. As a result, we are seeing higher page load times. We tried using hook_js_alter in a custom module with the code below. What is the proper way to not load the js files we don't need for the anonymous user?

mymodule_js_alter($javascript) {

  $javascript['somefile']['weight']=50;
  $javascript['somefile']['scope']=bottom; //region for bottom of the page

}

Current code:

function mymodule_js_alter(&$javascript) {

    if(user_is_anonymous()){
       unset($javascript['sites/all/modules/contrib/autocomplete/autocomplete.js']);
     }
 }

If you don't want to load your JS in anonymous user, check the user if its logged in then load the JS file if its true. use user_is_logged_in() to check if user is logged in, place it inside your hook_preprocess_page().

Example:

  $theme_path = drupal_get_path('theme', 'zen');
  // This will load only in authenticated user.
  if(user_is_logged_in()) {
    drupal_add_js($theme_path . '/plugins/jQuery/jquery-2.2.3.min.js');
  }


Code fails only if not logged in Hello I'm currently working in the template.php file to preprocess a view and i'm experiencing strange things:

This relates to a field collection field:

  $collect_field = $value->field_field_screenshot[0]['rendered']['entity'];

Without being logged in this code fails with

  Notice: Undefined index: entity

If logged in everything is fine...

Somebody could imagine what is happening here?

As per the error message, no such index 'entity' exists in the array $value->field_field_screenshot[0]['rendered'] Do a dpm($value->field_field_screenshot[0]['rendered']) when both logged in and logged out and you will see the difference.

Is field_screenshot associated with a user account or profile? In which case, the anonymous user object has no such field, so you're trying to assign to $collect_field something that doesn't exist. You should assert whether the user is logged in or not before doing the assignment.


Dynamic Payment Method required Input Field for Ubercart Checkout I have a site running with Drupal 7.12 and Ubercart 3.0. I am creating a custom payment module which is used to pay by mobile phone. The workflow is:

User enters his mobile phone number in the checkout page
When he clicks on "verify phone number" he gets an SMS with a PIN which he has to enter in another input field.

The PIN field is a required field, but only if this specific payment option is chosen.

I know that i can add additional information by returning an instructions array in my callback method, like this:

function uc_my_payment_method($op, &$order) {
    switch ($op) {
        case 'cart-details':
            $build['instructions'] = array(
                '#markup' => t('Your mobile phone') . ': ' .
                     /* some markup for the new input fields */
                    '<br />'
            );
            return $build;
    }
}

But i am stuck at the form elements. Can you help me? Do you need additional information?

It's a bit late but just for reference for anyone finding this page as a search result: From what I found out by experimenting, you are right that you need to return an element. Actually what I had to do in my case was to use the following code:

$form = array();
$form['mobile_phone'] = array(
  '#type' => 'textfield',
  '#title' => t('Mobile phone'),
  '#description' => t('Enter your mobile phone number here and a PIN will get sent to you.'),
);
return $form;

You just build a normal form and it gets drupal_rendered when needed.


View Members Tab of a Group So I've had my first taste of Drupal Group, and it looks really promising so far. Now I may be missing something totally, but if my user (testuser1) is a  member of a group with 2 other members, why can I not see the Member tab as testuser1?

However, as a site admin I can see the Members Tab:

I already have enabled the Group Type permission: View individual group members for both members and outsiders. So my question is, how do I allow members and outsiders to view the members of that group?

Ok, so I have now realised that the Members tab I displayed above for the site admin, was actually just a tab to show the User-Group relationship, which in way no way links to the user's profile.

So I've applied a solution (which I'm happy with) using Views module. For now I'll just link to my pastebin for this and explain the solution a little later.


Database query to check if current user has created a node reference? I have a content type B with a node reference field (from url) pointing to content type A.
When current user is at "node/add/typeB/nid_of_type A" page then how can i check the database if he has already created a B node for that A node?

I am trying the following code in my template php:

function theme_name_form_alter(&$form, &$form_state, $form_id) {
if($form_id == 'b_node_form') {
global $user;
if (arg(0) == 'node') {
 $nid = arg(3);
}
$query = db_select('node', 'n')
->condition('type', 'b', '=')
->condition('uid', $user->uid, '=');
$query->join('field_data_field_a_ref', 'ar', 'n.nid = ar.entity_id');
//field_a_ref is the node reference field from B to A type
$query->condition('field_a_ref_nid', $nid, '=');
$query->groupBy('ar.entity_id')->execute();
if(!empty($query)) {
drupal_goto('/');

    } else {

   }
  }
 }

But i get this error:

  PDOException: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'FROM node n INNER JOIN field_data_field_a_ref ar ON n.nid = ar.entity_id W' at line 1: SELECT FROM {node} n INNER JOIN {field_data_field_a_ref} ar ON n.nid = ar.entity_id WHERE (type = :db_condition_placeholder_0) AND (uid = :db_condition_placeholder_1) AND (field_a_ref_nid = :db_condition_placeholder_2) GROUP BY ar.entity_id; Array ( [:db_condition_placeholder_0] => vote [:db_condition_placeholder_1] => 1 [:db_condition_placeholder_2] => 7 ) in theme_name_form_alter() (line 109 of C:...\sites\all\themes\theme_name\template.php).

Any help?

Took a while to spot this, but you're not selecting any fields in the query so the SQL syntax here SELECT FROM {node} n is invalid.

Just select a field and you should be fine:

$query = db_select('node', 'n')
  ->fields('n', array('nid'))
  ->condition('type', 'b', '=')
  ->condition('uid', $user->uid, '=');


How do I save the user submitted values of a multi-step node editing form in the database after last step submission? In Drupal 7, I am trying to programmatically create a custom content type. I have defined my custom content type implementing hook_node_info().

For my node editing form, I am using hook_form() and defined my custom node's title here. I used hook_form_alter() to convert my node editing form into a multi-step form, where I used the following code.

if ($step == 4) {
  $form['actions']['finish'] = array(
    '#type'   => 'submit',
    #value'  => t('Submit'),
  );
}
// Add validation handler.
$form['#validate'][] = 'mymodule_form_validate';
// Add submission handler.
$form['#submit'][] = 'mymodule_form_submit';

function mymodule_form_validate($form, &$form_state) {
  drupal_set_message(t('validating multistep form'));
}

function mymodule_form_submit($form, &$form_state) {
  switch($form_state['triggering_element']['#value']) {
    case $form['actions']['next']['#value']: // if 'Continue >>' is clicked.
      $step++;
      $form_state['rebuild'] = TRUE;
      break;
    case $form['actions']['finish']['#value']: // if 'Submit' is clicked.
      $form_state['rebuild'] = FALSE;
      // To Do.
      // Store the values from the form in the database here.
      drupal_set_message(t('Your form has been submitted'));
      break;
  }
}

My multi-step form is working great, but I am stuck on my last step of the form, where I save the user submitted values in the database. I am not getting any reference on this topic.
I am looking for information on how to save my this node in the database, what hooks to use, and some more details. Please guide me in the right direction.

After you have constructed your custom node object by stepping through your multi-form, use the node_save() function. That will write your node to the database.

To see how Drupal creates and saves it nodes you can take a look at node_add(). Hope that helps a little.


How to avoid the error 'array expected string given' in db_query I am getting this error: Argument 2 passed to db_query() must be an array,
string given. In db_query in below function.

function uc_guest_checkout_uc_checkout_complete($order, $account) {
  if (!empty($_SESSION['uc_guest_checkout'])  && !user_is_logged_in()) {
    switch ($order->data['complete_sale']) {
      case 'new_user':
        // For guest checkout, we replace the ubercart generated username and email
        // for a new user with one that is more anonymous.
        $name = uniqid('anon-', TRUE);
        $mail = $name . '.' . uc_store_email();
        db_query('UPDATE {users} SET name = "%s", mail = "%s" WHERE uid = %d', $name, $mail, $account->uid);
   break;
  case 'logged_in':
    // If the order is marked logged in but anonymous, this means that
    // we must have set the uid to the default account, but still treat
    // this as a new user.
    $order->data['complete_sale'] = 'new_user';
    break;
    }
  }
  _uc_guest_checkout_end();
}

I tried this queries but none were creating account with valid names and emails as per db_query which is throwing error but successfully creating user accounts.where as these below queries creating names with random names.

db_update('users')
        ->fields(array(
            'name' => $name,
            'mail' => $mail
        ))
        ->condition('uid', $account->uid)
        ->execute();

db_query('UPDATE {users} SET name = :name, mail = :mail WHERE uid = :uid',
                array(':name' => $name, ':mail' => $mail, ':uid' => $account->uid));

How do I resolve this?

You're using Drupal 6 syntax, you need to convert it to Drupal 7 syntax:

db_update('users')
  ->fields(array('name' => $name, 'mail' => $mail))
  ->condition('uid', $account->uid)
  ->execute();

See the Database API docs for more details.