From 9a8ccf6b296415667e7026217c2c3c5e2fad1362 Mon Sep 17 00:00:00 2001
From: interdruper <interdruper@2437374.no-reply.drupal.org>
Date: Fri, 18 Nov 2016 10:56:55 +0100
Subject: [PATCH] Issue #2158869: If the target field has set the default
 upload directory and it exists in the Media Folder tree, select it - Fix:
 check if ['#options']['file_directory'] is defined.

---
 media_browser_plus.module | 15 ++++++++++++++-
 1 file changed, 14 insertions(+), 1 deletion(-)

diff --git a/media_browser_plus.module b/media_browser_plus.module
index da302dd..cb9df50 100644
--- a/media_browser_plus.module
+++ b/media_browser_plus.module
@@ -864,12 +864,25 @@ function media_browser_plus_form_file_entity_add_upload_alter(&$form, &$form_sta
         'parent' => 0,
       );
       $field_folder_info = field_info_field('field_folder');
+      $folders = taxonomy_allowed_values($field);
       $form['field_folder'][LANGUAGE_NONE] = array(
         '#type' => 'select',
         '#title' => $field_folder_info['label'],
         '#description' => t('Defines the folder where the uploaded files will be saved'),
-        '#options' => taxonomy_allowed_values($field),
+        '#options' => $folders,
       );
+      // If the target field has set the default upload directory
+      // and it exists in the Media Folder tree, select it.
+      if (!empty($form['#options']['file_directory'])) {
+        $needle = $form['#options']['file_directory'];
+        foreach ($folders as $tid => $name) {
+          $term = taxonomy_term_load($tid);
+          if (media_browser_plus_construct_dir_path($term) === $needle) {
+            $form['field_folder'][LANGUAGE_NONE]['#default_value'] = $tid;
+            break;
+          }
+        }
+      }
       break;
 
     // Nothing to do for now.
-- 
1.9.0.msysgit.0

