How to search for complete SKU like "K-00019" (without splitting it at "-" and without removing leading zeros) I am using Search API to search commerce products by SKU. But when I enter "K-00019" as search string, every item is retrieved that contains "19". I investigated why this happens and found, that a method called "prepareKeys" splits the string K-00019 into two parts: K and 00019, then ignores the first part (letter K) and transforms the second part to 19 because of leading zeroes.
As you can mention, this behaviour leads to way too much results.
I need a search that allows to search for the complete sku. Do you have an idea how I can accomplish this? I do not have to necessary use Search API, if you have another suggestion, it would be perfectly fine, even a workaround would be okay.

I made a workaround: I added a computed field to the product type , copying the SKU, removing the dash/hyphen and saving this value. Instead of including the real SKU in the index, I included this stripped version.
At the form part, I added a validation function that removes dashes/hypens from the search input automatically. Just for sake of documentation:

function mymodule_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'views_exposed_form') {
    $form['#validate'][] = 'sku_search_validate';
  }

function sku_search_validate($form, &$form_state) {
  if (isset($form_state['values']['my_sku']) && !empty($form_state['values']['my_sku'])) {
    $new_value = str_replace('-', '', $form_state['values']['my_sku']);
    $form['my_sku']['#parents'] = array('my_sku');
    form_set_value($form['my_sku'], $new_value, $form_state);
  }
}


What is the name of the module that gives a detailed report of modules and themes installed? There is a module that gives a very detailed view of all the modules and themes installed on a site and the core modules as well. I can't remember the name, but I know it exists because I installed it for testing purposes some time ago.

Can anyone remember the name, or tell me about some other modules which do the same thing so I can check if it is the one?

It sounds like you are talking about the Module summary module for D7. The Used modules for D6 is no longer supported.


Edit account creation message I'm trying to change the message users see after creating an account. It currently says:

Thank you for applying for an account. Your account is currently pending approval by the site administrator.
In the meantime, a welcome message with further instructions has been sent to your e-mail address.

What's the best way of changing this? Would the String Overrides module help? A Rule, perhaps?

Many thanks.

This is exactly what the String Overrides module is for.

If you only need just a couple strings, you can also use settings.php.  See this section:

/**
 * String overrides:
 *
 * To override specific strings on your site with or without enabling locale
 * module, add an entry to this list. This functionality allows you to change
 * a small number of your site's default English language interface strings.
 *
 * Remove the leading hash signs to enable.
 */

You don't want to use Rules, because although you can add a new message with a rule, the old message will still be there as well (which isn't what you want, I assume).


Sort contents in content list I need to sort contents in the same manner as blocks are sorting in the block list.
In the block list we can drag an drop blocks to place the them up and down, same functionality I needed for content list for contents.

To add Sort functionality using Drag and Drop into admin/content section, you need to play with administration views using Admin Views module. Note that Weight module is also necessary for this. After installing and enabling these module you can edit administrative views under admin/views section.

But if you simply want to add your new views of specific contents then there is already Weight view available under admin/views section. You can check this view to see the working and functionality using Drag and Drop.

Note: Weight module must be enabled for contents to be sorted.


is there a way to change multiple tags at once? I decided to change a tag which is commonly used.  Is there an easy way to change it for all my content or do I have to manually go in and change each one?  Thank you.

If you changed the tag itself from taxonomy. It will change for all content that use the tag. The only issue you may run into is if your doing url paths based on any taxonomy terms.


Breadcrumbs disappear on cache clear, come back with subsequent cache clear I have a site where the breadcrumb is in different locations depending on what node type or page is being viewed.

In some places, it is interspersed with node content, so the only solution was for my colleague to inject it into the page as a variable, like so (from .theme):

$block = Block::load('breadcrumbs');
$variables['content']['breadcrumbs'] = \Drupal::entityTypeManager()->getViewBuilder('block')->view($block);

I've noticed that when I deploy code, the breadcrumbs disappear. I then have to clear the cache, clear Varnish, and clear the cache again and finally hard refresh in my browser to see them again.

Is this related to how breadcrumbs are being injected into the page and if so, is there a better way to do it?

In a node use the breadcrumb builder directly:

\Drupal::service('breadcrumb')->build(\Drupal::routeMatch())->toRenderable();

The node gets cached already and the cache metadata of the breadcrumbs bubbles up to the node.

In a page it's preferable to place the block in a region (can be a region of its own) and then place the variable of the region in the page template.

If you want to use code to place the block, make sure you use the block for the correct theme (you have to query the block table with the property theme for this). Now it seems like you use the breadcrumb block placed first on your site, not necessarily the one for your theme.


Sub-menu items in twig How can I theme all the menu levels individually in menu.html.twig?

I need to give different markup to the 2nd (child) and 3rd (grandchild) level, and in the twig I only have parent and child.

  {% if item.below %}
    {{ menus.menu_links(item.below, attributes.removeClass('nav'), menu_level + 1) }}
  {% endif %}

Whatever I put in this is duplicated for the child and grandchildren.

I thought that menu_level + 2 might get it. What does menu_level + do?

EDIT:
Thanks to Hudri's tip below I did the following Thanks Hudri!

  {% if menu_level == 0 and item.is_expanded %}
    <li{{ item.attributes.addClass(item_classes) }}>
    <a href="{{ item.url }}" class="dropdown-toggle nav__title" data-target="" data-toggle="dropdown">{{ item.title }} </a>
  {% elseif menu_level == 1 %}
    <li{{ item.attributes.addClass(item_classes) }}>
    {{
      link(
        item.title,
        item.url,
        item.attributes.removeClass(item_classes),
        item.attributes.setAttribute('title', '')
      )
    }}
  {% elseif menu_level == 2 %}
    <li{{ item.attributes.addClass(item_classes) }}>
    {{
      link(
        item.title,
        item.url,
        item.attributes
      )
    }}

menu_links is a Twig macro, that is called recursively. That macro is located in menu.html.twig. In there you can do stuff based on current menu_level.

{% if menu_level == 0 %}

{% else %}

{% endif %}

Notice that this macro is called recursivly, so if you are adding a classes like {% set attributes = attributes.addClass('menu--level' ~ menu_level) %}, this additional class is also stored and passed down recursivly!

Also take a look at core/themes/classy/templates/navigation/menu.html.twig to get an example of a full menu template file.


Different checkout form based on user or role As described, in the docs Checkout Form Builder. This is how you modify the checkout flow. Is it possible to have different checkout flows based on role or user?

For example;

If a teller is logged in. There is no need to collect show account information, or billing.
If a customer is logged in. It will display those panes.

i think something along the lines of this should work.  If you have a whole load of these I'd put them in custom module. Otherwise template.php

/***
* Implements hook_form_FORM_ID_alter
*/

function myform_form_theformid_form_alter(&$form, &$form_state, $form_id){
  global $user;
  if (in_array('teller', $user->roles)) {
  unset($form['account_information']);
  }
 }


Select and trigger popup on marker via javascript Is it possible using javascript to trigger a select on an openlayers marker?
I have access to the name and coordinates of the marker, at the moment I am using setcenter to adjust the map to show the marker but I can not find an api call for selecting markers? Hopefully I'm just missing something simple!

Cheers,
Paul

update

So the use case is:

Auto complete search that shows place names
select a place name
map scrolls to the correct lat/long

Now I need to trigger the marker popup that is in the centre of the screen.

Note:
I have popups working via mouse clicks.

you can select whether you want a Popup to appear on a MouseOver event or on a MouseClick event, go to Admin - Structures - Openlayers - Maps, edit the map you are using and you can change these on the 'Behaviors' tab. Hope this helps.


get node creation date in a view I'm trying to get a nodes "poll" created date and how much time it has until it closes in a view.
but having a problem reaching that information for the available fields, I tried to create a relation with the content: author with no luck.

Poll is a core module and it appears that it doesn't make the "end date" available to views. You could add your own "end date" field to the poll content type but then you have to enter it twice.

Or try the more advanced pollfield module:

Because pollfield allows you to build polls as part of the CCK system, this module provides a more flexible polling option than the Drupal core poll module.

Please let me know how it goes, I'm interested in the pollfield module myself, just don't have time right now to play with it ;-)


How can I render an image_field from within hook_block_view? I want to contain my custom content type's image field (cck) within a block. I define the block within hook_block_view:

