l create a content type which has a field of entity_reference, called field_user, the widgets type is autocomplete, target type is user,and I create a views display attached, and set it as required.

when I input existed user's keyword, field_user can search out user and node save is OK.

But when input user's keyword which no user has such keyword, the views behind entity_reference attached have no result return,this is fine,but the wrong keyword which I input in autocomplete widgtes text is still there. as field_user is not empty(staticsfied with required) so when I submit the node it' created suceefully even didn't check the field_user is valid or not.

after the node saved, I found that there is no field_user value show,it's still empty.

why entity_reference didn't clean up input of autocomplete when there is no result return and raise an error when submited?

Files: 

Comments

Ananya MultiTech’s picture

r u serious this is happening with you?? I tried creating this situation but i never found such error..
IF the entity is not found then it will not create that Node..

castelar’s picture

Same issue here. My required reference field validates when a title is typed in autocomplete, but not selected from dropdown adding the nid.

For example, manually typing in "netflix" validates, even though field should be "Netflix (X)"

End result - the form submits, and the reference field is empty even when required.

rooby’s picture

Title: save node even input is not valid in autocomplete » Saving allowed even when input is not valid in autocomplete results

I can confirm this bug.

I can create a node that has 'asdfasdfgqerbge' for the value of the entityreference field and it still saves.
I can assure you that entity does not exist.

swati.karande’s picture

Hi,
I am not able to replicate this issue. Can you please give me some more inputs like related module version and drupal version which you used so that we can replicate?

Thanks.

rooby’s picture

I just tried on a different site and it works as expected.

I'll check again on the problem site tomorrow and see what's going on.

pacproduct’s picture

I'm facing the same issue here (Checked with both versions 7.x-1.0 and 7.x-1.x-dev).

As stated above, the problem arises when the entityreference field is used with the "Views: Filter by an entity reference view" mode.
In my case, I'm referencing nodes.

During my tests, the code that seems to cause the validation to be ineffective is this function (in EntityReference_SelectionHandler_Views.class.php):

  public function validateAutocompleteInput($input, &$element, &$form_state, $form) {
    return NULL;
  }

Seems like this is directly related to #1819618: Incorrect autocomplete validation with views selection mode claiming that this bug has already been fixed fore the "simple" mode here: #1389238: Autocomplete widget improvements. The view mode might need a similar fix as well.

pacproduct’s picture

FileSize
1.49 KB
FAILED: [[SimpleTest]]: [MySQL] Unable to apply patch entityreference_1702172-7_views_autocomplete_validation.patch. Unable to apply patch. See the log in the details link for more information. View

I'm wondering if the same code that was added to the EntityReference_SelectionHandler_Classic.class.php file to fix the "simple" mode wouldn't fit our needs?

I've tried to copy-paste it from EntityReference_SelectionHandler_Classic.class.php to EntityReference_SelectionHandler_Views.class.php, and it's working well in my case. Here is what my EntityReference_SelectionHandler_Views->validateAutocompleteInput() function looks like now:

  /**
   * Implements EntityReferenceHandler::validateAutocompleteInput().
   */
  public function validateAutocompleteInput($input, &$element, &$form_state, $form) {
      $entities = $this->getReferencableEntities($input, '=', 6);
      if (empty($entities)) {
        // Error if there are no entities available for a required field.
        form_error($element, t('There are no entities matching "%value"', array('%value' => $input)));
      }
      elseif (count($entities) > 5) {
        // Error if there are more than 5 matching entities.
        form_error($element, t('Many entities are called %value. Specify the one you want by appending the id in parentheses, like "@value (@id)"', array(
          '%value' => $input,
          '@value' => $input,
          '@id' => key($entities),
        )));
      }
      elseif (count($entities) > 1) {
        // More helpful error if there are only a few matching entities.
        $multiples = array();
        foreach ($entities as $id => $name) {
          $multiples[] = $name . ' (' . $id . ')';
        }
        form_error($element, t('Multiple entities match this reference; "%multiple"', array('%multiple' => implode('", "', $multiples))));
      }
      else {
        // Take the one and only matching entity.
        return key($entities);
      }
  }

What do you think?
(the attached patch just adds the content of the function, as shown above)

pacproduct’s picture

Status: Active » Needs work
FileSize
1.73 KB
PASSED: [[SimpleTest]]: [MySQL] 119 pass(es). View

Patch revamped to match the expected format.

pacproduct’s picture

FileSize
2.45 KB
PASSED: [[SimpleTest]]: [MySQL] 119 pass(es). View

Actually using the code from the Generic class could not work properly as the View method adds an additional level in the returning array: The bundle type. I've run some additional tests and corrected the patch to take this into account.

castelar’s picture

