title: How to render custom entity

text:
# Question
Title: How to render custom entity
I have a custom entity and i don't have any fields in the entity.Instead what i have is:- Adding custom entity page has a form where we have several fields where we are able to fill all the fields in the form.Now the problem which i m facing is is: how to display the entity added on my\_entity/% page?

# Answer
if you are using Entity API, you can take a look to this article http://www.trellon.com/content/blog/creating-own-entities-entity-api and to the example\_task module:

The process works like this:

```
  // Your entity view path
  $task_uri = 'task/%example_task';
  $task_uri_argument_position = 1;

  $items[$task_uri] = array(
    'title callback' => 'entity_label',
    'title arguments' => array('example_task', $task_uri_argument_position),
    'page callback' => 'example_task_view',
    'page arguments' => array($task_uri_argument_position),
    'access callback' => 'entity_access',
    'access arguments' => array('view', 'example_task', $task_uri_argument_position),
    'file' => 'example_task.pages.inc',
  );

/**
 * Task view callback.
 */
function example_task_view($task) {
  drupal_set_title(entity_label('example_task', $task));
  return entity_view('example_task', array(entity_id('example_task', $task) => $task), 'full');
}

```

This will invoke to the function in entity/includes/entity.controller.inc folder of Entity API module:

```
  /**
   * Implements EntityAPIControllerInterface.
   */
  public function view($entities, $view_mode = 'full', $langcode = NULL, $page = NULL) {
    // For Field API and entity_prepare_view, the entities have to be keyed by
    // (numeric) id.
    $entities = entity_key_array_by_property($entities, $this->idKey);
    if (!empty($this->entityInfo['fieldable'])) {
      field_attach_prepare_view($this->entityType, $entities, $view_mode);
    }
    entity_prepare_view($this->entityType, $entities);
    $langcode = isset($langcode) ? $langcode : $GLOBALS['language_content']->language;

    $view = array();
    foreach ($entities as $entity) {
      $build = entity_build_content($this->entityType, $entity, $view_mode, $langcode);
      $build += array(
        // If the entity type provides an implementation, use this instead the
        // generic one.
        // @see template_preprocess_entity()
        '#theme' => 'entity',
        '#entity_type' => $this->entityType,
        '#entity' => $entity,
        '#view_mode' => $view_mode,
        '#language' => $langcode,
        '#page' => $page,
      );
      // Allow modules to modify the structured entity.
      drupal_alter(array($this->entityType . '_view', 'entity_view'), $build, $this->entityType);
      $key = isset($entity->{$this->idKey}) ? $entity->{$this->idKey} : NULL;
      $view[$this->entityType][$key] = $build;
    }
    return $view;
  }
}

```

As you can see the content is finally rendered through a render element using "Entity.tpl.php"

A way to add your customizations to the view in order to render elements which are not fields may be extending from "EntityAPIController" and writing builContent function:

```
class ExampleTaskController extends EntityAPIController {

      public function buildContent($entity, $view_mode = 'full', $langcode = NULL, $content = array()) {
        $wrapper = entity_metadata_wrapper('example_task', $entity);
        $content['author'] = array('#markup' => t('Created by: !author', array('!author' => $wrapper->uid->name->value(array('sanitize' => TRUE)))));

        // Make Description and Status themed like default fields.
        $content['description'] = array(
          '#theme' => 'field',
          '#weight' => 0,
          '#title' =>t('Description'),
          '#access' => TRUE,
          '#label_display' => 'above',
          '#view_mode' => 'full',
          '#language' => LANGUAGE_NONE,
          '#field_name' => 'field_fake_description',
          '#field_type' => 'text',
          '#entity_type' => 'example_task',
          '#bundle' => $entity->type,
          '#items' => array(array('value' => $entity->description)),
          '#formatter' => 'text_default',
          0 => array('#markup' => check_plain($entity->description))
        );

        return parent::buildContent($entity, $view_mode, $langcode, $content);
      }
    }

```
> 1 votes

---
Tags: forms, entities
---


# Question
Title: Export/Import Content Types/Contents to another Drupal site (version 6)
I'm looking for something to help me to export my content types / contents i have locally in a drupal project. i need to use it in another Drupal project.

I just stumbled upon the Bundle copy module but it is only available for Drupal 7 and my project is version 6.26 - I can't update my core unfortunately for various reasons.

is there something similar working for version 6 please? Thanks in advance

# Answer
For content types, views and much more you can use features, while for the nodes, node\_export will do the job.
> 1 votes

# Answer
For content type - Content Copy module which lives in the CCK project for Drupal 6
For node export - Node export module
> 0 votes

# Answer
The data\_export\_import module is available for Drupal 6. If I am correct, this solution would be for content (data) not content types so you might want to still use features for the content types along with this module.

What I like about data\_export\_import is that it is an all-in-one module (for export AND import of data. Whereas as with other solutions, the import and export stages are done by separate modules, which *could* mean that extra work is needed ensuring compatibility of the export with the import.)
> 0 votes

---
Tags: 7, nodes, importing-exporting, migrations
---


title: How to import / export content type?

text:
# Question
Title: How to import / export content type?
In Drupal 6 we had content type export import, I cannot find this in Drupal 7.

Any tips please?

# Answer
> 15 votes
I ended up using the Bundle Copy module.

# Answer
> 14 votes
You could use Features to export and import content types in code.

# Answer
> 2 votes
This features was part of CCK module, that you can see move into Drupal core. In their project page the maintainers wrote it:

> content\_copy : The D7 branch of the Features module supports expoting and importing content types and fields in 'feature' modules. There is currently no UI to manually export and import field definitions.

So like @digital said, you should use Features.

# Answer
> 1 votes
+1 upvote on the Bundle Copy module by giorgio79 above - a similar module would be: the data\_export\_import module.

What I like about data\_export\_import is that it is an all-in-one module (for export AND import of data. Whereas as with other solutions, the import and export stages are done by separate modules, which *could* mean that extra work is needed ensuring compatibility of the export with the import.)

---
Tags: 7, nodes, importing-exporting
---


# Question
Title: Does using MongoDB for field storage limit functionality?
I am considering using MongoDB on a site for field storage, and not just moving cache, session, lots, etc., out of my SQL database.

The Field Storage API should make this seamless, assuming I am using the Drupal API for accessing data. But, does this limit my site in any way. In particular, I am wondering how Views will be affected.

# Answer
its a cool question.

Im on my 5 week adventure of playing around with Drupal 7 and mongo,

However as Cahpabu stated and quoted.

> NO RELATIONSHIPS WHATSOEVER. EFQ Views do not support relationships because Mongo doesn’t support JOINs." - Under the Converting the Views section on this post. (Just to clarify, I'm not being argumentative, I'm genuinely curious) – Chapabu Sep 6 at 15:57

I think you can do a lot using mongo with Drupal, moving a lot of other stuff into mongo, like sessions, etc. simple "fields" however :

Since Views is extremly limited with Mongo db. I found out that its better(and much more timeconsuming) to rewrite some custom modules fitting into the schema of mongo.

So its for sure, a great adventure if your starting up a new project/site. But the adventure will be filled with great challenges down mystery lane.

Even the Whitehouse had to go back to Mysql from mongo. here is a quote I found on it.

> "The current release depends on MongoDB. When we first created the application, we wanted to make sure we had a highly scalable application and database to meet our anticipated performance needs under high loads. We have been running MongoDB in production for over a year, but we have decided that the performance benefits it provides are outweighed by the complexity of trying to extend Drupal features backed by MongoDB."

However other people had great succes with mongodb and Drupal 8 Mongodb and Drupal 8

> As they state in their slide, To achieve full mongodb functionality is of course impossible.

But you will have to give up several modules using SQL, (which is a lot) For now, I still have the feeling that Drupal cant dance a full tango with Mongo. Even using the modules. its still a rough way.
> 7 votes

---
Tags: views, database
---


# Question
Title: Database problem after moving the site: unknown server error
I just moved my site onto the server and put it under /drupal\_test directory. I now have got an error in the browser, but there is no errors in the apache error log:

```
PDOException: SQLSTATE[HY000] [2005] Unknown MySQL server host 'http://www.mydomain.com' (1)
in lock_may_be_available() (line 167 of /var/www/drupal_test/includes/lock.inc).

```

I have searched around online, many suggests that this is a problem with settings.php, but I can't see any problem with my settings:

```
$databases = array (
  'default' =>
  array (
    'default' =>
    array (
      'database' => 'websitedb',
      'username' => 'websitedbusername',
      'password' => 'thepassword',
      'host' => 'http://www.mydomain.com',
      'port' => '',
      'driver' => 'mysql',
      'prefix' => '',
    ),
  ),
);

```

I tried to use the ip address as the host, I got an error like this:

```
PDOException: SQLSTATE[HY000] [2013] Lost connection to MySQL server at
'reading initial communication packet', system error: 111 in lock_may_be_available()
(line 167 of /var/www/drupal_test/includes/lock.inc).

```

Also, my current site www.mydomain.com works fine.

Any help will be very much appreciated! Thanks!

# Answer
> 4 votes
In the above database configuration the problem seems to be with the `host`, you need to enter the "database hostname", or try entering the static ip "xxx.xxx.xxx.xxx" of the database host.

Aslo check the credentials of your database if they are correct or not. Discussion about the same issue faced be other people is available at: https://drupal.org/node/1315592 .

---
Tags: database, configuration
---


# Question
Title: Redirecting a page after form submission
If I have a module that is creating a page, after form submission for that page, how would I redirect? Is there a function to do this in Drupal? I imagine that I would put the redirect command inside my function that executes after form submission, correct?

# Answer
> 1 votes
Beside the `drupal_goto()` function there's also the `'redirect'` property in the `$form_state`

See https://api.drupal.org/comment/18139#comment-18139

---
Tags: 7, forms
---


# Question
Title: Is it possible to hook to variable_set() event?
I would like to track the system changes event, to make them revertable. When checking variable\_set(), I see there is no hook provided for that event. Is there any way for me to do this?

I can alter to hook to settings forms, but there's a lot of settings form to track, if I can hook to variable\_set() directly, code becomes much simpler.

I can also track the variable changes with features + strongarm modules, but it's better if Drupal admin can browse the variable history without code touching.

# Answer
> 11 votes
It seems that it's impossible using only Drupal, which means:

`variable_set()` itself doesn't invoke any hooks, but it uses `db_merge()`. That function is using the `MergeQuery` class. Now, it would be nice to hook with `hook_query_alter()`, but it only works for query classes that implements the `QueryAlterableInterface` interface. Sadly, this interface is now implemented only by the `SelectQuery` and the `SelectQueryExtender` classes, not by the `MergeQuery` class.

Note that even if you will find a way to create a child class of `MergeQuery`, that will implement `QueryAlterableInterface`, and make Drupal use it. `hook_query_alter()` only works on queries that have tags, and `variable_set()` doesn't tag its query, so the hook would not be used anyway, unless you are willing to hack core. But if you are, you don't need all that, you could simply hack in a hook call.