function foxyidx_block_view($delta)
{
    $t = get_t();
    if ( arg(0) == 'node' && is_numeric(arg(1)) ) {
        $node = node_load(arg(1));
    }
    switch($delta)
    {
        case 'foxyidx_images':
            $block['subject'] = '';
            $render_out = drupal_render($node->field_image);
            $block['content'] = <<<HTML
                {$render_out}
HTML;
            break;

If I were to render the image_field in a template I would use

print drupal_render($content['image_field']);

However, in the hook_block_view function I assume I need to use another function. Any ideas?

I think a combination of field_get_items() and field_view_value() would do the trick:

$image_items = field_get_items('node', $node, 'field_image');
$image_view = field_view_value('node', $node, 'field_image', array_shift($image_items));

$block['content'] = render($image_view);


How can add a textfield to user/register page form in drupal 7? I want modify and adding a textfield in my Drupal 7 user/register page. I know that the form is generated by the function user_register_form()

Can i add a textfield in this way?

function bartik_copy_user_login($form, &$form_state) {
  global $user;

  // If we are already logged on, go to the user page instead.
  if ($user->uid) {
    drupal_goto('user/' . $user->uid);
  }

  // Display login form:
  $form['name'] = array('#type' => 'textfield',
    '#title' => t('Username'),
    '#size' => 60,
    '#maxlength' => USERNAME_MAX_LENGTH,
    '#required' => TRUE,
  );

  $form['name']['#description'] = t('Enter your @s username.', array('@s' => variable_get('site_name', 'Drupal')));
  $form['pass'] = array('#type' => 'password',
    '#title' => t('Password'),
    '#description' => t('Enter that accompanies your username.'),
    '#required' => TRUE,
  );
$form['address'] = array('#type' => 'textfield',
    '#title' => t('Your address'),
    '#size' => 60,
    '#maxlength' => 125,
    '#required' => TRUE,
  );

  $form['#validate'] = user_login_default_validators();
  $form['actions'] = array('#type' => 'actions');
  $form['actions']['submit'] = array('#type' => 'submit', '#value' => t('Log in'));

  return $form;
}

Drupal 7 provides the ability to add custom fields to the User through admin/config/people/accounts/fields.  This functionality should already be in core.


What modules do I need to add tokens in my content that references the current nodes field? I have a blog content type and I also have a taxonomy reference field for "color". How do I embed the field's color value in the body of my blog post via a token?

You'll need...

Entity API for its extended entity/field token support
Token filter which provides a simple filter that supports tokens

And probably nothing else :)


How can I get the parent node of a referenced node? I have a node called project which contains field building as a referenced item, I used the the hook on building node insert and, having this building id I need to get project id which this building is assigned to. How can I get the project id (the building's parent).

I have found the hostEntity() used in drupal 7 (As Far As I Know), but it seemed this is not applicable anymore in Drupal 8.

Any help?

I think hostEntity was specific to FieldCollection in D7 and not to entity reference. Field Collection is tied to one specific host Entity. With entity reference there is no specific host entity, you can possibly reference one entity in multiple host entities.

You can use Entity Query to get all (host) nodes that reference a specific entity within a specific field.

In a very basic form this would return all "Project" nodes that reference a specific building by field building:

$query = \Drupal::entityQuery('node')
  ->condition('field_building', $building_nid);
$nids = $query->execute();

$building_nid is the node id of the building. This will return "project" node ids in your case.


Address field validation-- how to allow only English/single-byte characters? Using the Address Field module, I have created a country/state/city formatter to allow users to input their location.

On my site, about half of the users are Japanese.

Address Field provides a select list of countries by default, and I have added select lists for states/provinces.

However, users input cities in a standard text field.  I am using Location Taxonomize to tag users with their cities, so I want all cities to be in the same language (in this case, English).  I already have some help text on the form that asks users to input their data in English, but I'd like to add form validation to make sure.

Many Japanese sites do this by checking whether the user input is single-byte or double-byte; since Japanese characters are single-byte and standard English characters are single-byte, this is sufficient for my purposes.

Is there a function for checking this in the form API?

You could compare the length of the string by using strlen which doesn't account for double-byte characters and then using drupal_strlen which does account for double-byte characters. If those functions think the length is different then there are some double-byte characters in there.

That comparison would need to go in a custom form_validate function.


What's the difference between Drupal 8.0.x and 8.1.x? On the drupal core download page I see two development branches, 8.0.x and 8.1.x.

I'm sure in the old days it just went linearly 8.0 then next would be 8.1 etc. but this suggests development is now parallel as if 8.0 and 8.1 are really different.

I'm interested to learn why this is this way. Why, for instance, as a developer would I work off 8.0.x and not 8.1.x?

The answer is semantic versioning. The "1" in 8.1.x, represents a branch that can contain new features as well as bug fixes. Backwards-compatibility to code written for 8.0.x is inherent in the numbering system. So, if your code requires features in 8.1.x, you should develop against it, but note you won't be able to deploy your code until 8.1.0 releases.


How to handle session for anonymous users for CSRF tokens? I need to provide list of CSRF tokens in drupalSettings for every anonymous user so JS can make safe requests to api endpoints.

The CSRF service mentions the need for session to exist for the seed but I am not clear about how to create the session correctly. I tried various approaches but none seem to work correctly.

So far I have tried:

if (session_status() === PHP_SESSION_NONE) {
  session_start();
}
// or
\Drupal::service('session_manager')->start();
// or
\Drupal::service('session_manager')->save();
// or
\Drupal::service('session_manager')->regenerate();
// or
\Drupal::service('session')->start();
// or
\Drupal::service('session')->migrate();

I am trying this in my route controller hook_page_attachments_alter.

This is my code:

/**
 * Implements hook_page_attachments_alter().
 */
function foo_page_attachments_alter(array &$attachments) {
  // Needed for persistent, per-user, csrf tokens.
  $session = \Drupal::request()->getSession();
  if ($session->isStarted() === FALSE) {
    $session->start();
  }
  // or
  \Drupal::service('session_manager')->start();

  /** @var Drupal\Core\Access\CsrfTokenGenerator $csrf */
  $csrf = \Drupal::service('csrf_token');

  $attachments['#attached']['drupalSettings']['foo']['tokens'] = [
    'pathA' => $csrf->get('/pathA'),
    'pathB' => $csrf->get('/pathB')
  ];

  $session->save();
  // or
  \Drupal::service('session_manager')->save();
}

So the solution to this problem is that something has to be saved into the session :)

  if (\Drupal::service('session')->isStarted() === FALSE) {
    \Drupal::service('session')->start();
    \Drupal::service('session')->set('foo', 'bar');
  }
  \Drupal::service('csrf_token')->get('baz');

Also, there is no need to call save() method.


Why I'm not able to delete all taxonomy terms tree? I'm using custom drush command for flushing my custom vocabulary:

    function drush_mm_category_delete_all() {
  $vocab = \Drupal\taxonomy\Entity\Vocabulary::load('mm_vocab');

  if (! $vocab) {
    throw new Exception("Missing 'mm_vocab' vocabulary");
  }

  $tree = \Drupal::service('entity_type.manager')
    ->getStorage("taxonomy_term")
    ->loadTree('mm_vocab', 0, NULL, FALSE);

  drush_print('Amount of terms to delete: ' . count($tree));
  $counter = 0;

  foreach($tree as $term) {
    $term_entity = \Drupal\taxonomy\Entity\Term::load($term->tid);
    $term_entity->delete();
    $counter++;
  }

  drush_print('Amount of deleted terms: ' . $counter);

}

I'm getting error:

  Error: Call to a member function delete() on null

but WTF? I see that loadTree returns flat array of all vocab term. It seems that all items are object with tid property.

If I add:

if ($term_entity) {
  //delete here
}

I'm able to run command without error, but only small amount of terms are deleted. Why?

The comment is correct, children are deleted automatically.

So what you can do is set the max_depth argument to 0, then you should only get the top-level terms and you can delete those.


Tons of file_usage queries I'm attempting to debug a site with intermittent slowness, and I've managed to track it down to a long series of file_usage queries which appear to be coming from a search_index rebuild.

SELECT base.fid AS fid, base.uid AS uid, base.filename AS filename, base.uri AS uri, base.filemime AS filemime, base.filesize AS filesize, base.status AS status, base.timestamp AS timestamp
FROM
file_managed base
WHERE  (base.fid IN  ('50545'))

And

SELECT f.module AS module, f.type AS type, f.id AS id, f.count AS count
FROM
file_usage f
WHERE  (fid = '22638') AND (count > '0')

These queries appear to be triggered on random page loads, and they continue until they are killed, or the page times out.

I thought it might have something to do with rebuilding the search index, so I've added

$conf['search_cron_limit'] = '0';

To settings.php to no avail. There are a whole lot of modules on this site, so I don't really know where to start.

As it turns out, in the system_cron was ultimately causing the query storm. The particular bit of offending code was:

$result = db_query('SELECT fid FROM {file_managed} WHERE status <> :permanent AND timestamp < :timestamp', array(
    ':permanent' => FILE_STATUS_PERMANENT,
    ':timestamp' => REQUEST_TIME - DRUPAL_MAXIMUM_TEMP_FILE_AGE,
  ));
  foreach ($result as $row) {
    if ($file = file_load($row->fid)) {

As it turns out, there were about 200k files which matched that first query. It would then loop through them all and check to see if they had any references remaining. Since it had to do this check that may times, it was hammering the database and causing a decent amount of slowdowns. Additionally, it wouldn't find anything to prune since all of those files are still presently in use.

The solution in my case was to simply set the status field to 1 on all of the offending records, since they weren't going to change any time soon (these are product images whcih don't get updated often). The full consequences of that are unknown to me, but it seemed like a reasonable fix.


Entity Reference- How do I display more than one view mode? I am using entity reference to display some nodes. In manage display, I am rendering my entity reference content with teaser view mode. However, I need to display the first node different. I need the first one with a picture and the other ones I just need the date, text and a link. Something like  in the picture.

I solved by using the module entity reference multiple display  which let you to configure different view modes for your field reference. You can split in groups to achieve that.

You install the module and after it is enabled, you go to your content type and in manage display choose rendered entity with different view modes. I have attached a picture

From then you can choose how many groups you would like to display in my case I just need two, the first one I needed to be displayed as view mode teaser and the second one I need no picture in the teaser and just need to display at most two elements in that group.

If anyone has another way to handle this please post your answer here.


How do I set up PayPal parallel payments in Drupal 7 Commerce Express Checkout module? After an exhaustive online search, I can't find an answer to my problem: where do I place the code snippets PayPal provides to implement PayPal parallel payments in Drupal 7's Express Checkout module? I went to this site to find the code snippets to paste into my site's code, but unfortunately, I can't figure out what file to paste the code snippets into in the Express Checkout module. I've read all of the instructions on PayPal, and being a relative beginner at Drupal (and a total beginner at PayPal), I can't figure out what to do next.

I am trying to allow users of my website to buy downloadable files provided by other users. When they do so, I want to take a small commission for posting their materials on my site. I understand that chained payments is also an option people use for this type of scenario, but considering my inexperience with PayPal, I think that parallel payments is the better of the two options.

In case it matters, I'm working in PayPal's sandbox mode. I've downloaded the paypalplatform.php file and I think I'm supposed to upload this to the main Express Checkout folder (but I'm not sure?), and I understand how to get my sandbox API credentials from PayPal, but I'm pretty much clueless from that point on.

The two specific snippets I'm having trouble with are these:

1.) The one in step 3a, where the instructions say "Insert this code snippet into the section of your code that initiates the preapproval flow on your website." What code initiates the preapproval flow?  Is it contained in a file in the Express Checkout folder somewhere? In which file is it located, and specifically, where in the code should I paste the snippet provided by PayPal?

2.) The snippet provided in step 4c, where the instructions say "Insert this code snippet into the section of your code that initiates a PARALLEL PAYMENT on your website." Again, where is this code located?  Is it in a file in the Express Checkout folder? In which file is it located, and specifically, where in the code should I paste the snippet?

Any help anyone can give me would be much appreciated. Thank you.

The short answer is that there isn't just a place to "paste the snippet." That integration wizard is hopelessly simplistic. Support for a new payment method within Drupal Commerce would require more than simply adding code to a page, because presumably you'll want some sort of local record of any payment action taking place. For that to happen, you have to work with the Drupal / Drupal Commerce APIs as well.

In Drupal Commerce, these integrations are handled through payment method modules. We have documentation for writing them in the developer guide on DrupalCommerce.org. Additionally, if you're PayPal Express Checkout, you should switch to using the 2.x branch of the main PayPal project, http://drupal.org/project/commerce_paypal, as it has a complete implementation of the Express Checkout payment method and has been verified by PayPal.


How to specify PHP block visibility settings for content types AND loads of urls? I wrote lately some instruction to display a block in two different cases:

when the content type is [my-content-1] or [my-content-2]
when the url is /my_page1 or /my_page2

I found how to do it in Block visible for Specific Content Type AND Specific URL.

<?php
$match = FALSE;
$types = array('content-petites_annonces' => 1);
if (arg(0) == 'node' && is_numeric(arg(1))) {
  $nid = arg(1);
  $node = node_load(array('nid' => $nid));
  $type = $node->type;
  if (isset($types[$type])) {
    $match = TRUE;
  }
}

if (substr($_SERVER["REQUEST_URI"], 0, 10) == '/petitesan')
{ $match = TRUE;}

if (substr($_SERVER["REQUEST_URI"], 0) == "/node/add/content-petites_annonces
")
{ $match = TRUE;}

return $match;
?>

It works fine, I could declare several content types in the first array (I've got 6).
But as for the urls, it only works if I repeat the same line every time (and there are loads of them).

if (substr($_SERVER["REQUEST_URI"], 0) == "/my_page1
        ")
    { $match = TRUE;}
if (substr($_SERVER["REQUEST_URI"], 0) == "/my_page2
    ")
    { $match = TRUE;}
...

I am certain there is a more mutualized way to do it.
Is there also a mean to get it working regardless of the pagination, i.e. whithout having to notify every time

 if (substr($_SERVER["REQUEST_URI"], 0) == "/my_page?page=X
            ")
            { $match = TRUE;}

Is the answer hidden in the 0, 10 in the precision about the request URI? I didn't even used that line.

This sounds like the perfect use case for something like the Context module. Contexts are triggered and become active, and would save you from writing tons of PHP to get the matching to work in an unlimited number of use cases and edge cases.

  Think of conditions as a set of rules that are checked during page
  load to see what context is active. Any reactions that are associated
  with active contexts are then fired.

Related modules


D7: How can I list duplicate entities based on the entity title and bundle, without custom coding There is a module for removing duplicate nodes, but how to delete duplicate entities (in my case ECK entities) based on title and bundle that are the same?

I was thinking that the search api module might be of help, which I installed. But listing duplicates requires something extra.

I also have Rules installed, but not sure how to create such rule.

What would be a recommended way to do this?

I'd look at the Entity Bulk Delete module. This module provides a Drush command that can bulk delete arbitrarily specified entity types.

The caveat here is the module does not delete based on your specified logic of duplicate titles. For that, you can modify its EntityFieldQuery in the _entity_bulk_delete_query() function so it matches your criteria for deletion removal.


Does a guide for installation of drupal Cartaro distribution exist? I have been trying to install the Cartaro distribution of drupal on windows that makes drupal

a complete geo-stack. I have been unable to find complete documentation for the same and the

installation fails to detect postgis installed on the computer as well as there is some confusion about the terminology for geoserver.

Have a look at Cartaro's Getting Started guide. Especially see the quoted commands to set up permissions for PostGIS properly.

Additionally, there have been changes to the error reporting of Cartaro in July which should result in more precise error messages in case something is wrong with PostGIS.

Please report any bugs in Cartaro using its bug tracker on the Drupal site so that is does not get overlooked. We'd be happy to see a report there regarding the GeoServer terminology along with a more verbose description.


Set to the language of admin pages to english despite the language of front pages? Possible Duplicate:
  Do not translate the admin area / How can I set the language of the admin area to English?

Just that. I have a multilingual site but I'm very used to see the admin pages in english. Let's say I'm creating a new node in spanish then I see all in spanish language. Is there any way to set the language of admin pages to english despite the language of front pages?

Administration Language module lets the administrator see all administration pages in their preferred language.


Configuration Settings of Authcache + File Cache I have already file cache module installed and working perfectly except that I've read that it also work with authcache.

So I installed authcache but wondering what is the proper configuration in the settings.php.

In authcache readme file, it gives an example as follows:

$conf['cache_backends'][] = 'sites/all/modules/filecache/filecache.inc';
$conf['cache_backends'][] = 'sites/all/modules/authcache/authcache.cache.inc';
$conf['cache_backends'][] = 'sites/all/modules/authcache/modules/authcache_builtin/authcache_builtin.cache.inc';
$conf['cache_class_cache_page'] = 'DrupalFileCache';

And my current configuration for file cache module is:

$conf['cache_backends'] = array('sites/all/modules/filecache/filecache.inc');
$conf['cache_default_class'] = 'DrupalFileCache';
$conf['filecache_directory'] = '/tmp/scfilecache-' . substr(conf_path(), 6);

I tried to combine the two configuration as follows without luck:

$conf['cache_backends'][] = 'sites/all/modules/filecache/filecache.inc';
$conf['cache_backends'][] = 'sites/all/modules/authcache/authcache.cache.inc';
$conf['cache_backends'][] = 'sites/all/modules/authcache/modules/authcache_builtin/authcache_builtin.cache.inc';
$conf['cache_class_cache_page'] = 'DrupalFileCache';
$conf['filecache_directory'] = '/tmp/scfilecache-' . substr(conf_path(), 6);

My site returns an error with the config above.

Anyone know what is the correct configuration for authcache + file cache?

After testing for several settings, I came up with the following configuration:

$conf['cache_backends'][] = 'sites/all/modules/filecache/filecache.inc';
$conf['cache_default_class'] = 'DrupalFileCache';
$conf['filecache_directory'] = '/var/www/clients/client1/web8/tmp';
$conf['cache_class_cache_authcache_key'] = 'DrupalFileCache';

$conf['authcache_builtin_cache_without_database'] = TRUE;

$conf['page_compression'] = 1;

$conf['page_cache_maximum_age'] = 600;

$conf['cache_backends'][] = 'sites/all/modules/authcache/authcache.cache.inc';
$conf['cache_backends'][] = 'sites/all/modules/authcache/modules/authcache_builtin/authcache_builtin.cache.inc';

I am using nginx and just change the $conf['cache_class_cache_page'] to $conf['cache_default_class']. I don't know if I am using the correct config, but this works for me.

And the speed of my server increase significantly when I ab test it.


How do I troubleshoot unit tests using xdebug? I have xdebug in a Vagrant box, based on VDD, set up and working correctly. Breakpoints trigger phpstorm and mostly works just fine. But when I enable the testing module and try to run a single test on admin/config/development/testing  where a breakpoint in the test source code has been setup, nothing gets triggered. I am assuming that's because PHPUnit is using a separate process. I went though this but it's not helping much.

I was unable to figure out why the debugger would not initially trigger for tests while it's triggered for other normal requests. Then I changed the xdebug.remote_autostart = 0 to xdebug.remote_autostart = 1 and it started working. I even changed it back to xdebug.remote_autostart = 0 and it kept working.

I also found out that one can also temporarily enable the phpstorm break at first line by xdebug settings:

I presume there is not one answer fit all but hope this helps others.


restrict page callback url? With this callback code - is it possible to restrict url just to be example/page1 (2 arg) but not example/page1/321 or example/page1/abc/efg...?

// hook_menu example
function example_menu() {
 $items['example/page1'] = array(
'page callback'     => 'example_page1_callback',
'access callback'   => TRUE,
'type'              => MENU_CALLBACK,
 );
 return $items;
  }

 // hook_meny callback function
function example_page1_callback() {
 // please provide code within this function to turn these next three
  // variables into separate output variables for the template.
  $variable_to_print1 = 'Foo';
  $variable_to_print2 = 'Bar';
  $variable_to_print3 = array('bing', 'bang', 'bong');
  return;
 }

The easiest way would be within your code.

You could change your 'access callback' => TRUE, to a function e.g. 'access callback' => my_access_check,

And within that function you can have an if statement to detect if a 2nd arg existing and if it does return false which would provide an access denied

If you wanted to do a "page not found" or a redirect or something else then you could put this logic into your 'example_page1_callback' function


Is there any way to dynamically add a CSS class selector to a view with submitted exposed filters? I need to add some different styling to a view based on whether the exposed filters have been applied or not. Eg add the class "filtered" once a person has submitted their info in the exposed filter?

You can do this with View's pre_render hook, eg, something along the lines of this:

function YOURMODULE_views_pre_render(&$view) {

  if ($view->name=='NAME_OF_YOUR_VIEW') {
    drupal_set_message('<pre>' . $view->exposed_data . '</pre>'); // to see what you have to work with
    if (!empty($view->exposed_data['type'])) {
      $view->display_handler->set_option('css_class', 'view-has-been-filtered');
    }
  }

}

The above is based on a node type exposed filter, you will need to look at your View to see what filter names are involved, but the logic is that the exposed_data filter arrays will be empty until you have applied the filter.  For example, here, this looks like this when you first go to the View:

Array
(
    [type] => Array
        (
        )

    [submit] => Apply
    [form_build_id] => form-85a47ba22bc12a8b443e4cc35afe75f7
    [form_token] => 105c57eec73efe4cfedd9acabc55786a
    [form_id] => views_exposed_form
    [] => Apply
)

and this is what it looks like after selecting 'foo' as a type in the exposed filter:

Array
(
    [type] => Array
        (
            [foo] => foo
        )

    [submit] => Apply
    [form_build_id] => form-85a47ba22bc12a8b443e4cc35afe75f7
    [form_token] => 105c57eec73efe4cfedd9acabc55786a
    [form_id] => views_exposed_form
    [] => Apply
)

ADDITION:

If this works for you, and per your comment, I suppose the following would work for any/all Views, but I haven't battle tested it...

function YOURMODULE_views_pre_render(&$view) {

  $filter_classes=array('view-has-been-filtered');

  if (!empty($view->exposed_data) && is_array($view->exposed_data)) {

    foreach($view->exposed_data as $k => $key) {
      if (is_array($key) && !empty($key)) {
        $filter_classes[]='view-has-been-filtered-by-' . str_replace('_', '-', $k);
      }
    }

    if (count($filter_classes) > 1) {
      $view->display_handler->set_option('css_class', implode(' ', $filter_classes));
    }

  }

}

...with the logic here being the only arrays in $view->exposed_data are filters, and if they aren't empty, the View has been filtered.

EEEK ADDITION:

My logic is somewhat flawed in that my initial tests were for filters that allowed multiple selections, and, of course, Views used arrays to capture them in $view->exposed_data.  If your filters are just single value fields, Views will do something like this first:

Array
(
    [multiple_value_allowed_type] => Array
        (
        )

    [field_single_value_field] => All
    [submit] => Apply
    [form_build_id] => form-f601bde36c625db96bad7a84bf4fa210
    [form_token] => 105c57eec73efe4cfedd9acabc55786a
    [form_id] => views_exposed_form
    [] => Apply
)

so I guess the following dull ax approach would work:

function YOURMODULE_views_pre_render(&$view) {

  $filter_classes=array('view-has-been-filtered');

  if (!empty($view->exposed_data) && is_array($view->exposed_data)) {

    foreach($view->exposed_data as $k => $key) {
      if (is_array($key)) {
        if (!empty($key)) {
          $filter_classes[]='view-has-been-filtered-by-' . str_replace('_', '-', $k);
        }
      } else {
        switch ($k) {
          case 'submit':
          case 'form_build_id':
          case 'form_token':
          case 'form_id':
            break;
          default:
            if (!empty($k) && $key != 'All')  {
              $filter_classes[]='view-has-been-filtered-by-' . str_replace('_', '-', $k);
            }
        }
      }
    }

    if (count($filter_classes) > 1) {
      $view->display_handler->set_option('css_class', implode(' ', $filter_classes));
    }

  }

}

DOUBLE D'OH ADDITION:

Of course, this quick and dirty logic also works:

function YOURMODULE_views_pre_render(&$view) {

  if (!empty($view->exposed_data) && count($_GET) > 1) {
    $view->display_handler->set_option('css_class', 'view-has-been-filtered');
  }

}

ADDITION DUE TO COMMENTARY:

If you are setting css classes via the UI that you want to preserve, you can do this:

$view->display_handler->set_option('css_class', $view->display_handler->get_option('css_class') . ' view-has-been-filtered');

which gets that UI option and then adds the view-has-been-filtered class to it.  Please note the required space in front in the code :)


Drupal core patches with Commerce Kickstart 2.0 In the installation instructions for Commerce Kickstart 2.0, it alludes to the fact that Kickstart has two patches to the core.  See instructions at https://drupalcommerce.org/commerce-kickstart-2/install.

Did these patches make it into Drupal 7.34? I am asking because I don't want an install of Drupal core with Commerce Kickstart; I just want the Commerce Kickstart code without the core. I don't want to use the installer.

Basing on the content of the drupal-org-core.make file that comes with the distribution, I can say the patches are not part of Drupal 7.34. In fact the make files requires Drupal 7.34, and then lists the patches to apply.

projects[drupal][version] = 7.34

; Patches for Core
projects[drupal][patch][] = "http://drupal.org/files/issues/install-redirect-on-empty-database-728702-36.patch"
projects[drupal][patch][] = "http://drupal.org/files/drupal-1470656-14.patch"
projects[drupal][patch][] = "http://drupal.org/files/drupal-865536-204.patch"
projects[drupal][patch][] = "http://drupal.org/files/issues/drupal-7.x-allow_profile_change_sys_req-1772316-28.patch"
projects[drupal][patch][] = "http://drupal.org/files/1275902-15-entity_uri_callback-D7.patch"

You could apply those patch manually, but you would still be missing all the patches the distribution is applying to third-party modules. See all the lines containing [patch][] in the drupal-org.make file. The following lines are the ones for the Features module, but you can find more lines for other modules.

projects[features][version] = 1.0
projects[features][patch][] = "http://drupal.org/files/1572578-part-one.patch"
projects[features][patch][] = "http://drupal.org/files/1597186-1-features-do-not-cache-includes.patch"
projects[features][patch][] = "http://drupal.org/files/927566-multiple-link_path.patch"
projects[features][patch][] = "http://drupal.org/files/1669720-fix-features-flush-cache.patch"


Adding a block where an admin can create users on the fly What methods are there for creating users on the fly for Drupal 8 in a block? I'm creating a page where the admin can create content, but also there is a user reference field. I currently have it expose current users in the system that you can choose from. In order for me to create a new user to the list, I have to goto the admin/people/create page, but what methods are there to expose this user creation form on the content creation page?

I tried inline_entity_form but that doesn't work as it is still in alpha. It's best if I can just do this in core. Ajax isn't necessary as reloading the page is ok.

Well, it's a great opportunity for you to learn how to write a custom block, and a custom form in it:

Create a new block in one of your module
Create a custom form in it.
Place your block somewhere in your page. You are done!

For both block and form creation there are nice articles just for Drupal 8.

Good luck!


Content type template only for viewing, not editing I've added a page template to override certain content types

function THEMENAME_preprocess_page(&$variables) {
  if( !empty($variables['node']) ) {
    $variables['theme_hook_suggestions'][] = 'page__node__' . $variables['node']->type;
  }
}

This successfully uses page--node--vendor.tpl.php instead of page.tpl.php

The problem is that it is also using this template when editing the node, which looks rather silly. How can I modify this to only use the template when viewing content and not when editing?

** Yes, I do want Drupal to use this theme when creating/editing content, and not a separate admin theme.

This was the most convenient variable I found in the $variables array to check whether I was viewing or editing

function THEMENAME_preprocess_page(&$variables) {
  $is_editing = isset($variables['page']['content']['system_main']['#node_edit_form']) && $variables['page']['content']['system_main']['#node_edit_form'];

  if( !empty($variables['node']) && !$is_editing ) {
    $variables['theme_hook_suggestions'][] = 'page__node__' . $variables['node']->type;
  }
}


Existing orders with deleted coupon throw EntityMetadataWrapperException My users have been placing orders on my website with a coupon code that now no longer exists. Any orders that previously used the coupon/discount 'freeshipping' are now throwing me the following error when I try to edit them (change their status):

  EntityMetadataWrapperException: Missing data values. in
  EntityMetadataWrapper->value() (line 83 of
  /sites/all/modules/entity/includes/entity.wrapper.inc)

Is there any way to fix this? I need to be able to edit those orders and change their status from pending to processing. I had a look at this discussion, but it doesn't seem like a solid solution was found.

If time is a factor you could just create a new coupon that matches the machine name of the old one.

Then when you are ready to fix them, first edit the orders to remove the coupons from them.once all are removed, then delete the coupon.


Can't add new language to a Drupal 8 installation I have installed a Drupal 8 installation using the app utility from my hosting.

The main language is Spanish, but when I'm trying to add two new languages from admin/config/regional/language there is no "Add language" button. The module Interface Translation is installed.

Is it possible that languages are locked by any configuration file? How can I make the button appear again?

Uff, silly me!!! The problem was that the block that shows the link to add a new language was removed from my admin theme. Ok, I hope this helps somebody else with a similar problem too.


Drupal Form API tableselect programmatically check or uncheck checkbox I followed this code example and built up my own version of how I want to use the tableselect. I want to use the table select for configurations. To do this I need programmatically check or uncheck a checkbox. How would I go about doing this.

Here is the general idea of my code

function my_form($form, $form_state) {
  $users = array(
    array('uid' => 1, 'first_name' => 'Indy', 'last_name' => 'Jones'),
    array('uid' => 2, 'first_name' => 'Darth', 'last_name' => 'Vader'),
    array('uid' => 3, 'first_name' => 'Super', 'last_name' => 'Man'),
  );

  $header = array(
    'first_name' => t('First Name'),
    'last_name' => t('Last Name'),
  );
  $options = array();
  foreach ($users as $user) {
    $options[$user['uid']] =array(
      'first_name' => $user['first_name'],
      'last_name' => $user['last_name'],
    );
  }
  $form['table'] = array(
    '#type' => 'tableselect',
    '#header' => $header,
    '#options' => $options,
    '#empty' => t('No users found'),
  );
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Submit'),
  );
  return $form;
}

I am hoping/guessing it something simple like setting something in the options array.

I fixed this I understand how #default_value works now. It has to be an array.

$values = array();

$values[1] = TRUE;
$values[2] = FALSE;
$values[3] = TRUE;

$form['table'] = array(
    '#type' => 'tableselect',
    '#header' => $header,
    '#options' => $options,
    '#default_value' => $values,
    '#empty' => t('No campground to claim'),
  );


Commenting gallery items i want to create a gallery where users can comment on each image. I've seen approaches for Drupal 7, for example:

Node gallery Module
This is currently not supported in Drupal 8.
Gallery / Image Content Type with references
Is this a suitable approach for more than 1000 pictures?

Is there a better way to make this work in Drupal 8? Am I missing improvements on Drupal 7/8?

I built 2 gallery type sites with album-image and category-product relations last week - my first 2 Drupal 8 sites! If direct modules are not available, you can try using views to solve your problem by creating your own gallery setup (if acceptable).

Step 1: Create provision for gallery categories

Create a taxonomy vocabulary named gallery_category and add relevant fields to it. These would serve as albums:

image: album cover
body: album description

Step 2: Create provision for gallery items

Create a content-type named gallery_item and add relevant fields to it:

image: the image
body: image description
category: reference to the gallery_category vocabulary - you can have single or multiple values depending on whether your images would belong to one or more categories (as per requirement).

Step 3: Set up views

Create one view to display a list of all categories
Create another view or modify the default taxonomy term view to fine-tune the list of gallery items inside a category.
For the views, if you have too many categories or items, make sure you enable paging or some other relevant solution to make sure all items don't load in a page.

Note: This is a general answer to try and help you. Modify the steps and details as necessary to achieve the output you desire. Good luck!


How to call js and css file and replace the script in code I'm trying to display a map in node page, it's working but the code doesn't look professional.

function customodule_block_info() {
    $blocks['customodule'] = array(
        'info' => t('Google Map Exemple'),
        'cache' => DRUPAL_NO_CACHE
    );
    return $blocks;
}

function customodule_block_view($delta = '') {
    $block = array();
    switch ($delta) {
        case 'customodule':
            $block['content'] = '<!DOCTYPE html>

';

    };
    return $block;
}

I want to know how hook_block_view can read the css and js files?

Create the JS and CSS files and then in the block view add them in the following way:

drupal_add_css(drupal_get_path('module', 'my_module') . '/css/my_css_file.css');
drupal_add_js(drupal_get_path('module', 'my_module') .'/js/my_js_file.js', 'file');

We have done something similar at a module we develop:
Guardian news


Multilingual site with different domain Is it possible to make multilingual site with each language has own domain? So I want to manage all domains with one code and database. All languages will be exactly same translated content.

It's quite possible to do. But there may be some cases where you need to do some custom code. That also totally depends on your business requirement.

However, please follow this one How to set different languages for different domains, and display the language switcher accordingly?

In Drupal 7 Domain Access module is the best one to make multi domain sites. This has a helper module called Domain Locale which is what you need I guess from the question asked.


Console style syntax highlighting I am using the syntax highlighter, which is convenient. I was wondering if there is a module for a console style rendering. For example, in a wordpress site, I saw

I highlighted it just to show that it is not an image of an actual terminal.

The GeshiFilter module may help you.

  At the time of this writing the GeSHi library supports highlighting for more than 130 programming languages and configuration syntaxes, including: ActionScript, Ada, Apache Log, AppleScript, ASM, ASP, Bash, C, ColdFusion, C++, QT, C#, CSS, D, Delphi, Diff, DOS, dot, Eiffel, Fortran, Groovy, Haskell, HTML, INI, Inno, Java, Javascript, LaTeX, Lisp, Lua, Motorola 68000 Assembler, Matlab, mIRC Scripting, MySQL, Objective C, OCaml, OpenOffice.org Basic, Oracle 8 SQL, Pascal, Perl, PHP, PL/SQL, Python, QBasic/QuickBASIC, Rails, Microsoft Registry, robots.txt, Ruby, SAS, Scheme, Smalltalk, Smarty, SQL, TCL, Text, Visual Basic, vb.net, VHDL, XML, X++.


Should I stay with Poormanscron or is it worthwhile to set up an external cron? In Drupal 7 Poormanscron has been made part of core and is the default.  I understand that for this to work at all, the site must get regular page requests in order to trigger Poormanscron - but that is not a concern with my site.

The Javascript it inserts in each page is insignificant and should not deteriorate overall performance much (if anything).  However, when the cron task actually runs, it will do so when someone requests a page, which is exactly the time you do not want your site to appear busy.  Is this a concern, or is this taken care of in some way (e.g. by running the cron task as a low priority subprocess)?

Poormanscron let you configure frequency, but not when to run.  I would prefer to have cron run at night, when the site see very little traffic.

So far, I've made do with Poormanscron.  The fact that it comes "built-in" can be viewed as some sort of recommendation.  However, I am concerned about performance. To me, it looks as if setting up an external cron job (with Gnu/Linux/Unix crontab) is a better solution for a production site.  Is this correct, or is there something I've overlooked?  Are there other things one should factor into this comparison?

PS.  I already know about the Elysia cron contributed module (basically a poor man's cron on steroids), and that it will let you set the time of day to run.  However, to keep this focused I will prefer answers that only look at the core Poormanscron vs. external cron. (Adding contributed modules also carries a performance penalty.)

Unless I'm mistaken. Poormans cron significantly impacts page load performance when cron runs. I only use it on sites I'm quickly working with locally and have no intention of working on in the near future again.
Using crontab to run cron completely removes the detrimental performance of using poormans cron, apart from the subsequent page load having to re-build the necessary caches. Using crontab is the better option, it provides predictable behaviour, is more reliable, and has less of an effect on users.
You may also want to look into using drush to run cron.
As a side note, on the performance tab there is a setting for the 'Minimum cache lifetime' does not only affect the page cache but all caches. If a time is not set there then as far as I know all caches are dumped on each cron run. (There are one or two sensationalist blog posts which appear to say otherwise though, but if you look at the core code they are incorrect.) This is something else which comes into play with cron runs and performance.
Elysia cron: This is more cron on steroids, and is not a replacement for poormans cron, as the Elysia cron documentation suggests, you should have cron running every minute to get the most flexibility with it, which poormans cron is just not capable of.


Ubercart shipping quotes silently fails on server migration I'm having a hard time figuring out why shipping quotes are failing after migrating to a new server.

I can clone the repo in my local machine, and shipping quotes come in fine. I can't find anything in the AJAX request/response headers that tells me why they're failing on the development site. They work on the live site. (It uses Drupal 7.7, while the development site is using Drupal 7.15.)

They work on my local machine (cloned from the same, updated the repository as development).

I get the following error messages on the watchdog log every time I try to get a shipping quote.

  Type: Rules
  Location: /system/ajax
  Referrer: /cart
  Message: Unable to evaluate condition data_is

  Type: Rules
  Location: /system/ajax
  Referrer: /cart
  Message: Unable to apply data selector order:delivery-address:country: Unknown data property delivery_address

I enabled the Rules UI module to view active/disabled rules. And it looks like some rules are based on parameters that no longer exist, perhaps due to updating the Ubercart module. This is confusing because I did the upgrade locally, and I did not find this issue.

These are the active rules with errors:

E-mail an order update notification
Machine name: uc_order_update_email_customer
Weight: 0
Error: Data selector order:order-status for parameter data is invalid

Complete non-shippable order after payment received
Machine name: uc_checkout_complete_paid
Weight: 0
Error: Data selector updated_order:order-status for parameter data is invalid

Ok, I eventually traced the issue back a module called "UUID", which is required by Node Export.

Disabling UUID module solved my issues. The errors in the rules UI (admin/config/workflow/rules) simply went away.

Would love to know more about why this is. I don't need node export at the moment so it doesn't matter to me.


Use Tokens and/or Replacement Patterns in Shortcodes Looking for a way to add a token/replacement pattern into shortcode.

For example, creating a button where different text and link is required depending on other factors - something like the following:

[button link="mysite/[url replacement pattern]" text="[label replacement pattern]"][/button]

The main reason I need to do this is that I'm using view field views and want to replace an empty field with a custom button, contained in the 'sub view' when the view is empty, which needs to be different depending on what should be in the 'sub view' - I'm using shortcodes in with Global: Text Area in the No Results Behaviour (if that makes sense)

Unless, of course, anyone knows another way to achieve the same result.

Ok, seems there are some limited ways to do this, using available replacement patterns that are not contained within square brackets. i.e. %1 and !1, but not [replacement pattern]

Luck would have it, the replacements I need are the %1 and !1 values.

Still - would be great if anyone had any ideas how to use square bracketed replacement patterns in shortcodes without closing the shortcode (which is what appears to happen).


Redirect to webform from controller and back to custom form I have a use case where I'm creating a custom form, but for business reasons, I need to obtain customer information in a separate webform prior to granting access to my custom form. So my workflow needs to be as follows:

Customer attempts to access form at /my-custom-form url
Customer is redirected to customer information webform at /customer-information-form
Customer fills out customer info form and submits it.
On submission, customer is redirected to /my-custom-form url.

My thought was to use a controller for the /my-custom-form url, and just do a redirect to the webform, and then when the webform has been submitted, redirect back to the form, having to note that the webform is submitted. However, what I'm having problems finding is how to redirect using an internal URL using the Drupal\Core\Url class. In order to use the redirect() method that is included in the ControllerBase class, it has to be a defined route name (e.g. my_module.my_custom_route. If I try something like this:
$url_object = \Drupal::service('path.validator') ->getUrlIfValid('/customer-information-form');
$route_name = $url_object->getRouteName();
$this->redirect($route_name);

$route_name = entity.webform.canonical, which throws an error, since that's a generic route name.
So my question is, how do I redirect my user to my webform using an internal path, especially when it is just a generic webform?
UPDATE: So the ControllerBase class has a redirect() method that from what I've seen, should allow me to redirect. However, when I use this code in my controller function:
$url_object = \Drupal::service('path.validator')->getUrlIfValid('/my-custom-form');
$route_name = $url_object->getRouteName();
$route_params = $url_object->getRouteParameters();
$this->redirect($route_name, $route_params);

but when I run it, I get an error that my controller must return a response. If I add some simple markup like so
return [
  '#type' => 'markup',
  '#markup' => $this->t('Hello, World!'),
];

Then I get that markup instead of the redirect happening.  What is the purpose of that redirect() method if it doesn't redirect?

What is the purpose of that redirect() method if it doesn't redirect?

You find this method in both, controller and form:
ControllerBase::redirect()
FormBase::redirect()
It creates a redirect response and you return it if a certain condition is met:
if (...) {
   return $this->redirect($route_name);
}

Example: https://drupal.stackexchange.com/a/277596/47547


Permit a user to create new accounts I am looking for a way to allow one type of users to create a second type of users.

Can anyone advise me on how to do this?

I am using the profile module but creating a profile does not create a corresponding user who owns the profile.

Use the Role Delegation module.

  This module allows site administrators to grant some roles the
  authority to assign selected roles to users, without them needing the
  administer permissions permission.

  For each role, Role Delegation provides a new assign ROLE role
  permission to allow the assignment of that role.

  The module also adds an assign all roles permission. Enabling this
  permission for a role is a convenient way to allow the assignment of
  any other role without having to check all the assign ROLE role
  permissions in the Permissions page.

  If an administrator has the administer users permission, a role
  assignment widget gets displayed in the account creation or editing
  form, and bulk add/remove role operations become available on the user
  administration page. Otherwise, if s/he has at least the access user
  profiles permission, the module adds its own Roles tab to the user
  profile so that roles can be assigned.


get user_page and modify main content I'm very new to drupal.
I have successfully added a new menu Tab. And When I click on it, it shows a new page with the expected data.

However I would like:

To have a "proper page" not just the unthemed view. How can I get the user page and assign my view to its main content ?
Is there any way to make the menu "ajax" ?

So far I have:

function custom_user_page_callback()
{
  $view = views_get_view('activity_feed');
  $view->set_display('view_block_name');
  //$view->set_arguments(array($tid));
  $view->set_items_per_page(5);
  $view->pre_execute();
  $view->execute();

  // Here Instead of printing what shall I do ?
  // like:
  // $page = drupal_get_page( user );
  // $page["main_content"] =  $view->render();
  print $view->render();
}

function custom_user_menu()
{
    $items['user/%user/activity'] = array(
        'title' => 'Activity',
        'page callback' => 'custom_user_page_callback',
        'access arguments' => array('access content'),
        'type' => MENU_LOCAL_TASK,
    );
    return $items;
}

I get the impression you want to create pages out of components, so rather look at Panels (and Panels Ajax Tabs).

In order to use panels properly you have to learn how to use Page manager also as Panels integrates with it. The best online tutorials on that subject are from Johan Falk at Node One, Learn Page Manager! series. Tutorial 4 - 7 of that series deals specifically with Panels, but start at the beginning and work your way through it. You will also learn a lot about context which is an essential concept to master as a Drupal site builder.


Validate based on existing CCK field value? I have a content type with an address field in it. My client has requested that when saving, the site should check whether another node (of the same content type) already has that address.

I.e., I want the content type to validate if and only if the address being given hasn't been used.

How do I do this? Using Drupal 6, by the way.

You should be able to use hook_nodeapi for this!

In this example I'm assuming the node type is blah

In a custom module just write something along the lines of:

function mymodule_nodeapi(&$node, $op, $a3 = NULL, $a4 = NULL) {
  if ($op == 'validate' && $node->type == 'blah') {
    $sql = db_query("SELECT bl.field_address
           FROM {content_type_blah} bl
           WHERE bl.field_address = '%s'", $node->field_address)

    if ($sql != '') {
        form_set_error($node->field_address, t('This address is already being used'));
    }
  }
}

That way, before a node is saved (during the validation) it runs an SQL query to see if the address field is duplicated anywhere else on any other node with the type blah.  If it is, then it throws an error on the form field!  You will need to tweak the query dependant on your table names etc.

I'm only writing that code from the top of my head, and I've not tested it (sorry) but it should definately be a starting point!  I may have the $node->field_address part wrong!

If all else fails, put a die(print_r($node)); after the if ($op == 'validate'... line and you can get the right part from that!

Hope this helps :)

References:

http://api.drupal.org/api/drupal/developer--hooks--core.php/function/hook_nodeapi/5
http://api.drupal.org/api/drupal/includes--form.inc/function/form_set_error/6


Drupal 7 Views, List, Filters and User I have three content types :
Content type A
Content type B
Content type C

B has a node reference to A.
C has a node reference to B.

I have also 2 roles :
Role 1
Role 2
Role 1 is belong to Content type B.
Role 2 is belong to Content type C.

I'm creating a view list in which

1) Content type A (nid) is passed from URL. Filter nodes of type B with nid of type A. ( done with contextual filter )
2) Criteria content type == B ( done with criteria )
3) Join content type C with content type B. ( done with relationship )

I have successfully got a list with above three.

But I have one more thing to do :
If logged-in user is Role 1, I want to filter nodes of type B of the logged-in user.
If logged-in user is administrator, show all nodes of type B which is filtered with node of type A.

How can I do that ? I'm using D7.7

[Edit]
I think filter criteria don't need for user role. It can be done with user filter for content type B. But I can only select all users associated the type B. I cannot select the current logged-in user id from views filter.
I may need to use this module : http://drupal.org/project/viewsphpfilter
Unfortunately, it has no update for D7.

I've done with hook_views_query_alter().

function mymodule_views_api() { // your module name into hook_views_api
    return array(
        'api' => 3,
        // might not need the line below, but in any case, the last arg is the name of your module
        'path' => drupal_get_path('module', 'mymodule'),
    );
}

function mymodule_views_query_alter(&$view, &$query){
    global $user;
    switch($view->name){
        case 'my_view_name' :
            if(!in_array('administrator', $user->roles) || array_key_exists(4, $user->roles)){
                $result = db_query('my_query_here');
                $nodes = array();
                foreach($result as $row){
                    $nodes[] = $row->entity_id;
                }
                $query->where[0]['conditions'][] = array(
                    'field' => 'node.nid',
                    'value' => $nodes,
                    'operator' => 'in'
                );
            }
            break;
}


How to use profile 2 to display user profile page with comments enabled? I have  Downloaded, Installed and enabled profile 2, profile 2 pages & profile 2 group access ( i have organic groups)

Then went to permissions View any profile (all users), View own profile (authe. , admin), Edit own profile (authe. , admin.)

After which i Went to Config > People > Account settings > Manage Display > Custom Display settings and checked user account.

Whats are the next steps that i should do, or are missing, that i should have done, inorder to enable user profile page along with default comments enabled on this page ?

Not sure what you mean by default comments, but I doubt you can use core comments with Profile2 entities. The comment module only works with nodes.

See this core issue for work being done in this area.

Check the Profile2 issue queue for potential workarounds for comments.


cck dynamic select list in a array I have used the code like this

$ch2 = curl_init("http://openexchangerates.org/api/currencies.json");
curl_setopt($ch2, CURLOPT_RETURNTRANSFER, 1);

$json2 = curl_exec($ch2);
curl_close($ch2);

$currency = json_decode($json2);

$opts = '';
foreach($currency as $key => $val)
{
$opts .=$key.'=>'.$val.',';
}

return array($opts);

Here I am getting the combo like this everything in a single line

AED=>United Arab Emirates Dirham,AFN=>Afghan Afghani,ALL=>Albanian Lek,...

What can I do for all the currencies listing 1 by 1 ??

This works for me:

<?php

$ch2 = curl_init("http://openexchangerates.org/api/currencies.json");
curl_setopt($ch2, CURLOPT_RETURNTRANSFER, 1);

$json2 = curl_exec($ch2);
curl_close($ch2);

$currency = json_decode($json2);

return (array)$currency;


How do I store URL parameter in user registration field? I'm trying to store a url variable into a field on the user registration page.

http://domain.com/user/register?aid=74

Can I use javascript to pull that variable and store it in one of the input fields?

Using hook_form_alter you can set the default value of your field to be this query parameter.

function MY_MODULE_form_alter(&$form) {
  $q = drupal_get_query_parameters();
  $form['parameter_field']['default value'] = check_plain($q['aid']);
}


Print multiple files field links, descriptions and file extensions in Twig I have a content type with a field field_file_attachment that allows uploading multiple files with txt, pdf, gif and img extensions.

I would like to get links, descriptions and extensions of all these files printed in my Twig file node--page--full.html.twig.

Is this possible? Should I create a preprocess function for page?

You should be able to do something like this,

{% for file in node.field_file['#items'].entity %}
  {{ file.uri.value }}
  {{ file.name.value }}
{% endfor %}


How can I sort Views output by whether or not field content matches a string? I feel like there must be a module for this, but I can't find one.

What I have is a field with 4 possible values. I want to sort items with a specific one of the values to the top, then everything else in order by creation date.

In SQL, the query would look something like this:

SELECT fields FROM table ORDER BY textfield = "text" DESC, datefield

Consider two different approaches here:

Add a single view with multiple sort criteria:

Create two views:

The first view should include a filter criteria with operator "is one of" for the textfield value you want to use (ex. "text") and a sort criteria based on date.
The second view should include a filter criteria for "is none of" for the textfield value used in the first view (ex. text).
Within the second view, add a field "Global: View area" within the view header selecting the first view created.

The second option requires additional configuration, but should give you more control over the sorting of the different groups. In addition, using multiple sort criteria for text fields occasionally causes duplicates to appear and the multi-view approach avoids this problem.

Update

Check out Views Argument Extras. This module provides a method to sort based on argument criteria (such as arbitrary fields) without using weights. Here's my configuration:

The above configuration will be too simplified for your 'sort by day, then text field, then time configuration', but it's a good start. To sort by day, then text field, then time you'll need to use the date module and limit the elements that it sorts by (checkboxes).

If this is something you plan to apply globally, consider adding the Weight module and sort based on that instead of Views Argument Extras.


Feeds Node processor mapping I want to import XML data from a remote server. The Feeds module has to interact with an API that outputs the data in a XML format where the actual content is in JSON format. Here's an example of the XML file:

<serverResponse>
  <status statusCode="0">OK</status>
    <messages>
      <user/>
      <tech/>
      <alert header="_*Alert*_"/>
    </messages>
  <content>
    {"appointmentSet":[{"appts":[]}],"bookingAllowed":false,"maxBookAheadPeriod":25}
  </content>
</serverResponse>

What I try to achieve is to let the Feeds module grab the <content> data and put it in a node text field. Then I want to use the drupal_json_decode function to decode the JSON data in readable text.

In my XML Xpath parser settings I've used //content for the Context value. But I've no idea what to do with the processor mapping. Can someone please help me? Does the Node processor mapping require a unique identifier for the GUID or is this not mandatory?

Does the Node processor mapping require a unique identifier for the GUID or is this not mandatory?
You do not need to have a unique identifier to import data, but you might get duplicate data if you do not use a unique identifier.  From your question I assume you are interacting with the API in the feeds fetcher. Can you get "duplicate" results when using the API? Or, is each import ALWAYS  creating new nodes?
Xpath
Use //content/text() to return the json text {"appointmentSet":[{"appts":[]}],"bookingAllowed":false,"maxBookAheadPeriod":25}


Upgrading from 8.3.7 to 8.4 conflicts with acquia/blt-project In the composer.json file I added "drupal/core": "~8.4" to the required section. When I run composer update drupal/core --with-all-dependencies, I get the following output.

  Loading composer repositories with package information
  Updating dependencies (including require-dev)
  Your requirements could not be resolved to an installable set of packages.

  Problem 1

  drupal/core 8.4.0 conflicts with acquia/blt-project

Why does Drupal 8.4 conflict with acquia/blt-project?

The problem was a line in my composer.json file which is prevent the upgrade from happening.

In the "conflict" section, there's a line "drupal/core": ">=8.4.0-alpha1"
I have to remove that line and also run the following commands to complete the upgrade.

composer update --lock
composer require acquia/lightning:^3.0 acquia/blt:^8.9 --no-update
composer update acquia/lightning --with-all-dependencies


Using field_create_instance(), db_set_active() and node_save() in conjunction I'm in the process of writing a module that will essentially publish a node to two sites (the one the user is creating the node on and another one specified in code). Both sites run on the same Drupal installation, with all the needed database info defined in $databases.

In short, part of the process involves populating a hidden field in the second website's "article" content type. That field isn't defined on the first site because it doesn't need to be referred to there. I want to make Drupal "aware" of the field by the time it performs node_save(), but without actually creating the field on the first site, because the resulting tables in the database would go unused.

So, the basic logic of my module's code is:

Modify the node form slightly to include a new checkbox
If it's checked:

Manipulate $node to specify values for a field that only exists on the other site
Use hook_node_insert and hook_node_update to switch to the other site's database and perform a node_save in it

It's a bit more complex than that and the other site also checks said field's value to display a message, but the steps above are the ones relevant to my problem. Initially I thought just adding an array for the field in $node would do the trick, but then I learned that the field needs to have an instance attached to the bundle before any subsequent database interactions will do anything with it. In order to do that, it looks like the standard procedure is to use field_create_field and field_create_instance - only I would like to get away with only using the latter, since I don't want the field to actually exist on the first site, only the second one.

Are there any reliable ways of achieving this? I hope I explained it well enough but will try to provide more detail if necessary.

I've figured out a solution to this, although I'm not sure if it's the best performance wise. It would seem that even after switching database with db_set_active(), node_save() (and presumably any other field<>database operations) will continue to use the field info as defined beforehand, so even if you've specified a value for a field that only exists in the second database, it will assume the field doesn't exist. Using field_info_cache_clear() right after db_set_active() solves the problem.

Obviously clearing any cache in a hook like this sort of defeats the purpose of the cache; fortunately in my case it won't be necessary too often.

If anyone knows of a better way of handling it without clearing any caches or creating the field on both/all sites, I'd love to know. I won't mark this as the accepted answer for the time being.


Pathauto unable to bulk update contents alias with AJAX error In some way I have imported a legacy large database schema to Drupal's database schema. Everything works fine and the imported contents is working fine as nodes.

However, when I try to perform Bulk Update for aliases via admin/config/search/path/update_bulk, using pathauto module, I got the following error message after about 4825 items :

An AJAX HTTP error occurred. HTTP Result Code: 500 Debugging information follows. Path: /drupal/batch?render=overlay&id=1074&op=do StatusText: Service unavailable (with message) ResponseText: EntityMalformedException: Missing bundle property on entity of type node. in entity_extract_ids() (line 7844 of /xxxxx/drupal/includes/common.inc).

The following is a screen shot:

Clicking on the link titled Please continue to the error Page just send me to the bulk Update page with error message:

An error occurred while processing pathauto_bulk_update_batch_process with arguments : pathauto_bulk_update_batch_process

I could not able to find more detailed debug info and I don't know what's the matter?

Last version of Pathauto is used.

I have just find the cause of the issue. It is just two records of node table among about 13K records has no type field value.

To solve it, using PHPMyAdmin I have filled them with the machine name of an available content type. in my case it is archieve


Create custom template for a specific node without node ID? I want to create a custom tpl for a specific node. However I dont want to use node id in the file name (page--node--11.tpl.php). Is there any way to do it?

Sure, you can use hook_preprocess_node() or hook_preprocess_page() to suggest any template you want for a node or a page.  I am suggesting both because of the name you gave in your question page--node--11.tpl.php is really a page template not a node template.

Regardless, you could do this:

function YOURTHEME_OR_MODULE_preprocess_node(&$variables) {

  if ( /* whatever logic */ ) {

    $variables['theme_hook_suggestions'][] = 'node_whatever_you_want_to_call_it';

  }

}

or

function YOURTHEME_OR_MODULE_preprocess_page(&$variables) {

  if ( /* whatever logic */ ) {

    $variables['theme_hook_suggestions'][] = 'page_whatever_you_want_to_call_it';

  }

}

and now when that node is rendered, it will use node-whatever-you-want-to-call-it.tpl.php or if the page, page-whatever-you-want-to-call-it.tpl.php.


Custom entity - BaseFieldDefinition for entity reference field I want to create custom content entity, with entity reference field, and display it by views.

Reference field is defined by:

  $fields['category'] = BaseFieldDefinition::create('entity_reference')
    ->setLabel(t('Category'))
    ->setSetting('target_type', 'taxonomy_term')
    ->setRevisionable(false)
    ->setCardinality(-1);
;

How I'm supposed to use this field in view, to display referenced term names ?

The easy solution is to create the field via the interface instead of creating it as a base field. Drupal core still have some issues with basefields not working exactly the same way as config fields (fields created as config via interface). Views is missing various integration, the same goes with date fields.

In your case, where you have a multi valued field, it would be store the same way, the only difference is the table name (ENTITY__FIELDNAME vs FIELDPREFIX_FIELDNAME).

If you really want to use base fields, you can make up from the missing integration by handling it yourself in a custom EntityViewsData class for your entity. Having done this in the past, my advice would be to just create a config field, since that is working pretty well, and doesn't change anything on the way the field is store in the database anyways.


How to update user profile after submitting a webform? We have a webform and our clients can register for an event using this webform, some of fields are preloaded in the form like "firstname" or "lastname", but i like to update the user info in the user's table in case if the user change his/her info in the event registration webform.

I like to know also how can I update user info using single query because when I look at Drupal database, every single info is in different table like 'field_data_field_first_name' !

I'm not really experienced in Drupal development, so thx for ur help.

You can use the 'Rules' module to trigger an event when your webform is submitted. Using rules pull out the fields, compare them and update the Profile information if they have changed.

Webform integration: - http://drupal.org/node/474644

Hope this helps.


Creating views or facets search with multiple flags So I'm categorising with flags and I will have over 20 per node so that multiple people can flag a node with their opinion... Searching for the past two weeks I have found it hard to work out how I put these flagged results on to the front end, in search, making multiple flag recipes (to show to searchers), with views?

My first question is, do I have to make a view for every single flag I have on the front end? There are over 20 of them, I don't mind doing this but can't this be put in to an exposed view or something so I can have one view with all outputs covered?

How can I mix up certain flags together/make recipes so that if I wanted three certain flags together so that people can search through that output I could, can I do this in views with flags?

My final question is, how do I put the output of a search or a view I make and make it sortable by how many times that node has been flagged with that flag or combination of different flags? If someone wants to see the nodes all flagged with 'river' and that the nodes that come to the top of the search/output/view has had it's 'river' flag flagged by more users than those below it. This will show that that node is definately more 'river' than the other ones.

I found out that if I add all of the flags (each one individually) as a relationship, so I end up with 20+ relationships, I can expose each one in a field to visitors and that way they can click through what type of flags they want to see and don't.

It's not pretty, you will end up with 20+ true/false select boxes but its working.


Why is Views Nivo Slideshow block only displaying to logged in users? I'm using the Views Nivo Slider module to create a slideshow for a couple of different sites I'm creating. The slideshow works perfectly if a user is logged in, but the block doesn't display at all when not logged in (the HTML for the block isn't even there). I thought it might be a permissions issue, so I tried giving anonymous users every permission possible, and still no luck. Any idea what might be causing this? Could it be something in my view?

I have some problems with blocks before and I always check the following, it has solved my problems so far.

Check your block permission.
Verify the block is assigned to a valid region setting in your template.
Rebuild the node permissions in admin/reports/status. Before doing this, backup your database and clear the cache.
Verify the access permission used from the view is view published content.

When I am working with views, I make sure the theme developer module is not enabled. I disable it, and then I clear the cache.


How do I add a password field on registration form? I have a basic website, with nothing installed on it yet. My first task is to get my users to be able to register with a password. I see that certain "modules" will allow you to do this, but is a module really necessary to be able to register with a set password?

I'm using Drupal 7.

Go to Account Settings (admin/config/people/accounts) and uncheck the Require e-mail verification when a visitor creates an account checkbox.

  With this setting disabled, users will be logged in immediately upon
  registering, and may select their own passwords during registration.

If you want both (Password field + email verification), use the User registration password module


Is there an easy way to move non-English selected nodes into a language section? I have a site in English but it also has a few nodes in Arabic, a few in Aramaic, a few in Hebrew, etc.

Is there an easy comfortable UI way to move each group of nodes for a language section? To better explain, here is how the URL should look in relation to each section:

  www.example.com/ar0/This-is-a-node-in-arabic0

  www.example.com/ar1/This-is-a-node-in-aramaic0

  www.example.com/he/This-is-a-node-in-hebrew0

Let me just clarify, I am not talking about a sub-site, All nodes are exactly on the same English-native site.

it is important for me for any case to have a solution that doesn't include Views at all since these are simple nodes.

From your comments I understand that you want to display URLs based on languages.You can achieve that by simply  editing each node and edit URL alias (under URL path settings) for each node.

If you have bunch of nodes and want to change the all URL aliases at once, follow the steps

1) Install and Enable Pathauto and Views Bulk Operations (VBO) modules.

2) Define Path alias patterns in URL alias settings (admin/config/search/path/patterns)

3) Create a view with Views Bulk Operation field and select "Update node alias" option.

