What is the most reliable and fault tolerant way to integrate 3rd-party data structures via a web service in Drupal 7? I've seen a number of strategies for integrating remote data structures in Drupal. The strategies have seemed to evolve as certain modules have stabilized and use cases have been tried.

Imagine we have a data structure "Farmers Markets" that is represented by a number of data types (market, market_hours, vender, stall, produce) etc that are exposed via a REST API. The IDs for the external service would need to relate in Drupal, ie when loading a "market" we would want to grab data from the 'market_hours' and 'stall'. What would be the best way to represent that as read-only content in Drupal that is synced on a regular basis?

I'm trying to evaluate this with the following criteria:

Data Structures in Drupal:

Nodes vs Custom Entities

A number of scenarios involving web services I've seen use custom entities. It simplifies the CRUD ops. However, these items would be "content" in that they would be viewed publicly.

Storage (Local vs Remote):

I've seen a couple of examples where services are loaded as remote entities, which this module creates a library for: https://drupal.org/project/wsdata . This sounds most appealing, but haven't seen a lot of use cases. There also examples of custom code: https://drupal.org/sandbox/fago/1493180

Syncing Data:

Feeds vs Migrate vs Guzzle vs 'Web Service Client' vs 'Web Services Data'

There are a number of options. Feeds now supports entities. Migrate seems a lot cleaner than feeds, especially for custom scenarios. I've also seen folks using a guzzle client to grab sync with remote services: http://drupalcode.org/project/ckan.git/blob/refs/heads/ckan_dgu_7.x-1.x:/ckan.drush.inc#l273. I've also noticed the WS Client module https://drupal.org/project/wsclient provides an option that has been created specifically as a rest client. Web Services Data loads directly from a service and caches it locally.

Thanks for any thoughts.

1. Reformulating the question

Your example suggests that the data is read only on the Drupal side, with one-way syncing only. I think this is the most important factor to consider here, because in effect whatever solution you implement will be a variant of remote storage, syncing and local caching - even if the local caching ends up being entities in the Drupal database.

So the question, rather than being "local storage vs remote storage" is going to be:

Should you cache the data locally at all ;
Should you cache the data as actual entities, and use Feeds (or similar) to synchronise the data regularly ; OR
Should you use some custom made module that provides the syncing and the caching.

An article you might be interested is in "Remote Entities in Drupal 7".

2. Caching the data

In general, caching the data is a good idea:

You are protected against outages of the other services, or timeouts
in the connection ;
Having your data present in your Drupal database will speed up operations ;
Having your data present in your Drupal database will mean that you are more likely to get integration with other modules, such as Views (though this is not guaranteed).

The only advantage of not caching the data is that you never get stale data, which in some cases is preferable - sometimes it is preferable to display no data rather than stale data. I do not see this as a benefit in the example you have given, so I will focus this answer on a solution that involves local caching.

3. Local entities + Syncing

If you go for the option of having local entities and syncing them yourself, then we come back to your original questions:

Should you use nodes or custom entities ;
Which module is best for syncing.

3.1 Nodes vs Custom entities

The definition of what exactly is a node is one that is quite open. The documentation page on nodes suggests that nodes are "posting" that are "stored" on your site - neither of which apply to your data ;
As a Drupal developer I would expect that if something is a node then I should be able to manipulate it on the site itself ;
As Drupal user, I would similarly expect that nodes can be edited ;
This Drupal 8 issue https://drupal.org/node/2019031 suggests that the concept of "read only" is one that would apply at the entity level, rather than the bundle level. If this ever gets implemented you would benefit from it by having gone down this route.

To summarise: your data being read only and stored remotely it makes more sense to use a custom entity type to represent your data.

3.2 Syncing

For the second part, the two main modules for this are, as you suggest, Feeds and Migrate.

The difference between Feeds and Migrate is that Feeds is build for regular importing of content, while Migrate is build for one-off porting of content from one place to another. Migrate does support updating existing data, however given that both modules are well supported it makes more sense to use the module that was build for the task at hand - Feeds is a better match.

Having used both modules myself (Feeds for syncing, Migrating for migrating) I do not find Feeds to be more messy than Migrate. Migrate has required more custom code in my experience, though migrating entire sites is more complex than importing single content types, so it's hard to compare.

4. Custom module for remote storage, syncing + caching

There are a number of modules out there that can help with this task.

You mentioned the Web Services Data module, and others have mentioned the Data module. Another option to consider is the Remote Entity API module. Note that the only one of those I have experience with is the Data module.