**If you feel hardcore** you can use a more indirect PHP approach: `$conf` is a global array of configuration variables; you can write a module that will replace it with object acting like an array, as described on Stack Overflow. To make it a good substitute you need to implement `ArrayAccess`. Pull all values from original `$conf` into your object. Then, in `ArrayAccess::offsetSet()` implement your logging logic.

# Answer
> 6 votes
You could use a database trigger, which would be faster than code.

Here is the MySQL doc.

1. create a table to store old values

```
CREATE TABLE variable_backup
(
    name varchar(128) not null,
    value longblob,
    updated datetime not null,
    primary key (name, updated)
);

```
2. create your triggers, one for insert and one for update:

```
CREATE TRIGGER backup_variable_update BEFORE UPDATE ON variable
    FOR EACH ROW
        INSERT INTO variable_backup (name, value, type, updated) VALUES (OLD.name, OLD.value, "update", NOW());

CREATE TRIGGER backup_variable_insert BEFORE INSERT ON variable
    FOR EACH ROW
        INSERT INTO variable_backup (name, value, type, updated) VALUES (NEW.name, NEW.value, "insert", NOW());

```

Now all of your updates and inserts will record old values in variable\_backup.

# Answer
> 5 votes
As you can see in the source code, `variable_set()` makes no request for hooks or alterations, e.g no `module_invoke_all()` or `drupal_alter()` calls there.

```
function variable_set($name, $value) {
  global $conf;

  db_merge('variable')->key(array('name' => $name))->fields(array('value' => serialize($value)))->execute();

  cache_clear_all('variables', 'cache_bootstrap');

  $conf[$name] = $value;
}

```

However, you might be able to listen to the `db_merge()` query with a specially placed `hook_query_alter()` and do some additional processing there but, as pointed out by Molot, `hook_query_alter()` looks unlikely to be able to target the `db_merge()` query.

Alternatively, you could perhaps cron snapshot the variable table to diff it against previous revisions of that table, or else implement some other form of variable revision storage to compare against.

---
Tags: 7, hooks
---


# Question
Title: Drush gives me "warning: fwrite() expects parameter 1 to be resource"
I'm always using Drush to manage my Drupal websites. Now I got a new website, where another hosting company set up Drush, and it isn't working. Contacting them is a problem because of a time difference.

The problem is when I run the command: `drush selfupdate --debug`

I get the following error:

```
X-Powered-By: PHP/5.4.19
Content-type: text/html

<br />
<b>Warning</b>:  fwrite() expects parameter 1 to be resource, string given in <b>/path/to/drush/includes/output.inc</b> on line <b>34</b><br />
<br />
<b>Warning</b>:  fwrite() expects parameter 1 to be resource, string given in <b>/path/to/drush/includes/output.inc</b> on line <b>34</b><br />
GNU Wget 1.12 bouwde op linux-gnu.

+digest +ipv6 +nls +ntlm +opie +md5/openssl +https -gnutls +openssl
-iri

Wgetrc:
  /etc/wgetrc (system)
Locale: /usr/share/locale
Compileer: gcc -DHAVE_CONFIG_H -DSYSTEM_WGETRC="/etc/wgetrc"
  -DLOCALEDIR="/usr/share/locale" -I. -I../lib -O2 -g -pipe -Wall
  -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector
  --param=ssp-buffer-size=4 -m32 -march=i686 -mtune=atom
  -fasynchronous-unwind-tables -fno-strict-aliasing
Link: gcc -O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions
  -fstack-protector --param=ssp-buffer-size=4 -m32 -march=i686
  -mtune=atom -fasynchronous-unwind-tables -fno-strict-aliasing
  -Wl,-z,relro -lssl -lcrypto -ldl -lz /usr/lib/libssl.so
  /usr/lib/libcrypto.so -ldl -lrt ftp-opie.o openssl.o http-ntlm.o
  gen-md5.o ../lib/libgnu.a

Copyright (C) 2009 Free Software Foundation, Inc.
Dit is vrije software: u mag het vrijelijk wijzigen en verder verspreiden.
De precieze licentie is GPLv3+: GNU GPL versie 3 of later.
Zie http://gnu.org/licenses/gpl.html voor de volledige tekst.
Er is GEEN GARANTIE, voor zover de wet dit toestaat.

Oorspronkelijk geschreven door Hrvoje Nikšić <hniksic@xemacs.org>.
Tegenwoordig onderhouden door Micah Cowan <micah@cowan.name>.
Rapporteer gebreken in het programma (of suggesties) aan <bug-wget@gnu.org>;
meld fouten in de vertaling aan <vertaling@vrijschrift.org>.
<br />
<b>Warning</b>:  fwrite() expects parameter 1 to be resource, string given in <b>/path/to/drush/includes/output.inc</b> on line <b>34</b><br />
<br />
<b>Warning</b>:  fwrite() expects parameter 1 to be resource, string given in <b>/path/to/drush/includes/output.inc</b> on line <b>34</b><br />
<br />
<b>Warning</b>:  fwrite() expects parameter 1 to be resource, string given in <b>/path/to/drush/includes/output.inc</b> on line <b>34</b><br />
<br />
<b>Warning</b>:  fwrite() expects parameter 1 to be resource, string given in <b>/path/to/drush/includes/output.inc</b> on line <b>34</b><br />
<br />
<b>Warning</b>:  fwrite() expects parameter 1 to be resource, string given in <b>/path/to/drush/includes/output.inc</b> on line <b>34</b><br />
<br />
<b>Warning</b>:  fwrite() expects parameter 1 to be resource, string given in <b>/path/to/drush/includes/output.inc</b> on line <b>34</b><br />
<br />
<b>Warning</b>:  fwrite() expects parameter 1 to be resource, string given in <b>/path/to/drush/includes/output.inc</b> on line <b>34</b><br />
<br />
<b>Warning</b>:  fwrite() expects parameter 1 to be resource, string given in <b>/path/to/drush/includes/output.inc</b> on line <b>34</b><br />
<br />
<b>Warning</b>:  fwrite() expects parameter 1 to be resource, string given in <b>/path/to/drush/includes/output.inc</b> on line <b>34</b><br />
<br />
<b>Warning</b>:  fwrite() expects parameter 1 to be resource, string given in <b>/path/to/drush/includes/output.inc</b> on line <b>34</b><br />
<br />
<b>Warning</b>:  fwrite() expects parameter 1 to be resource, string given in <b>/path/to/drush/includes/output.inc</b> on line <b>34</b><br />
<br />
<b>Warning</b>:  fwrite() expects parameter 1 to be resource, string given in <b>/path/to/drush/includes/output.inc</b> on line <b>34</b><br />
<br />
<b>Warning</b>:  fwrite() expects parameter 1 to be resource, string given in <b>/path/to/drush/includes/output.inc</b> on line <b>34</b><br />
<br />
<b>Warning</b>:  fwrite() expects parameter 1 to be resource, string given in <b>/path/to/drush/includes/output.inc</b> on line <b>34</b><br />
<br />
<b>Warning</b>:  fwrite() expects parameter 1 to be resource, string given in <b>/path/to/drush/includes/output.inc</b> on line <b>34</b><br />
PHP configuration     :  /usr/local/lib/php.ini
Drush version         :  5.0-dev
Drush configuration   :

<br />
<b>Warning</b>:  fwrite() expects parameter 1 to be resource, string given in <b>/path/to/drush/includes/output.inc</b> on line <b>34</b><br />
<br />
<b>Warning</b>:  fwrite() expects parameter 1 to be resource, string given in <b>/path/to/drush/includes/output.inc</b> on line <b>34</b><br />

```

Server: Apache2 Drupal version 6

# Answer
Please note that in Drush 5 and later, drush self-update only informs you of whether there is an update; this is no longer a mechanism for updating Drush. In fact, this code is now broken, as it is set up to test for updates on drupal.org, whereas new releases are being made on GitHub.

Are you having other problems with Drush? If so, the best route is probably to ask your ISP, who installed it for you. You can also try installing the version that you want following the manual instructions in the Drush README file; basically, you just need to unpack the Drush release (or check out from git), and insure that the Drush you want to use appears first in your PATH.

You could also inform your ISP that Drush 6 is out, and is now the recommended version. Ideally, they would then upgrade for you. If you want to use Drupal 8, though, then you'll probably have to install from the master branch yourself.
> 1 votes

---
Tags: drush
---


# Question
Title: Filter data using exposed filter using country in drupal 7?
I want to filter all views data through IP address (or country) on the front page.

How can I work with exposed filter module? Is there any other method to filter data using selection box (Countries)?

# Answer
> 1 votes
Entities are opened for views to show results. Fields are attached to entities, and with views you can either show the fields or can filter your results with the fields. So, assuming you are trying to make a view of any entity (node,user etc.), you can use the Address field or the Countries module and add the field provided by any of the module to entity you are listing though views.

After adding the field to the entity, the same field will be available in views to be showed or used as exposed filters.

# Answer
> 0 votes
Use a combination of these modules (quotes included are from their project pages):

* Smart IP:

> ... identifies visitor's geographical location (longitude/latitude), country, region, city and postal code based on the IP address of the user. These information will be stored at session variable ($\_SESSION) with array key 'smart\_ip' and Drupal $user-\>data object with array key 'geoip\_location' of the user but optionally it can be disabled (by role) at Smart IP admin page. Other modules can use the function smart\_ip\_get\_location($ip\_address) that returns an array containing the visitor's ISO 3166 2-character country code, longitude, latitude, region (FIPS), city and postal code. It provides a feature for you to perform your own IP lookup and admin spoofing of an arbitrary IP for testing purposes.
* IP Geolocation Views & Maps:

> Despite what the name may suggest, IP Geolocation Views & Maps (IPGV&M) is first and foremost a mapping engine.
>
> The module makes it very easy to create Views-based mapping solutions using the map renderer of your choice (Google, OpenLayers or Leaflet) with any location storage module of your choice, e.g. Get Locations, Geofield, Geolocation Field or Location.
>
> This allows you to bring together modules and feature sets that without IPGV&M you would not be able to combine.
* Location:

> ... allows real-world geographic locations to be associated with Drupal nodes, including people, places, and other content. The Location module allows admins to collect addresses, geocode them (translate addresses to lattitude/longitude), and associate locations with Drupal nodes and users. Location data is automatically used to generate GeoRSS within your existing RSS feeds.

---
Tags: views
---


# Question
Title: Redirect to login page if login block fails
If you fail to log in correctly from a login block, I would like the user to be directed to the login page to log in from there. How can this be accomplished?

# Answer
I guess altering the user login form and override the user\_login\_final\_validate() with a custom custom\_user\_login\_final\_validate() with all codes copy from existing to custom and adding redirecting codes to login page with a check that current page is not user login page, should work.
> 0 votes

---
Tags: 7, forms, redirection
---


# Question
Title: Get enitity ID after programatically creating one
I have a the following code:

```
// Create an Entity with wrapper
  $node = entity_create('node', array('type' => 'person'));
  $entity = entity_metadata_wrapper('node',  $node);

  // Add a node title
  $entity->title = $person['name'];

  // Add the address information
  $entity->field_person_address->thoroughfare = $person['address'];
  $entity->field_person_address->locality = $person['city'];
  $entity->field_person_address->administrative_area = $person['state'];
  $entity->field_person_address->postal_code = $person['postalcode'];
  $entity->field_person_address->country = $person['country'];

  // Save the entity
  $entity->save();

```

The data is saved in the DB perfeclty, but I need to get the entity ID of the new save node.

How do I do that?

# Answer
> 10 votes
You can use

```
$entity->save();

$nid = $entity->nid->value();

```

# Answer
> 23 votes
You can use getIdentifier() method of the wrapper.

```
$node = entity_create('node', array('type' => 'person'));
$entity = entity_metadata_wrapper('node',  $node);
$entity->save();
$entity->getIdentifier();

```

---
Tags: 7, entities
---


# Question
Title: hook_field_extra_fields on node types stored in variable
I am developing a module. It adds a button to certain content types:

```
function mymodule_node_view($node, $view_mode, $langcode) {
  ....
  $node->content['mymodule_button'] = drupal_get_form(....);
}

```

I give the option to configure what content types must have this button:

```
function mymodule_admin_settings() {
  ....
  $form['mymodule_node_types'] = array(
    '#type' => 'checkboxes',
    '#options' => $options, //node types
    '#default_value' => variable_get('mymodule_node_types', array()),
    .....
  )
  return system_settings_form($form);
}

```

I want to configure the weight of the button through the 'manage display' page of each content type. For that I use the hook\_field\_extra\_fields() implementation:

```
function mymodule_field_extra_fields() {
  $extra_fields=array();
  $mymodule_types = variable_get('mymodule_node_types', array());
  .....
  $display_elements['mymodule_button'] = array(
     ...
    'weight' => 0,
  );
  foreach ($mymodule_types as $type) {
    $extra_fields['node'][$type]['display'] = $display_elements;
  }
  return $extra_fields;
}

```

I need when the admin changes the content types in the configuration page, the 'extra fields' will be shown only in the content types selected, not in the other ones. This function is not working this way with this code.

# Answer
> 0 votes
hook\_field\_extra\_fields is invoked by FieldInfo::getBundleExtraFields. This method caches the extra fields info in the database.

```
cache_set("field_info:bundle_extra:$entity_type:$bundle", $info, 'cache_field');

```

So you want to empty cache when the affected bundles changes. That is, add a custom submit callback for `mymodule_admin_settings()` and check what bundles changes over the previous settings.

Tip to Empty the cache:

```
$cid = "field_info:bundle_extra:$entity_type:$bundle";
cache_clear_all($cid, 'cache_field', true);

```

You may prefer to empty the cache for all bundles. In this case, `$cid` is the common prefix for all bundles:

```
$cid = "field_info:bundle_extra:$entity_type";

```

---
Tags: nodes, entities
---


# Question
Title: Uninstall core forum.module while keeping content type and taxonomy
I'm upgrading a site from D5 to D7 and have a large amount of forum posts. However, I no longer want to use the core forum module, instead using views...

When I disable the module, I lose access to the "Forum Post" content type that the module creates. Also, Drupal doesn't have "ownership" of the "Forums" taxonomy.

On the plus side, the content remains. However, I can no longer add new "Forum Post" content and, since the forum module isn't enabled, I can't even create automatic aliases for the "Forum" taxonomy.

Is my only option to run through node\_convert, and hope for the best? Or is there a few things I can manually edit in the DB that would give me full ownership of the content type and taxonomy (as if I had created them from scratch and never installed the module in the fist place)?

Thanks!

# Answer
The problem is that there is no simple thing like "content type ownership". There is `module` column in `{node_type}` table, but simply changing it to "node" (as set for handmade content types) might not be enough. Forum module implements node-related hooks, and integrity of forum data might be endangered if you will simply turn them off and change module in database.

Safer option would be to export data you need to some neutral format, like XML, and then use Feeds or similar module to import it again, to the content type created with your new needs in mind.
> 2 votes

---
Tags: 7, taxonomy-terms, nodes
---


title: Alter node before render or after save

text:
# Question
Title: Alter node before render or after save
I need to alter the content of a node either before it is viewed or after it is saved. In order alter the fields I will need the create date of the node. I am currently attempting to do this via `hook_node_view`, but is there a better way?

# Answer
hook\_node\_presave() can help you making the changes

> Act on a node being inserted or updated. This hook is invoked from node\_save() before the node is saved to the database.

so inside this hook you can get the created time and can change the title.

As an example code: Here I am making node title as the time article node is created.

```
function mymodulename_node_presave($node) {
  if($node->type == "article") {
    $node->title = $node->created;
  }
}

```

**Make sure you do not call node\_save() inside this function, else this will turn out to non breking recursion.**
> 1 votes

# Answer
hook\_node\_insert() responds to the creation of a new node.

This hook is invoked from node\_save() after the node is inserted into the node table in the database, after the type-specific hook\_insert() is invoked, and after field\_attach\_insert() is called.
> 0 votes

---
Tags: 7, views, nodes
---


# Question
Title: Exposed filter checkbox for "has comments"
I would like to add a checkbox as an exposed filter to my view. When checked it will show all ndoes with 0 comments.

I looked at BEF but it didn't seem to be able to handle this. I also have another exposed filter for that view, otherwise I could just hide the filter and use jquery to toggle the url when checking the checkbox.

# Answer
> 2 votes
You can add your own filter trough a custom module. I was in need of the same thing. The following code should work.

```
<?php
/**
 * Implements hook_views_api()
 */
function my_module_views_api() {
  return array(
    'api' => 3,
  );
}

/**
* Implements hook_views_data().
*/
function mymodule_views_data() {

  // comment_count
  $data['node_comment_statistics']['has_comment'] = array(
    'title' => t('Has comment'),
    'real field' => 'comment_count',
    'help' => t('Filter to see if entity has comments.'),
    'filter' => array(
      'handler' => 'cjsm_ikz_handler_filter_has_comments',
    ),
  );

  return $data;
}

```

The next thing should be a filter in an include file.

```
<?php
/**
* @file
* Definition of mymodule_handler_filter_has_comments.
*/

/**
 * Simple filter to see if entity has comments or not.
 *
 * @ingroup views_filter_handlers
 */
class mymodule_handler_filter_has_comments extends views_handler_filter_boolean_operator {
  function query() {
    $this->ensure_my_table();
    $field = "$this->table_alias.$this->real_field";

    if (empty($this->value)) {
      if ($this->accept_null) {
        $or = db_or()
        ->condition($field, 0, '=')
        ->condition($field, NULL, 'IS NULL');
        $this->query->add_where($this->options['group'], $or);
      }
      else {
        $this->query->add_where($this->options['group'], $field, 0, '=');
      }
    }
    else {
      $this->query->add_where($this->options['group'], $field, 0, '<>');
    }
  }
}

```

For me this is providing a selectbox. Because I also want to be able to see nodes with and without comments at the same time. But it does exactly what you are looking for. If you are having trouble implementing this I suggest you search for the ins and outs of creating custom views filters.

---
Tags: 7, views
---


title: Using Doctrine in D8

text:
# Question
Title: Using Doctrine in D8
I have downloaded the latest version of Drupal 8 my project structure looks like:

```
private/
  EntityOne.php
  EntityTwo.php
  Test.php => Test Script (Eventually AUT)
public/
  index.php => Drupal Engine

```

Inside Test.php I wish to begin building a series of entities which at first will be used externally and eventually be moved into Drupal modules.

I have Googled and spent hours trying to get Doctrine to start letting me build tables with my entities, but I am doing something wrong.

http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/tutorials/getting-started.html#obtaining-the-entitymanager

Is of no help, there is no **"vendor/autoload.php"** but there is a **"core/vendor/autoload.php"**

I can include this file in Test.php and everything is fine but when I start adding code:

```
  include '../public/core/vendor/autoload.php';

  use Doctrine\ORM\Tools\Setup;
  use Doctrine\ORM\EntityManager;

  // Create a simple "default" Doctrine ORM configuration for Annotations
  $isDevMode = true;
  $config = Setup::createAnnotationMetadataConfiguration(array(__DIR__."/src"), $isDevMode);

```

I get an error:

Fatal error: Class 'Doctrine\ORM\Tools\Setup' not found in ...\private\index.php on line 10

There is no **"Doctrine/ORM"**

What am I missing???

Alex

# Answer
> 5 votes
Drupal 8 uses the annotation reader from Doctrine Common but it does not use the ORM. The handbook page for the Drupal entity field API is being written at https://drupal.org/node/2078191

---
Tags: 8
---


title: Replace email address with word "email"

text:
# Question
Title: Replace email address with word "email"
Using the email module, you only have the option of outputting the email address as a link, the email address as plain text, or a link to a web form. What I want is to just print the word "email" as `mailto` link.

For example: In display suite using the link field formatter, you can opt to use the label as the link so the website displays the word "website" which is a hyperlink to the actual url. Is their anyway to do this with email?

# Answer
> 0 votes
It looks like you want to have one more custom field formatter. In order to create a custom field formatter all we need is implementation of 2 hooks

so code will be like this

```
/**
 * Implements hook_field_formatter_info().
 *
 */
function mymodule_field_formatter_info() {
  // Add a setting to a formatter type.
  $formats = array(
    'email_custom' => array(
      'label' => t('Email Custom'),
      'description' => t('Display the email address as custom format.'),
      'field types' => array('email'),
    ),
  );
    return $formats;
}

/**
 * Implements hook_field_formatter_view().
 */
function mymodule_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
  $element = array();
  switch ($display['type']) {
    case 'email_custom':
      foreach ($items as $delta => $item) {
        $output = l("email", 'mailto:' . $item['email']);
        $element[$delta] = array('#markup' => $output);
      }
      break;
  }
  return $element;
}

```

after adding this codes to your custom module clear the caches and you will see one more field formatter as Email Custom(you can change the labels in above code). Now your configurations in manage display for this field will be .

> 1. Hide your field label
> 2. Select Email Custom as field format

---
Tags: emails, display-suite
---


# Question
Title: user form_alter to change text on button for user_pass form
```
function footheme_form_alter($form, $form_state, $form_id) {
if($form_id == 'user_pass') {
 $form['actions']['submit']['#value'] = 'reset password';
 print "boom";
 }

```

This does not work, "boom" is printing so I know it works but this is wrong

```
 $form['actions']['submit']['#value'] = 'reset password';

```

here is the debug output

