Answers.Body: <p>I'm not sure if this is too specific to help someone in the future, but maybe it will directly or indirectly.</p>
  <p>After adding the field to a different entry type field layout, I added this:</p>
  <pre><code>foreach ($section-&gt;getEntryTypes() as $entryType) {
     Craft::$app-&gt;getSections()-&gt;saveEntryType($entryType);
  }
  </code></pre>
  <p>Saving the actual <code>entryType</code> after saving the layout is what allowed me to access this.</p>
  
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2023-06-15T18:36:29.690Z
Answers.LastActivityDate: 2023-06-15T18:36:29.690Z
Answers.UserDisplayName: Cat Named Dog
Body: <p>I'm currently using migrations to change/swap content. On certain entries, there are assigned category fields attached to specific entry types. I am consolidating all of these to a single category field and also changing the entry types to the default. The new field is on another fieldlayout since it's a different entry type. I need a way to save the old category information in the short term so I can assign it.</p>
  <p>What's happening is sometimes it can find the field, sometimes it can't:</p>
  <pre><code>public function safeUp()
      {
  
          $sectionFieldMappings = [
              [
                  'sectionHandle' =&gt; 'bowlerProducts',
                  'entryTypeHandle' =&gt; 'product',
                  'fieldHandle' =&gt; 'bowlerProductAttributes',
                  'categoryHandle' =&gt; 'bowlerProductAttributes'
              ],
              [
                  'sectionHandle' =&gt; 'centerProducts',
                  'entryTypeHandle' =&gt; 'product',
                  'fieldHandle' =&gt; 'bowlingCenterProductAttributes',
                  'categoryHandle' =&gt; 'bowlingCenterProductAttributes'
              ]
          ];
  
  
          foreach ($sectionFieldMappings as $sectionFieldMapping) {
  
              $sectionHandle = $sectionFieldMapping['sectionHandle'];
              $entryTypeHandle = $sectionFieldMapping['entryTypeHandle'];
              $attributesFieldHandle = $sectionFieldMapping['fieldHandle'];
              $categoryHandle = $sectionFieldMapping['categoryHandle'];
  
              $section = Craft::$app-&gt;sections-&gt;getSectionByHandle($sectionHandle);
              $entryTypes = $section-&gt;getEntryTypes();
              $defaultEntryType = null;
  
              foreach ($entryTypes as $entryType) {
                  if ($entryType-&gt;handle == $entryTypeHandle) {
                      $defaultEntryType = $entryType;
                  }
              }
  
  
  
              if ($defaultEntryType) {
  
                  $entries = Entry::find()
                      -&gt;section($sectionHandle)
                      -&gt;anyStatus()
                      -&gt;all();
  
                  foreach ($entries as $entry) {
  
                      // need to make a note of the current category slug
                      // once we change entry type, it won't be accessible
                      $categoriesToSave = $this-&gt;getCategorySlugs($entry);
  
                      // change entry type and save entry so the new field is accessible
                      $entry-&gt;typeId = $defaultEntryType-&gt;id;
                      $entry-&gt;fieldLayoutId = $defaultEntryType-&gt;fieldLayoutId;
  
                      if (Craft::$app-&gt;elements-&gt;saveElement($entry)) {
  
                          echo $entry-&gt;title . &quot; saved. \n&quot;;
  
                          $savedEntry = Craft::$app-&gt;getEntries()-&gt;getEntryById($entry-&gt;id);
  
                          $allCategoryIds = [];
  
                          foreach ($categoriesToSave as $categoryToSave) {
                              $categoryIds = $this-&gt;getCategoryIdsFromSlugs($categoryToSave['slugs'], $categoryToSave['parentTitle'], $categoryHandle);
                              $allCategoryIds = array_merge($allCategoryIds, $categoryIds);
                          }
  
                          echo &quot;the entry fieldlayoutid is  &quot; . $entry-&gt;fieldLayoutId . &quot; and the product fieldLayout id is &quot; . $defaultEntryType-&gt;fieldLayoutId;
  
                          try {
                              echo &quot;setting field: &quot; . $savedEntry-&gt;getFieldValue($attributesFieldHandle) . &quot;\n&quot;;
                          } catch (Exception $e) {
                              echo &quot;couldn't find field &quot; . $attributesFieldHandle . &quot;\n&quot;;
                          }
  
                          $savedEntry-&gt;setFieldValue($attributesFieldHandle, $allCategoryIds);
                          echo &quot;All category IDs to assign: &quot; . implode(&quot;,&quot;, $allCategoryIds) . &quot;\n&quot;;
  
                          if (Craft::$app-&gt;elements-&gt;saveElement($savedEntry)) {
                              echo &quot;Saved after setting field value \n&quot;;
                          } else {
                              echo &quot;Failed to save after setting field value \n&quot;;
                          }
                      }
                  }
              }
          }
      }
  </code></pre>
  <p>Above is code that changes the entry type to the default entry type, then on save success, use information from its previous fieldlayout and add that to the field found on the default entry type.</p>
  <p>I've confirmed the the correct field layout ID with <code>echo &quot;the entry fieldlayoutid is  &quot; . $entry-&gt;fieldLayoutId . &quot; and the product fieldLayout id is &quot; . $defaultEntryType-&gt;fieldLayoutId; \n</code></p>
  <p>and the existence of the field with:</p>
  <pre><code>try {
    echo &quot;setting field: &quot; . $savedEntry-&gt;getFieldValue($attributesFieldHandle) . &quot;\n&quot;;
  } catch (Exception $e) {
      echo &quot;couldn't find field &quot; . $attributesFieldHandle . &quot;\n&quot;;
  }
  </code></pre>
  <p>On first run <code>craft migrate/up</code>, the <code>catch</code> block is called because the field handle is invalid. If I let it run all the way, all the entries <code>entryType</code> is correctly swapped, however, they were not assigned category relations on the new field.</p>
  <p>If I force quit the migration and then run <code>craft migrate/up</code> again, then it is able to find the field.</p>
  <p>I've tried clearing/flushing all caches.</p>
  <p>Each time I run a migration, I restore the previous database.</p>
  <p>Edit:</p>
  <p>It's possible the migration before this one that is responsible for creating a new field and adding it to the entry type is getting messed up. Still noting that it works in that it adds the new field/tab to the field layout I specified. but something internal to craft api doesn't seem to know it's there until other actions take place.</p>
  <p>The migration is:</p>
  <pre><code>public function safeUp()
      {
          $fieldSectionMapping = [
              'centerProducts' =&gt; 'bowlingCenterProductAttributes',
              'bowlerProducts' =&gt; 'bowlerProductAttributes'
          ];
  
          foreach ($fieldSectionMapping as $sectionHandle =&gt; $fieldHandle) {
  
              $field = Craft::$app-&gt;fields-&gt;getFieldByHandle($fieldHandle);
              $section = Craft::$app-&gt;sections-&gt;getSectionByHandle($sectionHandle);
              $entryTypeHandle = &quot;product&quot;;
              $defaultEntryType = null;
  
              foreach ($section-&gt;getEntryTypes() as $entryType) {
                  if ($entryType-&gt;handle == $entryTypeHandle) {
                      $defaultEntryType = $entryType;
                  }
              }
  
              $fieldLayout = $defaultEntryType-&gt;getFieldLayout();
              $layout = $entryType-&gt;getFieldLayout();
              $tabs = $layout-&gt;getTabs();
  
              foreach ($tabs[0]-&gt;elements as $i =&gt; $element) {
                  if ($element instanceof CustomField &amp;&amp; $element-&gt;getField()-&gt;handle === 'bowlingCenterProductAttributes') {
                      return true;
                  }
              }
  
              $newFieldElement = new CustomField($field);
  
              $newTab = new FieldLayoutTab([
                  'name' =&gt; 'Product Attributes',
                  'sortOrder' =&gt; count($tabs) + 1,
              ]);
              $newTab-&gt;elements = [$newFieldElement];
  
              $tabs[] = $newTab;
              $fieldLayout-&gt;setTabs($tabs);
  
              Craft::$app-&gt;getFields()-&gt;saveLayout($fieldLayout);
          }
      }
  </code></pre>
  <p>What I did was comment this out completely, manually create the fields and assign them to the appropriate entry type layout, then run my migrations for the first time and then the field that was invalid before, is now found.</p>
  