From the View output you can generate Auto paths for selected nodes in one click action.


Inserting PDF files via the Image icon in ckeditor. Is there a better way? I would like to insert inline files throughout the text editor, without having to attach them all at the bottom of the page. I figured out that I can upload them via the image icon, remove the blank image, and then insert the link by browsing to the file I just uploaded. But surely there is a better way?

Can anyone share?

The canonical "Drupal way" is to keep files in file fields. You are free not to display them in your theme for readers and only keep links in body. Having them explicitly linked to a node has some advantages: you can keep track if files are used or should be deleted, you can display them in views, in search you can possibly add "with attachment" option and so on.

You can write a CKEditor plugin - copy image uploading one, change output from <img src=" to <a href=" and you have what you wanted. It's what you want, but be careful, you might regret it in the future if you'll ever need that node-file relation.


ubercart checkout review button position I use drupal 6 and ubercart 2.

I would like to change position of the checkout button on checkout/review page to the top or possibly to duplicate it (it is currently on the bottom of the page which is not very user friendly)
I found a function in uc_cart.pages.inc called

function theme_uc_cart_checkout_review($panes, $form)

Inside on the bottom I found the code for review button

$output .= '
'. $form
        .'

';

However, moving the code above the table code, breaks whole page. (I tried this inside the .inc file, because adding the function inside template file, I got an error) What would be the correct way of achieving my task? Thank you

