Views generated block - how to override filter on some pages? On every page of his new site, the client would like a block with four featured links. This will be fairly consistent throughout the site, but on some pages he'd like to override and display four links of his own choosing.

I'm thinking of using Views and/or Nodequeue for the block, but I am not sure how to provide a default that can be easily changed for some nodes? Is there a better way?

I would create a custom module for this, sounds like it could be done quite easily.

Create an admin interface where the 4 default links can be entered.
Create fields on nodes, where the special links can be entered.
In the block view, try to load the node, if possible check for custom links and use default links if needed.

The above solution is good and flexible if you only want links.

If you instead want node references, with the posibility of getting more data, like an image, taxonomy term etc, nodequeue could come in handy instead, as you with views can setup a more sophisticated display easily. It would however become a bit more tricky to override, but could be done via preprocess functions or hook_views_query_alter.


How does the theme folder work in drupal 7? In Drupal 7, I would disable a theme within the admin section and i would physically rename the theme directory (from themeName to themeName_old), clear cache and restart the server, to my surprise, drupal 7 still picks up the theme (themeName_old).

The only only way i managed to get rid of a theme completely is by removing the the directory from the theme folder. Why is that?

Folder name does not matter. What matters is name of the info file. If you have themeName.info in folder, Drupal knows it's a folder for a theme named themeName.


Remove a contextual filter programmatically Is there a way to programmatically remove a contextual filter from a view? I have a view where, at times, I want to display it without the contextual filter active. This is the code I tried.

function MYMODULE_views_pre_view(&$view, &$display_id, &$args) {
  if ($view->name == 'some_view') {
    unset($view->args);
  }
}

I also tried the same code within hook_views_pre_execute().

How can I achieve this?

To remove a contextual filters just set the $args to empty array or unset the desired arguments unset($args[0]) to remove the first argument an so on:
Here is an example to remove all contextual filters:

/**
 * Implements hook_views_pre_view().
 */
