I've installed Entity Reference and Profile2. When I try to create a field that refers to a user by the "first name" field in their Profile, I select Profile as the target, and I tell it to use the First Name field to sort and all I get when I use the autocomplete is "main profile" listed for each user, but not their username, firstname, anything. I tried "profile type" as the target, and all I get is a single profile type. It looks like when I use "Profile" as the target, it searches for all users that have a "first name" but displays the name profile type, not the name of the user. Is there any way I can have the autocomplete search using the first name field?

Comments

jeisses’s picture

subscribed

I have the same problem; will I need to create a custom widget to work around this?

afriend’s picture

same problem here.

probably this could help.
http://coder1.com/articles/printing-or-rendering-node-field-or-profile2-...

But my problem is that I want to search users from entityreference (in field 1) to user entity and then I want to get user's address from profile2 address's fields (in field 2) for that user's profile2 using another entityreference.

any idea?

joachim’s picture

If you're on the latest version of EntRef, can't you set up which properties or fields of the target entities are used for autocomplete?

> will I need to create a custom widget to work around this?

If I'm wrong about the above, a custom select plugin for EntRef would be better.

shendric’s picture

Hey all,

I ended up spending a little time creating a custom select plugin that allows me to search by first and last name and display the full name in the autocomplete. It works, just took a little time to work through the process of creating the plugin.

mansspams’s picture

@shendric would you mind sharing code?

afriend’s picture

you need to use latest entiref module. Then you will get "Views: Filter by an entity reference view" in the field config page. just create desired view containing field that you want to searched in rendered entity.
I hope it helps.

Ashish

amphioxus’s picture

Same problem here.

@afriend: I tried setting up a entity reference view, and it almost worked. The entref view collects the first and last name fields of my users. When I then create the entity reference field in my new content type and choose "select list" as my widget type, it shows the list of users by first and last name, just as I wanted. But when I actually create content of that content type, and select a bunch of users, it only displays "main profile", instead of "Firstname Lastname" for each one. When displayed, the fields link to the correct user profiles, it's just that I can't figure out how to make it output the actual names, and not "main profile" for everyone.

The other problem is that I never got autocomplete to work, despite the names nicely showing up in the "select list" widget. I'm not sure how to fix it, except somehow modify my page.tpl.php to tease out the names from the $content array. All the information is in there, but I don't yet know how to get at the appropriate fields in that array. Or is there a better way of doing this?

Thanks, Armin

afriend’s picture

for displaying desired field from referenced entity you need to use formatter in "Manage Display" setting.

shendric’s picture

I don't mind at all. As soon as I get back to my desk, I'll post the high points.

amphioxus’s picture

Thanks for the advice, Ashish.

I've tried playing around with the display settings, but I'm probably missing something.

Here's what my "format" options are for displaying the referenced field (which links to my Profile2 fields): 1) Label, 2) Entity ID, 3) Rendered entity and (not too useful here) 4) Hidden.

When I choose "Label", all I get printed out is the term "Main Profile" (or whatever I named the profile2 profile) for each referenced user. It does link to the correct user page, though.

When I choose "Entity ID", I get the user ID number for each referenced user.

"Rendered entity" looks very promising, but I couldn't get it to do what I want either. Once I select "Rendered entity", it allows me to set the format settings to a bunch of options called "View modes". Here's the view mode options I have available:

a) "User account": if selected, it prints out all fields of the users' profile page, including a title for each. I couldn't figure out how to limit the fields here. Ideally, I would want to create my own view mode with just "First name" and "Last name" as the fields displayed.

b) "Profile page": I actually don't see a difference to the outcome in a)

And then there are additional options:
c) "Teaser"

d) "Tokens" ... sounds useful, but again I couldn't figure out how to display the fields i want.

e) iCal

So maybe I'm missing how to create my own "View mode" to limit the fields being displayed? I don't want to show the whole profile page for each referenced user, but only their first and last name fields, which I implemented with the profile2 module.