your better off targeting the checkout button via CSS than mess with ubercarts tables on checkout as the $form contains all of the other code which you would need to parse to extract the button and apply it somewhere else.

Just do a position: absolute on the button.

If your CSS isn't up to par, then I would parse the $form variable and preg_replace() it out. You'll need to have good regex skills to grab it.


Can panelizer automatically switch layouts based on a condition? For a new project I'm starting, Panels+Panelizer seems a very good fit, but I'm still figuring out how to do some advanced things with it.

I like the fact that you can define the default layout and content panes for a certain node type, and allow the editor to override the default panes per node.

In some cases I want the layout and content panes to be dependent on certain conditions. For instance, if the date field on a node is not empty, I want a calendar pane in the right column; otherwise I want a 'related news' pane.

I have read about visibility rules, but the options seem rather limited (eg. there is no "not empty" condition for fields) and it does not allow you to change the layout completely. Which other methods exist make the default layout and content panes depend on certain conditions (other than the node type)?

Visibility rules are the way to go.

Granted the built in ones are not always as sophisticated as one might like at times, but on the other hand, access plugins are among the easiest to do on your own, allowing you arbitrary conditions.

See What are Ctools plugin (content type, access, etc), and how does one create them? for a example of how to implement one.

It can also be worthwhile checking the Ctools issue queue for a plugin that matches your requirements. Development of Ctools has almost gone away with all the active contributors working on D8 instead, but I have found useful patches in the queue.


