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.
Ruby b2b-commercee-commerceecommerceecommerce-apiecommerce-frameworkecommerce-platformheadlessheadless-commerceheadless-ecommercemarketplacemulti-tenantmulti-vendormulti-vendor-ecommerceopen-sourcespree-commerce
Let product types declare which custom fields their products need
Damian Legawiece4795033fee9
diff --git a/spree/core/app/models/spree/product.rb b/spree/core/app/models/spree/product.rbindex 84c50402a0..8263536ed2 100644--- a/spree/core/app/models/spree/product.rb+++ b/spree/core/app/models/spree/product.rb@@ -193,6 +193,10 @@ module Spreevalidate :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') }@@ -847,6 +851,27 @@ module Spreeassociation(:default_variant).resetend+ def becoming_active?+ active? && (new_record? || status_changed?)+ end++ def required_custom_fields_present+ return if product_type.blank?++ required_definitions = product_type.product_type_custom_field_definitions.required.+ includes(:custom_field_definition).map(&:custom_field_definition)+ return if required_definitions.empty?++ filled_definition_ids = metafields.reject(&:marked_for_destruction?).+ filter_map { |metafield| metafield.metafield_definition_id if metafield.value.present? }++ required_definitions.each do |definition|+ next if filled_definition_ids.include?(definition.id)++ errors.add(:base, :missing_required_custom_field, name: definition.name)+ 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/app/models/spree/product_type.rb b/spree/core/app/models/spree/product_type.rbindex 4dec80af5c..16fa32007b 100644--- a/spree/core/app/models/spree/product_type.rb+++ b/spree/core/app/models/spree/product_type.rb@@ -19,6 +19,11 @@ module Spreehas_many :product_type_categories, class_name: 'Spree::ProductTypeCategory', dependent: :destroyhas_many :categories, through: :product_type_categories, class_name: 'Spree::Category'+ has_many :product_type_custom_field_definitions, -> { ordered },+ class_name: 'Spree::ProductTypeCustomFieldDefinition', dependent: :destroy, inverse_of: :product_type+ has_many :custom_field_definitions, through: :product_type_custom_field_definitions,+ class_name: 'Spree::MetafieldDefinition'+# restrict, not nullify — removing a product's type (deletion included) would# invalidate its type-driven data, so types in use cannot be deletedhas_many :products, class_name: 'Spree::Product', dependent: :restrict_with_errordiff --git a/spree/core/app/models/spree/product_type_custom_field_definition.rb b/spree/core/app/models/spree/product_type_custom_field_definition.rbnew file mode 100644index 0000000000..c3cfa3abb3--- /dev/null+++ b/spree/core/app/models/spree/product_type_custom_field_definition.rb@@ -0,0 +1,29 @@+module Spree+ # Which custom field definitions a ProductType uses, whether each is required+ # before a product of that type can be activated, and the order the dashboard+ # renders them in. Read live by reference — no values are copied to products.+ class ProductTypeCustomFieldDefinition < Spree.base_class+ belongs_to :product_type, class_name: 'Spree::ProductType'+ # Association and column carry the 6.0 custom-field vocabulary; the class is+ # still named MetafieldDefinition until the rename wave lands.+ belongs_to :custom_field_definition, class_name: 'Spree::MetafieldDefinition'++ validates :product_type, :custom_field_definition, presence: true+ validates :custom_field_definition_id, uniqueness: { scope: :product_type_id }+ validate :custom_field_definition_applies_to_products++ scope :required, -> { where(required: true) }+ scope :ordered, -> { order(:sort_order, :id) }++ private++ # A type describes products, so a definition scoped to another resource+ # (Order, Customer) would render a field the product form can never fill.+ def custom_field_definition_applies_to_products+ return if custom_field_definition.blank?+ return if custom_field_definition.resource_type == 'Spree::Product'++ errors.add(:custom_field_definition, :must_apply_to_products)+ end+ end+enddiff --git a/spree/core/config/locales/en.yml b/spree/core/config/locales/en.ymlindex 543884a502..a2d956e878 100644--- a/spree/core/config/locales/en.yml+++ b/spree/core/config/locales/en.yml@@ -243,6 +243,8 @@ 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 productsunregistered_fulfillment_types: 'contains unregistered fulfillment types: %{types}'models:spree/allowed_origin:diff --git a/spree/core/db/migrate/20260806100001_create_spree_product_type_custom_field_definitions.rb b/spree/core/db/migrate/20260806100001_create_spree_product_type_custom_field_definitions.rbnew file mode 100644index 0000000000..2cf14b1761--- /dev/null+++ b/spree/core/db/migrate/20260806100001_create_spree_product_type_custom_field_definitions.rb@@ -0,0 +1,17 @@+class CreateSpreeProductTypeCustomFieldDefinitions < ActiveRecord::Migration[7.2]+ def change+ create_table :spree_product_type_custom_field_definitions do |t|+ t.references :product_type, null: false, index: false+ t.references :custom_field_definition, null: false+ t.boolean :required, null: false, default: false+ t.integer :sort_order, null: false, default: 0++ t.timestamps+ end++ add_index :spree_product_type_custom_field_definitions,+ [:product_type_id, :custom_field_definition_id],+ unique: true,+ name: 'idx_product_type_cf_defs_unique'+ end+enddiff --git a/spree/core/lib/spree/testing_support/factories/metafield_definition_factory.rb b/spree/core/lib/spree/testing_support/factories/metafield_definition_factory.rbindex f434e0226b..7b0aede110 100644--- a/spree/core/lib/spree/testing_support/factories/metafield_definition_factory.rb+++ b/spree/core/lib/spree/testing_support/factories/metafield_definition_factory.rb@@ -1,5 +1,5 @@FactoryBot.define do- factory :metafield_definition, class: 'Spree::MetafieldDefinition' do+ factory :metafield_definition, aliases: [:custom_field_definition], class: 'Spree::MetafieldDefinition' donamespace { 'custom' }sequence(:key) { |n| "custom_field_#{n}" }name { 'Custom Field' }diff --git a/spree/core/lib/spree/testing_support/factories/product_type_custom_field_definition_factory.rb b/spree/core/lib/spree/testing_support/factories/product_type_custom_field_definition_factory.rbnew file mode 100644index 0000000000..ca84e57514--- /dev/null+++ b/spree/core/lib/spree/testing_support/factories/product_type_custom_field_definition_factory.rb@@ -0,0 +1,10 @@+FactoryBot.define do+ factory :product_type_custom_field_definition, class: Spree::ProductTypeCustomFieldDefinition do+ product_type+ custom_field_definition++ trait :required do+ required { true }+ end+ end+enddiff --git a/spree/core/lib/spree/testing_support/factories/product_type_factory.rb b/spree/core/lib/spree/testing_support/factories/product_type_factory.rbindex b4d29f606d..02ab176ada 100644--- a/spree/core/lib/spree/testing_support/factories/product_type_factory.rb+++ b/spree/core/lib/spree/testing_support/factories/product_type_factory.rb@@ -1,6 +1,6 @@FactoryBot.define dofactory :product_type, aliases: [:prototype], class: Spree::ProductType do- name { 'Baseball Cap' }+ sequence(:name) { |n| "Baseball Cap #{n}" }store { Spree::Store.find_by(default: true) || association(:store) }enddiff --git a/spree/core/spec/models/spree/product_spec.rb b/spree/core/spec/models/spree/product_spec.rbindex da693a92ba..41d92d5193 100644--- a/spree/core/spec/models/spree/product_spec.rb+++ b/spree/core/spec/models/spree/product_spec.rb@@ -504,6 +504,58 @@ describe Spree::Product, type: :model doendend+ 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'++ expect(product).to be_valid+ 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'++ expect(typeless).to be_valid+ end+ end+describe 'assigning a product type to a persisted product' dolet(:size) { create(:option_type, name: 'size') }let(:color) { create(:option_type, name: 'color') }diff --git a/spree/core/spec/models/spree/product_type_custom_field_definition_spec.rb b/spree/core/spec/models/spree/product_type_custom_field_definition_spec.rbnew file mode 100644index 0000000000..3bd2c2dd9b--- /dev/null+++ b/spree/core/spec/models/spree/product_type_custom_field_definition_spec.rb@@ -0,0 +1,73 @@+require 'spec_helper'++RSpec.describe Spree::ProductTypeCustomFieldDefinition, type: :model do+ let(:product_type) { create(:product_type) }+ let(:definition) { create(:custom_field_definition) }++ describe 'validations' do+ it 'rejects a second row for the same definition' do+ create(:product_type_custom_field_definition, product_type: product_type, custom_field_definition: definition)+ duplicate = build(:product_type_custom_field_definition, product_type: product_type, custom_field_definition: definition)++ expect(duplicate).not_to be_valid+ expect(duplicate.errors[:custom_field_definition_id]).to be_present+ end++ it 'allows the same definition on another type' do+ create(:product_type_custom_field_definition, product_type: product_type, custom_field_definition: definition)+ other = build(:product_type_custom_field_definition, product_type: create(:product_type), custom_field_definition: definition)++ expect(other).to be_valid+ end++ it 'rejects a definition scoped to another resource' do+ order_definition = create(:custom_field_definition, :for_order)+ join = build(:product_type_custom_field_definition, product_type: product_type, custom_field_definition: order_definition)++ expect(join).not_to be_valid+ expect(join.errors[:custom_field_definition]).to include('must be a custom field definition for products')+ end+ end++ describe 'defaults' do+ it 'is optional and unsorted' do+ join = described_class.new++ expect(join.required).to be(false)+ expect(join.sort_order).to eq(0)+ end+ end++ describe 'scopes' do+ it '.required returns only required rows' do+ required = create(:product_type_custom_field_definition, :required, product_type: product_type)+ create(:product_type_custom_field_definition, product_type: product_type)++ expect(described_class.required).to eq([required])+ end++ it '.ordered sorts by sort_order' do+ second = create(:product_type_custom_field_definition, product_type: product_type, sort_order: 2)+ first = create(:product_type_custom_field_definition, product_type: product_type, sort_order: 1)++ expect(described_class.ordered).to eq([first, second])+ end+ end++ describe 'association from the product type' do+ it 'returns definitions in sort order' do+ later = create(:product_type_custom_field_definition, product_type: product_type, sort_order: 5)+ earlier = create(:product_type_custom_field_definition, product_type: product_type, sort_order: 1)++ expect(product_type.reload.custom_field_definitions).to eq(+ [earlier.custom_field_definition, later.custom_field_definition]+ )+ end++ it 'is destroyed with the product type' do+ create(:product_type_custom_field_definition, product_type: product_type)++ expect { product_type.destroy }.to change(described_class, :count).by(-1)+ end+ end+end