The patch in #9 didn't work for me. Saving is still allowed.

pacproduct’s picture

I've just tested the following:
I've installed a Drupal 7.19 (standard install) with:
- Entityreference 7.x-1.0+4-dev
- Views & Views UI

I've create 2 basic pages "Basic page 1" and "Basic page 2" to have some initial nodes.

Then I've created an Entityreference view listing my nodes.
I've added an Entityreference field to the Basic page content type:
- using the "Autocomplete" widget
- using the view I've created
- required

When I tried to edit one of my basic pages, here is what happened:
- When I filled the entityreference field with "aetiouoiu", the node was updated, but the entityreference field was left blank.
- When I filled the entityreference field with "Basic", the node was updated, but the entityreference field was left blank.
- When I filled the entityreference field with "Basic page 1", the node was updated, but the entityreference field was left blank.
- When I filled the entityreference field with "Basic page 1 (1)", the node was updated, and the entityreference field was correctly saved.

Then, I've applied my patch #9 to entityreference.

When I tried to edit one of my basic pages, here is what happened:
- When I filled the entityreference field with "aetiouoiu", the node couldn't be saved because the text entered did not match any entity.
- When I filled the entityreference field with "Basic", the node couldn't be saved because the text entered matched several entities. Note: There is a cosmetic issue in this case: The html returned by the view is displayed in the error message.
- When I filled the entityreference field with "Basic page 1", the node was updated, and the entityreference field was correctly saved, referencing my node 1.
- When I filled the entityreference field with "Basic page 1 (1)", the node was updated, and the entityreference field was correctly saved, referencing my node 1.

@castelar, what is different between my tests and yours?

castelar’s picture

Just tried again, and it works. Even works when the letter case does not match. Thanks!

pacproduct’s picture

FileSize
2.46 KB
PASSED: [[SimpleTest]]: [MySQL] 119 pass(es). View

Patch reviewed to fix the cosmetic issue I was talking about in #11.

Dean Reilly’s picture

Status: Needs work » Needs review

Marking as needs review for the test bot.

+++ b/plugins/selection/EntityReference_SelectionHandler_Views.class.php
@@ -147,7 +147,48 @@ class EntityReference_SelectionHandler_Views implements EntityReference_Selectio
+      $entities = $entities[key($entities)];

Use $entities = current($entities); instead.

pacproduct’s picture

FileSize
2.45 KB
PASSED: [[SimpleTest]]: [MySQL] 121 pass(es). View

Patch re-rolled with Dean's improvement.

japanitrat’s picture

Bug exists also for node-filters (not views). Tested with Entity Reference 7.x-1.0 on a Drupal 7.23

dahousecat’s picture

I've applied patch #15 but the bug still exists.

I have a taxonomy with a field collection field containing an entity reference to a user using the "Views: Filter by an entity reference view" mode.

Could the field collection layer be contributing to the problem?

snaisel’s picture

Issue summary: View changes

I've try the patch, and works so fine, but when you filled with a "0", saves the node with no reference. I tried to fix it, even with rules, with no results

attiks’s picture

Status: Needs review » Reviewed & tested by the community

Patch works, thanks all

PS: I think field collection can best be handled in a separate issue

MustangGB’s picture

Status: Reviewed & tested by the community » Needs review
Related issues: +#1959624: Autocomplete widgets not referencing the single entity result
FileSize
1.83 KB
PASSED: [[SimpleTest]]: [MySQL] 121 pass(es). View

This is actually a bug in EntityReference-SelectionHandler-Generic.class.php as well, which is being fixed over at #1959624: Autocomplete widgets not referencing the single entity result.

So here is a re-roll using the new generic method.

nithinkolekar’s picture

Same issue with entityform having entityreference field, referring to node.
Patch worked but in error message span entities are displaying instead of rendered message(drupal default Bartik theme).

Multiple entities match this reference; " <span class="views-field views-field-title"> <span class="field-content">Emma Roberts</span> </span> (11137)", " <span class="views-field views-field-title"> <span class="field-content">Michael Fassbender</span> </span> (11136)"

rvb’s picture

Patch #20 worked for me! Thanks Pacproduct.

pacproduct’s picture

Well to be fair, patch #20 was created by akamustang.

crutch’s picture

This seems the same issue: https://www.drupal.org/node/2317149

Somehow the node number should not be present because it is not friendly for a site visitor submitting forms. It's okay for site maintainers because we can instruct why the node number is there. A site visitor we are unable to instruct them not to backspace/delete the node number.

ashedryden’s picture

#20 fixed my issue, applied to Entity Reference 7.x-1.1.

Alla Tyurina’s picture

#20 fixed my issue, applied to Entity Reference 7.x-1.1.

