When cloning entity, fields are not cloned.

I've traced how the cloning works and found that it is done in entity_ui_get_form and there is nothing about fields.

I am not sure if this should work out of the box, but it would be nice to have an option to clone a fields.

Support from Acquia helps fund testing for Drupal Acquia logo

Comments

dealancer’s picture

Another problem that I've noticed is that entity is cloned without any fields, even default fields are not created, which is kind of weird.

zkday’s picture

Assigned: Unassigned » zkday

This is needed features,
Assign for me.
Thanks.

zkday’s picture

Status: Active » Needs review
FileSize
1.79 KB

Sorry for delay.
This is an patch for this issue. ;)

klonos’s picture

gillarf’s picture

Just tried this patch, and the clone works now on fields (thank you hugely zkday!)

But NB clone still does not copy field groups.

pgrond’s picture

I can confirm the patch is working. Fields are copied over when cloning.

elvismdev’s picture

#3: 1513812.patch queued for re-testing.

geek-merlin’s picture

Status: Needs review » Reviewed & tested by the community

so as of #5/#6 it seems rtbc.

gillarf’s picture

Please note the patch does not fix this issue for field groups (http://drupal.org/project/field_group)

elvismdev’s picture

This patch not worked in my case to clone a Entity Registration type successfully, it drops me a lot of errors when trying to clone.

Notice: Undefined index: field_univ en _token_field_info() (línea 1322 de /var/www/eventos.unaicc.cu/sites/all/modules/token/token.tokens.inc).
Warning: array_count_values(): Can only count STRING and INTEGER values! en _token_field_info() (línea 1329 de /var/www/eventos.unaicc.cu/sites/all/modules/token/token.tokens.inc).
DatabaseTransactionNoActiveException: en DatabaseConnection->rollback() (línea 1019 de /var/www/eventos.unaicc.cu/includes/database/database.inc).

I am looking forward from this issue http://drupal.org/node/1537516 created for Entity Registration and they are pointing that the problem is related to Entity API, one or another, the patch not properly work at least for Entity Registration module in my case.

DamienMcKenna’s picture

FYI here's some code I wrote recently for cloning the field groups from a content type to an entityform, it might help improve this patch to also handle field groups:

function _copy_field__groups($content_type_name, $entityform_type_name) {
  $old_entity_type = 'node';
  $new_entity_type = 'entityform';

  // Clone the field groups.
  $all = field_group_info_groups();
  $groups = array();
  if (isset($all[$old_entity_type][$content_type_name])) {
    foreach ($all[$old_entity_type][$content_type_name] as $display_type => $group_types) {
      foreach ($group_types as $group_type => $group) {
        // Clear some settings.
        unset($group->id);
        unset($group->export_type);
        unset($group->export_module);

        // Update some others.
        $group->in_code_only = FALSE;
        $group->type = 'Normal';
        $group->entity_type = $new_entity_type;
        $group->bundle = $entityform_type_name;
        $group->identifier = str_replace($old_entity_type . '|' . $content_type_name, $new_entity_type . '|' . $entityform_type_name, $group->identifier);

        // Update the field names, this is dependent upon my specific use case.
        foreach ($group->children as $key => $field_name) {
          $group->children[$key] = _field_rename($field_name);
        }

        // Save the group.
        field_group_group_save($group);
      }
    }
  }
}
DamienMcKenna’s picture

Status: Reviewed & tested by the community » Needs work

Changing the status to "needs work" as it needs to also handle field groups.

zkday’s picture

I thinks entity module need provide an hook for this case, that is another module (e.g field_group, Entity Registration) will implements. and default suport field group by implements this in entity module.

yurg’s picture

Patch #3 was applied manually to Entity 7.x-1.1 (after automated patch fail) and it works as advertised.

dshields’s picture

Thanks for Patch #3, but this would be fantastic if it could handle Field Groups!

dshields’s picture

Does anyone know why cloning of entities doesn't allow for field groups to be cloned as well as the fields?

WebmistressM’s picture

I too am having this same problem. I tried to use the patch in #3 but I cant seem to apply it. Not sure if you can apply one patch file for patching multiple files (one being entity.module and the other being /includes/entity.ui.inc)

dshields’s picture

Try: patch -p1 < 1513812.patch
I think that command worked for me.

WebmistressM’s picture

Hmm.. Ill try that again. One thing I did notice when opening the patch file is that it had a patch for 2 different files within the entity module. I have never dealt with using a patch file that changed 2 files in one patch. Since one is in the main entity module directory and the other file is in entity/includes.... where should I place the patch file in the first place?

pixelsweatshop’s picture

-deleted-(wrong thread)

WebmistressM’s picture

Status: Needs work » Needs review

That seems to have done the trick. Not marking this as fixed but I do hope that this will go into the next release of Entity.

dshields’s picture

I don't think this should be closed until cloning entities allows for cloning of field groups as well as fields.

solquimpo’s picture

Hi. I'm attaching a patch which mostly contains zkday's work in #3 with very minor comment corrections. Also, I added the following lines:

    // Save entity key name value (e.g. type) where this entity is cloned from.
    // This value is handy for cloning other parts of the entity like field groups.
    $entity->cloned_from = $entity->{$entity_info['entity keys']['name']};

because I'm currently trying to patch another module (Entityform) to clone field groups.

dshields’s picture

#23 works perfectly for me!
Thanks, solquimpo!

Nicolas Bouteille’s picture

Issue summary: View changes

Applied it too. No errors and fields correctly cloned. Thank you!

mausolos’s picture

We're coming up on the two year anniversary for this issue. Looks like the code is working. Can we get this into an official Entity release anytime soon?

geek-merlin’s picture

@#26: the start is always to set RTBC.
see https://drupal.org/node/156119

setting rtbc as of #24 & #25

geek-merlin’s picture

Status: Needs review » Reviewed & tested by the community

Now really.

mausolos’s picture

:) thanks!