```
Array
(
    [#form_id] => user_pass
    [#type] => form
    [#build_id] => form-dadfsdfsd
    [#id] => user-pass
    [#method] => post
    [#action] => /user/password
    [#theme_wrappers] => Array
        (
            [0] => form
            [1] => block
        )

    [#tree] =>
    [#parents] => Array
        (
        )

    [#validate] => Array
        (
            [0] => user_pass_validate
        )

    [#submit] => Array
        (
            [0] => user_pass_submit
        )

    [#theme] => Array
        (
            [0] => user_pass
        )

    [#processed] =>
    [#defaults_loaded] => 1
    [#required] =>
    [#attributes] => Array
        (
        )

    [#title_display] => before
    [#array_parents] => Array
        (
        )

    [#block] => stdClass Object
        (
            [bid] => 72
            [module] => system
            [delta] => main
            [theme] => footheme
            [status] => 1
            [weight] => -14
            [region] => content
            [custom] => 0
            [visibility] => 0
            [pages] =>
            [title] =>
            [cache] => -1
            [css_class] =>
            [subject] =>
            [last_in_region] => 1
        )

    [#weight] => 1
    [name] => Array
        (
            [#type] => textfield
            [#title] => E-mail
            [#size] => 60
            [#maxlength] => 254
            [#required] => 1
            [#default_value] =>
            [#description] => A password reset message will be sent to your e-mail address.
            [#input] => 1
            [#autocomplete_path] =>
            [#process] => Array
                (
                    [0] => ajax_process_form
                )

            [#theme] => textfield
            [#theme_wrappers] => Array
                (
                    [0] => form_element
                )

            [#pre_render] => Array
                (
                    [0] => ctools_dependent_pre_render
                )

            [#defaults_loaded] => 1
            [#tree] =>
            [#parents] => Array
                (
                    [0] => name
                )

            [#array_parents] => Array
                (
                    [0] => name
                )

            [#weight] => 0
            [#processed] => 1
            [#attributes] => Array
                (
                )

            [#title_display] => before
            [#id] => edit-name
            [#name] => name
            [#value] =>
            [#ajax_processed] =>
            [#sorted] => 1
            [#children] =>
  E-mail *

            [#printed] => 1
        )

    [form_build_id] => Array
        (
            [#type] => hidden
            [#value] => form-CyR7yFGjBz2kf85j4mMIhozHP-_OPIk
            [#id] => form-CyR7yFGjBz2kf85j4mzD4aIhozHP-_OPIk
            [#name] => form_build_id
            [#parents] => Array
                (
                    [0] => form_build_id
                )

            [#input] => 1
            [#process] => Array
                (
                    [0] => ajax_process_form
                )

            [#theme] => hidden
            [#defaults_loaded] => 1
            [#tree] =>
            [#array_parents] => Array
                (
                    [0] => form_build_id
                )

            [#weight] => 0.002
            [#processed] => 1
            [#required] =>
            [#attributes] => Array
                (
                )

            [#title_display] => before
            [#ajax_processed] =>
            [#sorted] => 1
            [#children] =>

            [#printed] => 1
        )

    [form_id] => Array
        (
            [#type] => hidden
            [#value] => user_pass
            [#id] => edit-user-pass
            [#parents] => Array
                (
                    [0] => form_id
                )

            [#input] => 1
            [#process] => Array
                (
                    [0] => ajax_process_form
                )

            [#theme] => hidden
            [#defaults_loaded] => 1
            [#tree] =>
            [#array_parents] => Array
                (
                    [0] => form_id
                )

            [#weight] => 0.003
            [#processed] => 1
            [#required] =>
            [#attributes] => Array
                (
                )

            [#title_display] => before
            [#name] => form_id
            [#ajax_processed] =>
            [#sorted] => 1
            [#children] =>

            [#printed] => 1
        )

    [actions] => Array
        (
            [#type] => actions
            [submit] => Array
                (
                    [#type] => submit
                    [#value] => E-mail new password
                    [#input] => 1
                    [#name] => op
                    [#button_type] => submit
                    [#executes_submit_callback] => 1
                    [#limit_validation_errors] =>
                    [#process] => Array
                        (
                            [0] => ajax_process_form
                        )

                    [#theme_wrappers] => Array
                        (
                            [0] => button
                        )

                    [#defaults_loaded] => 1
                    [#tree] =>
                    [#parents] => Array
                        (
                            [0] => submit
                        )

                    [#array_parents] => Array
                        (
                            [0] => actions
                            [1] => submit
                        )

                    [#weight] => 0
                    [#processed] => 1
                    [#required] =>
                    [#attributes] => Array
                        (
                        )

                    [#title_display] => before
                    [#id] => edit-submit
                    [#ajax_processed] =>
                    [#sorted] => 1
                    [#children] =>
                    [#printed] => 1
                )

            [#theme_wrappers] => Array
                (
                    [0] => container
                )

            [#process] => Array
                (
                    [0] => form_process_actions
                    [1] => form_process_container
                )

            [#weight] => 100
            [#defaults_loaded] => 1
            [#tree] =>
            [#parents] => Array
                (
                    [0] => actions
                )

            [#array_parents] => Array
                (
                    [0] => actions
                )

            [#processed] => 1
            [#required] =>
            [#attributes] => Array
                (
                    [class] => Array
                        (
                            [0] => form-actions
                        )

                )

            [#title_display] => before
            [#id] => edit-actions
            [#sorted] => 1
            [#children] =>

            [#printed] => 1
        )

    [#sorted] => 1
    [#children] =>
)

```

# Answer
Instead of having arguments as call by value you should have it by reference, so little change to your codes as

```
/**
* Implements hook_form_alter()
*/
function footheme_form_alter(&$form, &$form_state, $form_id) {
  if($form_id == 'user_pass') {
   $form['actions']['submit']['#value'] = t('reset password');
   print "boom";
 }
}

```

and then clear your caches.
> 1 votes

---
Tags: 7
---


title: Update CCK Field Every 90 Days

text:
# Question
Title: Update CCK Field Every 90 Days
I'm using Drupal 7. I have a CCK field called Placement Date (Placement\_Date) that the end user will manually put in. I then have two text fields, Start\_of\_Period and End\_of\_Period. Start\_of\_Period initially is set to Field-\>Placement\_Date and Field-\>End\_of\_Period is set to 90 days out. The setup is no problem, but after 90 days Field-\>Start\_of\_Period needs to be the old End\_of\_Period + 1, and Field-\>End\_of\_Period needs to be another 90 days out from the new Field-\>Start\_of\_Period. I looked to Rules to try to find a way to schedule this, but cannot figure out what I need to be doing.

Any help would be greatly appreciated. Thanks in advance.

# Answer
> * You need to set up cron tab on your server may be once a day
> * use hook\_cron() to add your custom code write query to grab nids for which field values needs to be updated.
> * use node\_load\_multiple() to load all nodes with the query returned nids
> * update the field values and save the node again in a loop.
> * set the crontab to run at the time when your site receives least traffic, this way it will not be performance issue as well.
> 2 votes

---
Tags: rules
---


# Question
Title: Allow authenticated user to create an article
hey im fairly new to D7 and ive noticed that there isn't really a way to create an article without the admin toolbar, but i would like users of my websites to be able to create articles. How would i do this without giving them access to the toolbar?

# Answer
Go to admin/people/permissions and check the permission "Article: create content" and maybe on a block create a link for them called create content.
> 2 votes

# Answer
Go to *Admin-\>People-\>Permissions*, check the permission *Article: Create new content* for the Authenticated user. Scroll down to the bottom and click *Save permissions*. Now, there will appaear a link "*Add content*" in the navigation menu for the Authenticated user.

(There should be no need for you to create this link explicitly.)
> 0 votes

# Answer
I had the same problem. The permissions were turned on but I still couldn't see the toolbar.

**Solution:** The "Add content" link for authenticated users was *in the sidebar*, **not** at the top, as it is for administrators. I had to scroll down to see the link.
> 0 votes

---
Tags: nodes
---


# Question
Title: How to set an existing database field to auto increment
I have an existing database that has an id field that is an unsigned integer with a length of ten (and is set as the primary key). I would like to write an update to change this field so that it auto increments. How would I go about doing that? I am familiar with writing updates, just haven't done one like this before. I am doing this with Drupal 7.

# Answer
> 1 votes
I found the solution I was looking for here. Below is the relevent part.

For example, suppose you have:

```
$schema['foo'] = array(
  'fields' => array(
    'bar' => array('type' => 'int', 'not null' => TRUE)
  ),
  'primary key' => array('bar')
);

```

and you want to change foo.bar to be type serial, leaving it as the primary key. The correct sequence is:

```
db_drop_primary_key('foo');
db_change_field('foo', 'bar', 'bar',
  array('type' => 'serial', 'not null' => TRUE),
  array('primary key' => array('bar')));

```

# Answer
> 0 votes
Although not strictly a Drupal question, you can make the field into an auto\_increment field in MySQL with:

```
ALTER TABLE my_table MODIFY COLUMN my_id int(10) AUTO_INCREMENT PRIMARY KEY;

```

"PRIMARY KEY" is just-in-case and may not be needed as is already the primary key.

As with any direct database schema changes, backup first.

---
Tags: 7, database, updating
---


# Question
Title: Exporting block settings in a Feature (Drupal 7)
I am trying to learn about creating a reasonable workflow between a development site and a production site and I have decided to use the Features module to help accomplish this task.

On my front page I have a couple blocks that display newly added and top rated content. I have used features to export these views but I do not see anyway inside of the Features module to export my block settings. I set the new projects and highest rated blocks to show up in the content section of a page. I filter it to only show up on the front-page inside the view.

How to export these block settings inside my feature so I do not need to reconfigure them on each site?

# Answer
You can export much more using Feature together with Strongarm and Features extra.

***Strongarm*** gives site builders a way to override the default variable values that Drupal core and contributed modules ship with. It is not an end user tool, but a developer and site builder tool which provides an API and a limited UI.

***Features extra*** supports: vocabularies; nodequeues (definitions); block settings; custom blocks (boxes).

Additionally UUID Features Integration provides a mechanism for exporting content (nodes, taxonomy, fields) into a features module.
> 13 votes

# Answer
You could use the Boxes module as per Exporting of blocks for features.

If you'd rather not install additional modules, and you're dealing with a Views block (where you simply need the block configuration settings), another option is to do this at the code level with a hook\_update\_N() implementation in a custom module's install file. See below for an example.

```
/**
 * Configure block settings.
 */
function my_module_update_7101() {

  // Enable blocks
  db_update('block')
    ->fields(array(
      'status'     => 1,
      'region'     => 'content',
      'visibility' => 1,
      'pages'      => 'node/999',
      'title'      => 'My Block Title',
      'css'        => '',
      'js'         => '',
    ))
    ->condition('delta', 'BLOCK_ID')
    ->execute();
}

```
> 4 votes

# Answer
An alternative is to use mini-panels instead of custom blocks as been suggested here. They work much the same, and panels appear to be better supported by features. If you already plan to use panels, this also saves a few extra modules.
> 0 votes

---
Tags: 7, blocks, features
---


# Question
Title: Page Manager Error: The requested page "/xxxx" could not be found
I am working almost 4 hours on the following problem, and can't solve it (Drupal 7).

I tried to build a new simple page in the page manager as I did few times before. I entered a simple path as /xxxx Then, after I saved the page, and tried to load it, I got the following error message:

> The requested page "/xxxx" could not be found

Can somebody help me figure out why I can't create new page?

In addition, when I tried to disabled the page on the page manager, I got the following error:

> Notice: Undefined offset: 1 in template\_preprocess\_page\_manager\_edit\_page() (line 42 of D:\MYSITE\sites\all\modules\ctools\page\_manager\theme\page\_manager.theme.inc

Does someone knows what is the problem, and how can I fix it?

Thanks!

# Answer
Are you using the stable version of the ctools and panels module, this error doesn't seems to be in the issue queue of the respective modules.

As @David as mentioned the problem could be of selection rule or the access rule.

Have a look at the use tutorial for creating the page with page manager: http://nodeone.se/en/learn-page-manager-part-1-overview

Also check the documentation of the page manager module: https://drupal.org/node/1862908
> 1 votes

---
Tags: 7, chaos-tool-suite
---


title: Altering nodes title value

text:
# Question
Title: Altering nodes title value
I am trying to alter the title of my nodes to prevent URLS appearing in any title. This is the code I am using.

```
function mytemplate_preprocess_node(&$variables) {
  $node = $variables['node '];
  $variables['title'] = cleaner(check_plain($node->title));
}

```

`cleaner()` removes URLs from nodes. The above works perfectly on teasers, but not on full view or when the title is displayed in a list with other articles inside a block.

How can I make sure that the URL disappear whenever the concerned node's title is listed?

# Answer
You need to implement both

* template\_preprocess\_page() : this will take care of node full view mode.
* temaplte\_proprocess\_node() : this will take care of node teaser view mode

In your theme template.php

```
function mythemename_preprocess_page(&$variables) {
  if(isset($variables['node']) && $variables['node']->type == "your content type") {
    drupal_set_title("your_title");
  }
}

/**
 * Override or insert variables into the node template.
 */
function mythemename_preprocess_node(&$variables) {
  if($variables['type'] == "your content type") {
    $variables['title'] = "your title";
  }
}

```

Note:

> * only changing in template\_preprocess\_node(), will now reflect on node teaser view as it will be overridden by page template.
> * in order to change you should use drupal\_set\_title() instead of $variables\['title'\].
> 0 votes

# Answer
Use template\_preprocess\_page() in the template.php to update the page title for full view, However please don't your code for hook\_preprocess\_node() as that code would be required for updating the page title for teaser view.

Examples:

```
// Example of updating the nodes title for all content types.
function MYTHEME_preprocess_page(&$vars) {
  // Check if the variable is of node type.
  if (!empty($vars['node']) {
    $updated_title = cleaner(check_plain($node->title));
    drupal_set_title($updated_title);
  }
}

```

To update the page title of specific page just update the `if` condition as below:

```
if (!empty($variables['node']) && $variables['node']->type == 'CONTENT_TYPE') {
  $updated_title = cleaner(check_plain($node->title));
  drupal_set_title($updated_title);
}

```

---

The above things will update the page title at the time of rendering, however the better solution is to clear the URL's from the node title before saving (insert/update) the node so that you wont need to modified at the time of rendering:

```
// Using the hook_node_presave() for removing the URL's from title.
function MyModule_node_presave($node) {
  $node->title = cleaner(check_plain($node->title));
}

```

**Note**: The hook\_node\_presave() will help you for new nodes and the nodes those you are going to update.
> -1 votes

---
Tags: nodes, theming
---


# Question
Title: How can I know whether user has logged in through facebook account or through Site login?
How can I know whether user has logged in through FB or through site's login section? I am giving points to user based on FB login that's why It's important to know. Thanks

# Answer
> 0 votes
You could use Rules module together with Notification module, to achieve what you want. There is no out of the box solution for this problem.

You will have to look into Adding a new rule to react to user registrations Or to user logins. You will properly have to create a custom module depending on the deepth of what you exactly need

---
Tags: 7, users, social-network
---


title: hook_services_resource is not working

text:
# Question
Title: hook_services_resource is not working
EXAMPLE : this is my sample for service resource hook, i'm using drupal 7. I have enabled the services module and ctools module. the end point is working fine, but when i browse the **endpoint/commerce\_rest/retrieve** url is not working

It returns the following exception, exception 'ServicesException' with message 'Could not find resource retrieve.' as following:

```
/var/www/webui/drupal/sites/all/modules/services/includes/services.runtime.inc:359\nStack trace:\n#0
/var/www/webui/drupal/sites/all/modules/services/servers/rest_server/includes/RESTServer.inc(83): services_error('Could not find ...', 404)\n#1
/var/www/webui/drupal/sites/all/modules/services/servers/rest_server/includes/RESTServer.inc(36): RESTServer->getController()\n#2
/var/www/webui/drupal/sites/all/modules/services/servers/rest_server/rest_server.module(40): RESTServer->handle()\n#3 [internal function]: rest_server_server()\n#4
/var/www/webui/drupal/sites/all/modules/services/services.module(218):
 all_user_func('rest_server_ser...')\n#5
[internal function]: services_endpoint_callback('commerce_rest', 'retrieve')\n#6
/var/www/webui/drupal/includes/menu.inc(516): call_user_func_array('services_endpoi...', Array)\n#7
/var/www/webui/drupal/index.php(33): menu_execute_active_handler()\n#8 {main}

```

And the source code is:

```
function test_module_services_resources() {

   $resource = array(
      'commerce_rest' => array(
      'retrieve' => array(
        'file' => array('type' => 'inc', 'module' => 'search_service'),
        'callback' => 'test_module_search_service_results',
        'access callback' => 'search_access_callback',
        'access arguments' => array('view'),
        'access arguments append' => TRUE,
        ),
    )
 )
);
    return $resource;
}

```

this hook is not invoked, when I browse the url.

# Answer
> 2 votes
You can try:

```
/**
 * Implements hook_services_resources
 */
function test_module_services_resources() {

  $resources = array();

  $resources['search_results'] = array(
    'index' => array(
    'callback' => 'test_module_search_service_results_index',
    'file' => array(
      'type' => 'inc',
      'module' => 'test_module',
      'name' => 'resources/search_results.resource'
    ),
    'access arguments' => array('access content'),
    'args' => array(),
    ),
  );

  return $resources;

}

```

Ensure the resource callback `test_module_search_service_results_index` is located in your module subfolder

```
test_module/resources/search_results.resource.inc

```

Then try hitting http://www.example.com/api/search\_results (using your site services endpoint)

---
Tags: hooks, services
---


# Question
Title: Adding CSS class to flagged node teasers
I have tried the following code corolla theme's template.php

```
/**
 * Implements template_preprocess_node().
 */
function corolla_preprocess_node(&$variables) {
  $flag = flag_get_flag('sold'); // Machine name of your flag.
  if ($flag && $flag->is_flagged($variables['node']->nid)) {
    $variables['classes_array'][] = 'node-flag-sold';
  }
}

```

This is supposed to add CSS class="node-flag-sold" next to "node". But looking through my firebug, there arenosuch classes added.

Please note, that my node--content-type.tpl.php is custom rewritten. Do I need to add anything there?

# Answer
> 3 votes
The preprocess code looks reasonably correct.

Make sure you're printing out the `$classes` variable in your custom `node--content-type.tpl.php`

e.g, in the wrapper div here:

```
<div id="node-<?php print $node->nid; ?>" class="<?php print $classes; ?> clearfix"<?php print $attributes; ?>>

<!-- Node template content ... -->

</div><!-- /.node -->

```

If curious, `$variables['classes_array']` is flattened into `$variables['classes']` in `template_process` with

```
// Flatten out classes.
$variables['classes'] = implode(' ', $variables['classes_array']);

```

In D7, process functions are introduced, running after preprocess functions.

---
Tags: theming, flags
---


# Question
Title: Looking for "Edit own Blocks" permission?
It would be very useful for me to have something like "Edit own Blocks" permission.

As administrator (user 1) I created some blocks in a site. I also gave permission to create new blocks to other role users.

Then these user now can edit and delete my blocks. I need them to be able to create their own block but not to edit nor to delete mines.

I tried with the https://drupal.org/project/block\_access modulen which does the job but it adds a lot configuration stuff in every block which I just see "too much" for what I need.

Any other way to do this?

# Answer
> 2 votes
Block are not content. They don't have an owner, revision and all that. But there is another way round. You can make some of content to be a blocks with Nodeblock or one of it's competitors:

> This module allows you to specify content type(s) as being a block. This allows the content managers of the site to edit the block text and title without having to access the block administration page. Users only need edit access to that node in order to edit it.

That way you can create content type Block, and apply node permissions to it. All of them, including "edit own block".

---
Tags: blocks, users
---


# Question
Title: Price formatter for range of variation products
Is there a way to write a price formatter to display the lowest and highest price of a collection of product variations? My reason for thinking it might not work is the scope of the product variation vs. it's "parent" product display.

If not, is there some way to build a view that will query to max ( and another for the min ) price of a collection of variations under one product display?

**For Example:**

I have a product display with 4 variations. Each variation has a different size lets say, and therefore each variation has a different price. I'm looking for a way for my product display to show the price of the cheapest variation and the highest priced variation as a range. As opposed to the first variation price that is shown now

# Answer
Commerce Pricing Attributes

> This module provides some enhancements to the Commerce Product Option and Commerce Product Attributes handling by applying pricing rules to custom product attributes. So, you can add attributes to products that affect the final product price.

* Dynamic price calculation based on selected operators.
* Cart combination based on product attributes.
* Support for multi currency.
* Multilingual attributes.
* Different attributes and settings per product.
* Price adjustments either per item or per order.
* Rules integration.
* Easy UI for editing and reordering attributes
> 0 votes

---
Tags: commerce
---


# Question
Title: How to hide node edit / delete link in a view conditionally?
I have a view that lists a content type in a table. There are edit/delete links so the users can edit the content. I want to display these links conditionally.

These are just orders sent in by customers and I only want to let them edit or delete them until the "status" field is set to "processed". Once their order has been processed, they shouldn't be able to modify nor delete it. I can show them a message via a custom module, but it would be nice to remove the edit/delete buttons for these nodes.

# Answer
Although an old issue, the way to do this in D7 commerce is with

`hook_commerce_entity_access`

```
/**
 * Implements hook_commerce_entity_access
 */
function MODULE_commerce_entity_access($op, $entity, $account, $entity_type) {
  if ($entity_type == 'commerce_order') {
    // Prevent edit and delete of 'processed' status orders
    if ($entity->status == 'processed' && ($op == 'edit' || $op == 'delete')) {
      return FALSE;
    }
  }
}

```
> 2 votes

# Answer
You can user views\_php module and can programmatically render edit and delete link after checking the required condidtions. So the following steps may help you

1. Install views\_php module
2. now in your view add edit and delete and nid field but exclude them from display
3. now add global php field in views and load the node using the nid(you can check using dpm($data); if you have devel installed) now get the node field value and check the condition and display the edit link which you can directly get as token as you have already added that field to views.
4. follow the 3 rd step and this time render delete link. hope this helps you
> 1 votes

---
Tags: 7, views, entities
---


title: Drupal Search function in custom module

text:
# Question
Title: Drupal Search function in custom module
I created a drupal custom module for my website, the module functionality is it display list of students who have registered in my site. Now I want to update my custom module with search functionality, the search function should like google search function.

My custom module look like following structure

>

Now I want to implement the search function in my custom module. When I search using the fields of the table like student name, gender, author name, and status, how do I do this?

>

# Answer
> 0 votes
You have few options:

1. Use `hook_views_data()` to hook your custom tables with Views.
2. Use Data module as it features automatic integration with Views.
3. Reorder your setup to use Drupal's node type/user profile/entity, which has Views support out of the box.

Doing it really manually will be a waste of time, unless you need some very specific functionality that can be hardly achieved by using Views for it.

Views will also provide you with caching, paging and it will be easier to maintain it in the future.

---
Tags: 7, search
---


# Question
Title: Select list of node titles for a view exposed filter
I want to create an exposed filter based on the title of a node. How do I do this? I would prefer this filter be a select list - that is, all of the node names are listed based on the criteria I list.

So let's say you have three titles for events:

```
A Trip to the Woods

Go to the Beach

Off to the Farm

```

I would like the exposed filter to be a select list of these three nodes.

# Answer
> 2 votes
Look into the Finder module in addition to creating a View Page.

From the Finder module project description:

> Typically Finder is used for these purposes:
>
> * As a search tool to find a group of nodes or users.
> * As a way to navigate to a specific node or user page that matches criteria.
> * As an alternative to exposed filters for a Views module display.
>
> Specific example uses of Finder:
>
> * An autocomplete search on node titles in order to find a node.
> * **A select list of all the possible values for a particular content field in order to get a list of corresponding nodes.**
> * Multiple groups of radio buttons and checkboxes with taxonomy terms to find nodes that match all the selected terms.
> * An autocomplete search on usernames in order to go to a user profile.
> * A multi-step wizard form to whittle down a pool of potential results by asking questions on one step that will reduce the possible answers on the next step.

Finder should be able to pick and choice, or filter, what shows up in the that Select list.

# Answer
> -1 votes
Views Autocomplete Filters

> * It works for node titles or cck text fields.
> * The autocomplete results are actually the view results, so they are view related.

---
Tags: views
---


# Question
Title: How to configure REST server to create new node from URL parameters?
Drupal 7.23 Services 7.x-3.5

I've followed the instructions for setting up Services module, including https://drupal.org/node/1699354. I got the endpoint setup successfully. I am able to retrieve index of nodes using ...endpoint/node and specific nodes using .../endpoint/node/#.

Now how can I create new nodes via Service through an URL? The Services manual gets really confusing at this point, is outdated and full of errors. The sample code they provide here https://drupal.org/node/1334758 ... am i supposed to put this in a custom module in order to be able to POST? If so, it turns my whole site blank right after adding this line:

```
// cURL
$curl = curl_init($request_url);

```

Also, there's an issue with CSRF validation, as showing in the Firefox Poster tool. The Services forum is a madhouse so I come here in hopes that someone can guide me in the right direction. What other modules do I need to get this to work? Why does my site go blank after adding the code above?

A simple solution would be the following:

domain/endpoint?title=test&url=http%253A%252F%252Fwww.example.com

and produce a new node of nodetype with a title and URL.

# Answer
In order to create the node you must use the POST HTTP request so you can't do something like domain/endpoint?title=test&url=http%253A%252F%252Fwww.example.com(it's GET HTTP request). You can do the following to solve your problems:

1. First you need to make the Services 3.0 work with Firefox Poster tool. You can go Testing with REST Server for checking all the basic function in case you forgot to set the permissions or forgot to enable resources.
2. After you find out how to communicate with Services 3.0. You can use drupal\_http\_request to build your own POST/GET HTTP request. An example will be here Making authenticated requests to REST Server.
> 1 votes

# Answer
Sample code provided there is flawed as there is no need to get CSRF token two times. One time is enough after user login. Also, CSRF token needs to be obtained in the same curl session as login, as Drupal Services returns empty otherwise, try the following code once:

```
<?php

        // LOGIN AND GET CSRF TOKEN

        /*
            * Server REST - user.login
        */

        // REST Server URL
        $request_url = 'http://mysite....com/server/user/login.json';

        // User data
        $user_data = array(
        'username' => 'xxxx',
        'password' => 'xxxx',
        );
        $user_data = http_build_query($user_data);

        // cURL
        $curl = curl_init($request_url);
        curl_setopt($curl, CURLOPT_HTTPHEADER, array('Accept: application/json')); // Accept JSON response
        curl_setopt($curl, CURLOPT_POST, 1); // Do a regular HTTP POST
        curl_setopt($curl, CURLOPT_POSTFIELDS, $user_data); // Set POST data
        curl_setopt($curl, CURLOPT_HEADER, FALSE);  // Ask to not return Header
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
        curl_setopt($curl, CURLOPT_FAILONERROR, TRUE);

        $response = curl_exec($curl);
        //print_r($response);
        $http_code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
        //print "<br>".$http_code."</br>";
        // Check if login was successful
        if ($http_code == 200) {
            // Convert json response as array
            $logged_user = json_decode($response);
            //print_r($logged_user);

        }
        else {
            // Get error msg
            $http_message = curl_error($curl);
            die($http_message);
        }

        // Define cookie session
        $cookie_session = $logged_user->session_name . '=' . $logged_user->sessid;

        //GET CSRF TOKEN
        curl_setopt_array($curl, array(
        CURLOPT_RETURNTRANSFER => 1,
        CURLOPT_URL => 'http://mysite....com/services/session/token',
        ));
        curl_setopt($curl, CURLOPT_COOKIE, "$cookie_session");
        // $csrf_token = curl_exec($curl);
        //print_r($csrf_token);

        $ret = new stdClass;

        $ret->response = curl_exec($curl);
        $ret->error    = curl_error($curl);
        $ret->info     = curl_getinfo($curl);

        //print_r($ret->response);
        $csrf_token = json_decode($ret->response)->token;

        /*
            * Server REST - node.create
        */

        // REST Server URL
        $request_url = 'http://mysite....com/server/node';

        // Node data
        $node_data = array(
        'title' => 'A node created with services 3.x and REST server',
        'type' => 'page',
        'body[und][0][value]' => '<p>Body</p>',
        );
        $node_data = http_build_query($node_data);

        // cURL
        $curl = curl_init($request_url);
        // Accept JSON response
        curl_setopt($curl, CURLOPT_HTTPHEADER, array('Accept: application/json', 'X-CSRF-Token: ' .$csrf_token));
        curl_setopt($curl, CURLOPT_POST, 1); // Do a regular HTTP POST
        curl_setopt($curl, CURLOPT_POSTFIELDS, $node_data); // Set POST data

        curl_setopt($curl, CURLOPT_HEADER, FALSE);
        // use the previously saved session
        curl_setopt($curl, CURLOPT_COOKIE, "$cookie_session");
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
        curl_setopt($curl, CURLOPT_FAILONERROR, TRUE);

        $response = curl_exec($curl);
        print "<br><br>";
        print_r($response);
        $http_code = curl_getinfo($curl, CURLINFO_HTTP_CODE);

        // Check if login was successful
        if ($http_code == 200) {
            // Convert json response as array
            $node = json_decode($response);
        }
        else {
            // Get error msg
            $http_message = curl_error($curl);
            die($http_message);
        }

        print_r($node);

    ?>

```
> 1 votes

# Answer
For some reason, the CRUD operation 'index - List all nodes' has to be checked in addition to 'Create a node' within the Resources menu, otherwise the CSRF validation issue remains.
> 0 votes

---
Tags: services, 8
---


# Question
Title: Where is the class "placeholder" defined?
According to the function:

```
function drupal_placeholder($text) {
  return '<em class="placeholder">' . check_plain($text) . '</em>';
}

```

It would return the HTML code with class "placecholder". I had searched the word "placeholder" in the drupal 7 project about 4,800 files. I expected to find the default CSS definition of class placeholder e.g. em.placeholder{} or .placehoder{}. But I can't.

I can only find some files with html ID attribute #placeholder{} was defined.

```
Some of the files:
 drupal/modules/color/color-rtl.css
 drupal/modules/color/color.css
 drupal/sites/all/module/ctools.css.stylizer.css

```

Because I want to modify class with my style globally. Please advise if any default definition of class placeholder in drupal 7.

# Answer
The only uses of the placeholder class in core are (filename, followed by line number, follby the line):

```
modules/dashboard/dashboard.js:35:        if ($('.placeholder', this).length == 0) {
modules/dashboard/dashboard.js:38:        $('.placeholder', this).html(empty_text);
modules/dashboard/dashboard.js:41:        $('.placeholder', this).remove();
modules/system/system.admin.css:264:.exposed-filters .current-filters .placeholder {

```

and also a few in jquery.ui that you can ignore:

```
misc/ui/jquery.ui.draggable.min.js:40
misc/ui/jquery.ui.sortable.min.js:26
misc/ui/jquery.ui.sortable.min.js:27
misc/ui/jquery.ui.sortable.min.js:29
misc/ui/jquery.ui.sortable.min.js:39
misc/ui/jquery.ui.sortable.min.js:40
misc/ui/jquery.ui.sortable.min.js:43
misc/ui/jquery.ui.sortable.min.js:55
misc/ui/jquery.ui.sortable.min.js:56
misc/ui/jquery.ui.sortable.min.js:59
misc/ui/jquery.ui.sortable.min.js:60

```

You can safely ignore all this and just implement your own css for the .placeholder class in your theme.
> 1 votes

---
Tags: theming
---


# Question
Title: Get term name for page title from term id passed in the contextual filter?
What is the correct method of getting term name in the page title field if I have passed the term id in contextual filter. I have added the `Content: Has taxonomy term ID` contextual filter in views, I have tried to overwrite the page title be provide "%1" but that also provides term id as the "filter value type" contains term ID.

One way to achieve this using the "global php" field in the header and getting the term ID from the argument as "arg(1)", and getting the term name from the term ID and than setting page title using "drupal\_set\_title($term\_name)".

# Answer
> 0 votes
Got the solution:

The mistake I was doing was selecting the "Display all results for the specified field" for the "When the filter value is NOT in the URL" field of contextual filter, Instead I was supposed to do the following for this field:

* Check "Provide default value".
* Select Type: "Taxonomy term ID from URL"
* Select checkbox: "Load default filter from term page"

and rest everything as mentioned in the question.

# Answer
> 2 votes
**Answers Updated:** try this hook, hook\_view\_pre\_render()

> This hook is called right before the render process. The query has been executed, and the pre\_render() phase has already happened for handlers, so all data should be available.

```
function MYMODULE_views_pre_render(&$view) {
  if ($view->name == 'your_view_name') {
     $term = taxonomy_term_load(arg('arg_position_in_url'));
     $title = $term->name;
     $view->build_info['title'] = $title;
  }
}

```

---
Tags: views, 7
---


# Question
Title: Smart way to compare drupal instance files with official release to search for modified files
I was asked to update (just install new core and modules versions) a Drupal site that uses roughly 100 (yes: hundred) contributed modules. I suspect that some of these modules might have been modified, maybe including core.

I'm looking for a smart way that would allow me to utilize git (or some other tool) to automatically search for files that differ from the ones available in official release for specific module version (contributed or core).