Yes, the same. Thanks for patch.

Tessa Bakker’s picture

Status: Needs review » Needs work

Patch needs work when using a more complex entity reference view, see also comment #21 new patch will follow.

Tessa Bakker’s picture

FileSize
2.19 KB
1.95 KB
PASSED: [[SimpleTest]]: [MySQL] 121 pass(es). View

New patch with interdiff.

This patch will work nicely with #980144: Issues with "required, multiple" fields in forms

Tessa Bakker’s picture

Status: Needs work » Needs review
Tessa Bakker’s picture

FileSize
1.95 KB
PASSED: [[SimpleTest]]: [MySQL] 121 pass(es). View

Missed the double quote in 'Multiple entities match %label": !multiple'.

Tessa Bakker’s picture

FileSize
1.94 KB
PASSED: [[SimpleTest]]: [MySQL] 121 pass(es). View

New patch:
* Better form errors (less tech talk)
* Better filtering of user/database input, where needed

SpadXIII’s picture

Status: Needs review » Reviewed & tested by the community

Looks good and works fine. Minor error-messages- and filtering-fixes were already done.

DamienMcKenna’s picture

RunePhilosof’s picture

Marked #1819618: Incorrect autocomplete validation with views selection mode as duplicate of this issue.

#1819618 also has some better error messages, that could be added to this issue:
https://www.drupal.org/files/issues/interdiff-1819618-7-9.txt
Added in #1819618-9: Incorrect autocomplete validation with views selection mode by dooug.

Anybody’s picture

The patch from #31 is working very good and fixes a truely major issue. It just cost me hours to find out this reason and fix for our problems.

Please please add it to the latest .dev release and create a new stable release as soon as possible.
This is already a very old issue.

Thank you so much! =)

jamesrward’s picture

We've been running with #31 for over a year with no issues to report. Any chance of a merge and stable release?

MorinLuc0’s picture

Status: Reviewed & tested by the community » Needs work

Great patch if we can get some test written for this we can commit it to the dev branch.

wipeout_dude’s picture

On initial testing of the patch in #31 it's very elegant and works well.. Would be good to get it into the main release.. Will save us a LOT of hassle and extra admin finding out whet the person meant when the node is saved blank..

FiNeX’s picture

The patch #31 works perfectly. Thank!

MustangGB’s picture

Anyone fancy having a crack at the tests?

This was always my fear with this module takeover that every issue would just end up as "Needs tests".

:'(

hgoto’s picture

Nice patch!

I feel like having a crack at the tests. Even the generic selection handler had no test and I'm trying to add the tests for the following scenarios.

  • Validation checks for autocomplete with EntityReference_SelectionHandler_Generic.
    • No validation error occurs for an existing title.
    • A validation error occurs for an invalid title.
    • A validation error occurs for a title shared by many entities.
    • A validation error occurs for a title shared by several entities.
  • Validation checks for autocomplete with EntityReference_SelectionHandler_Views.
  • No validation error occurs for an existing title.
  • A validation error occurs for an invalid title.
  • A validation error occurs for a title shared by many entities.
  • A validation error occurs for a title shared by several entities.
hgoto’s picture

Status: Needs work » Needs review

The last submitted patch, 41: entity_reference-saving_allowed_even-1702172-41.patch, failed testing.

Status: Needs review » Needs work
hgoto’s picture

I fixed the wrong file doc and some points in the patch #41 following the coding standard check.

The following issue may need to be resolved before we use the autotest properly. The autotest failed but it succeeded in my environment. I'd like someone to run tests locally to investigate.

#2857322: Functions of Token module is used without checking Token module status

The change between patch #41 and this patch is small and I created a interdiff with #31 again.

The last submitted patch, 45: entityreference-saving_allowed_even-1702172-43.patch, failed testing.

Status: Needs review » Needs work
hgoto’s picture

I adjusted some small points in the patch #43.

Tests in the patch pass in my environment and fail on drupal.org CI system... I don't understand why it fails. I'd like someone to test it in a local environment.

The last submitted patch, 48: entityreference-saving_allowed_even-1702172-48.patch, failed testing.

hgoto’s picture

The test only patch #48 lacks the addition of files[] in .info file. Here's a correct one.

+files[] = tests/entityreference.form.test

Status: Needs review » Needs work
MustangGB’s picture

Hmm, patch+tests passes fine for me too, and tests only fails as expected, not sure why the testbot is failing.

MustangGB’s picture

So I tried on a different install and was able to reproduce the testbot errors.

After some hunting I found that _entityreference_autocomplete_validate() calls entityreference_get_selection_handler() which returns EntityReference_SelectionHandler_Broken.

This seems to be because the EntityReference_SelectionHandler_Views plugin isn't being loaded.

