I'm using an image in my field collection, and would like to use FileField paths to put uploaded files in the same folder as the field collection's host Node.

There's no token for the host node available in the Replacement Patterns.

Comments

bt82’s picture

+1

i am having exactly the same problem. any solution would be appreciated.

Anonymous’s picture

Would love to have node tokens work in field collections as well.

mnlund’s picture

Second this! The Host entity token doesn't work as expected in Rules. None of the bundle tokens are showing.

areynolds’s picture

If you're looking to access field collections through Rules, you can use the data selector in the manner described in this issue.

That said, I agree that some better token integration would be a big step in making Field Collections easier to use.

nicholas.alipaz’s picture

Kind of odd this is not already available seeing how a token module was created. Hope someone can look into this. I may at some point, but not sure if I can do it for my current project due to deadline.

nicholas.alipaz’s picture

I guess the token module might be part of the entity api, hadn't realized when I posted initially. However, this still seems to be of use and I do wonder if it should be in the queue for Entity API instead.

Anyhow, I have little time to deal with a proper patch so I threw together some code that gets the job done for the one field I need this for. This is likely the completely wrong way of performing the replacement as I believe I should be using the token chaining bit. But again, time is of the essence and I had no time to attempt wrapping my head around chaining. Do note the hardcoded field and table names, this is just in a separate module so that I can get what I need until a proper solution is found:

function field_collection_token_token_info() {
  $info['tokens']['field_collection_item']['parent-node'] = array(
    'name' => t('Field Collection Parent Node NID'), 
    'description' => t("Parent node NID."), 
    'type' => 'format',
  );
  return $info;
}

function field_collection_token_tokens($type, $tokens, array $data = array(), array $options = array()) {
  $replacements = array();
  $sanitize = !empty($options['sanitize']);

  if ($type == 'field_collection_item' && !empty($data[$type])) {
    $item = $data[$type];

    foreach ($tokens as $name => $original) {
      switch ($name) {
        case 'parent-node':
          $result = db_query("SELECT node.* FROM {field_data_field_subtitles_data} col, {node} node WHERE col.entity_id = node.nid AND col.field_subtitles_data_value = :eid", array(':eid' => $item->item_id));
          $results = $result->fetchAll();
          $replacements[$original] = $results[0]->title;
          break;
      }
    }
  }
  return $replacements;
}
johaziel’s picture

First enabled Entity_token
Then created a module field_collection_token inspired of #6 like this

function field_collection_token_token_info() {
  $info['tokens']['field_collection_item']['parent-node'] = array(
    'name' => t('Field Collection Parent Node NID'),
    'description' => t("Parent node NID."),
    'type' => 'format',
  );
  return $info;
}

function field_collection_token_tokens($type, $tokens, array $data = array(), array $options = array()) {
  $replacements = array();
  $sanitize = !empty($options['sanitize']);

  if ($type == 'field_collection_item' && !empty($data[$type])) {
    $item = $data[$type];

    foreach ($tokens as $name => $original) {
      switch ($name) {
        case 'parent-node':
          $fc=entity_load('field_collection_item', array($item->item_id));
          $host_entity = $fc[$item->item_id]->hostEntity();
          $replacements[$original] = $host_entity->nid;
          break;
      }
    }
  }
  return $replacements;
}

Now, you will see the Field collection tokens in Replacement patterns of FileField paths
with [field_collection_item:parent-node]

RicardoJBarrios’s picture

I've tried #7, but a dpm of $host_entity give me an empty result and doesn't work. I've been looking at the API and googling a lot and I've found that in some scenarios hostEntity() doesn't work. I'm using it in File (Field) Paths.

Someone have it working?

Drupal 7.17
Entity API 7.x-1.x-dev (2012-Oct-24)
File (Field) Paths 7.x-1.0-beta3
Field collection 7.x-1.0-beta4

tommychris’s picture

Same as #8, its notworking :(

field_collection_token_token() not run, only field_collection_token_token_info().

Here is the .info file for module:

name = "Field Collection Token"
description = "http://drupal.org/node/1372652 #7"
core = "7.x"
dependencies[] = field_collection
dependencies[] = token
dependencies[] = filefield_paths
dependencies[] = entity_token
jhoffmcd’s picture

I am also looking for a fix to this. Hopefully we can all resolve this. I will test as well.

I'm also using File (Field) Paths

neRok’s picture

StatusFileSize
new1.14 KB