How to place content/user field value inside of a rules action? I'm trying to grab the contents of a field in my node of custom Content Type 'Messages'. The field is called 'targetuser'. I successfully grab the content of this field, and place it inside a field on my User profile called 'last_user_messaged' with the rule 'set a data value'. Hooray...

I then fetch the entity type User (see second action), and the field/property last_user_messaged (site:current-user:field-last-user-messaged), which in theory, should now return the data I'd set there with my first action.

That said, when I try and set my third action 'Send a push notification to a user account' with the data selector [last-messaged:1], upon execution, my logs tell me that it's empty. Technically, shouldn't last-messaged:0  return the first value inside field last_user_messaged? And last-messaged:1 return the second value? Or am I reading this wrong?

In short: I want my push notification to send to the integer (a uid) that is placed in last_user_messaged field.

I hope this makes sense.

Have a look at issue # 430274, which somehow explains that "after saving something" actually happens ... "before saving something" (which is not a bug, simply how the Rules module works ...).
From the limited details provided in the question, it could well be that this also explains what causes your issue.

A possible compromise to avoid these kind of issues, is to transform relevant parts of what you're trying to do in your Rules Action(s) in a Rules Component, so that your Rule "schedules the execution" (using the Rules Scheduler submodule) of that Rules Component. For example after only a few seconds or minutes later on (if your cron job runs frequent enough, otherwise it'll be next time cron runs). This compromise will ensure that, at the time the Rules Component is executed, the "Save of the entity" for sure completed, and updates will have been applied as expected.

