Repository navigation
[6.x] Importing - #19612
Open
i-just wants to merge 472 commits into
Open
[6.x] Importing#19612i-just wants to merge 472 commits into
i-just wants to merge 472 commits into
Conversation
Contributor
Contributor
📚 Storybook previews@craftcms/ui — open Storybook Changed components:
resources/js — open Storybook Changed components: |
The server sends a saved Checkboxes or Multi-select default back as a list rather than the JSON it was entered as, so its options showed as unselected, and choosing one dropped the rest. The step's card summed it up as Skip. Amp-Thread-ID: https://ampcode.com/threads/T-a103929f-775b-4400-9882-6f772745fd68 Co-authored-by: Amp <amp@ampcode.com>
A template error on a row the search had hidden couldn't be shown or focused, so Apply seemed to do nothing. Amp-Thread-ID: https://ampcode.com/threads/T-a103929f-775b-4400-9882-6f772745fd68 Co-authored-by: Amp <amp@ampcode.com>
The step list kept the summaries of applied steps to itself, so the preview's tabs went on naming a step's old section and entry type. Amp-Thread-ID: https://ampcode.com/threads/T-a103929f-775b-4400-9882-6f772745fd68 Co-authored-by: Amp <amp@ampcode.com>
A preview relates an unsaved asset in place of each file the import would upload, so a field that needs a number of assets validates as it would after the import, rather than reporting the item as a problem. A file whose extension isn't allowed is left out, as the import leaves it. The field's own control only lists saved assets. Validating an Assets field whose value is a collection, as an eager-loaded one is, no longer throws. Amp-Thread-ID: https://ampcode.com/threads/T-a103929f-775b-4400-9882-6f772745fd68 Co-authored-by: Amp <amp@ampcode.com>
An element only records the attributes it saved, and the title, as changed, so a copy with a new alt text or other attribute looked the same as the element it was loaded from. Only the same instance is taken as unchanged now. Amp-Thread-ID: https://ampcode.com/threads/T-a103929f-775b-4400-9882-6f772745fd68 Co-authored-by: Amp <amp@ampcode.com>
Saving a step saves its whole plan, which can fail on another step even once this one is valid. The page only showed a toast and took the save as done. Now the save rejects with the plan's errors, and the form stays as it was: the step's own errors show on its fields, and every error is listed in the page's error summary, one about another step marked as such. Amp-Thread-ID: https://ampcode.com/threads/T-a103929f-775b-4400-9882-6f772745fd68 Co-authored-by: Amp <amp@ampcode.com>
Every container's button was named Map field, Edit mapping or View mapping alone, so a screen reader's list of buttons couldn't tell them apart. Each one's accessible name now ends with its field's label. Amp-Thread-ID: https://ampcode.com/threads/T-a103929f-775b-4400-9882-6f772745fd68 Co-authored-by: Amp <amp@ampcode.com>
Keeping both of a file that matches an existing one uploads every reference anew, so a repeated one is a second asset, which the preview had collapsed into one. Otherwise the import reuses the first upload's asset for any later file of the same name, wherever it comes from, so the preview now collapses those by name rather than by source. Co-authored-by: Amp <amp@ampcode.com> Amp-Thread-ID: https://ampcode.com/threads/T-a103929f-775b-4400-9882-6f772745fd68
A plan registered in code can set a lightswitch column's default as true or false, which the import applies, but its When empty popover read it as Off and the step's card summed it up as Skip. Co-authored-by: Amp <amp@ampcode.com> Amp-Thread-ID: https://ampcode.com/threads/T-a103929f-775b-4400-9882-6f772745fd68
A file at a URL with no extension is fetched on import to find out what it is, which a preview can't do, so its stand-in asset has no extension and failed the field's allowed file kinds. An unsaved asset whose file has no extension is left out of that check. Co-authored-by: Amp <amp@ampcode.com> Amp-Thread-ID: https://ampcode.com/threads/T-a103929f-775b-4400-9882-6f772745fd68
[6.x] Refine import UI
The override replaced LionButton's fills, but the invoker no longer extends LionButton, so it only undid 6.x's styling. Also drop the Lion reference from checkedValue()'s comment. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A step's preview results were cached for five minutes, keyed only on the step, its local file and the current user, so editing or deleting elements in the meantime still showed the earlier results. The key now also includes how many elements there are and when any was last updated or deleted. Every element counts, as an item's result can depend on the elements it relates to. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A single-select combobox now reserves the clear button's width while the button shows, so a long value ends before it instead of running under it. The import mapping's Incoming data column gets a minimum width of 14rem. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
# Conflicts: # CHANGELOG.md # packages/craftcms-ui/src/styles/shared/base.css # resources/translations/en/app.php # src/Config/GeneralConfig.php # workbench/database/seeders/DatabaseSeeder.php
# Conflicts: # packages/craftcms-ui/src/components/tooltip/tooltip.ts
# Conflicts: # CHANGELOG.md # src/Providers/CraftServiceProvider.php # src/User/Elements/User.php
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This branch has not been deployed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
It imports data from JSON, CSV or XML sources (local files or URLs) into Craft CMS elements or Eloquent models.
Core concepts:
Extensibility:
CraftCms\Cms\Import\Commands\ImportCommandData Types:
boot()viaCraftCms\Cms\Import\DataTypes\DataTypes::register(). To replace a built-in one,remove()it firstTransformers:
ElementTransformer=> the base element transformer, and the default for element importers without their own (in core, Users)EntryTransformer=> default when importing EntriesAssetTransformer=> default when importing AssetsElementTransformerauto-matches incoming keys to attributes and field handles even when the names aren’t exact (e.g.Plain Text/plain_text→plainText), and supports convention-basednormalize{PropName}()methods
myPlainTextField, or run complex checks to decide what valuemyOtherFieldgets. A transformer can be given as an instance or a class nameImporters:
ElementImporter(abstract) =>EntryImporter,AssetImporter,UserImporter. Each implementstargetClass(). Common settings:site(required) andfieldLayoutEntryImporteraddssectionandentryType, and can set an entry’s parent (parentId) in Structure sectionsAssetImporteraddsvolumeUserImporterwon’t import sensitive attributes likeadminorpassword; the only sensitive ones it allows areaffiliatedSiteId,email,passwordResetRequiredandphotoId.photoIdcan also be a URL or alocal path to the photo file
ModelImporter(abstract) =>SystemMessageImporteris the only built-in. Its mappable destinations are the model table’s columnsAddresshas no importer, so it’s never a standalone target. It can only be imported as nested content (Addresses field / User addresses)0disables batching)boot()viaCraftCms\Cms\Import\ImporterTypes::register()Field import handlers:
CraftCms\Cms\Import\FieldHandlers\FieldImportHandlerInterface, so the field itself needs no import code$importer->afterItemImported())boot()viaCraftCms\Cms\Import\FieldHandlers\FieldImportHandlers::register(). A field uses the handler for its own class or its nearest parent classAssetsFieldImportHandlerlets an Assets field value mix asset IDs with URLs and local file paths, creating assets from the files in the field’s upload locationfileConflictsetting decides what happens when a file with the same name already exists: use the existing asset (default), replace its file, or create a new assetImport plans:
import_plans)boot()viaCraftCms\Cms\Import\ImportPlan::register('handle', fn () => new ImportPlanData()...), and committed to your repository. The factory onlyruns when the plans are first loaded, so registering them adds no work at boot and doesn’t stop
artisan config:cachefrom working. The registered handle becomes the plan’s handle. A plan that is invalid, or that sets adifferent handle, is skipped and logged. Registering the same handle twice throws;
remove()unregisters a plan@root-relative or aliased path, or a URLmap), or fill one from a template instead (templates)matchCriteria)clearableItems)keepMissingNestedElements)allowedPrivateHostsconfig setting; loopback, link-local and cloud metadataaddresses are always rejected. The downloaded file’s contents must match its data type
importDisk(a local temp folder by default; use a shared disk if queue jobs can run ondifferent
servers), and each later job reads only its own items. They’re cleaned up when the step finishes, and stale ones are removed by garbage collection. Otherwise (batching disabled, or a job that stops early on a source that
fits in one batch) a follow-up job reads the source again
Mapping UI
depth
{lists the source’s columns as variables ({title}, or{{ object['First Name'] }}for names that aren’t identifiers). Templates work inside nested mappings too, where{blocks.heading}is the current block’s value. They’re rendered in Twig’s sandbox, since saving import plans doesn’trequire admin, and checked when the mapping is applied and when the plan is saved
matchCriteria,clearableItems,andkeepMissingNestedElementsare reserved: incoming data using them, at any depth, is never offered as a column and can’t be read by a templatecanBeSet: false(e.g.,id,uid) can only be used for matching, not setMatch criteria — three tiers, last wins
matchCriteriakey on the row,[systemHandle => incomingKey].Also looks inside
$data['fields']. If the row has no value for that key, the value given is matched on as-is.additionalMatchCriteria(), already resolved to actual values.Values from tiers 1 and 2 are matched literally (query syntax like
*ornot 5isn’t applied); tier 3 values are used as given.Clearable items
An array shaped like the match criteria. If a field or attribute is
nulland explicitly appliedunset()entirely, so the existing value is left untouched.Importing:
triggerImportPlans){source}is a@root-relative or aliased path, or a URL):artisan craft:import:entries {source} [--site=] [--section=] [--entry-type=] [--transformer=] [--match-criteria=]artisan craft:import:assets {source} [--site=] [--volume=] …artisan craft:import:users {source} …artisan craft:import:system-messages {source} …--siteonly on multisite), and--match-criteriatakes JSON (invalid JSON is silently ignored)Making things importable:
ElementImporter/ModelImportersubclass viaImporterTypes::register()CraftCms\Cms\Support\Attributes\Importablemarks an element’s properties as importable. Its flags areexcludeFromUiMapping,isContainer,canBeMatchCriteria,canBeClearedandcanBeSetCraftCms\Cms\Element\Contracts\ImportableContainerPropertiesInterfacemust be implemented by an element type with a container property (isContainer: true), likeUser’s addressesCraftCms\Cms\FieldLayout\Contracts\ImportableFieldLayoutElementInterfacemakes field layout elements importableCraftCms\Cms\Field\Contracts\ImportableElementContainerFieldInterfacelets container fields be imported correctlyCraftCms\Cms\Import\FieldHandlers\FieldImportHandlerInterfaceadds import-specific handling for a field typeEvents:
ItemImporting/ItemImported,ImportPlanSaving/ImportPlanSaved,ImportDispatching/ImportDispatched. The*ingevents are cancellable; to cancel, a listener sets$event->isValid = false.ItemImportedalso carries the element or model the data was imported into.
Each import run also fires lifecycle events, all sharing the run’s
runId:ImportStarted,ImportStepStarted,ImportChunkStarted/ImportChunkFinished,ImportStepFinishedandImportFinished(the*Finishedevents report whether anything failed). CLI imports fire these too, apart from the chunk events.
Config:
importDisk=> the filesystem disk import runs store their parsed source data on (set it to a shared disk if queue jobs can run on different servers)allowedPrivateHosts=> hostnames a source URL may resolve to private IP addresses forPermissions:
There’s a permissions group
importwithviewImportPlansand, nested under it,saveImportPlans,deleteImportPlansandtriggerImportPlans.Related issues
CMS-2390