#7 works for me. You get the nid as described (which is all I wanted), but now that you have the nid you should be able to load all the nodes tokens.

Pre-made module of #7 is attached.

yannickoo’s picture

StatusFileSize
new1.62 KB

Here is a more coding standard version of #11. I think it would be better to have the whole node as token and not just the node id.

yannickoo’s picture

Status: Active » Needs review

Forget the extra module, let's put this into Field collection. The problem with this patch is that it does not work for other host entity types than node. Means that this won't work if your field collection is in a user, comment, taxonomy term ... entity.

I have no idea how to fix that because you have to specifiy the type which has to be sth. like 'node'. There is no 'entity' type.

yannickoo’s picture

Forgot the patch...

yannickoo’s picture

Title: Provide host entity ID as token » Token support for host entity
Karthick_s’s picture

Status: Needs review » Active

I use this along fileField path .The patch works fine on a saved node. but it does not fetch host entity details on node creation itself. I use embedded widget.

yannickoo’s picture

Status: Active » Needs work
jhoffmcd’s picture

Just to confirm before I try any of this, you say it does not gather Entity replacement patterns, only Nodes?

katannshaw’s picture

#14 worked great for me. Thanks for your work on this patch.

petrovnn’s picture

please include patch #14 in next release, i have absolutely same problem

designerbrent’s picture

This looks like it will be helpful, though I can't get it to work. Shouldn't there be a line that goes into the module file to make it load the .token.inc file?

yannickoo’s picture

No that is not necessary. Did you try clearing the cache?

designerbrent’s picture

Not sure why it wasn't working yesterday for me but at least the tokens show up for me now. I am having a problem with trying to get the NID to actually go into the first filename.

markj’s picture

I applied the patch from #14 and the replacement tokens are showing up for me, but when I try to use one of the tokens, I get the following error:

Warning: Illegal offset type in isset or empty in token_tokens() (line 900 of /mnt/u1/var/www/drupal/sfutheses/sites/all/modules/token/token.tokens.inc).

It doesn't matter if the token is for a system-generated value, like [field_collection_item:host:nid], or for a content-type-specific field.

Using Field Collection 7.x-1.0-beta5, File (Field) Paths 7.x-1.0-beta4, Token 7.x-1.5, Entity Tokens 7.x-1.1, Drupal core 7.22.

jastylr’s picture

I'm getting the same error message as well:

Warning: Illegal offset type in isset or empty in token_tokens() (line 900 of /Applications/MAMP/htdocs/cshof-drupal/sites/all/modules/token/token.tokens.inc).

I was trying to set the path for an uploaded image in a field collection using File Field Paths and a value from the host content type. I was able to select the appropriate token but when I created the actual content and saved it, I got the error and the image path did not include the value I was trying to set.

jastylr’s picture

As an update:

What I have is a content type representing a group of individuals for a particular year. The year is a Date field in the host content type and I have a field collection that includes fields for an individual's name and their image. I have setup the File Field Path for the uploaded image to grab the Year value from the host node. The field collection itself is setup to allow for multiple instances.

I created the content, specifying a year and uploading my first image as part of the field collection. When I save the node, I get the error above in my previous post and the file path for the image does NOT include the year as intended.

I found that by going back and editing the node to remove the image and re-adding it, the error message no longer appears and the image file ends up in the correct path which includes the year value from the host entity. This happens again if I edit the node and add another field collection instance to upload another image. I can then again, go back and edit the node to remove and re-add the image and everything is fine again.

Not sure why this is happening but seems to have something to do with adding versus editing the content?

daniel wentsch’s picture

Thanks for your Patch #14 @yannickoo, but it seems I can't get it to work:

using
- field_collection 7.x-1.0-beta5
- filefield_paths 7.x-1.0-beta3+4-dev

Your patch was successfully applied, field_collection.tokens.inc exists, fluched caches multiple times – but no luck, I don't get any host token replacement patterns shown on the image field inside my field collection (Screenshot attached).

Any ideas? Are you maybe using the dev build of field_collection?

Thanks & regards,
Daniel

UPDATE:
Typically: as soon as I posted about my issue I found the solution. I accidentially used the wrong token browser (below the field description) instead of looking at the replacement patterns inside filefield paths' fieldgroup.

The module now works as desired - perfect, thanks a lot.

daniel wentsch’s picture

Status: Needs review » Needs work

Confirming issues #24/#25.