I could use drush to dump installed modules names and versions or use some shell script to read that data from \*.info files. Then I could use that to generate git commands. So in theory it is not that difficult. But that's just a theory :)

So any input on this would be helpful from people who did similar things. Any caveats? Maybe other approach or just some code examples?

Or maybe there is a Drupal module that can do this for me?

# Answer
The Hacked! module is exactly what you're after:

> This module scans the currently installed Drupal, contributed modules and themes, re-downloads them and determines if they have been changed. Changes are marked clearly and if the diff module is installed then Hacked! will allow you to see the exact lines that have changed.
> 4 votes

---
Tags: drush, upgrading, version-control
---


# Question
Title: How to make #states work when dependant element is modified with JS .click()
We have custom JS that changes the value of some radio buttons using .click() and we have #states defined in other form elements that react to changes in those radio buttons.

The #states work fine when the radios are manually clicked but don't work when they are clicked through our custom JS .click() (the radio button values change, but the #states are not fired).

This is how the #states is defined:

```
'#states' => array(
  'invisible' => array(
    ':input[name="field_measure_system[und]"]' => array('value' => 'METRIC'),
   ),
),

```

and this is how the JS modifies the radio button:

```
$('a.tab-metric').click(function() {
$('#edit-field-measure-system-und-metric').click();

```

Thanks!

# Answer
Drupal states are bound to the change event, therefore you need to trigger that one too. The following snipped should do what you want:

```
$('#id-of-radio-button').trigger('click').trigger('change');

```
> 3 votes

---
Tags: 7, javascript
---


title: Hidding view tab on node/%/view

text:
# Question
Title: Hidding view tab on node/%/view
I've successfully managed to hide "View" tab on node page with this code:

```
/*
 * Implements hook_menu_local_tasks_alter().
 */
function mymodule_menu_local_tasks_alter(&$data){

    foreach ($data['tabs'][0]['output'] as $key => $value) {
        if ($value['#link']['path'] == "node/%/view"){
            unset($data['tabs'][0]['output'][$key]);
        }
    }
}

```

but when I enter the frontpage this error is displayed:

> Notice: Undefined offset: 0 in custom\_alter\_menu\_local\_tasks\_alter()... Warning: Invalid argument supplied for foreach() in custom\_alter\_menu\_local\_tasks\_alter()...

This line that causes the error is the following.

```
foreach ($data['tabs'][0]['output'] as $key => $value) {

```

I don't know what is wrong with the code. On frontpage there are no tabs and I don't have custom coding there.

I'm using Drupal 7.

# Answer
I dont know what is your purpose but to pass this error you just do that

```
/*
 * Implements hook_menu_local_tasks_alter().
 */
function mymodule_menu_local_tasks_alter(&$data){
  if(isset($data['tabs'][0]) && is_array($data['tabs'][0])){
    foreach ($data['tabs'][0]['output'] as $key => $value) {
      if ($value['#link']['path'] == "node/%/view"){
        unset($data['tabs'][0]['output'][$key]);
      }
    }
  }
}

```
> 1 votes

# Answer
The way to hide the node/%/view tab is to implement `hook_menu_alter()`, and change the menu defined from the Node module, which uses the following definitions.

```
  $items['node/%node'] = array(
    'title callback' => 'node_page_title',
    'title arguments' => array(1),

    // The page callback also invokes drupal_set_title() in case
    // the menu router's title is overridden by a menu link.
    'page callback' => 'node_page_view',
    'page arguments' => array(1),
    'access callback' => 'node_access',
    'access arguments' => array('view', 1),
  );
  $items['node/%node/view'] = array(
    'title' => 'View',
    'type' => MENU_DEFAULT_LOCAL_TASK,
    'weight' => -10,
  );
  $items['node/%node/edit'] = array(
    'title' => 'Edit',
    'page callback' => 'node_page_edit',
    'page arguments' => array(1),
    'access callback' => 'node_access',
    'access arguments' => array('update', 1),
    'weight' => 0,
    'type' => MENU_LOCAL_TASK,
    'context' => MENU_CONTEXT_PAGE | MENU_CONTEXT_INLINE,
    'file' => 'node.pages.inc',
  );

```

In particular, you need to change the menu type for node/%node/view from `MENU_DEFAULT_LOCAL_TASK` to `MENU_CALLBACK`, and change the type for node/%node/edit from `MENU_LOCAL_TASK` to `MENU_DEFAULT_LOCAL_TASK`.

`MENU_CALLBACK` keeps the menu item still accessible for those users who have the permission to see it, but the menu item would not be visible as tab or link.

As for using `hook_local_task_alter()`, I don't see Drupal core modules that alter the tabs added from other modules, but looking at blog\_local\_task\_alter(), I notice the following code.

```
  if ($root_path == 'blog') {
    $item = menu_get_item('node/add/blog');
    if ($item['access']) {
      $item['title'] = t('Create new blog entry');
      $data['actions']['output'][] = array(
        '#theme' => 'menu_local_action',
        '#link' => $item,
      );
    }
  }
  // Provide a helper action link to the author on the 'blog/%' page.
  elseif ($root_path == 'blog/%' && $router_item['page_arguments'][0]->uid == $user->uid) {
    $data['actions']['output']['blog'] = array(
      '#theme' => 'menu_local_action',
    );
    if (user_access('create blog content')) {
      $data['actions']['output']['blog']['#link']['title'] = t('Post new blog entry.');
      $data['actions']['output']['blog']['#link']['href'] = 'node/add/blog';
    }
    else {
      $data['actions']['output']['blog']['#link']['title'] = t('You are not allowed to post a new blog entry.');
    }
  }

```

