How to alternate image on left/right using "Views Parity Row" module This great tutorial explains everything except the CSS work.
http://gogrow.org/tutorials/views_parity_row

I need to add CSS class to each row so I can set left/right alignment accordingly in css style.
Views settings allows me to set the ccs class in Page: Style options but this one is always the same for each row. I need the class name also to alternate.

I need something like dynamically use the View Mode as css class name.

Current output:

Desired output:
 and

Or am I missing something and the CSS work is done in a complete different way?

You can just set all view-rows to be left and then do like this in your css:

.views-row:nth-child(2) {
   float: right;
}

UPDATE:

.views-row:nth-child(odd) {
  float: left;
}
 .views-row:nth-child(even) {
  float: right;
}

As @No Sssweat pointed out you can use nth-child odd and even to style every second element. You don’t need to style on the parent just use above code.

I actually wrote something wrong you can add nth-child on the .views-row elements


How to create a view using the References module? I currently have Two content types:

Content Type 1: Videos

Content Type 2: Politicians

The main Videos content type references the Politicians content type as a way of "tagging" Politicians that can be seen in the videos.  What I'd like to do on each Video node is create a view that shows all other video nodes that have the same Politicians referenced within them.  For some reason I cant seem to get it to work.  This is what I have so far.

Create a view block with title field from the Video id like to
see
Create a relation to the Politicians field with a reverse
Create a filter based on Content NID

For some reason when i go to a Video node I don't see any results at all. In fact I don't even see the video of the node I'm currently on.

If I change the relation to Politicians field without the reverse I only see the same node that I'm currently on.  I should be seeing all videos with the same politician.  What am I doing wrong here?