As jastylr said, this error only occurs upon adding files to new field collection instances. Upon editing an already existing field collection the tokens get properly inserted.

Could anyone for who #14 is working on new field collection instances please post their versions of filefield_paths, entity, token and field_collection?

I'm currently using filefield_path-7.x-1.0-beta4, entity-7.x-1.1, token-7.x-1.5 and field_collection-7.x-1.0-beta5 and wonder if upgrading to dev might help.

maximpodorov’s picture

Status: Needs work » Needs review
StatusFileSize
new1.66 KB

#14 is fixed to support token info information provided by host entity.

yannickoo’s picture

Status: Needs work » Needs review
StatusFileSize
new1.65 KB

I removed a single line.

daniel wentsch’s picture

Thanks yannickoo, but the problem remains after successfully patching and clearing the caches.
After adding a new instance of a field collection and saving an (existing) node I still get the following error and the replacement pattern (node id of the host entity) stays empty :(

Warning: Illegal offset type in isset or empty in token_tokens() (Zeile 900 von /foobar/sites/all/modules/contrib/token/token.tokens.inc).

cecrs’s picture

The patch in #30 works beautifully on already existing field collection items, i.e., if I am editing an existing field collection entry on a node. If I am creating a new field_collection instance, that token fails with the Warning: Illegal offset type in isset or empty in token_tokens(). error.

I think that the basic issue is that the token code is being run before the node is saved, it may be similar to this issue for the domain module: https://drupal.org/node/1336698.

nicholas.alipaz’s picture

My guess is $data[$type]->item_id is not yet available during the insert vs the edit op, but I could be wrong.

TheChemic’s picture

I'm also looking for a solution to this. I need to get the parent node's id on new node creation so that I can keep my image files organized into nid folders.

c3rberus’s picture

I too am looking for this, would like to use a token value from the host entry.. any change for author to look at the patches submitted and commit something in --dev? :)

bpsommerville’s picture

Changing the field_collection_tokens method in patch #30 as follows seems to fix the error in #31 for me

function field_collection_tokens($type, $tokens, array $data = array(), array $options = array()) {
  $replacements = array();
  $sanitize = !empty($options['sanitize']);

  if ($type == 'field_collection_item' && !empty($data[$type])) {
    $item = $data[$type];

    if ($host_entity_tokens = token_find_with_prefix($tokens, 'host')) {
      // Load field collection item and getting host entity and host entity type.
      if($item instanceof FieldCollectionItemEntity && $item->hostEntityType() ){
         $host_entity_type = $item->hostEntityType();
         $host_entity = $item->hostEntity();
      } else {
         $field_collection_item = entity_load('field_collection_item', array($item->item_id));
         $host_entity_type = $field_collection_item[$item->item_id]->hostEntityType();
         $host_entity = $field_collection_item[$item->item_id]->hostEntity();
      }
      $host_entity_info = entity_get_info($host_entity_type);
      $host_entity_token_type = isset($host_entity_info['token type']) ? $host_entity_info['token type'] : $host_entity_type;
      $replacements += token_generate($host_entity_token_type, $host_entity_tokens, array($host_entity_token_type => $host_entity));
    }

  }

  return $replacements;
}
markdatter’s picture

I'm using the code from #36 and I am not getting any errors when creating a new host node. Unfortunately, the token replacement is not working properly when I try to use the nid of the host entity during host node creation. I inserted some debugging lines into the code and I noticed that the nid of $item->hostEntity() is "NULL" when the value of $host_entity is being assigned.

I also noticed that the "else" block is not being executed during new host node creation, nor is it being executed when editing an existing host node. Under what condition would that code be executed?

nicholas.alipaz’s picture

This thread is going to go on forever if people don't understand what I wrote earlier:

My guess is $data[$type]->item_id is not yet available during the insert vs the edit op, but I could be wrong.

During the insert op of any entity, the identifier is not yet assigned. The only solution that I can see is to do a query for the auto-increment's next available value or perhaps save the entity twice so you can grab the id.

jody lynn’s picture

StatusFileSize
new3.38 KB

I added a hook_field_attach_insert to resave the field collections right after the host entity's field collection field is created.

This works so long as your tokens are set to change on an update. For example, I'm using filefield_paths and had to set the field settings to 'active updating'.

Status: Needs review » Needs work

The last submitted patch, field_collection-1372652-39.patch, failed testing.

daniel wentsch’s picture