PS: as an alternative, add an extra "save entity", after your first Rules Action (possibly that might be sufficent also).


What is the 'Drupal way' to create a menu callback and display a rendered page of JSON? I have created a new menu item and a callback function.

  ...
  $items['user/%user/enquiries'] = array(
    'title' => t('Enquiries'),
    'page callback' => '_client_enquiries',
    'access callback' => 'user_access',
    'access arguments' => array('view enquiries'),
    'type' => MENU_LOCAL_TASK,
    'weight' => 1
  );
 ...
 function _client_enquiries() {
   return t('Enquiries');
 }

I am now going to CURL some json from a published google spreadsheet, and cherrypick, and then print some of it out in a table. My question.. what is the drupal way to do this? I think it would be to create a custom theme function which makes my processed json data available to a template, which I can somehow load onto my menu callback and output. If that is the case, could anyone give me some pointers/examples or a point in the right direction.

Much simpler:

function _client_enquiries() {

  $var_to_output = caculate_value_to_return();

  drupal_json_output($var_to_output);
  drupal_exit();
}


What are the most appropriate users and permission levels for Drupal sites on shared hosting? Although the Drupal site goes into great detail about permissions and security, there are only vague/unclear references to shared hosting. From a Drupal point of view, what is the most secure set-up (ownership and permission levels) for a site on shared hosting?