Any help would be very much appreciated. Thanks,
- Armin

amphioxus’s picture

@shendric: Many thanks for offering to share. I'd be very interested in how you implemented this as well. (But hopefully, the entity reference view approach I've tried will work for my problem ;-)

afriend’s picture

Hi Armin,
I got success with "Rendered Entity" then in View mode "Tokens" Option.

But for this to work you need to create views view of the fields using 2 entities 1) of the field you want to search 2) of the field you want to take field data from. Then in in the "Field Settings" mode under "Entity selection mode" select option "Views: Filter by an entity reference view " and select your views view. It will fetch the fields in view mode of the entity.

amphioxus’s picture

Hmm, I thought that's what I've been doing... I created a view (entity reference view) with the fields "last name" and "first name" from profile2, and the "user profile" field from user (the latter I hide from views display). And I selected the option to filter by this entity reference view.

When creating a new node of the content type that has the referenced field, I can see the list of users I want to link to in the dropdown list. But when I use "Tokens" in the "rendered entity" option, I can't figure out how to actually use tokens. (I thought tokens would allow me to just print specified fields, like [user], or [profile:first_name] or whatever...) It always just displays the whole user profile page for each chosen user. There doesn't seem to be any room for entering the tokens. This might just be a basic oversight on my behalf, or something I'm doing with the entity view is wrong.

amphioxus’s picture

I played around a bit by inserting tokens into the page.tpl.php for my content type, but it turned out to be annoying to get the tokens to be printed.

I found an easier solution for my particular problem, which was to install the RealName module. It allowed me to specify which tokens to use to replace the label referring to a user name. So by just using the view mode "Label", it now renders "Firstname Lastname" of the associated user profile. That's all I really needed...

I never really got the autocomplete to work (even when selecting the last name as the search field in the entref view) and have to stick to the dropdown widget. It works, but it's a bit annoying to select multiple users from a list of about 150... for now I'm going to stick with it I guess...

Thanks for your help,
Armin

jeisses’s picture

Some good suggestions, but I don't think I can use the views method, as I have about 2000 entities to be selected (the warning says there can be out of memory errors with more then 100 entities). I also need anautocomplete widget.

@shendric: I would appreciate if you could share the source of your widget, as I'm not sure how to make one myself

Thanks for helping

shendric’s picture

Hey,

Sorry it took so long. Here's what I have. Of course, I just found out that it doesn't seem to work properly, as not all of my users end up being listed, unless I'm logged in as administrator. I haven't quite figured that out.

/**
 * Override for the Profile type.
 *
 * This only exists to workaround core bugs.
 */
class EntityReference_SelectionHandler_Profile_profile2 extends EntityReference_SelectionHandler_Profile {
  
  private $query_match;
  private $query_operator;
  
  public function buildEntityFieldQuery($match = NULL, $match_operator = 'CONTAINS',$match_field='first_name') {
    $this->query_match = $match;
    $this->query_operator = $match_operator;
    $query = parent::buildEntityFieldQuery($match, $match_operator);

    if ($match_field=='first_name') {
      $query->fieldCondition('field_first_name','value',$match,$match_operator);
    } else {
      $query->fieldCondition('field_last_name','value',$match,$match_operator);
    }
    return $query;
  }
  
  public function entityFieldQueryAlter(SelectQueryInterface $query) {
    
   
    $conditions = &$query->conditions();
    foreach ($conditions as $key => $condition) {
      if ($condition['field'] == 'profile.label') {
          // Remove the condition.
          unset($conditions[$key]);
      }
    
    }
   
  }
}

I also had to adjust the getReferenceableEntities function in order to have it search across either first name or last name:


/**
   * Implements EntityReferenceHandler::getReferencableEntities().
   */
  public function getReferencableEntities($match = NULL, $match_operator = 'CONTAINS', $limit = 0) {
    $options = array();
    $entity_type = $this->field['settings']['target_type'];

    $query = $this->buildEntityFieldQuery($match, $match_operator,'first_name');
    if ($limit > 0) {
      $query->range(0, $limit);
    }

    $results = $query->execute();
    $query2 = $this->buildEntityFieldQuery($match, $match_operator,'last_name');
    if ($limit > 0) {
      $query2->range(0, $limit);
    }

    $results2 = $query2->execute();
    $result_ids1=array();
    $result_ids2=array();
    
    if (!empty($results[$entity_type])) {
      $result_ids1 = array_keys($results[$entity_type]); 
    }
    
    if (!empty($results2[$entity_type])) {
      $result_ids2 = array_keys($results2[$entity_type]); 
    }
    
    $result_ids = array_unique(array_merge($result_ids1, $result_ids2));
   

    if (!empty($result_ids)) {
      $entities = entity_load($entity_type, $result_ids);
      foreach ($entities as $entity_id => $entity) {
        $options[$entity_id] = $this->getLabel($entity);
      }
    }

    return $options;
  }

I have no idea if this is the right way or the wrong way to do this, but it's the best way I could figure out to do it. Now, if I can figure out why users that are also site administrators can't be looked up this way. *sigh*

pwaterz’s picture

@shendric can you make a patch out of that?

shendric’s picture

It's not really a patch for anything, it's a plugin to EntityReference. You have to create a new handler and register it as a plugin to EntityReference using ctools. If that sounds vague, it's because I'm still vague on the way it works, myself. The documentation on creating these things is a little hard to come by, so I ended up just hacking it out over a few days, and because I'm not sure how it works, I'm not sure how to fix the problem with some users in the system just seemingly randomly not showing up unless I'm an administrator. Very frustrating.

pwaterz’s picture

ahh, I understand. A patch still helps other people work on it. Just say the patch isnt finished yet.

shendric’s picture

Actually, that's not the way I understand patches. A patch is to make a change to a module (core or otherwise) to keep it working until it's committed to the next version. This will never be a patch, because it's an extension to a module; it doesn't replace any of the actual entityreference code.

pwaterz’s picture

I beg to differ. That is a perfect reason to create a patch. A patch doesn't have to 'replace' code. It can also add new code as well. You could create a patch that is an entire module. The patch just makes it easier for other to work with. If I wanted to apply the code above I would have to manually add all of that code. A patch would put it in it's proper place and also allow me to easily add to it and create a subsequent patch from it that contains your addition and mine.

shendric’s picture

I also have this code that I use to transform the "Main Profile" to the first name and last name fields of that profile:


/**
* Implements hook_help()
*/

function profile_label_help($path, $arg) {
  if ($path == 'admin/help#first') {
    return t('Changes the profile entity label to the full name of the user');
  }
}

/**
* Implements hook_entity_info_alter().
*/
function profile_label_entity_info_alter(&$entity_info) {
	
	$entity_info['profile2']['label callback']='_profile_label_label_callback_set';
}

function _profile_label_label_callback_set($entity,$entity_type) {

	if ($entity_type == 'profile2') {
		$output_first_name = field_get_items('profile2',$entity,'field_first_name');
		$output_value_first_name = field_view_value('profile2',$entity,'field_first_name',$output_first_name[0]);
		$label_first_name = drupal_render($output_value_first_name);
		$output_last_name = field_get_items('profile2',$entity,'field_last_name');
		$output_value_last_name = field_view_value('profile2',$entity,'field_last_name',$output_last_name[0]);
		$label_last_name = drupal_render($output_value_last_name);
		$label = t("@label_first_name @label_last_name", array ('@label_first_name'=>$label_first_name, '@label_last_name' => $label_last_name));
		return decode_entities($label);
	}
}
shendric’s picture

Fair enough. I would just consider that another module, not a patch, but I see no reason to argue semantics, since I don't know how to create a patch, anyway.