A quick check to confirm this by commenting out the if statement in plugins/selection/views.inc (i.e. if (module_exists('views'))) to force the plugin to always be added. This seems to work and all tests now pass.

It seems that this file (plugins/selection/views.inc) is getting called before views(/ctools) is being enabled by the test.

I'm thinking the solution should be that after the test dependencies are enabled we force it to add the views plugin. I tried to do this in setUp() without much luck. Is this something you could have a go at hgoto?

hgoto’s picture

@MustangGB thanks. I see. Your insight helped me a lot!

As far as I understood, it's impossible to reload the plugin file plugins/selection/views.inc as require_once is used to load the file in ctools function. So we need to enable views module before entityreference module so that plugins/selection/views.inc is loaded only after views module is enabled.

I'd like to try a revised patch. (Of course, this works in my environment.)

Status: Needs review » Needs work
MustangGB’s picture

Status: Needs work » Reviewed & tested by the community

Perfect, very comprehensive tests, and they're passing now as well.

Kris77’s picture

Patch in #20 works for me too with Entityreference and select entity by views

joseph.olstad’s picture

Nice work on patch #54! Thanks +1

ashedryden’s picture

Issue tags: +to

This applies cleanly to 7.x-1.4, but causes 500 errors on autocomplete after each character entered.

hgoto’s picture

@ashedryden thank you for testing. Can you share the detail of the error and steps to reproduce?

Kris77’s picture

I have tried patch #54 and works with entityreference 7.x-1.1, but not return error if I select the same identity with the same ID but only with the same label.

I have a fieldcollection multiple field with a entityreference field. I select entity by autocomplete widget.

  • I create my node and select from entityreference field my entity with ID = 1.
  • Click on ADD ANOTHER ITEM, select one more time entity with ID = 1
  • Click on SAVE button and my node is created but contains two equal values.

Thanks.

hgoto’s picture

@Kris77, thank you for testing.

I don't fully understand what you want. If you want to forbit duplicate entities, you would be interested in the following issue or module rather than this issue.

#2010488: Forbid to use duplicate entities in entityreference field
Entityreference unique: https://www.drupal.org/project/entityreference_unique

hgoto’s picture

Issue tags: -to

I think the issue tag "to" is added by mistake.

Kris77’s picture

@hgoto thank you so much for your reply and suggestions. I will try to be clearer.

This my scenario:

  • Entityform type: FORM1
    • In FORM1 i have a field collection field: FC1
    • In FC1 i have a entityreferencefield with autocomplete widget: ER1

So, when i visit page to create my entityform type(FORM1)

  • I select entity in ER1 and click on field collection button "add more item",
  • Select the same entity and click on field collection button "add more item" but error not appear.
  • Click on SUBMIT button but error not appear and the form is submit with two same entities .

I've tried your solutions but none of them seems to work with field collection.

hgoto’s picture

@Kris77 thank you for the detailed explanation. I got it.

If I understand your requirement correctly, it's not very related with this issue. I believe it's better to file a new issue with "Support request" or to use Drupal Answers in order to get hints to implement that feature :)

(In my opinion, that requirement needs to be implemented with a custom code.)

BramDriesen’s picture

I'm not sure if this is related to this issue but today we found out the following.

We have a node with an entityreference field that only allows one other node type as values. When creating content in this node the dropdown is showing valid values. However it's possible to bypass the type by pasting the complete node title + id in the field.

So practical example:
Title | NID | Node type
Test 1 | 1234 | X
Test 2 | 5678 | Y

When creating a node of type Z with the node reference field set to only allow node type X. It's possible to reference to node "Test 2" of type Y by pasting the value "Test 2 (5678)" into the field.

What I think is happening is because we supplied a valid node + id it's bypassing the check for the type. Or was the "allowed types" option in the field settings never intended for validation on the save event and only for the dropdown values.

Let's say we have some creative users on our site :)

If this issue is not related I'll happily create a new issue for it.

MustangGB’s picture

@BramDriesen Are you using Mode Simple (with optional filter by bundle) or Views: Filter by an entity reference view?

BramDriesen’s picture

@MustangGB Just checked and we are using Simple (with optional filter by bundle).

MustangGB’s picture

It's not particularly clear in the summary, but this issue is for the second mode, i.e. views.

I've not attempted to replicate your issue yet, that said I would have thought it'd been sorted out by #1959624: Autocomplete widgets not referencing the single entity result, which is already included in the latest release.

Either way, probably best to open a new issue I'd say.

BramDriesen’s picture

I checked the version of the module and we are using the latest stable release.

Created a new issue: #2894475: Saving entity ignores the allowed bundles settings when a valid nid is supplied