As an example of the kind of info I'm looking for, WordPress suggests the following shared hosting settings:

All files should be owned by the actual user's account, not the user account used for the httpd process.
Group ownership is irrelevant, unless there's specific group requirements for the web-server process permissions checking. This is not usually the case.
All directories should be 755 or 750.
All files should be 644 or 640. Exception: wp-config.php should be 600 to prevent other users on the server from reading it.
No directories should ever be given 777, even upload directories. Since the php process is running as the owner of the files, it gets the owners permissions and can write to even a 755 directory.

Hosting options

Hosting options for a website site is generally one of the following:

dedicated server
virtual private server (VPS)
shared hosting

With a dedicated server, only one site is hosted on a physical computer, and the configuration is as secure as the computer itself.

With a VPS, your software runs on the same physical computer as other users' virtual machines. However, it is functionally equivalent to a dedicated server. Most important, a VPS has the privacy and security of a dedicated server.

With shared hosting, your web site resides on a file system shared with other users.  This, unfortunately, makes it less secure than when it is running on a dedicated server or VPS.  The rest of this article discusses the security of a WCMS in shared hosting environment.

Environment

A shared hosting environment can be regarded as consisting of a web server, a file system, a settings file, a database, and some users.

In the following examples, it is assumed that the owner account is "tom", and that the settings file (holding database credentials) is named "settings.php".