Status: Needs review » Needs work
StatusFileSize
new3.14 KB

Patch #39 didn't apply, I changed paths of diff file to make it apply.

PS: Seems to work now, thanks a lot.

daniel wentsch’s picture

Status: Needs work » Needs review
stevendeleus’s picture

Status: Needs work » Needs review

Is it possible to support tokens for any host entity, not just nodes?

daniel wentsch’s picture

Using this setup on another site I found another issue with patch #39:

It doens't work when re-saving an existing node with revisioning enabled.
As soon as Created new revision is checked the following good old error comes back and the filefield path is reset to none:
Warning: Illegal offset type in isset or empty in token_tokens() (Zeile 900 von /foobar/sites/all/modules/contrib/token/token.tokens.inc).

amogiz’s picture

Hi, i applied with success the patch, but i can't get the [node:title] token from the list.
Dis I miss something ?

amogiz’s picture

Finally I foud it : the tokens were in Field Collection host entity part.
Thanx for this great patch !!!!!!

markdatter’s picture

I'm using #41 and everything seems to be working when I upload field collection images during new host entity creation. This works for me without filefield_paths set to 'active updating'. Am I missing something, or have others made this work without that setting?

I don't have revisioning enabled, so I can't speak to the concern raised in #44.

dlomis’s picture

jody lynn’s picture

I had the same issue as in #44. A node update with revisions on breaks the token.

Here's an updated patch to address that.

jody lynn’s picture

Issue summary: View changes
StatusFileSize
new3.39 KB
ndobromirov’s picture

Hello guys,
I had similar problem to this one. It was to use tokens from the root node, containing a field collection within field collection.

For example: node -> fild_collection -> field_collection -> field.
The field needs to get tokens provided by the node.

Based on the solution in #50 with some small changes, here is how I made it work:
Add new token:

<?php
array(
  'root_host' => array(
    'name' => t('Field Collection root host entity'),
    'description' => t('Root host entity.'),
    'type' => 'node',
  ),
);

This helper method:

<?php
/**
 * Helper method tho extract the host entity for a given field_collection.
 * 
 * @param mixed $field_collection_item
 * @return array(host_entity_type, host_entity)
 */
function _<MY_MODULE>_get_host_entity_info($field_collection_item) {
  // Safty check.
  if (!($field_collection_item instanceof FieldCollectionItemEntity)) {
    $field_collection_item = new FieldCollectionItemEntity((array)$field_collection_item);
  }
  // Load field collection item and get host entity and host entity type.
  $host_entity_type = $field_collection_item->hostEntityType();
  $host_entity = $field_collection_item->hostEntity();
  
  // When saving revisions, only $item->original knows the hostEntity.
  if (!$host_entity && isset($field_collection_item->original)) {
    $host_entity_type = $field_collection_item->original->hostEntityType();
    $host_entity = $field_collection_item->original->hostEntity();
  }
  return array($host_entity_type, $host_entity);
}

Token info implementation change:

<?php
  if ($type == 'field_collection_item' && !empty($data[$type])) {
    $item = $data[$type];
    
    if (($host_entity_tokens = token_find_with_prefix($tokens, 'host'))) {
      // Get host entity
      list($host_entity_type, $host_entity) = _<MY_MODULE>_get_host_entity_info($item);
      
      $host_entity_info = entity_get_info($host_entity_type);
      $host_entity_token_type = isset($host_entity_info['token type']) ? $host_entity_info['token type'] : $host_entity_type;
      $replacements += token_generate($host_entity_token_type, $host_entity_tokens, array($host_entity_token_type => $host_entity));
    }
    
    if (($root_host_entity_tokens = token_find_with_prefix($tokens, 'root_host'))) {
      // Keep original $item.
      $new_item = $item;
      // Get root host entity.
      do {
        list($host_entity_type, $host_entity) = _<MY_MODULE>_get_host_entity_info($new_item);
        $new_item = $host_entity;
      } while ($host_entity_type == 'field_collection_item');
      
      $host_entity_info = entity_get_info($host_entity_type);
      $host_entity_token_type = isset($host_entity_info['token type']) ? $host_entity_info['token type'] : $host_entity_type;
      $replacements += token_generate($host_entity_token_type, $root_host_entity_tokens, array($host_entity_token_type => $host_entity));
    }
  }

Probably this not the prefect thing as there are some code repetitions, but let me hear your opinions and I will make a patch for it.