pwaterz’s picture

@shedric, it's not that hard http://drupal.org/node/707484

tdimg’s picture

Project: Profile 2 » Entity reference
Version: 7.x-1.2 » 7.x-1.x-dev
Category: support » bug
Priority: Normal » Critical

I have the exact same problem as originally posed:

- Profile2 7-1.2 installed
- EntityReference latest dev

- no Views - thought worth mentioning as this has been mentioned as a work around in this issue queue.

I have two Profile types, the main profile obviously and a second staff profile that only staff roles can complete.

Doesn't matter which selector I'm using, the Profile reference always only tries to match the Profile type (select list/checkboxes only display the profile type), and yes, I'm not using Profile Type as a target type.

Also, I'm using Display Suite to create and then display the referenced entity using custom view modes, but whatever I've got there, all it displays on the node is the name of the profile type.

For lack of movement in this issue queue and its apparent relation with Entity Reference, I've changed the association of it.

joachim’s picture

Category: bug » feature
Priority: Critical » Major

> When I try to create a field that refers to a user by the "first name" field in their Profile, I select Profile as the target, and I tell it to use the First Name field to sort and all I get when I use the autocomplete is "main profile" listed for each user, but not their username, firstname, anything.

That's normal.

EntRef shows you the 'title' of an entity.
Profile2 doesn't really have a concept of a title, so just returns the type of a profile when the entity API asks for its title. Hence you get 'main profile' over and over again.

> I tried "profile type" as the target, and all I get is a single profile type.

Also normal.

'Profile type' is also an entity. There's one entity for each type. This isn't the thing you want.

> It looks like when I use "Profile" as the target, it searches for all users that have a "first name" but displays the name profile type, not the name of the user.

Also normal...

If you set it up like this, you're now pointing to profiles, not users.

> Is there any way I can have the autocomplete search using the first name field?

You're probably going to need a behaviour plugin for EntRef that is specifically geared to working with Profile2.

tdimg’s picture

> You're probably going to need a behaviour plugin for EntRef that is specifically geared to working with Profile2.

Thanks joachim for making this clear.

So it seems shendrik provided in #16 and #22 some code for a behaviour plugin, though as pwaterz points out, it would be a lot better if he'd provide this as a patch file.

Now my PHP and Drupal knowledge are still somewhat limited and I can only get so far, some actual documentation on how to write such behaviour plugins would be really nice, the example shipped with the module isn't really that helpful either.

siretfeL’s picture

Status: Active » Needs review

...having the same problem as described here, I managed to get the right result (selecting at manage display: label with link to entity ref) by following another (related but original targeting an auto-complete issue) solution patch from here: http://drupal.org/node/1896210. Hope that helps, although I must say it needs review.

marcoscano’s picture

Issue summary: View changes
Status: Needs review » Active

Once there is no patch in this issue it cannot be in "needs review" :)

I can confirm there is a workaround which is to create an entityreference views display to populate the autocomplete, and then apply the patch in #1896210: When filtering autocomplete by a view #default_value always be the entity title instead of the custom view result (e.g. a field on the entity) to have the widget to show the labels correctly

Chasen’s picture

Confirmed that the patch mentioned in #29 correctly updates the display on the EDIT page for the node in question from "Main Profile" to whatever the actual referenced entity was, such as "First name" (so "Ben Smith" shows up rather than "Main Profile")

The display of the field on a standard published view page for a node functionality already exists, you just need to edit the Manage Display section for that particular content type. Format = Label works perfectly for me.

Shiraz Dindar’s picture

Confirming that #29 works on the edit form, but does not do anything for the node view. Unlike Chase, setting the display format to Label didn't resolve the node view for me. Expecting to have to write a small custom field formatter for this.

bermin’s picture

i agree with Shiraz. Edit form is working just fine with latest ver of module, but at the node level the displayed result is switched to username which is not what was selected using autocomplete and a custom view at the Edit page.