The web server process may run with the user permissions of the owner account "tom", or with group permissions of the group "www", depending upon the configuration.

Also, a standard Gnu/Linux or Unix environment is assumed, and it is assumed that the reader understands the Unix access control system with separate read (r), write (w) and execute/access directory (x) permissions split into three blocks (user, group, other).

Before I go on to discuss specific settings, it may be helpful to list the conditions we want to satisfy:

For a web-site to be operational, the web server must have read access to all the files that make up the site, and access  directory access to all the directories that make up the site.
For secure operation, web server must not have write access to any of the files it handles.
For secure operation, a web script run by a rogue user must not have read access to the files owned by another user.
For the owner to work on his own site using the CLI, the user must have read and write access to his own files.
To protect the files from being accessed by other users using the CLI, the "other" block should have no permissions set.

Unfortunately, on a shared host, you can only have 4 out of 5.  I know of no way you can  satisfy all five conditions on a shared host.

As far as I know, two different configurations are used by shared host providers.  Both are discussed below, along with the permissions to use to best protect files and directories, and what condition the configuration fails to satisfy.

Config 1: Web server is running as owner

This is AFAIK the most widely used configuration.  The web server is running as owner of the files.  This means that a rogue user cannot use his web server user to run a script to read another user's files.  This type of configuration also protects users from each other in the CLI.

However, it also means that we can't have separate permissions for the owner and the web server. To satisfy condition 2 with this type of setup, you need to restrict write permissions for the owner in order to prevent write access for the web server to everything except the upload directory.

Permissions:

Directories:  500 r-x --- --- tom.tom
Files:        400 r-- --- --- tom.tom
settings.php: 400 r-- --- --- tom.tom
Upload Dir.:  700 rwx --- --- tom.tom

Unfortunately, this means that condition 4 cannot be satisfied.  I.e. the site cannot be maintained through the CLI. The owner will be constrained to use some sort of web-based dashboard to access the site (my recommendation is that the owner maintains a copy on some staging server where he has unrestricted access, and mirror changes made on the staging server to the shared host).

Config 2: Web server is running as a member of the www group

This configuration is used by some (IMHO) less professional providers of a shared host solution.  The web server is running as a member of the www group, and is given the required read access through the group block:

Permissions:

Directories:  750 rwx r-x --- tom.www
Files:        640 rw- r-- --- tom.www
settings.php: 640 rw- r-- --- tom.www
Upload Dir.:  770 rwx rwx --- tom.www

These settings have the advantage of giving the owner full access to his files through the CLI, and restricts the web server to read access only.

However, it also fails to satisfy condition 3.  I.e. it allows a rogue user on the shared host (or a hacker that as compromised the site of another user sharing the host) to run a script to read any file that can be read by the web server.  This gives the rogue script access to the file settings.php with the database credentials, which makes it trivial to completely take over the site.

My recommendation is to avoid this type of configuration.

Addendum: How dangerous is it to use a shared host?

I certainly would not put anything sensitive, such as credit card numbers or medical records, on a shared host.  But shared hosting is cheap, and there is an attraction in that.  I use shared hosting myself for several of my sites.  I haven't been hacked yet, but I know that the risk exists and I am prepared for the day when it happens.  If I am hacked, I will simply delete everything on the shared host, and reinstall the site from a mirror copy I keep on a secure staging server.

With "config 2", the main problem is the others.  If some other website that you share the host with gets compromised, your website is also lunch.  Making security depend upon another party you don't know and have no control over is not a good idea.  This is why my recommendation is to avoid "config 2"-type hosting arrangements.

With "config 1", you alone control your web site's security. This is better (in particular if you know what you're doing).  But it is not fool-proof.  Nobody's perfect, and  if you goof up and your site is compromised, the attacker will have access to every file stored on that host that belongs to you.  In other words, to minimize the damange when you're hacked, do not keep anything on that host that will cause harm if someone else gains access to it.  In particular, do not keep your email on that shared host.  There is usually tons of sensitive data in email, so you do not want it anywhere near a web server executing as "you".

And if your web applicaton is handling sensitive data, make sure your budget allows for a dedicated host or a VPS.

You may also want to see this guide to Securing file permissions and ownership at Drupal.org.