Drupal

Segalanya mengenai Drupal

Check embedded Views return empty or not

Views providing alternative to embed into any template using hook of views_embed_view(). However, it produce still produce a bunch of division HTML tag although the return result is zero or empty. To make sure there should be no rendering for empty Views by using this snippet:

$view = views_get_view_result($name, $display, $args);
$result = count($view);
if ($result) {
//do something here
}

 

Project d.Note

Project D.Note is a new idea from successor  of Kripkorn Studios. It is a revamping project that focus on new objective and target.

Not like previous KS site, project d.Note now will serve more tutorials, notes and guidelines for Drupal development, designing and consultations. It is solely own under Hadafi Solution & Resources company.

As for maintenance planning to keep this project running in subsequence five years, I will introduce premium content which only can be read by valid subscribers. Subscriptions may undergoes annually.

Currently we are working in organising for managing current content to make it ease for learning process. Meanwhile pushing all non-Drupal related articles to be put under Archive categories which can be access freely by readers.

Working on designing theme, it already take about four months to come out with fresh and simplified design. The more important is to introduce new learning guidance that can help readers to understand and learn about Drupal more clearly. Previous project already set a benchmark that we hope the same in this project.

As for now, we are targeted project d.Note can be go live in around May 2015. But its all depend on time consuming and resources availability. This project right now touched 65% development progress. We might undergoes various and lots of testing before totally released into live server.

Fail updating database structure Drupal 7.34

In version Drupal 7.33 there is an updating database structure to lengthing the block title from 64 characters to maximum length which is 255. This update can be apply without any error if site was built fresh from Drupal 7. However for those experience migrating from Drupal 5 or Drupal 6, its may or may not display an error during this process.

You may encounter this error during updating process:

Update #7009

Failed: PDOException: SQLSTATE[01000]: Warning: 1265 Data truncated for column 'title' at row 192: ALTER TABLE {block} CHANGE `title` `title` VARCHAR(255) NOT NULL DEFAULT '' COMMENT 'Custom title for the block. (Empty string will use block default title, <none> will remove the title, text will cause block to use specified title.)'; Array ( ) in db_change_field() (line 3020 of /home/parasolx/public_html/includes/database/database.inc).

If you look at error, it comes from the data in the tables that block the scripts to update the table structures. After drill down into database, I found that row 192 contain "NULL" in title field which is should not happen. This is because title is mandatory when creating a new block.

However, previous framework Drupal may bypass this validation which cause the block to create without a title. To counter this problem, I run this script:

UPDATE block SET title = '' WHERE title IS NULL;

You can use this SQL within your database management programme such as phpMyAdmin. After that try running to update the database again. Mine works perfectly after troubleshoot this error.

Fixed problem of search index stucked with EntityMalformedException

Drupal 7 comes with internal search function to list out all content based on keywords or phrase out of the box. Drupal will conduct a frequent indexing of words in body content during cron running.

However this process maybe or have tendency to stuck at certain percentage due to migration from major Drupal version, slow or interruption of connection during posting new content or database corrupted.

Usually error found in Logs:

Notice: Trying to get property of non-object in _node_index_node() (line 2632 of /home/public_html/modules/node/node.module).

EntityMalformedException: Missing bundle property on entity of type node. in entity_extract_ids() (line 7405 of /home/public_html/includes/common.inc).

Notice: Undefined property: stdClass::$type in _node_extract_type() (line 370 of /home/public_html/modules/node/node.module).

The root of cause you will getting EntityMalformedException is because in Drupal 7 all content must have at least one node revision. To check either the data in search index was corrupted or not, just run these script in your phpMyAdmin.

SELECT n.nid FROM node n LEFT JOIN search_dataset d ON d.type = 'node' AND d.sid = n.nid WHERE d.sid IS NULL OR d.reindex <> 0 ORDER BY d.reindex ASC, n.nid ASC LIMIT 0,1;

Result return as nid number, which either you need to recheck for that node or just delete it.

Sometimes only one node which cause this search index halted. Or you can just run these SQL to detect either all nodes has revision ID.

SELECT nid FROM node WHERE nid NOT IN (SELECT nid FROM node_revision);

If results shows multiple nid, means a lot of "bad" node that need to be clean up. It can be re-edit each one of nodes or either you can directly delete all of them through database.

After that, run cron and check either there is an increase percentage of search index progress.

However, please make sure you do a backup before doing anything to database structure.

Fixed problem with loop infinite Redirect module

Combine two powerful module, PathAuto and Redirects in Drupal 7 preventing from error of "Page not found" when any changes done for content title. This is one step on how to make Drupal really powerful in handling SEO method.

PathAuto responsible in creating human readable for URL creation instead of default Drupal path "node/*" pattern based on token replacement. While Redirects functioning to create an URL alias and redirect to new path when there is a changes in old alias.

However the big problem of infinite loop may occur if old alias being used again in same content. This might cause content not able to be access by user or generate fatal error because Redirects keep loop redirect at the same content.

I already patched from development version Redirects which fixed these problem. This patched search any duplicate redirect alias, delete it and return HTTP code instead 301 into 202.