Keep in mind I and not using and wont be switching to the Entity Reference module since this is a large legacy project (I'm using the References module).

You could achieve your goal by building two views

The first is the view you have build with relationship to politicians content type, Add new field gets the politician id tagged in that video

The second is a view that gets videos for politicians ids sent as a contextual filter

  that accepts multiple values by checking that checkbox as in the picture

Install  that module views field view that enables you to embed a view inside another view as a field

Add new field in the first view that embed the second view and send the politicians ids as tokens to that view

Now you could achieve your goal


Drupal 8 convert json to Array I´m getting data from web service in Drupal 8:

$uri = "http://localhost:8888/drupal8/tipo_receta.json";
 try {
    $response = \Drupal::httpClient()->get($uri, array('headers' => array('Accept' => 'application/json')));
    $data = (string) $response->getBody();
    if (empty($data)) {
      return FALSE;
    }else{
        print $data;
    }
  }
  catch (RequestException $e) {
      return FALSE;
  }

I have this JSON source:

{
    "document_type ": "receta",
    "recipe_doc_id ": 1,
    "recipe_title": "Título de la receta",
    "recipe_description": "Descripción con todos los pasos de una receta",
    "recipe_ingredients": [
        {
            "ingredient_doc_id": 33,
            "ingredient_doc_hid": "ing_pera",
            "ingredient_name": "pera",
            "ingredient_value": "2 peras"
        },
        {
            "ingredient_doc_id": 54,
            "ingredient_doc_hid": "ing_manzana",
            "ingredient_name": "manzana",
            "ingredient_value": "300 grs. De Manzana"
        }
    ]
}

This is my result on the page:

C:\wamp64\www\drupal8\core\themes\bartik\bartik.theme:142:string '{
    "document_type ": "receta",
    "recipe_doc_id ": 1,
    "recipe_title": "Título de la receta",
    "recipe_description": "Descripción con todos los pasos de una receta",
    "recipe_ingredients": [
        {
            "ingredient_doc_id": 33,
            "ingredient_doc_hid": "ing_pera",
            "ingredient_name": "pera",
            "ingredient_value": "2 peras"
        },
        {
            "ingredient_doc_id": 54,
            "ingredient_doc_hid": "ing_manzana",
         '...

How can i get an array so i could filter the data like this?

if($data['recipe_doc_id'] == "1"){
print $data['recipe_title'];
}

Use the Json::decode() method:

use Drupal\Component\Serialization\Json;

...

$decoded = Json::decode($data);


Why the main theme isn't applied in the preview? When I’m in administration mode, using the 'seven' theme, and I click on Preview, instead of using the main theme, the preview uses seven's stylesheets, which is silly-willy because it’s not what I would expect from a preview.

There are lots of reasons why the main theme isn't applied. I think this comment by merlinofchaos sums up some of the larger hurdles well:

Right now, in Drupal, we store temporary data in a cache by caching the generated form. In order to preview, we have to process that form and reassemble data. This is fine when you click preview, but in a system like this, you're actually visiting a different URL from the form.
Logically, we could put the form build id in the URL and load the form and process it, but there are several weaknesses with that:

It is wasteful (processing a form that was not submitted)
Form build IDs are sha generated strings. There is no way to reproduce it if you don't have it. This means you can't do content locking.
It continues the trend on Drupal of the form owning the data when the form typically should only be a representation of the data.

Read More »
Lot's of contrib modules have attempted to address these issues:

Site Preview System
Page Preview

That said, "Allow to preview content in an actual live environment" recently made it into Drupal 8 Core
But don't get too excited. "Allow content creators to preview exactly how content will appear on the site after it's saved" is still very much a work in progress. And recent comments indicate it will be a Drupal 9, not 8 issue.


Displaying a product price on Ad Push content? Hi just started using Drupal a couple of days ago.
I'm using Commerce Kickstart 2. I'm having troubles displaying the product price on the Ad Push content. I just want to know if there is a way to display the product price on the Ad Push?

Thank you very much.

You would need to add a new Product Reference field to the Ad Push content type. This allows content editors to pick a product to reference. You can then display the price through the "manage display" tab of the Ad Push form. You'll want the "Product: Price" field.


How can I destroy or unset session? I create module with many sessions . I want unset all session after module work . When I use session_destroy(); end of my module code , I have error and after that my sessions seem delete (session_unset(); not worked) . but after 4 or 5 time refresh page all sessions show to me .

Error:

Warning: session_destroy(): Trying to destroy uninitialized session in Drupal\...

How can I fix this problem in my drupal 8 ?

Don't use low level session_destroy(), use the session manager instead:

\Drupal::service('session_manager')->destroy();

This will remove all session data and the user is logged out, if that's what you want. You still get a warning if there is no session, so you might want to check this first.

A better solution might be to use the symfony Session object

$request = \Drupal::request();
$request->getSession()->clear();

if you have set the session data in the request object or

$_SESSION = [];

if you have used the deprecated $_SESSION superglobal.

Normally you don't destroy the session or clear all session data, because there might be other modules that also use session data. Simply remove session variables in the same place where you have set them.

$request = \Drupal::request();
$session = $request->getSession();
$session->set('mymodule.value', $value);

// remove later when you don't need the value anymore
$session->remove('mymodule.value');

When all modules removed their values the session is destroyed by Drupal automatically (for anonymous users).


How to tell if the current language is written RTL or LTR I'm looking for the function – if that exists – for asking Drupal about the current language direction (RTL/LTR).

I check the global language variable but it doesn't contain that information.

After looking more closely into $GLOBALS['language'] I found it actually has the language direction, so the answer is:

global $language;
if($language->direction == 1)
    echo 'RTL';
else /* $language->direction == 0 */
    echo 'LTR';

Better yet — thank you MPD, I can use the Drupal constants LANGUAGE_LTR and LANGUAGE_RTL instead of 0 and 1 respectively, just like this:

global $language;
if($language->direction == LANGUAGE_RTL)
    echo 'RTL';
else /* $language->direction == LANGUAGE_LTR */
    echo 'LTR';

For reference this is what $GLOBALS['language'] looks like:

stdClass Object
(
    [language] => ar
    [name] => Arabic
    [native] => 'Arabic' [it was in arabic letters but SE refused it]
    [direction] => 1
    [enabled] => 1
    [plurals] => 0
    [formula] =>
    [domain] =>
    [prefix] => ar
    [weight] => 0
    [javascript] =>
    [provider] => language-default
)


Filtering link associated with view based on permissions I have a view, print a list of meetings. Using the 'custom text' option I added a link related to the meeting - 'clone meeting'. If the person has a particular permission for the meeting then I would like display the link, but only then.

I don't want to filter the whole record, so can't see a way using hook_views_pre_render(). I could regex the rendered content in hook_views_post_render(), but this seems error prone. How should the conditional link be added?

Drupal 7. Views 7.x-3.5.

Resolved by:

Installing views php
Creating a static class with the permission logic in it.
Editing the view to have Global:PHP as a field.

The class is autoloaded via module.info file. files[] = 'MyClass.inc'. Static function is just a facade to the module function so that it will be in scope.

class MeetingClonePerms {
  public static function accessCloning($nid) {
    // Calls module function here.

The php in Global:PHP views field is in 'output code':

<?php
if (MeetingClonePerms::accessCloning($row->nid)) {
  print  'nid . '">clone';
}
?>


Adding View to Content Type already existing to combine fields I have a content type that is loaded with 1000's of records. These are not shown through any custom view as of right now. I have multiple fields I would like to combine into a single field.

For example:

field_one, field_two, field_three

...combine above into single field:

field_combined

I don't need to do any calculations, I would just like to combine them into one field when the content type page is displayed.

To do what you want, one way is to create a new view, something like this should work I think:

Create a new view of the content type you wish to include
Set display format to Table
Add the fields you want combined to the Fields section
Arrange them in the order in which you want them displayed
Under format: Table | Settings, choose which column you want ALL of these fields to appear in and select that for each

This should present a new view with all of those fields in one column, and any other data as you see fit in other columns. You may need to adjust some styling to get them to format properly - for example, text is inline, so to have it appear on a separate line, you will need to wrap it a DIV or something like.


Show also content on users view I have a Drupal View that was created to show users which are members of the site, this works fine but now the client wants to see not only users on the same view, but also content of type "X", but when I try to add the Filter Criteria for Content type = X , that Filter is not available (don't know why I can't see it), I don't know if this is related to the fact that this was a view created to show Users and not Content from the very beginning.

My question is, what would be the way (hopefully the easiest) to show not only users but also content of Type "X" on my view ? I don't need any logic between the user and the content, is just show on the view results Users and Content of type "X".

Thanks in advance.

What about just creating two different views, one for users and another one for content? If there is no relationship between users and content, this might be the easiest solution.

You can create two different blocks and then display them together in your page (using Blocks, Context, Panels or whatever method you prefer).

Hope it helps,


How to use hook_user_login and hook_user_logout to output content to the page I came across this post: execute a php code after a user login and I implemented the accepted solution. In my implementation, however, I'm trying to output content to the page. This simply doesn't show up. My module name is "alert", and here's the code:

alert.module

<?php

function alert_user_login(&$edit, $account) {
  for ($i=0; $i < 1000; $i++) {
    echo 'hi<br>';
  }
}

alert.install

<?php

function alert_install() {
  // Set the module weight so it can override other modules.
  db_query("UPDATE {system} SET weight = 99 WHERE name = 'alert'");
}

function alert_uninstall() {
  // Remove the module from the system table
  db_query("DELETE FROM {system} WHERE name = 'alert'");
}

alert.info

; $Id$
name = Alert
description = Present dialogs or perform redirects based on certain events
core = 7.x

I'm implementing this in my theme's template.php file. Should this work?

It will not work in template.php
You need to add this in a module file, check here on howto
instead of myTheme it will be modulename
If module name is foo then it will be foo_user_login

    // @file : foo.module
    function foo_user_login(&$edit, $account) {
      fluenz_user_function($account->uid);
    }
    // and this function name was also different just an FYI
    function fluenz_user_function($uid) {
      for ($i=0; $i < 1000; $i++) {
        echo 'hi<br>';
      }
    }


Display children of taxonomy term in parent taxonomy page i would like to print the children of taxonomy term in its parent taxonomy page.
For example there is a news portal and under Sports taxonomy term page i would like to print the children of Sports term:
SPORTS
football #basketball #tennis ...
and then the latest nodes...
How can i achieve this?

Create a view of taxonomy terms
Create a block display for the view
Add a contextual filter for vocabulary ID
Make the block show up on all vocabulary pages in the block settings.


Where are my breadcrumbs coming from? I at one stage had the Menu breadcrumbs module, then the Custom breadcrumbs module enabled. I have now disabled both of them, but the breadcrumbs are still displaying. Only the Home breadcrumb is displayed on every page, and on the search results page "Home > Search > Content" is displayed.

Where are my breadcrumbs coming from since I disabled both modules?

Search results page

You are here

Home ›

Search ›

Content ›

Every other page

You are here

Home ›

Typically the option to disable these are located under your theme settings (/admin/appearance/settings/THEMENAME). If your theme doesn't provide the option to disable these, you can always resort to http://drupal.org/project/disable_breadcrumbs


How to handle exceptions in a batch process I have some special configured content entities in my system which are protected in a pre-delete hook against entity deletion.
There is also a batch process (VBO - entity delete) where they can be selected before hand.

I want to handle gracefully the exception in a batch process which wasn't written by me (and cannot be touched). I tried to subscribe to the exception event and look for xmlHttpRequest which was all fine, but then I dunno what response to set back to stop the process, or log the exception within the batch process with the proper message. What I always get back is this, where the error message is what I put into the AjaxResponse body:

Any help appreciated find a more sophisticated solution to redirect from the batch processing in case of an exception.

So in the end I took and overrode the plugin provided by the VBO.
This will put the exception message into the summary displayed with a drupal_set_message at the end of the batch process (VBO 3.0.0-alpha2).

namespace Drupal\my_module\Plugin\Action;

use Drupal\views_bulk_operations\Plugin\Action\EntityDeleteAction;

/**
 * Delete entity action with default confirmation form.
 *
 * @Action(
 *   id = "my_module_delete_entity",
 *   label = @Translation("MyModule Delete selected entities"),
 *   type = "",
 *   confirm = TRUE,
 * )
 */
class MyModuleEntityDeleteAction extends EntityDeleteAction {

  public function execute($entity = NULL) {
    try {
      $entity->delete();
      return $this->t('Delete entities');
    }
    catch (\Exception $e) {
      return $e->getMessage();
    }
  }

}


Instantiating Fields: via UI, API or Drush? Are there any benefits of using one method of instantiating over another?

From what I'm guessing, creating field instances via the API (programatically) has benefits over the UI since you get to version control the changes.

Drush commands can be put into a script as well and then version controlled.

Are there any other pros/cons to doing things programatically versus the UI?

You can use Features to export your UI-created field configurations and version control the result. It's much faster to create and modify field instances in the UI unless you're extremely familiar with the Field API. I used to create fields programmatically but I feel like my time would have been better spent using the UI and occasionally exporting with Features for VCS/simpletesting.


How do I use block_view_alter for the template file? I want to alter a view block. I used hook_block_view_alter(), but this is not working in a template theme Drupal 8.

How do I use hook_block_view_alter() in template theme?

I think from the *.theme file you should use hook_preprocess_HOOK


Access control based on session Currently I am making a website for restaurants. In the site, each restaurant is a node type and a menu item is another node type. The relationship between restaurant and menu items is one to many.

What I am doing is that after user creates and saves a restaurant node, the user session will keep the newly-created restaurant node id, based on that id, user can create multiple menu items for this restaurant.

What I want to make is that only when there is a restaurant id in user's session can user go to menu item add page, otherwise they cannot do that.

So how can I add this menu-item-add-page access control based on user's session?

Cheers!

I might suggest using Rules, Node Limit and Field Permissions for this... something like:

limit the user to creating one node (restaurant) type
create a field for the user, alter its access using Field Permissions, so they can't see or change it
use Rules on the event of new content created (restaurant), assign that user Field the node id of the newly created node
using Rules again, assign the appropriate field in any further node creation (menu item) using the user field value (which now contains the node id of the restaurant)
using Rules again, check url for /node/[menu-item]/add and see if that user has a user field containing a node id - if no id, redirect to a message screen saying they have to create a restaurant first

In this way, you limit each user to one restaurant, assign a permanent value to that user for the restaurant they create, and make some checks to ensure they have an assigned node id before they are able to create a menu item.

Rules:

  The Rules module allows site administrators to define conditionally
  executed actions based on occurring events (known as reactive or ECA
  rules). It's a replacement with more features for the trigger module
  in core and the successor of the Drupal 5 workflow-ng module

Node LImit:

  The Node Limit module allows administrators to restrict the number of
  nodes of a specific type that roles or users may create. For example,
  if a site has an "Advertiser" role that can create "advertisement"
  nodes, then the node limit administrator can restrict all users in
  that role to a specific number of nodes. He may also restrict users on
  a per-user basis.

Field Permissions

  The Field Permissions module allows site administrators to set
  field-level permissions to edit, view and create fields on any entity.


replace template with other when conditions are met I want to add a record do theme_hook_suggestions variable but only when specific conditions are met, especially when system is going to use a specific template in theme. In effect I want to replace one template with other.

I.e. - when user sees node with id = 50 and view mode == teaser and user has set some specific parameters system should use template node-special.tpl.php. In any other condition system should use base template node-50.tpl.php

I cannot do this, as far as I understand, in any *preprocess or *process functions basing on variables because there is no information available about what template are candidate for use.

How can I achieve this?

EDIT, more detailed explanation:

I'm trying to build a A/B testing system for e-commerce site I run.
I want to set a A/B test where for selected base template a new variant will be defined and for chosen group of users this new variant will be used. I want to have a universal solution where I could configure this just by one line of code. It should work both for nodes, fields, blocks, pages templates. I just simply need to substitute one template field with another.

ie I want to have a universal config:

$ABconfig = array(
        'ABbigrelated' => array( //test name
                'basetemplate' => 'related-nodes', //base template
                'newtemplate' => 'related-nodes-bigimages', //new template
                'GAdimensions'  =>  'dimension2' //config for googleanalitics

        )
);

You can alter the list of template suggestions in your preprocess hook:

function drop_preprocess(&$variables) {
  $variant = drop_get_variant_for_current_user($variables);
  if ($variant) {
    $suggestions = array();
    foreach ($variables['theme_hook_suggestions'] as $suggestion) {
      $suggestions[] = $suggestion
      $suggestions[] = $suggestion . '--' . $variant;
    }
    $variables['theme_hook_suggestions'] = $suggestions;
  }
}

This will add templates variants for all theme hook. So for instance, this allow you to override the node.tpl.php and page.tpl.php templates with node--special.tpl.php and page--special.tpl.php ones (when drop_get_variant_for_current_user() returns 'special'. If the template for a variant does not exists, it will simply be ignored.

Note that the order of suggestions is preserved. If you have three specialized node templates: node.tpl.php, node--special.tpl.php and node-article.tpl.php (the default one, the 'special' variant and the template for article nodes), when rendering an article node, the 'node-article.tpl.php' will be used since 'node_article' will be after both 'node' and 'node__special' in $variables['theme_hook_suggestions'].

Because it will run for all templates used on the page, the use a static cache in get_variant_for_current_user() so the actual variant won't be computed again and again for the same request/template.

Update:

The exact used template with be the last one in $variables['theme_hook_suggestions'] for which a template file exits. For instance if $variables['theme_hook_suggestions'] == array('node', 'node--special', 'node-article', 'node-article--special'), but only the node.tpl.php, node-article.tpl.php and node--special.tpl.php files exist, then node--special.tpl.php will be used.
The drop_get_variant_template() function is the one where you put your variant selection logic (and that has to be written).


Language detection URL domain on localhost I built a website in German on al local drupal installation. Now, I try to add English as a second language. As language detection method I am using URL. Using the path prefix option everything works well but when I try to use the domain option it doesn't work.

The domain option is what I want to use when the website is finally online.

mywebsite is in German and en.mywebsite is in English.

On my localhost I access my site with localhost/drupal722. I tried to configure the English URL as localhost/en.drupal722 but this does not work.

I deleted the path prefixes of both languages. Regarding the German domain configuration I tried both, leaving blank and insert localhost/drupal722/.

Does somebody has an advice on how to get this working?

It is better that you configure a subdomain or even a complete domain. For example, site1.localhost and site2.localhost and that you change your apache or web server to point to the Drupal root folder. Even you can change your OS hosts and link to fake domains, for example, site1.example.com and site2.example.com.

For multi-domain and multi-language I would recommend these modules which work like a charm:

Domain Access
Internationalization

You can add new sites and in each site have one or more different languages. These would solve all your problems as it works very well and it is pretty good in configuring content served from a single installation to several different domains and languages.


Entity inside a Webform? I have a Webform that has an option for a number of tickets. Depending on the number of tickets I need to take information for each ticket, which I was thinking would be the entity?

So if they pick 2 tickets I will need to show the fields some how for the information to then be taken twice.

Any help?

The webform module doesn't really provide such a feature without either using unstable dev version modules (and maybe achieving it) or custom code.

An easier alternative would be to use the Entityform module, which allows you to use any add-on modules that work with Drupal's field API.

This means you could achieve your requirement using something like the Field Collection or Inline Entity Form modules to provide a repeatable group of fields. In that case you can set the field to unlimited values and it will give the user the option to 'Add another item'.

With the Inline Entity Form option, you would have a separate entity for your ticket and you form will have an Entity reference field using the inline entity form widget, which will provide the full form, inline, whenever the user clicks the 'Add another' button.


Get the user ID for a newly created user account I'm trying to import user data from a JSON file. So far I've managed to import user entities with some fields. The next step would be to retrieve the user ID.
The code I wrote is the following one.
$users_json = file_get_contents("../import/users.json");
$users_array = json_decode($users_json, true);

foreach ($users_array as $user) {
  if(!empty($user["roles"])) {
    $values = array(
      'name' => $user["name"],
      'pass' => '',
      'status' => $user["status"],
      'mail' => $user["e_mail"],
      'field_first_name' => $user["first_name"],
      'field_last_name' => $user["last_name"],
      'field_nationality' => $user["nationality"],
      'field_introduction' => $user["introduction"],
      'field_about_me' => $user["about_me"],
      'field_current_job' => $user["current_job"],
      'field_website' => $user["website"],
    );

    $storage = \Drupal::entityTypeManager()->getStorage('user');
    $userEntity = $storage->create($values);
    if ($userEntity->save() == 1) {
      echo "User " . $userEntity->id . " saved!\n\n";
    }
    else {
      echo "User " . $userEntity->id . " updated!\n\n";
    }
  }
}

However, when I try to print the user ID, I get no data.
I've just started to use Drupal API, so I'm not very familiar with it. Is there something I'm doing wrong?

You don't have access to an id property. You need to use the id() method instead, e.g. $userEntity->id(). See the documentation for User.
For example:
echo "User " . $userEntity->id() . " saved!\n\n";


How authenticated users can choose favorite products and show them in their profile? in my drupal project, I want to have many products specification. I want authenticated users can choose their favorite product and they can set price for favorite product. these favorite products can show in their user's profile. and in any product page, all users can see all of the prices that set by authenticated users.

In Drupal 7 which approach / technique should I use?

This really seems like a perfect fit for the Flag module. Excerpt from its project page (bold markup added here):

... Flag is a flexible flagging system that is completely customizable by the administrator. Using this module, the site administrator can provide any number of flags for nodes, comments, users, and any other type of entity. Some possibilities include bookmarks, marking important, friends, or flag as offensive. With extensive views integration, you can create custom lists of popular content or keep tabs on important content.
Flags may be per-user, meaning that each user can mark an item individually, or global, meaning that the item is either marked or it is not marked, and any user who changes that changes it for everyone.
In this way, additional flags (similar to published and sticky) can be put on nodes, or other items, and dealt with by the system however the administration likes.

If you're not familiar with the Flag module, checkout the set of 8 video tutorials about the flag module.
Refer to Flag's Community documentation for (way) more details.
And to show this in their user's profile, could be implemented via an appropriate view (using Views), in the format of a block display, whereas you adapt the block visibility settings to only show such block for an URL that corresponds with the user's profile.


Changing the file of a file field (drupal 7) I have a content type that contains a file field which is always a .zip file.  When a file is uploaded I have a module that unzips the file to make a few changes then re zips the file to a new location.  I would like to associate this newly created .zip file with my content type but so far I have not been able to find a way to do that.  I initially tried to change the url of the file field in which it worked temporarily but it seems that the file field was later re-saved with the initial value.

I do my unzipping and re-zipped from hook_node_presave (I also tried to do from hook_node_insert) but neither seemed to work.  Could anyone offer me any advice about how to change the file of a file field?

File fields are referenced by their ID in the file_managed table; as well as updating the field in your presave hook, you'll probably need to update the file entity that relates to that id with the new filename/path.

This is just a basic example but it should give you a starting point:

// Get the file id from the field
$fid = $node->field_file[$node->language][0]['fid'];

// Load the file
$file = file_load($fid);

// Update the filename
$file->filename = basename($new_path);

// Update the uri (this must be in the format of a schema uri, e.g. public://folder/file.jpg
$file->uri = $new_path;

// Save the changes
file_save($file);

You might also want to update the filesize field; it's used in a few places in the system.


deadlock with cache clear I am trying to clear the cache or view status reports in D7 i get the below error.

PDOException: SQLSTATE[40001]: Serialization failure: 1213 Deadlock found when trying to get lock; try restarting transaction: DELETE FROM {cache_bootstrap} WHERE (cid = :db_condition_placeholder_0) ; Array ( [:db_condition_placeholder_0] => system_list ) in cache_clear_all() (line 167 of /var/web/includes/cache.inc).

How do i fix the serialization error?

Thank you..

The Asynchronous Prefetch Database Query Cache module should handle it. If you want the longer version see How to get rid of Deadlocks and Lock time out type issues?


How to redefine default theme_image() function? By default drupal use theme_image() for render images. How to set for render custum function, ex. theme_cus_image()?

If your purpose is overriding theme_image(), and make Drupal (or third-party modules) use your theme function when calling theme('image'), then you need to implement hook_theme_registry_alter().

function mymodule_theme_registry_alter(&$theme_registry) {
  if (isset($theme_registry['image'])) {
    $theme_registry['image']['function'] = 'theme_cus_image';
  }
}

Implementing that code, when a module uses code similar to the following one, it will call your function, and not theme_image().

$form['enable'] = array(
  '#markup' => theme('image', array('path' => 'misc/watchdog-error.png', 'alt' => $status_short, 'title' => $status_short)),
);

If you need to override theme_image(), and use your code when the image class is a specific one, and theme_image() in the other cases, then you should use code similar to the following one.

function mymodule_theme_registry_alter(&$theme_registry) {
  if (isset($theme_registry['image'])) {
    $theme_registry['image']['function'] = 'theme_cus_image';
  }
}

function theme_cus_image($variables) {
  if (!empty($variables['attributes']['class']) && $variables['attributes']['class'] == 'the class you are looking for') {
    // Add your code.
  }
  else {
    return theme_image($variables);
  }
}

The problem with that code is that it is assuming no other module overridden the same theme function. If another module with a lower weight (or for which its hook_theme_registry_alter() is executed first) overrides theme_image(), the new theme function would not be called from the code I shown, as it explicitly calls theme_image().
It is also not possible to call the original theme function with theme('image') as that would cause an infinite loop: theme('image') would call theme_cus_image(), which would call theme('image'), which would call theme_cus_image(), which would call theme('image'), which would call […].

Keep in mind that, with Drupal 7, preprocess functions are invoked also for theme functions that don't use template files. If you want to replace theme_image() just to alter one of the variables it gets, then you can use code similar to the following one, which unsets the width, and the weight of the image.

function mymodule_preprocess_image(&$variables) {
  foreach (array('width', 'height') as $key) {
    unset($variables[$key]);
    unset($variables['attributes'][$key];
  }
}

Similarly, if you would want to alter the class assigned to the image, you could use the following code.

function mymodule_preprocess_image(&$variables) {
  if (!empty($variables['attributes']['class']) && $variables['attributes']['class'] == 'the class you want to alter') {
    $variables['attributes']['class'] = 'your class';
  }
}

If your purpose is defining a new theme function that is used from your module, then you simply need to implement hook_theme().

function mymodule_theme() {
  return array(
    'cus_image' => array(
      'variables' => array('path' => NULL, 'width' => NULL, 'height' => NULL, 'alt' => '', 'title' => NULL, 'attributes' => array()),
    ),
  );
}

In this case, theme_cus_image() will be used from code that calls theme('cus_image'). The code that calls theme('image') will still be using theme_image().


How to output just the Name and Status in drush listing modules Running drush pm-list gives the modules and theme list through some fields. By default, it gives me the Package, Name, Status and Version.
I am trying to make a shell script that outputs only module and status to be consumed by other scrips, and things will be much easier if the drush pm-list shows only Name and Status.

Is there a way to prints only the information about the Name and Status from the drush pm-list and omits the Package and Version information?

Using Drush 8 or Drush 9:

drush pm-list --fields=Name,Status

If you want to consume the output from another script, you might also want to consider:

drush pm-list --format=json

In that instance, all fields will appear in the output; however, since the output will be in json, it is easy to parse and then use only the fields of interest.


How to decide to create a multilingual site or to create different site for each language? This is the first time I want to create a multilingual website. The site is Turkish now and I want to add English as second language (for both interface and content).

The main site (the Turkish one) has about 15 content types and each content type has 10-20 fields (text, entity reference, date, image etc). Also each content type has its own node.tpl.php and I made lots of customization to display node types. In short, the site is a bit complex.

I made some research about creating multilingual site (in Drupal of course) but I couldn't decide yet to use Drupal's multilingual features or to clone the Turkish site and create another site for English with some (language) modifications.

Creating two separate site is easier for me but using Drupal's multilingual features seems the "correct" way but more painful.

How to decide to create a multilingual site or to create different site for each language?

(More details: - Almost all of the contents in the Turkish site will have its corresponding content in the English site. - There is a team of non technical editors.)

In my personal view, I will consider if the new language site will be mostly identical to the existing one or not.

It means that if most of the pages / contents in the Turkish site will have its corresponding page / content in the English site, then I will build multilingual site, otherwise, I would like to set up a separate one.


How to add a comment using service api when uuid_service module is enabled How to add a comment when UUID and services are enabled
The url which we tried is :

http://localhost/api/comment/uuid_of_new_comment (PUT request)
with json raw data:

{
    "comment": {
        "uuid":"uuid_of_forum ",
        "subject": "testing"
    },
    "uuid":"uuid_of_new_comment ",
    "type":"comment"
}

I know that it is not correct. But was not able to find a proper documentation for this any where. So trying some random things !!!

It will be highly helpful if some one can suggest where to find proper documentation for uuid with services .

First, when creating a comment you must use POST. Here's an example:

POST: ?q=[my_endpoint]/comment.json

{
  "subject":"Testing...",
  "comment_body":{"und":[{"value":"Hello world..."}]},
  "nid":"123"
}

Secondly, from my understanding the uuid will automatically be generated server side, so you should not need to send it up to Drupal. And lastly, you use the PUT http method to update a comment, and in that case you can send along similar JSON, but include the cid value (e.g. 456) and exclude the nid value in the JSON object, and change the URL path to ?q=[my_endpoint]/comment/456.json

{
  "subject":"Updating...",
  "comment_body":{"und":[{"value":"Hello world again..."}]},
  "cid":"456"
}


Creating node with multiple custom blocks, best method What is the best method to create a node that includes multiple custom blocks with content related to only this node? The main concern is having a method that content editors will be able to understand with all the blocks related to this node editable from the node edit page for example. Having multiple custom blocks with each having an edit page is really confusing.

You could try the context module https://drupal.org/project/context. With context you can specify that certain blocks only appear on a path specified so if you only wanted them to appear on the page with the url applepoluza you could do so.

As for being able to edit the blocks from the node edit page, perhaps you could set a context with a path to the edit page of the specific node to display a new custom block and in that custom block put in a list of links to each of the desire custom block edit pages. That would a be a pretty simple way to be able to accessibly access all of the custom blocks edit pages from the node edit page.

To directly edit the blocks on a node edit page would get pretty messy but could probably be done with something like Entity Fields and a bit of hard coding if you REALLY wanted to.


Filling fields with data on fly I have some records imported to my module tables. Some of this data is synchronized to drupal nodes by creating and updating existing nodes of specified type. This operation is made each time new import is done. The problem is, it produces around 60 000 nodes for every new import and it is quite a lot. Synchronization takes hours and operations through Views takes ages or crashes.

Is there any way to store my data only in my tables and serve them from this tables as nodes? Some way to only creates nodes with some properties set as language and title, and then provide data for fields directly from my tables?

If revisions aren't important you might want to fork your website codebase and try installing Field SQL NoRevisions module, by removing the "revisions" of Nodes node creation and fetching takes half the number of normal drupal queries.

Depending on you Read vs Write ratio you also might want to consider moving some of your Fields into a NoSQL database such as MongoDB.


More info for autocomplete choices? When I have an entity reference field with an autocomplete widget, is there a way to add a field to the info that appears in the autocomplete choices? Seems like the default field is Title, but this in my case might be ambiguous.

An easier solution is to modify the 'label callback' property of the node entity.

function mymodule_entity_info_alter(&$entity_info) {
    $entity_info['node']['label callback'] = '_mymodule_label_callback_set';
}

function _mymodule_label_callback_set($entity, $entity_type){
    if($entity_type == 'node' && $entity->type == 'my_node_type'){
        //Compute new label here
       $label = 'test';
       return $label;
    }
}


Show "Log in" link all the time (even for logged in users) I have a menu item "My Shop" which redirects to the user/login page. But custom Drupal behavior hides this link whenever a user is logged in.
I would like to show this menu-item all the time. Is there a way to do so?

The reason why I do this is the following. It's a site with a webshop-portal. To access this portal, users need to log in. Whenever they are on their portal/webshop, he should keep seing the menu-link and when they return to the front-end of the site, the user should be able to go his webshop without loggin in again.
I hope I make myself clear on this one. If I don't, please let me know!

If you're trying to show a link called "My Shop" which takes anonymous users to the log in page and logged-in users somewhere else, you can just create a second menu item also called "My Shop" and set it to display only for users that have the authenticated user role.  Then set the destination to whatever you want; that way both logged in users and anonymous users will have "My Shop" links pointing different places.

You can have multiple menu items on the same menu with the same name (Drupal doesn't check for uniqueness in order to allow for situations like this).

As long as you give the two "My Shop" menu items the same weight (or drag them so that they are next to each other), they will appear to be the same menu item.


How to check in a Rules Condition if a specific value of a multi-value field is selected? I have a "checkboxes" field that allows the user to select unlimited options.
How do I check if at least a specific value has been selected?

I am using the Rules module, and when it checks if the 'field has value' it combines all the options. Right now, if both the values "b" AND "c" are selected, then the action (which checks for the value "b") won't be executed.

I ended up creating a "Check a Truth Value" condition with the Rules module. The code below is the one I used.

if ($node->field_area_51[0]['value']) {
  foreach ($node->field_area_51 as $key => $value) {
    if ($value[value] == 'b') {
      return TRUE;
    }
  }
}


Show 'submitted by' date in a language different from English I want to change the "submitted by" field. I want to show the date in another language. When I use views to display dates, the date shown is in the correct language.

When I add this to node.tpl.php, the date is in English.

echo date("j F Y", $node->created);

What is the correct way in Drupal to show the date like "17 december 1978" when the language set in Drupal is Dutch?

Month names are not added automatically.

An elegant way to do this is described here:

https://drupal.org/comment/8251325#comment-8251325

function monthname_install() {
  $months = array(
    'January',
    'February',
    'March',
    'April',
    'May',
    'June',
    'July',
    'August',
    'September',
    'October',
    'November',
    'December',
  );

  $options['context'] = 'Long month name';

  foreach($months as $m) {
    t($m, array(), $options);
  }

  drupal_set_message(t('Month names have been made available for translation. The rest is up to the translation team :-)'));
}


How can I tell that my hook_nodeapi function is being called by cron and not a user? I am attempting to filter the viewing of node/cck fields attached to the nodes, so I have written a custom hook_nodeapi function and I am editing the field values if the user doesn't have permissions (redacting them). The problem is, that when cron runs and apachesolr attempts to index the same content, cron doesn't have "the permissions" associated and so ends up indexing redacted content.

I need a simple test that returns a boolean if a function is being called by cron. Any ideas? I have started looking through cron code (Drupal 6) and it looks like bootstrap sets up cron with default anonymous user account details...

How is cron being executed?  If done via crontab like

0 1 * * *   /usr/bin/wget -O - -q -t 1 http://my.site.com/cron.php

then I suspect that

function hook_whatever () {
  global $user;

  if (strpos(request_uri(), "/cron.php") === 0 && $user->uid == 0) {
    // from crontab
  } else {
    // from somewhere else
  }
}

would work.

Manually running from one of the admin pages may be trickier, but taking out the $user->uid check may suffice in that case.


Altering widget produces error, "Class name must be a valid object or a string" I'm using hook_field_widget_properties_alter to successfully set the widget type of some fields to 'options_select', but when trying to set others to entityreference_autocomplete, I get the error, "Class name must be a valid object or a string in mysite\includes\common.inc". Here's the code:

/*implementation of hook form alter*/
function mymodule_overrides_field_widget_properties_alter(&$widget, $context){
  // set widget type to options_select for field_expertisetags and og_group_ref
     $widget['module'] = 'entityreference';
     $widget['type'] = 'entityreference_autocomplete_tags';
}

Any thoughts as to the cause?

I discovered that the target field was of a type that required different settings. I solved it by entering this:

$widget['active'] = '1';
$widget['#access'] = '1';
$widget['module'] = 'taxonomy';
$widget['type'] = 'taxonomy_autocomplete';
$widget['settings']['autocomplete_path'] = 'taxonomy/autocomplete';
$widget['settings']['size'] = '60';

I also realized you can go to the content type, select a field type and the underlying html for that dropdown will reveal the field type module value, and the settings under the widget dropdown will reveal the 'type' value you need to use. Hope that helps someone.


How to improve search results filtering on taxonomy I would like to know the best way to filter drupal search results using taxonomy. I want users to be able to search for particular results from a particular taxonomy..this can be done to refine already searched results, or can be done from scratch.

Any module for Drupal 7 that does this well?

Use Custom Search module.

  This module alters the default search box in many ways. If you need to
  have options available like in advanced search, but directly in the
  search box

Or, the other best solution is to use create a view with exposed filters. Here is article about it


user_role_revoke_permissions() for administrator I am using EU Cookie Compliance module.  During module installation, permission has been set to admin also. I need to revoke that permission which is assigned to Admin as cookie pop-up is coming-up for admin also.
In Permissions, it is grayed-out. So I can't able to disable that permission.

When I used below code, it is revoking permission for all other roles but not working for Admin.

user_role_revoke_permissions('administrator', [
      'display eu cookie compliance popup',
    ]);

Please suggest me a solution how to revoke that permission for admin.

Here is the snippet code works for @Saba original author of the post in case someone needs it.

function YourModuleName_eu_cookie_compliance_show_popup_alter(&$show_popup) {
  $current_user = \Drupal::currentUser();
  $roles = $current_user->getRoles();
  if (in_array('administrator', $roles)) {
    $show_popup = FALSE;
  }
}


how to render a welcome page in page--front.tpl.php I have a template page--front.tpl.php. It contains all different stuffs and a welcome message, wrapped in a div container. Since, I want it to be editable, I created a new basic page called 'Welcome message'. It opens in a separate node 'welcome-message'.

Now I want this to be rendered in page--front.tpl.php in given div container. Any suggestions?

Login as admin to the site, visit "admin/config/system/site-information" , scroll down to find setting for for front page and then form "Default front page" set the node relative path to be used as default front page that looks like "welcome-message" in your case.

with the above process you have informed drupal to use the node you have created as front page.

Now remove the hard-coded page front template you have created before as "page--front.tpl.php" because it will be used over the node till its present there.

clear your caches.


how to force  image file and music file  to download with zip format in drupal 6? i have content type to upload music and image files.i want to provide a link to the users to download those music and image files.By using force download module , i can provide the download link for the file ,but now i want to zip the file when user click the download link and so user can download the image or music file in zip format.

i have installed the pclzip module and custom formatter module and i think we can achieve this by creating custom formatter for those cck field,but i dont know how to implement it? or any other module suggestion?  thanks in advance.

I'll answer with a question, do you want to make a zip file because it's an easy way to force browser to download the image or the mp3 instead of showing it ?

If so I'll recommend you the File Force Download module to achieve this. Also you have DownloadFile module and a .htaccess way to do this: Force Files to Download Instead of Showing Up in the Browser but I don't find this one to be very flexible.


How do I turn off account creation? Recently I've been receiving many spammers creating an account on my website, which is quite basic and for which I don't need users create an account.
What would the likely URL that spam bots are finding be?
Is there a way to turn off account?

The answer given on How do I remove the user registration/login form? is relevant for this question too.

While it's technically possible to remove the login functionality, you shouldn't, because then your administrator could never log onto the site.
In order to remove the register functionality, you simply need to browse to admin/user/settings (for Drupal 6) or admin/config/people/accounts (for Drupal 7 and 8) and select the the "Only site administrators can create new user accounts" option.


Customization of Facebook style Statues module I am using Drupal 7 with Facebook-style Statues module.

While writing the status I would like to load the URL when user paste any URL, just like facebook.

Is there any way to customize this module or do i have to build entire new module.

I think you want Facebook-style Micropublisher this allows you to have a image present if the URL your connecting to allows it.


Should I manually upload these large files? I have about 10 large zip files (20Mb) which need to be uploaded to a site once, and once only.  I then want to be able to download them from a block in a sidebar (i.e. not from the main content).

I was thinking that the easiest way to do this would be manually upload them to the site (via ftp), then hardcode links in the blocks to reference the file location.  Does this sound OK?  Does it violate any drupal rules?

The reasons I wanted to do it this way, rather than through the file UI or another module, are that I don't have to worry about the php.ini upload_max_filesize and post_max_size.  Also, I won't have to work out how to use the drupal UI to put a link in a block.

What do you think?

Manually uploading the files and hardcoding the links into a block, Shouldnt be a problem.

You Could also check this module out :) Download File Module


How do I theme a form element? I was able to theme the form. Now I want to put a submission button into a <div>, but I can't theme the submission button.

This code worked for the form.

print "text text text";
print drupal_render_children($variables["form"]);

Here is the code I used to theme the submission button.

$form['submit'] = array(
  '#type' => 'submit',
  '#value' => t('Submit'),
  '#attributes' => array('style' => "padding: 0 10px;"),
  '#theme' => "submit",
);

function scores_theme($existing, $type, $theme, $path) {
  $path = drupal_get_path('module', 'scores');
  return array(
    'submit' => array(
      'render element' => 'submit',
      'template' => 'submit',
      'path' => $path,
    ),
  );
}

What should I put into submit.tpl.php? Any of these doesn't work.

print drupal_render_children($submit);

print drupal_render($variables['submit']);

print drupal_render($submit);

You should be able to wrap form elements with #prefix and #suffix:

$form['submit'] = array(
  '#type' => 'submit',
  '#value' => t('Submit'),
  '#attributes' => array('style' => "padding: 0 10px;"),
  '#theme' => "submit",
  '#prefix' => "
",
  '#suffix' => "
",
);


How can I create two blocks at once from the same custom module? I have figured out how to create a block from a custom module, by creating a ./src/Plugin/Block folder, then creating a PHP script inside it, with the following code:

<?php
namespace Drupal\MY_MODULE_NAME\Plugin\Block;

use Drupal\Core\Access\AccessResult;
use Drupal\Core\Block\BlockBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Session\AccountInterface;

/**
 * Provides a block with a simple text.
 *
 * @Block(
 *   id = "BLOCK_MACHINE_NAME",
 *   admin_label = @Translation("BLOCK_DISPLAY_TITLE"),
 * )
 */
class MyBlock extends BlockBase {
  /**
   * {@inheritdoc}
   */
  public function build() {

    $html = "MY_BLOCK_CONTENTS_HERE";
    return [
      '#markup' => $this->t( $html ),
    ];
  }

  /**
   * {@inheritdoc}
   */
  protected function blockAccess(AccountInterface $account) {
    return AccessResult::allowedIfHasPermission($account, 'access content');
  }

  /**
   * {@inheritdoc}
   */
  public function blockForm($form, FormStateInterface $form_state) {
    $config = $this->getConfiguration();
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function blockSubmit($form, FormStateInterface $form_state) {
    $this->configuration['my_block_settings'] = $form_state->getValue('my_block_settings');
  }
}

My question is, if I want my Custom Module to create a second block, how would I do that?

Do I just create a second script under ./src/Plugin/Block using this same format, and change the BLOCK_MACHINE_NAME and BLOCK_DISPLAY_NAME values?

If I change the line:

class MyBlock extends BlockBase { ... }

to

class MySecondBlock extends BlockBase { ... }

... can I keep all the functions under it the same, eg:

class MySecondBlock extends BlockBase {
    public function build() { ... }
    protected function blockAccess() { ... }
    public function blockForm() { ... }
    public function blockSubmit() { ... }
}

Or is it more complicated than that? Do I need to try and build both Blocks from within the same script, and a single set of functions?

Any advice is greatly appreciated, thanks!

You can a create as many block plugins as you want within a single module. Each of these plugins must have a unique ID in annotation. In order to reduce code duplication you can create an abstract class that would hold all common functionality. Other classes can extend it and override methods that need a different implementation.


Sort by one criteria and have another to fall back on I'm trying to configure a view (using the Views module) that sorts the content by content weight, then by total content views (loading a max of 6 items).

For a quick explanation, this is to list the most popular 'resources' on the resources page (PDFs). I'd like the list to be sorted by total views, which I've already achieved. However, I want to be able to give a weight to specific resources (resource is a content type, I've created a weight field using a simple list(integer) field that goes from -3 to 3) which the 'Popular Resources' view sorts by first before loading by total views.

I've tried giving the view 2 sort criteria, which are:

Content: Most Popular Resources Block Weight (asc)
Content statistics: Total views (desc)

I have 1 resource with a popular resource block weight set (the rest don't have a weight set), but the view isn't showing this resource as it has a lower number of total views than the others being loaded.

If possible I'd like the view to sort by resources that have a weight set, then when it runs out of blocks that have a weight, use total views to load and sort the rest of the resources. I've tried looking for a way to do this but haven't found anything yet.

Any assistance would be greatly appreciated.

Managed to find the issue. The resources that didn't have a weight set were treated as having a lower weight than ones that did. I changed the weighting to sort by descending, which is the opposite of how weight should work, but seems to be the only solution.


How do i create a payment method+gateway with a custom function called by the gateway to determine whether payment is successful? We're looking to use a payment gateway - SecurePay in this case - that allows merchants to save credit card details in their system and then trigger payments against that credit card again for future checkouts by sending a token representing that credit card, without the user re-entering the details, and we don't need to store credit card numbers in our database.

The native handling of credit cards by UberCart, along with the uc_securepayxml module was great for the initial transaction, and storage of credit card number + token with SecurePay but the validation step on the checkout screen meant that it looks like I'll have to set up an alternative payment method + gateway to manage the sending of tokens for payment.

The problem that I'm having is getting Ubercart to fire the function that is supposed to either return success or failure when the order is finally submitted when I don't use the 'credit' payment method.

To be clear, the issue isn't (so far :P) sending the data off to SecurePay, it is convincing UberCart to use the return value of my custom function to determine whether a payment is successful or not, without using the supplied Credit Card module.

Here is all the relevant code (I think) that I'm currently using, so some advice on what needs to change or even just a working example would probably be enough to answer my question!

Using Drupal 6 and UberCart 2, and I cleared the Drupal cache a few times, btw.

<?php
/* This function creates a new payment method */
function uc_securepaytoken_payment_method() {

  $methods[] = array(
    'id' => 'sptoken',
    'name' => t('SecurePay Token'),
    'title' => t('SecurePay Token'),
    'desc' => t('Pay by triggering a tokenised payment through Secure Pay.'),
    'callback' => 'uc_payment_method_sp_token', /* I believe this callback function just sets some strings for display in various places and the validation when submitting on the checkout page, is that right? */
    'weight' => 1,
    'checkout' => TRUE,
  );

return $methods;
}

/*
* This function sets up the payment gateway,
* I believe that if the 'sptoken' key in the $gateways array matches the ID of the payment method,
* the function named in the value should be fired when I want to process a payment
* (NB - This doesn't actually seem to be happening)
*/
function uc_securepaytoken_payment_gateway() {

  $gateways[] = array(
  'id' => 'securepay_token',
  'title' => t('SecurePay Tokens'),
  'description' => t('Process credit card payments using SecurePay Tokens.'),
  'settings' => 'uc_securepaytoken_settings_form',
  'sptoken' => 'uc_securepaytoken_charge',
);

return $gateways;
}

function uc_securepaytoken_charge($order_id, $amount, $data) {

  /*
  * This is the function that I want to use to process a payment
  * and return success or failed, at the moment it doesn't seem to be working
  * and dpm() doesn't display anything, Ubercart simply always completes checkout without doing this
  */

  }

?>

The answer, is that uc_payment_process() needs to be called in hook_order() when the $op variable is 'submit' with the payment method ID as the first argument.

The missing link to bring payment methods, gateways and actual payments together is as follows:

<?php

/**
 * Implements hook_order
 * This is the bit that actually gets the method/gateway-combo into gear
 * when an order is submitted in the checkout process.
 */

  function uc_securepaytoken_order( $op, $arg1, $arg2 ) {

    switch( $op ) {
        case 'submit':

          if($arg1->payment_method == 'sptoken') {

            // Attempt to process the payment
            $pass = uc_payment_process( 'sptoken', $arg1->order_id, $arg1->order_total, $data, TRUE, NULL, FALSE);

            // If the payment failed, store the data back in the session and
            // halt the checkout process.

            if(!$pass) {
            $message = 'We were unable to process this payment. Please verify your details and try again. If the problem persists, contact us to complete your order';
            return array(array('pass' => FALSE, 'message' => $message ));
            }

          }

        break;
    }
}

?>

The next "gotcha" is that the return value from uc_payment_process() is only TRUE if your callback function defined by the gateway returns an array that looks something like this (but with success = TRUE). Check out the uc_credit module for more clues.

<?php
$result = array(
    'success' => FALSE,
    'comment' => 'Invalid transaction type',
    'message' => 'Invalid transaction type',
    'data' => array(
        'module' => 'uc_securepaytoken',
        'transaction_id' => 0,
    ),
    'uid' => $user->uid,
    'log_payment' => 0,
);
?>

For further reading check:

http://api.lullabot.com/uc_payment_process - API Reference
http://www.commerceguys.com/resources/articles/122 - Post explains uc_payment_process() and a few other UC API concepts but no explicit reference to hook_order() unfortunately :(


Using #attached to attach js to form by a custom module My idea:
I am trying to use a module to manage all the js and css with #attached method.
#attached method I found from:
- Adding CSS and JS to form with attachments
- https://www.drupal.org/docs/7/api/javascript-api/managing-javascript-in-drupal-7

My module folder containing:
testing.info
testing.module
js/mask.js

In testing.info, it's including file testing.module
files[] = testing.module

In testing.module, I'm trying to use the #attached method to attach "jquery mask" to all form tags, including add/edit node, webform field. Here is my code but it does not work. -___-

function testing_init() {
  $build['#attached']['js']['https://cdn.testing.com/jquery.mask.min.js'] = array('type' => 'external');
  $form['#attached']['js'][] = drupal_get_path('module', 'testing') . '/js/mask.js';
}

Question:
Am I using the wrong method to attach js to form tag?
I don't want to load these files on all pages, what is the better way?

@NoSssweat is it possible only load for add/edit node and webform(not
  search form)? – CocoSkin

You can by utilizing hook_form_BASE_FORM_ID_alter

For node's add/edit form:

/**
 *  Implements hook_form_BASE_FORM_ID_alter.
 */
function mymodule_form_node_form_alter(&$form, &$form_state, $form_id) {
  $form['#attached']['js'][] = drupal_get_path('module', 'mymodule') . '/js/custom.js';
}

For Webform:

/**
 *  Implements hook_form_BASE_FORM_ID_alter.
 */
function mymodule_form_webform_client_form_alter(&$form, &$form_state, $form_id) {
  $form['#attached']['js'][] = drupal_get_path('module', 'mymodule') . '/js/custom.js';
}


How do I create a grouped exposed filter on a block? I have both a "Galery" content type and a "Galery category" taxonomy. The taxonomy only has two terms, 'Video' and 'Photo' (picture).

When I create a Galery content type, I need to choose the galery category.

I created a view that would display an exposed form, that would allow the user to either pick one of the 2 available categories. A colleague helped me setting up a grouped search and customizing it. Here is how it looks:

However, when testing it, we realized nothing was displayed. Moreover, the <Any> choice does display everything, so I think I've wrongly set something.

If this helps, I'm using "better exposed form" with the "autosubmit" and "use ajax" functions enabled.

What is happening and how should I fix it?

Thank you in advance

In your view, make sure your exposed filter is not the gallery type field itself, but 'Has taxonomy term' filter with the taxonomy group vocabulary selected and then set the exposed grouped filters the same way.


How to create multiple variants of a page in page manager I'm attempting to create multiple pages that use panels within a page in page manager.

For example I'm trying to create the path

127.0.0.1/brands

And have multiple pages that follow that same path like the following

127.0.0.1/brands/brand1
127.0.0.1/brands/brand2
127.0.0.1/brands/brand3

I created multiple variants for each brand in the brands page manager. I had a feeling that I could create the various subpages by using the 'Request Path' selection condition. But I've attempted the following

/brands/brand1
/brand1

and all of these lead to a 'page requested not found' when visiting 127.0.0.1/brands/brand1

Is there a way to create a sub page of a page using page manager, without creating a whole new page?

Create a page with the url /brands and add your variants. Use the "String: URL Path" selection rule to manage each one.

How to:

Under selection rules for the main (panel) page add the "String: URL Path" rule with a single line "/brands"

Do the same with the variants but:
Under the first variant use /brands/brand1
Under the second variant use /brands/brand2
...
...


Updating user profile to update node I currently have a user's profile set up with some extra fields and when that user obtains the role "paid user" an entity is created with a rule and a node that copies those extra fields in the profile is then published.  I'm having an issue however, that whenever I update the user's profile fields, it creates ANOTHER node and leaves the old one.

I'm looking for a solution that will either delete the duplicate node OR will update the current one.

Does anyone have any ideas for this?  I've tried the deduped module someone built for Drupal 7 but it doesn't seem to be working.

EDIT: Here is the second Rule I've created to try to unpublish the older node.

Event: Before saving a user account
Conditions: Entity exists by property(Entity type: Node, Property: Title, Value: [account:field-business-profile])

Data comparison(Parameter: Data to compare:[account:field-bus-name],Data value:[account:field-business-profile:title])

Actions: Unpublish content(Parameter:Content:[account:field-business-profile])

EDIT2: I've updated the second rule to rooby's edits.  The original content remains published though.  I've tried going back and forth between the account-business-profile:nid and account-unchanged-business-profile:nid to no avail.
Here are some pictures I've uploaded of the rule and the two pieces of content:

Moving to an answer so I don't overload your question with comments.

Your second rules doesn't seem to ever load the node you want to unpublish/edit.

You need an action for "Fetch entity by property" (although I would be wary of fetching by title, I prefer the safety of node ID). For this action you can limit it to 1, so it only gets one node (there should only be 1 anyway).

Then that will fetch your node, and then you can do comparisons on that node or unpublish that node (or whatever else you may want).

The problem is though is that at this stage rules only knows it is an entity, it doesn't know what type or anything so you can't actually access its fields or do node actions like unpublish on it.

So (I think this is the only way) you have to install the http://drupal.org/project/rules_conditional module.

Then after your "Fetch entity by property" action you can add a loop and loop over entity-fetched (it will return an array even though you specified to return 1.

Then in this loop add a "Conditional".

Then in the conditional add an "If". For the if you can do entity has field, or entity is of type and content is of type. You can add multiple Ifs. If you want multiple nested ifs you have to add it like
    conditional
      if entity is of type node
        conditional
          if content is of type page
            action unpublish node

Once you have added the ifs rules will know that the fetched-entity is a node and what fields it has.

Then you can add an unpublish action and select entity-fetched (or list-item because of the loop)

So your rule might look like this:

Event: Before saving a user account
Action: Fetch entity by property(Parameter: Entity type: Node, Property: Title, Value: [account:field-business-profile], Limit result count: 1 Provides variables: Fetched entity (entity_fetched))
Action Loop: (Property: List: [entity-fetched], List item: Current list item (list_item))
  Conditional:
    If: Entity is of type (Parameter: Entity: [list-item], Entity type: Node)
      Conditional:
        If: Content is of type (Parameter: Content: [list-item], Content types: Basic page)
          Action: Unpublish content (Parameter: Content: [list-item])

Or it could look like this (without the loop, just working on the 1st entity-fetched):

Event: Before saving a user account
Action: Fetch entity by property(Parameter: Entity type: Node, Property: Title, Value: [account:field-business-profile], Limit result count: 1 Provides variables: Fetched entity (entity_fetched))
Conditional:
  If: Entity is of type (Parameter: Entity: [entity-fetched:0], Entity type: Node)
    Conditional:
      If: Content is of type (Parameter: Content: [entity-fetched:0], Content types: Basic page)
        Action: Unpublish content (Parameter: Content: [entity-fetched:0])


What is significance of confirmation page before deleting a node? I want to know what exactly usage of node confirm delete page except to avoid miss configuration.

This is no t exactly Drupal specific, but I'll answer them anyway because one could miss a few reasons. Correct me if I'm missing any.

It prevents accidentally clicking the delete button and actually deleting it.
It provides security against CSRF attacks. If the node is deleted as soon as the node/xyz/delete page is loaded, an attacker can make an administrator open that URL, and the node will be deleted without his intention.

Because the specifications say so. http://www.rfc-base.org/txt/rfc-2616.txt     GET requests should not make any change in data, so the request must be either a POST or a DELETE. Since Drupal forms only support GET and POST, we use the latter.


How do enable panelizer support for a custom entity? I've programmatically created an entity. I'd like to panelize it. What plugins do I need to write to accomplish this?

Thanks!

Just create a PanelizerEntity Plugin in your module.
Ex if your entity type id (or machine name) is 'course'. Create a file PanelizerCourse.php in your_module/src/Plugin/PanelizerEntity/

This file should extends PanelizerEntityBase like that:

<?php

namespace Drupal\your_module\Plugin\PanelizerEntity;

use Drupal\panelizer\Plugin\PanelizerEntityBase;

/**
 * Panelizer entity plugin for integrating with courses.
 *
 * @PanelizerEntity("course")
 */
class PanelizerCourse extends PanelizerEntityBase {

}


adding all children node flag count to sort parent i have created two content type parent and child. a parent has children. and each child has own flag count value. like:

under Parent A
   child1 had flag count=5
   child2 had flag count=2
   child3 had flag count=0

under Parent B
    child1 had flag count=3
    child2 had flag count=1
    child3 had flag count=0
    child4 had flag count=6.

now sort the parent according to all children's flag count value.Like here Parent B should come first because he has his children flag count value is 10..

please help me to short out this scenario...

Is it possible to have a hidden field on parent node value for which updates as per the flag counter on referenced node changes.In that case it will be easier to build custom query or even if you use views you can sort by the hidden field  value.

Updated:

  Child node 1 has a node reference to Parent Node.
  Keep flag count as hidden field on parent content type
  The time flag is updated on Child node, you can grab all parent nodes on the updated child node.
  Change the hidden field value on parent node from hidden field value to +1.

Code that can be used to update parent node field
 - you will have all parent node id in child node object, grab the ids.
 - Use the following code to update the parent fields.

  $node = node_load($nid);
  $node->field_flag_count['und'][0]['value'] += 1;
  field_attach_presave('node', $node);
  field_attach_update('node', $node);

  This will save lot more node save processing and unnecessary node
  revisions

SO this way the total flag count will all be present on parent node and sorting will be lot more easier that way!.


Theme UberCart catalog page to use custom html Working with Ubercart 3.x on Drupal 7.

I want to theme the /catalog/1 page, where it shows my products. I want to use completely custom html that has divs nested with tables nested with divs.

I know that I can override with my own view, but I have no idea how to get the data that the existing view is using?  I want to make my own tpl.php file that will loop the products for that catalog, but I don't know which variables to access, or what functions to call.

Thank you

Your theme's files will override the module's files.

You should install the "Devel" and "Theme Developer" modules.

https://drupal.org/project/devel_themer

WHen you have these installed and configured, it will show you the template names to use for specific pages/blocks/views/etc.


Display submission history of a node? Use case: This content type offers an Approval Status with three radion button options, Submitted, Approve, and Reject.

A node from this content type can go through all three in its lifetime.

And that "history" should be displayed at the bottom of  the page.

How do I do this?

You will need to make sure that the content type creates a new version with every edit. Then, you should be able to make a Views block that shows node versions and the status field.


I need to bring a site to version control, and set up the continuous Integration environment I am an entrepreneur with a Drupal 6x project that started small enough to not need version control (per developers), but now I am convinced there is no way without it. There's extensive documentation on JIRA, complete with well-written User Stories covering everything. I read up a bit about how this could be done and came up with the following plan -

Separate site code from database using modules

Context
Features
Strongarm
Profiler

Put the code in a SVN repository and create a staging site
Create a mirror of the staging server on EC2 production server
Create Selenium tests, and run them on the cloud using Saucelabs
Create a build workflow in JIRA Studio using Elastic Bamboo to run automatic updates
Update and install profiles using Drush Make
Run updates on production server (I am not sure how)

To begin with, I have made a list of about 50 "Features", each with its components (views, content types, modules etc). This will no doubt be challenging as the site contains about a dozen custom modules and web services, not to mention another dozen instances of content type "application" containing custom code (most of which I would like to have converted to upgradable views or modules). The good thing is that the site is not yet in production so the risk is still limited.

Does anyone have any experience in doing something similar? What pitfalls and limitations should I expect to encounter? I would greatly appreciate any suggestions for improving/correcting the above plan, or any insight or advice that you experts out there might have for me.

Ok, I'll give this a try :) I won't be able to fully answer your question, but maybe give you have few interesting hints. Note that my numbering is not in direct response to yours :)

As I already mentioned in the comment, no project is too small for version control. I personally recommend Git. Reasons are the plain awesome speed of it (wait time in git is measured in milliseconds, not seconds) and the huge amount of features. It can be a bit hard to pick up, because of weird names and arguments but the following documentation explains many of them really good: http://www.eecs.harvard.edu/~cduan/technical/git/. Another reason is that it is now used by drupal.org, so knowing git will help you when you want to contribute back (providing patches, testing patches, release modules, ...)

That said, if you'd like to use SVN for some reason (like integration with services you plan to use), then go for it. SVN works reasonable well too and is much better than no source control. (Unless you ask Linus Torvalds..). Also, there are often ways to migrate from one VCS to another if you change your mind. SVN -> Git works well, for example.

Third, approach this step by step. Don't try to do everything at once. Give you (and your developers) the time to learn the new tools.

Switching from Drupal 6 to Drupal 7 is not a trivial thing. Especially with a lot custom code. Note only are there tons of API changes and new concepts (like the entity/field system), there is also the point that many contributed modules aren't fully ready yet.

Deployment management is one of the weak points of Drupal, that also hasn't changed that much in Drupal 7. We are aware of the problem and people are working hard to resolve this for Drupal 8: http://groups.drupal.org/build-systems-change-management/cmi. Features etc. helps, but it's not a silver bullet. Not everything can be exported as a feature.

There are also a few Drupal-specifc options for deploying staging/production sites. Pantheon (still in beta) and Acquia Dev Cloud might be worth checking out.

Continuous integration, automated testing is important and really useful but also require time to set up, write the tests and so on. Time you might or might not have at this point. But especially automated tests is an area where it is easy to do incremental improvements. Once you have a environment set up to run them, you can write more and more tests as time permits.

So, here is my recommendation for the updated question in the comment:
Finish and release as is, but start using a VCS (version control system) for Drupal 6 now. Create a staging environment for your site. Look at what (contributed) modules you are using and check if a port to Drupal 7 is feasable at that point. Don't underestimate the time that will take. Also start to improve the testing/deployment process, starting with what you think will bring you the most benefits/cost.
You can also create more specific follow-up questions or look those which already exist. As you can see, even only giving a few hints to a question like this can get huge and take quite a bit of time.


How to change the delete Message "Are you sure you want to delete" in Drupal 7 I want to change the message "Are you sure you want to delete" to simple "delete".
Can someone explain how I can do that?

One option (that requires no coding) is to use the String Overrides module.

It allows you to replace any string with another string that is passed though the t() function, though a nice easy to use GUI.

The other option is to use hook_form_alter(). For more details on that see the question that Rupesh linked to.


How to test __get() in Node object? I've created UnitTest based class for my service.

In one of my tested methods from service class I have code like:

if ($node->hasField('field_foo')) {
  $section = $node->field_foo->entity;
}

I've created mock for Node class and I know how to "emulate" hasField. However, how to mock this line:

$section = $node->field_foo->entity

I'd to set $section to be a Term object (or mock). Is this even possible?
Now my test falls with an error:

  Trying to get property of non-object

but this is clear why. I'm using just mock, not real Node object.

Yes, magic methods afaik can't be mocked.

You can use get('field_foo')->entity which does exactly the same as __get(), at least in this case. And then make that return a stdClass object with a ->entity property. That's not exactly the same as what really happens, but it will work in the same way for your code.


How do I print custom user fields? I am trying to customize the authored by information for all of my nodes that prints the User First and Last Name, which are custom fields on the User Profile.

I copied the node.html.twig template into my theme
I added the following code to load the user information in my preprocess function

function blend_preprocess_node(&$variables) {

// Load the current user.
$user = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id());

// get field data from that user
$firstname = $user->get('field_first_name')->value;
$lastname = $user->get('field_last_name')->value;

// some default getters include
$email = $user->get('mail')->value;
$name = $user->get('name')->value;
$uid= $user->get('uid')->value;

}

I added this code to node.html.twig

{{ title_prefix }}   {% if not page %}

  {{ label }}

   {% endif %}   {{ title_suffix }}

{% if display_submitted %}

      {{ content.field_services }}

  {{ author_picture }}

    {% trans %}Submitted by {{ firstname }} {{ lastname }} on {{ date|date("m/d/Y") }}{% endtrans %}
    {{ metadata }}

   {% endif %}
{# We hide the comments and links now so that we can render them later. #}

{{ content|without('comment', 'links', 'field_tags', 'field_services') }}

{% if content.field_tags|length and not is_front %}
{{ content.field_tags }}   {% endif %}
{{ content.links }}   {{ content.comment }}

How do I make variables (mostly fields) from different entities available to print in different template files?

Assuming this information is from the user profile.

You could do the following

blend.theme

function blend_preprocess_node(&$variables){
    $node = $variables['node'];
    $variables['firstname'] = $node->getOwner()->field_first_name->value;
    $variables['lastname'] = $node->getOwner()->field_last_name->value;
}

From there you can use {{ firstname }} and {{lastname}} anywhere in your template.


outputting image from custom module I am writing a custom module that will output an image on the page. I believe that I should have this image in my module folder and not rely on that image being in the site files. I'm not sure how to reference that image to produce the img tag.
mymodule
-/mymodule.info
-/mymodule.module
-/files
-/files/myimage.png

I want to be able to render the image so that the source is displayed with an img tag:

For outputing image, you should use theme function, with image theming. And path argument inside.

For example:

$img = theme('image', array('path' => "path to image"));
// $img will containt the image tag.
// path can be relative from drupal root, or it can be 'files' path (public://image.jpg)

Read more about it, you can here: https://api.drupal.org/api/drupal/includes%21theme.inc/function/theme_image/7

The power of Drupal in overwriting, so I suggest you to use theme way.


How to get relationship id in views drupal 7? I am using User relationships module and created relation friends. Where we can send and receive friend requests just like fb. So l have created view to list all my-friends and also added remove link to the each friend. In view "status link (action)" field is providing remove link which can be used to remove the particular friend from our friend's list, but the link is not accessible to the users other than admin. I want to get relationship id (rid) in view so that I can create remove link. Is there anyone who knows the way to get rid? I just want to create url like below
myhomesite.com/user/26/relationships/1115/remove?destination=user/373/friends . where 26 is logged in user id and 1115 is the relationship id.Thanks.

If you want to output a link in views which leads to the page where the user's account can be deleted you can use the field "User: Cancel link". That field should be present in your view since you have the user as a relationship.

If you still want the user's uid and link to some page on your own you need to add the field called "User: uid" and then rewrite the output of the field.

Add the field called User: uid, then under the settings for the field expand Rewrite results and click Rewrite the output of this field, enter the text that should be displayed. Then click output this field as a link and use the [uid] placeholder in the link. The [uid] will be replaced with the user's uid when the View is rendered. You can see an example of the settings in the image below.


Update core keeping other composer packages After upgrading Drupal to the last version with Drush (8.1.15) the other composer.json dependencies (e.g. drupalconsole) are removed.

Are there any way to update Drupal with Drush keeping other composer dependencies?

diff --git a/docroot/composer.json b/docroot/composer.json
index 6089861..b9536cf 100644
--- a/docroot/composer.json
+++ b/docroot/composer.json
@@ -4,28 +4,11 @@
     "type": "project",
     "license": "GPL-2.0+",
     "require": {
-        "ckeditor/fakeobjects": "4.6.2",
-        "ckeditor/image": "4.6.2",
-        "ckeditor/link": "4.6.2",
-        "codemirror/codemirror": "5.27.4",
         "composer/installers": "^1.0.24",
-        "drupal/console": "~1.0",
-        "jquery/geocomplete": "1.7.0",
-        "jquery/icheck": "1.0.2 ",
-        "jquery/image-picker": "0.3.0",
-        "jquery/inputmask": "3.3.7",
-        "jquery/intl-tel-input": "12.0.0",
-        "jquery/rateit": "1.1.1",
-        "jquery/select2": "4.0.3",
-        "jquery/timepicker": "1.11.11 ",
-        "jquery/toggles": "4.0.0",
-        "jquery/word-and-character-counter": "2.5.1",
-        "progress-tracker/progress-tracker": "1.4.0",
-        "signature_pad/signature_pad": "2.3.0",
-        "wikimedia/composer-merge-plugin": "~1.4"
+        "wikimedia/composer-merge-plugin": "^1.4"
     },
     "replace": {
-        "drupal/core": "~8.3"
+        "drupal/core": "^8.4"
     },
     "minimum-stability": "dev",
     "prefer-stable": true,

I've seen that there is a composer project for Drupal but I'm not using it in this project.

If you have a composer based project, you probably should use composer to update it.  E.g.:

composer update drupal/core --with-dependencies

Make sure to keep the composer.json, composer.lock, and docroot/vendor/composer/installed.json files in your repository.

Note:  It's best to go 'all-in' with composer and use it to add and maintain modules as well as core. E.g.:

Add new module:   composer require drupal/module

Update module:  composer update drupal/module --with-dependencies

To manage patches, see the cweagans/composer-patches project.

You can also include various 3rd party libraries (e.g. chosen, colorbox, and the like) using your composer.json file.


Is upgrading MySQL to MariaDB seamless for Drupal sites My server has an outdated version of MySQL (5.5, which EOL'd in December). The WHM panel has an update option and the recommended upgrade is MariaDB 10.3.

In theory (with all usual "test first" caveats), should a major upgrade like this be seamless for the Drupal sites running on the server?

Drupal runs fine on both MariaDB and MySQL, so you should be able to replace one with the other without any issues at the application layer (Drupal).  I don't believe the abstraction layer does anything differently between the two so you shouldn't have issues with needing to change field types (swapping to Postgres or other engines Drupal supports would change that answer significantly).

I would expect with an update like that to require some downtime, and a change of username and passwords for the database itself. So you will probably need to update the database connection settings once the update is complete.

All that of course depends on WHM doing the actual update of the database layer correctly so that "test first" caveat is a big deal.


what will be the cause of redirection loop while accessing view settings page I have drupal 7.14 setup installed with views module.
Whenever i am trying to access "admin/structure/views" the
site goes into redirection loop and not opening the views setting page also same behavior is showing for Linkit Profiles settings page.

I can add views by directly calling this url "/admin/structure/views/add" but not able to edit as they are not listing but i need to know why the views settings page not showing.

Solutions which i already tried:

Uninstalled views module and again installed.
run update.php
cleared views cache from database

But it doesn't give me any result any guesses why this is happening.

Five things I would check:

.htaccess rewrite rule?
Faulty alias? Check the table url_alias for any entry that contains admin/structure/views.
Redirect? If you have any redirect modules installed (globalredirect, redirect), check if there is a redirect set for the path in question.
Otherwise check the table menu_router, look for the path in the path column and see which function is set in the page_callback column. In D7 with Views 3 this should be ctools_export_ui_switcher_page.
Check your servers access and error logs to see if there's anything suspicious.


Which .tpl file should I use to theme the quiz module's detail page? I am using the Quiz module for a requirement.

I want to theme the quiz detail page, multiple choice questions page and the Jquery timer which I am using with that page.

Which .tpl files should I edit for this?

The answer surely will be here it describes how to create a .tpl files for ehat you want D7 theme suggestions


changing a MySQL query to a drupal query any ideas I'm trying to change the following query to a drupal db_query:

SELECT first_name, SUBSTR(first_name,1,3) AS firstname_substr FROM civicrm_contact WHERE id != 'NULL' ;

I have tried this, but its not working:

$firstname_substr = $query->addExpression('SUBSTRING(cc.first_name,1,3)','cc.firstname_substr');

Below is the function I am trying to add it to:

function search_pcp($name, $from = 0, $count = 5){

  $query = db_select('civicrm_pcp', 'pcp');
  $query -> join('civicrm_contribution_page','cp', 'pcp.page_id = cp.id');
  $query -> join('civicrm_contact','cc','pcp.contact_id = cc.id');
  $query -> addJoin('LEFT OUTER','civicrm_entity_file','cef', 'cef.entity_id = pcp.id');
  $query -> addJoin('LEFT OUTER','civicrm_file','cf', 'cef.file_id = cf.id');
  $query -> condition('pcp.is_active','1','=');
  $query -> condition('cp.is_active','1','=');

  $db_or = db_or();
  $db_or->condition('cc.first_name',  $name, 'like');
  $db_or->condition('cc.last_name',  $name, 'like');

  **//$db_or->condition($firstname_substr, $name);**

  $query -> condition($db_or);

  return $query->execute();

}

I believe you need to change

$firstname_substr = $query->addExpression('SUBSTRING(cc.first_name,1,3)','cc.firstname_substr');

to

$query->addExpression('SUBSTRING(cc.first_name,1,3)','firstname_substr');

and

$db_or->condition($firstname_substr, $name);

to

$db_or->condition('firstname_substr', '%'. db_like($name) . '%', 'like');

So it will look like this:

function search_pcp($name, $from = 0, $count = 5){

  $query = db_select('civicrm_pcp', 'pcp');
  $query->join('civicrm_contribution_page','cp', 'pcp.page_id = cp.id');
  $query->join('civicrm_contact','cc','pcp.contact_id = cc.id');
  $query->addJoin('LEFT OUTER','civicrm_entity_file','cef', 'cef.entity_id = pcp.id');
  $query->addJoin('LEFT OUTER','civicrm_file','cf', 'cef.file_id = cf.id');
  $query->condition('pcp.is_active','1','=');
  $query->condition('cp.is_active','1','=');

  // changed cc.firstname_substr to just firstname_substr
  $query->addExpression('SUBSTRING(cc.first_name,1,3)','firstname_substr');

  $db_or = db_or();
  $db_or->condition('cc.first_name',  $name, 'like');
  $db_or->condition('cc.last_name',  $name, 'like');

  // corrected the condition statement
  $db_or->condition('firstname_substr', '%' . db_like($name) . '%', 'like');

  $query -> condition($db_or);

  return $query->execute();

}


How to send user password during registration? How to send user password during registration.
I have to send html email when user register in the site using rules module in drupal 7 and i have to send the username and user password in that mail.
i used [account:name] and [account:password] or [user:password] but i did not get the user password on my mail.

This doesn't answer the question, but it has to be said.

You should not e-mail users their password.

It's highly irresponsible to do so.

There are strong reasons for Drupals default behaviour.

People tend to re-use their passwords in lots of places, and e-mails are not a secure communications channel.

If your end user re-uses the password for their VPN tunnel, and login to their e-mail over an unencrypted channel, (no https for the e-mail, and no password on the local wifi for example), then you have just broadcasted that password for the world to see. And now you've facilitated the cyber attack on their workplace. There's probably a large number of both known and unknown ways to compromise the passwords as well. NSA are practically guaranteed to get it.

Don't do it.

Yes, it's the users fault for re-using their password and not requiring HTTPS to their mail and a strong password on the wifi, but you are the developer and need to know better.


Views Calendar Pager Skips a Month Forward In our calendar constructed by Views, the pager (also constructed by Views) skips a month when you hit next. However, the "previous" pager button only goes back one month. So it goes forward two months and back one...

Has anyone else experienced this? I've tried messing with the pager settings, but to no avail. This calendar was added to the site before my time, so I don't really know what to look for, but if you need more info, let me know and I'll try to find it!

This is a bug in the Date module, fixed by this simple RTBC patch in comment #35

https://www.drupal.org/node/2375235#comment-10205617


How do prevent other users from seeing certain views in a user profile? I have setup a View which showscertain information to a user, when he/she is logged in provided that logged in user is referenced in the content type containing that information.

The View shows this information user the name of the uid from the url.

The website is such that the logged in user can view the profile of other users, this makes the logged in user have access to the information of the user whose profile is viewing which shouldn't be the case. Please tell me  how do I prevent this?

This is honestly, a question that I have faced many times.
You have 2 options.

Use a path like /my_posts and then using UID argument with "logged in user" as the failback argument.
This is a common wa. Modules like Flag comes with default Views that uses "logged" in user as the failback argument so it doesn't need to mess with php.

However, the ideal solution would be,

A. Add the UID argument as necessary (user reference, author, etc).

B. Set When the filter value is NOT available to Provide default value and then to User ID From URL.

C. Check Specify validation criteria. and choose "php code".

<?php
global $user;
if ($user->uid == $argument && is_numeric($argument) && $argument >0 ){
  return TRUE;
}
?>

D. 'Action to take if filter value does not validate'  => Display "Access Denied"

Good luck!