marc.groth’s picture

#50 worked perfectly for me. Thanks Jody Lynn.

Using the following setup:

Drupal 7.26
Entity API 7.x-1.3
File (Field) Paths 7.x-1.0-beta4
Field collection 7.x-1.0-beta5

vincer’s picture

After applying patch in #50, in admin/reports/status I get the following alert:

The following token types are not defined but have tokens ... field_collection_item

When I replace the patched dev version with field_collection-7.x-1.0-beta7 the alert is gone.

UPDATE

I reattempted this and it works now.

czigor’s picture

I have the same issue. I do have a [field_collection_item:host_entity] token though, but it does not work.

Problem/Motivation

  1. Minimal Drupal install
  2. Enable Rules UI, Field UI and Field collection.
  3. Create a page CT with a Field collection in it. Enable revisions for Page.
  4. Create a Rule with an 'After updating an existing field collection item' event. Condition: [field_collection_item:host_entity] is of entity type node. Action: display message: "FC updated!"
  5. Edit the FC inside a page node.
  6. No message appears.

Root of problem

The problem is that when FieldCollectionItemEntity::fetchHostDetails() is called from rules_unwrap_data() the revision_id has not been written into the database yet. Thus the EFQ in FieldCollectionItemEntity::fetchHostDetails() has no result.

Proposed resolution

The patch in #50 is almost good, except that no new tokens are needed.

czigor’s picture

czigor’s picture

Status: Needs review » Needs work

This patch is not good. It makes entity update hooks run twice, first with correct $entity->original property then with $entity->original being identical to the updated field collection.

Somehow the field collection update workflow should be changed or tweaked.

jody lynn’s picture

czigor: I agree. It's just a dirty hack for those desperate for the feature.

czigor’s picture

Status: Needs work » Needs review
StatusFileSize
new1017 bytes

The following patch is OK assuming the host entity of a field collection does not change. A hint supporting the validity of this assumption is in the DOxygen of FieldCollectionItemEntity::setHostEntity(): "Sets the host entity. Only possible during creation of a item."

jmuzz’s picture

You are correct, the host entity for a field collection item should not change.

I have verified that field_collection_item:host_entity does appear in the data selectors in Rules, but I don't think it's the same thing as a token. Try this:

- Create a view on field_collection_items .
- Add to the Header a "Global: Text area"
- In the settings for the text area check "Use replacement tokens from the first row"
- [item_id] is the only one available.

You can also see this in rules if you go to step 4 of your instructions in #54 and open up the replacement patterns for the message.

I think that #50 should be reviewed here and #58 should be put into a separate issue.

whop’s picture

Hello, is there any update ?
I also need to use host entity token, patch #50 is enabling that.
But it saves correctly only when editing content, thus on second attempt. Not at creation time.
#58 doesn't add host entity.
Using beta 7

Thanks for help or suggestions !

jmuzz’s picture

Status: Needs review » Needs work

#58 allows the host to be picked in the data selector in rules but does -not- add a token for it.

#50 is not good as explained in #56 and #57.

veleiro’s picture

So I can use rules to get the host entity id? I'm looking to pass it as a views argument.

veleiro’s picture

I ended up using the following custom token for my situation:


$path = current_path(); 
$base = basename($path);

if($base=='edit'){

$collection_id = dirname($path);
$collection_id_base = basename($collection_id);
$collection = entity_load_single('field_collection_item', $collection_id_base);
$node = $collection->hostEntity();
return $node->nid;

}
else{
return $base;
}
kaare’s picture

How should the format be? I've started implementing field_collection.tokens.inc, but have reached an architectural barrier. The Field collection entity contains some basic information about the host entity that can be provided without loading the host entity and fetch the values from there:

  • FieldCollectionItemEntity::hostEntityType()
  • FieldCollectionItemEntity::hostEntityBundle()
  • FieldCollectionItemEntity::hostEntityId()

These can either be provided directly to the $type == 'field_collection_item' tokens like this:

  • [field_collection_item:host-type]
  • [field_collection_item:host-bundle]
  • [field_collection_item:host-id]

