Comments

hkirsman created an issue. See original summary.

hkirsman’s picture

If somebody wants give a try.
I think the correct place to fix this is in inline_entity_form/src/Plugin/Field/FieldWidget/InlineEntityFormBase.php - getTargetBundles()
Here's to code I have at the moment:


  /**
   * Gets the target bundles for the current field.
   *
   * @return string[]
   *   A list of bundles.
   */
  protected function getTargetBundles() {
    $settings = $this->getFieldSettings();
    if (!empty($settings['handler_settings']['target_bundles'])) {
      $target_bundles = array_values($settings['handler_settings']['target_bundles']);
      // Filter out target bundles which no longer exist.
      $existing_bundles = array_keys($this->entityTypeBundleInfo->getBundleInfo($settings['target_type']));
      $target_bundles = array_intersect($target_bundles, $existing_bundles);
    }
    elseif (!empty($settings['handler_settings']['view'])) {
      // Make sure that if using a view for the entity selection only
      // the bundles which are returned by the view are available to create.
      $view_name = $settings['handler_settings']['view']['view_name'];
      $display_id = $settings['handler_settings']['view']['display_name'];
      $view = Views::getView($view_name);

      $base_table = $view->storage->get('base_table');
      $bundle_field = '';

      $infos = \Drupal::entityManager()->getDefinitions();
      if (is_array($infos)) {
        foreach ($infos as $info) {
          if ($info->getDataTable() == $base_table) {
            $bundle_field = $info->getKeys()['bundle'];
            break;
          }
        }
      }

      if (!empty($bundle_field)) {
        $display = $view->storage->get('display');
        $i = 0;
//        $filter = $view->get_item($display_id, 'filter', $bundle_field);
//        if (is_array($filter) && isset($filter['value'])) {
//          $settings['bundles'] = $filter['value'];
//        }
//        elseif (
//          is_array($settings['handler_settings']['view']['args'])) {
//          $arguments = $view->get_items('argument');
//
//          if (is_array($arguments) && isset($arguments[$bundle_field])) {
//            $i = 0;
//            foreach (array_keys($arguments) as $argument) {
//              if ($argument == $bundle_field) {
//                if (isset($settings['handler_settings']['view']['args'][$i])) {
//                  $args = explode('+', $settings['handler_settings']['view']['args'][$i]);
//                  $settings['bundles'] = array();
//                  foreach ($args as $arg) {
//                    $settings['bundles'][$arg] = $arg;
//                  }
//                }
//                break;
//              }
//              $i++;
//            }
//          }
//        }
      }
    }
    else {
      // If no target bundles have been specified then all are available.
      $target_bundles = array_keys($this->entityTypeBundleInfo->getBundleInfo($settings['target_type']));
    }

    return $target_bundles;
  }

Got stuck at getting the filters. What was interesting is that I didn't see the filters in display that was set in the field but the filters where in the default view.

feyp’s picture

Category: Bug report » Feature request
Status: Active » Needs review
Related issues: +#1872316: Can't select a default bundle when using entity reference views
StatusFileSize
new3.58 KB

Hi hkirsman,

great start, attached is a forward port of my D7 patch against the latest 8.x-1.x-dev version. Tested with bundle filter and bundle argument (contextual filter) in a view showing taxonomy terms on Drupal 8.1.1.

hkirsman’s picture

Nice1, FeyP!
Also tested in 8.1.1 and works! I have 3 content types in total and my view is filtering only one of them. That 1 view was properly selected in the using "Add new node" button on the form.

dawehner’s picture

+++ b/src/Plugin/Field/FieldWidget/InlineEntityFormBase.php
@@ -152,14 +152,64 @@ abstract class InlineEntityFormBase extends WidgetBase implements ContainerFacto
     }