Kindly to download it below since today (5 Sept 2014), there is no latest stable version release.

[Snippet] Drupal 7 DB Query

Drupal 7 implemented database abstraction layer which built up on top with PDO. This make Drupal 7 in one step forward more faster for querying data from database compare to Drupal 6. Below are the snippets that can really useful for drowling custom data from database.

$uid = 1;
$result = db_query('SELECT n.nid, n.title, n.created
FROM {node} n WHERE n.uid = :uid', array(':uid' => $uid));

// Fetch next row as a stdClass object.
$record = $result->fetchObject(); 

// Fetch next row as an associative array.
$record = $result->fetchAssoc();

// Fetch data from specific column from next row
// Defaults to first column if not specified as argument
$data = $result->fetchColumn(1); // Grabs the title from the next row

// Retrieve all records into an indexed array of stdClass objects.
$result->fetchAll();

// Retrieve all records as stdObjects into an associative array
// keyed by the field in the result specified.
// (in this example, the title of the node)
$result->fetchAllAssoc('title');

// Retrieve a 2-column result set as an associative array of field 1 => field 2.
$result->fetchAllKeyed();
// Also good to note that you can specify which two fields to use
// by specifying the column numbers for each field
$result->fetchAllKeyed(0,2); // would be nid => created
$result->fetchAllKeyed(1,0); // would be title => nid

// Retrieve a 1-column result set as one single array.
$result->fetchCol();
// Column number can be specified otherwise defaults to first column
$result->fetchCol($db_column_number);

// Count the number of rows
$result->rowCount();

[Snippet] The right way rendering field in Drupal 7

The best part in Drupal 7, it was totally a massive upgrade from Drupal 6 by introducing of entity concept. This is really awseome since we do not depend on "nodes" concept anymore. Supporting the entity, more and less in D7 we could expand used of Field API which provide custom field design through GUI.

Its not stop there. For themers, we able to print and render any field from any entity bundle directly into theme files without sacrifice write up SQL query code. By using node_load(), we load everything node data for nid targeting.

The best practices to render specific field is using field_get_items(). After that pass this array into field_view_value() to get the raw value and sanitize them before rendering.

$node = node_load($nid);
$field = field_get_items('node',$node,'field_name');
$output = field_view_value('node',$node,'field_name',$field[0]);
print render($output);

This method make the render value aware towards language tag. Direct calling raw value like this:

$value = $node->field_name['und'][0]['safe_value'];

is not a best practice!

[Snippet] Pass multiple filter values in Drupal Views

One the most powerful function in Drupal Views is contextal filter. This function able to the Views module to filter the result based on argument specific in contextual filter item. However, the problem with this function is it unable to support multiple filter by "OR" conditions. The best solution to counter this problem is by altering its query before Views rendering the results.

By creating custom module, we leveraging hook_views_query_alter().

function my_module_views_query_alter(&$view, &$query) {
  dpm($query,'query');
}

This will shows all query that available in all views. So, we specific by add condition to target specific views.

if ($view->current_display == 'my_current_display') { ... }

Then, by adding query altering for an array:

foreach ($nids as $nid){
  $query->where[1]['conditions'][] = array(
   'field' => 'node.nid',
   'value' => $nid,
   'operator' => '=',
 );

After that we add some more query altering:

$query->where[1]['type'] = 'OR';

Save and clear your cache.

[Snippet] Menus get duplicate in Admin Menu for Drupal 7

During developing web using Drupal 7, sometimes we caught with duplication of menus when using Admin Menu. This problem usually happen when we accidently move or modify administration menu to other menu blocks. Actually it shoudn't happen because Drupal was designed to able handle any modification make to any menu.

However when someone with inexperience with Drupal system, installing unstable modules that interfere with Drupal menu system could leads this problem happened unexpected.

For solution:

We need to log into database either through bash or using GUI like PHPMyAdmin.

Then, ran this query:

DELETE FROM `menu_links` WHERE `menu_links`.`module` = 'admin_menu'

After that ran this query:

DELETE FROM `menu_links` WHERE `menu_links`.`module` = 'system'

These two query will delete all menus under admin menu. You will face blank menu if try to refresh any page.

After that go to "admin/build/modules".

Here Drupal will rebuilt all menu system again based on default configuration.

If it still didn't work, repeat this step again but instead go to "admin/build/modules", run directly in web browser bar, "http://example.com/update.php". This step will force Drupal to refresh all default configuration and modules installed.

Lastly clear all Drupal cache manually.

Good luck.

[Snippet] Getting all permission list index based on roles

Drupal handle permission through roles base assigning to user. One user could apply multiple roles. Each of roles specified various permission define in hook_permission(). To get list of index for all permission for one user, we could used this snippet.

<?php
  $roles = array(3 => 'Project Manager');
  $roles = $user->roles;
  $permissions= user_role_permissions($roles);
  print_r($permissions);
?>

Then by using user_access, we can define custom arguments like below:

<?php
if(user_access("create project content")) {
 print '<a href="/node/add/project">New Project</a>';
}
?>
Subscribe to Drupal