MaxBSU’s picture

When I applied patch from #23 and tried to clone Entityform entity, I got PHP Fatal Error 'Fatal error: Unsupported operand types in field.info.inc'. After some debug, I found that issue was related with these code lines of the patch:

  // Make sure entity is cloning this have field.
  if (!empty($entity->_field_instances)) {
   foreach ($entity->_field_instances as $field_instance) {
     $field_instance['bundle'] = $entity->{$entity_info['entity keys']['name']};
     $field = field_create_instance($field_instance);      
     field_update_field($field);
  }

In my case $field variable contains field's instance id from field_config_instance table as id property instead of field's config id, that stores in $field->field_id(in my case ids are not always similar). For this reason, some fields configuration in field_config table are wrongly rewrited with these code lines of field_update_field function

  // Store the field and create the id.
  $primary_key = array('id');
  drupal_write_record('field_config', $field, $primary_key);

Does anybody else have this problem or it can be reproduced only for me?

esbenvb’s picture

I have suggested a hook in this issue, https://drupal.org/node/2259799 which is less intrusive and more flexible, if other modules need other alterations to the entity object.

blacklabel_tom’s picture

bump

fago’s picture

Status: Reviewed & tested by the community » Needs work

Setting a special cloned_from key seems to be fine for me and avoids the introduction of a separate hook - so let's go with that instead of #31.

  1. +++ b/includes/entity.ui.inc
    @@ -662,6 +662,19 @@ function entity_ui_clone_entity($entity_type, $entity) {
    +    // Save entity key name value (e.g. type) where this entity is cloned from.
    +    // This value is handy for cloning other parts of the entity like field groups.
    

    Comment exceed 80chars. Generally, comment language should be improved.

  2. +++ b/includes/entity.ui.inc
    @@ -662,6 +662,19 @@ function entity_ui_clone_entity($entity_type, $entity) {
    +      // set info field_instances for entity and save it in hook_entity_insert.
    +      $entity->_field_instances = $field_instances;
    

    Is it necessary to do that? The more direct and less ugly approach would be to just load the fields of the cloned entity type in hook_entity_insert.

zkday’s picture

Assigned: zkday » Unassigned
mrsinguyen’s picture

Patch with comment #33

mrsinguyen’s picture

Status: Needs work » Needs review
nicholasThompson’s picture

Any news on this getting committed?

Nicolas Bouteille’s picture

Status: Needs review » Needs work

FYI : Patch #35 did not work for me cloning Entityform with fields. #23 did again.

alfaguru’s picture

I just tried using patch #23 to solve the problem of a registration type entity not getting fields on cloning. It didn't work so I set a breakpoint on the hook_entity_insert implementation to see why. In the following lines:

<?php
  $bundle = $entity->{$entity_info['entity keys']['name']};
  $entity->_field_instances = field_info_instances($entity_info['bundle of'], $bundle);

?>

- the field instances are being got from the new, cloned bundle, not the one being cloned from. For the registration type at least, this results in an empty set. Since the original bundle is in the 'cloned_from' field, it is not difficult to get its fields instead with the following additional code:

<?php
  if (empty($entity->_field_instances) && !empty($entity->cloned_from)) {
    $entity->_field_instances = field_info_instances($entity_info['bundle of'], $entity->cloned_from);
  }

?>

The above now works for me. Any comments? I'll roll a patch from #23 when I have time.

alfaguru’s picture

Just realised these lines:

  $bundle = $entity->{$entity_info['entity keys']['name']};
  $entity->_field_instances = field_info_instances($entity_info['bundle of'], $bundle);

- come from #35. I was experimenting with both patches and it looks like one breaks the other if you mix the code. Going to reapply 23 properly now...

rivimey’s picture

@alfaguru did you manage to reroll the patch as you suggested in #40?

rivimey’s picture

I have had a go at combining #35 with the subsequent mod; not guaranteeing I understood correctly but my limited testing worked.

alfaguru’s picture

@rvimey sorry I didn't get back on this. #23 worked perfectly for me with no need for further changes, once I'd removed the stuff from #35 accidentally mixed in.

rivimey’s picture

@alfaguru thanks for getting back to me. Are we therefore saying that #35 is a false trail, and #23 is good to go?

Do people agree that we could RTBC #23?

solquimpo’s picture

Aye.

rivimey’s picture

Status: Needs work » Reviewed & tested by the community

Given what @alfaguru and @solquimpo have posted recently, it seems reasonable to set the patch from #23 as RTBC.

It would be good however to get confirmation from both @MaxBSU and @fago gven that they both posted things relating to the #23 change.

Status: Reviewed & tested by the community » Needs work

The last submitted patch, 42: 1513812-with-added-cloned-from-field-42.patch, failed testing.

Status: Needs work » Needs review

Status: Needs review » Needs work

The last submitted patch, 42: 1513812-with-added-cloned-from-field-42.patch, failed testing.

peterlolty’s picture

Issue summary: View changes

I also confirm #23 patch is working to clone Entity Registration type. And there is a field collection field inside with NO problem.

ps. I hide #42 to avoid the system retest it and change the order of #23 patch to the front.

peterlolty’s picture

Issue summary: View changes
peterlolty’s picture

Status: Needs work » Reviewed & tested by the community

RTBC is for #23 patch.

Max_Headroom’s picture

#23 Patched and tested.
Only problem I found is that fieldgroups did not clone. But as an addon module, I think it is out of the scope of this issue.
+1 for commit

aliciatheduff’s picture

#23 patched and tested - cloning all registration entity fields

Leeteq’s picture

While I am all for committing this without https://www.drupal.org/project/field_group support (see comment #53), I think a new, follow-up issue should be created post-commit to get that also covered, since the field_group module is becoming important for so many projects (over 100.000 as per now).

darkodev’s picture

Tying to clone a Redhen entity and fields. Using patch #23 results in

Fatal error: Unsupported operand types in field.info.class.inc on line 495

Same error when trying to delete the cloned entity

Doing a dd() on line 495 shows an empty $field['settings'], which I assume is my issue. If I temporarily hack in some is_array() checks in field.info.class.inc for $field['settings'] and $field['storage']['settings'] I get a cloned entity with all fields. I was expecting that one of the fields wouldn't get cloned, perhaps, since it's settings might be borked, but looks like they were all created.

Could be something else at play for my particular use-case, so just noting this in case someone else encounters a similar issue.

fago’s picture

Status: Reviewed & tested by the community » Needs work

Reviewed #23 again:

  1. +++ b/includes/entity.ui.inc
    @@ -662,6 +662,19 @@ function entity_ui_clone_entity($entity_type, $entity) {
    +    // Save entity key name value (e.g. type) where this entity is cloned from.
    +    // This value is handy for cloning other parts of the entity like field groups.
    

    Comment exceeds 80chars.

  2. +++ b/includes/entity.ui.inc
    @@ -662,6 +662,19 @@ function entity_ui_clone_entity($entity_type, $entity) {
    +      // set info field_instances for entity and save it in hook_entity_insert.
    

    Comment must start as uppercase sentence. Also, it seems that work-a-round is necessary, but why? This should be documented here also as the naive approach would be different!

Also as darkodev wrote in #56, it looks like there are issues with it. Or does it work well for everyone else?

xaa’s picture

Trying to apply #23. I have same issue as Darkodev (#56) in field.info.class.inc, line 495.

Is it possible to revert without import full sql backup?
I've still the issue after patch reset. It seems a major issue here as the site becomes unavailable (error 500)

lookatthosemoose’s picture

#23 works for Entity Registration module to clone fields. Does not clone field groups, but will clone the fields themselves.

Thank you!

simonbcfa’s picture

Drupal 7.43
Entity 7.x-1.7

#23 error - no clone
#35 cloned form with no fields

ericdee’s picture

Any of the above patches include what seems like a major bug that can in edge cases cause the nasty fatal error:

Fatal error: Unsupported operand types in field.info.class.inc on line 495

This fatal error is due to corruption of the field_config table and to fix it, the overwritten fields need to be restored from a working version.

By nature, cloning an entity should only create new field config instances. In my understanding it shouldn't create new fields (in field_config), nor should it update fields in field_config.

In the entity.module file is the patched code:

// Make sure entity is cloning this have field.
  if (!empty($entity->_field_instances)) {
    foreach ($entity->_field_instances as $field_instance) {
      $field_instance['bundle'] = $entity->{$entity_info['entity keys']['name']};
      $field = field_create_instance($field_instance);
      field_update_field($field);
    }
  }

The call to field_create_instance will create AND SAVE a the new field instance and will return a field instance, NOT a field. The call to field_update_field in this case updates the field_config but its argument in this case is a field config instance.

Depending on the id and field_id values of your field_config and field_config_instance tables, field_update_field in these patches can end up creating a duplicate field in the field_config table and causing the fatal error

The new instance code should be something like:

// Make sure entity is cloning this have field.
  if (!empty($entity->_field_instances)) {
    foreach ($entity->_field_instances as $field_instance) {
      $field_instance['bundle'] = $entity->{$entity_info['entity keys']['name']};
      field_create_instance($field_instance);
    }
  }

Will post an updated patch shortly

@darkodev @MaxBSU

ericdee’s picture

This patch just corrects the field_update_field part of patch #42 against 7.x-1.x (7.x-1.8)

xaa’s picture

patch #23 is working here. thank you
the others seem not working (#35, #42, #62)

I am a bit lost on this issue. Is #23 still the most effective patch ?

firfin’s picture

I read the entire thread thoroughly and I believe @ericdee nailed the ONLY problem people had with patch from #23. It made my similar errors disappear at least. Counting those I think we have almost 20 confirmed bug-kills. Please re-confirm if you can, though I am quite convinced this can go straight to testing. It's been almost 5 years now. But let's follow procedure ;-)

Updated ericdee's patch from #62 because of @fago's comments #33 and #57. I just improved the comments a bit. Patch is for dev version of course.

@darkodev @MaxBSU Did #62 or does my patch here work for you?

@xaa: what isn't working for you with #62? Works fine for me. Using it with entityform and quite diverse fields (IBAN, dynamic addressfield form with postal code lookup, hidden, markup, dynamic selects, etc)

@simonbcfa: what error did you get? Same as #30 and #56 ? Please try this one.

rivimey’s picture

Some review thoughts:

  1. +++ b/entity.module
    @@ -1572,3 +1572,27 @@ function entity_ctools_plugin_directory($module, $plugin) {
    +    $entity->_field_instances = field_info_instances($entity_info['bundle of'], $entity->cloned_from);
    

    Not very keen on an underscore prefix here... is this DCS?

    Would it be appropriate to reference the workaround, as in line 676?

    Would prefer the line was not so long, but willing to ignore if alternative worse.

  2. +++ b/includes/entity.ui.inc
    @@ -662,6 +662,20 @@ function entity_ui_clone_entity($entity_type, $entity) {
    +      // Set field_instances info for entity. ¶
    

    Space at EOL will fail commit.

  3. +++ b/includes/entity.ui.inc
    @@ -662,6 +662,20 @@ function entity_ui_clone_entity($entity_type, $entity) {
    +      // This is a unexplained workaround see issue #151382
    

    This is *an* unexplained

    However, 1-line summary of said workaround would be good as well.

rivimey’s picture

Status: Needs review » Needs work

Wondering if changing name "_field_instances" to "clone_instances" would be appropriate?

firfin’s picture

about #65 : 1 and #66 DCS doesn't say anything about it, at least as far as I can find. But I found this http://drupal.org/node/70335 saying _ is meant to indicate (but doesn't enforce) a private function or variable. Then again maybe we don't want this anyway, as discussed in http://drupal.org/node/866102 ?
I think other modules or functions might want to do something with this. So I agree, and dropped the _field_instances for clone_instances.

Also fixed the typo and whitespace error. All changes in attached patch.

BTW this is also needed for and partially fixes #1816402: Ability to clone Entityforms (entire form with all fields) . Added as related issue.

RdeBoer’s picture

Which parts of the entity are cloned?

How are field collections handled (deep copy, shallow copy)

Does the patch include the cloning of Display Suite settings, like https://www.drupal.org/node/1816402#comment-11662679 does?

rivimey’s picture

Happy with the changes, thanks!

firfin’s picture

@rdeboer well, this issue is about fields. So those get cloned. I tested it with entityform, there the field dependencies (visibility settings etc) did not get cloned. Don't know about display suite settings, try the patch? Field collection seem to copy fine for me though.

I would suggest continuing in #1816402: Ability to clone Entityforms (entire form with all fields) AFTER this issue gets fixed. As tedbow (maintainer of entityform) suggested. So this should be the first step, no?
Afterwards we can work on entityform for the cloning of dependencies, display suite settings etc.

(off topic but maybe bundle_copy_ds can help you out?)

firfin’s picture

Thanks Rivimey, is that also a way of saying it works for you?
How many more OK do we need to go to RTBC ?
Like I said in #64 we have around 20 "problem solved"s with this patch .. Not proper for me to put it on RTBC though.

joelpittet’s picture

Status: Needs review » Reviewed & tested by the community

I liked the underscore before, sorry @rivimey, but wondered if that name may conflict with something actually on the entity, not likely but a bit of paranoia.

Anyways I've used this patch and it's worked great so RTBC

rivimey’s picture

@firfin - As I didn't apply and test the patch, no I cannot say 'it works for me'; I was saying the changes you made looked fine and the patch as a whole seems reasonable. Do you know if there are automated tests covering this? If so it would be easier to accept...

@joel a good point about underscore. My understanding is that clashes are normally avoided by making the names specific to the code that wishes to use them. Consequently, although I am happy with the existing name, perhaps "entity_cloned_instances" would be less likely to cause issues?

I have just had another look at the "unexplained workaround" comment. Referring to the issue is fair enough, but I am still very unsure what the workarund is for. The line of code has been there since #23 although the comments have changed since then.

Finally, Is there an opportunity to remove the new cloned instances field (whatever it's called) once the clone has been compketed? It would seem good to "clean up after ourselves, if for no other reason than the newly cloned entity could itself later be cloned...

fago’s picture

Status: Reviewed & tested by the community » Needs work
+ if (!empty($entity->clone_instances)) {
+ foreach ($entity->clone_instances as $field_instance) {
+ $field_instance['bundle'] = $entity->{$entity_info['entity keys']['name']};

This hard-codes the name as bundle, but this might be wrong. We need to use the bundle-key here.

joelpittet’s picture

Status: Needs work » Reviewed & tested by the community

@fago it looks like for field instance bundle is the correct key. @see https://api.drupal.org/api/drupal/modules%21field%21field.module/group/f...

Do you know of a case where this is not correct?

sp3boy’s picture

It is my recent experience on a live site that if you are still running patch #23 and the values of the id column in field_config_instance start overlapping the values of the id column in field_config, you will get corruption of field_config rows.

The site in my case had been using patch #23 for something like 3 years with no apparent problem but twice in the last three weeks it crashed completely first with one, then with eight corrupted rows in field_config.

I could reproduce the corruption at will on a copy of the live site - with #67 in place it does not happen.

PhilippVerpoort’s picture

#67 fixed the problem with cloning fields that I had in the entity registration module. Thanks!

rivimey’s picture

Bump... can we get this committed? It seems to me we have consensus this is a good fix.

drupgirl’s picture

+1 to get this committed.

LeDucDuBleuet’s picture

Status: Reviewed & tested by the community » Patch (to be ported)

#67 fixed the problem with cloning fields that I had in the entity registration module as well. Thanks!

Could we have this committed please?

joelpittet’s picture

Status: Patch (to be ported) » Reviewed & tested by the community

Leaving it RTBC to help it get committed. Patch to be ported is for already committed patches that need to go on other branches.

gottaknow’s picture

On drupal: 7.59 PHP: 7.1.17 Registration: 7x.1-6 Entity API 7x.1.9 with #67 patch installed.
Clone module works fine, but when you go into Manage Registration ‘Settings’ none of the settings from the previous node are being cloned.
Form fields from the function registration_entity_settings from the registration module. Fields such as capacity, form Address, Confirmation message, wait list message
The defaults are set. Is this the intention to leave these as defaults or should the clone with the Entity patch meant to catch ALL of the fields in the clone?

firfin’s picture

@gottaknow: Old issue, but if I recall correctly this patch was for cloning fields, which is quite different from cloning 'settings'. I think you may have to open another issue for cloning settings. Unsure of whether this should go into the queue for Registration module or in this queue.

.bert’s picture

+1 for #67.

Works beautifully for cloning entity registration types. Thanks for this @firfin!

.bert’s picture

Re-roll for patch in #67 attached.