-    else {
-      // If no target bundles have been specified then all are available.
+    elseif ($settings['handler'] == 'views' && !empty($settings['handler_settings']['view'])) {
+      // If an entity reference view is used, try to extract the target bundles

I'm wondering whether we should make that rather a configuration of the field widget instead of trying to apply some magic and extract if from views. This feels really a lot of potential fragile code. Maybe less magic is actually what the people want.

smaz’s picture

StatusFileSize
new3.58 KB

I've made a tiny tweak, as this wasn't working for me - $config_entity_type->getDataTable() was returning null, so I've swapped that to ->getBaseTable() as you're looking for the base table anyway.

@dawehner, I agree that that's potentially fragile but if we select the bundles on the field, there's then a chance the view could surface different entities that couldn't be used.

I guess maybe a setting for 'Limit bundles based on the view's filters' or something would be a better option?

Interdiff:

Line 32

+          if ($config_entity_type->getDataTable() == $base_table) {

Is now:

+          if ($config_entity_type->getBaseTable() == $base_table) {
jdleonard’s picture

StatusFileSize
new3.83 KB

I also encountered this issue. #3 works for me, but #6 does not because my view's base table is "node_field_data" (the node entity type's data table). So, it sounds like we need to check that at least one of the entity type's base table and data table match the view's base table. I don't know enough to know whether this is a valid assumption and whether this handles all possible scenarios.

Revised patch attached. Other changes it contains:

  • Removes an unnecessary if statement
  • Adds a use statement to make \Drupal\views\Views::getView($view_name); more readable
  • Removes an unnecessary use of the Drupal static service container wrapper (entityTypeManager is accessible via $this)
dww’s picture

In #5 @dawehner wrote:

I'm wondering whether we should make that rather a configuration of the field widget instead of trying to apply some magic and extract if from views. This feels really a lot of potential fragile code. Maybe less magic is actually what the people want.

I totally agree. While #7 is working nicely (at least for a view filter), wearing my site builder hat I thought it was weird that the bundle selector was tied to the reference type in the way it is. It seemed strange for those options to disappear when editing the entity reference field instance settings by selecting I wanted to use a view to define the entities to reference. It makes sense as someone who helped maintain views and contributed to core, but I don't think it makes sense to the rest of the world. If the settings are going to disappear like that, then we need the magic in this patch.

I agree we should consider detangling these and let it be a separate configuration setting for what (if any) bundles can be created using the widget.

Meanwhile, I haven't tested the arguments code in here, but a brief skim of #7 seems pretty reasonable. The filter case is working with limited testing.

Tentative +1 to committing #7 (or something close to it) as an shorter-term fix, and work towards a separate widget config for this in the long term.

Thanks!
-Derek

rpsu’s picture

I'm wondering whether we should make that rather a configuration of the field widget

I second that, digging some logic from a view may just be too difficult to the end user/ sitebuilder.

While the regular entity reference node bundles etc. can be configured using the field configuration, if it is not available (like in this case) I'd much rather find the configuration from a field widget. And if the field configuration does have the setting, the widget could tell user the correct location to configure the allowed add/create bundles.

rpsu’s picture

Status: Needs review » Needs work
rpsu’s picture

Status: Needs work » Needs review
StatusFileSize
new11.34 KB

here is a patch which allows configuring the allowed bundles via field widget if the refence is done using a view.

It also adds the default bundle selection.

Status: Needs review » Needs work

The last submitted patch, 11: 2729333-ief-bundle-selection-erv-11.patch, failed testing. View results
- codesniffer_fixes.patch Interdiff of automated coding standards fixes only.

rpsu’s picture

Status: Needs work » Needs review
StatusFileSize
new12.01 KB
new682 bytes

Forgot the update config schema, added here.

Status: Needs review » Needs work

The last submitted patch, 13: 2729333-ief-bundle-selection-erv-13.patch, failed testing. View results
- codesniffer_fixes.patch Interdiff of automated coding standards fixes only.

rpsu’s picture

Status: Needs work » Needs review
StatusFileSize
new11.94 KB
new1.04 KB

Putting the new config fields where they belong to

johan den hollander’s picture

Status: Needs review » Reviewed & tested by the community

Exactly what I needed. Applied the patch on 1.0.0-rc6 and it works well.
I don't like the fact that I had to specify 3 times that I want to work with nodes of type "employee" to get there. But it works!

I can see why the other options make sense. So IMHO this should be committed!

jidrone’s picture

In my case a have a custom Entity Reference Selection plugin, and also would like to have it working, so I suggest to change the condition:

$field_settings['handler'] == 'views'

to:

$field_settings['handler'] != 'default:node'

jidrone’s picture

Status: Reviewed & tested by the community » Needs review
StatusFileSize
new11.95 KB
new702 bytes

I added that change, it will work also for existing sites with the patch.

johan den hollander’s picture

Applied the #18 patch. Confirming that is still works good for me.

bramdriesen’s picture

Status: Needs review » Reviewed & tested by the community

RTBC in that case :) I also tested it and it works for me as well.

geek-merlin’s picture

Status: Reviewed & tested by the community » Needs work

There is an upcoming feature in core that adds exactly this setting: #2800875: Autocreate for Entity Reference selection handlers that extend ViewsSelection

Which we shoule leverage here. (And help there get it in. ;-)

jonathanshaw’s picture

@geek-merlin: did you realise that #2800875: Autocreate for Entity Reference selection handlers that extend ViewsSelection is NOT likely to actually proceed and enable Autocreate for Entity Reference fields that use Views reference method, despite the title? Amateescu in that issue has explicitly rejected doing that, because there is no way to enforce the validation.

dustinyoder’s picture

Upgraded to '8.x-1.0-rc8' of inline entity form module and now this patch is causing errors on the 'manage form display' page of any content type using Inline Entity Form - Complex widget. The first error I get is on line 155, with
Error: Call to a member function hasKey() on null in Drupal\inline_entity_form\Plugin\Field\\FieldWidget\InlineEntityFormComplex

scottsawyer’s picture

I created then closed #3215100: Filter bundles when filtering entity references with a view based on using one of the recent patches in #2800875: Autocreate for Entity Reference selection handlers that extend ViewsSelection because it's actually not sufficient to solve this problem. Unfortunately I haven't found a clear solution.

The problem is, with #2800875: Autocreate for Entity Reference selection handlers that extend ViewsSelection, we'd limit the bundles IEF is able to create to one and only one. What we want is to be able to limit the bundles to any arbitrary subset of available bundles.

I was trying to figure out a generic solution, but as has been demonstrated by comments in this issue, unless we figure out how to parse the available bundles out of the view, you always run the risk of the view and the field configuration not being aligned and creating a WTF experience. At a minimum, this would need some clear documentation.

The route I am considering is a custom field widget extending (in my case) Inline Entity Form - Complex for this configuration and re-implement getTargetBundles(). This way the WTF is tied to my specific project.

arantxio’s picture

StatusFileSize
new11.95 KB
new22.21 KB

I've made a reroll for this patch as it stopped applying in rc15 release.

jrochate’s picture

Thanks @Arantxio. That works on current RC19.

I think it's a good way of dealing with the problem.