function MYMODULE_views_pre_view(&$view, &$display_id, &$args) {
  if ($view->name == 'some_view') {
    // Remove all filters.
    $args = [];
  }


Body class name has an ampersand I am styling a page in a Drupal 7 site that has the title "Weddings & Private Events" and a URL alias of /weddings-private-events but the body class name is weddings-&-private-events which is invalid in CSS
 See screenshot below:

Is this a bug in D7? I'm using 7.26. Is there a way for me to fix this? I want to style a page specific element without using the node id which may change on export.

It's not a D7 bug - all core code uses drupal_html_class(), which removes any dodgy characters (including ampersands) by running the incoming string through drupal_clean_css_identifier().

Presumably your theme (or a custom/contrib module) is adding a class without sanitising it. Look for something like:

function MYTHEME_preprocess_html(&$vars) {
  if ($node = menu_get_object()) {
    $vars['classes_array'][] = str_replace(' ', '-', $node->title);
  }
}

and change it to use

$vars['classes_array'][] = drupal_html_class($node->title);


create contact form block with prepopulated entity references and send email to content author I am trying to create 3 forms, 2 of them should be made into blocks to show on specific content types. One for anon users and another for logged in users. The other is just a site wide contact form replacement for core Contact.

Anonymous Contact Form: Name, Email, Entity Reference to Content, Message

Logged In Contact Form: Entity Reference to Content, Message (Pull username and email from account)

Site Wide Contact: Name, Email, Message, Term Reference to Category

The Entity reference is important since I will be pulling data from it to populate the email message (like nid, author, etc...)

When a user submits the non-site wide contact forms, Rules should be able to pull the data from the form and send an email to the node author.

Views Contact Form/Core Contact: Can't add entity reference fields (or any fields) to it to link form submissions to content.

EntityForms: Creating forms is easy, but the notification part is convoluted at best with complex but somehow simple data selectors (raw output?) for Rules. Also, the token support is spotty at best (or so I have come across). The prepopulate part worked perfectly, but can't seem to figure out if it is possible to send email based on an Email field or get entity reference tokens like [entityform:field_reference:author:mail]. Doesn't seem to work in Eforms.

Webform: Can't get fields to prepopulate and hide/disable.

Custom: Thinking about just doing this. But I am unsure as to how I can add a entity reference field to a custom (non UI) created form and hide the form.

Can anyone recommend the best solution or at least which module is capable of what I need?

Thank you.

Consider looking at the Bean module. Here is a quote about its project page:

  Think of a Bean as a method to provide new types (compared to node this would be a content type) which then provides an add content interface to create as many blocks as you require (see screenshot below). The bean content can then be placed around the site just like any other block.

As a bonus, the Bean module also works great in combination with the UUID and UUID Features Integration modules.

On top of that, after you become familiar with the Bean module, you might find other cases in your site where you also want to use the Bean module.


drupal commerce membership expiration I used this tutorial for creating a membership with Drupal Commerce which works well.

How I can set membership expiration?

I know I should use Rules, but I do not know how.

If your "membership" is already implemented as a role, you could use the Commerce License module (the Commerce License Role submodule).  In the UI, licenses can be assigned to have default lengths that will automatically be set upon purchase; if you need to change lengths, you can also configure rules to do so.


How can I create a link from an organic groups content node back up to the parent OG? I have used Organic Groups 7.x-2.7 to create groups and can create content which is allocated only to that group. When I am viewing a group content node how do I create a link back up to the parent group? Ideally I'd like to be able to create a views block with this link in it.

burnsjeremy was right that the information I need is available to my node itself. To get this into a views block to position in a different place etc I can use contextual filter on 'Content: Nid' and 'When the filter value is NOT available' set the 'default value' to 'Content ID From URL'. I can then add the fields as normal via views.

Next will be the challenge of getting the parent group of a child group when on the node of a piece of content within the child group.


How do I programmatically install and enable a module? There is a lot resource for doing it in Drupal 6, but I didn't find a solution for Drupal 7.

How can I install and enable selected modules?

There's just one step, using module_enable():

$modules = array('module1', 'module2'); // Array of module names
$enable_dependencies = TRUE; // Whether or not to enable dependant modules

module_enable($modules, $enable_dependencies);


Hook to catch a variable in a POST request to a specific url? I'm testing an external email collection service that appears periodically at certain time intervals on a site.

When a user completes the form, the application can pass the email address as a variable in a POST request to a specific url.

What hook should I use to catch and process the email address at this one specific url?

I thought of using hook_init() something like the following, but I'm not sure if this is a good way to do something like this?

/**
 * Implements hook_init()
 * Check for variable sent via POST and process if found
 */
function mymodule_init() {
  if (drupal_get_path_alias() == "myurl") {
    if (isset($_POST['email_variable'])) {
      <custom processing>;
    }
  }
}

Notes:

The url is a normal node page that already exists on the site.
The form is externally hosted, so a form alter is not an option.

You should use the services module to create an endpoint and use the url where is sent as the path to endpoint.

You don't state which type format the data is being posted to your site but the services module can handle many different types.

Also it's not stated exactly what you want to do with the received data but the services module can be set up to process it in a variety of ways.

You can capture it to a databse table etc
or Here's an example of creating a node using services:
http://www.drupalwoo.com/content/blog/drupal-services-creating-node-from-external-form


Block with #markup urls I have a very big content written as a Basic Page where i want to construct a block with a menu tree structure next to it, in order to let users to click on a link and to guide them to the appropriate section of this huge article. Imagine that there will be some  tags with a specific "id" next to a section of the content for example. How can i implement this and what approaches should i follow?

Thanks in advance.

Create a custom block to only show on that page in full html with links to that content... should work.


How do I ouput a node reference field using a node reference template in Drupal 7? In drupal 6 you can create templates to control how node reference fields are output on a content type basis using the suggestion below:

node-nodereference-exampletype.tpl.php

and then output a node reference field that references 'exampletype' nodes in a node template like so:

$node->examplenodereference[0]['view'];

The file naming conventions and output syntax have changed in drupal 7.

Working off the information at this link http://drupal.org/node/998848 I have tried template suggestions like these with no luck:

node--nodereference--exampletype.tpl.php
node-nodereference--exampletype.tpl.php
node--nodereference-exampletype.tpl.php
node-node-reference-exampletype.tpt.php
and so on...

I have tried adjusting the display mode for the field from teaser to full content etc.

I have tried outputting the field with:

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

and

print $field_screening_movie_title;

and variations on the above.

What is the correct way to name a node reference template file in drupal 7? Do I need to use the render function to output a node reference field using the template?

Thanks

This module has one display formatter named Rendered node, in its setting you can select view mode which referenced node will render in that view mode.

so you can define new view mode and configure referenced node in that view mode

have a look at this post: http://mearra.com/blogs/juha-niemi/drupal-7-custom-node-view-modes


Placing the Rocket Chat block on a page I'm trying to include a Drupal 8 Rocket Chat plugin module in my website. I installed the plugin module, set up a chat server, but I'm failing, of all places, at actually placing the block on a page (/chat). How do I do that? I'm completely new to Drupal.

install the livechat module and rocket_chat module.
  Setup the rocket_chat module.
  Go to [Structure][Block layout]. there you can place the livechat block
  using the "Place block" button.
  This works as a normal block we recommend you add it to a footer or alike
  for performance.

Source: Rocket chat module README.md

In other words, go to /admin/structure/block find the Footer region and click on Place block search for "RocketChat Livechat" and click Place block.


RSS feed not updating using feeds module I have an RSS feed that has not been updated after the initial import. I actually managed to get it to update once using cron, but even that has since stopped working. Looking at the original feed, I see it is being updated, but I'm not getting the updates on my site.

My feed importer settings are as follows:

It is attached to a specific content type
The minimum refresh period is 15 minutes
The option "Import on submission" is checked
The fetcher is "HTTP"
The parser is set to "common syndication parser"
The processor is "node processor"
I respecify the content type in node processor settings
The input format is the default one
"Expire nodes" is set to "never"
"Update existing nodes" is set to "Update existing nodes (slower than replacing them)"

Is there anything else I need to do, maybe configure something in Job Scheduler? I couldn't find a UI for it.

EDIT: Upon checking admin/reports/dblog as per Jeremy's suggestion I found the following error:

  Download of failed with code -1003.

Does anyone know what this means or how I can fix it?

If you look at /admin/reports/status does it say that cron is running?

If cron is running then looking at the watchdog entries (
admin/reports/dblog) around the time it is running may give you an insight.

If that dosn't work then you may have to start putting debug into the modules code to work out what is going wrong.


Migrate field_collections I'm using Drush and the migrate tools to migrate a Drupal 7 site to Drupal 8. The site uses field_collections which do not migrate. The field_collections page indicates it is probably being deprecated and recommends moving to paragraphs.

I have searched, but all of the custom migrations I have found so far have been flat fielded. I need to figure out a way to convert field_collections to paragraphs, or field_collections to custom entities.

I am generally comfortable with PHP and OOP, but building the entities and/or migrations in a new module have me confused.

How would I proceed to build a migration for a content type that included one or more field_collections, so that the field_collection data would be available in Drupal 8?

There's a patch in development for the Paragraphs module to support migration in Drupal 8. This work is currently undergoing development with recent activity. This might be a good way to get a start on your own work and contribute back to the community.


Why delete old redirects? I have many, MANY redirects (thousands).  Most just redirect the system (node/12345) url to the friendly one - but we also have a lot of others.

I have Drupal set to never delete old redirects after they haven't been accessed for X amount of time, but the mere presence of the option to do so makes me think there's a legitimate reason I may want to.

Is there a lot of overhead?  Or is it simply to keep the list manageable?  Do people typically delete them, and if so, what's the time frame?  Six months?  A year?

Whether to keep redirects is an SEO question. Do you have good search results on Google which you don't want to loose. Or you have external sites or even print stuff that point to your old URLs. Then you have to keep them.

If all this is not true, you can safely delete you old redirects.

About the DB:

The redirects are stored in the url_alias table. It has two indexes for the mapping from nid to redirect url and from redirect url to nid. This means that reading is fast even if you have thousands of redirects.

If you are creating a lot of redirects this can get slow. But this will not hit you for a few thousand redirects. If you have millions you have to dive into MySql details (or whatever DB system you are using) and find what you can do about it. Since you are only adding records to the DB table, there's a lot of DB tuning stuff that can help you.


How can I re-Install a site I pulled in from a git repo? I cloned an entire site from git. I cannot install it.

Inside the foo.com/sites folder there are a couple folders. The settings.php file is in the folder dev.foo.com rather than the default folder.(I know this is how multisite is.)

I have added a line in my hosts file
    127.0.0.1       dev.foo.com

I have added a stanza to the http.conf file
    <VirtualHost *:80>
DocumentRoot /var/www/foo.com
ServerName dev.foo.com
    </VirtualHost>

Restart Apache - then I go to dev.foo.com - then I see the It Works! file created by apache rather than the drupal installer that I should see from dev.foo.com
How come?
2.. How can I use the database of the site I cloned? With Backup and Migrate?
EDIT: tried the site in a couple other browsers and I see this

Site off-line
The site is currently not available due to technical problems. Please try again later. Thank you for your understanding.
If you are the maintainer of this site, please check your database settings in the settings.php file and ensure that your hosting provider's database server is running. For more help, see the handbook, or contact your hosting provider.

3...Looks like I need the database before trying to install? Yeah?

If you see "it works", Apache hasn't recognised index.php - either you are being served files from the wrong directory, or Apache isn't configured to use index.php as the default file in a directory. You can test the latter readily: http://dev.foo.com/index.php will show the correct page while http://dev.foo.com/ will display "It works".
mysqldump, backup and restore, PHPMyAdmin ... whatever tools you have available.
Yes, you need a working DB locally to install Drupal. And you need the values in settings.php to work to load your existing DB.


How to solve these errors after running update.php? I´ve updated my D6 site to Drupal 7.
Even after running several times the update.php script, there are two errors still out there:

The following updates returned messages:

system module

Update #7061

  Failed: DatabaseSchemaObjectExistsException: Table system_update_7061 already exists. in DatabaseSchema->createTable() (line 657 of /home/liga/public_html/includes/database/schema.inc).

votingapi module

Update #7201

  Failed: DatabaseSchemaObjectDoesNotExistException: Cannot change the definition of field votingapi_vote.content_type: field doesn't exist. in DatabaseSchema_mysql->changeField() (line 454 of /home/liga/public_html/includes/database/mysql/schema.inc).

Note: I have Voting API module installed in D6, but I haven´t upgraded it yet.

This is what I´ve done:
I´ve deactivated the module in D6, I´ve upgraded everything, and I haven´t updated the module nor try to use it, yet. Maybe the second error will go away when I do upgrade Voting Api to d7. but how about the first error?

Any thoughts will be greatly appreciated. Thanks!

UPDATE: I´ve updated my site to the latest D7 version (7.22 - 2013-Apr-03), and Votingapi module to it´s latest stable version (7.x-2.11 - 2013-Mar-22), and the issues remain exactly the same.

My approach when this happens is to look at the table structure in a clean install of D6 to figure out what fields should be there, and compare that to the table structure in the current site. The issue is occurring because the update script has found something unexpected, so you need to figure out what that is.

In some cases, I've renamed the problematic table in the current database so I've got a copy, created a new table with the correct structure, and then copied the data from the backup table into the new table. I'm on a Mac, and Sequel Pro lets you do this via a handy GUI very easily.

In others, I've looked at the specific update script noted in the error to see what changes to the database it's trying to make - comparing that to the current version of the table can help identify why it's not allowing the update to occur.

This approach usually allows me to most database issues I encounter during upgrades.


Multiple site with multiple databases and single login I have two instances of Drupal on same server instance 1 and instance 2 with different databases. I want the following feature: unique login for both instances.

When I login to instance 1 and if I open the URL of instance 2 on same browser then it should not ask me to log in again.
While any add/update operation is performed on instance 1 or instance 2, the user table should be updated in both databases.

This is not something that it easy to accomplish, your main problem will be to keep track on the users on the two instances, since users doesn't have a Global Unique ID (GUID) but instead uses the user id or uid which is a simple serial id.

You also have to figure out how to handle people editing the same profile at the same time on the two different sites, which easily can lead to some major headaches when site 1 wants to update site 2 and vice versa.

You can take a look at the bakery module which can be used for a single signup system. I'm not sure this will be useful out of the box for you, but you probably could find some inspiration to how you can handle signing in users on multiple sites.

In any regard - you will probably need some custom coding or a clever module I haven't heard off yet.


Argument 1 passed to EntityViewBuilder must implement interface, null given In my Drupal project I have this error:

Recoverable fatal error: Argument 1 passed to Drupal\Core\Entity\EntityViewBuilder::view() must implement interface Drupal\Core\Entity\EntityInterface, null given, called in /Users/team1/workspace/ga_p/modules/field_collection/src/Plugin/Field/FieldFormatter/FieldCollectionItemsFormatter.php on line 33 and defined in Drupal\Core\Entity\EntityViewBuilder->view() (line 110 of core/lib/Drupal/Core/Entity/EntityViewBuilder.php).

I do not know if it's from having created multiple fields (fieldCollections)

But I do not know how to remove this error.

Drupal Version: 8.3.4

Try this patch

diff --git a/src/Plugin/Field/FieldType/FieldCollection.php b/src/Plugin/Field/FieldType/FieldCollection.php
index 8721220..c5335be 100644
--- a/src/Plugin/Field/FieldType/FieldCollection.php
+++ b/src/Plugin/Field/FieldType/FieldCollection.php
@@ -183,19 +183,15 @@ class FieldCollection extends EntityReferenceItem {
   public function preSave() {

     if ($field_collection_item = $this->getFieldCollectionItem()) {
-      // TODO: Handle node cloning
-      /*
-      if (!empty($host_entity->is_new) && empty($entity->is_new)) {
+      $host = $this->getEntity();
+
+      // Handle node cloning
+      if($host->isNew() && !$field_collection_item->isNew()) {
         // If the host entity is new but we have a field_collection that is not
         // new, it means that its host is being cloned. Thus we need to clone
         // the field collection entity as well.
-        $new_entity = clone $entity;
-        $new_entity->target_id = NULL;
-        $new_entity->revision_id = NULL;
-        $new_entity->is_new = TRUE;
-        $entity = $new_entity;
+        $field_collection_item = $field_collection_item->createDuplicate();
       }
-      */

       // TODO: Handle deleted items
       /*
@@ -231,11 +227,10 @@ class FieldCollection extends EntityReferenceItem {
       }
       */

-      $this->newHostRevision = $this->getEntity()->isNewRevision();
+      $this->newHostRevision = $host->isNewRevision();

       // If the host entity is saved as new revision, do the same for the item.
       if ($this->newHostRevision) {
-        $host = $this->getEntity();

         $field_collection_item->setNewRevision();

diff --git a/src/Plugin/Field/FieldWidget/FieldCollectionEmbedWidget.php b/src/Plugin/Field/FieldWidget/FieldCollectionEmbedWidget.php
index 4d6ae09..800383f 100644
--- a/src/Plugin/Field/FieldWidget/FieldCollectionEmbedWidget.php
+++ b/src/Plugin/Field/FieldWidget/FieldCollectionEmbedWidget.php
@@ -104,9 +104,8 @@ class FieldCollectionEmbedWidget extends WidgetBase {
   protected function formMultipleElements(FieldItemListInterface $items, array &$form, FormStateInterface $form_state) {
     // We don't want to render empty items on field collection fields
     // unless a) the field collection is empty ; b) the form is rebuilding,
-    // which means that the user clicked on "Add another item"; or
-    // c) we are creating a new entity.
-    if ((count($items) > 0) && !$form_state->isRebuilding() && !$items->getEntity()->isNew()) {
+    // which means that the user clicked on "Add another item"
+    if ((count($items) > 0) && !$form_state->isRebuilding()) {
       $field_name = $this->fieldDefinition->getName();
       $cardinality = $this->fieldDefinition->getFieldStorageDefinition()->getCardinality();
       $parents = $form['#parents'];

mentioned here.


Migration with duplicate entry error I'm running migration in Drupal 8, but got a duplicate error below.

SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '10b1b105-355b-3c77-8880-a0c247f826f3' for key 'node_field__uuid__value': INSERT INTO     [error]
{node} (vid, type, uuid, langcode) VALUES (:db_insert_placeholder_0, :db_insert_placeholder_1, :db_insert_placeholder_2, :db_insert_placeholder_3); Array

My question, is there any configuration or a migration plugin that I have to specify in my migration config yml file to check for existing record and update if exists, if not exists then create a new record?

I'm using migration_plus module.

I found the answer from someone on Facebook group (Drupal support group)
The answer is to add " --update" argument to the migration command, it will check for existing record and update it, or create new record if not exists.


How to set additional node type options programmatically? When creating a node type programatically, some node type options can be set in hook_node_info, including name, base, description, has_title, title_label, has_body, and help. As far as these node options go, using hook_node_info is cleary the canonical way of doing it.

However, some additional node type options cannot be set using this hook, and I have not yet found any canonical documentation that explains how do do this.

The options I look for a method of setting programatically include:

whether commenting by default are open or closed;
whether the node should be published, promoted, sticky and/or have revisions enabled upon creation;
whether it should display author and date information.

The solution I currently use is to set the appropriate database variables in hook_install for the module that creates my_nodetype to the defaults I want, e.g.:

variable_set('comment_my_nodetype', COMMENT_NODE_CLOSED);
variable_set('node_options_my_nodetype', array('status','promote'));
variable_set('node_submitted_my_nodetype', FALSE);

I figured out this solution by reading the source code to discover that these database variables determine behavior at runtime.  I've not found documented anywhere how one should go about setting these additional node type options.

Is there a better way of doing this than the improvised soluton I currently use?

Is there a better way of doing this than the improvised soluton I
  currently use?

I don't think so. Also I don't find it improvised.

Here's a D7 module I once made that creates a new content type: https://github.com/leymannx/drupal-personality-test/blob/master/personality_test.install

/**
 * Implements hook_install().
 */
function MYMODULE_install() {
  node_types_rebuild();
  $types = node_type_get_types();

  // Add a body field
  node_add_body_field($types['MY_CONTENTTYPE']);

  // Add custom fields
  add_custom_fields();

  // Default to not to be promoted
  variable_set('node_options_MY_CONTENTTYPE', array('status'));

  // Disable comments
  variable_set('comment_MY_CONTENTTYPE', COMMENT_NODE_CLOSED);

  // Hide date and author information
  variable_set('node_submitted_MY_CONTENTTYPE', FALSE);

  // Disable node preview
  variable_set('node_preview_MY_CONTENTTYPE', 0);

  // Disable menu entry
  variable_set('menu_options_MY_CONTENTTYPE', array(0));
}

I experienced just the same and solved it exactly like you via hook_install. If I remember it right, I probably found the code in core when looking how the article and page node types get created.

Related: How to set node type options programmatically (where another tiny module gets recommended you'd need to have everything together in hook_node_info).


drupal 6 using form api number field Currently i am  using drupal six form api. I just wanted to add number field to form but there is no way that i found to add numeric field to form. Is there is any way to do this by using form api drupal6 to add numeric field in drupal 6.

Thanks

The Elements module provides an HTML5 number field element to the FAPI. You can use it like this:

$form['foo'] = array(
  'type' => 'numberfield'.
  'title' => t('Bar'),
  ...
);


How to convert username to hyperlink in comment reply similar to StackExchange? Is there any contributed module or usable functionality which is somewhat similar to StackExchange reply comment, where when we add username with "@" sign, it notifies user. However in my case I would like to convert them into users profile page hyperlink.

For example, if user added in reply @foobar, if username with foobar exists will be converted in hyperlink to foobar profile page.

You are looking for the Mentions module:

  The Mentions module offers Twitter like functionality, recording all references to a user's username - using the [@username] or [@#uid] filter format - from various locations, providing a centralized page to track all mentions (via the Views module).


Let users assign particular roles to other users How can I let a "subadmin" to assign only particular roles to other users?

Just an example: my users can only use the forum if they have the "forum user" role. I would like to delegate the right to a "subadmin" to assign the "forum user" role to particular users, without letting this subadmin to be able to assign any other roles. Or I also want to let this subadmin assign the "article creator" role to others, etc.

Is there a module for that? Or do I have to create my own?

I hope Role Delegation module solves your problem !

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

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


Why did upgrading Drupal 6 cause a huge increase in database traffic? Last week I inherited a several-year old messy implementation of a mid-sized Drupal site. Short version: 1 NFS/mysql server, 3 Apache servers. Everything was overloaded and crawling along. The first thing I did was add a memcached server to the mix which cut the network traffic to the mysql server a lot. Next I got the code all running on local file systems using VCS and only used the NFS mounts for the files directory. Again, network traffic went down.

The CMS was actually an extended install of Pressflow dated at v6.20. I had the bright idea to update this to 6.26, which I did using the Pressflow 6.26 package. Other than a few conflicts with other modules that had to be resolved, this went pretty smoothly. The site works fine.

However, looking at the interface stats on the mysql server, since the upgrade the ethernet traffic is about 100% more to handle the same site load. It's been three days now and the pattern is the same. The network traffic hugely increased corresponding to the upgrade to 6.26. The metric I'm using here is bytes transferred in and out of the DB server. Unfortunately I don't have stats about number of queries run.

What changed between 6.20 and 6.26 that would cause this and is there anything I can do to mitigate it?

Apart from the NewRelic suggestion, which I put in a comment, consider reproducing this issue in a second environment, I assume you do have a staging/testing environment of the site, or at least a local installation. If not, you should get one ;)

Then you can install the devel.module, enable query logging and/or xhprof profiling. Then you can actually switch between the old version and the new one and compare the difference within Drupal. Devel's query logging will tell you exactly which queries are executed and how long they took.


how to create a link field which validates to a set of nodes? Is there a way to set the Validation for a Link field so that authors are only allowed to link to a pre-determined certain set of nodes?

IOW: when authors add a link field to a Node I want them to be limited to only links that are on our site -and- which are webforms or other nodes. I do -not- want them to be able to freely link to other domains.

Ideally, I'd like to be able to limit this set of valid links to nodes of a certain content type, or with a certain tag.

Just to be clear: these are not site visitor form fields, these are the fields for -Authors-.

try the advanced link module:

Provides autocomplete widget for CCK Link field and additional
functionality over standard field:
Variants of URL filtering (external or internal).
Additional filter options by using URL patterns.
Autocomplete link field for internal mode - displays suggestions from existing url aliases and menu items
Option to allow users select url title from predefined list of values
Use cases
You want allow users specify link only to several sites (i.e. specify link only to facebook or twitter)
You want restrict users to specify only internal or external links
You want to use autocomplete suggestion when specifying internal links


How to render CCK image field within page.tpl.php I have my image field's array $node->field_blog_image, but how do I render it as it does in the $page['content']?

The URI confuses me as its simply public://my_image.jpg

file_create_url to get the path of your image:

// $nid is the id of your node
$entity = entity_load('node', array($nid));
$uriImagefromNode = $entity[$nid]->field_image_test_field['und'][0]['uri'];
$urlImagefromNode = file_create_url($uriImagefromNode);
// $urlImagefromNode variable now has the path to the image

I hope this information be useful.


How do I upgrade using GIT? From time to time, there will be minor and major updates to Drupal core. If the release is designated as a security update, we should apply the update as soon as we can. Otherwise, we may choose to apply the update at any time to receive the bug fixes it contains. There are also major release upgrades; we may want to apply these, so we have all the new and powerful features.

How do I upgrade using GIT?

I'd recommend installing and using Drush with GIT instead of only GIT when it comes to security or any other updates. It's really easy to update with drush.

drush up

will update everything

drush up modulename

will only update a module of your choosing

drush up drupal

will only update drupal core.


Display all nodes with actually viewed taxonomy term I have an taxonomy term.

I want to display all nodes that has this term assigned just under the taxonomy term description.

So when user goes to page with the taxonomy he can see the description (that works by default) but also e.g. teasers of all nodes that has this term in field. I guess I have to somehow use view with some filter, but I cannot get it working.

I added the view with block that I've put into structure -> block layout.

I can display all the nodes that has field1 set to term A by adding (to view) Filter criteria field1 = term A. But this is "hardcoded" and I need term A to be another term based on which term page am I visiting.

For example, when I visit page of term A I want to display all nodes that has field1 set to term A. But when I look for term B page, I want to list all nodes with field1 = term B in my view.

There is a default view related to taxonomy term u can make use of it and change accordingly it will solve ur problem.


Does anybody else encounter issues with the new Flexslider 2.3.0 library and Drupal? After installing the most recent version of the flexslider library (2.3.0) the Drupal Flexslider module (7.x-2.0-alpha3) is not able to find the flexslider library anymore.

I get the following error on admin/reports/status:

FlexSlider version could not be determined. Please consult the README.txt for installation instructions.

I realized that the most recent version does not work with the Drupal flexslider module. I downgraded the flexslider JS library to version 2.2.2 and the flexslider Drupal module got recognized.

I used the following JS library version of flexslider ... here you can find all releases


Import date field with feeds I have a csv with a Date field that contains the date in one of the following formats:

dd/mm/yy (ex. 13/11/04)
dd/mm/yyyy (ex. 13/11/2004)

I need to import these dates to my field in the format dd-mm-yyyy, using feeds.

I've tried everything but without success. I have my date field set with my custom date format (dd-mm-yyyy).

What do I need to do in feeds (or even feeds tamper) to import this data?

Thanks.

I've struggled with this question today, and because i didn't found any clear answer here's the method with drupal 8.7:

go to your node type structure, and select the display of your field (for example : DD-MM-YYYY)
go back to the feeds mapping, remove your date entry.
add a new entry for the date, or rebuild the entire mapping if you can't change the order of your csv.
clear the cache
the date work now with your new format


Node Access - Change ownership of node before loading I'd like to change the ownership of a node before it loads on the edit page to essentially transfer ownership of a node from one person to another.  My goal is to give multiple users access to a single node.

I was looking through the Node API hooks and I was hoping that I could use either hook_load or hook_node_load and alter the $node->uid but both say this in the description:

  This hook should be used to add information that is not in the node or node revisions table, not to replace information that is in these tables (which could interfere with the entity cache).

So unfortunately I can't use those hooks.

I noticed that hook_node_prepare allows you to "act on a node about to be shown on the add/edit form", however, it looks like the node access hook already runs before that hook does, because I run into an "access denied" message.

My goal was to avoid having to control access to the node, and instead, just transfer ownership so that it can defer access control to the currently installed node access module (Taxonomy Access) and the "Edit Own Content" permission.  I didn't want to add more custom logic or additional node access modules on top of our existing access modules because it's already complex as it is and not recommended.

Is this the right approach or should I just cave and use hook_node_access (or some other access hook)?  I'm worried about the implications of adding another layer of node access to our already complex system, but if it's the best way to do it, I will.

One possible solution might be to add a User Reference field to the node and add the Users you want to grant access to. Then in hook_node_access, check for that field, and return the proper access for view/edit/delete. Don't forget the value of the author field too, to preserve the original functionality. Basically, if the current UID is in the list of referenced users, return TRUE.

I feel like I have done this in the past in 7, but can't locate any code examples at the moment.


Expose filter like google I create a views and filter node title , with expose filter.
how to change it to work like Google . don't have apply button and filter on time.
is it possible ?

The closest I know you can get by doing just site buiding is by using the views autocomplete filters module which gives the possibility of using an autocomplete widget for the exposed filter by simply checking an option in the exposed filter options in the view.


Unique violation when trying to create a new Field Collection using Rules When I try to create a new field collection for a node I just saved, I encounter following error:

  PDOException: SQLSTATE[23505]: Unique violation: 7 ERROR: duplicate
  key value violates unique constraint "node_pkey" DETAIL: Key
  (nid)=(47) already exists.:

However, if I try to create a node this way, it works fine, so I assume it's a bug in Field collection.

I don't know it it matters, but I'm using PostgreSQL 9.3 as my DB. Also, this issue might be related to the issue about Field Collection Item Duplicate with Rules, but I'm not sure (there is not DB level error mentioned there).

Example of failing rule:

{ "rules_generate_field_collection_items" : {
    "LABEL" : "Generate field collection items",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "node_insert--smlouva" : { "bundle" : "smlouva" } },
    "DO" : [
      { "entity_create" : {
          "USING" : {
            "type" : "field_collection_item",
            "param_field_name" : "field_dodatky_ke_smlouve_fc",
            "param_host_entity" : [ "node" ]
          },
          "PROVIDE" : { "entity_created" : { "entity_created" : "Created entity" } }
        }
      }
    ]
  }
}

For example, this works fine:

{ "rules_generate_nodes" : {
    "LABEL" : "Generate nodes",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "node_insert--smlouva" : { "bundle" : "smlouva" } },
    "DO" : [
      { "entity_create" : {
          "USING" : {
            "type" : "node",
            "param_type" : "mesto",
            "param_title" : [ "node:title" ],
            "param_author" : [ "site:current-user" ]
          },
          "PROVIDE" : { "entity_created" : { "entity_created" : "Created entity" } }
        }
      }
    ]
  }
}

It seems to be working fine, when I'm using event "Before saving content (of type ...)". If you also want to make sure, that it only affects newly created entities (mostly nodes), you'll also want to add condition "Data value is empty" for node:nid or another entity ID.


Need to insert a custom node edit link in the node template I've removed the tabs 'view and edit' from the node content type display.
I need to provide a custom link to edit the particular node based on user permissions.
I've used node/%/edit in node tpl but it does'n't work. Can someone help me with the proper method to achieve this

In your node.tpl.php you have access to current node object $node and you can get the node id.
You can check permissions for current logged user with user_access function

So you can do the next thing in your node.tpl.php

<?php
      if (user_access('your_permission_here')){
       //create link for current node edit
       echo l(t('Edit this node'), 'node/' . $node->nid . '/edit');
      }
?>


Add content type filter on taxonomy page I am new to drupal, i have created 2 different content types i.e. Online and Offline. I want to add content type filter dropdown on taxonomy page to select any one content type from online/ offline. Can anyone help?

Instead of creating the two different content type i.e. online and offline, you should create vocabulary with two terms and then add "term reference" field to that content type.


Executing multiple drush commands I manage a lot of Drupal sites and drush is a lifesaver. I usually script what I need done and then loop over all of the sites.

Many times I need to execute several Drush commands on the same site. Because Drush has to go through the bootstrap process for each command it can be a bit slow. So if I do three commands, Drupal gets bootstrapped three times. Example:

drush cc all
drush dl freds_module
drush en --yes freds_module

So is there any way to run multiple commands with one bootstrap? Something like:
drush "cc all" "dl freds_module" "en --yes freds_module"

The idea is to bootstrap drush only once rather than three times. If it is not possible, I'll still be happy with Drush.

Thanks.

From my personal experience, I would run these tree commands like this:
drush cc all; drush dl freds_module; drush en freds_module --yes. I use semicolons to separate my commands. You can also use the ampersand(&&), drush cc all && drush dl freds_module && drush en freds_module --yes. Here, if one command fails, the rest will not run.


Why is it considered improper to directly add an `onclick` attribute to an HTML element? From a Drupal perspective, why is it considered improper to directly add an onclick attribute to an HTML element instead of using a Javascript behavior?

There's a good answer in the JavaScript subreddit on reddit here. To summarise, here are the reasons provided:

  tight coupling between presentation and behavior
  code runs in the global scope
  makes testing and debugging difficult
  defies progressive enhancement
  quickly becomes hard to maintain
  also it will unbind any previously assigned click handlers which might be an unwanted side effect

Maintainability and testability are the major killers for me here.

There's not much more to add to give a Drupal specific answer. The only two things that comes to mind are the following:

Behaviours are automatically re-applied to any content loaded via AJAX, so if you have an AJAX powered view the click handler will be rebound for you without having to have the function in the global scope.
You don't have to try and locate templates, or hack away at anything just to add a new attribute to an element. For example, if you want a click handler on a node title link, you have to update the template. If you then add a new view mode, but still want to have the click handler listening, then you need to ensure the onClick is on that element as well - this increases the maintenance time and risk of error. If you just use a behaviour, then you can hook onto the title link class and it'll work everywhere.


Template file for Views exposed filter block Views has a great feature where you can expose the exposed filters as a block (Exposed form in block under Exposed form).

So what's the "standard" way to theme these?  Is there a Views template for this (I couldn't find one), or do I theme it with a renamed block.tpl.php?

Actually, although the exposed filter block does not have any template file in the list under Theming information, you can theme it with a views template file like this:

views-exposed-form--MYVIEWNAME.tpl.php

There is an example views-exposed-form.tpl.php in the Views module theme directory.


Trigger a function after saving content type I've created my own search engine with a custom module and some XML.
I would like to add content to the XML file with a custom function in my module.

The content that needs to be added will be coming from some content types. Is there a way to trigger a function after a content type is saved (node saved)?

I know the Rules module can do this, but I need to do it from my custom module (i.e. I need to write a function to achieve this).

Is this even possible?

There are some hooks you can use to do this, but they are all fired before the data is recorded in the database.

Have a look at hook_node_insert(), hook_node_update() and hook_node_presave(). The two first ones are fired only on insert or update, the last one every time.

After, another way to do so, is to add your own submit method on node_form, using the hook_form_FORM_ID_alter() (hook_form_node_form_alter()), which will be fired after the node is properly saved in the database.

If I were you, I would use a setting page for my module to set the content types to use.


How do I clone an existing site? I used the following steps for a D8 site:
 git clone
 composer update (get the packages)
 make a database
 make files folder and settings.php writable
navigate to d8.localhost.install.php (host made and site enabled)

Somehow this did not work do I miss something?

I think it can depend a little on what your goal for the "clone" is.

When we want to make clones of a live site for development or testing or whatever very little works as well as just making an image of the whole server, spinning it up somewhere else and modifying the allowed domains to account for the new IP address.

If you want specific help about some part of the cloning process then perhaps we need more information about what s going wrong; error messages, WOD etc. I notice in your post you mention making the database but not importing the old database, was that step taken?


Quantize/dither image using ImageMagick commands on image style actions Is there a way to use custom imagemagick commands on a image style action.
I'm trying to create a dither effect like the ones shown on the examples on the imagemagik site: http://www.imagemagick.org/Usage/quantize/#dither.

Here's another example: http://caca.zoy.org/study/out/lena5-2-1.png.

The command on the imagemagick website looks like this:

  convert colorwheel.png -dither Riemersma      -colors 16 dither_riemersma.gif

plus

  convert  logo.png  -remap pattern:gray50  mono_remap.gif
  convert -size 15x640 gradient: -rotate 90 \
                   -remap pattern:gray50     mono_remap_gradient.gif

but I don't know how or if it is possible to add this to an action.

Can someone shed some light on this? Is there an alternative method to accomplish this?

Imagecache actions has a 'custom' action which allows you to run your own actions. It may help you, though I used it years ago on a drupal 6 site with GD so can not say for certain if it will work for you.


Adding variation types and sub variation types I'm new to commerce kickstart and am wondering how I can create variation types and "sub" variation types? I would like to create an architecture that allows me to have a variation type fruits and then sub types apples and oranges e.g. - how can I do this?

You can create fruits as taxonomy and assign this to your product type.

Creating Taxonomy:

Go to Administration -> Structure -> Taxonomy.
Click on "Add vocabulary" link to create new taxonomy and it will redirect you to taxonomy form.
Add name(fruits) for vocabulary and save the form and it will redirect you to list of taxonomy.
Click on list terms in row of fruits taxonomy.
Click on 'Add Term' link to add new term for fruits taxonomy.

Assign Taxonomy to product type:

Go to Administration -> Store -> Product
Click on Product types link in top of page and it will redirect you to list of Product types.
Click on Manage fields link in row of Product.
Add Term Reference field and select fruits as vocabulary and save the form.

Selecting taxonomy as menu:

If you want to display taxonomy as menu, you can use 'Taxonomy menu' module.

  Transform any of your taxonomy vocabularies into existing menus
  easily!

Taxonomy menu will create your Taxonomy Term as menu item.

Configuration of Menu:

Edit your taxonomy in admin and select Menu location for taxonomy menu.


Load external php library in custom module I’ve read a lot of topic on this but i can’t figure why it is not working for me.

I’ve built a custom module. It is working fine since return $output; in my controller class is working : I can see in front-end a page with my custom html.

I’ve written a script outside Drupal in order to test. Basically, i connect to a webervice and retrieve all the datas. It’s working fine.

Now, i want to execute that script inside the controller class.

I need to load an external php library to instantiate an object.

In my test php file (outside Drupal) a simple require_once is working.

require_once('nusoap.php');

But it is not working in my controller class.

So, i’ve activated the library module and do :

$path = libraries_get_path('nusoap') . DRUPAL_ROOT . '/modules/contrib/webservices_tr/webservices_dc/src/Controller/nusoap.php';

require($path);

It’s still not working.

Error message indiquactes :

  Error: Class 'Drupal\webservices_dc\nusoap_client' not found

I’m sur the file path is correct because if i do this, i can see the content of the file.

echo file_get_contents(DRUPAL_ROOT . '/modules/contrib/webservices_tr/webservices_dc/src/Controller/nusoap.php');
die();

I’ve also tried this :

in nusoap.php (where there is the class i need to include),

namespace Drupal\webservices_dc;

and in module controller class :

use Drupal\webservices_dc\nusoap_client;

But it is still not working.

Finally, i’ve copied the content of the external php library inside the module controller and it is working.

So i’m nearly sure the issue is related to the loading of that external library.

What is the correct way to load external php library (and wait it is fully loaded) in order to use it in a custom module ?

You cannot require classes with require or library hooks. Nor should you be editing external packages.

You are supposed to require external php packages with Composer. Composer will update the autoloader. Then in your class, you can say:

use ExternalPackage\namespace\Foo;

In the header and Foo class is then usable. Furthermore, you can inject it to the constructor with a little more work.

I would advise using SoapClient instead of nusoap as that is very old.

Regarding SoapClient, here is something I solved recently injecting it proper to my class, because that's the same road you're heading down.

Dependency inject a class with values from a config object?


How to alter the languages available in a form I have a multilanguage site. When I go to edit a node, all the languages of the site are available. I only want some of the active languages to appear in the dropdown for certain users (for various complicated reasons).

In Drupal 6 I did this:

function example_form_alter(&$form, &$form_state) {
    //example_language_list returns an array in the from of   ("en"=>"English") etc
    $languages = example_language_list($form['#node'], TRUE);
    $form['language']['#options'] = $languages;
    if (count($languages)==1) {
        $form['language']['#disabled'] = TRUE;
    }
}

Any idea how I do this in Drupal 7?

OK: found the answer for anyone else. In D7, the i18n implements a callback that happens AFTER the form is rendered, so you need to add a callback as well. So:

function example_form_node_form_alter(&$form, $form_state) {
   $form['#after_build'][] = '_example_form_node_form_alter';
}

function _example_form_node_form_alter($form, &$form_state) {
  //example_language_list returns an array in the form of ("en"=>"English") etc
  $form['language']['#options'] = example_language_list($form['#node'], TRUE);
  if (!i18n_node_language_options($node, 'required')) {
    $form['language']['#options'] = array(LANGUAGE_NONE => t('Language neutral')) + $form['language']['#options'];
  }
 return $form;
}


form_set_error highlight single field in multiple value field Is it possible to highlight only one field with form_set_error when this field belongs to a multiple value field. Let's say I have a field name field_videos which accepts multiples values. After running validation, only video #2 isn't valid :

form_set_error('field_videos', t('Video URL not valid'));

How can I tell drupal to highlight only field #2 ?

Thanks

I solved this by using the delta of the field with the error. In this example, field_acceptable_domains is a multi-value text field and I'm using valid_url to validate each value.

// This is a multi-value field, so we need to loop through the values.
foreach ($form_state['values']['field_acceptable_domains'][LANGUAGE_NONE] as $delta => $url) {
  if (!valid_url($url['value']) && !empty($url['value'])) {
    form_set_error('field_acceptable_domains][' . LANGUAGE_NONE . '][' . $delta, t('The domain %domain is not valid.', array('%domain' => $url['value'])));
  }
}


I would like to duplicate the default product layout grid in a Commerce Kickstart2 site thanks for looking at my post!

I have a Drupal7 Commerce Kickstart2 site.  I recently cloned the default products page so I can create a new page with the same layout.  It worked great except that the product grid that displays on the original default products page doesn't show up on my new page. Instead I have a page where the products just list vertically.  How do I fix that?

Here are the links to the two pages:

https://www.subcitizen.com/products

https://www.subcitizen.com/ames-bros-m-12.html

Thanks so much for any and all info!  I really appreciate it!

Jason

It's because the CSS for the list elements is not being applied

display: inline;
float: left;
min-height: 380px;
height: auto;
margin: 0;
padding-right: 5px;
padding-bottom: 30px;
width: 230px;

So you need to change the CSS selector so that it does apply.

I think that isn't the right answer though, instead of duplicating the template I think you should edit the view so that it shows your brand pages with the brand info at the top rather than put it in the template (if that is what you're doing).  It'll take a while to work out but the site will be much easier to maintain over time.


Create MySQL View in hook_schema() I want to create a MySQL View in hook_schema() for a module I am developing.

Does anyone know how to do that?

I already know how to resolve this issue.

In the .install file instead of trying to create a View in the hook_schema in hook_install you can just use de db_query and create the view. Don't forget in the hook_uninstall to drop the created View.

With my researches i found that is impossible to create a view directly in hook_schema like you do in a table, but if someone knows how to that please share.

Hope this help someone out there.

EDIT: Thanks for the correction kiamlaluno


Unable to see page context in cache context I created a page using Page Manager with Layout Builder. I created a path called: /my-account/{agent_number} witch allows me to create the agent_number string context.  I created my own custom block and able to get the agent_number like this:

$this->getContextValue('agent_number');

Now I build my block and would like to use contexts to cache my block:

/**
 * {@inheritdoc}
 */
public function build() {
  $data = get_expensive_data($this->getContextValue('agent_number'));
  return [
    '#theme' => 'my_custom_module',
    '#data' => $data,
    '#cache' => [
      'contexts' => ['agent_number'],
      'max-age' => 86400,
    ],
  ];
}

I created my own CacheContext service:

<?php

namespace Drupal\earc_card_details\Cache\Context;

use Drupal\Core\Cache\CacheableMetadata;
use Drupal\Core\Cache\Context\CacheContextInterface;
use Drupal\Core\Plugin\Context\ContextRepositoryInterface;

/**
 * Defines the AgentNumberCacheContext service, for caching.
 *
 * Cache context ID: 'agent_number'.
 *
 * @see \Drupal\Core\Session\AccountProxy::setAccount()
 */
class AgentNumberCacheContext implements CacheContextInterface {

  /**
   * The context repository service.
   *
   * @var \Drupal\Core\Plugin\Context\ContextRepositoryInterface
   */
  protected $contextRepository;

  /**
   * Creates LanguageInterfaceContext object.
   *
   * @param \Drupal\Core\Plugin\Context\ContextRepositoryInterface $context_repository
   *   The context repository service.
   */
  public function __construct(ContextRepositoryInterface $context_repository) {
    $this->contextRepository = $context_repository;
  }

  /**
   * {@inheritdoc}
   */
  public static function getLabel() {
    return t("Agent Number");
  }

  /**
   * {@inheritdoc}
   */
  public function getContext() {
     $contexts = $this->contextRepository->getAvailableContexts();
     // Agent number is missing here.
     return $contexts['agent_number'] ?? '';
  }

  /**
   * {@inheritdoc}
   */
  public function getCacheableMetadata() {
    return new CacheableMetadata();
  }

}

The problem is that $this->contextRepository->getAvailableContexts() does not return the agent_number context.  Is there a way to get the page bulder context to appear here?

Try a route based context extending RouteCacheContext:

Example:

<?php

namespace Drupal\Core\Cache\Context;

/**
 * Defines the RouteCacheContext service, for "per route name" caching.
 *
 * Cache context ID: 'route.name'.
 */
class RouteNameCacheContext extends RouteCacheContext {

  /**
   * {@inheritdoc}
   */
  public static function getLabel() {
    return t('Route name');
  }

  /**
   * {@inheritdoc}
   */
  public function getContext() {
    return $this->routeMatch->getRouteName();
  }

}

You can use this core example and get instead of the route name a route parameter.

You can improve cache efficiency and prefix the context name with route.. Cache contexts are ordered hierarchically, so that the caching system can remove specific cache contexts already covered by more general ones when merging cache metadata.

This leads to further considerations. If the block is only visible on a specific route and the route has only one parameter, then the core route context would have the same results as the custom context. So a specific route context only makes sense if you have too many cached block variations because the block is used in different routes or because of other route parameters and the context aware block plugin doesn't have already an appropriate cache context.


Loading taxonomy term custom field data I have a vocabulary "holiday_types" with taxonomy terms "ski" and "beach". I have a custom field on these taxonomy terms "field_activityid" which relates to a legacy system.

I want to load all these terms so that as I loop through a list of regions I can add the taxonomy_term ID to an entity reference field, and I need to get the legacy activityid to query an external API.

I'm having issues with entityQuery not recognising 'holiday_types' as a bundle of taxonomy term, I tried 'type' too. I'm also not getting entityQueryAggregate working either so thought I'd pose the question here to see if there's a 'proper' way of querying custom fields on taxonomy terms.

Adding example here which produces "QueryException: 'bundle' not found"

$holidayTypesQuery = \Drupal::entityQueryAggregate('taxonomy_term');
$holidayTypesQuery->conditionAggregate('bundle', 'holiday_types');
$ids = $holidayTypesQuery->execute();
$storage = \Drupal::entityManager()->getStorage('taxonomy_term');
$entities = $storage->loadMultiple($ids);

If I change 'bundle' to 'vid' it errors with the following:

    Drupal\Core\Database\DatabaseExceptionWrapper: SQLSTATE[42000]:
Syntax error or access violation: 1305 FUNCTION purkidev.holiday_types does not exist:
SELECT holiday_types(taxonomy_term_field_data.vid)
AS vid_holiday_types
FROM {taxonomy_term_data} base_table
LEFT JOIN {taxonomy_term_field_data} taxonomy_term_field_data
ON taxonomy_term_field_data.tid = base_table.tid
INNER JOIN {taxonomy_term_field_data} taxonomy_term_field_data_2
ON taxonomy_term_field_data_2.tid = base_table.tid
HAVING (holiday_types(taxonomy_term_field_data_2.vid) = :db_placeholder_0); Array ( [:db_placeholder_0] => )
in Drupal\purkitest\Controller\PurkitestController->simple() (line 89 of /Users/steve/Sites/purkidev/modules/purkitest/src/Controller/PurkitestController.php).

Trying without Aggregate:

$holidayTypesTIDs = \Drupal::entityQuery('taxonomy_term')
  ->condition('vid', 'holiday_types')->execute();
$taxonomyTermStorage = \Drupal::entityManager()->getStorage('taxonomy_term');
$holidayTypes = $taxonomyTermStorage->loadMultiple($holidayTypesTIDs);
foreach ($holidayTypes as $holidayType) {
  dpm($holidayType);
}

This works but when I dpm($holidayTypes) I don't get anything in the fields:

[fields:protected] => Array
    (
    )

...hence why I was trying aggregate as I thought it brought together the fields.

So, can I access the value of my field_activityid from here and if so how? Have tried various random things like

dpm($holidayType->field_activityid->value())

which produces

Call to undefined method Drupal\Core\Field\FieldItemList::value()

Following berdir's comments here's the latest whole function... which now works - thanks all for helping my syntax!

public function simple() {

$holidayTypesTIDs = \Drupal::entityQuery('taxonomy_term')
  ->condition('vid', 'holiday_types')->execute();
$taxonomyTermStorage = \Drupal::entityManager()->getStorage('taxonomy_term');
$holidayTypes = $taxonomyTermStorage->loadMultiple($holidayTypesTIDs);

$markup = '';
foreach ($holidayTypes as $holidayType) {
  $markup .= "
Holiday Type: ";
  $markup .= $holidayType->getName();
  $markup .= "

TID: ";
  $markup .= $holidayType->id();
  $markup .= "

ActivityID: ";
  $markup .= $holidayType->field_activityid->value;
  $markup .= "

";
}

return array(
  '#markup' => $markup,
);

}

Your entity query works fine (without aggregate). dpm() doesn't work in D8 for content entities, try kint() instead, but that will also be misleading.

Your last attempt was almost correct: ->value is a property (a magic property, actually), not a method. So this should work fine:

$holidayType->field_activityid->value

As referenced already in a few questions, have a look at http://wizzlern.nl/drupal/drupal-8-entity-cheat-sheet; it's a bit old but it's still a great overview of the Content Entity (Field) API.

If you do want to use dpm()/kint(), then always run it on $entity->toArray(). That will give you an array structure of the fields, you can translate that 1:1 to object properties and it will work fine. For deltas, use $holidayType->field_activityid[1]->value; not providing it defaults to delta 0.

And, no, you definitely don't want an aggregate query. You need that if you want to COUNT() or SUM() some values of your entities.


Possible to have conditional Tokens? In using URL aliases, is there a way to have conditional token usage? An example of what I'm looking for is:

I have programs on my page, each having their own unique program code.

By default, say my program is General Arts, the URL alias would be /programs/general-arts

However, sometimes, the programs may have multiple program codes due to being taught in different locations.

What I'd like (if it's possible at all) is when I create another program with the same name (let's use General Arts again for example), except it has a different program code, I'd like the URL alias' to then be /programs/general-arts-C123 for the first one and /programs/general-arts-D321 for the second one because they're the same program, just different program codes (due to being taught in different locations). Pretty much appending the course code to the end of the URL to distinguish the two.

Or is the only way to do something like this is to manually override the URL alias and put the custom URL in?

You can just return an empty string with your custom token.

Or you could make your custom token return the title and course code and handle it that way.


How to set root term in Hirerchical select I have a vocabulary like the following:

Parent 1
  Child 1
  Child 2

Parent 2
  Child 3
  Child 4

I want the dropdown only to show Parent 2 and its childs, so I changed the root_term id to parent id

'root_term' => termid, // Enter a term ID here if you want to display only terms below the term with that ID.

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

if($form_id == 'myform_node_form')
{
  $form['field_myfield']['und']['#config']['params']['root_term']= termid;
}

Please let me know how to achieve this ??

As I explained in this link ,this is bug in HS module.

finally i found your mistake
in your code , in hs_taxonomy.module
in function hs_taxonomy_hierarchical_select_root_level($params) you don't consider
$params['root_term'] and in every hs this item bypassed by 0 value

<?php
$terms = _hs_taxonomy_hierarchical_select_get_tree($params['vid'], 0, -1, 1);
?>

must be

<?php
$terms = _hs_taxonomy_hierarchical_select_get_tree($params['vid'], $params['root_term'], -1, 1);
?>

if user not set parent in content_taxonomy settings for term reference it passed 0 by default.

please apply this patch to your module.
just notice for this work correctly you want select (not duplicate second level select option)
Save term lineage
in Hierarchical Select configuration in Save lineage part.
i test it ,working like a 'BENZ'


How to display the same views exposed form block twice? I'm trying to display the same views exposed from block twice. Once in the left nav and once in content top. With multi block I can clone the block and I am able to display both. However, I would like the left nav form to have less exposed filters.

The problem is that in hook_form_alter() and hook_preprocess_views_exposed_from() there are no unique identifiers that I can check to alter the form. It runs through the hooks twice but I cannot seem to know if I am dealing with the left nav form or the content top form.

Does anyone have any insight into this?

I tried the code below which works for views 2 and was going to create my own block and render the form. But I cannot get the code to work for views 3.

$view = views_get_view('brands');
$view->set_display('page_2');
$view->init_handlers();

$form_state = array(
  'view' => $view,
  'display' => $view->display_handler->display,
  'method' => 'get',
  'rerender' => TRUE,
  'no_redirect' => TRUE,
);

$output = drupal_build_form('views_exposed_form', $form_state);
$blocks['content'] = $output;

Am I looking in the wrong direction?

This code worked for me. I'm using Views 6 Alpha 4.

$view = views_get_view('your_view');
$view->set_display('the_display_you_want_that_have_a_exposed_block');
$view->init_handlers();
$exposed_form = $view->display_handler->get_plugin('exposed_form');
print $exposed_form->render_exposed_form(true);


Rules module: How do I execute code just before content is deleted? I'm trying to execute some code right before content is deleted. The Rules module has events for

After updating existing content
Before saving content
After saving new content
After deleting content

However, none of these execute my code at the right time. Is there a way to easily add new events? If so, where should I hook? My knowledge of the Drupal core is very small.

Background:

What I'm doing is updating a menu link that links to the content in the database, but as the update code only runs after having deleted the content, there isn't any row to be updated because Drupal apparently deletes menu items that link to non-existent content.

You might be looking to implement hook_delete().

You can also check node_delete_multiple() in node.module, if you want to have an idea of what Drupal core does when it delete nodes...there's other hooks that get called as well.


Drupal 8 Accessing Menu Tree in a Block's JS How can I pass the menu into a block's javascript?

I am trying to build a block for a custom mobile menu (client wants specific logic/animations/etc) and use that in Structure > Block layout > Main Navigation.

They want me to do it via jQuery for reasons, but I cannot find how to get access to the menu tree in the javascript of the block. I feel like this should be simple enough with the API but the documentation seems to be all focused on PHP.

Any help is appreciated, thanks!

NOTE

I did find this post but I'm honestly not sure what it is trying to do, it is from about 4 years ago, and making/bundling libraries to just access the menu seems like it is probably not the ideal way to do this. Also I am using Bootstrap's theme and I do not see a template.php.
Thanks again!

The documentation is inevitably focused on PHP, since Drupal is written in PHP and server-side renders.  And the answer to getting info from PHP/server side to JS/client side is not really Drupal specific.  Like any other situation of this ilk in web development, you have two basic choices.  Either annotate your HTML with enough elements, IDs and classes that you can pull the necessary info out of the DOM, or expose an endpoint containing the info in a convenient-for-JS-consumption format like JSON for your javascript to fetch.

As for the latter, if you don't feel like rolling your own endpoint, there seem to be one, two three and maybe more modules, although I cannot vouch for any of them.


Output different menus based on site section (URL) I'm working on a Drupal 8 site that's divided up into sections that correspond to projects. So URL aliases will be /project-a/some-content, /project-b/some-content, etc.

I'd like to support creating menus—for each section—in the admin, and to render those in the primary navigation region based on which section you're in.

My assumption is that somewhere I need a switch statement that uses URL segment 1 for case and specifies a configured menu to load for each case, or a default.

Is this the best approach? Where would I do that, if so?

You should be able to use standard path based visibility conditions.

Just put both menu blocks into the same region, and configure each to only be shown on paths like /project-a/* and the other on /project-b/* and so on.


Hide payment options with rules My client wants to bypass payment options if a custom chooses shipping outside the US. I have figured out some of the parts using rules but I cannot figure out how to 1) skip the payment selection step or 2) hide the other shipping options.

For option 2, would I disable all payment methods in the Admin UI and then, using a series of rules, enable the ones I want based on the shipping method selected?  That seems a little backward but it might work.

I would recommend you to disable payment method by default on which you have to operate(enable/disable). In rules you can check the condition where you have to enable the particular payment method & in action you can simply enable the payment method you want to.

This is what I have done in one project...as in action part it's hard to find remove option.


Good method/approach in improving advanced Drupal development skills This might be a bad place to post this, but here it goes.

I'm looking for a good approach in bettering my knowledge/skills to Drupal. I have been using it since D5 and I still feel like I am so 'unskilled' in doing advanced development. I still struggle with how to create a custom module or hook alter methods properly (with 1 try and not 10) through the template.php file. I have seen others create some insane modules or scripts and I just boggles me on how they come up with it.

It's always been trial-and-error for me, and sometimes I get it to work but never can get an answer on 'Why that worked'.

I have been a php developer for over 10+ years, touched a bit of C#, Ruby, and Java but nothing hugely professional. I have always been driven to continue pursuing Drupal development. Just so incredibly overwhelming still at times. I have high hopes to make the next DrupalCon in Austin, Texas.

I have found the Drupal Examples module to be a great starting point for learning enough to develop my own modules, or to aid in solving a particularly thorny problem I'm having.

There's also the Devel and Dev Themer modules, which help to illuminate some of what's going on behind the scenes.

Then there is the API documentation, which I personally have a harder time understanding until I read some of the comments.

These are the ones I use most; others will probably chime in with others, which I know about but lack enough experience in to form a helpful opinion.


Content Types linked to Content Types Using Drupal (v7.22) I'm creating a site that lists different cars. The editor of the site wants to be able to add different stats to the cars. But they don't know exactly which stats they will need so want the ability to add stat themselves. So for example they can set up two different stats where they fill in values:

Content
  Content Type (Stat)
  Title = Stat A
  Default Value = 10
  Min Value = 0
  Max Value = 50

Content
  Content Type (Stat)
  Title = Stat B
  Default Value = 20
  Min Value = 0
  Max Value = 40

Then they can add those stats to a new Content Type that they have created. When they add a type of Stat it will include the Default Value but it can be changed:

Content Type
  Title = Car
  Stat A Value = 10
  Stat B Value = 20

Content Type
  Title = Lorry
  Stat B Value = 30

Finally they can create Content of that Content Type and the Stats will use the value for that Stat by default but they can change it. I will create rules so that the entered values must be within the min/max set by the Stat.

Content
  Content Type = Car
  Title = Car Name
  Stat A Value = 15
  Stat B Value = 18

Can this be done with Drupal?

I'm hoping this answer works for you. If you're wondering if you can set a default value for a field in a content type when adding new content, the answer is yes.


How to Add Existing File to file_managed. File is Blank I have manually added some files to the Private Files directory on my Drupal 7 site and wish to add them to the file_managed table in the database.

This is what I have attempted:

Load the existing file with the file_get_contents($PATH_TO_FILE) function.
Used the file_save_data($loaded_file, $destination, FILE_EXISTING_REPLACE) function save the file and add it to the Database.

The Result:

The expected file is in the File System but is 0 bytes and blank
File is added to Database

The main issue is that the existing file isn't getting uploaded properly and is being displayed blank. How can I fix this?

Make sure that your $loaded_file is a file object enter link description here not just a file content.


Problem with submitting ajax form with autocomplete I've been a newbie to drupal and trying to add feature to our corporate website (this module
called 'userpasswords2' searches database of local mailsystem passwords).
I'm using AJAX autocomplete and modification of the form.

AJAX autocomplete works fine, I can choose the user but I have a problem - I cannot submit the form by enter key. If I submit it by hittin 'submit' button by mouse, everything works fine. But I cannot submit it from keyboard.

I would like it to work like here https://api.drupal.org/api/drupal - user enters for example 'hook', chooses what he/she needs, hits enter, then hits enter again and get the result!

So again - clicking submit button works fine, hitting 'enter' key doesn't work.

Googled a lot, the workarounds I've found doesn't work for me. Please help.

function userpasswords2_menu() {
  $items = array();
  $items['userpasswords2'] = array(
      'title' => 'User passwords',
      'page callback' => 'drupal_get_form',
      'page arguments' => array('userpasswords2_form'),
      'access callback' => TRUE,
      'type' => MENU_CALLBACK,
  );
  $items['userpasswords2/ajax_username_autocomplete_callback2'] = array(
      'page callback' => 'ajax_username_autocomplete_callback2',
      'type' => MENU_CALLBACK,
      'access callback' => TRUE,
  );
  return $items;
}

function userpasswords2_form($form, &$form_state) {
  $form = array();
  $form['user'] = array(
      '#type' => 'textfield',
      '#title' => t('Введите имя пользователя'),
      '#autocomplete_path' => 'userpasswords2/ajax_username_autocomplete_callback2',
      '#executes_submit_callback' => 'TRUE',
  );
  $form['box'] = array(
    '#type' => 'markup',
    '#prefix' => '
',
    '#suffix' => '
',
    '#markup' => '
',
  );
  $form['actions']['submit'] = array(
    '#type' => 'submit',
    '#ajax' => array(
      'callback' => 'userpasswords2_callback',
      'wrapper' => 'box',
    ),
    '#value' => t('Submit'),
  );
  return $form;

}

function ajax_username_autocomplete_callback2($string = "") {
  $matches = array();
  if ($string) {
    $result = db_select('my_domain_passwords')
      ->fields('my_domain_passwords',array('fullname','password'))
      ->condition('fullname', db_like($string) . '%', 'LIKE')
      ->range(0,10)
      ->execute();
    foreach ($result as $user) {
      $form['custom']['username'] = $matches[$user->fullname] = check_plain($user->fullname);
      $form['custom']['password'] = check_plain($user->password);
    }
  }
  drupal_json_output($matches);
}

function userpasswords2_form($form, &$form_state) {
$form = array();
$form['user'] = array(
    '#type' => 'textfield',
    '#title' => t('Введите имя пользователя'),
    '#autocomplete_path' => 'userpasswords2/ajax_username_autocomplete_callback2',
    '#executes_submit_callback' => 'TRUE',
);

$form['box'] = array(
  '#type' => 'markup',
  '#prefix' => '
',
  '#suffix' => '
',
  '#markup' => '
',
);
$form['actions']['submit'] = array(
  '#type' => 'submit',
  '#ajax' => array(
    'callback' => 'userpasswords2_callback',
    'wrapper' => 'box',
  ),
  '#value' => t('Submit'),
);
return $form;
}

function userpasswords2_callback($form, &$form_state) {
  if ( (!empty($form_state['custom']['username'])) && (!empty($form_state['custom']['password'])) ) {
    $output_string = $form_state['custom']['username'] . " : " . $form_state['custom']['password'];
  } else {
    $output_string = "No such user: " . $form_state['values']['user'];
  }
  $username = $form_state['custom']['username'];
  $password = $form_state['custom']['password'];
  $element = $form['box'];
  $element['#markup'] = $output_string;
  return $element;
}

I think you need to do this:

$form['actions']['submit'] = array(
    '#type' => 'submit',
    '#ajax' => array(
      'callback' => 'userpasswords2_callback',
      'wrapper' => 'box',
      'event' => 'click'
    ),
    '#value' => t('Submit'),
  );

just add 'event' => 'click' you your submit ajax element in the form. This must be done for all forms you want to be submitted through #ajax.


How do you negate a rule in Rules 2? I'm working with a Drupal 6 tutorial (but building in Drupal 7) that uses the Rules module, and I notice that some of the rules the presenter is building rely upon negation (e.g. "if NOT blah-blah") Am I missing something, or is this possibility not available in the Drupal 7 version of the module?

Rule conditions may be negated by checking the Negate checkbox ("If checked, the condition result is negated such that it returns TRUE if it evaluates to FALSE.") You can't negate a rule event or an action.


How do I get the (date)timestamp since last cron run? I'm building a module but am stuck..
I need the timestamp from the previous cron as I run a hook_cron job so I can check which nodes are new and email those.

So I need the date/time stamp from the last cron run but how do I get there'?

A UNIX timestamp of the last cron run can be fetched with:

variable_get('cron_last');

If you need to, you can easily manipulate a UNIX timestamp with PHP's date function.


Is it possible in Views to get parent term of parent term all the way up a tree I'm at my wits end on this. Here's my situation:

I have a content type which references a Vocabulary of geographical areas which actually has 6 levels ("Island Chain > Region > Province > City > District > Precinct").
I've used Hierarchical Select to control data entry, and set it so that the entire lineage is kept in each attached node - the node should be attached at the precinct level.

Now, what I want to do is to create a View which allows me to display a table of nodes, grouped by geographical area, and at the same time allow the user to select the geographical area he wishes to display (preferably at any level in the hierarchy).

I've already done something like this using a View by Taxonomy formatted as a table, attaching the content, and then displaying in each table row the node data, the term, and the parent term. However, this only seems to work for two levels (ie a Vocabulary where there is only a parent/child relationship), and I'm stuck on displaying the bottom level, then its parent, then its parent again, all the way up to the top and all in the same row so that I don't get duplicate lines and can group/aggregate data at all these different levels.

By the way, it seems that the Hierarchical Select Views module still does not work for D7 - or at least, I can't find out how to display it.

use Client-side hierarchical select" module.

1)Force selection of deepest level (If checked the user will be forced to select terms from the deepest level.)

2)Parent (Allows to select a parent term to use only a subtree of a vocabulary for this field.)

3)Labels per hierarchy-level


Module to easily insert link to other content into textarea? Title pretty much says it all. I want a button or something next to the textarea that will let you link selected text to a particular node.

I am guessing that I should be using the WYSIWYG module with a particular editor, and happy to hear suggestions as to which combination.

CKEditor with CKEditor Link does the trick.


adding data attribute to option value in Drupal 6 I have a form, like this:

        $form['my_case_type_list']=array(
            '#type'=>'select',
            '#title' => 'Issue Type',
            '#options' => $my_list,
            '#multiple' => false,
            '#attributes'=>array('size'=>1),
            '#weight'=>2,
        );

where $my_list is an array, like this:

$array[0] = 'string 1'
$array[1] = 'string 2'
$array[2] = 'string 3'

This renders a dropdown list with the array key as the option value and the array value as the option text.  I want to use a multi-dimensional array to also provide each option with a data id.  An array like this:

$return_array[0] = array('name' =>'string 1', 'description'=>'description for string 1');
$return_array[1] = array('name' =>'string 2', 'description'=>'description for string 2');
$return_array[2] = array('name' =>'string 3', 'description'=>'description for string 3');

and have the description field be used, in the option value, as a data attribute.  So, it would be rendered like this:

<select name="my_case_type_list" size="1" class="form-select" id="edit-my-case-type-list">
    <option data-desc='description for string 1' value="0">String 1</option>
    <option data-desc='description for string 2'  value="1">String 2</option>
    <option data-desc='description for string 3'  value="2">String 3</option>
</select>

Is this even possible?  Can you assign a multi-dim array to a form?  When I do, it just create option groups and each dimension of the array becomes an option.

thanks
jason

This has been asked previously for Drupal 7 and there is no great answer so it's unlikely to be possible in Drupal 6 the answer seems to be implementing a custom theme_select


Pass custom query strings across website I want to use some custom query strings for tracking purposes and for visibility rules. The goal is, to provide a link such as www.example.com#affiliateid=1 and the string is preserved through the whole web session. Ideally, # should be used instead of ?, as it is ignored by google and prevents duplicate content.

However, each time I click a link on my site, the parameters are lost.

I don't really know where to start -
are they usually passed and is this a problem with url rewrite or would I have to learn drupal that it should append the strings to each link?

Thank you!

That's probably a bit messy. Have you considered using cookies or even the session variable?

Edit:
Turns out it might actually be possible and without much fuss! Thanks OP for raising the question and making us question (and research) this a bit.

Drupal has a hook to rewrite all URLs (hook_url_outbound_alter), which coming to think about it makes total sense.

Basically you can use this hook to grab a session variable or a cookie - you still want to store it somewhere just so that in case you lose it at some point you can easily retrieve it and recover the navigation - and rewrite the URLs according to whatever rules you need.

Here's a sample for future reference, not mine just adding it here so we don't lose it if the link breaks:

<?php
/* Helper function for using strpos with an array of strings.
 */

function strposa ($haystack, $needles) {
    $bool = false;
    foreach ($needles as $needle) {
        if (strpos($haystack, $needle) !== false) {
            $bool = true;
        }
    }
    return $bool;
}

/* Implements hook_url_outbound_alter
 */

function rl_int_url_url_outbound_alter(&$path, &$options, $original_path) {
    //Break path into an array
    $arr = explode('/',$path);
    //Get country list and exclude paths
    $c_list = array('us','ca');
    $system_paths = array('admin', 'user', 'sites', 'system');
    $exclude_paths = array('node/add', 'sitemap');
    //If the path contains a system path in the first argument, or has an exclude path in the full path string, do not set a prefix.
    if (in_array($arr[0], $system_paths) || strposa($path, $exclude_paths)) {
        $options['prefix'] = '' ;
    //OK, it's not an excluded path. If the path doesn't have the prefix already, add a prefix.
    } else if (in_array($arr[0], $c_list) == false) {
        $c = $_COOKIE('Drupal_visitor_country');
        $l = $_COOKIE('Drupal_visitor_language');
        $options['prefix'] = $c . '/' . $l . '/';
        //Special case: remove "home" from the path if it's the home page, so that it's example.com/us/en instead of example.com/us/en/home.
        if (drupal_lookup_path('alias', $path) === 'home') {
            $path = '';
        }
    }
}
?>

Hope this helps!


How to make a parent - child taxonomy list How can I make a category page displaying all my 100+ taxonomy terms in a parent/child way (something just like http://www.dmoz.org/)?

-parent
--child
--child
-parent
...

Yes above answer works, but parent terms are showed at top of view, so it's nice to remove them. I use Views Hacks module , and only check Selective Exposed Filters.
For filter select Taxonomy term: Parent (selective) and choose is not one of all
You can view my view at http://www.attorney-directory.net/practice-areas


How to make all images in Views display at same dimensions My preview (thumbnail) images won't seem to display on my Views 3*16 grid page and my edits in the image Filed don't seem to make a different.  How do I ensure and force the Field image (cell) in the said Views page to show all the image content consistent in size? The image is a link to the actual page Node content. I'm probably missing something trivial, but you help would much appreciated.

(I'm using Bootstrap 3, Views 3.7 on Drupal 7.28).

Thanks.

You have to chose an image style for your images. Set up your grid image style first under admin/config/media/image-styles


adding css in fresh.css nothing change is made I'm using sub theme zenophile and created sub theme and now in my own sub theme I added some css rules in fresh.css but it's changing nothing.

I did clean refresh, but nothing happening...

You need to tell your theme to pickup your css file.. You can do that using .info file of theme using below code..

stylesheets[all][] = fresh.css

Clear Drupal Cache to see changes...

For more information refer Writing theme.info files...


Negative number of stock after order many products I have a website made using Drupal 7 and Ubercart 3.6, and with the uc_stock module.

If client is adding to cart product qty more, then set in stock level that is doesn't generate any errors or notices. And stock level is decrementing to negative number, see screenshot:

Is it possible to disable Negative number of stock level?

Solution of this problem is Ubercart Out of stock Notification module.


xautoload not loading class I have a PHP class that I have developed to mediate the interactions with a client's SSO web service. The class needs to be used by both a Symfony site and a Drupal 7 site. On the Drupal side, I've dropped a copy of the class inside the SSO module I'm developing, and I'm attempting to use xautoload to load it, but I was getting a class not found error when attempting to instantiate an object from it.

Now I'm just dumping the output of get_declared_classes() to the message area with dpm(), and I don't see that it has loaded the class.

Here's the structure of my module

client_sso/
|
--client_sso.info
--client_sso.module
--includes
  |
  --ClientSSO.php

My client_sso.info looks like this

name = Client SSO
description = Integrate Drupal with Client SSO service
package = AARP
core = 7.x
dependencies[] = xautoload (>= 7.x-5.0)
files[] = includes/*.php

I disabled and re-enabled the module to rebuild the module registry and cleared all caches, but it appears to be cheerfully ignoring the file with the class.

I have verified that I can directly load the class with

module_load_include('php', 'client_sso', 'includes/ClientSSO');

What should I try next?

Several things to consider.

*.php only looks in the folder itself. **/*.php also looks in subdirectories recursively. This seems ok in this case, but I want to mention it for other visitors.

The files[] = .. always requires clearing the cache.
If you have problems with this, drush rr (Registry Rebuild) is useful.

The core class registry with files[] = .. does not work for classes in namespaces.
xautoload does not change this.

The Registry Autoload module makes namespaced classes work with the core registry. But I don't know how well it works with the *.php-style wildcards.

Or, you can use hook_xautoload() to register additional namespace directories.


How to integrate an exported Rules component in a custom module? i have created list of component fields in a Drupal 7 module, copied the exported Rules code and then pasted it into our custom module

But it is not working. Any ideas how to get it to work?

This is my exported Rule:

$rule = '{ "rules_faircent_rules" : {
"LABEL" : "Faircent Rules",
"PLUGIN" : "rule set",
"OWNER" : "rules",
"TAGS" : [ "Faircent Rules" ],
"REQUIRES" : [ "rules" ],
"USES VARIABLES" : {
  "fc_home_city" : { "label" : "Home city ", "type" : "integer" },
  "fc_pin" : { "label" : "Pin Code", "type" : "integer" },
  "fc_loan" : { "label" : "Loan Type", "type" : "integer" }
},
"RULES" : [
  { "RULE" : {
      "PROVIDE" : { "result" : { "result1" : "Calculation result", "result" : "Calculation result" } },
      "IF" : [
        { "data_is" : { "data" : [ "fc-home-city" ], "value" : "10" } },
        { "data_is" : { "data" : [ "fc-pin" ], "value" : "5" } },
        { "data_is" : { "data" : [ "fc-loan" ], "value" : "12" } }
      ],
      "DO" : [
        { "data_set" : { "data" : [ "fc-loan" ], "value" : "35" } },
        { "data_set" : { "data" : [ "fc-home-city" ], "value" : "15" } },
        { "data_set" : { "data" : [ "fc-pin" ], "value" : "25" } },
        { "data_calc" : {
            "USING" : { "input_1" : [ "fc-home-city" ], "op" : "+", "input_2" : [ "fc-pin" ] },
            "PROVIDE" : { "result" : { "result1" : "Calculation result" } }
          }
        },
        { "data_calc" : {
            "USING" : { "input_1" : [ "result1" ], "op" : "+", "input_2" : [ "fc-loan" ] },
            "PROVIDE" : { "result" : { "result" : "Calculation result" } }
          }
        }
      ],
      "LABEL" : "Calculate over all "
    }
  }
]

}
}';

$configs['commerce_checkout_order_email'] = rules_import($rule);
echo '<pre>';
print_r($configs['commerce_checkout_order_email'] );

Above code is not working for me. What will be exact solution?

Here is what's needed to integrate your exported Rules component in a custom module:

<?php
function MY_MODULE_NAME_default_rules_configuration() {
  $configs = array();
  $rule = '{ "my_exported_rule" : {
    "LABEL" : "My Exported Rule",
    ...,
  }
}';
  $configs['my_exported_rule'] = rules_import($rule);
  return $configs;
}
?>

So to use such exported Rule, you need to run it through the function rules_import(). This will change the exported Rule in a format that is  usable for the Rules module.

To reuse this example:

Replace MY_MODULE_NAME with the machine name of your module.
Replace the value used for $rule by the content of your exported rule.
Make sure to use the machine name of your rule (= my_exported_rule in my sample) as the key in $configs.

In the sample contained in the question, the machine name of the rule is rules_faircent_rules, though that is NOT what is used in the $configs ... Therefor I think you should correct your code like so:

$configs['rules_faircent_rules'] = rules_import($rule);
echo '<pre>';
print_r($configs['rules_faircent_rules'] );

Refer to the articled "Drupal 7 - Defining rules within a module using PHP" for some more details.


Using multisite for a ReSTful API and Auth Strategy My Situation

I have a small app with a public interface. I'm interested in making an API for this to be used in a mobile environment and even eventually as a public API. I want to keep it simple with the priority on aspects like security and performance.

My Plan

Why Drupal? Well, I know Drupal and I can envision a setup where I have 2 sites. www.mygui.com (default) and api.mygui.com (API). All database structure is determined by the work done in the default site. Using the Drupal Services Module (and only a few other necessary core modules) on the API site I plan to allow authenticated updates to the database by way of JSON and the drupal_internal_api.

My Problem

I already have a prototype (not in drupal) that uses tokens. I'm new to services and don't really know all its limits and capabilities yet. This looks promising but still in the pipeline: Drupal Services Auth Token Module. I would like advice or resources regarding a good authentication strategy. For example, which is best? Keep the user base the same with assigned "API Uer" roles or have a completely separate user base specifically for the API site? Keeping in mind that an API username is a long term setup where the username/password or token should not change until the API user is ready with a new app release? Can I have a nice GUI for users to manage their API site credentials on the default site?

This can certainly be achieved without any multisite. Meaning you could always house the API on the same site and proxy the path api.mysite.com to mysite.com/api thus allowing it to be invisible to the user. (Make sure your webhost supports mod_proxy or you have some external proxy you can use for this task)

As for the actual authentication, I don't bother with tokens. Use credentials. This way people can get and keep a session (in line with however long you want them to based on session_lifetime in your settings.php) - After an initial call to a log in path, they can then subsequently call the API over and over again by passing the unique session they are assigned.

Go with the single site approach and use web proxy magic to make it look like a different domain. Easy enough.


Upload text file without extension I am working in a project where I have to upload files thru a Drupal site. I am having an issue since the files I am trying to upload have not extension. The files are text files, but without the .txt at the end and to be honest I don't mind if Drupal add .txt after the file name.

How do I define a file validator for files without extensions?

I found out that leaving the extension with an space instead of empty work, but I wonder how secure it this solution. In my case I remove the file a second after I upload it as I am only interested on its content.

Here is the code that worked for me:

$validators = array('file_validate_extensions' => array(' '));
$file = file_save_upload($i, $validators);

Thank you.