Skip to content

armgit / spree

Public Imported from GitHub
0

Open Source Platform for DTC, B2B Commerce, Marketplaces & Omnichannel. REST APIs, TypeScript SDKs, and production-ready Next.js storefront. Self-host it. Own your data. No vendor lock-in. Zero platform fees.

Make a type's required custom field advisory, not enforced

Damian Legawiec1e16a0dd5aff
diff --git a/CLAUDE.md b/CLAUDE.md
index c046f258f6..8f5ace30df 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -16,7 +16,7 @@ Active plans (6.0 target, work pending):
- `6.0-cart-order-split.md` — Cart/Order model separation, dual-FK owner everywhere (`cart_id`/`order_id` exactly-one, `#owner` as method — NOT polymorphic), idempotent copy-on-completion (`Order#cart_id` unique, order-before-payment), Order state machine removed (Checkout::Requirements for steps; payment/fulfillment statuses derived-then-persisted via one recompute service). **Shipped to 6-0-dev (feature/6-0-core-rewrite Waves 1+5):** Cart owns checkout end to end, machine + `spree_orders.state` gone, `Carts::Complete` three-phase pipeline live, `Orders::UpdateStatuses` sole status writer; only Wave 7 data migration (incomplete orders → carts) remains
- `6.0-admin-api.md` — Admin REST API conventions, auth, endpoint list (~300 endpoints)
- `6.0-admin-spa.md` — React admin architecture, extension points, table registry, i18n + server-error mapping
-- `6.0-product-types.md` — Prototype → ProductType rename, custom-field schema enforcement. **Creation-time template (2026-08-06):** type edits never mutate existing products (custom-field form/validation + `fulfillment_types` are live by reference; option types/categories seed additively at attach; explicit previewed `ApplyToProducts` job is the only bulk path); per-product type detach/reassign allowed (non-destructive), required fields validate at activation only, no Store API exposure. **Fully shipped** (all phases, Phase 2 rescoped + delivered 2026-08-06)
+- `6.0-product-types.md` — Prototype → ProductType rename, custom-field schema enforcement. **Creation-time template (2026-08-06):** type edits never mutate existing products (custom-field form/validation + `fulfillment_types` are live by reference; option types/categories seed additively at attach; explicit previewed `ApplyToProducts` job is the only bulk path); per-product type detach/reassign allowed (non-destructive), `required` on a type's custom field is **advisory only** (dashboard marker; no server validation — Spree writes product + fields in two steps), no Store API exposure. **Fully shipped** (all phases, Phase 2 rescoped + delivered 2026-08-06)
- `6.0-remove-master-variant.md` — Eliminate is_master, add default_variant_id FK on Product. **Shipped to 6-0-dev (PR #14265):** is_master removed from all models, default_variant_id + `spree:remove_master_variant` data-migration rake landed; only the physical is_master column drop remains (6.1 cleanup).
- `6.0-typed-stock-movements.md` — Replace generic StockMovement with typed kinds + concrete FKs
- `6.0-normalize-state-to-status.md` — Rename state → status on Payment, Shipment, InventoryUnit, ReturnAuthorization, GiftCard
diff --git a/docs/plans/6.0-product-types.md b/docs/plans/6.0-product-types.md
index f3b7975c20..162d9347e2 100644
--- a/docs/plans/6.0-product-types.md
+++ b/docs/plans/6.0-product-types.md
@@ -10,10 +10,10 @@
Rename and extend the existing `Spree::Prototype` model into `Spree::ProductType` — a persistent, schema-defining, **store-owned** association on Product. Today Prototype is a fire-and-forget creation template (it *replaces* the product's option types and taxons at creation, then has no ongoing relationship — and since the legacy admin's prototype UI was already deleted, prototypes are currently uncreatable outside the console). ProductType becomes a **creation-time template with live-by-reference schema** (semantics revised 2026-08-06, replacing the earlier "live template" design):
-- **Live by reference (no sync, no copies):** the custom-field form the dashboard renders, the required-field validation, and `fulfillment_types` delivery eligibility are all read from the type *at use time*. Editing the type's custom-field definitions updates every product form on next load with zero product rows touched.
+- **Live by reference (no sync, no copies):** the custom-field form the dashboard renders (including which fields are marked required) and `fulfillment_types` delivery eligibility are read from the type *at use time*. Editing the type's custom-field definitions updates every product form on next load with zero product rows touched.
- **Seeded at attach time (additive, one-shot):** option types and categories are materialized state (join rows that variants and navigation hang off), so the type seeds them additively when a product is created with the type or a type is assigned later. Editing a type **never mutates existing products**; the only path from a type edit to existing products is the explicit, previewed, additive-only **"Apply to existing products"** action.
-This is the Shopify-shaped behavior (category changes affect nothing retroactively) with Saleor's schema value (type-driven forms and validation), and it closes Spree's biggest functional gap in catalog modeling while building on existing infrastructure rather than starting from scratch.
+This is the Shopify-shaped behavior (category changes affect nothing retroactively, and a type's `required` flag is guidance rather than a save-time rule) with Saleor's schema value (type-driven forms), and it closes Spree's biggest functional gap in catalog modeling while building on existing infrastructure rather than starting from scratch.
## Implementation status (verified 2026-08-05; semantics rescoped 2026-08-06)
@@ -23,7 +23,7 @@ This is the Shopify-shaped behavior (category changes affect nothing retroactive
1. **Seeding trigger fixed** — `sync_associations_from_product_type` now also runs `after_update, if: :saved_change_to_product_type_id?`, so assigning a type to an existing product and reassigning both seed (detach is a no-op). Presence guards query the join tables rather than the cached associations, which are stale when pending variants insert option-type joins in the same save.
2. **`ProductTypeCustomFieldDefinition`** — table + model with `required`/`sort_order`, `required`/`ordered` scopes, per-type uniqueness, and a validation that the definition's `resource_type` is `Spree::Product`. **No `Spree::CustomFieldDefinition` constant exists in Ruby** (the 5.5 alias this plan assumed is API-layer only), so the association carries custom-field vocabulary while `class_name` points at `Spree::MetafieldDefinition`.
-3. **Required-field validation at activation only** — `becoming_active?` (`active? && !new_record? && status_changed?`) gates it, so a type gaining a required field never breaks saves of already-active products. Creation is deliberately excluded: importers and API clients save the product and attach its custom fields in two writes, so blocking creation would reject the first of them (the CSV importer does exactly this — `product_variant.rb:88` saves, `:93` attaches).
+3. **`required` is advisory — no server-side enforcement** (revised 2026-08-06, see Key Decisions). The join keeps the flag and the dashboard marks the field; nothing rejects a blank value.
4. **`ProductTypes::ApplyToProducts`** + `ApplyToProductsJob` + `POST /api/v3/admin/product_types/:id/apply_to_products` (202 with `products_count`). Batched, additive, idempotent; the category half delegates to `Categories::AddProducts`, which owns the counter-cache/position/search-index bookkeeping a raw `insert_all` would skip.
5. **Admin write surface** — `option_type_ids`, `category_ids` and the nested `custom_field_definitions` replace-set are permitted; the serializer returns association ids as prefixed ids (read/write symmetry). Category ids are re-scoped to `current_store` before assignment (OptionType is global — nothing to scope there).
6. **Dashboard** — the type sheet edits option types, categories and the dnd-kit-sortable custom-field list with per-row `required` toggles, carries the "changes apply to new products" note, and offers the confirmed apply action. The product form renders custom fields from its type via a new `definitionIds` prop on `FormBackedCustomFieldsProvider` (omitted ⇒ all definitions, so typeless products are unchanged). Keys added to all six locales.
@@ -57,7 +57,7 @@ Also shipped alongside: an integration spec for the whole resource (product type
- **Seeded additively at attach:** option types and categories are copied (additively) when a product gets the type — at creation or a later assignment. Editing a type never mutates existing products; there are **no propagation callbacks** on the join models, no locked option types, and no provenance tracking to maintain. Products manage their option types freely after seeding; the type is a template, not a contract.
- **Explicit apply action:** `ProductTypes::ApplyToProducts` (additive-only, idempotent, background job, previewed with the affected count) is the sole sanctioned path from a type edit to existing products — a deliberate bulk edit the merchant asks for by name, categorically different from a standing invariant mutating products as a side effect.
- **The custom-field join carries `required` and `sort_order`.** `spree_product_type_custom_field_definitions` determines which definitions a type uses, whether they're required, and display order. This is the schema enforcement layer. **No `level` column** — variant-level definitions are deferred to 6.1 (2026-08-06); option types already own variant identity, and the column would be speculative schema.
-- **Required fields are enforced when an existing product is activated** (2026-08-06, refined during sample-data work). The validation runs when a persisted product transitions into `active` — never on creation, and never on ordinary saves of an already-active product — otherwise adding a required definition to a type instantly makes every existing active product of that type fail on its next save (the latent mass-mutation the live-by-reference half would otherwise reintroduce). Shopify precedent: definition validations apply to new writes only.
+- **`required` is advisory, never enforced server-side** (2026-08-06, reversing the earlier "enforced at activation" decision). The flag stays on the join, ships in the API, is editable in the type editor, and renders as a marker on the product form — but no validation rejects a blank value. **Why the reversal:** Spree writes a product and its custom fields in *two* steps (the CSV importer saves at `product_variant.rb:88` and attaches at `:93`; API clients can do the same), so any save-time rule fights the write model. Three successive attempts at a trigger — activation-only, excluding creation, including creation — each either broke the importer or left a hole (a product created active never changes status again, so it would stay permanently non-compliant). **Competitor check:** Shopify has no required flag on metafield definitions at all; Medusa and Vendure have no type-driven required concept. Only Saleor enforces, and it can because attributes exist *solely* through the type and ride the product mutation atomically — neither is true in Spree, where any definition can attach to any product. A dashboard-side nudge on the activation action can be added later without touching the model.
- **Prefix ID: `pt_`.** Replaces `proto_`.
- **No shared value pools — ever, for custom fields** (2026-08-06, closing the former open question). Custom-field values remain per-resource strings. The split of roles, stated precisely: **predicate** search/sort/filter on those strings already ships storefront-side (5.6 — per-definition `searchable?`/`sortable?` flags, `SearchProvider::MetafieldSchema`, `with_metafield_filters` with Ransack-style predicates, in both Database and Meilisearch providers) and continues unchanged. **Faceted navigation over canonical values with counts** ("Color: Red (42)") is the OptionType/OptionValue role — value rows already shared, translatable, disjunctive facet counting shipped in 5.4 — and a value pool on custom fields would duplicate it. If demand for product-level descriptive facets emerges (the Vendure Facet / Saleor non-variant-attribute case), that is a new dedicated plan, not a custom-fields extension.
- **ProductType is optional.** Products without a type work exactly as today. Type enforcement is additive, not breaking.
@@ -175,8 +175,7 @@ class Spree::Product < Spree.base_class
after_create :sync_associations_from_product_type
after_update :sync_associations_from_product_type, if: :saved_change_to_product_type_id?
- # Activation-only: never fails an ordinary save of an already-active product
- validate :required_custom_fields_present, if: :becoming_active?
+ # No required-field validation — `required` is advisory (see Key Decisions).
private
@@ -196,21 +195,6 @@ class Spree::Product < Spree.base_class
end
end
- # Creation is excluded: writers that save the product before attaching its
- # custom fields (the CSV importer, API clients) get a fair chance to do both.
- def becoming_active?
- active? && !new_record? && status_changed?
- end
-
- def required_custom_fields_present
- return unless product_type
-
- product_type.product_type_custom_field_definitions.required.each do |join|
- unless has_custom_field?(join.custom_field_definition)
- errors.add(:base, "Missing required custom field: #{join.custom_field_definition.name}")
- end
- end
- end
end
```
@@ -269,7 +253,7 @@ Admin API + `@spree/admin-sdk` `productTypes` resource + dashboard pages (list u
Product form behavior:
1. Option types and categories seeded by the type render like any others — nothing is locked; the merchant may remove or add freely after seeding.
-2. Custom-field form fields render from the type's **current** definition list in `sort_order`, grouped by namespace, with required indicators; required fields validated on activation only.
+2. Custom-field form fields render from the type's **current** definition list in `sort_order`, grouped by namespace, with a marker on the ones the type calls required (advisory — no save is blocked).
3. Creating a product: optional ProductType selector; selecting a type seeds its option types and categories additively. Changing or clearing the type later is allowed (explicit, non-destructive; the form re-renders custom fields from the new type).
ProductType editing:
@@ -375,7 +359,7 @@ Also in this phase: the seeding-trigger fix (`after_create` → `after_save` on
### Phase 4: React dashboard
-- ProductType list + edit pages (with the "affects new products only" messaging and the apply-action confirm); product form integration (seeded option types render as ordinary removable rows, dynamic custom-field form from the type definition, required-field validation surfaced at activation); i18n in all locale files.
+- ProductType list + edit pages (with the "affects new products only" messaging and the apply-action confirm); product form integration (seeded option types render as ordinary removable rows, dynamic custom-field form from the type definition, required fields marked but never blocking); i18n in all locale files.
### Rake task: backfill product_type_id (advisory)
@@ -394,7 +378,7 @@ Advisory, not automatic — `product_type_id` stays nullable. (Realistically a s
- **New CustomFieldDefinitions should be resource_type-aware** (`resource_type: 'Spree::Product'` for product-intended definitions).
- **Don't create a separate Attribute/Property system.** Everything builds on custom fields. No new EAV tables.
- **Editing a ProductType must never mutate existing products** except through the explicit `ApplyToProducts` action (additive-only, previewed, background job). No propagation callbacks on the join models — ever.
-- **Required-field validation runs when an existing product is activated.** Nothing may make an already-active product fail an ordinary save because its type gained a required definition, and nothing may block creating a product before its custom fields are attached.
+- **Never enforce `required` server-side.** The flag drives a dashboard marker only. Spree writes a product and its custom fields in two steps, so a save-time rule fights the write model — see the Key Decision for the three trigger variants that each failed. A dashboard-side nudge is fine; a model validation is not.
- **No Store API exposure of ProductType** — no endpoint, no expand, no filter. Storefronts see categories and collections only.
## Resolved Questions
diff --git a/docs/plans/decisions.md b/docs/plans/decisions.md
index ba13fab77a..efe5610a61 100644
--- a/docs/plans/decisions.md
+++ b/docs/plans/decisions.md
@@ -1,3 +1,36 @@
+## 2026-08-06: A product type's `required` custom field is advisory — no server-side enforcement
+
+Reverses the "enforced at activation" position taken earlier the same day
+in `6.0-product-types.md`. The flag stays on
+`ProductTypeCustomFieldDefinition`, ships in the Admin API, is editable
+in the type editor, and renders as a marker on the product form — but no
+model validation rejects a blank value.
+
+**Why.** Spree writes a product and its custom fields in *two* steps:
+the CSV importer saves at `product_variant.rb:88` and attaches
+metafields at `:93`, and API clients can do the same (a metafield needs
+a persisted parent, so `custom_fields=` stashes values until
+`after_save`). Any save-time rule fights that. Three triggers were tried
+and each failed: activation-only left a product created `active`
+permanently non-compliant, since status never changes again; excluding
+creation had the same hole; including creation broke the sample-data
+import twice and needed a staging shim inside the importer to work
+around the model's own rule.
+
+**Competitor check.** Shopify has no required flag on metafield
+definitions at all — validations cover length/range/regex only. Medusa
+and Vendure have no type-driven required concept. Only Saleor enforces
+(`valueRequired`), and it can because attributes exist *solely* through
+the product type and ride the product mutation atomically. Neither holds
+in Spree, where any definition can attach to any product independently
+of a type. Adopting the Shopify position deletes the most fragile code
+in the feature.
+
+**Constraint going forward:** never add a model validation for this. A
+dashboard-side nudge on the activation action is acceptable and
+reversible; a server rule is not.
+
+
## 2026-08-06: ProductType is a creation-time template, not a live sync; type changes are allowed; no Store API exposure
Competitor review (Saleor / Shopify / Medusa / Vendure) reversed the
diff --git a/packages/dashboard/src/components/spree/custom-fields/custom-fields-inline.tsx b/packages/dashboard/src/components/spree/custom-fields/custom-fields-inline.tsx
index 860d9f87aa..6728160ada 100644
--- a/packages/dashboard/src/components/spree/custom-fields/custom-fields-inline.tsx
+++ b/packages/dashboard/src/components/spree/custom-fields/custom-fields-inline.tsx
@@ -100,6 +100,12 @@ interface CustomFieldsMeta {
resourceType: string
/** Plural, human-readable resource name for empty-state copy (e.g. "orders"). */
resourceLabel?: string
+ /**
+ * Definitions the resource's type marks as required. Advisory only — the
+ * backend never rejects a blank one (see Spree::Product), so this drives a
+ * visual marker and nothing else.
+ */
+ requiredDefinitionIds?: string[]
}
/**
@@ -183,6 +189,8 @@ interface FormBackedProviderProps<T extends CustomFieldsFormShape> {
* to render every definition for the resource type.
*/
definitionIds?: string[]
+ /** Subset of `definitionIds` the type marks required — shown with a marker. */
+ requiredDefinitionIds?: string[]
children: ReactNode
}
@@ -191,6 +199,7 @@ export function FormBackedCustomFieldsProvider<T extends CustomFieldsFormShape>(
resourceType,
resourceLabel,
definitionIds,
+ requiredDefinitionIds,
children,
}: FormBackedProviderProps<T>) {
// The provider only ever touches the `custom_fields` field; narrow to the
@@ -238,10 +247,10 @@ export function FormBackedCustomFieldsProvider<T extends CustomFieldsFormShape>(
() => ({
state: { values },
actions: { setValue },
- meta: { definitions, isLoading, resourceType, resourceLabel },
+ meta: { definitions, isLoading, resourceType, resourceLabel, requiredDefinitionIds },
mode: { kind: 'form' },
}),
- [values, setValue, definitions, isLoading, resourceType, resourceLabel],
+ [values, setValue, definitions, isLoading, resourceType, resourceLabel, requiredDefinitionIds],
)
return <CustomFieldsContext value={ctx}>{children}</CustomFieldsContext>
@@ -539,7 +548,7 @@ function FieldsEditor({ onSetUp }: { onSetUp: () => void }) {
const {
state: { values },
actions: { setValue },
- meta: { definitions },
+ meta: { definitions, requiredDefinitionIds },
mode,
} = useCustomFieldsContext()
@@ -549,6 +558,7 @@ function FieldsEditor({ onSetUp }: { onSetUp: () => void }) {
<CustomFieldRow
key={def.id}
definition={def}
+ required={requiredDefinitionIds?.includes(def.id)}
value={values[def.id]}
onChange={(next) => setValue(def.id, next)}
/>
@@ -745,11 +755,31 @@ function CreateDefinitionSheet({
interface CustomFieldRowProps {
definition: CustomFieldDefinition
+ /**
+ * The product type marks this field required. Advisory: it renders a marker,
+ * and nothing rejects a blank value — see Spree::Product.
+ */
+ required?: boolean
value: unknown
onChange: (value: unknown) => void
}
-function CustomFieldRow({ definition, value, onChange }: CustomFieldRowProps) {
+// The product type's `required` flag is guidance, not a rule the API enforces
+// (Shopify behaves the same way), so this marks the field without blocking any
+// save.
+function RequiredMarker() {
+ const { t } = useTranslation()
+ return (
+ <span
+ className="ml-0.5 text-muted-foreground"
+ title={t('admin.components.custom_fields.required_hint')}
+ >
+ *
+ </span>
+ )
+}
+
+function CustomFieldRow({ definition, required, value, onChange }: CustomFieldRowProps) {
const inputId = `custom-field-${definition.id}`
const friendlyLabel = definition.label || definition.key
// The `namespace.key` identifier matters to developers / API consumers but
@@ -791,6 +821,7 @@ function CustomFieldRow({ definition, value, onChange }: CustomFieldRowProps) {
<div className="flex items-center justify-between gap-4">
<FieldLabel htmlFor={inputId} title={technicalKey} className="cursor-pointer">
{friendlyLabel}
+ {required && <RequiredMarker />}
</FieldLabel>
{widget}
</div>
@@ -802,6 +833,7 @@ function CustomFieldRow({ definition, value, onChange }: CustomFieldRowProps) {
<Field>
<FieldLabel htmlFor={inputId} title={technicalKey}>
{friendlyLabel}
+ {required && <RequiredMarker />}
</FieldLabel>
{widget}
</Field>
diff --git a/packages/dashboard/src/components/spree/products/product-custom-fields-provider.tsx b/packages/dashboard/src/components/spree/products/product-custom-fields-provider.tsx
index 8aeff3b0db..3b78b81e76 100644
--- a/packages/dashboard/src/components/spree/products/product-custom-fields-provider.tsx
+++ b/packages/dashboard/src/components/spree/products/product-custom-fields-provider.tsx
@@ -36,11 +36,22 @@ export function ProductCustomFieldsProvider<T extends CustomFieldsFormShape>({
[productType?.custom_field_definitions],
)
+ // Marks the fields the type calls required. Nothing rejects a blank one —
+ // the marker is the whole enforcement.
+ const requiredDefinitionIds = useMemo(
+ () =>
+ productType?.custom_field_definitions
+ ?.filter((definition) => definition.required)
+ .map((definition) => definition.id),
+ [productType?.custom_field_definitions],
+ )
+
return (
<FormBackedCustomFieldsProvider
form={form}
resourceType="Spree::Product"
definitionIds={definitionIds}
+ requiredDefinitionIds={requiredDefinitionIds}
>
{children}
</FormBackedCustomFieldsProvider>
diff --git a/packages/dashboard/src/locales/ar.json b/packages/dashboard/src/locales/ar.json
index 4a4628aec7..038d7a4158 100644
--- a/packages/dashboard/src/locales/ar.json
+++ b/packages/dashboard/src/locales/ar.json
@@ -329,6 +329,7 @@
"manage_in_settings": "الإدارة في الإعدادات",
"new_definition_description": "حدّد حقلاً مخصصاً لتخزين معلومات مكتوبة ومنظمة في {{resource}} الخاصة بك.",
"new_definition_title": "حقل مخصص جديد",
+ "required_hint": "موصى به من هذا النوع من المنتجات",
"section_title": "الحقول المخصصة",
"set_up": "إعداد الحقول المخصصة",
"values_save_partial_failed": "تعذّر حفظ بعض الحقول المخصصة: {{fields}}",
diff --git a/packages/dashboard/src/locales/de.json b/packages/dashboard/src/locales/de.json
index 0046cdaffa..cf10e63b7f 100644
--- a/packages/dashboard/src/locales/de.json
+++ b/packages/dashboard/src/locales/de.json
@@ -329,6 +329,7 @@
"manage_in_settings": "In den Einstellungen verwalten",
"new_definition_description": "Definieren Sie ein benutzerdefiniertes Feld, um typisierte, strukturierte Informationen zu Ihren {{resource}} zu speichern.",
"new_definition_title": "Neues benutzerdefiniertes Feld",
+ "required_hint": "Von diesem Produkttyp empfohlen",
"section_title": "Benutzerdefinierte Felder",
"set_up": "Benutzerdefinierte Felder einrichten",
"values_save_partial_failed": "Einige benutzerdefinierte Felder konnten nicht gespeichert werden: {{fields}}",
diff --git a/packages/dashboard/src/locales/en.json b/packages/dashboard/src/locales/en.json
index 68edb54605..3950607c34 100644
--- a/packages/dashboard/src/locales/en.json
+++ b/packages/dashboard/src/locales/en.json
@@ -329,6 +329,7 @@
"manage_in_settings": "Manage in settings",
"new_definition_description": "Define a custom field to store typed, structured information on your {{resource}}.",
"new_definition_title": "New custom field",
+ "required_hint": "Recommended by this product type",
"section_title": "Custom fields",
"set_up": "Set up custom fields",
"values_save_partial_failed": "Some custom fields could not be saved: {{fields}}",
diff --git a/packages/dashboard/src/locales/fr.json b/packages/dashboard/src/locales/fr.json
index 82d85c11c1..0fe629f31e 100644
--- a/packages/dashboard/src/locales/fr.json
+++ b/packages/dashboard/src/locales/fr.json
@@ -329,6 +329,7 @@
"manage_in_settings": "Gérer dans les paramètres",
"new_definition_description": "Définissez un champ personnalisé pour stocker des informations typées et structurées sur vos {{resource}}.",
"new_definition_title": "Nouveau champ personnalisé",
+ "required_hint": "Recommandé par ce type de produit",
"section_title": "Champs personnalisés",
"set_up": "Configurer les champs personnalisés",
"values_save_partial_failed": "Certains champs personnalisés n’ont pas pu être enregistrés : {{fields}}",
diff --git a/packages/dashboard/src/locales/pl.json b/packages/dashboard/src/locales/pl.json
index 7ddfd1dd6e..552bcc8861 100644
--- a/packages/dashboard/src/locales/pl.json
+++ b/packages/dashboard/src/locales/pl.json
@@ -335,6 +335,7 @@
"manage_in_settings": "Zarządzaj w ustawieniach",
"new_definition_description": "Zdefiniuj pole niestandardowe, aby przechowywać typowane, ustrukturyzowane informacje dla: {{resource}}.",
"new_definition_title": "Nowe pole niestandardowe",
+ "required_hint": "Zalecane przez ten typ produktu",
"section_title": "Pola niestandardowe",
"set_up": "Skonfiguruj pola niestandardowe",
"values_save_partial_failed": "Niektórych pól niestandardowych nie udało się zapisać: {{fields}}",
diff --git a/packages/dashboard/src/locales/zh-CN.json b/packages/dashboard/src/locales/zh-CN.json
index 898fc06112..6734cabc1c 100644
--- a/packages/dashboard/src/locales/zh-CN.json
+++ b/packages/dashboard/src/locales/zh-CN.json
@@ -329,6 +329,7 @@
"manage_in_settings": "在设置中管理",
"new_definition_description": "定义自定义字段,以在您的{{resource}}上存储有类型的结构化信息。",
"new_definition_title": "新建自定义字段",
+ "required_hint": "此商品类型建议填写",
"section_title": "自定义字段",
"set_up": "设置自定义字段",
"values_save_partial_failed": "部分自定义字段无法保存:{{fields}}",
diff --git a/packages/dashboard/src/routes/_authenticated/$storeId/settings/product-types.tsx b/packages/dashboard/src/routes/_authenticated/$storeId/settings/product-types.tsx
index 07ace0800f..8f0e4fcaf3 100644
--- a/packages/dashboard/src/routes/_authenticated/$storeId/settings/product-types.tsx
+++ b/packages/dashboard/src/routes/_authenticated/$storeId/settings/product-types.tsx
@@ -516,14 +516,18 @@ function CustomFieldDefinitionsEditor({ form }: { form: UseFormReturn<ProductTyp
() => new Map((definitions?.data ?? []).map((definition) => [definition.id, definition])),
[definitions?.data],
)
- const selectedIds = fieldArray.fields.map((row) => row.id)
- const selectedIdSet = new Set(selectedIds)
+ // `fieldArray.fields[].id` is React Hook Form's own row key, NOT our
+ // definition id — it overwrites any `id` in the row value. Read the
+ // definition ids from form state and keep the RHF key for React/dnd identity.
+ const rows = (form.watch('custom_field_definitions') ??
+ []) as ProductTypeFormValues['custom_field_definitions']
+ const selectedIdSet = new Set(rows.map((row) => row.id))
const available = [...definitionsById.values()].filter(
(definition) => !selectedIdSet.has(definition.id),
)
- const labelFor = (id: string) => {
- const definition = definitionsById.get(id)
- return definition?.label ?? definition?.key ?? id
+ const labelFor = (definitionId: string) => {
+ const definition = definitionsById.get(definitionId)
+ return definition?.label ?? definition?.key ?? definitionId
}
function handleDragEnd(event: DragEndEvent) {
@@ -544,13 +548,16 @@ function CustomFieldDefinitionsEditor({ form }: { form: UseFormReturn<ProductTyp
{fieldArray.fields.length > 0 && (
<DndContext sensors={sensors} collisionDetection={closestCenter} onDragEnd={handleDragEnd}>
- <SortableContext items={selectedIds} strategy={verticalListSortingStrategy}>
+ <SortableContext
+ items={fieldArray.fields.map((row) => row.id)}
+ strategy={verticalListSortingStrategy}
+ >
<div className="flex flex-col gap-1 rounded-md border p-2">
{fieldArray.fields.map((row, index) => (
<SortableCustomFieldRow
key={row.id}
sortableId={row.id}
- label={labelFor(row.id)}
+ label={labelFor(rows[index]?.id ?? '')}
form={form}
index={index}
onRemove={() => fieldArray.remove(index)}
diff --git a/spree/core/app/models/spree/product.rb b/spree/core/app/models/spree/product.rb
index 4cc548d225..769daf20e2 100644
--- a/spree/core/app/models/spree/product.rb
+++ b/spree/core/app/models/spree/product.rb
@@ -193,10 +193,6 @@ module Spree
validate :discontinue_on_must_be_later_than_make_active_at, if: -> { make_active_at && discontinue_on }
- # Activation only: a product type gaining a required field must never make
- # already-active products unsaveable.
- validate :required_custom_fields_present, if: :becoming_active?
-
scope :for_store, ->(store) { where(store_id: store.id) }
scope :draft, -> { where(status: 'draft') }
scope :archived, -> { where(status: 'archived') }
@@ -851,43 +847,6 @@ module Spree
association(:default_variant).reset
end
- # Activation of an existing product only. Creation is excluded on purpose:
- # importers and API clients routinely save the product first and attach its
- # custom fields immediately after, so a new record has no fair chance to
- # carry them yet. The guard still fires the moment anyone activates a
- # product that is missing required fields.
- def becoming_active?
- active? && !new_record? && status_changed?
- end
-
- def required_custom_fields_present
- return if product_type.blank?
-
- required = product_type.product_type_custom_field_definitions.required.
- joins(:custom_field_definition).pluck(:custom_field_definition_id, :name)
- return if required.empty?
-
- filled_definition_ids = filled_custom_field_definition_ids
-
- required.each do |definition_id, name|
- next if filled_definition_ids.include?(definition_id)
-
- errors.add(:base, :missing_required_custom_field, name: name)
- end
- end
-
- # Reads from memory when the association is already loaded (nested writes in
- # the same save); otherwise asks the database for ids alone, since the
- # association eager-loads every definition it touches.
- def filled_custom_field_definition_ids
- if metafields.loaded?
- metafields.reject(&:marked_for_destruction?).
- filter_map { |metafield| metafield.metafield_definition_id if metafield.value.present? }.to_set
- else
- metafields.where.not(value: [nil, '']).pluck(:metafield_definition_id).to_set
- end
- end
-
# Additive, unlike the legacy prototype callback which replaced both sets —
# the type seeds the product when attached (creation, later assignment,
# reassignment) and never removes anything; detaching seeds nothing.
diff --git a/spree/core/config/locales/en.yml b/spree/core/config/locales/en.yml
index a2d956e878..acda43ee47 100644
--- a/spree/core/config/locales/en.yml
+++ b/spree/core/config/locales/en.yml
@@ -243,7 +243,6 @@ en:
errors:
messages:
blank: can't be blank
- missing_required_custom_field: 'Missing required custom field: %{name}'
must_apply_to_products: must be a custom field definition for products
unregistered_fulfillment_types: 'contains unregistered fulfillment types: %{types}'
models:
diff --git a/spree/core/spec/models/spree/product_spec.rb b/spree/core/spec/models/spree/product_spec.rb
index dd59d78460..c9348c93e0 100644
--- a/spree/core/spec/models/spree/product_spec.rb
+++ b/spree/core/spec/models/spree/product_spec.rb
@@ -504,73 +504,41 @@ describe Spree::Product, type: :model do
end
end
+ # Shopify mode: `required` on a type's custom field is guidance the dashboard
+ # surfaces, never a save-time rule. Spree writes a product and its custom
+ # fields in two steps (importers, API clients), so enforcing at save would
+ # reject the first of them — and enforcing later would break products whose
+ # type gained a required field after they were created.
describe 'required custom fields from the product type' do
let(:definition) { create(:custom_field_definition, name: 'Material') }
let(:product_type) { create(:product_type) }
- let(:product) { create(:product, product_type: product_type, status: 'draft') }
before do
create(:product_type_custom_field_definition, :required, product_type: product_type,
custom_field_definition: definition)
end
- it 'blocks activation while the field is missing' do
- product.status = 'active'
-
- expect(product).not_to be_valid
- expect(product.errors.full_messages.join).to include('Missing required custom field: Material')
- end
-
- it 'allows activation once the field has a value' do
- create(:metafield, resource: product, metafield_definition: definition, value: 'Cotton')
-
- product.reload.status = 'active'
-
- expect(product).to be_valid
- end
-
- it 'ignores optional fields' do
- product_type.product_type_custom_field_definitions.update_all(required: false)
-
- product.reload.status = 'active'
+ it 'does not block creating an active product with the field missing' do
+ product = build(:product, product_type: product_type, status: 'active')
expect(product).to be_valid
+ expect(product.save).to be(true)
end
- it 'leaves an already-active product saveable when the type gains a required field' do
- active_product = create(:product, product_type: create(:product_type), status: 'active')
- create(:product_type_custom_field_definition, :required, product_type: active_product.product_type,
- custom_field_definition: create(:custom_field_definition))
-
- active_product.reload.name = 'Renamed'
-
- expect(active_product).to be_valid
- expect(active_product.save).to be(true)
- end
-
- it 'ignores products without a type' do
- typeless = create(:product, product_type: nil, status: 'draft')
- typeless.status = 'active'
+ it 'does not block activating a product with the field missing' do
+ product = create(:product, product_type: product_type, status: 'draft')
- expect(typeless).to be_valid
- end
-
- # Importers and API clients save the product, then attach its custom fields.
- # Blocking creation would reject the first of those two writes.
- it 'allows an active product to be created before its fields are attached' do
- product = build(:product, product_type: product_type, status: 'active')
+ product.status = 'active'
expect(product).to be_valid
expect(product.save).to be(true)
end
- it 'still blocks a later activation of that product' do
- product = create(:product, product_type: product_type, status: 'active')
- product.update!(status: 'draft')
-
- product.status = 'active'
+ it 'keeps the flag readable so the dashboard can mark the field' do
+ join = product_type.product_type_custom_field_definitions.first
- expect(product).not_to be_valid
+ expect(join.required).to be(true)
+ expect(product_type.product_type_custom_field_definitions.required).to eq([join])
end
end