# Question
Title: Changing the order used to show the weekdays
I have installed the event calendar module.

The problem that I have is that the calendar block outputs as follows:

> S M T W T F S

where I would like it to be outputted as follows:

> M T W T F S S

I've tried looking at other sources but I cannot seem to find a solution.

Can anyone offer a solution?

Thanks in advance.

# Answer
Hopefully that module integrates with the rest of the system properly - if it does, you can go to /admin/config/regional/settings and change "First day of week" to Monday.
> 2 votes

---
Tags: 7, views, blocks
---


# Question
Title: Get the body of content referenced in an Entity Reference field in node
I have a content type "event" which contains an entity reference to another content type "speaker". The speaker content type contains image and body fields. If I select a speaker for my event, I am only able to output a link to the speaker within the event node page. Is there a way I can output the image and body fields within the referenced speaker content in the event node page?

# Answer
> 2 votes
Found it:

Content Type \> Manage Display

Change Format to "Rendered Entity"

---
Tags: 8, entities
---


title: Drupal Views Datasource and Flag Links

text:
# Question
Title: Drupal Views Datasource and Flag Links
I want to use Views Datasource module to output JSON, i then want to construct the JSON output using REACT JS or alike. I am currently stuck on how to output the Flag Link, it just comes back with an OPS field. Ideally i want this as a plain link so I can trigger it through jquery/ajax.

UPDATE: as requested using the php field i managed to get the output i was after which is something like:

# Answer
> 0 votes
Unfortunately I couldn't get the perfect solution to this so I had to use Views PHP. Remember to add a hidden field for the nid of the node

```
<?php
$link = flag_create_link('MyFlagMachineName', $row->nid);
preg_match_all('/<a[^>]+href=([\'"])(.+?)\1[^>]*>/i', $link, $result);
if (!empty($result)) {
  echo $result[2][0];
}
?>

```

---
Tags: views, flags, 8
---


title: MAC -> Drush higher bootstrap level?

text:
# Question
Title: MAC -> Drush higher bootstrap level?
Since a couple of days now, i switched from a ubuntu machine to a macbook pro retina for my development works.

I installed XAMPP on it, without to much trouble. But I have been struggeling with drush for quite some time now, and I am hoping to find a little help here.

Drush partially works... I can download Drupal, download modules etc. I CANNOT enable the modules, perform sql-cli commands (however sql-connect DOES work?!).

The error i get is:

```
Command pm-enable needs a higher bootstrap level to run - you will need to invoke drush from a more functional Drupal environment to run this command.                                           [error]
The drush command 'en token' could not be executed.                                                                                [error]
Drush was not able to start (bootstrap) the Drupal database.                                                                                [error]
Hint: This may occur when Drush is trying to:
 * bootstrap a site that has not been installed or does not have a configured database. In this case you can select another site with a working database setup by specifying the URI to use with
the --uri parameter on the command line. See `drush topic docs-aliases` for details.
 * connect the database through a socket. The socket file may be wrong or the php-cli may have no access to it in a jailed shell. See http://drupal.org/node/1428638 for details.

Drush was attempting to connect to:
 Drupal version         :  7.28
 Site URI               :  http:// default
 Database driver        :  mysql
 Database hostname      :  localhost
 Database username      :  root
 Database name          :  drupal_site
 PHP executable         :  /usr/bin/php
 PHP configuration      :  /Users/myusername/drush/php.ini /Users/myusername/drush/php.ini
 PHP OS                 :  Darwin
 Drush version          :  7.0-dev
 Drush temp directory   :  /tmp
 Drush configuration    :
 Drush alias files      :
 Drupal root            :  /Applications/XAMPP/htdocs/drupal_site
 Site path              :  sites/default

```

Now I have been googling around for this for days and found numerous topics, stating all kinds of things (change your settings.php file to use 127.0.0.1 instead of localhost =\> did not work)

One thing i would like to add is that i discovered that my OS runs a different php version as the XAMPP instance?!

Ps: My drupal\_site is fully functional! Just drush won't work with me.

Any help would be very much appreciated!

Best,

# Answer
Your drush is using system php, whereas Drupal is using XAMPP's. This reliably creates drush problems.

Look into XAMPP and figure out where its php binary is and then set your path accordingly in .bashrc or whatever other shell init files you have sitting around.

Check your progress with *drush status*, in particular what it reports for the database connection.
> 2 votes

# Answer
You can explicitly provide drupal installation using `--root` option

```
drush status --root=/path/to/drupal

```

OR you can create a alias for your site,

First find where is your drush home directory is,

```
drush ev 'print(drush_server_home());'

```

Now create a file,

```
vim drush_home_path/.drush/drushrc.php

```

and put the contents as below,

```
$aliases['drupal_site'] = array(
  'root' => '/path/to/drupal/',
  'uri' => 'drupal_site',
);

```
> 0 votes