Easy peasy. The major architectural question is how to provide the host entity, as this can be any kind of fieldable, tokenable entity. The token browser knows nothing of this. The idea I've had so far is to provide separate token for each available entity type and follow Organic Group's example in naming. This will leave it up to the site builder to pay attention to what token to use.

  • [field_collection_item:host--node]
    • [field_collection_item:host--node:nid]
    • [field_collection_item:host--node:title]
    • [field_collection_item:host--node:content-type]
  • [field_collection_item:host--user]
    • [field_collection_item:host--user:uid]
    • [field_collection_item:host--user:mail]
  • [field_collection_item:host--field_collection_item]
    • [field_collection_item:host--field_collection_item:host--node:nid]
    • [field_collection_item:host--field_collection_item:host--user:name]

Otherwise, if the host token should be entity type independent, we have to provide all available properties and fields that all entities can have, which creates chaos.

As I've written this I've come to the the conclusion that this is the cleanest way to do it. Any opinions?

kaare’s picture

Oooor.. one could create a new token type 'host' and provide all attributes and nested values there:

  • [field_collection_item:host:type]
  • [field_collection_item:host:bundle]
  • [field_collection_item:host:id]
  • [field_collection_item:host:node:nid]
  • [field_collection_item:host:node:content-type:machine-name]
  • [field_collection_item:host:node:title]
  • [field_collection_item:host:user:uid]
  • [field_collection_item:host:user:mail]
  • [field_collection_item:host:field_collection_item:type]
  • [field_collection_item:host:field_collection_item:host:node:title]
kaare’s picture

Status: Needs work » Needs review
StatusFileSize
new4.67 KB

And here is the implementation as suggested in #65. It works with File (Field) Paths.

The token browser becomes really heavy with this if you have a lot of fieldable entity types available, so the use of Token tweaks module is recommended.

kaare’s picture

Issue tags: +Needs tests
kaare’s picture

Status: Needs review » Needs work
StatusFileSize
new101.01 KB

*facepalm* Sorry, I've completely ignored major part of this issue, only looked at the first and last comments and patches, which doesn't include the field_collection.token.inc part. Having read everything my patch also struggles with the case of saving nodes with field collections and revisions enabled. I'll have a closer look at the current and possible other solutions later this week.

In any case, I think having a new token type ('host') and chained entity type tokens after that solves the problem of not knowing what kind of entity type the host is, at least in the browser. This is how it behaves in the token browser:

Token browser with host entity selectors.

This also lets you select Field collection items as host entities, allowing for complex nested setup.

kaare’s picture

This patch fixes tokens during revisions.

There are other concerns that are out of the scope of this issue:

  • #59: Views tokens. The tokens available in views config is a completely different system from Drupal core tokens => unrelated.
  • #54: Rules tokens browser. Rules doesn't use Drupal core tokens in its selector or during data mining. => unrelated. Add a separate issue for this. Otherwise, Rule Tokens might be what you want.

To keep this issue simple let's keep focus: Only provide core token support for the host entity of field collections.

kaare’s picture

Status: Needs work » Needs review
gge’s picture

Can you please build a dev?

kaare’s picture

@gge: You mean build a test site?

kaare’s picture

I realize the list of available host entity types can be made smarter if one look at what field collections exists and what they are attached to. This would definitely clean up some mess in the token browser.

kaare’s picture

Like this. The entity browser becomes much more sane without the noise of entity types not instantiated with field collection fields. This version uses field_info_field_map() to pick items from entity_get_info()

Token browser expanded with field collection host entities.

gge’s picture

I wanted to use File (Field) Paths for an image field in a field collection and I needed to use a token that belongs to the host node. I was wodering if you are going to push your patch to the dev branch so other people could test it.

Thanks.

nicholas.alipaz’s picture

gge, a patch is typically only pushed into a branch once it has been reviewed and tested (successfully) by the community. Plus I don't believe kaare to be a mainteinter on the field collection module, nor am I.

kaare, nice work on the patch, I have yet to test but will try to soon.

kaare’s picture

@gge: Yeh, I'm no maintainer, just in need of this exact feature for my current project. Have a look at drush makefiles to automatically setup a set of modules with selected patches, if you haven't already.

@nicholas.alipaz: Thx! A review of it would help tremendous for the maintainers to get this in.

MatthewHager’s picture

Status: Needs review » Reviewed & tested by the community

I just tested this with filefield_paths and it worked perfectly. Thanks for your patch!

jmuzz’s picture

Status: Reviewed & tested by the community » Needs work
+++ b/field_collection.tokens.inc
@@ -0,0 +1,145 @@
+    'name' => t("Host entity bundle"),

All the strings should be single quoted unless they contain variables or single quotes.