The Web Services Data module does not yet have a release - which may indicate the code is not yet stable, the API might change and so on. It does not support Entity Field Queries (according to it's project page), and a quick browse of the code repository shows no evidence of it having Views support - so you would not be able to use Views to display your entities ;
The Data module is more oriented, in my experience, towards non-developers who have data in a table and want to expose it to views. I have found the Drupal 6 version to be quite frustrating to use - though that might have changed since then ;
The Remote Entity API module sounds quite promising - it supports fetching and caching of remote entities, and has Views support. It's only on alpha release - so API might still change. At first glance it does not seem to have Entity Field Query support either, and it only support one type of remote service so you would have to implement your own.

Conclusion

Given that none of the remote storage modules support Entity Field Queries, using actual entities + feeds is the solution that will give you the best integration with your Drupal site.

If Views support is enough, and you are not worried about potential integration with other modules via Entity Field Queries, then using the Remote Entity API might be the way to go - you would need to implement your own remote interface however.


Removing parts of a content type so, I was trying to get rid of the comment title and there is a lot to read about that on the net, but I still had my issues getting it right, so I came up with this, but I believe there should be a better way.
What is the best way of doing this:

function theme_preprocess_comment(&$vars) {
// Remove the comment title
  $vars['title'] = NULL;
}

You can set your content type to not use comment title by unchecking "Allow comment title" under the settings for your content type.

Then I would copy comment.tpl.php to your theme and customize the output there instead of just unsetting the title value in theme_preprocess_comment().


View Bulk Operation page Customization i have created on view page which have option to update the node values but as a default behavior of VBO i first need to check the checkbox form my table and then click on update button then it goes to another page where i can select which value to be added

After click on update button next page will come for selection of value

after this selection and next is clicked the value get updated...

here i need to change this whole process to first page only i need my select box (i.e. Workgroup & Project Type dropdown) should come to first page only where i have my list to select the value and update button on click of that the node values should update and i return back to the same page..

It's quite hard to understand exactly what you mean but I think an answer I wrote before might help since VBO doesn't really do what you want it to.

How to bulk delete selected content/nodes?

Follow the link if that "one page" functionality is what you need. It's limited but it works.


Customizing custom modules We are planning to implement custom features (in the form of newly developed modules) on top of a standard Drupal7 installation. This "standard" Drupal installation may include some contribution modules such as organic groups.
This extended Drupal installation will be provided to different clients each of which may require custom theming and some (minor) customisation of the custom features mentioned above.

What I am wondering about is the deployment and code maintenance architecture.
Coming from an object oriented background my initial reaction was to propose a layered architecture along these lines:

------------------------
Client Customization Modules
----^ ^ ^ ^ ^ ^ ^ ^-----
Generic Self-created Modules
----^ ^ ^ ^ ^ ^ ^ ^-----
  Contribution Modules
----^ ^ ^ ^ ^ ^ ^ ^-----
      Drupal Core
------------------------

Meaning the custom main extension modules ("Self-created Modules") would be overwritten/overloaded wherever the respective client requires individual changes using a second custom layer of "Client Customization Modules".
From my point of view this is benefitial as it allows for the generic "Self-created Modules" to remain identical for all clients so bugfixes can easily be performed on a single, central svn location.

Now a colleague argued heavly against such an approach, saying having a 4th module layer which basically overwrites hooks of the 3rd layer would be extremely bad practice in Drupal development as it raises the application complexity and makes debugging virtually impossible.

The alternative would be to create redundant copies of the "Generic Self-created Modules" layer for each client and directly customize these instances. While this is surely possible, a bugfix or change to the generic functionality would then not be possible anymore in a central location, so this approach seems quite dirty to me.

Is it really considered bad practice, or heavily advised against, to customize ones own custom modules by "hooking custom hooks" in a way proposed above?

In Drupal, most of the customization is not done by overriding existing code but rather by extension or alteration.  Most contribution modules and Drupal core provides extension points (hooks) and configuration variables. Your custom modules (self-created and client customization) should re-use these hooks and configurations.

For your self-created modules, you can use the Features module to easily export configurations into code. To customize your features at the client customization level, you can choice to either use alteration hooks or to re-write part of the Features-generated code to make it customizable via in-DB configuration. See http://developmentseed.org/blog/2009/jul/09/development-staging-production-workflow-problem-drupal and http://www.archive.org/details/CodeDrivenDevelopmentUsingFeaturesEffectivelyInDrupal6And7 for more information on the Features module. Also, the Kit Specification provides information on how to build re-usable features modules (with Features)., see also http://funnymonkey.com/building-features-for-install-profiles and http://nodeone.se/blogg/an-alternative-way-of-structuring-features-for-distributions.


Ubercart change product image thumbnail in cart view to a different field When you install ubercart, there is a product image field that is used by default. The field is labeled uc_product_image. I decided not to use this field for different reasons, but now I notice that none of the images for products are showing in the cart as thumbnails. I found and changed the field in the views I could, but I can't find where to change it in the actual cart.

Any help on where or how to change this will appreciated.

One option would be to use form_alter hook to change the display.


How to password protect terms in Taxonomy I have a taxonomy vocab "region"
in the region, I have a bunch of provinces as the terms, and subpages for each province.

I would like to add a password protect or only allow authorized users to access the provinces.

etc, only username "ontario" "password" can access the term "ontario" in the taxonomy. Is this possible?

These modules may help, for D7 & D8 on DEV version is Taxonomy Access Control Lite, on approved versions (recommended): D7 is Taxonomy Access Control and for D8 is Permissions by Term, review wich one fit best your needs.


Add theme color palette picker I have a multisite in Drupal 8 eg. same codebase, differrent db. The client is asking for different color scheme for each subsite. I was thinking of implementing somehow Bartik's color picker, but have no idea how. The current theme is not derived from Bartik.
O the question is how can I implement color picker in my custom subtheme?

Thanks

This is done by the color module which is a part of Drupal core.

  The Color module allows users with the Administer site configuration permission to quickly and easily change the color scheme of themes that have been built to be compatible with it. In order for the color module to work, a theme must be specifically designed to use the color changing features.

Here's a great guide to integrate to the color module in Drupal 8.

Integrating the color module into your drupal 8 theme


How to Create a wall of activities (like Facebook wall) in my site, for each user? I am building a social network site.
My plan is that every user would be able to write articles, tips, upload pictures, comment to others, like other posts etc.

My question is how can I aggregate all the user different activities in to one page (e.g. wall), so the user and all the other users can see all the activities in one page (similar to facebook wall)?

Thanks in advance.

You need to give the ability to users to create a relationships.
https://drupal.org/project/user_relationships. You can set up what kind of content is shareable.

Then using https://drupal.org/project/heartbeat you can get activity streams.

Really do yourself a favor and get https://drupal.org/node/1849900. It can save up huge amounts of time, allowing you to set up a facebook-like network in a few hours!


theming username field in user-register form i'm trying to theming my user register form. i would like to have a custom function for the username part. So, i'm doing

$form['account']['name']['#theme'] = 'my_custom';

i define my hook_theme and just for testing purpouses, this is my custom function

function theme_my_custom( $variables ){
  return 'testing code...'
}

My problem is when i go to user/register, i still can see the label for my username. Only the input is replaced by the code of my function. I would expect replace the element entirely, but this is not happening.

Any clues? Thanks.

As you can see on the Form API reference page, '#theme' Only affects the input box itself. To remove other things generated by the form API, you'll have to clear the array -

$form['account']['name']['#title'] => '';
$form['account']['name']['#description'] => '';

or just

$form['account']['name'] = array(...);

To reset existing elements.


Indexing the term of unpublished entities I have a views of unpublished contents of content-type X, which has the Term Y.

It works fine with published content but a thing that I noticed is that if I unpublished a content that has a taxonomy term, in Views it loses the term associated with it, therefore I cannot filter my list based on taxonomy term anymore.

I also found Taxonomy Entity Index module but it doesn't work at all.

Also a related issue on drupal.org

Is there any workaround for this?

For anyone who might encounter the same issue:

It looks like that it's a common issue in D7 and unfortunately going to be in D8, but hopefully the fix will be in core for D9.

Right now we have to use TEI module as a workaround for D7 and D8.

If you are installing this module into an existing site, visit admin/config/system/taxonomy-entity-index to rebuild the Taxonomy Entity Index.

Also note that in Views there will be some new fields/filters to work with, for instance instead of Content: Has taxonomy terms in filters section of views, you should use Taxonomy Entity Index: Has taxonomy terms on Nodes and for exposing the taxonomy terms also you should use Taxonomy Entity Index: Has taxonomy terms on Nodes not the default Content: Has taxonomy terms.


Where can I alter the labels used on the login form? This must be configurable somewhere, surely, but I just can't find where. I'm sure I'm doing something silly. Apologies for such a simple question.

Try this way by implementing hook_form_alter.

/**
 * Implements hook_form_alter().
 */
function YourCustomModuleName_form_alter(&$form, Drupal\Core\Form\FormStateInterface $form_state, $form_id){
    if ($form_id == 'user_login_form') {
        //- change label for username input
        $form['name']['#title'] = t('Your New UserName Label');
        //- change label for password input
        $form['pass']['#title'] = t('Your New Password Label');
    }
}


Update existing content using migrate module I'm using migrate module in Drupal 7 to update existing content of a Drupal site. My source and destination tables are the same. I got some documentation from http://drupal.org/node/1117454. Here's my code:

<?php
class MTestMigration extends Migration {

  public function __construct() {
    parent::__construct();
    $this->systemOfRecord = Migration::DESTINATION;
    $this->team = array(
      new MigrateTeamMember('foo', 'foo@bar.com', t('Site builder')),
    );

    $this->description = t('Migrate basic slides');

    $source_fields = array(
      'nid' => t('The node ID of the slide'),
      'title' => t('The node title of the slide'),
      'uri' => t('the slide image'),
    );

    $q = db_select('node', 'n');
    $q->leftjoin('field_data_field_image', 'i', 'i.entity_id=n.nid');
    $q->leftjoin('file_managed', 'f', 'i.field_image_fid=f.fid');
    $q->fields('n', array('nid', 'vid', 'type', 'language', 'title', 'uid', 'status', 'created', 'changed', 'comment', 'promote', 'sticky', 'tnid', 'translate'))
      ->fields('f', array('uri'))
      ->condition('n.type', 'slide', '=');
    $this->source = new MigrateSourceSQL($q, $source_fields);

    $node_options = MigrateDestinationNode::options(LANGUAGE_NONE, 'filtered_html');
    $this->destination = new MigrateDestinationNode('slide', $node_options);

    $this->map = new MigrateSQLMap($this->machineName,
        array(
          'nid' => array(
            'type' => 'int',
            'unsigned' => TRUE,
            'not null' => TRUE,
            'description' => 'Unique Node ID',
            'alias' => 'n',
          )
        ),
        MigrateDestinationNode::getKeySchema()
    );

    $this->addFieldMapping('is_new')
      ->defaultValue(TRUE);

    $this->addFieldMapping('nid', 'nid');
    $this->addFieldMapping('title', 'title');
    $this->addFieldMapping('is_new')->defaultValue(TRUE);
    $this->addFieldMapping('uid', 'uid');
    $this->addFieldMapping('revision')->defaultValue(TRUE);
    $this->addFieldMapping('revision_uid', 'uid');
    $this->addFieldMapping('created', 'created');
    $this->addFieldMapping('changed', 'changed');
    $this->addFieldMapping('status', 'status');
    $this->addFieldMapping('promote', 'promote');
    $this->addFieldMapping('sticky', 'sticky');
    $this->addFieldMapping('comment', 'comment');
    $this->addFieldMapping('language')->defaultValue('und');

    $this->addFieldMapping('path')->issueGroup(t('DNM'));
    $this->addFieldMapping('pathauto_perform_alias')->defaultValue('1');

    $this->addFieldMapping(NULL, 'name');
    $this->addFieldMapping(NULL, 'vid');
    $this->addFieldMapping(NULL, 'type');
    $this->addFieldMapping(NULL, 'language');
    $this->addFieldMapping(NULL, 'tnid');
    $this->addFieldMapping(NULL, 'translate');

    $this->addFieldMapping('field_image', 'uri')
      ->arguments(FILE_EXISTS_RENAME);
  }
}

I end up with this error:

  Column not found: 1054 Unknown column 'map.destid1' in 'field list':
  SELECT n.nid AS nid, n.vid AS vid, n.type AS type, n.language AS
  language, n.title AS title, n.uid AS uid, n.status AS status,
  n.created AS created, n.changed AS changed, n.comment AS comment,
  n.promote AS promote, n.sticky AS sticky, n.tnid AS tnid, n.translate
  AS translate, f.uri AS uri, map.destid1 AS migrate_map_destid1,
  map.needs_update AS needs_update FROM {node} n LEFT OUTER JOIN
  {field_data_field_image} i ON i.entity_id=n.nid LEFT OUTER JOIN
  {file_managed} f ON i.field_image_fid=f.fid LEFT OUTER JOIN
  {migrate_map_mtest} map ON n.nid = map.sourceid1 WHERE (n.type =
  :db_condition_placeholder_0) AND (map.sourceid1 IS NULL OR
  map.needs_update = 1) ; Array ( [:db_condition_placeholder_0] => slide
  ) in MigrateSourceSQL->rewind()

This post about Unknown column 'destid1' in 'field list' helped me when I had the same problem.

In particular, drop the migrate_map_* and migrate_message_* tables since they may have been created incorrectly beforehand.


Computed twig Automatically update the computed value using Ajax Whe I use computed twig with "Automatically update the computed value using Ajax" checket, it create "update" button next to my computed twig field. How I make the field update really automaticlally without this update button.
Thanks.

I figgured out. It was because the theme template rewrite the form input element and this broke automatic comuting on forms.


'hook_entity_operation_alter', but for users I'd like to customise the Operations dropdowns on /admin/people

The documentation for hook_entity_operation_alter() says the second parameter should be:

\Drupal\Core\Entity\EntityInterface $entity:

However when I do:

function mymodule_entity_operation_alter(array &$operations, EntityInterface $entity) {
    kint( $entity );
}

I get:

  Argument 2 passed to mymodule_entity_operation_alter() must be an instance of EntityInterface, instance of Drupal\user\Entity\User given

Is there anything else I can use?

mymodule.module also needs:

use Drupal\Core\Entity\EntityInterface;

Credits to drupality, who first mentioned this in a comment below my question


How to separate UI language from node's language? I have a site that uses 3 languages, namely English, Polish and Russian. And we have content editors with 3 native languages. Now, most of the times Russian guy will want Russian UI and will be editing Russian nodes. But sometimes he will need to correct nodes written in Polish. He will not want his UI to turn to Polish when doing that, of course.

Is there a way to allow users to select their default admin language? Desired effect for nodes is:

http://example.com/node/435 displayed in layout based on node's language (let's say, Polish)
http://example.com/en/node/435 redirected to proper language (here http://example.com/pl/node/435) - that's pretty much easy and was answered in many places.
http://example.com/node/435/edit should be opened in UI based on user's preference set in a profile field, for example, or redirected to proper language edit path like http://example.com/pl/node/435/edit
http://example.com/en/node/435/edit should be redirected to http://example.com/node/435/edit or http://example.com/pl/node/435/edit (consistent with previous point).

If possible, I want this globally, for all admin pages, not only node edits, but of course node edits will be most common = most important to me.

I forgot this in my initial comment but you can actually solve this by installing Entity Translation!

It separates entity and interface translation. With both you can specify different language negotiation schemes. In admin/config/regional/language/configure simply set the user's language setting as the highest priority in the interface language negotiation queue.

By having URL as the first criteria and user preference in the content language negotiation queue you can attain this functionality you documented.


Which modules should I add to Advanced Forum to provide increased functionality? Drupal 6 Advanced Forum is very capable, but the basic installation doesn't offer many features. For example, by default there is no signature possible.

What modules/plugins/things do you recommend adding to provide a well rounded set of improved functionality in Advanced Forum?

For example, Apache Solr is meant to be a very good add-on to provide improved search functionality. There will surely be lots of other modules that you can think of that would be needed to provide some of the features that come as standard in 3rd party software. Which modules would you say are the most useful ones to have?

Edit:

One need of the forum is to support posting from a mailing list. It can do this already, but maybe there are nice features that can be added to improve this. Perhaps something that makes e-mail formatting look better in a forum, if that is necessary.

Anti-spam is important too. I don't know whether there is a single, catch all anti-spam module. Perhaps there are several modules that should be used here.

The forum is important for community building, so plugins that would help there, for example things that make profiles more informative.

I am interested in all sorts of good functionality. I would like to hear about plugins that people suggest because they are useful, even though I haven't referred to them in this post. That is what I am hoping for. I don't know what to look for / what good things to add.

While I do think this question is off-topic for this site, I know what you're going through. I recently built a forum with drupal, and I was surprised at how difficult it was to choose a good module to fulfill certain requirements, or even how to find the right ones for the job.

So to help you out, here's some modules I used to add functionality to the forum:

Flag + Flag Abuse
Privatemsg
Subscriptions
ACL + Forum Access
Author Pane
AutoAssignRole
CAPTCHA + reCAPTCHA
Comment Permissions
Comment Upload
Custom Search
Flatcomments
Override Node Options
Private Upload
Quote
User stats


Simple way to change messages after node creation Before I would use Custom Submit Messages to customize each message but, seems to not work as we like with Drupal 7.

Is there any other simple way that will allow to alter the message text after creating content?

You can do it through Rules

Create a new rule configuration and set the event to Node | After saving new content.

Add a condition, Node | Content is of type and set CONTENT TYPES to Article, as shown in the following screenshot:

Add an Action and select System | Show a message on the site

By using the Action, After saving new content, we're asking Rules to react on content creation. This means that the rule will fire every time a new content has been created in the system. By using Conditions, we can tell Rules to only fire the action if the created content type is Article (or any other content type). In the MESSAGE field, we've used REPLACEMENT PATTERNS to insert chunks of data from the objects available in our current rule configuration.


What is the best way to collect and report statistics from within views 3's exposed filter? I have a content type "song" and created a view on it. Using Views 3 exposed filter, people can search with different criteria.

With Google Analytics, I can collect some rough statistics. But I do not want anonymous statistics. I would like to collect and report the criteria by the login user/roles.

I can put a PHP code into my view so that every time someone interacts with this view, the PHP code will collect the criteria from the URL and save to a table.

Is there a better way?

EDIT

I've got an interim solution:

Write a custom module that uses hook_form_alter to update the exposed filter form. See link.
Install Views Watchdog
Create a view that reports on these watchdog entries. I can use PHP to parse the watchdog's location field to get my reports better.

If you have a better alternatives, please let me know.

You can use GA Push module:

  GA Push offers an API to enqueue informations that are sent GA
  servers, and three submodules to track browser events (using jQuery),
  form validation errors and log exceptions.

Instead of saving the data in your custom table you can just send it to Google Analytics.

Collect your data in your PHP code and send it like this:

      $push = array(
        'eventCategory' => $category,
        'eventAction'   => $action.
        'eventLabel'    => $label,
        'eventValue'    => $value,
      );
      ga_push_add_event($push);

You may hook on the form submit instead of adding PHP code to the view.


Open login form in popup iframe? Using Colobox module? I have the login form block in my header. I removed it and in its place to put a 'login' link.

When clicking the link I'd like a popup (iframe or inline content) to show up. When the form is submitted the popup should close and then return and refresh the parent page.

I think the colorbox module is the right module to do this but I think that my request must be a frequently request and maybe there is an easier way to do this?

Thanks

I can confirm that the http://drupal.org/project/colorbox module is one of the easiest (and most supported) ways to have a lightbox for the login form.

There is also other benefits like being able to load AJAX content in the lightbox as well using 'colorbox-load'


How to restrict access to the site during development? I am creating a new Drupal 7 based site.

The development will be on a server that is publicly accessible. I am working in a multi-site environment.

I would like to totally block access to the site to anyone & anything but authorized users. Including access to the site name, theme, etc...

I used Secure Site for similar tasks before. It did http-level authentication and returned 403 when authentication failed. It doesn't have a D7 version.

What would be the easiest way to do this?

Make a module and paste following code in your module file:

<?php

/**
 * Implementation of hook_boot().
 *
 * Ask for user credentials and try to authenticate.
 */
function foo_boot() {
  require_once DRUPAL_ROOT . '/includes/password.inc';

  if (isset($_SERVER['PHP_AUTH_USER']) && isset($_SERVER['PHP_AUTH_PW'])) {
    $query = "SELECT pass FROM {users} WHERE name = :name";
    $result = db_query($query, array(':name' => $_SERVER['PHP_AUTH_USER']));
    $account = new stdClass();
    foreach ($result as $row) {
      $account->pass = $row->pass;
    }
    if (isset($account->pass)) {
      if (user_check_password($_SERVER['PHP_AUTH_PW'], $account)) {
        return;
      }
    }
  }

  header('WWW-Authenticate: Basic realm="Development"');
  header('HTTP/1.0 401 Unauthorized');
  exit;
}

This uses HTTP Authentication and checks the Drupal Database for a valid username and password.

If you have any problems with PHP CLI, Drush or cron, you can add following code in the hook:

  // Allow cron through
  if (basename($_SERVER['PHP_SELF']) == 'cron.php') {
    return;
  }

  // Allow PHP CLI/Drush through
  if (isset($_SERVER['argc'])) {
    if (php_sapi_name() == 'cli' || (is_numeric($_SERVER['argc']) && $_SERVER['argc'] > 0)) {
      return;
    }
  }


How can I achieve basic authentication in Drupal? I am trying to get working webservices in drupal (Services, restws,...), but ,as a first step I am trying to get a cookie using 'Basic Authorization' using the following python script:

import urllib2
import base64

def login(u,p):
    url = 'http://127.0.0.1/drupal/node?destination=node'
    r = urllib2.Request(url,None,{'Authorization':'Basic '+base64.b64encode(u +':' + p),
                                  'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
                              'Accept-Encoding': 'gzip, deflate'})
    f = urllib2.urlopen(r)
    cookie = f.headers.dict['set-cookie'] # <--- this fails, raises exception
    csrf = f.read()
    return csrf,cookie

csrf, cookie= login('username', 'password')
print base64.b64encode(csrf)
print "cookie:", cookie

The line 'cookie=f.headers.dict['set-cookie']' fails, since there's no cookie returned in the response.
What could I have  missed ?

Drupal 7 will not set a session cookie unless it has to, for performance reasons. If there is no form under http://127.0.0.1/drupal/node, and no module requires sessions, you will not get any session, simple as that.


Does the SimpleTest method drupalGetMails() prevent actual emails from being sent? During a SimpleTest, does the data intercepted by drupalGetMails() continue to your systems mail transport agent or is the actual send suppressed?

That is only the getter.

// Use the test mail class instead of the default mail handler class.
variable_set('mail_system', array('default-system' => 'TestingMailSystem'));

in DrupalWebTestCase::setUp stops mails being sent. TestingMailSystem does nothing else but collect emails in the drupal_test_email_collector variable.


Can I make a node reservable? Is it possible to make a node reservable (for users that do not have rights to edit/add content, or even anonymous users)? The node in this case is a "timeslot" for a service.

So there would be lots of nodes and each node could only be reserved once. At reservation time the person making the reservation should give his/her contact details. No payment or anything like that is made at this point.

I found the tutorial about Using webfom 3.x to reserve items/nodes in Drupal 7 (using the Webform module to "reserve a node"), but not sure if it is the best way (I am looking into it).

Or if anyone can just point me into the right direction, would be appreciated.


How to use db API addExpression I am trying to find a way of creating a view of both a custom entity type and a node. I was following this as a guide: https://drupal.org/node/748844 (see the way end for the D7 implementation, I have quoted it below, but for some reason, its not fully displaying...)

I am trying to understand this line

$query2->addExpression(':the_group_type', 'Type', array(':the_group_type' => 'Group'));

I see from online documentation that addExpression adds an expression to a list of fields, which I would assume means something like SUM(quantity). But I don't understand what the addExpression lines (there are actually two of them) are doing in this code.

Code listed below:

/**
 * Implements hook_views_pre_execute()
 */
function YOUR_MODULE_NAME_views_pre_execute(&$view){
    if($view->name == 'YOUR_VIEW_NAME'){
    //extracts my nodes
    $query2 = db_select('node', 'node');
    $query2->leftJoin('location_instance', 'location_instance', 'node.vid = location_instance.vid');
    $query2->leftJoin('location', 'location', 'location_instance.lid  = location.lid');

    //created and nid are the same fields used by my_view query
    $query2->addField('node', 'title', 'users_name');
    $query2->addField('node', 'nid', 'uid');
    $query2->addField('location', 'latitude', 'location_latitude');
    $query2->addField('location', 'longitude', 'location_longitude');
    $query2->addExpression(':the_group_type', 'Type', array(':the_group_type' => 'Group'));

    //set some conditions if necessary
    $query2->condition('node.type', 'group', '=')
           ->condition('node.status', 1, '=');

    $query1 = $view->build_info['query'];
    $query1 ->addExpression(':the_user_type', 'Type', array(':the_user_type' => 'User'));

    //union custom query with my_view default query
    $query2->union($query1, 'UNION ALL');

    //in order to prevent Cardinality violation errors i have to make a "total" query
    $total_query = db_select($query2,'total')->fields('total');

    //update views query and count_query with my new query.
    $view->build_info['query'] = $total_query;
    $view->build_info['count_query'] = $view->build_info['query']; //count_query is necessary for the pager
  }
}

Any valid SQL expression is allowed, and that includes placeholders (like in that code), literal values, or SQL functions calls (including aggregate functions, such as COUNT(*)).

$query2->addExpression(':the_group_type', 'Type', array(':the_group_type' => 'Group')) is equivalent, in plain SQL, to 'Group' AS Type.
It is an expression that is widely used in the Views module. For example, if you enable the "Add Views signature to all SQL queries" option, the query executed by the Views module will be similar to the following one. (This is the query I get for the front page view.)

SELECT node.sticky AS node_sticky, node.created AS node_created, node.nid AS nid, 'frontpage:default' AS view_name
FROM
{node} node
WHERE (( (node.promote <> '0') AND (node.status = '1') ))
ORDER BY node_sticky DESC, node_created DESC
LIMIT 10 OFFSET 0

The 'frontpage:default' AS view_name part is added using SelectQuery::addExpression() in a way similar to what the code you show does.


How to auto generate barcodes for Entity Registration in Drupal 7 I read this article about using rules and a trigger to populate/create a barcode field from a serial field, tried toy follow it but the screens/ facilities of Drupal 6 seem different for v 7 and the documented steps cannot be replicated. In particular I expected barcodes to be part of the drop down for fields but it isn't

"basically you should add a new rule that fills for you the barcode when new content is created starting from the serial field. The steps are:

create a new rule
trigger it on the event: 'after new content is saved'
set some condition on the type of the content (optional)
use 'populate a field' (under CCK category) as action
choose your barcode CCK field
Use the token of your serial field : [node:field_YOUR_TOC_SERIAL_FIELD-id] -- I don't remember why I didn't use the token but the follow php code:

 array('barcode' => [node:field_MY_FIELD_NAME-id]));