# Answer
@ChristophWeber got me on the right track. I solved the problem by opening my .bash\_profile (create your own if you don't already have one). I then added these two lines. The first tells drush to use the XAMPPs PHP rather than the default. The second line makes mySQL available (you can test if mysql is available by typing 'mysql' into the terminal).

Lines to add to .bash\_profile:

```
export DRUSH_PHP='/Applications/XAMPP/bin/php'
export PATH=/Applications/XAMPP/bin/:$PATH

```
> 0 votes

# Answer
Use "127.0.0.1" instead of "localhost" as the hostname.
> -1 votes

---
Tags: drush
---


# Question
Title: How to add a condition (rule) to skip questions when using the Quiz module?
I'm using Quiz module and I have a quiz with questions 1 to 10.

I want this:

Question 1: If answer is yes **jump** to question 2. If answer is no jump to question 7.

How can I achieve this? Do I need to use Rules module?

# Answer
> 1 votes
To get this to work using the Rules module (which I'd also use for this), you should ALSO use the Conditional Rules module. Some more details about this module (from its project page):

> ... provides Rules plugins for conditionally altering execution flow directly inside a group of **actions**.

Some examples of using the Conditional Rules module:

So by using both of these modules, you could use a **Rules Action** to redirect (= jump) to either question 2 or question 7, based on the answer (yes or no) provided to question 1.

This would answer your question for "question 1". By creating up to 10 similar rules (1 for each question that has a similar requirement), you should have a solution for all other questions that would need it also. However, you should be able to take advantage of other facilities that the Conditional Rules module offers (by constructing complex conditions as a condition set and then use those in the condition elements). So that you include all the required logic (for all your 10 questions) in a single Rule.

---
Tags: quiz
---


# Question
Title: How to refresh a coded block when a flag is clicked in it?
I have created a block in which I display a flag. All of it is done programatically. The content of the block changes depending on the flag status, but when a user clicks on the flag, it does not refresh the page or the block. The content is currently refreshed only when I reload the page.

I have gone as far as to create a callback from my block module to a jquery file, but I do not quite know where to go from here. I am not familiar enough with jquery to fully understand what to do, and how to use the callback function. Here is what I have thus far in my .module file:

```
/**
* Implements hook_init().
*/
function mymodule_init() {
drupal_add_library('system', 'drupal.ajax');
}
/**
* Implements hook_menu().
*/
function mymodule_menu() {
$items = array();

$items['block/reload'] = array(
  'title' => 'Refresh block',
  'page callback' => 'mymodule_refresh',
  'access callback' => TRUE,
  'type' => MENU_CALLBACK,
);

return $items;
}

/**
* Menu callback.
*/
function mymodule_refresh($action, $type) {

}

```

In a .js file which I have put in a folder 'js' in my module's folder, I have created this:

```
(function($){

$(document).bind('flagGlobalAfterLinkUpdate', function(event, data) {

}

});

})(jQuery);

```

# Answer
The easiest way would be to use the module Block Refresh. With this module you can set up any block to be reloaded both manually and by an interval. For your use case you would chose the first option, here is an example form the block configuration page:

You will see now a refresh button on blocks title, which could be hidden by the following CSS:

```
.block-refresh-button {
    display:none;
}

```

and then triggered by clicking the flag:

```
$(".flag").click(function() {
    $(".block-refresh-button").each(function() {
        $(this).click();
    });
});

```

I did not test the code.
> 2 votes

# Answer
To reload the page:

location.reload();

http://www.w3schools.com/jsref/met\_loc\_reload.asp
> 0 votes

---
Tags: blocks, javascript, flags
---


# Question
Title: Transfer Value of Field to Another Field under Content Type Manage Fields
I have created several content types and unfortunately, I made a mistake on some of the fields. The fields are field\_image and field\_screenshot.

Under manage fields, I use field\_image and sometimes field\_screenshot. Now I want to use one field only for featured image on my node content. So, how can I transfer the value of field\_image to field\_screenshot? Is this possible?

# Answer
> 8 votes
No, this is not easily possible through the Drupal interface. You will need to execute a custom SQL query to move your data from one field to another.

The following two queries will copy all field data from field\_image to field\_screenshot **for each entity where field\_screenshot is empty**.

```
INSERT INTO field_data_field_screenshot
SELECT a.*
FROM field_data_field_image a
LEFT JOIN field_data_field_screenshot b ON a.entity_id = b.entity_id
AND a.entity_type = b.entity_type
WHERE b.entity_id IS NULL

```

and

```
INSERT INTO field_revision_field_screenshot
SELECT a.*
FROM field_revision_field_image a
LEFT JOIN field_revision_field_screenshot b ON a.entity_id = b.entity_id
AND a.entity_type = b.entity_type
WHERE b.entity_id IS NULL

```

After running this you can then delete the first field.

If field\_screenshot alreadly has data that you want to overwrite you will need to delete it first using these queries. **Make sure this is what you want to do first because this WILL delete your data**

```
TRUNCATE TABLE field_data_field_screenshot
TRUNCATE TABLE field_revision_field_screenshot

```

# Answer
> 0 votes
Here is how you can do it in a module with COMBO of db\_query and db\_insert

```
$result = db_query('SELECT a.*
  FROM {field_data_field_image} a
  LEFT JOIN {field_data_field_screenshot} b ON a.entity_id = b.entity_id
  AND a.entity_type = b.entity_type
  WHERE b.entity_id IS NULL'
);

$records = $result->fetchAll();
foreach ($records as $record) {
  db_insert('field_data_field_screenshot') // Table name no longer needs {}
        ->fields(array(
          'entity_type' => $record->entity_type,
          'bundle' => $record->bundle,
          'deleted' => $record->deleted,
          'entity_id' => $record->entity_id,
          . // All Columns
          .
          .
          .
        ->execute();
}

```

And repeat the revision field as well.

---
Tags: 7
---


# Question
Title: Does a user role change remove their Profile2 fields?
Say I have a user role PendingArtist, and its Profile2 fields: skills and about me.

How do I change the role of a user? And does the role change delete the PendingArtist's Profile2 fields?

Edited: Don't know why I asked this, could have tried it out myself. Please ignore this question.

# Answer
If you are using Profile2 in combination with Profile2 Reg Path (which you probably do or in this case - might as well use it), then you'll find two sections when you are editing Profile2 (*at admin/structure/profiles/manage/profile\_name\_here*) :

1. **Roles** \- that's where you assign which roles will have the fields from Profile2;
2. **Assign Roles During Registration** \- that's where you set the roles to assign to a newly registered user if user creates a profile following the path you've set.

So, in your application you'd check "PendingArtist" and "ApprovedArtist" in *`"Roles"`* section, so that your fields show up for both of those roles. Then, in *`"Assign Roles During Registration"`* section you would check only "PendingArtist", so that only PendingArtist role gets assigned to a newly created user. In the end, when the role of PendingArtist is changed to ApprovedArtist - the data entered in profile2 fields remains as entered originally.
> 2 votes

---
Tags: 7, users
---


# Question
Title: How to disable all commerce modules from Commerce Kickstart using Drush?
I need to disable all commerce modules from the Commerce Kickstart distribution. I've done this before using the drupal backend admin/modules and have no problem at all but it took me around 4hs because of the modules dependencies.

This time I would like to do it using Drush.

How can I do this?

I tried with `drush dis -y commerce` but I get a lot of error/warning lines (not sure if it worths to post them here...) and get the site broken.

# Answer
> 2 votes
Note that by disabling all of the Kickstart specific modules (which is practically required to uninstall Commerce due to dependencies) may cause your site to become unusable. If you're using the image rotator or the Kickstart specific content types things could get really crazy. You've been warned. **Go slowly.**

I know you want to know how to do it in drush, but using the UI will likely be easier given the amount of time it will take to do this:

1. Uninstall the Kickstart specific modules. These will be all of the modules whose **Package** is **Commerce Kickstart**. There should be 18 of these. Disable one or two at a time. You have to do these first.
2. Once those are done, then you'll need to go through and disable all of the Commerce Contrib modules. These would be modules found under **Commerce (Contrib)**, **Commerce (*whatever*)**, etc.
3. Once those are done, then you should be able to disable the Commerce core modules.

# Answer
> 1 votes
If you try to disable too many modules at once, especially modules that have interdependencies, weird stuff can happen.

One way to do this is to go to the modules page, look at what commerce modules you can uncheck, and then make a list of those. Then write them in a list. Then go back to the page and do it again, and again, and again until you disable all the modules you wanted.

Then take your lists and write a drush command like this:

`drush dis commerce_product_ui other_modules_in_set_1 -y; drush dis module_in_set_2 -y; drush dis module_in_set_3 -y`

You can set this to a bash alias then to do it quickly and easily in the future. Ugly and untested but it will probably work.

# Answer
> 1 votes
1. It's not recommended to disable commerce after installing
2. It's *really* not recommended to try to uninstall commerce after installing
3. **Recommended** \- The easiest way to do it with kickstart would be simply using the commerce kickstart profile, and then not installing the kickstart profile. Then you're turning on modules instead of trying to turn them off.

---

If you can map the dependencies, then going from least dependent to most dependent, you could disable the commerce modules using drush. I would start with all the features, then move on to commerce\_x modules that aren't core, then on to core modules.

`drush pm-disable least_dependent` // most likely features

`drush pm-disable moderately_dependent` // most likely commerce\_x contrib

`drush pm-disable most_dependent` // most likely commerce\_x core modules

---
Tags: 7, commerce, drush
---


title: Get menu item of a content type

text:
# Question
Title: Get menu item of a content type
Is it possible to get the menu item of a certain content type through the API?

The idea is to improve Markus Orenstrat solution to set the active trail based on the content type. As it stands it requires hardcoding the `menu_tree` id in the service.

```
 if ($bundle == 'blog') {
   $plugin_id = 'menu_link_content:a00a209d-075e-46a2-b200-e2d439d92228b';
 }

```

I figured this could be avoided since the administration area allows to assign a menu item to a content type.

# Answer
> 1 votes
That's stored in the third party settings of the node type.

```
$type = NodeType::load('article');
$type->getThirdPartySetting('menu_ui', 'parent')

```

See also menu\_ui\_get\_menu\_link\_defaults().

---
Tags: routes, 8, entities
---


# Question
Title: How to set a value programatically only when a content type is saved for the first time?
I'm trying to record the user agent string into a text field (`field_useragent`) the first time a content type is saved. This is what I tried:

```
/*
 * Implements hook_ENTITY_TYPE_insert()
 */
function mymodule_node_insert(Drupal\Core\Entity\EntityInterface $entity) {
  if ($entity->getType() == 'my_content_type') {
    // Log the user agent.
    $entity->set("field_useragent", $_SERVER['HTTP_USER_AGENT']);
  }
}

```

But, this doesn't save the user agent string. So I tried using this code:

```
/*
 * Implements hook_ENTITY_TYPE_presave()
 */
function mymodule_node_presave(Drupal\Core\Entity\EntityInterface $entity) {
  if ($entity->getType() == 'my_content_type') {
    // Log the user agent.
    $entity->set("field_useragent", $_SERVER['HTTP_USER_AGENT']);  }
}

```

This saves the user agent string, but it does so every time the node is edited. How can I save it only upon insertion?

# Answer
As per @Ivan Jaros comment:

```
/*
 * Implements hook_ENTITY_TYPE_presave()
 */
function mymodule_node_presave(Drupal\Core\Entity\EntityInterface $entity) {
  if ($entity->getType() == 'my_content_type') {
    /// Log the user agent if the account is being created.
    if ($entity->isNew()) {
      $entity->set("field_useragent", $_SERVER['HTTP_USER_AGENT']);
    }
  }
}

```
> 1 votes

---
Tags: hooks, 8
---


title: Customize admin form field in

text:
# Question
Title: Customize admin form field in
I need to customize the aspect of one single field in a editing admin form. More specifically I want change the height of a multiselect field. Have I to create complete admin sub-theme containing just a one-line CSS file or there is another way to achieve this?

# Answer
> 2 votes
You could use `hook_form_alter` in a module to attach a the CSS (library) to the form with the needed changes.

---
Tags: forms, 8, theming
---


# Question
Title: LDAP Module - Notice: Trying to get property of non-object in ldap_authentication_init() appears
I have a site with Drupal 7.41 and LDAP module version 7.x-2.0-beta8. My goal is to connect my drupal site with an Active Directory account. After I installed LDAP module i saw a error message: Notice: Trying to get property of non-object in ldap\_authentication\_init() (line 223 of \[... \] ldap/ldap\_authentication/ldap\_authentication.module) But i thought that was a part of Module. When i configure and test my module, this error message still appears. The stack of test is:

```
            sid = empresa.cl
            numeric_sid = 1
            name = empresa.cl
            status = 1
            ldap_type = default
            address = XX.XXX.X.XXX
            port = 389
            tls = 0
            followrefs = 0
            bind_method = 2
            basedn = Array ( [0] => ou=chile,dc=empresa,dc=cl )
            binddn =
            user_dn_expression = empresa//%username
            user_attr = samaccountname
            account_name_attr =
            mail_attr = mail
            mail_template =
            picture_attr =
            unique_persistent_attr =
            unique_persistent_attr_binary = 0
            ldap_to_drupal_user =
            testing_drupal_username = nombre
            testing_drupal_user_dn = CN=nombre, OU=chile, DC=empresa, DC=cl
            grp_unused = 0
            grp_object_cat =
            grp_nested = 0
            grp_user_memb_attr_exists = 0
            grp_user_memb_attr =
            grp_memb_attr =
            grp_memb_attr_match_user_attr =
            grp_derive_from_dn = 0
            grp_derive_from_dn_attr =
            grp_test_grp_dn =
            grp_test_grp_dn_writeable =
            search_pagination = 0
            search_page_size = 1000

```

Any possible suggestion or advice for this problem?

# Answer
> 1 votes
This message disapears when i add data in a 'Authorization Tab' In a email section and I select a "LDAP Server Type" (This option belongs to LDAP server's configuration from Server tab) such as Active Directory.

Thank, you Anyway

---
Tags: authentication-authorization
---


# Question
Title: Long-running cron task never fully executed
I am developing a Drupal Cron that has a very long-running task. First I tried with a simple Cron, which, of course, did not work because of "Memory exhausted" PHP fatal error.

Then, I developed a Batch with the Batch API which worked fine as a normal Batch. However, I could not make to run it completely inside the Cron. It receives the same PHP error.

After that, I developed a Cron using the Queue API. However, I could not make Drupal to run all queue jobs in the same cron. The execution stops at some point and I am unable to run more jobs. I know that there is an option to define the worker's function time, but my task is a long-running task. So it is limited by PHP.

I also tried to use Background Process module in order to execute my long-running task but it had the same problem as before: the execution stops at some point.

I am sure that the code can be executed completely. The only working way was through Batch page but I want to run it automatically every day (Cron).

Do you know how can I run a Cron until it finishes?

As I said, I tried with Batches and Queues but it did not work. PHP "memory exhausted" or timeout errors appear or the execution can be cut by Drupal.

Thank you.

# Answer
> 3 votes
After a long battle analyzing how to execute a long-running task as a Drupal Cron, finally I found a generic solution that involves the Queue API and Cron. Maybe this can help other people who is struggling with a similar problem. Here are the steps I followed:

1. Think about how to execute your long-running task as chunks in terms of **Drupal Queue items**. You need to represent all tasks as queue items. For example, the first item (or action) may be to initialize the complex work that needs to be done. Then, the following items may execute that work by pieces. Each item (or chunk) has to be processed individually, so no PHP Timeout or PHP Memory Exhausted error appear.
2. **Create a new Cron that will create the queue and its items**. Make sure that you also implement the `hook_cron_queue_info()`.
3. **Implement the queue item process function** you defined in the above hook. If you need to pass information between each item process, you can use Drupal's `variable_get(...)` and `variable_set(...)`. If you need a more complex structure, you can define a database with Schema API in the module `my_module.install` file.
4. Now **create a new function** that will read and process one or more items of your queue (if not empty).

For example:

```
function my_module_process_my_queue() {
  $my_queue = DrupalQueue::get('my_module_queue');
  if ($my_queue->numberOfItems() > 0) {
    $action = $my_queue->claimItem();
    if ($action) {
      my_module_queue_process_item($action->data);
      $my_queue->deleteItem($action);
    }
  }
}

```
5. **Install a Cron module** (such as Elysia Cron) **or add a cron job in your server configuration**. At least, you need to specify the execution of 2 Cron functions. The first one (from step 2) will run the moment you prefer. In my case, it has to run once a day. The second one will be a simple Cron that will call the function from step 4. That second Cron will run every X minutes. Where X means the maximum time execution that a queue item processing may take. If you do not install a Cron module, you do not need the second Cron function. In my case, I decided to use Linux `crontab` configuration and Drush.

For example:

```
*/2 * * * * cd /path/to/your/drupal/installation && export DRUSH_PHP=/path/to/your/bin/php && drush ev "my_module_process_my_queue();"

```
6. Finally, **execute your crons or wait until they are executed**. Once a day, the queue will be filled with new queue items. Those items will be processed during the first Cron execution and every X minutes with the other one. So, after some time, all queue items will be processed and the long-running task will finish.

---
Tags: cron
---


title: How do I alter the node entity?

text:
# Question
Title: How do I alter the node entity?
Maintainer of Custom Publishing Options here... trying to figure out how to port to 8 in a clean way.

https://www.drupal.org/node/2647410

I have config entities working, so I can define custom publish options in the admin.

From here, I would like to add these options on the Node form(s), but they also need to be stored in node\_field\_data table. Previously hook\_schema\_alter / entity\_info\_alter was used to do this, example below:

D7:

```
/**
 * Implements hook_schema_alter().
 */
function custom_pub_schema_alter(&$schema) {
  $types = variable_get('custom_pub_types', array());
  foreach ($types as $type) {
    $schema['node']['fields'][$type['type']] = array(
      'description' => t('Custom publishing option @name', array('@name' => $type['name'])),
      'type' => 'int',
      'not null' => TRUE,
      'default' => 0,
    );
  }
}

```

D8:

```
function custom_pub_entity_base_field_info(EntityTypeInterface $entity_type) {
  if ($entity_type->id() === 'node') {
    $fields = [];

    foreach (Drupal::entityTypeManager()->getStorage('custom_publishing_option')->loadMultiple() as $machine_name => $publish_option) {
      $fields['cpo_' . $publish_option->id()] = BaseFieldDefinition::create('boolean')
        ->setLabel(t('!label', ['!label' => $publish_option->label()]))
        ->setDescription(t('A status added by custom publishing options.'))
        ->setRevisionable(TRUE)
        ->setTranslatable(TRUE)
        ->setDefaultValue(FALSE)
        ->setDisplayConfigurable('form', TRUE);
    }

    return $fields;
  }
}

```

`$fields` looks good here, and no errors are thrown - yet, I do not see any change to the data in the database. I would expect fields to be added to the node\_field\_data table, what is missing here? hook\_schema\_alter() has been removed, is there a way to trigger this to update that I don't see?

The purpose of this module is to let admins define their own statuses to use with the default node statuses, which from there they can combine them for different Views/Rules/Action capabilities. Being set on the node similar to status/promote/sticky made it fairly quick.

# Answer
> 3 votes
When entities are created, I had to do this to create them in the node table:

```
$manager = \Drupal::entityDefinitionUpdateManager();

if ($is_new) {
      // create the field definition for the node
      $storage_definition = BaseFieldDefinition::create('boolean')
        ->setLabel(t('!label', ['!label' => $label]))
        ->setDescription(t('!description', ['!description' => $description]))
        ->setRevisionable(TRUE)
        ->setTranslatable(TRUE)
        ->setDefaultValue(0)
        ->setDisplayConfigurable('form', TRUE);

      $manager->installFieldStorageDefinition($id, 'node', 'custom_pub', $storage_definition);
    } else {
      $storage_definition = $manager->getFieldStorageDefinition($id, 'node');

      if (isset($storage_definition)) {
        // update the label and description on the definition
        $storage_definition
          ->setLabel(t('!label', ['!label' => $label]))
          ->setDescription(t('!description', ['!description' => $description]));

        $manager->updateFieldStorageDefinition($storage_definition);
      }
    }

```

---
Tags: nodes, 8, entities
---


# Question
Title: Trying to modify a menu with hook_menu_alter
What is the best way to add a link to the user menu for a menu defined in my custom module?

# Answer
> 2 votes
Implement the hook\_menu() in your custom module, then clear the cache and you will see the link in the User menu (you need place the block for the User menu in a region).

```
function YOUR_MODULE_NAME_menu() {
   $items = array();
   $items['/path'] = array(
   'type' => MENU_NORMAL_ITEM,
   'menu_name' => 'user-menu',
   'title' => t('Title'),
  );
  return $items;
}

```

---
Tags: 7, routes, hooks
---


title: Update field schema

text:
# Question
Title: Update field schema
Now that `content_alter_db()` has been removed from D7, what is the recipe to update a field's schema?

My field needs to change from

```
function sheetnode_field_schema_7001($field) {
$columns = array(
  'value' => array(
    'description' => 'The worksheet content.',
    'type' => 'text',
    'size' => 'big',
    'not null' => TRUE,
  ),
);
$indexes = array();
return array(
  'columns' => $columns,
  'indexes' => $indexes,
);
}

```

to

```
function sheetnode_field_schema_7002($field) {
$columns = array(
  'value' => array(
    'description' => 'The worksheet content.',
    'type' => 'text',
    'size' => 'big',
    'not null' => TRUE,
  ),
  'name' => array(
    'description' => 'The worksheet title.',
    'type' => 'varchar',
    'length' => 255,
    'not null' => FALSE,
  ),
);
$indexes = array(
  'name' => array('name'),
);
return array(
  'columns' => $columns,
  'indexes' => $indexes,
);
}

```

# Answer
> 10 votes
Based on megadesk3000's answer, I ended up writing the following code:

```
function sheetnode_update_7002(&$sandbox) {
  $fields = field_info_fields();
  foreach ($fields as $field_name => $field) {
    if ($field['type'] == 'sheetfield' && $field['storage']['type'] == 'field_sql_storage') {
      $schema = sheetnode_field_schema_7002($field);
      foreach ($field['storage']['details']['sql'] as $type => $table_info) {
        foreach ($table_info as $table_name => $columns) {
          $column_name = _field_sql_storage_columnname($field_name, 'name');
          db_add_field($table_name, $column_name, $schema['columns']['name']);
          db_add_index($table_name, $column_name, array($column_name));
        }
      }
    }
  }
  field_cache_clear();
}

```

This seemed to work fine.

# Answer
> 3 votes
This is modified version of @infojunkie code with support for multiple columns, so they should be re-created once missing.

```
/**
 * Re-create missing module field schema.
 */
function foo_field_update_7001(&$sandbox) {
  $field_type = 'foo_field'; // CHANGE THIS.
  $fields = field_info_fields();
  foreach ($fields as $field_name => $field) {
    if ($field['type'] == $field_type && $field['storage']['type'] == 'field_sql_storage') {
      $schema = foo_field_field_schema($field); // CHANGE THIS.
      foreach ($field['storage']['details']['sql'] as $type => $table_info) {
        foreach ($table_info as $table_name => $columns) {
          foreach ($schema['columns'] as $column => $data) {
            $column_name = _field_sql_storage_columnname($field_name, $column);
            db_add_field($table_name, $column_name, $schema['columns'][$column]);
            db_add_index($table_name, $column_name, array($column_name));
          }
        }
      }
    }
  }
  field_cache_clear();
}

```

# Answer
> 2 votes
Have not done yet, but i would try something like this:

First you have to change the schema in `hook_field_schema()` to the new schema. Thats no problem, cause this hook is called, when you create an instance of that field. So all newly created fields will automatically use the new schema.

After that implement `hook_update_n` to update the tables of already created fields and do the following:

First get all the Instance names of fields that use the old schema:

```
SELECT field_name FROM field_config WHERE type='YOUR_FIELD_NAME';

```

With these instance names you can change the tables with the db api (db\_add\_field, db\_change\_field and db\_drop\_field for example) so they match your new field\_schema. That would be 2 tables per result of the query above: `field_data_INSTANCE_NAME` and `field_revision_INSTANCE_NAME`

Run `update.php` after that.

---
Tags: 7, entities
---


title: Block with #markup urls

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

Thanks in advance.

# Answer
> 0 votes
Create a custom block to only show on that page in full html with links to that content... should work.

---
Tags: routes
---


title: locking custom module function

text:
# Question
Title: locking custom module function
In my custom module, I would like to acquire lock on a particular function which will allow only one process to execute that piece of code at a time and then allow other process and so on. So that the code does not run in parallel.

Is it possible ?

# Answer
> 3 votes
Drupal provides its own locking mechanisms.

> In most environments, multiple Drupal page requests (a.k.a. threads or processes) will execute in parallel. This leads to potential conflicts or race conditions when two requests execute the same code at the same time. A common example of this is a rebuild like `menu_rebuild()` where we invoke many hook implementations to get and process data from all active modules, and then delete the current data in the database to insert the new afterwards.
>
> This is a cooperative, advisory lock system. Any long-running operation that could potentially be attempted in parallel by multiple requests should try to acquire a lock before proceeding. By obtaining a lock, one request notifies any other requests that a specific operation is in progress which must not be executed in parallel.
>
> To use this API, pick a unique name for the lock. A sensible choice is the name of the function performing the operation. A very simple example use of this API:
>
> ```
> function mymodule_long_operation() {
>   if (lock_acquire('mymodule_long_operation')) {
>     // Do the long operation here.
>     // ...
>     lock_release('mymodule_long_operation');
>   }
> }
>
> ```
>
> If a function acquires a lock it should always release it when the operation is complete by calling `lock_release()`, as in the example.

A function that has acquired a lock may attempt to renew a lock (extend the duration of the lock) by calling `lock_acquire()` again during the operation. Failure to renew a lock is indicative that another request has acquired the lock, and that the current operation may need to be aborted. \> If a function fails to acquire a lock it may either immediately return, or it may call `lock_wait()` if the rest of the current page request requires that the operation in question be complete. After `lock_wait()` returns, the function may again attempt to acquire the lock, or may simply allow the page request to proceed on the assumption that a parallel request completed the operation.

In Drupal 8, the example code would not be much different.

```
function mymodule_long_operation() {
  $lock = \Drupal::lock();
  if ($lock->acquire('mymodule_long_operation')) {
    // Do the long operation here.
    // ...
    $lock->release('mymodule_long_operation');
  }
}

```

See `\Drupal\Core\Lock\LockBackendInterface` for the interface exposed by the locking service.

# Answer
> 0 votes
As stated in my above comment, you could use a lock file on your system / a database stored setting value of your module. Once the process is in use, it should write that flag. After the process finished, the flag should be removed.

If the process is triggered by another request, it has to check for the presence of this flag first and wait until it vanishes.

This would solve your problem of not running in parallel. BUT this will also block the second request, leading to longer wait times for the end-user. And end-users can be quite unpatient. Speaking of pushing the button multiple times, or reloading the page, because they don't see any progress.

Therefore you should additionally consider implementing a kind of enqueuing the tasks, that does not require the entire request to wait.

---
Tags: 7
---


# Question
Title: How to pass views link as a variable to a node?
I have had a custom tables and I need them to view using Views in Drupal 7 module and it works.

In the Views module we can output fields as a link and redirect to the page what we need and I did this.

My question: when that link is clicked by the user, I need the link name to go to the specific node that I want as variable and being accessed by that node.

Is that possible in Drupal 7?

# Answer
> 1 votes
Have a look at the Rules Link module to generate a custom link that can trigger a rule (from the Rules module). So that via the Rules module you can then implement your logic about the "specific node and that variable" that you mentioned in your question.

Some more details about the Rules Link module (from its project page):

> This module lets you create links which trigger arbitrary functionality with the help of Rules.
>
> Features
>
> * Attach the link to any entities.
> * Show the link only for certain bundles.
> * Narrow the entities on which the link will be shown using the visibility conditions.
> * The links are usually displayed using Views.
> * For entities that can be displayed, the links can be shown on node view.
> * Supports an arbitrary number of additional Rules parameters for passing context via Views.
> * 3 types of links: Javascript, Normal and Confirmation form links.
> * Use individual permissions for each link.

---
Tags: 7, views
---


# Question
Title: How to get the NodeID from ItemID of connect Item from Field Collection
I have a nodetype which is has a connected field collection (multiple values). In this case one of items of the collection is a date and I have got the ID of this one. So:

```
field_collection_item_load($did);

```

takes me just half the way home, since I still need some data of the node, hosting this collection, which in turn holds that item.

Illustration:

```
node // need that id
  + dates (Field Collection)
     + item (of item of the field collection)
       + ....
       + date // got this id
       + more fields
     + ...
     + more items

```

Any Ideas?

# Answer
you may want to try `hostEntity()` method (link)

> Returns the host entity, which embeds this field collection item.

Then you'll be able to extract nid from the result returned by hostEntity().

but it is not clear what are you loading with *`field_collection_item_load($did);`*

is *`$did`* the id of the field\_collection item - meaning the field collection and not the field in it? if so, than you can do something like this

```
$entity = entity_load_single('field_collection_item', $did);
$host_entity = $entity->hostEntity();
$nid = $host_entity->nid;  // returns node id of the node that hosts given field collection

```
> 3 votes

---
Tags: entities
---


# Question
Title: How to auto-assign a user a particular role when that user gets autocreated in a content form?
I need to auto-assign newly autocreated users from the content editing form a particular role.

I created this new content-type : *Music Track* and created a new field - *Artist* for it. The *Artist* field is entity referenced to Target type - USER. I was expecting a Roles list under *Entity Selection* area so that I can restrict only *Artist* role users to be created when creating a new content and adding new artists but its not available.

**Note:** Users are being autocreated using Entityreference Autocreate module.

# Answer
*Note: I use this in a project and it works* (it does not use the Entityreference Autocreate module).

First alter the artist form and add a custom validate and a custom submit

```
function YOUR_MODULE_NAME_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'artist_node_form') {

            //hidding the Entity Reference field (User), it will be created in the process
            unset($form['field_user']);

            if (!isset($node->nid) || isset($node->is_new)) {
                $form['field_username'] = array(
                    '#type' => 'container',
                    '#weight' => 3,
                    'field_username' => array(
                        '#type' => 'textfield',
                        '#title' => t('Username'),
                        '#maxlength' => 60,
                        '#description' => t('Spaces are allowed; punctuation is not allowed except for periods, hyphens, apostrophes, and underscores.'),
                        '#required' => TRUE,
                        '#attributes' => array(
                            'class' => array(
                                'username',
                                ),
                            ),
                        '#default_value' => '',
                        '#access' => TRUE,
                        '#weight' => -10,
                        )
                    );

                $form['field_password'] = array(
                    '#type' => 'container',
                    '#weight' => 4,
                    'field_password' => array(
                        '#type' => 'password_confirm',
                        '#size' => 25,
                        '#description' => t('Provide a password for the new account in both fields.'),
                        '#required' => TRUE,
                        ),
                    );

       $form['#validate'][] = 'artist_node_form_validate';
       $form['#submit'][] = 'artist_node_form_submit';
    }
  }
}

```

In the custom validate you need to validate the username and check if the username is available.

```
function artist_node_form_validate($form, &$form_state) {
    $valid_user = user_validate_name($form_state['values']['field_username']);
    if(!is_null($valid_user)) {
        form_set_error('field_username', $valid_user);
    } else {
        $user = user_load_by_name($form_state['values']['field_username']);
        if($user){
            form_set_error('field_username', t('The username @username already exist.', array('@username' => $form_state['values']['field_username'])));
        } else {
            $form['field_username'];
        }
    }
}

```

In the custom submit you will create the user

```
function artist_node_form_submit($form, &$form_state) {
    $new_user = array(
        'name' => $form_state['values']['field_username'],
        'pass' => $form_state['values']['field_password'], // note: do not md5 the password
        'mail' => $form_state['values']['field_email'][LANGUAGE_NONE][0]['email'],
        'status' => 1
        );

    //The first parameter is sent blank so a new user is created.
    $new_user = user_save('', $new_user);

    //assigning the role
    $role = user_role_load_by_name("artist");
    user_multiple_role_edit(array($new_user->uid), 'add_role', $role->rid);

    //field_user is the Entity Reference field
    $form_state['values']['field_user'][LANGUAGE_NONE][0]['target_id'] = $new_user->uid;

}

```
> 2 votes

---
Tags: entities, users
---


# Question
Title: After moving Drupal 7 site, adding /user or /?q=user to base URL simply reloads maintenance page
I've just moved a Drupal 7 site from Bluehost to Inmotion (by reinstalling the latest core and adding the 'sites' directory from the old server account, then uploading the database). Since the move I can't log in from the browser.

The DNS has transitioned. At the new location Drupal is installed in a subdirectory -- public\_html/sub. I've altered the .htaccess file at the level above (public\_html/.htaccess) as per these directions https://support.lunarpages.com/knowledge\_bases/article/549 so that the site will open there with the base url in the browser.

That does happen, with the base URL currently showing the under maintenance message, just as the site was left. But when I attempt to go to /user or even /?q=user to log in and resolve any last errors from the move, then bring the site back online, I am not given a login form. It simply continues to show the under maintenance message.

I'm guessing this problem is somehow related to .htaccess and/or settings.php, but I can't seem to find the right combo of changes that will allow me to log in. Any suggestions? (I did clear the cache and sessions tables in the DB when this error first occurred, but no help.)

# Answer
Update your settings.php to this:

`$conf['site_offline'] = 0;`

From https://www.drupal.org/node/276457#comment-901392
> 0 votes

---
Tags: migrations, .htaccess, configuration
---


# Question
Title: How to redirect URL of kind node/nid to its url alias
I want to replicate the effect seen in http://www.drupal.org/node/1 , where you are redirected to drupal.org/about.

I have a fresh Drupal 7 installation, I create a node with a path, and don't get the effect. I have tried with module Path Auto, and nothing.

# Answer
> 0 votes
I have tried with module Global Redirect and I have achieved the desired results. I had thought it eliminated erroneously duplicated URLs, but it seems that it goes further to "hide" system path if an alias-url is set.

The problems stated in the documentation page itself, about incompatibilities with multilingual sites: I had found a problem of infinite reloop, but it was my fault; it was caused by a directory named "en" which is a very bad idea if you have languages set at suffixes in the URL, so it will cause the path to be www.example.com/en/ instead of www.example.com/en , thus doing an infinite loop.

# Answer
> 1 votes
Even though you've figured out a great solution, Rules may well be a module that can help you out with this for other problems you have in the future. Rules contains several options to fire off several events. For example, if you tell Rules to React on event `Content is viewed`, you can then set certain events, conditions, and actions. One of these Events will cause the user to be redirected to another page - not as simple as Global Redirect, but if there's something you need done before redirecting, this could do a lot for you.

---
Tags: path-aliases
---


# Question
Title: How can I get a summary from a view into another view?
There are a few views that gather and analyze data from several nodes to form a budget based on their workflow. These views have a "total" area (defined as a custom content field within the view), which calculates the the total amount of money allocated by each node.  Each node is also associated with a team object, and what I want to accomplish is to get the "total" field from each view to act as a column in another view, so we can see how much money was allocated/spent with each team.

Essentially, what I'm trying to do looks more or less like this:

```
Team Number | View 1 Total | View 2 Total | View 3 Total | Total of the Totals
1           |          $33 |         $-10 |         $-20 |                  $3
2           |          $50 |         $-15 |         $-10 |                 $25

```

I've looked into trying views-field-view, but I haven't been able to find an option that allows me to select that specific row, which is created with a summarized table as the format. This is the same across all three views. How would I go about achieving this, with either views-field-view or another module? Or should I just go ahead and do this with a panel using custom PHP code?

# Answer
You can combine the Views Field View module with the Views Aggregator Plus or with the Views Calc module.

**Views Calc:**

> Adds simple calculations to a views table. You can SUM, AVERAGE, COUNT, MIN, MAX, or AVG selected columns. A plug in theme makes the view look more spreadsheet-like (right justifies numeric fields, shades calculated columns and rows, and underlines calculated rows).

**Views Aggregator Plus:**

> In addition to what Views and Views Calc do, this module:
>
> * enumerates group members
> * produces tallies, i.e. textual histograms
> * aggregates on Views PHP code-snippet evalutations
> * can filter out result rows on regexp patterns
> * gives you sorting on Views' Math expressions
> * can process Webform submissions
> * lets you add your own custom aggregation functions
>
> ... and it puts summary statistics at the bottom of your aggregated table as well!
> 2 votes

---
Tags: views
---


# Question
Title: Quiz Module - Restart (Reload) the question of the quiz when it has been wrongly attempted four times
I am trying to reload the page (or) make the user attempt the question again if he/she has made four wrong attempts.

I am using Quiz module in Drupal 7.

Is there a possibility?

Thanks

# Answer
> 1 votes
It's kind of hard to decide what to do without code samples, but the following ideas come to my mind:

First, you could try a simple PHP command in the form of `header("Refresh:0");`, calling that once the wrong answer count reaches 4.

My second idea is that you try to integrate some JavaScript into the module itself, attaching a click event to the buttons or whatever it your user is clicking on. The click event could keep track of how many wrong answers they've gotten, and once they hit the threshold, have the JavaScript call location.reload().

---
Tags: quiz
---


# Question
Title: change field value in a view using preprocess_views_view_fields
I'm trying to change the value of a field in a view programatically but i find some problems.

* first is that even though I created a Global: custom text field which field id is 'nothing', It's value remain unchanged and the value is applied to a new field created at the end of the view.
* Second is that this function creates some errors and drupal send lots of notices:

> Notice: Undefined property: stdClass::$wrapper\_prefix in include() (line 32 of /my/path/sites/all/modules/views/theme/views-view-fields.tpl.php).
>
> Notice: Undefined property: stdClass::$label\_html in include() (line 33 of /my/path/sites/all/modules/views/theme/views-view-fields.tpl.php).
>
> Notice: Undefined property: stdClass::$wrapper\_suffix in include() (line 35 of /my/path/sites/all/modules/views/theme/views-view-fields.tpl.php).

My code is:

```
function real_estast_sub_preprocess_views_view_fields(&$vars) {
  $view = $vars['view'];

  foreach ($view->field as $id => $field) {

    // change the global custom text content depend on result (node id)
    if ($vars['row']->nid == 1625){
      $vars['fields']['nothing']->content = '666€';
    }else{
      $vars['fields']['nothing']->content = $vars['row']->field_data_field_price_field_price_value."€/noche ";
    }
  }
}

```

What's the problem here? I tried to follow all the steps explained in:

How to insert values into Global custom text field of views programmatically?

> Edit: I soolved the notices form drupal by adding:
>
> ```
>   $vars['fields']['nothing']->wrapper_prefix = '';
>   $vars['fields']['nothing']->wrapper_suffix  = '';
>   $vars['fields']['nothing']->label_html = '';
>
> ```
>
> But it's like I'm defining a totally new field instead of assigning a value to the existing one

# Answer
You are probably not accessing the fields array correctly, and creating your own additional renderable array within $vars.

Install the Devel module if you haven't already and put

```
dpm($vars);

```

at the top of your function. That will allow you to view the structure of the object on the screen (make sure you're logged in as user 1).
> 1 votes

---
Tags: views, entities, theming
---


# Question
Title: How to restrict content access within a site?
In a community site. I want to restrict users to have some private parts of the site like forum, groups and discussion board with their scope (should not be visible to others).

That is a specific forum should be available to a specific set of users who belongs to a specific group.

Eg: Let's say there are multiple groups of users like cricket players, football players. I want to restrict the visibility and access to cricket forum only to cricket players and Football forum respectively. And there is a third forum called sports which should be visible to both.

The question can split into two:

1. How to create a specific set of users?
2. How can I restrict the specific set of users to the forums, groups, etc...

# Answer
> 1) How to create a specific set of users?

That's what you typically do by creating appropriate "roles" in your site, and then for each user, you assign appropriate "roles".

> 2) How can I restrict the specific set of users to the forums, groups, etc...

Combine this with granting "Permissions" to "roles" (which are then inherited by all users with the appropriate role). E.g. you grant access to (selected) forums.

When it comes to "groups", there are typically these modules that get used for that:

1. The most commonly used is Organic Groups, for which there is a set of amazing video tutorials to Learn Organic Groups. Especially the video about "Basic Organic group setup" should help to get you going with it. Here is what you'll learn from it (quote from that link):

> * How to create a content type that is used as groups – meaning containers for other stuff (content and other entities)
>     * How to modify a content type (Articles) to allow it to be posted to selected groups
>     * That the user creating a group by default will be the group manager
>     * How to add more members to a group
>     * That there is an example feature shipped with OG
>     * That groupness and group contentness is actually managed by special fields
>     * That group membership is actually also managed with a field (of the same type that tells what group a content piece belogs to)
2. For anybody who considers the Organic Groups module as rather complex (like me ...), have a look at the (fairly new) Group module as a possible alternative. Some more details about it (from its project page):

> **Organic Groups** allows content itself to be groups, which isn't always what people want. It relies on an entity reference field to keep track of the ties between a group (node, term, ...) and its content (node, term, user, ...).
>
> **Groups** instead creates groups as entities, making them fully fieldable, extensible and exportable. Every group can have users, roles and permissions attached to it. Groups can also act as a parent of any type of entity. Seeing as a group itself is also an entity, creating subgroups is very easy.

Even though it only has a beta release for D7 so far, its Usage statistics seem to indicate it is like a "rising star". And I've heard it mentioned recently in various occasions as a valid alternative for the "heavy" Organic groups module.

The Group module also integrate nicely with the Rules module, as explained in comment #2 of issue 2603136, which states the following:

> ... you can already use Rules to:
>
> * Add a new Group
>     * Create a new GroupMembership and save it (the equivalent of $group-\>addMember())
>     * Add or remove a GroupRole from a GroupType
>     * React on new GroupMembership or Group entities
>     *
>
> What hasn't been done yet is custom Rules actions or conditions. Seeing as 90%+ of Group is pure Entity API CRUD-operations, there has been no custom Rules code yet given how much you can already accomplish out-of-the-box.
>
> Useful Rules we may add could be:
>
> * E-mail all members of a Group, optionally filtered by GroupRole
>     * Easier-to-understand labels for the above list: "Member joined group" sounds easier than "GroupMembership entity is created"
>
> ...

Refer to Integrations with other modules and its "Related issues" about other modules for which integrations already exist, or are in the pipeline.

**Note**: It seems to me that "a particular school" (as in your comments below) would be a perfect with a "particular group" (no matter which of the 2 modules above you would use).
> 1 votes

# Answer
> Profile mean roles – Monish

Perhaps you should explore using:

## Path Access

> Path\_access provides the means to restrict pages based on their path alias - meaning you can lock out certain **user role** groups from whole sections of a site using wildcards.
> 0 votes

---
Tags: users, organic-groups, nodes, subsites
---


# Question
Title: hook_views_query_alter if date field empty sort with another field postdate
I have a view that show all contents of type NEWS NEWS has like fields :

Content = Title

Scheduler = publish-on

and in sort criteria : I want sort contents with two option : With scheduler (publish-on = DESC) and With post date

I want sort content with scheduler, and when scheduler field is empty he sort with post date. I have created hook views query alter and I have a problem, how can I sort field with condition if publish\_on is empty then sort with postdate

```
function custom_sort_views_query_alter(&$view, &$query) {

    if($view->name === 'articleview') {
        $view->query->add_where(1,'publish_on',  'NOT IN');
        $view->query->orderby[0]['field'] = "CASE WHEN publish_on IS NULL THEN created ELSE publish_on END";
        $view->query->orderby[0]['direction'] = "DESC";
        $view->query->orderby[1]['field'] = "created";
        $view->query->orderby[1]['direction'] = "DESC";
    }
}

```

# Answer
> 2 votes
The solution that comes to my mind now (after your question's comments) is make two queries, one query with the records that have publish\_on field empty and the other with the field non empty and then use a UNION between them.

Why this? AFAIK You can't sort some records in a query based in a condition and other records based in another condition, so to achieve this you must split the records and apply the sort method separately. This is records of a condition first and records of another condition before, but you can't merge the records and the order condition.

Maybe this posts can help you:

https://stackoverflow.com/q/2258376/3653989

https://stackoverflow.com/q/19296047/3653989

https://stackoverflow.com/q/3730093/3653989

Maybe you also want to read http://www.w3schools.com/sql/sql\_union.asp

---
Tags: 7, hooks, views
---


# Question
Title: How can I track download statistics for private files?
One of the most important metrics for the publications database I'm working on will be file downloads, looked at in various combinations with things like publication type, date published, etc. With the system I'm migrating from, I parse the server logs with a python script, and then reconstructing information about publication type, etc. is time consuming or impossible. Google analytics doesn't work because a lot of the file downloads come from direct requests to the file, not via the page itself.

My hope is that with drupal's private file system, the system should know about and be able to send to google analytics (or some other counter failing that), information about all file downloads in that private file system. Ideally it would carry with it information on the node that the file is attached to, making it much easier to look at, for example, the number of journal article downloads for material published in FY2015.

I'm fairly new to drupal, and honestly I'm so tied up with other parts of the build that I haven't been able to do much to dig into this yet, beyond searching here and on google a number of times. My searches so far have been fruitless, so I'm trying to find out whether I need to try to make sure enough detail is implicit in the file system to allow me to parse the log files better.

Can anyone help me figure out how counting file download statistics can be accomplished without relying on server logs? I'm happy to explore modules, my initial thought was that the google analytics module might take care of that on its own, but I realized it still relies on someone clicking a link.

I should mention that I am using the media and file\_entity module.

# Answer
> 3 votes
Give these modules a try

### Download Count

> The download\_count module tracks downloads of private files attached to nodes via the core upload or contributed filefield modules for d6 and private core file fields for d7.

### File download count

> An API for tracking file downloads. Recommended use is by using file\_entity's file/\[file:fid\]/download callback page. Basically the difference between this and other file download tracking modules is this module does not intend to track every single time the file is viewed. It only wants to track when a file is actually triggered for download. It is up to the site to implement links to the file download URL.

### AJAX Download Counter

> This module uses AJAX to count file downloads. It's optimized for medium to large sites (such as my own site, OpenGameArt.org) where the total number of file downloads might be in the hundreds of thousands or even millions. Using this module has some advantages and some limitations versus other methods of counting downloads:

---
Tags: 7, media, nodes, files
---


# Question
Title: Adding a custom subject field to the Revision Information Drupal 7
I would like to be able to add a subject field to the Revision Information along with the log message. Is there any way I could do that?

# Answer
> 0 votes
I would suggest a different approach: You could extend the node\_revision table with a new column that holds the revision log's title and modify the node edit form to capture the value for this field. Below is a little module example that does the trick. If you need some more help, let me know, cheers!

```
<?php

/*
 * Implements hook_form_BASE_FORM_ID_alter().
 */
function raks_form_node_form_alter(&$form, &$form_state, $form_id){
  if( isset($form['revision_information']) ){

    // Check the revision log checkbox when the log subject or textarea is filled in.
    // This must not happen if "Create new revision" is enabled by default, since
    // the state would auto-disable the checkbox otherwise.
    if (isset($form_state['node']) && !$form_state['node']->revision) {
      $form['revision_information']['revision']['#states'] = array(
        'checked' => array(
          array('input[name="log_subject"]' => array('empty' => FALSE)),
          array('textarea[name="log"]' => array('empty' => FALSE)),
        ),
      );
    }

    $form['revision_information']['log_subject'] = array(
      '#type' => 'textfield',
      '#title' => 'Revision log subject',
      '#weight' => -15,
      '#description' => t('Provide an subject for the changes you are making.'),
    );

    // Reorder / Move the checkbox above the new form field
    $form['revision_information']['revision']['#weight'] = $form['revision_information']['log_subject']['#weight'] - 1;
  }
}

/*
 * Implements hook_schema_alter().
 */
function raks_schema_alter(&$schema) {
  $schema['node_revision']['fields']['log_subject'] = array(
    'type' => 'varchar',
    'default' => null,
    'description' => "The subject of the revision log's description",
    'length' => 255,
    'not null' => FALSE,
  );
}

/*
 * Implements hook_install().
 */
function raks_install() {
  if (!db_field_exists('node_revision', 'log_subject')) {
    $schema = drupal_get_schema('node_revision');
    db_add_field('node_revision', 'log_subject', $schema['fields']['log_subject']);
  }
}

/*
 * Implements hook_uninstall().
 */
function raks_uninstall() {
  if (db_field_exists('node_revision', 'log_subject')) {
    $schema = drupal_get_schema('node_revision');
    db_drop_field('node_revision', 'log_subject');
  }
}

/**
 * Implements hook_views_api().
 */
function raks_views_api()
{
    return array(
        'api' => 3
    );
}

```

You would also need a separate \*.views.inc file, e.g. raks.views.inc, with the following code inside:

```
<?php

/**
 * Implements hook_views_data_alter().
 */
function raks_views_data_alter(&$data)
{

  $data['node_revision']['log_subject'] = array(
    'title' => "Subject of the revision's log",
    'help' => "Subject of the revision's log",
    'field' => array(
      'handler' => 'views_handler_field',
      'click sortable' => TRUE, // This is use by the table display plugin.
    ),
    'sort' => array(
      'handler' => 'views_handler_sort',
    ),
    'filter' => array(
      'handler' => 'views_handler_filter_string',
    ),
    'argument' => array(
      'handler' => 'views_handler_argument_string',
    )
  );

}

```

Once this file is in place (and following a clear-cache if needed), you should have access to the log\_subject as a field in your Content Revisions view.

Let me know if this works all the way, I am curious :-) May even submit it as a contrib module on D.O., what do you think?

# Answer
> 1 votes
No - because revisions are not Drupal entities themselves but metadata associated with entities. You can expose an entity to the revisioning system but not the other way around, its a core part of Drupal.

Best way I could think of to come close to this functionality is to have a special fieldset / field collection of fields that allow for what you want (ex. log message, subject) and then use field permissions to hide that from the end user. You would then have your team use these fields for recording their updates rather than the log field.

---
Tags: 7
---


title: wishlist and commerce bundle

text:
# Question
Title: wishlist and commerce bundle
i have commerce\_bundle module installed, and we use it to implement (shop the look) concept, the problem is that we already use flags to implement wishlist for separate products and view the items added to wishlist by a view, now we need to allow bundles to be added to wishlist, but we can't view it in the same view that render the products items in wishlist. are there any ideas to solve this problem?

# Answer
Try this sandbox which reimplements Wishlists as orders. It won't work out of the box since it only hooks into the main add to cart form, so you'd need to add that in... but it's an order so you can theme it like a regular cart/order form.
> 2 votes

---
Tags: views, commerce, flags
---


title: Modifying base_url in settings.php

text:
# Question
Title: Modifying base_url in settings.php
When we deployed to a production site, CSS and images got broken.

One approach to mitigate this was editing settings.php, the base\_url

**$base\_url = '/oursite';**

(Where "oursite" is our domain, i.e. http:localhost/oursite/ )

But that also broke some functionality on our local site. For example:

**The requested page "/oursite/?q=oursite/node/add/cmsdeliverable%3Ffield\_demo\_id\_reference%3D1208" could not be found.**

What other approaches can I take?

# Answer
Firstly, your $base\_url should be fully qualified: http://www.example.com.

Secondly, you should configure your $base\_url to be 'dynamic' - different for development, staging and production. Detect the 'environment' and then set the $base\_url accordingly.

As for the broken styling, I have seen broken theme problems related to file system rights. It may be that your site is using CSS/JS aggregation / compression. These compressed files are created on the fly by Drupal (check admin/config/development/performance). If there are file/folder rights issues on the production, the files will not be created.

May be useful to check the error log (/admin/reports/dblog) - could just point you in the right direction.
> 2 votes

---
Tags: uri
---


# Question
Title: Adding Quick Tabs Programmatically to a node is not working
I'm writing below code in my node--type.tpl.php, but only empty page is loading when i load the node page.Can you please help in knowing my mistake. What i need to add to display quicktab and its corresponding viewmode content? my code is:

```
<?php
 $nid=$node->nid;

$tabs['Home'] = array(
  'title' => t('Home'),
  'type' => 'node',
  'nid' => $nid,
  'viewmode_home' => TRUE,
  'hide_title' => FALSE,
);
$tabs['About'] = array(
  'title' => t('About'),
  'type' => 'node',
  'nid' => $nid,
  'viewmode_about' => TRUE,
  'hide_title' => FALSE,
);

$quicktabs['qtid'] = 111; //given a random number
$quicktabs['tabs'] = $tabs;
$quicktabs['style'] = 'Mac';
$quicktabs['ajax'] = FALSE;
print theme('quicktabs', $quicktabs);
?>

```

# Answer
> 0 votes
I got this to work using node--typename.tpl.php

```
$tabs = array(
      array(
        'title' => t('Overview'),
        'type' => 'view',
        'vid' => 'product_tabs',
        'display' => 'block_1',
        'args' => $node->nid,
        'weight' => 0,
      ),
      array(
        'title' => t('Dimensions & Weight'),
        'type' => 'view',
        'vid' => 'product_tabs',
        'display' => 'block_4',
        'args' => $node->nid,
        'weight' => 1,
      ),
      array(
        'title' => t('Shipping'),
        'type' => 'view',
        'vid' => 'ps3_games',
        'display' => 'default',
        'args' => $node->nid,
        'weight' => 2,
      ),
      array(
        'title' => t('Ratings & Reviews (' . $node->comment_count . ')' ),
        'type' => 'view',
        'vid' => 'product_tabs',
        'display' => 'block_3',
        'args' => $node->nid,
        'weight' => 3,
      ),
    );
    $qtoptions = array(
      'style' => 'Zen',
      'ajax' => FALSE,
    );
    $qtname = 'commerce_product23';
    $quicktabs = quicktabs_build_quicktabs($qtname,$qtoptions,$tabs);
    print drupal_render($quicktabs['content']);

```

works with views, but if I try to use nodes it does not.

**You should try another method.**

**Create a Quicktab using the Quicktabs UI. Then create a custom module to override the settings/output of the quicktab using the machine name to target a specific quicktab**

For Example:

```
 function mymodule_quicktabs_alter($quicktabs) {
    $nid = $node->nid
        if ($quicktabs->machine_name == 'quick_tab_front_page') {
        $quicktabs->tabs = array(
          0 => array(
        'nid' => $nid,
        'view_mode' => 'full',
        'hide_title' => 1,
        'title' => 'Full',
        'weight' => '-99',
        'type' => 'node',
          ),
          1 => array(
        'nid' => $nid,
        'view_mode' => 'teaser',
        'hide_title' => 1,
        'title' => 'Teaser',
        'weight' => '-99',
        'type' => 'node',
          ),
        );
        $quicktabs->renderer = 'quicktabs';
        $quicktabs->style = 'Arrows';
        $quicktabs->options = array();
        }
        }

```

---
Tags: nodes, entities, blocks
---


# Question
Title: Can I refresh parent window through drupal_goto?
I am working within iframe but hoping to refresh whole page through drupal\_goto. Is it possible to do it ?

Thansk

# Answer
> 1 votes
drupal\_goto will can be used to reload the same window. if you are in iframe, then it will reload the iframe, if you want to refresh the whole page you need javascript and you can add it inline using drupal\_add\_js

```
  drupal_add_js('parent.location.reload();',array('type' => 'inline'));

```

---
Tags: redirection
---


# Question
Title: create a custom field which is allowing multiple values using custom module
I created custom content type and one custom field(text) successfully. But my requirement is, my custom field should allow to add multiple values.

# Answer
for unlimited set the cardinality to -1 `'cardinality' => -1`

example:

```
function _namecards_namecard_installed_fields() {
  $t = get_t();
  return array(
    'namecards_namecard_phone' => array(
      'field_name' => 'namecards_namecard_phone',
      'label' => $t('Phone'),
      'type' => 'text',
      'cardinality' => -1,
    ),
    'namecards_namecard_fax' => array(
      'field_name' => 'namecards_namecard_fax',
      'label' => $t('Fax'),
      'type' => 'text',
      'cardinality' => -1,
    ),
  );

}

```
> 1 votes

---
Tags: entities
---


# Question
Title: Not load JS formatter field used Views Infinite Scroll
I had my module formatter field for Image Slide . After load scroll page that field not run slide , I Debug see not include js slide when load scrolled ! So how to include js or call js field formatter after load scrolled ?

# Answer
> 0 votes
add an ajax complete function to your js code.

Ex:

```
$( document ).ajaxComplete(function() {
    // Do stuff here when ajax loads.
});

```

---
Tags: views
---


# Question
Title: How can I hook into entityforms being submitted?
I've installed entity forms. I have made a form. I would like to fire some code when a user fills out and submits the form I have created. I do not know how to do this. I don't know which hook to use, nor entirely understand how hooks work.

I've done my best to learn php and read the documentation, but I don't understand. I understand that this is likely a very simple question, I have never had any formal computer training, so even the simplest concepts allude me.

# Answer
> 1 votes
Entityforms are - as the name suggests - stored as entities. So you can hook into hook\_entity\_insert(), or hook\_ENTITY\_TYPE\_insert(), having the inserted data as parameter (the entity will be an object):

```
/**
 * Implements hook_entity_insert().
 */
function MYMODULE_entity_insert($entity, $type) {
  if ($type == 'entityform') {
    // Do your stuff here.
  }
}

```

or

```
/**
 * Implements hook_ENTITY_TYPE_insert().
 */
function MYMODULE_entityform_insert($entityform) {
  // Do your stuff here.
}

```

You could also utilize rules to define custom actions on submission, as the entityform submission triggers the entityform\_submission rule.

---
Tags: 7, hooks, entities
---


# Question
Title: drupal_render($node_view); is not working
Node page is not loading once I add below code

```
 drupal_render($node_view);

```

I was referring https://api.drupal.org/api/drupal/modules%21node%21node.module/function/node\_view/7 and added below code in my `node--type.tpl.php`

```
<?php
  $node = node_load($nid);
  $node_view = node_view($node);
  $rendered_node = drupal_render($node_view);
  echo $rendered_node;
?>

```

# Answer
> 1 votes
As I don't have the Drupal sources at hand right now, I didn't digg into it yet. But I'm pretty sure the node\_view() function is using your node--type.tpl.php for rendering its output.

So calling it within your template will lead to a recursion. You might want to check on that.

---
Tags: nodes, entities
---


# Question
Title: How to set custom markers with Openlayers?
I'm trying to set my Openlayers markers to custom icons. I have looked at the Openlayers Examples, and I have added a new style of type Icon and then I have added an assets folder inside the Openlayers module directory. I then have set the path to the marker in the style settings tab.

The problem is that no matter how I configure the path, the marker doesn't show up in the style preview or on my map. I have tried the full site path for the marker, I have tried the path from the drupal root, and I have tried the path from the Openlayers module folder. None of these work.

As always, any advice is appreciated.

# Answer
To "***set custom markers***" (as in your question title), you may also want to look at the IP Geolocation Views & Maps module. Partial quote from its project page (especially note the last paragraph of it):

> 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.:
>
> This allows you to bring together modules and feature sets that without IPGV&M you would not be able to combine.
>
> Like beautiful animated marker clustering on Google or Bing or Mapbox ... any of various map providers.
>
> But more importantly IPGV&M adds some features you won't find as conveniently packaged elsewhere.
>
> These include marker differentiation based on field values or ranges (2nd screenshot) with or without font icons, various centering options, super-imposing the current visitor's location, allowing multiple content types to be displayed on the same map, full screen button and mini-map inset (bottom screenshot), polygon support (Geofield), marker tags and tool tips and cross-highlighting of associated content on the page when markers are hovered (and vice versa).

Head over to its (impressive) project page for even more information about it (it would be way too long to include a quote of it all here). That project page also includes various screenshots.
> 1 votes

# Answer
So, I updated OL to the dev version and the behavior went away.
> 0 votes

---
Tags: 7, javascript
---


# Question
Title: What to name field collection theme file?
There are several articles here that address theming field collections but none that specifically cover the naming conventions required to actually get them recognized by Drupal.

field--field-field-collection-name.tpl.php does not work for me. Perhaps because I am theming the edit page of my field collection, but field--field-collection-name--edit.tpl.php doesn't work either. I have tried every permeation and order of names I can think of with no success.

Surely there is a way to theme a page whose URL is domain-name/field-collection/field-field-collection-name/\*/edit.

Any help?

# Answer
Theme hook suggestions typically work off of content type (or in this case bundle type), field name, or other variables. URL is not one of the defaults.

However you can create a custom template suggestion and use the URL to create that suggestion. If you want to theme the edit page you'll want to make sure you're putting the template and template suggestion in the administration theme.

Here's a good page on theming suggestions: https://drupal.org/node/1089656
> 0 votes

# Answer
`field-collection-item--field-name.tpl.php` is what worked for me.
> 0 votes

---
Tags: theming, entities
---


# Question
Title: Added Classes showed in dpm but don't show up in the output HTML
I want to add some classes into my form (node/add/-- form) so I use hook\_form\_FORM\_ID\_alter but I don't know why the classes add to my field in the dpm() output but when I check the html output those classes doesn't show up ?

Here is the code that I have always used for adding a class but I don't know why this doesn't work for this form

```
function contribute_form_alter_form_injection_node_form_alter($form, &$form_state) {

     $form['field_product_brands']['#attributes']['class'][] = 'Added-Class1';
     $form['field_product_brands']['#attributes']['class'][] = 'Added-Class2';
     dpm($form);
}

```

I Should mention that I clear the cache and disable and enable the module but no luck.

# Answer
Given that you try adding classes to a field widget, you might want to use hook\_field\_widget\_form\_alter():

```
/**
 * Implements hook_field_widget_form_alter().
 */
function MYMODULE_field_widget_form_alter(&$element, &$form_state, $context) {
  // Add a css class to widget form elements for all fields of type mytype.
  if ($context['field']['type'] == 'taxonomy_term_reference') {
    // Be sure not to overwrite existing attributes.
    $element['#attributes']['class'][] = 'myclass';
  }
}

```
> 2 votes

---
Tags: 7, theming, forms
---


# Question
Title: How to let views's sort criteria random equally
I have two node content. I want to know which content is able to convince user to sign up.

I create a views block and two node contents. The views will randomly choose one node content and display.

At the views sort criteria, I choose global random, but it does not random equally. It choose option A more than option B.

Question: How to let it choose random equally or alternate such as A,B,A,B,A,B..etc?

# Answer
If you enable core **Statistics** module, you get some more filters in views:

* Content statistics: Most recent view
* Content statistics: Total views
* Content statistics: Views today

You can select one of them, and sort ascending. So that it will always show the least recent viewed node, or least viewed node in all times, or least viewed node today, respectively which filter you've chosen.
> 1 votes

---
Tags: 7, views
---


# Question
Title: Can't clear cache as drupal_test.cache_filter doesn't exist
I run into an issue, I can't clear the cache anymore as I get this error:

`PDOException: SQLSTATE[42S02]: Base table or view not found: 1146 La table 'drupal_test.cache_filter' n'existe pas: TRUNCATE {cache_filter} ; Array ( ) in cache_clear_all() (line 168 of C:\wamp\www\drupal-7.41\includes\cache.inc).`

I've read a few posts on stackoverflow with the same problem but different table and I wonder if I can try to apply the same solution (I don't know much sql so I'm not sure if I can just copy and paste from any solution as I don't want to make things worse). Some solutions seem to be dropping and recreating a table called cache\_field, others cache\_rules but I couldn't find anything for that specific table drupal\_test.cache\_filter. Do you reckon it's worth trying both of them, or does anybody have another solution? Last time I had this problem - I can't remember if it was the same table though - I ended up reinstalling the whole drupal, and I'd like to avoid this.

# Answer
Did you try to run drush rr in advance? It would clean up your registry of modules an quite often fixes those issues.

Maybe some module got moved or if removed try to figure out what has been removed, re-install it and try again.
> 0 votes

---
Tags: caching
---


# Question
Title: How can I combine the fields of two field collections in my theme?
**Note:** I've not accepted an answer on this because the answer I got wasn't what I needed. In the end I abandoned field collections in favor of paragraphs for this task.

---

**Update:** I really appreciate @NoSssweat's answer, but it isn't what I'm looking for in this case, so I'm still looking for an answer. Please help me better understand how to crawl through and combine two field collections.

---

**Update 2:** I found a way to build a view that would do roughly what I want with what I have as long as I don't combine the staff and other fields. Would there be a way to incorporate the view into my template, or perhaps it would be better to do the whole page as a view and attach the field collection views. I assume that I could handle moving the attachment into the appropriate place through some views preprocess function?

---

**Update 3:** I've just found out one more requirement: the order of the contributors is important, and it could be any mix of staff and non staff contributors (staff first, non-staff first, a mix). I think I need to have a look at the Paragraphs module.

---

This is a more complex version of How can I combine the output of two separate fields in template.php?.

I have two field collections. One consists of a term reference for role:

and a entity reference for a user. The other consists of the same term reference and a text field to enter the names of contributors who are not users:

I want to sort all of those values into different roles and render them out as such:

**Role Name 1:** rendered Staff link, rendered staff link, external contributor

**Role Name 2:** rendered staff link, external contributor, external contributor

**Role Name 3:** external contributor, external contributor

(This is sorting all the people into roles as assigned, staff members first)

Here is how a page might actually appear (imagine names that are staff members are underlined links to user profiles, no other links exist):

**Editor:** Doe, John; Doe, Jane; Yamada, Tarou; and Yamada, Tomoko. **Author:** Yamada, Tarou and Doe, Betty

I have been trying to get something going using `mytheme_field__field_collection_name()`, but am running into a few stumbling blocks.

Here is pseudo code for how I imagine this should work:

```
<?php
function mytheme_field__field_collection_for_staff($variables) {
  isset($some_persistent_variable_roles) !! $some_persistent_variable = array();
  foreach ($variables['items'] as $item) {
    $role = grab the safe to print role name;
    $staff_member = grab the safe to print Staff Name link
    if (!in_array($role, $some_persistent_variable_roles) {
      $some_persistent_variable_roles[] = $role;
    }
    $some_persistent_variable_roles[$role][] = $staff_member
  }
}

function mytheme_field__field_collection_for_others($variables) {
  isset($some_persistent_variable_roles) !! $some_persistent_variable = array();
  foreach ($variables['items'] as $item) {
    $role = grab the safe to print role name;
    $person = grab the safe to print name text field
    if (!in_array($role, $some_persistent_variable_roles) {
      $some_persistent_variable_roles[] = $role;
    }
    $some_persistent_variable_roles[$role][] = $person
  }
}

```

I would then iterate through each of the roles, printing out a semicolon separated list of the staff members (a link to their profile with text of FamilyNameField, FirstNameField), and then the other contributors (plain text names)

So I have a few issues here (they may be the wrong questions, please educate me):

1. How can I persist a variable across multiple field processing functions so that I can later output them as part of the node. (I tried `variable_set`, but that seems to persist beyond just the page load which is not really what I want, I just want to build up values between function calls)
2. These two functions normally return some kind of output so would it make sense to return null with the first one and the rendered code with the second?
3. Or is there some other way that this calculated value should be injected back into the template?

Drupal is pretty new for me, so please tell me if I'm barking up the wrong tree with how I'm approaching this, I'm not married to this approach, I'm trying to learn the drupal way of doing it so I won't be fighting drupal at every turn.

---

**Additionally:** Later on I'll need to use these values, possibly in the same form, possibly not, to populate metadata tags, so that google scholar and the like can find and properly cite the work.

# Answer
> 1 votes
# The Drupal Way

Add a field of Entity Reference, Widget: Auto Complete Tag Style and change the number of values from 1 to unlimited.

* Select User as your target type

After you click save field settings you are taken to another screen, scroll down and find **Number of values** and change it to **Unlimited** and Save Changes.

All you gotta do is **create an entity reference field for each**. Authors, Editors etc...

On your entity reference field since we are using Autocomplete (tag style) you start to type a user name and select the user. Then add a comma `,` to add more users

Ex:

---

> Here is how a page might actually appear (imagine names that are staff members are underlined links to user profiles, no other links exist):
>
> Editor: Doe, John; Doe, Jane; Yamada, Tarou; and Yamada, Tomoko. Author: Yamada, Tarou and Doe, Betty

### Views

With the views module you can use this to create your display.

Uncheckmark view page and **checkmark View BLOCK**

Create a new view of content \[your content type\]. Type: Fields Format: Unformated List

In FIELDS add Editors and Authors fields.

Lastly,

Under Advanced, Add a CONTEXTUAL FILTER of nid \>\> select default value, then in drop down select nid from url. (Note: the preview will no longer work, since the preview url does not have a nid)

Your view block will be listed in BLOCKS, but you can also use Panels to insert your view block. You need to enable a module for that. I forgot which one. Sorry can't check right now.

---

> Additionally: Later on I'll need to use these values, possibly in the same form, possibly not, to populate metadata tags, so that google scholar and the like can find and properly cite the work.

You can use **Metatag** module for this.

> The Metatag module allows you to automatically provide structured metadata, aka "meta tags", about a website. In the context of search engine optimization, when people refer to meta tags they are usually referring to the meta description tag and the meta keywords tag that may help improve the rankings and display of a site in search engine results.

Video Tutorial

---
Tags: theming, entities
---


# Question
Title: Creating a Custom Field Type for Fieldable Entities
**Problem**

My custom field type will not save data. Every time I save the entity it is attached to (it doesn't matter what entity I do this on) the value always comes out NULL and SQL throws an error because that field can not be NULL in the database.

**Research**

I'm currently working on a module that will provide a custom field type to be used on entities. I have done my best from looking at the docs for Field Types API and seeing how other modules have implemented this e.g. Entity Reference, Examples, and Address Field.

**Attempt**

Below is my attempt and can not figure out what is wrong with the code.

**.install file**

```
/**
 * Implements hook_field_schema().
 */
function civsearch_code_reference_field_schema($field) {
  $columns = array(
    'target_id' => array(
      'description' => 'The id of the target code.',
      'type' => 'int',
      'unsigned' => TRUE,
      'not null' => TRUE,
    ),
  );

  return array(
    'columns' => $columns,
    'indexes' => array(
      'target_id' => array('target_id'),
    ),
  );
}

```

**.module file**

```
/**
 * Implements hook_field_info().
 */
function civsearch_code_reference_field_info() {
  return array(
    'civsearch_code_reference' => array(
      'label' => t('Code Reference'),
      'description' => t('This field stores the target_id of the referenced code.'),
      'settings' => array(
        'code_type' => '',
      ),
      'instance_settings' => array(),
      'default_widget' => 'civsearch_code_reference_autocomplete_tags',
      'default_formatter' => 'civsearch_code_reference_label',
    ),
  );
}

/**
 * Implements hook_field_settings_form().
 */
function civsearch_code_reference_field_settings_form($field, $instance, $has_data) {
  $settings = $field['settings'];

  $options = array(
    'muni_cloud_bulk' => t('Bulk'),
    'muni_cloud_bulk_exception' => t('Bulk Exception'),
    'muni_cloud_bulk_zoning_district' => t('Bulk Zoning District'),
    'muni_cloud_exception' => t('Exception'),
    'muni_cloud_jurisdiction' => t('Jurisdiction'),
    'muni_cloud_use' => t('Use'),
    'muni_cloud_use_unit' => t('Use Unit'),
    'muni_cloud_use_regulation' => t('Use Regulation'),
    'muni_cloud_use_zoning_district' => t('Use Zoning District'),
    'muni_cloud_zoning_category' => t('Zoning Category'),
    'muni_cloud_zoning_district' => t('Zoning District'),
  );

  $form['code_type'] = array(
    '#type' => 'select',
    '#title' => t('Code Type'),
    '#options' => $options,
    '#description' => t('The code type to be referenced.'),
    '#default_value' => $settings['code_type'],
    '#required' => TRUE,
  );

  return $form;
}

/**
 * Implements hook_field_widget_info().
 */
function civsearch_code_reference_field_widget_info() {
  return array(
    'civsearch_code_reference_autocomplete_tags' => array(
      'label' => t('Autocomplete (Tags style)'),
      'description' => t('An autocomplete text field.'),
      'field types' => array('civsearch_code_reference'),
      'settings' => array(
        'match_operator' => 'CONTAINS',
        'size' => 60,
        'path' => '',
      ),
      'behaviors' => array(
        'multiple values' => FIELD_BEHAVIOR_CUSTOM,
      ),
    ),
  );
}

/**
 * Implements hook_field_widget_settings_form().
 */
function civsearch_code_reference_field_widget_settings_form($field, $instance) {
  $widget = $instance['widget'];
  $settings = $widget['settings'];

  $form = array();

  $form['match_operator'] = array(
    '#type' => 'select',
    '#title' => t('Autocomplete matching'),
    '#default_value' => $settings['match_operator'],
    '#options' => array(
      'STARTS_WITH' => t('Starts with'),
      'CONTAINS' => t('Contains'),
    ),
    '#description' => t('Select the method used to collect autocomplete suggestions.'),
  );
  $form['size'] = array(
    '#type' => 'textfield',
    '#title' => t('Size of textfield'),
    '#default_value' => $settings['size'],
    '#element_validate' => array('_element_validate_integer_positive'),
    '#required' => TRUE,
  );

  return $form;
}

/**
 * Implements hook_field_widget_form().
 */
function civsearch_code_reference_field_widget_form(&$form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) {

  $element += array(
    '#type' => 'textfield',
    '#maxlength' => 1024,
    '#defaul_value' => 'bob',
    '#size' => $instance['widget']['settings']['size'],
  );

  return array('target_id' => $element);
}

/**
 * Implements hook_field_formatter_info().
 */
function civsearch_code_reference_field_formatter_info() {
  return array(
    'civsearch_code_reference_label' => array(
      'label' => t('Label'),
      'description' => t('Display the label of the referenced codes.'),
      'field types' => array('civsearch_code_reference'),
      'settings' => array(
        'link' => FALSE,
      ),
    ),
  );
}

/**
 * Implements hook_field_formatter_settings_form().
 */
function civsearch_code_reference_field_formatter_settings_form($field, $instance, $view_mode, $form, &$form_state) {
  $display = $instance['display'][$view_mode];
  $settings = $display['settings'];

  $element = array();

  if ($display['type'] == 'civsearch_code_reference_label') {
    $element['link'] = array(
      '#title' => t('Link label to the referenced code.'),
      '#type' => 'checkbox',
      '#default_value' => $settings['link'],
    );
  }

  return $element;
}

/**
 * Implements hook_field_formatter_settings_summary().
 */
function civsearch_code_reference_field_formatter_settings_summary($field, $instance, $view_mode) {
  $display = $instance['display'][$view_mode];
  $settings = $display['settings'];

  $summary = array();

  if ($display['type'] == 'civsearch_code_reference_label') {
    $summary[] = $settings['link'] ? t('Link to the referenced code') : t('No link');
  }

  return implode('<br />', $summary);
}

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

```

**Error**

```
PDOException: SQLSTATE[23000]: Integrity constraint violation: 1048 Column
'field_jurisdiction_target_id' cannot be null: INSERT INTO
{field_data_field_jurisdiction} (entity_type, entity_id, revision_id, bundle,
delta, language, field_jurisdiction_target_id) VALUES
(:db_insert_placeholder_0, :db_insert_placeholder_1, :db_insert_placeholder_2,
:db_insert_placeholder_3, :db_insert_placeholder_4, :db_insert_placeholder_5,
:db_insert_placeholder_6); Array ( [:db_insert_placeholder_0] =>
civsearch_property [:db_insert_placeholder_1] => 17 [:db_insert_placeholder_2]
=> 17 [:db_insert_placeholder_3] => test [:db_insert_placeholder_4] => 0
[:db_insert_placeholder_5] => und [:db_insert_placeholder_6] => ) in
field_sql_storage_field_storage_write() (line 452 of
/var/dev/modules/field/modules/field_sql_storage/field_sql_storage.module)

```

**Debug Backtrace**

```
15: field_sql_storage_field_storage_write() (Array, 2 elements)
14: call_user_func_array() (Array, 1 element)
13: module_invoke() (Array, 2 elements)
12: field_attach_insert() (Array, 2 elements)
11: EntityAPIController->invoke() (Array, 2 elements)
10: EntityAPIController->save() (Array, 2 elements)
 9: Entity->save() (Array, 2 elements)
 8: civsearch_property_edit_form_submit() (Array, 2 elements)
 7: form_execute_handlers() (Array, 2 elements)
 6: drupal_process_form() (Array, 2 elements)
 5: drupal_build_form() (Array, 2 elements)
 4: drupal_get_form() (Array, 2 elements)
 3: civsearch_property_form_wrapper() (Array, 2 elements)
 2: call_user_func_array() (Array, 1 element)
 1: menu_execute_active_handler() (Array, 2 elements)
 0: main() (Array, 2 elements)

```

# Answer
> 2 votes
Try this:

```
/**
 * Implements hook_field_widget_form().
 */
function civsearch_code_reference_field_widget_form(&$form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) {
  $value = isset($items[$delta]['target_id']) ? $items[$delta]['target_id'] : '';

  $element += array(
    '#type' => 'textfield',
    '#maxlength' => 1024,
    '#default_value' => $value,
    '#size' => $instance['widget']['settings']['size'],
  );

  // There are array wrapper because if it is no then value will be cut to one letter.
  // Link to realted toric is under the code block.
  return array(array('target_id' => $element));
}

```

Letter cutting.. Second array wrap is because of this FIELD\_BEHAVIOR\_CUSTOM, for default type one time is enough. Also, you have text mistake in code `'#defaul_value' => 'bob'`, there is no 't' at the 'defaul' end, and this value must be integer.

# Answer
> 0 votes
Since you specified that `target_id` is `not null` in `hook_field_schema`, therefore and you're actually passing NULL as per `db_insert_placeholder_6`, it won't let you save the field.

So either this line :

```
'not null' => TRUE,

```

needs to be removed (field instance needs to be recreated) or make sure the value is not empty

This line is invalid as per typo:

```
'#defaul_value' => 'bob',

```

so it should be:

```
'#default_value' => 'bob',

```

That's probably the main reason.

---
Tags: entities
---


# Question
Title: drupal 7 display user info for current user
I need to display `name, role, photo` of current user. I'm use `views`, in `Advanced settings` add `Contextual filters` select `Content: Author uid` and in settings of it select Provide default value ,in type selectbox choose `User ID from logged in user`. But in fields i haven't field 'user:name'. If i create relationship content : author , user name will be displayed, but only for users, that published node. At the end, i want see like this

```
Hello, SmithJN
Role: Authorised user
Photo: [photo]

```

# Answer
When you create the view, at the very first screen, you have the option to select the entity type on which you want to create the view. (thank J.Reynolds)

Then in Fields add Field `Name, Role, Image` In Fileter Criteria add filter `User : current`

It's all !
> 2 votes

---
Tags: users, views
---