In your case, you should check that `$root_path` is equal to node/%; in that way you would avoid to do something when the page being shown is the front page. (If node/% doesn't work, then node/%node should.)

I still think that `hook_local_tasks_alter()` should not be used in this case, as it seems to me that `hook_local_tasks_alter()` is thought to be used when altering the tabs depends from the page being viewed, as `blog_local_task_alter()` shows.
> 2 votes

---
Tags: hooks, routes
---


# Question
Title: How to truncate a given menu setting an expanded menu item as the root menu in drupal 7?
In my template `preprocess html` and `page` hooks, I test the current page of being a certain kind of node, set by the menu structure. Given such a menu:

main menu

* link 1
* link 2 (specials)
* \> link 2.1
* \> link 2.2
* link 3

Every node which menu's link has the menu parent `link 2` gets a treatment. On those nodes, I also want to only show all links inside link 2 menu, so start the main menu from that, so basically the main menu would then consist of `link 2.1` and `link 2.2`. How would you do that?

```
function mytheme_preprocess_html(&$vars) {

    $special = is_special_page();

    if ($special) {
        // alter menu
    }
}

function mytheme_preprocess_page(&$vars) {

    $special = is_special_page();

    if ($special) {
        // alter menu
    }
}

function is_special_page($node) {
    $breadcrumbs = drupal_get_breadcrumb();
    $businessMatch = preg_grep("/(specials?)/i", $breadcrumbs);

    return (count($businessMatch) > 0);
}

```

# Answer
I've figured it out myself, felt like sharing:

```
<?php
function _themename_submenu_tree_all_data($menu = 'primary-links', $mlid, $subonly = false) {
    $tree = menu_tree_all_data($menu);
    $childtree = null;

    /*
        thanks Jari http://stackoverflow.com/questions/19112294/how-to-extract-an-array-that-has-a-given-structure-and-whichs-key-value-matc/19112508?noredirect=1#comment28260688_19112508
    */

    function recursiveSearch($array, $key, $value){
      foreach($array as $sub){
        if ($sub['link'][$key] == $value)
          return $sub ;

        if (!empty($sub['below'])){
            $returned = recursiveSearch($sub['below'], $key, $value);
            if ($returned !== null)
                return $returned ;
        }
      }

        return null ;
    }

    $childtree = recursiveSearch($tree, 'mlid', $mlid);

    if ($subonly && $childtree != null) $childtree = $childtree['below'];

    return $childtree;
}

/**
 * Implements hook_preprocess_page().
 */
function themename_preprocess_page(&$vars) {
    if (arg(0) == 'node' && arg(1)) {
        $nid = arg(1);
        $node = node_load($nid);

        $vars['type'] = $node->type;

        // your internal check to see if the menu needs to be truncated

        $isbusiness = _themename_is_business_page($node);

        if ($isbusiness) {
            $trail = menu_get_active_trail();
            $mlid = $trail[ count($trail)-1 ]['mlid'];

            $sub = _themename_submenu_tree_all_data('main-menu', $mlid, true);
            $sub = menu_tree_output($sub);

            $vars['page']['main_menu']['menu_block_2']['#content'] = $sub;
        }
    }
}
?>

```
> 1 votes

---
Tags: routes
---


# Question
Title: hook_field_formatter_view does not get called
I have a custom field, that hooks into profile2 and saves it's value in user data blob. Everything works fine, except the hook\_field\_formatter\_view, that does not get called for a reason. As a result, when the field is viewed, it returns always an empty array. I have all declaration hooks in place.

```
<?php
 /**
  * Implementation of hook_field_info().
  */
 function profile_cal_field_info() {
  return array(
    'profile_cal' => array(
      'label' => t('Availability calendar'),
      'description' => t('Sets weekly available time.'),
      'default_widget' => 'profile_cal_cal',
      'default_formatter' => 'profile_cal_formatter',
    ),
  );
 }

 /**
 * Implements hook_field_formatter_info().
 */
 function profile_cal_field_formatter_info() {
  return array(
    'profile_cal_formatter' => array(
      'label' => t('Default'),
      'field types' => array('profile_cal'),
    ),
  );
 }

 /**
 * Implements hook_field_widget_info().
 */
 function profile_cal_field_widget_info() {
  return array(
    'profile_cal_cal' => array(
      'label' => t('Availability widget'),
      'field types' => array('profile_cal'),
      'multiple values' => FIELD_BEHAVIOR_DEFAULT,
      'default value' => FIELD_BEHAVIOR_NONE,
    ),
  );
}

 /**
 * Implements hook_field_formatter_view().
 */
 function profile_cal_field_formatter_view($entity_type, $entity, $field,     $instance, $langcode, $items, $display) {
  drupal_set_message('Called!');

  $element = array();

  return $element;
 }

 /**
 * Implements hook_field_is_empty().
 */
 function profile_cal_field_is_empty($item, $field) {
  return FALSE;
 }

 ?>

```

# Answer
> 0 votes
Your code is correct, I just tested it and it works for me. I created fresh Drupal instance, created profile\_cal module with your code without any modifications then added 'Availability calendar' field to 'Basic page' content type, created a page and got "Called!" message on the screen.

---
Tags: entities
---


title: Conditional fields in views drupal 6

text:
# Question
Title: Conditional fields in views drupal 6
I am using conditional field in content type.

Is it possible to do the same in views i want to show one field dependent on value of first.

Thanks

# Answer
Views Conditional is a simple module that allows you to define conditionals (if xxx then yyy) with fields in views.

> Conditions include:
>
> * Equal To
> * Not Equal To
> * Greater Than
> * Less Than
> * Empty
> * Not Empty

**For D6**

Views - Control field display

> It provides a views filter that allows users to control which fields are displayed.
>
> To use, install the module, then add the Global: Control field **visibility filter** to your view. Select which fields are controllable (either defaulting to visible or invisible). This will add an exposed element that allows users to toggle the fields you specify on or off.
> 1 votes

---
Tags: views
---


# Question
Title: Using EntityFieldQuery to order nodes in an OG Group using node_comment_statistics table
I have an EntityFieldQuery to fetch nodes of a certain type which belong to an OG group in a Drupal Commons instance.

```
  $query = new EntityFieldQuery();
  $query->entityCondition('entity_type', 'node')
    ->entityCondition('bundle', array('post', 'document', 'link'), 'IN')
    ->propertyCondition('status', 1)
    ->fieldCondition('og_group_ref', 'target_id', $panel_args[0], '=');

```

I was wondering if it was possible to also add the condition to order the nodes by most recent comment using the information from the `node_comments_statistics` table and the `last_comment_timestamp`.

Is this possible with EFQ since their are no joins? Or will I have to fall back to a basic Drupal Query?

# Answer
Add the custom `TAG` to the EntityFieldQuery and than use the hook\_query\_TAG\_alter() to add the JOIN to the query as below:

```
// Create the query as below (Note: "CUSTOMTAG" added for altering the query)
$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', array('post', 'document', 'link'), 'IN')
  ->propertyCondition('status', 1)
  ->fieldCondition('og_group_ref', 'target_id', $panel_args[0], '=');
  // Added the Tag, which we will be using to alter the query.
  ->addTag('CUSTOMTAG');
  // Complete the query (if you are having any other field condition).
  ->execute();

/**
 * Implements hook_query_TAG_alter()
 */
function MyModule_query_CUSTOMTAG_alter(QueryAlterableInterface $query) {
  // Add the join to the "node_comment_statistics" table.
  $query->join('node_comment_statistics', 'ncs', 'ncs.nid = node.nid');
  $query->orderBy('ncs.last_comment_timestamp')
}

```

Reference links: https://drupal.org/node/1157006#comment-7634027 http://www.phase2technology.com/blog/or-queries-with-entityfieldquery/
> 1 votes

---
Tags: organic-groups, 7, database
---


# Question
Title: Drupal Commerce: IPN received - When order paid in full not triggered
**Problem**

I'm testing on a live website and the trigger "When an order is paid in full" is not triggered by Paypal. I'm receiving the IPN and the payments are successful. Is there some set-up I'm missing?

**Set-Up**

I have Drupal Commerce and Commerce Paypal installed, I've got the latest versions of both of them and rules.

I'm using Paypal Sandbox for my payments and it's the only payment method. It's set-up according to http://www.drupalcommerce.org/user-guide/paypal-standard.

The payments are being paid and received in the sandbox.

I'm receiving the IPN's (here's the latest one from admin/reports/dblog) so why is the trigger not firing?

```
[mc_gross] => 12.38
[invoice] => 21-1380584852
[protection_eligibility] => Ineligible
[item_number1] =>
[payer_id] => ARQWQ9YGG73F4
[tax] => 0.00
[payment_date] => 16:46:30 Sep 30, 2013 PDT
[option_selection1_1] => 1
[payment_status] => Completed
[charset] => windows-1252
[mc_shipping] => 0.00
[mc_handling] => 0.00
[first_name] => Dominic
[mc_fee] => 0.62
[notify_version] => 3.7
[custom] =>
[payer_status] => verified
[business] => captain12a@msn.com
[num_cart_items] => 1
[mc_handling1] => 0.00
[payer_email] => captain14a@hotmail.co.uk
[verify_sign] => AiPC9BjkCyDFQXbSkoZcgqH3hpacAQf5aelWDuTPmoMQ5vx5hMDCzulp
[mc_shipping1] => 0.00
[tax1] => 0.00
[option_name1_1] => Product count
[txn_id] => 7Y390707M1183591C
[payment_type] => instant
[last_name] => Woodman
[item_name1] => Order 21 at drupaltest2
[receiver_email] => captain12a@msn.com
[payment_fee] =>
[quantity1] => 1
[receiver_id] => 2FHV6QVKKQXY4
[txn_type] => cart
[mc_gross_1] => 12.38
[mc_currency] => GBP
[residence_country] => GB
[test_ipn] => 1
[transaction_subject] =>
[payment_gross] =>
[auth] => A41o8UNEox9bol5SH7hvw4jIMV-gR-9qubh3WKMZ9hmLr7oTiHMUATibYSUjrjlHHqDUlwDOlwNt10ZLGJt8xDw

```

(I checked the trigger using ZioBuddha's idea and it works fine for cheque's)

# Answer
> 2 votes
It randomly started working. Here's what I did to debug in-case it helps someone else:

* IPN only works on a live server not a localhost. Paypal can't talk to localhost.

**Debug on Drupal Side - In Payment Rules**

Enable Log notifications with the full IPN during validation and processing (used for debugging).

It'll get stored at `example.com/admin/reports/dblogs`. You can see a sample IPN in my post.

I was originally getting the IPN in a log that looked like:

```
commerce_paypal_wps  |  1 Oct 2013 - 12:48am  | Customer returned from PayPal with the following POST...  |   username

```

That log contained the IPN in my original post.

**Paypal Settings**

You don't need to enable IPN notifications because the module does it automatically when it needs to. But if you do then you can view your history and see if they were getting sent. (I put `example.com` in the PayPal URL field.)

The only thing I did here was try re-sending an IPN.

**What you should have**

When it works your log should have something like this in it

```
commerce_paypal      |  1 Oct 2013 - 11:46am  |  Attempting to process IPN 7Y390707M1183591C. Array...   |  Anonymous (not verified)
commerce_paypal_wps  |  1 Oct 2013 - 11:46am  | IPN validated for Order 21 with ID 7Y390707M1183591C...  |  Anonymous (not verified)
commerce_paypal_wps  |  1 Oct 2013 - 11:46am  | IPN processed for Order 21 with ID 7Y390707M1183591C.    |  Anonymous (not verified)

```

# Answer
> 0 votes
Yes, you can trigger the event: go into orders admin page, view the order that you want to "trigger" and in the right side you can see "payment". Click that link and insert the exact amount of the order. Save and voilà: your order is paid in full.

I have no Commerce to test this for the exact url page, but in this way it works. I have test it more and more time for my clients web site.

M.

---
Tags: 7, commerce, payment-gateways
---


# Question
Title: How can I require that browscap.ini / get_browser() is functioning before allow a my module to be installed?
I have a module for my Drupal 7.x installation which needs browscap.ini / get\_browser().

The module works perfectly, but I want to make sure the browscap.ini is installed before installing of enabling the module. That way the module will not work unless browscap is installed correctly.

How can I do this?

# Answer
I fixed it using the following code:

```
/**
 * Implementation of hook_requirements().
 *
 */
function aserv_support_requirements($phase) {
  $requirements = [];

  if ($phase == 'install' || $phase == 'runtime') {

    if (!get_cfg_var('browscap')) {
      $requirements['aserv_support'] = [
        'title'    => t('Browscap not installed'),
        'value'    => 'Browscap has not be installed. Please install Browscap before enabling this module.',
        'severity' => REQUIREMENT_ERROR,
      ];
    }
  }

  return $requirements;
}

/**
 *  Implementation of hook_enable()
 */
function aserv_support_enable() {
  if (!get_cfg_var('browscap')) {
    drupal_set_message(t('ERROR Enabling Aserv_Support: Browscap has not be installed. Please install Browscap before enabling this module.'), 'error');
    module_disable(['aserv_support']);
  }
}

```
> 1 votes

---
Tags: 7, installation
---


# Question
Title: Limited popup like once per month and user
Is there a module for Drupal that has the following options:

* show a popup once in a month/day/... should be configurable
* save this information in a cookie or else
* the popup should display some text and nothing else

# Answer
check if

splashify module can help you here

> Display a splash page anywhere on your site by redirecting the user, showing a lightbox, or displaying a popup. This module is designed to be search engine friendly, mobile device friendly and offers multiple configuration options.Instead of using cookies to determine when the splash page shows up, we use jStorage.

Popup Message

> Display popup message for users once per browser session.
> 1 votes

---
Tags: javascript
---


title: Add language menu to the main menu

text:
# Question
Title: Add language menu to the main menu
I have menu structure like this:

Home | About | Products

if a user is currently on English page then I need like this:

Home | About | Products | Swedish

and if a user is currently on Swedish language then it will show like:

Home | About | Products | English

1: So how can I add a menu switcher link to the main menu which shows only one language link at a time? 2: What will be the pate for each of the language in the path field while adding a menu link.

# Answer
I have solved my problem with the help of a friend. I have created a list of two menus lists using menu-block module. One set of English menus and one set of Swedish menus in the following order.

Home | About | Products | Svenska

and for Swedish

Hem | OM | Produkter | English

After creating the menus , I was unable to provide URL or link to a node (/node/3) OR language (/?language=en) in the path field while creating the link item.

In my case if I change the language such as (http//mysite.com/?q=en) to (http//mysite.com/?q=sv) the above created Swedish menu-block appears. As Swedish menu-block was enabled on Swedish language and English on English menu-block. After that I change one of the hook available in the main theme to my requirement.

I used yourtheme\_menu\_link() hook in template.php file. Under the set of if statements I added this block.

```
    if ($element['#original_link']['mlid'] == 2662) {
    global $language;
     $lang = $language;
     $lang->prefix = "en";
    $special_link = '<a href="' . url('<front>', array('language' => $lang)) . '">English</a>';
} else if ($element['#original_link']['mlid'] == 2675) {
    global $language;
     $lang = $language;
     $lang->prefix = "sv";
    $special_link = '<a href="' . url('<front>', array('language' => $lang)) . '">Svenska</a>';
}

if (at_get_setting('extra_menu_classes', $theme_name) == 1 && !empty($element['#original_link'])) {
  if (!empty($element['#original_link']['depth'])) {
    $element['#attributes']['class'][] = 'menu-depth-' . $element['#original_link']['depth'];
  }
  if (!empty($element['#original_link']['mlid'])) {
    $element['#attributes']['class'][] = 'menu-item-' . $element['#original_link']['mlid'];
  }
}

```

Here 2662 and 2675 is the menu item id. This may help if someone need. It solved my problem.
> 2 votes

# Answer
You have two ways of doing this, one is to use HTML/CSS to position the language switcher block in the menu, probably a little harder to do with a variable length menu unless you right align it.

Two would be to add the language switcher to the menu, you can use something like http://www.liquidcms.ca/how-to-language-switcher-menu-item to do that.
> 2 votes

# Answer
Menu per language module will have the option

> This module enables you to have an clear overview per language what the menu entries are. In Drupal all of these links are on the same page and thus it is not clear in which language it is and the menus will grow very big in time aswell.
> 2 votes

---
Tags: routes, i18n-l10n
---