+++ b/field_collection.tokens.inc
@@ -0,0 +1,145 @@
+    'description' => t("For 'node' entity types this is the content type, otherwise available as [node:content-type:machine-name]"),

All sentences should end with a full stop.

@kaare, did you have any plans to add tests for this? I saw you set the tag for it. If nobody is going to do that soon it can be made a separate issue.

kaare’s picture

StatusFileSize
new5.32 KB
new2.66 KB

Thanks for the review. Points addressed and sprinkled some html as cosmetic on some of the text strings.

@jmuzz: No tests are planned. The tag was in hope that some more capable in writing tests than me would find time for it. It probably should be a follow up issue.

kaare’s picture

Status: Needs work » Needs review
Issue tags: -Needs tests

  • jmuzz committed 09a4419 on 7.x-1.x authored by kaare
    Issue #1372652 by kaare: Token support for host entity
    
jmuzz’s picture

Thanks kaare.

Followup issues still need to be created (or found if they exist) for:

1 - Rules tokens
2 - Views tokens
3 - Test coverage

Should link to this issue and post relevant patches from it (#58 for example).

jmuzz’s picture

Status: Needs review » Active
kaare’s picture

Status: Active » Needs review

Follow-up issues are unrelated to this issue's status. It still needs review, or if you are happy with this please feel free to RTBC it :-)

jmuzz’s picture

I committed it. See #82. I just don't think the issue should be closed until the followups get made.

kaare’s picture

Hah, you did! Totally missed that. Thx a bunch! :-)

kaare’s picture

Come to think about views' replacements tokens. This comes out of the box with views using relations? You have to set up a relation in order to access other entities. So this probably doesn't need a follow-up?

zmove’s picture

Status: Needs review » Needs work

Tested it and it works partially.

I encountered a problem with referenced fields on the host entity.

The host entity of the field collection is a node, that have a commerce product reference (it's a node display for people who knows drupal commerce).

With the patch, I can access to the node field-product token by using this

[field_collection_item:host:node:field_product]

And normally, I should be able to access the product SKU by doing that :

[field_collection_item:host:node:field_product:sku]

This is an available token when I work on the imagefield of my node, but when I work on my field collection. Even with that patch that allow to reference host entity (and all it's children), I got an error :

The File path is using the following invalid tokens: [field_collection_item:host:node:field_product:sku].

It seems that the commerce products token are not "parsed" to provide all available token when you are on a field collection.

Any ideas to fix that ?

kaare’s picture

+++ b/field_collection.tokens.inc
@@ -0,0 +1,145 @@
+      foreach ($entity_types as $entity_type => $entity_info) {
+        if ($entity_tokens = token_find_with_prefix($tokens, $entity_type)) {
+          $host = $collection->hostEntity();
+          $replacements += token_generate($entity_type, $entity_tokens, array($entity_type => $host), $options);
+        }
+      }

This piece of code will leave it to the child tokens to replace the nested values. The entity (node) is passed and then it's up to the child token handler to perform the substitutions. So I would look up the token implementation that handles you sku code and start debugging from there, then nest myself back up to field_collection_tokens().

osopolar’s picture

Status: Needs work » Needs review
StatusFileSize
new2.28 KB

I also run into problems where i need the token [field_collection_item:host:node:url:path] for the field collection pathauto alias. I didn't get the node alias as expected but the path node/nid. The problem was, that LANGUAGE_NONE was passed instead of the hosts language code.

I attached a patch where the host entity's language will be passed as option to token_generate(). I am not entirely sure if that is the correct way to fix it. Or maybe it get fixed somehow with the issue #1344672: Field Collection: Field translation (entity_translation) support.. At least it works for my purposes.

kaare’s picture

Status: Needs review » Fixed

@zmove, @osopolar: Please create a new issues for any new problems. This issue is committed and fixed.

osopolar’s picture

@zmove, did you find the cause or a solution for the problem with the sku? Would be nice if you test my patch, maybe it fixes your issue too.

As suggested I opened a new follow up issue, please post your answer there: #2567203: Improve token support for host entity.

zmove’s picture

@osopolar sorry, I probably used another method to do what I want. I say probably because in fact, I even don't remember the project that needed this feature. I just switched to something else.

Status: Fixed » Closed (fixed)

Automatically closed - issue fixed for 2 weeks with no activity.

jay.lee.bio’s picture

If anyone can solve the same problem for Paragraphs, I'd really appreciate it.