?>
If you didn't use Rules before have a look here: http://dev.nodeone.se/node/646  "

Its complicated but I essentially ended up using the available barcode online generators (Google has an online QR Code generator) and then embedding the URL in HTML mail that I was sending out.


Views Content slide show- with 2 rows Please help me.I am searching for a content slider in Drupal 7 .

I have created a view for displaying products.A block is created for this view.

My requirement:

I need a content slider with 2 columns and two rows.All the view items should be displayed in the slider.There will be four node contents in each slider.

eg:    row1   row1
       row2   row2

Please find the attached screen shot .I hope this may help more.

First : download the view slideshow model ;
second : add the field you want
third :from the setting you can add controller and pager
to display the item like this you have to use it in css to display it as for item


How i can create VIEW table using Drupal hook_schema() i want to create a view table in my custom module .install file and i want join with another table like i did in my db_query function but i want this thing in hook_schema function.

 db_query('CREATE VIEW Sample_Label_Data_By_CategoryId AS
                select
                `sample_label_library`.`SampleNumber` AS `SampleNumber`,
                `sample_label_category`.`CategoryName` AS `CategoryName`,
                `sample_label_and_category`.`CategoryID` AS `CategoryID`,
                `sample_label_library`.`MaterialName` AS `MaterialName`,
                `sample_label_library`.`EPANumber` AS `EPANumber`,
                `sample_label_library`.`SampleFilename` AS `SampleFilename`,
                `sample_label_library`.`LabelFilename` AS `LabelFilename`
                from ((`sample_label_and_category` join `sample_label_library`
                    on((`sample_label_and_category`.`SampleNumber` = `sample_label_library`.`SampleNumber`)))
                    join `sample_label_category` on((`sample_label_and_category`.`CategoryID` = `sample_label_category`.`CategoryID`)))')
    ->execute();

hook_schema() is only used to return a structured array representing your module's database tables. You can't execute a query from it. Well, you physically can, but you shouldn't.

Since hook_schema() is used on install, your code to create the View should be in hook_install(), and the code to remove it should be in hook_uninstall()


Add a MAX aggregation function to a query I'm building a query with $query = new db_select('node', 'n') and I'm grouping by a certain field (let's say $query->groupBy('title')), when I'm aggregate another field (such as $query->addField('n', 'MAX(nid)')) it gets sanitized into a field called n.MAXnid (which crashes with a warning when executed)

How can I add a n.MAX(nid) field to my select query?

In your case, the code should be something similar to the following one:

$query = db_select('node', 'n')->groupBy('title');
$query->addExpression('MAX(nid)', 'max_nid');

You don't use $query = new db_select('node', 'n'); db_select() already returns an object. If you want to clone that object, you should not invoke new on it.

$query->addExpression() returns the alias currently used for the expression you add; it is normally the same alias passed to the method, but it can be different if the alias is already used. In this case, the alias is max_nid if max_nid is not already used, or max_nid_N if the alias is already used; N is an integer that is added to make the alias unique.
Using the alias returned from $query->addExpression() is important when a function is altering a query passed from other functions, such as in the case of a query passed to a hook. In this specific case it is not necessary, as the function that is calling db_select() is also adding the expression.


Add result to view with webservice In my drupal 8 Commerce, I have a view with product and filter criteria.

And I want to know, if it's possible to add result to this view with a result of webservice.

I try to inspect $view->result in hook_views_pre_render

and the result is view\ResultRow with entity Product

Is it possible to add results without creating an entity and from an webservice just read information like this schema:

/myviewurl

Product 1 (from drupal db)
Product 2 (from drupal db)
Product 3 (from drupal db)
Product 4 (from webservice not in db)
Product 5 (from webservice not in db)
Product 6 (from webservice not in db)

Try hook_views_pre_render hook to alter view result if only you need to display result. You just need to prepare the webservice result as per hook_views_pre_render result data.


Importing CSV file to Generate Orders in Drupal Commerce I am using drupal commerce kickstart. I need to generate order-ids with dummy billing and shipping information. How to import csv file with order particulars? Is there any module? How to proceed?

You can do this with the migrate module: https://drupal.org/project/migrate and the add-on module commerce migrate: https://drupal.org/project/commerce_migrate .

This is a coding solution, but I can't think of any other way you could do this without some coding of your own.


Convert former embedded PHP code into a custom block module? Had a Drupal site that used the php filter module. After realizing the security risk I started the process of fixing things up.

Currently the last piece of code is a php snippet I embedded into a view to display the input fields of a content type (called post).

<?php
  module_load_include('inc', 'node', 'node.pages');
  $node_form = node_add('post');
  print drupal_render($node_form);
  $form['buttons']['submit']['#value'] = t('Save and add new');
?>

This is a view block embedded within a panel. Not 100% sure how to take this and make it a custom module that I suppose cloud be a block for me to embed on the panel page.

Update:
Attempted to make the module using hook_block_configure() but when enabled it is not showing up as a block option for me to embed.

<?php

/**
 * Implements hook_block_configure().
 */

function hook_block_configure($delta = '') {

  module_load_include('inc', 'node', 'node.pages');
  $node_form = node_add('post');
  print drupal_render($node_form);
  $form['buttons']['submit']['#value'] = t('Save and add new');

}

Is the correct command being used?

I don't really think embedding a node form in a node view is good in terms of performance because the entire node form needs to be rebuilt, and it can interferer caching mechanisms as well. Probably a ctools madal form with Ajax will do the job better.

You can define blocks in your site using a custom module. Panels will pick them up without any further integration.

function MYMODULE_block_info() {
  $blocks['MYMODULE_post_node_form'] = array(
    'info' => t('Add new'),
    'cache' => DRUPAL_NO_CACHE,
  );

  return $blocks;
}

function MYMODULE_block_view($delta = '') {
  $block = array();

  switch ($delta) {
    case 'MYMODULE_post_node_form':
      module_load_include('inc', 'node', 'node.pages');
      $node_form = node_add('post');
      $node_form['buttons']['submit']['#value'] = t('Save and add new');
      $block['content'] = $node_form; // No need to render() here. Will happen automatically.
      break;
  }

  return $block;
}

I'm assuming you know how to create a basic module with an .info file, change "MYMODULE" to the module name of your choice and how to install them.
If everything went OK, you will see the "Add new" block in admin/structure/blocks page and in "Add content" form in panels.


OK to have multiple media queries for each content type's CSS? Im making a responsive site and im using SASS. Im using the zen theme but any theme that outputted a body class based on the content type (of the page you are on) would be in the same situation.

I started creating media queries and trying to put my css code for all the different content type pages within each one. For this demo code there are 2 content types, but in reality sites are more complicated.

As a result my code soon become difficult to read and I lost the ability to put a break point exactly where I wanted it, eg content-type-A might need one a 700px, but content-type-B might need one at 750px.

@media all and (min-width: 960px) {
    body.content-type-a {
     // styles here
    }
    body.content-type-b {
        // Styles here
    }
}
@media all and (min-width: 500px) and (max-width: 959px) {
    body.content-type-a {
        // styles here
    }
    body.content-type-b {
        // Styles here
    }
}
@media all and (max-width: 499px) {
    body.content-type-a {
         // styles here
    }
    body.content-type-b {
        // Styles here
    }
}

So im thinking that this is a better way to organise media queries. Ive organised the css file by content type, and then put the media queries for that content type's page only. This means that for each page I know where to look for the code being used. It also makes it easy for me put breakpoints exactly where I want them.

// Content type A
@media all and (min-width: 960px) {
    body.content-type-a {
        // styles here
        }
}
@media all and (min-width: 500px) and (max-width: 959px) {
   body.content-type-a {
        // styles here
    }
}
@media all and (max-width: 499px) {
        body.content-type-a {
        // styles here
        }
}

// Content type B
@media all and (min-width: 960px) {
        body.content-type-b {
        // styles here
        }
}
@media all and (min-width: 650px) and (max-width: 959px) {
    body.content-type-b {
             // styles here
        }
}
@media all and (max-width: 649px) {
    body.content-type-b {
             // styles here
        }
}

This does mean that I will probably have multiple but separate media queries with the same breakpoint, is there any issue in this? This seems to me like a really logical way to work but no tutorial or screencast ive seen does things in this way. Are there issues I havnt considered? Does anyone work in this way?

First, I'll say that I'm not sure if I should even be answering this question.  I don't think this is a Drupal specific question.  You may get more/better answers from a forum dedicated to CSS.

Having said that:

There's no reason this shouldn't work.  The CSS is valid, and if it helps you stay organized, I say go ahead.

I guess there could technically be concerns regarding the performance,  but I highly doubt you'd ever be able to see/feel a difference.


URL alias for taxonomy in drupal 7 On a Drupal 7 site with pathauto installed I'm using a view to show all taxonomy terms of a given node. The terms are linked to the term's page. The problem is, that the path of those terms does not use the url alias' that are set for the terms. Is there a way (without programmatically rewrite the view) to use alias in a view?

I know about the globalredirect module, but a redirect is not a clean solution here, in my opinion. And I do not understand why the pathes aren't replaced by there aliases in a view, can someone explain please?

<?php

$field = $view->result;
?>

<?php

    foreach($field as $obj){

     $url = drupal_lookup_path('alias', 'taxonomy/term/'. $obj->tid);

?>

    <a href="<?php echo $url;?>">

<?php echo $obj->taxonomy_term_data_name;?>

        <img src="http://faliam.com/demo/sites/default/files/styles/catalogueimage/public/catalogue/<?php echo $obj->_field_data['tid']['entity']->field_illustration['und'][0]['filename'];  ?>" alt="" height="300" width="368">

<?php

}

?>


Is it valid to use entries in #default_value if they are not in the #options? I have a form. On this form I have a select element, like this:

  array(
    '#type' => 'select',
    '#title' => t('Animals'),
    '#multiple' => TRUE,
    '#options' => array(
      'rat' => t('Rat'),
      'cat' => t('Cat'),
      'dog' => t('Dog'),
    ),
  );

I also have a function called get_suggested_animals($user_id). Let's assume that this code works:

global $user;
print_r(get_suggested_animals($user->uid));

// Array
// (
//    [0] => lizard
//    [1] => cat
// )

Would it be OK to just write:

array(
    '#type' => 'select',
    '#title' => t('Animals'),
    '#multiple' => TRUE,
    '#options' => array(
      'rat' => t('Rat'),
      'cat' => t('Cat'),
      'dog' => t('Dog'),
    ),
    '#default_value' => get_suggested_animals($user->uid),
  );

without testing if default options are on the list of available ones? I know it works (in this example - only 'cat' is selected by default), it does not generate any warnings or anything, but I still feel uncertain if it's legit, or if there are hidden traps I simply don't know yet.

Reading through the code of form_process_select it is obvious that the situation where #default_value is set, but the value isn't a valid option, is not being handled properly:

This piece of code may "fail" in that case:

// If the element is required and there is no #default_value, then add an
// empty option that will fail validation, so that the user is required to
// make a choice. Also, if there's a value for #empty_value or
// #empty_option, then add an option that represents emptiness.
if (($required && !isset($element['#default_value'])) || isset($element['#empty_value']) || isset($element['#empty_option'])) {
  $element += array(
    '#empty_value' => '',
    '#empty_option' => $required ? t('- Select -') : t('- None -'),
  );

In your sample code, you don't set #required for the select field. That is why you don't observe any effect.

However, in the general case, you can't supply a bogus value for #default_value and always be sure that theFAPI will treat it just the same as not set or NULL #default_value.

If change your example and set #required to TRUE, and #multiple to FALSE, you should be able to reproduce a situation where having a bogus default value (such as "lizard") behaves different from the default value being NULL or absent.


Parent and subordinary weights and relations like in menu and taxonomy system module It seems that there is no module in the contribution repository which simulates the behaviour like this of terms in given vocabulary or menu items in a given menu from system modules in Drupal 7. (?) Wouldn't it be an interesting use-case to achieve something like entity trees simultaniously this way, like a task and sub task management, with a given weight and relation to each other to build parent and subordinary relations between them? I know about many reference and relation modules and asked already some specific questions about them and their limits here but I can't find an entry point where I could start to contribute on this special scenario. I can easely drag and drop taxonomy terms or menu items and give them an "order" and sub "order" in their hierarchy already from core and the system "knows" about this order. Not only of one level, also for more levels. It is not visually only. So I can build paths based on that relations. It seems that this is not possible to make with entities and any reference or relation modules out there ? Am I right or is my question asked the wrong way around?

Couldn't you do this with the Relation module, views and Rules?


Adding fields via ajax in form does not show in arrays in form_submit I have am trying to add fields to a form in drupal via ajax.  I am able to have my fields show up on the form without issue but the problem is seeing values of those fields when the form is submitted.  I have read many tutorials on this tonight and I am very confused why my input fields are not even showing up in $_POST.  Here is an example of what I am trying to do:

function add_product($form, &$form_state) {
    //Several other fields but the main one around this issue is below.
    $form['img_mng'] = array(
        'label' => array(
            '#type'     =>  'markup',
            '#markup'   =>  '
Upload Images
',
        ),
        'file1' => array(
            '#type'     => 'file',
            '#size'     => 22,
        ),
        'addMore'   =>  array(
            '#type' =>  'button',
            '#value'    => t('Add More Images'),
            '#ajax' => array(
                'callback'  =>  'add_img_upload',
                'method'    =>  'append',
                'wrapper'   =>  'kc_img_uploads',
                'keypress'  =>  'true',

            ),
            '#prefix'               =>  '
&nbsp;
',
        ),
    );

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

function add_product_validate($form,&$form_state) {
    //Appropriate Validation
    dpm($_POST); //$_POST does not show the fields, not sure how that is even possible since the new fields are added to the form.
    dpm(get_defined_vars()); //None of the variables show the new fields.
}

function add_product_submit($form,&$form_state) {
    // Appropriate database actions....
    dpm($form_state); //No values for new fields.
    dpm($_POST);  //New fields do not even show in the $_POST.
}

function add_img_upload($form,&$form_state) {
    dpm($form_state);  //Does not show the added field below if the button is clicked more than once.
    $num_of_files = 1;
    foreach ( $form['img_mng'] as $key => $value ) {
        if ( preg_match('/^file[0-9]+$/',$key) )
            $num_of_files++;
    }
    $form['img_mng'][sprintf('file%d',$num_of_files)] = array(
        '#type'     => 'file',
        '#size'     => 22,
        '#id'       => sprintf('edit_file%d',$num_of_files),
        '#name'     => sprintf('files[file%d]',$num_of_files),
        '#parents'  => sprintf('file%d',$num_of_files),
        '#array_parents'    => sprintf('file%d',$num_of_files),
    );
    $form_state['values'][sprintf('file%d',$num_of_files)] = '';
    $form_state['file2'] = NULL;
    return $form['img_mng'][sprintf('file%d',$num_of_files)];  //The fields are added to the form every time the button is clicked.  However, the id and name of the elements are only incremented once.  ie file1 becomes file2 but never makes it to file3+.  So I will have one file1 and 1 to many file2's.
}

I originally tried this with managed_file type but I see several people have run into the issue of it returning an empty string.  I was actually able to get it to return the field details but found clicking the upload button on any of the new fields submitted the form?  Any advice on how to correct this issue with managed_file type is highly desired but will settle for file type.  Thanks again.

The form builder function is what Drupal refers to whenever it needs to rebuild the form. Parts of the form should not be built in the ajax callback. Instead, you can return them using something like

function add_img_upload($form,&$form_state) {
  return $form['img_mng'];
}

Your form builder has access to form state information, which allows you to build the form conditionally depending on the state of the form.


Is there an official/recommended way to organize CSS files for a responsive theme? While creating a responsive theme (eg. a bootstrap based sub-theme) is there an official/recommended way to organize CSS files for different media queries? In general I put everything into one CSS file.

1. All In One

mytheme.info:

...
stylesheets[all][] = css/style.css
...

style.css:

body { ... }

p { ... }

...

@media (max-width: 767px) {
...
}

@media (min-width: 1024px) {
...
}

2. Separated CSS Files

mytheme.info:

stylesheets[all][] = css/style.css
stylesheets[all][] = css/480.css
stylesheets[all][] = css/720.css
stylesheets[all][] = css/960.css

style.css, 480.css, 720.css ...

3. Separate CSS Files for Each Media Query Defined in .info File

mytheme.info:

stylesheets[all][] = css/style.css
stylesheets[all and (min-width: 480px)][] = css/480.css
stylesheets[all and (min-width: 720px)][] = css/720.css
stylesheets[all and (min-width: 960px)][] = css/960.css

style.css, 480.css, 720.css ...

4. Other?

I wonder what is the recommended way for this or it doesn't matter (structural, performance wise etc).

This is possibly hard to answer. But all the way are acceptable.

Mostly people don't like reading through a single HUGE CSS file, and maintaining it is very difficult. On the other hand, splitting it out causes extra http requests which could potentially slow things down.

My opinion would be one of two things:

If you know that your CSS will NEVER change once you've built it, I'd build multiple CSS files in the development stage (for readability), and then manually combine them before going live (to reduce http requests).
If you know that you're going to change your CSS once in a while, and need to keep it readable, I would build separate files and use code (providing you're using some sort of programming language) to combine them at build time (runtime minification/combination is a resource pig).

With either option I would highly recommend caching on the client side in order to further reduce http requests.

I also found another question related to this https://stackoverflow.com/questions/16657159/when-using-media-queries-does-a-phone-load-non-relevent-queries-and-images . This will further clear your concept about this.


How to use form_set_error if no form field is involved in the error? In a form_validate hook, I have some custom validation and I'm using

form_set_error('field_foo', "error_message");

to show validation errors. If the validation returns an error that is not linked to a particular form field, how do I show the error, indipendently? (For example: the error is you compiled more that three times the form.)

EDIT: I though to use:

drupal_set_message("error_message", 'error');

From the documentaion for 7.x

  When a validation error is detected, the validator calls
  form_set_error() to indicate which element needs to be changed and
  provide an error message.

So, form_set_error() produce an error linked to a particular field of the form. I needed to display error indipendently in a custom complex validation, being errors not really about a field. I though to use form_set_error() on a random field, but it is not the perfect solution, for the field was highlighted and only the last error produced this way was visible.
drupal_set_message solves this two problem, but the validation success and the form continues like there was no error.

There is a plain solution

form_set_error('form',$error_messages);

Does not highlight any field, and the validation fails as expected. It doesn't allow multiple message, but this can be solved using a little hack

$error_messages = "";
if (type_error_1)
   $error_messages .= "Error Message on First Line
";
}
if (type_error_2){
   $error_messages .= "Error Message on Another Line
";
}
if(strlen($error_messages) > 0){
  form_set_error('form',$error_messages);
}


Exclude the www- append to only one multisite Stock Drupal 7 contains the following in the .htaccess file

  # To redirect all users to access the site WITH the 'www.' prefix,
  # (http://example.com/... will be redirected to http://www.example.com/...)
  # uncomment the following:
  RewriteCond %{HTTP_HOST} .
  RewriteCond %{HTTP_HOST} !^www\. [NC]
  RewriteRule ^ https://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

As per client request, this works just dandy! However, on a multisite installation, one site wants to be excluded from this rule. I tried to get them to remove the auto-www-append, but alas, that failed.

So now I'm in a situation which some multisites (most of them) want the www appended and a small group doesn't want it.

My question: Can I exempt some sites from this rule? Can I throw these exceptions into an apache conf file in /etc/httpd/conf.d/www-exceptions.cnf so that it's not overwritten in a core update?

Unfortunately putting separate htaccess files in each sites folder doesnt work, otherwise it would be quite straight forward.

Perhaps you can use REWRITECOND to do this?

RewriteCond %{REQUEST_URI} yourclientsdomain.com
RewriteCond %{HTTP_HOST} .
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^ https://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]


Error in Views override template "Notice: Undefined offset: 1 in include()" So I am theming a View with a template in my theme folder.

I am getting this error message:

"Notice: Undefined offset: 1 in include()"

This is the code:

<?php print ($fields["title"]->content); ?>

I've tried adding an IF statement like below (is my syntax correct???) and clearing the cache but the issue persists:

<?php if ($fields["title"]->content) { print ($fields["title"]->content); } ?>

P.S. the field is printing, it's just that there is an error message displayed in addition.

Also, by the way, I am using views-view-fields.tpl.php

You need to use isset() to avoid such notices:

<?php if (isset($fields["title"])) { print ($fields["title"]->content); } ?>


A sub-domain for each user blog Is there any module, or a way to get a user blog in a separate sub-domain, such as user1.example.com for user1, and user2.example.com for user2?

Maybe a combination of blog module and Subdomain module:

  Automatically creates subdomains and places content on them. There are
  4 modes:

  User: e.g. "Mary" and content at http://mary.example.com

  Taxonomy: e.g. "Seattle" and content at http://seattle.example.com

  Organic Group: e.g. "MyGroup" and content at
  http://mygroup.example.com

  Content type subdomains: e.g. "News" content at
  http://news.example.com


Reference to another database as a prefix I have a problem referencing another database as a prefix in my settings.php file.I have a master-site[mysite.local] and a slave [sub.local].Both of them are having separate database.I need to check the users table of the master-site as well as the users table of the slave site ,when a user tries to authenticate to the slave which is sub.local.I tried adding the following in the settings.php file of the slave

$databases = array (
  'default' =>
  array (
    'default' =>
    array (
      'database' => 'sub_drupal', //Database for the slave site
      'username' => 'root',
      'password' => '',
      'host' => 'localhost',
      'port' => '',
      'driver' => 'mysql',
      'prefix' => array(
                'default'   => 'sub_drupal.',
                'users'     => 'study.', //parent database
                'sessions'  => 'study.',
                'role'      => 'study.',
                'authmap'   => 'study.',
                'users_roles'   => 'study.',
            ),
    ),
  ),
);

But now it authenticates users only on the parent database.Is it not possible to authenticate users present in the slave database sub_drupal and also in the parent database study.Hope someone could help me with this.Thanks

You have the format wrong for two databases you need something like this:

$databases = array(
  'default' => array(
    'default' => array(
      'database' => 'd7',
      'username' => 'root',
      'password' => 'root',
      'host' => '127.0.0.1',
      'port' => '',
      'driver' => 'mysql',
      'prefix' => '',
    ),
  ),
  'db2' => array(
    'default' => array(
      'database' => 'd7_parent',
      'username' => 'root',
      'password' => 'root',
      'host' => '127.0.0.1',
      'port' => '',
      'driver' => 'mysql',
      'prefix' => '',
    ),
  ),
);

You can then use db_set_active('db2'); to change the connection and begin querying the second database.


Making responses to public nodes only viewable by the creator and the originator I've got a prototype site built in D6, pertinent modules:

CCK
Comment block
Node Comment
Views
Views Or

The site is built around a list of open requests; to solicit a private response. These nodes are of content type Request.

All open requests are public in that all users (logged in or not) can view these nodes.

When a response (comment) is received to an open request it should only be viewed by the author of the original request, or the author of the response.

These responses should be shown to these users on the original node as comments and on a seperate list.

How do I do this?

A quick search on D.o. came up with this forum post asking to do the exact same thing: http://drupal.org/node/919914

They suggest using Node Comment and Content Access together to achieve it, but I'm not certain Content Access will give you the specific option you're looking for.

It would be a start though, and you might be able to hook into Content Access and create a new "Parent Node author" or similar option if you are up for a coding session.


How to move a form field inside a container I have a "Birthday" field and the "date" module automatically adds the countainer around it.

Now I'm adding another field "Show Birthday". How can I display that field within the container?

The fieldset is added by the theme_date_combo() function, which is on the element itself, not the wrapper (i.e. $form['field_birthday']).

To get this to work you'll need to temporarily move the Show Birthday field into the date_combo field, like so:

function MYMODULE_form_article_node_form_alter(&$form, &$form_state, $form_id) {
  $form['field_birthday'][LANGUAGE_NONE][0]['field_show_birthday'] = $form['field_show_birthday'];
  unset($form['field_show_birthday']);

  $form['#validate'][] = 'MYMODULE_article_node_form_validate';
}

Importantly, you'll also need to move that field back to where it originally was when the node form is validated. You won't get any errors if you don't, but the field_birthday value simply won't be saved.

function MYMODULE_article_node_form_validate(&$form, &$form_state) {
  $form_state['values']['field_show_birthday'] = $form_state['values']['field_birthday'][LANGUAGE_NONE][0]['field_show_birthday'];
  unset($form_state['values']['field_birthday'][LANGUAGE_NONE][0]['field_show_birthday']);
}

The above assumes you're making changes to the Article node form, just replace article with the name of your content type in the code. If your fields are inside another fieldset you might need to dig a bit further into the form array to find out how to access the precise field, but the logic will remain the same.

This is the result I get with that code (using admin theme):

I've tested both add and edit node forms and they seem to work perfectly using this method.


Use variable from template.php in block I have a custom table in the Drupal DB, which I need to retrive and use on a few places on the site I'm creating. And I don't like to run soo much PHP in blocks, so I thought that I could get the table value I need, using PHP in template.php in the theme-dir and then just call the variable from a block, using PHP.

That didn't work.. Why and how should it be done?

template.php:

$sub_count = db_query("SELECT count FROM {sub_count}")->fetchField();

block:

<?php $sub_count; ?>

You need to use a preprocess function.  Take a look at template_preprocess_block().  In your template.php you can use:

function YOURTHEME_preprocess_block(&$variables) {
  $variables['sub_count'] = db_query("SELECT count FROM {sub_count}")->fetchField();
}

and can print into the .tpl.php file as you did above.

A few good articles to learn more about preprocess functions are

About overriding themable output
Setting up variables for use in a template (preprocess and process functions)

As a basic overview of preprocess functions, from the second article:

  Preprocess functions only apply to theming hooks implemented as
  templates. The main role of the preprocessor is to set up variables to
  be placed within the template (.tpl.php) files. Plain theme functions
  do not interact with preprocessors.

  Notes:

  Preprocessors are also used for providing template suggestions.
  In versions 5 and below, the function _phptemplate_variables served the
  same purpose. It has been deprecated in 6.
  Prior to Drupal 6.7, for your theme to have its preprocessors recognized, the template
  associated with the hook had to exist inside the theme. When a default
  template exists, copy it to your theme and clear the registry (or you
  should really be upgrading to a later version of Drupal anyway for
  security reasons, at which point you don't have to worry about this).


How can I limit the exposed filters to only display values for which content exists? We have a view for the Basic page content type, which has a Category field that allows to enter multiple values.
All values for Category are displayed (IoT, Cloud, Security), but there are only nodes that use IoT and Cloud. I want to display only IoT and Cloud for the Category exposed filter.

How can I limit the exposed filters to only display values for which content exists?

The view settings are the following.

Format

Show: Content | Teaser
Format: Unformatted List | Settings

Filter Criteria

Authored on (exposed)
Category (field_category) (exposed) | Settings (settings is set to Category tag, selection type = Dropdown)
Author (exposed)
Published (= Yes)
Content Type (= Basic Page)

Sort Criteria

Content: Authored on (desc)

Contextual Filters, Relationship

None

Exposed form

Exposed form style: Better Exposed Filters | Settings
Settings are set to default in Better Exposed Filters

Other

Use Ajax: Yes
Use aggregation: no
query settings: default settings

Here is what we tried. This only gets me the nodes that have a value for field_category and all term values for categories term individually.

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

  $node_storage = Drupal::getContainer()->get('entity_type.manager')->getStorage('node');
  $node_ids = $node_storage->getQuery();

  // This returns all nodes with a value for *field_category*.
  $nodes = $node_ids->condition('type','page')
    ->exists('field_category')
    ->condition('status', 1)
    ->sort('title')
    ->execute();

  // returns all taxonomy terms.
  $category_tree = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->loadTree('categories');

}

This works for me:

function mymodule_form_views_exposed_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  if (isset($form['tid']['#options'])) {
    foreach ($form['tid']['#options'] as $key => $value) {
      // Limit to numeric keys to exclude the 'All' option.
      if (is_numeric($key)) {
        // Start database query.
        $query = \Drupal::database()->select('taxonomy_index', 'ti');
        $query->fields('ti', ['nid']);
        $query->condition('ti.tid', $key);
        $nodes = $query->execute()->fetchAssoc();
        // Remove option if term has no instance.
        if (!$nodes) {
          unset($form['tid']['#options'][$key]);
        }
      }
    }
  }
}

You will probably need to adjust the 'tid' in $form['tid']['#options'] to the Filter identifier as defined in your views' filter settings.
Credits for the quick and efficient database query go to https://drupal.stackexchange.com/a/219368/25154.


Taxonomy sorting in view I am a Drupal newbie using Drupal 7.

I made a taxonomy for documents, and then a view in the views module to list the documents. When the view searches by the taxonomy term, it seems to sort by the term's ID number, rather than the name of the term. I want an alpha sort on the term, not the ID number. Is there a setting to change this that I've missed, or do I need to do programming to change it? Seems like a pretty common situation.

ID   Name
1    Homeland Security
2    Criminal Justice
3    Violence Against Women

will sort as above, not with Criminal Justice first.

Make sure you have Taxonomy: Term selected under the Sort Criteria box and not Taxonomy: Term ID.

I believe the sort that you are seeing under Format -> Settings is where you can select which fields are sortable and the default sort for a view of format: Table.  Making a field sortable creates a clickable link as a header for the table column allowing you to change the sort order by that field.


How to send an SMS message when a Webform is submitted? I am trying to have an SMS message sent when a form is submitted. The form is a quote request and I would like to send a simple message to my phone to alert me.

I have installed the SMS Framework module and the Clickatell module. I have set up an account on Clickatell and have the necessary username, password, and api id.

I can send a message by pasting the url in my browser using the example on the Clickatell site but I don't know how to send a message when the quote request form is submitted.

Using the "Webform Rules" module, you should be able to have the Rules module react on an event like "Webform submitted".

So create a custom rule using this Rules Event, and then add a Rules Action to send an SMS message, similar to what is shown in the video  tutorial "How to send SMS messages" (starting from around 5:25).


Should I activate feature modules on my dev site? I have installed the features module on my dev site.  I am using it to store newly developed site functionality within new modules.  I then install the modules on my live site.

I was wondering, should I activate these modules on my dev site?  I am considering not doing this, because the functionality already exists on the dev site  Activating the new features modules (that are created by functions) seems a bit redundant and even a little dangerous.

Features allows you to assure that the configuration that is described in code (in the features that you the module Features generates) is the current configuration in the DB. If you enable a feature that describes exactly the same configuration that you have in your site no changes are made.

Features is a powerfull way to move configuration between sites (dev, stg and live, between devs sites, etc). I don't understand exactly your setup, but I think you can enable them.

Features help you to know if some configuration change needs to be moved to producton. For example: you start with your features in a clean state (default state) in production and in your dev site. If you make a configuration change in your dev site implementing a new functionality you can see that the feature is in overwritten state: this means that you shold take this configuration change to production when new code is deployed. You can do it by hand, or regenerating the feature and deploying it to production.


How can I remove a theme that is no longer in core? Drush/Drupal 8 is throwing errors because a theme is 'enabled' that is 'missing'. The theme is/was part of core (test_stable), and I'm having difficulty getting it to uninstall.
I understand that the theme code needs to be there in order to uninstall, but this being core makes that difficult. I can manually place the module there locally, but would need to create a patch to actually have it installed (and then uninstalled) on the remote environments via composer.
The "Module Missing Message Fixer" module addresses this scenario with modules, but not themes.
I'm pretty sure enabling this theme in the first place was an accident. I'm hoping someone can help me determine if there is a way to do this w/out creating a patch that installs this old theme.

You can create a theme calling it test_stable. Then, you clear the cache with drush cr and uninstall the theme with drush theme:uninstall test_stable. It will solve your problem.
You don't need to create the whole theme; the test_stable.info.yml file is sufficient for Drupal to recognize the theme as present.
As the test_stable theme has been removed from Drupal after Drupal 8.7.x, and that file isn't present in latest versions, before proceeding with what I suggested, I would run drush updbst and check for pending updates.


Dripping Content for every User a customer asked me about content dripping in drupal. he said that it works in wordpress, but he need that in drupal.

so first of all what is content dripping? He need its for his own customers, who pay for a abo of its site content. So the abo runs for e.g. 10 weeks and the user gets 10 nodes with content on them, e.g.  chapters of a book.

So what he needs now is that the content "dripps" to the user, so the user gets every week a new chapter.

My first intention was to use rules, trigger and node_access to build up a custom set of rules to give the user the permissions once a week.

Then i searched around a lot and found a php script what does excactly that. It gets a list of all members, looks for the date of the abo and checks against a cck field in the node, and if the date is higher than the week of the abo + abo registration date, the content gets accessible.

but it would be much easier and better if i had a module...

So is there any module that does excatly that? As far as i know is content dripping a well known method in online marketing, so maybe there is something?

You could in fact develop your own module to do the above - for example, set a value attached to each user account of number of 'drips' left, which is then decremented by each pageview/similar, and then the total is refreshed at the start of the next billing period, for example by using a scheduled task implemented via the cron system.


hook_options_list not getting fired in a custom module I need to limit taxonomy term reference field options based on another field.This is needed as there are around 1000 terms available for this 'Select' field but I want to limit these options to a minimum using hook_options_list.

But this hook is not getting called from the custom module, not much detail provided on the drupal help too.

Does this hook require any prerequisite so it can be called.

You can use hook_field_info_alter() to attach custom allowed_values_function to your field and implement your own logic there:

function my_module_field_info_alter(&$info) {
  $info['my_field']['settings']['allowed_values_function'] = 'my_module_my_field_allowed_values_callback';
}

function my_module_my_field_allowed_values_callback($field, $instance, $entity_type, $entity) {
  // Custom logic
  return $values;
}


WYSIWYG module w/CKEditor not working drupal 7 I am unable to get WYSIWYG working with my Drupal 7 installation.

I watched a screencast to ensure I installed the module and library correctly, and everything appears to be properly installed. My host has PHP4 by default, but I am able to enable PHP5 and have done so.

The module is installed at: /www/drupal/sites/all/modules
The CKEditor library is installed at: /www/drupal/sites/all/libraries

I have enabled WYSIWYG as the screencast demonstrated and receive no error message at all. I enable and configure the module exactly as it's done in the screencast, yet when I go to edit the plain text version is still there.

I've tried CKEditor on it's own but kept running into a tmp file issue that I could not resolve so abandoned the idea.

At no point is there error text. It just doesn't work.

I have tested this in Chrome and IE9. I have also tried various other libraries and there is no luck. I tried TinyMCE and FCKEditor too.

In order for the CKEditor menu to appear you must select your preferences. After you have assigned an editor to the input format (full HMTL, filtered HTML, etc.) click the edit button to the right. Then select buttons and plugins and tick the items you want to use. Then the editor toolbar will show above the summary. Drove me insane for a month until I figured this out!


Filtering on node whose user ID is equal to the current user In Drupal 6 you can have a filter node.uid = current user. How do you do this in Drupal 7?

You need to add the filter as a "context" (Advanced) where you can supply a default argument. If you context is for a user, like the node author, then you can select stuff like id of logged in user.


styles unlimited value image fields I use unlimited values for image field in a content type, then the images displays one below the other :

Is there a way to render this field differently?
For example every line show me only three images.

Im using display_suite module to display the node content.

CSS. Your fieldset should be wrapped in one big div, with each field-item wrapped in it's own div. I see no reason you couldn't do this with CSS alone.

Unless there's a specific reason you need each line to be exactly three images. In that case you would have to override the field template: https://drupal.org/node/1089656

Then you would have to write some basic PHP logic that counts the number of field items and print those out in a 1X3 display.


Best way to optimize for authenticated user performance? The keyword here is authenticated!

Currently (as far as I know) the de-facto ways to optimize for anonymous access are through static page caches (varnish/squid/boost).

However, as far as I know this doesn't seem to do much good in a scenario where most of your users are authenticated.

Besides the obvious APC, Memcache and throwing money at hardware, what is the best way to performance tune a high-traffic site with mostly authenticated users?

For example: drupal.org, social networks, communities, etc.

I'm more interested in Drupal 6 at the moment so I guess MongoDB doens't apply for now...

Every site is different, thus it will require different tricks to get it working. Here are the ones I use for our sites for logged in performance.

http://drupal.org/project/dbtuner
http://drupal.org/project/advagg
http://drupal.org/project/labjs
http://drupal.org/project/css_emimage
http://drupal.org/project/imageinfo_cache
http://drupal.org/project/cdn

If you REALLY want to know what is causing the slow code, get a cache grind of your site. What all contributes to drupal page execution time?

edit: Looks like the 7.x version of Auth Cache is starting to be developed. Haven't used it but something to look into.

http://drupal.org/project/authcache


How to import Panel configuration from versionned code I have a Panel in my D6 website and I have exported it using the Panels Export Section and I want to know if it is possible to use this code from i a module so I can have a version control over the Panel configuration.
How can I do that. Is there any Panle API I can use??Or how can I export panel export in features??

Thanks


Implement hook_theme in custom module I am developing a custom module and I need to implement a theme. The result of my code below is that the code inside the block does not print because Drupal can't find the theme. I'm using hook_theme() and I'm not sure what I am missing.

Directory structure

jsblock.module code

/**
 * Implements hook_theme().
 */

function jsblock_theme($existing, $type, $theme, $path){
  return array(
      'jsblock_custom_theme' => array(
          'variables' => array('content' => NULL),
          'template' => 'panels_pane__block__jsblock_jsblock',
          'path' => drupal_get_path('module', 'jsblock') .'panels_pane__block__jsblock_jsblock',
      )
  );
}

I've been able to print the block by dropping the the file in the theme templates folder, but not when it is inside the module directory. Can someone please tell me what is wrong with my code?

From the naming of your module and template file, I suppose you want to add a template for a custom block returned by your module.

The reason, that your template is found by adding it to the theme is not that you implemented hook_theme() in your custom module, but the way you named the template. It is found by the theme registry's template suggestions used for the block within your panels pane.

If you want your own theme hook jsblock_custom_theme to be applied to the block, you will have to add the theme hook to your block output by using the theme() function. An abstract example:

/**
 * Implements hook_block_view().
 */
function jsblock_block_view($delta='') {
  $block = array();

  switch($delta) {
    case 'jsblock_jsblock':
      $variables = array();

      // Prepare your block variables here.

      $block['content'] = theme('jsblock_custom_theme', $variables);
      break;
  }

  return $block;
}

Some further suggested checks/improvements:

Check your template path: Keep in mind that drupal_get_path returns a path without trailing slashes. You will have to add a / to your path.
Place your template in a theme subfolder to keeping a cleaner module structure.
Don't name the template like the natively used template suggestions to avoid collisions while the theme tries overriding templates.


How to output view content as grid in custom template? I have created a view for content type xyz with fields F1, F2,F3,F4.

I open the group "advanced", clicked on "Theme: Information".

There are couple of template files, that are used by view.

I chosen the desired template and copy it into to the template folder.

Now, from views module, in theme folder, I opened views-view-grid.tpl.php and copy the content of this file to the file I have created in my template folder.

But output is not coming in grid format.

Is there any way to customize the fields of view in html structure?

what if I want to use html and php

Ok, now that I remember there is another method.

Add the following code to the bottom of your template.php file (located in /sites/all/themes/yourtheme/ folder)

function themename_preprocess_views_view_fields($vars){

      if ($vars['view']->name == "view_name" && $vars['view']->current_display == "block_1"){
        $vars['fields']['title']->content = // do php or whatever you want to it here
      }
    }

replace themename with your theme name
replace view_name with your view name
replace block_1 with your machine name

To add html, Ex:

function themename_preprocess_views_view_fields($vars){

  if ($vars['view']->name == "view_name" && $vars['view']->current_display == "block_1"){
  $a = $vars['fields']['title']->content;
  $vars['fields']['title']->content = "
" . $a . "
";
  }
}

With this method your grid should remain intact.


How to rewrite the ouput html of the image field for a node page? I have an image field where people can upload an unlimited number of photos to a node. By default, drupal 7 outputs these images with html similar to the following:

This is fine, but for my application, I would like to be able to print a unique number to identify the image in the class or as an id - so, instead of field-item even, field-item-012 even, for example.  Should this be done in the template file or in template.php file?

Thanks!

This looks like output coming from theme('field') theme function in field.module. You can override the output by putting the following function in your template.php:

/**
 * Implements template_preprocess_field
 */
function mythemename_preprocess_field(&$vars) {

}

More info on the preprocessor (with examples of how to add additional classes) is here: template_preprocess_field

EDIT:
Actually looking at the theme function, it seems that in your case I think you need to implement both a preprocessor and a template file for your field. So in the preprocessor you create a variable for the class:

/**
 * Implements template_preprocess_field
 */
function mythemename_preprocess_field(&$vars) {
  $element = $vars['element'];
  if ($element['#field_name'] == 'field_myfieldname') {
    $number = 123; // This variable should get the value you wish to attach to the class
    $vars['field_myfieldname_custom_class'] = 'field-item-' . $number;
  }
}

And then create a field template file field--field_myfieldname.tpl.php and put <?php print $field_myfieldname_custom_class; ?> where the class should appear.


Override Ajax throbber icon styles I've been digging around the CSS and JS files but I haven't quite found the exact thing that places the throbber.gif where it appears when clicking on 'previous' or 'next'.

The styling is in system.base.css file and I found this declaration:

.ajax-progress .throbber {
    background: url("../../misc/throbber.gif") no-repeat scroll 0 -18px transparent;
    float: left;
    height: 15px;
    margin: 2px;
    width: 15px;
}

but besides removing the background, the other parts of this declaration do not affect the placement of the throbber.gif.

It's hard to use Firebug and get the styles as the throbber only appears after pushing a button and it's only alive for a few seconds so I've tried screen capturing during the 'throbbing' and measuring distances in the scrn cap in Photoshop and applying but I discovered that the throbber is 'attached' to the button somewhere as it just moves the whole kit and kaboodle... the 'throbber' still appears right next to either 'previous' or 'next' button.

I'm trying to avoid the little jump that happens. When pushing 'next', the 'next' button is shoved left and down a little to make room for the throbber gif, and then shifts back when the new page is loaded.

Any ideas?

You can try Views Sexy Throbber, not exactly that you need, but is still cool...


Cache is not clearing, deleted template is still loading I created a new node template named node--artist-page.tpl.php and it worked fine. but then, (i'm brand new at this) when saw i made some errors with it i tried deleting it but Drupal keeps loading it!

i can tell because i echoe'd out an alert saying the 'my new node tpl is running'

in addition to clearing the cache (5 or more times) I even put it in the trash but it still loads!, anyone have any experience like this? or know how to fix?

am really stuck right now.

Make sure you clear your browser cache as well as Drupals.  Also it's worth checking you're making the changes in the right template files.  You could do this by switching templates in > admin > appeRances .

I hope this helps .


Migrate custom content type from D6 to D7 I started with the migrate_D2D module after did try with migrate 2.5. Same issue for me: Import custom content type into a fresh install of D7.

Do I create custom content type first on the D7 intall? Is there no way to import it via d2d?
Do I create custom CCK field into D7 db before mapping field using:
$query->addField('??','field_D6customCCKfield');
or just
$this->addFieldMapping('field_D7name', 'field_D6customCCKfield'); is enought ?
Do I map subfield like field_D6customCCKfield:data?

OK, it's better but my custom fields aren't created and I get this:

  "field_fichier_joint_lycee" was used as destination field in "field_fichier_joint_lycee" mapping but is not in list of destination fields
  "field_lien_page_lycee" was used as destination field in "field_lien_page_lycee" mapping but is not in list of destination fields

In my class do I add this?

$query->addField('??','field_D6customCCKfield')

You have to create the destination content type on the D7 site. Migrate/Migrate D2D won't handle that for you.

In your migration class you then use:

$this->addFieldMapping(destinationfield, sourcefield);

If you extend the D2D node migration class (DrupalNode6Migration) then you don't need to worry about defining a query.


How to call drupal_bootstrap from custom file in subfolder? I'm trying to call drupal_bootstrap from 'temp.php' in a subfolder called 'custom' my code as follow:

chdir('../');
define('DRUPAL_ROOT', getcwd());
require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

Once I call the temp.php I get Drupal homepage.

I also tried an explicit physical path but with no use, code as follow:

define('DRUPAL_ROOT', '/var/htdocs/drupal7');
require_once '../includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

temp.php located under the following folder structure:

- var
-- htdocs
--- drupal7
---- custom
----- temp.php

take a look at http://drupal.org/project/js they implemented a custom js.php that bootstraps drupal.

/**
 * @file
 * Callback page that serves custom JavaScript requests on a Drupal installation.
 */

/**
 * @var The Drupal root
 */
define('DRUPAL_ROOT', getcwd());

/**
 * @} End of "Required core files".
 */

/**
 * @name Required core files
 * @{
 * The minimal core files required to be able to run a js request
 */
require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
require_once DRUPAL_ROOT . '/includes/common.inc';
require_once DRUPAL_ROOT . '/includes/module.inc';
require_once DRUPAL_ROOT . '/includes/unicode.inc';
require_once DRUPAL_ROOT . '/includes/file.inc';
/**
 * @} End of "Required core files".
 */

// Do basic bootstrap to make sure the database can be accessed
drupal_bootstrap(DRUPAL_BOOTSTRAP_DATABASE);


Start next batch process automatically Is it possible to start next batch_set() after finishing first one?
I've some import functionality which includes 4 steps. The next step takes data processed from first batch process so this is consecutive process which needs to be run one after one.

I have done this before using Core drupal tools. Although I suspect different than your current approach.

I use a drupal Queue. and I fill it with items:

                                                    Queue
          Task1Items              Task2Items          Task3Items              Task4Items
    [---item1---item2---item3|item4---item5---item6|item7---item8---item9|item10---item11---item12]

I put all the tasks, in the ordering for the various steps of your task into a Queue. Then be sure to use a Drupal Reliable Queue:

  There are two kinds of (default) queue backends available: reliable, which
  preserves the order of messages and guarantees that every item will be
  executed at least once. The non-reliable kind only does a best effort
  to preserve order in messages and to execute them at least once but
  there is a small chance that some items get lost. For example, some
  distributed back-ends like Amazon SQS will be managing jobs for a
  large set of producers and consumers where a strict FIFO ordering will
  likely not be preserved. Another example would be an in-memory queue
  backend which might lose items if it crashes.

After inserting all the items. Your batch call simply iterates over the queue you've populated. Use something like Ultimate Cron to setup a group of task workers, or Background Process, or Ultimate Cron Queue Scalar to speedup your workload if you want.

Another handy module to view your queue visually is the Queue UI module. As the core Queue API is a developer API and has no UI by itself. Don't want to write php code to create/manage a queue -- look at Rules Queue.


How to Determine view type (content, user taxonomy, etc) I have inherited a site and I am trying to customise and replace some of the views. I have been told that there are views of various types, content, user, taxonomy, search index, etc. Where in the view after it has been created does it indicate the type of view.

If you are already editing the view, it is also in the Title (so you don't have to navigate away from editing).


Drush shell command not finding module I am using drush 5.7 and in my command line I can type:

drush dl wysiwyg

Works great but whenever I create a shell command with several downloads, or even just one download, it throws an error "No release history was found for the requested project"

Very confused and bizarre on why this would be happenning?

Test.sh

#!/bin/bash
#WYSIWYG
#http://drupal.org/project/wysiwyg
drush dl wysiwyg

Use cd to go to the right directory, you can later comment it out. If you have multisite, you have sites/default renamed or using multisite you have to go to that directory for the drush to work.