Tags: <cache><migration>
Title: Craft CMS 3.8 - Field not found after changing entry type, but then is found after running again
ThreadText: # Craft CMS 3.8 - Field not found after changing entry type, but then is found after running again
  
  (Asked by: username_0 on 2023-06-15)
  
  I'm currently using migrations to change/swap content. On certain entries, there are assigned category fields attached to specific entry types. I am consolidating all of these to a single category field and also changing the entry types to the default. The new field is on another fieldlayout since it's a different entry type. I need a way to save the old category information in the short term so I can assign it.
  
  What's happening is sometimes it can find the field, sometimes it can't:
  
  ```
  public function safeUp()
      {
  
          $sectionFieldMappings = [
              [
                  'sectionHandle' => 'bowlerProducts',
                  'entryTypeHandle' => 'product',
                  'fieldHandle' => 'bowlerProductAttributes',
                  'categoryHandle' => 'bowlerProductAttributes'
              ],
              [
                  'sectionHandle' => 'centerProducts',
                  'entryTypeHandle' => 'product',
                  'fieldHandle' => 'bowlingCenterProductAttributes',
                  'categoryHandle' => 'bowlingCenterProductAttributes'
              ]
          ];
  
          foreach ($sectionFieldMappings as $sectionFieldMapping) {
  
              $sectionHandle = $sectionFieldMapping['sectionHandle'];
              $entryTypeHandle = $sectionFieldMapping['entryTypeHandle'];
              $attributesFieldHandle = $sectionFieldMapping['fieldHandle'];
              $categoryHandle = $sectionFieldMapping['categoryHandle'];
  
              $section = Craft::$app->sections->getSectionByHandle($sectionHandle);
              $entryTypes = $section->getEntryTypes();
              $defaultEntryType = null;
  
              foreach ($entryTypes as $entryType) {
                  if ($entryType->handle == $entryTypeHandle) {
                      $defaultEntryType = $entryType;
                  }
              }
  
              if ($defaultEntryType) {
  
                  $entries = Entry::find()
                      ->section($sectionHandle)
                      ->anyStatus()
                      ->all();
  
                  foreach ($entries as $entry) {
  
                      // need to make a note of the current category slug
                      // once we change entry type, it won't be accessible
                      $categoriesToSave = $this->getCategorySlugs($entry);
  
                      // change entry type and save entry so the new field is accessible
                      $entry->typeId = $defaultEntryType->id;
                      $entry->fieldLayoutId = $defaultEntryType->fieldLayoutId;
  
                      if (Craft::$app->elements->saveElement($entry)) {
  
                          echo $entry->title . " saved. \n";
  
                          $savedEntry = Craft::$app->getEntries()->getEntryById($entry->id);
  
                          $allCategoryIds = [];
  
                          foreach ($categoriesToSave as $categoryToSave) {
                              $categoryIds = $this->getCategoryIdsFromSlugs($categoryToSave['slugs'], $categoryToSave['parentTitle'], $categoryHandle);
                              $allCategoryIds = array_merge($allCategoryIds, $categoryIds);
                          }
  
                          echo "the entry fieldlayoutid is  " . $entry->fieldLayoutId . " and the product fieldLayout id is " . $defaultEntryType->fieldLayoutId;
  
                          try {
                              echo "setting field: " . $savedEntry->getFieldValue($attributesFieldHandle) . "\n";
                          } catch (Exception $e) {
                              echo "couldn't find field " . $attributesFieldHandle . "\n";
                          }
  
                          $savedEntry->setFieldValue($attributesFieldHandle, $allCategoryIds);
                          echo "All category IDs to assign: " . implode(",", $allCategoryIds) . "\n";
  
                          if (Craft::$app->elements->saveElement($savedEntry)) {
                              echo "Saved after setting field value \n";
                          } else {
                              echo "Failed to save after setting field value \n";
                          }
                      }
                  }
              }
          }
      }
  
  ```
  
  Above is code that changes the entry type to the default entry type, then on save success, use information from its previous fieldlayout and add that to the field found on the default entry type.
  
  I've confirmed the the correct field layout ID with `echo "the entry fieldlayoutid is " . $entry->fieldLayoutId . " and the product fieldLayout id is " . $defaultEntryType->fieldLayoutId; \n`
  
  and the existence of the field with:
  
  ```
  try {
    echo "setting field: " . $savedEntry->getFieldValue($attributesFieldHandle) . "\n";
  } catch (Exception $e) {
      echo "couldn't find field " . $attributesFieldHandle . "\n";
  }
  
  ```
  
  On first run `craft migrate/up`, the `catch` block is called because the field handle is invalid. If I let it run all the way, all the entries `entryType` is correctly swapped, however, they were not assigned category relations on the new field.
  
  If I force quit the migration and then run `craft migrate/up` again, then it is able to find the field.
  
  I've tried clearing/flushing all caches.
  
  Each time I run a migration, I restore the previous database.
  
  Edit:
  
  It's possible the migration before this one that is responsible for creating a new field and adding it to the entry type is getting messed up. Still noting that it works in that it adds the new field/tab to the field layout I specified. but something internal to craft api doesn't seem to know it's there until other actions take place.
  
  The migration is:
  
  ```
  public function safeUp()
      {
          $fieldSectionMapping = [
              'centerProducts' => 'bowlingCenterProductAttributes',
              'bowlerProducts' => 'bowlerProductAttributes'
          ];
  
          foreach ($fieldSectionMapping as $sectionHandle => $fieldHandle) {
  
              $field = Craft::$app->fields->getFieldByHandle($fieldHandle);
              $section = Craft::$app->sections->getSectionByHandle($sectionHandle);
              $entryTypeHandle = "product";
              $defaultEntryType = null;
  
              foreach ($section->getEntryTypes() as $entryType) {
                  if ($entryType->handle == $entryTypeHandle) {
                      $defaultEntryType = $entryType;
                  }
              }
  
              $fieldLayout = $defaultEntryType->getFieldLayout();
              $layout = $entryType->getFieldLayout();
              $tabs = $layout->getTabs();
  
              foreach ($tabs[0]->elements as $i => $element) {
                  if ($element instanceof CustomField && $element->getField()->handle === 'bowlingCenterProductAttributes') {
                      return true;
                  }
              }
  
              $newFieldElement = new CustomField($field);
  
              $newTab = new FieldLayoutTab([
                  'name' => 'Product Attributes',
                  'sortOrder' => count($tabs) + 1,
              ]);
              $newTab->elements = [$newFieldElement];
  
              $tabs[] = $newTab;
              $fieldLayout->setTabs($tabs);
  
              Craft::$app->getFields()->saveLayout($fieldLayout);
          }
      }
  
  ```
  
  What I did was comment this out completely, manually create the fields and assign them to the appropriate entry type layout, then run my migrations for the first time and then the field that was invalid before, is now found.
  
  **Tags:** cache, migration
  
  
  ---
  
  ## 1 answers
  
  ### Answer by username_0 on 2023-06-15. Score: 1
  
  I'm not sure if this is too specific to help someone in the future, but maybe it will directly or indirectly.
  
  After adding the field to a different entry type field layout, I added this:
  
  ```
  foreach ($section->getEntryTypes() as $entryType) {
     Craft::$app->getSections()->saveEntryType($entryType);
  }
  
  ```
  
  Saving the actual `entryType` after saving the layout is what allowed me to access this.
  
  
  ---
  
  