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.

New documentation website with Spree tutorial (#13304)

Damian Legawiec7ff485534194
diff --git a/admin/README.md b/admin/README.md
index cb4c9d0578..77072675b8 100644
--- a/admin/README.md
+++ b/admin/README.md
@@ -1,4 +1,21 @@
# Spree Admin Dashboard
-Welcome to the Spree Admin Dashboard repository. This is a new, shiny admin dashboard for Spree Commerce which will replace the old admin dashboard in Spree 5.0.
+Welcome to the Spree Admin Dashboard repository. This is a new, shiny admin dashboard for Spree Commerce 5.
+## Installation
+
+To install the Spree Admin Dashboard, run the following command:
+
+```bash
+bundle add spree_admin
+```
+
+Run the install generator:
+
+```bash
+bin/rails g spree:admin:install
+```
+
+This will create the necessary files for the admin dashboard.
+
+You will need to restart your web server and run `bin/dev` to start the development server for the admin dashboard.
\ No newline at end of file
diff --git a/docs/developer/admin/admin.mdx b/docs/developer/admin/admin.mdx
index 8044ada90b..0453bb3907 100644
--- a/docs/developer/admin/admin.mdx
+++ b/docs/developer/admin/admin.mdx
@@ -1,49 +1,236 @@
---
title: Admin Dashboard
sidebarTitle: Overview
+description: Learn how to customize and extend the Spree Admin Dashboard
---
-Spree Admin Dashboard is the main interface for managing your store. It's built with Ruby on Rails and is installable as a `spree_admin` gem. If you're using Spree Starter, this is already installed for you.
+The Spree Admin Dashboard is a full-featured administration interface for managing your e-commerce store. It's built with Ruby on Rails and ships as the `spree_admin` gem.
-## Overview
+<Frame>
+ <img src="/images/spree_admin_dashboard.png" alt="Spree Admin Dashboard" />
+</Frame>
-Admin Dashboard can be fully customized to your liking. You can extend the UI, include custom CSS and JavaScript, and you can add new sections to the dashboard or modify existing ones.
+## What You Can Do
-The basis of the admin dashboard is same as with any Ruby on Rails application:
+The Admin Dashboard allows store administrators to manage:
-## Templates (aka Views)
+- **Products** - Create and manage products, variants, images, and inventory
+- **Orders** - Process orders, refunds, and shipments
+- **Customers** - View customer accounts and order history
+- **Promotions** - Create discounts, coupon codes, and special offers
+- **Content** - Manage pages, menus, and blog posts
+- **Settings** - Configure store settings, shipping, taxes, and payments
-Views are the HTML templates that are used to generate the user interface. They are responsible for displaying the data to the user. Views use standard [Ruby on Rails ERB template system](https://guides.rubyonrails.org/action_view_overview.html#erb), eg.
+## Customization Options
+
+As a developer, you can fully customize the Admin Dashboard:
+
+<CardGroup cols={2}>
+ <Card title="Add New Sections" icon="plus" href="/developer/tutorial/admin">
+ Create entirely new admin pages for custom features like Brands, Vendors, or any custom model
+ </Card>
+ <Card title="Extend Existing UI" icon="puzzle-piece" href="/developer/admin/extending-ui">
+ Inject custom fields, buttons, and sections into existing admin pages
+ </Card>
+ <Card title="Custom Navigation" icon="bars" href="/developer/admin/navigation">
+ Add menu items to the sidebar or create custom navigation structures
+ </Card>
+ <Card title="Custom Styling" icon="palette" href="/developer/admin/custom-css">
+ Add your own CSS to match your brand or modify the look and feel
+ </Card>
+</CardGroup>
+
+## Architecture Overview
+
+Spree Admin follows standard Rails conventions with some Spree-specific patterns:
+
+```
+app/
+├── controllers/
+│ └── spree/
+│ └── admin/
+│ └── products_controller.rb # Your custom controllers
+├── views/
+│ └── spree/
+│ └── admin/
+│ └── products/
+│ ├── index.html.erb # List view
+│ ├── _form.html.erb # Shared form partial
+│ └── _table_row.html.erb # Table row partial
+├── helpers/
+│ └── spree/
+│ └── admin/
+│ └── products_helper.rb # View helpers
+└── assets/
+ └── stylesheets/
+ └── spree/
+ └── admin/
+ └── custom.css # Custom styles
+```
+
+## Key Concepts
+
+### Controllers
+
+Admin controllers inherit from `Spree::Admin::ResourceController` which provides:
+
+- Full CRUD operations (index, new, create, edit, update, destroy)
+- Automatic authorization checks
+- Flash messages and redirects
+- Search and filtering with Ransack
+
+```ruby
+# app/controllers/spree/admin/brands_controller.rb
+module Spree
+ module Admin
+ class BrandsController < ResourceController
+ # That's it! CRUD is handled automatically.
+ # Override methods only when needed.
+ end
+ end
+end
+```
+
+<Info>
+ Learn more about creating admin sections in the [Admin Dashboard Tutorial](/developer/tutorial/admin).
+</Info>
+
+### Views & Templates
+
+Views use standard Rails ERB templates with Spree's [Form Builder](/developer/admin/form-builder) and [Components](/developer/admin/components):
```erb
-<%# Example of a simple view %>
-<div>
- <h1>Welcome to the <%= current_store.name %></h1>
+<%# app/views/spree/admin/brands/_form.html.erb %>
+<div class="card mb-4">
+ <div class="card-header">
+ <h5 class="card-title"><%= Spree.t(:general_settings) %></h5>
+ </div>
+ <div class="card-body">
+ <%= f.spree_text_field :name, required: true %>
+ <%= f.spree_text_area :description %>
+ <%= f.spree_file_field :logo, width: 300, height: 300 %>
+ <%= f.spree_check_box :active %>
+ </div>
</div>
```
-In views you can use Ruby code and also helper methods defined in
+### JavaScript & Interactivity
-Spree Admin provides a way for you to inject your own templates into existing screens, eg. adding additional fields to forms or adding new navigation elements.
+Spree Admin uses [Hotwire](https://hotwire.dev/) (Turbo + Stimulus) for interactivity:
-## Controllers
+- **Turbo Drive** - Fast page navigation without full reloads
+- **Turbo Frames** - Update parts of the page independently
+- **Turbo Streams** - Real-time updates over WebSocket
+- **Stimulus** - Lightweight JavaScript controllers
-Controllers are the Ruby classes that handle requests from the user. They are responsible for processing the data and returning the appropriate response. Controllers use standard [Ruby on Rails controller system](https://guides.rubyonrails.org/action_controller_overview.html).
+```erb
+<%# Using Stimulus controllers %>
+<div data-controller="dropdown">
+ <button data-action="dropdown#toggle">Menu</button>
+ <div data-dropdown-target="menu">...</div>
+</div>
+```
-### Namespace
+<Info>
+ Add custom JavaScript using [Stimulus controllers](/developer/admin/custom-javascript).
+</Info>
-Every Admin controller should be placed in `Spree::Admin` namespace and [app/controllers/spree/admin](https://github.com/spree/spree/tree/main/admin/app/controllers/spree/admin) directory, eg. `Spree::Admin::ProductsController`.
+### Styling
-### BaseController
+The Admin Dashboard uses Bootstrap 5 with custom Spree styling. You can:
-The main Admin Controller is [Spree::Admin::BaseController](https://github.com/spree/spree/blob/main/admin/app/controllers/spree/admin/base_controller.rb). It provides a lot of functionality out of the box, such as authentication, authorization, and breadcrumbs.
+- Add custom CSS files
+- Override Bootstrap variables
+- Use Tailwind-style utility classes
-### ResourceController
+```css
+/* app/assets/stylesheets/spree/admin/custom.css */
+.my-custom-card {
+ border-radius: 12px;
+ box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
+}
+```
+
+<Info>
+ Learn how to add custom styles in [Custom CSS](/developer/admin/custom-css).
+</Info>
+
+## Quick Reference
+
+### Available Tools
+
+| Tool | Purpose | Documentation |
+|------|---------|---------------|
+| Form Builder | Create consistent forms with validation | [Form Builder](/developer/admin/form-builder) |
+| Components | Dropdowns, dialogs, icons, badges, etc. | [Components](/developer/admin/components) |
+| Helper Methods | Navigation, links, utilities | [Helper Methods](/developer/admin/helper-methods) |
+| UI Extensions | Inject content into existing pages | [Extending UI](/developer/admin/extending-ui) |
+
+### Common Tasks
+
+| Task | How To |
+|------|--------|
+| Add a new admin page | Use the scaffold generator: `bin/rails g spree:admin:scaffold Spree::Brand` |
+| Add sidebar navigation | Use `Spree.admin.navigation.sidebar.add` in an initializer |
+| Add form fields | Use `f.spree_text_field`, `f.spree_select`, etc. |
+| Show flash messages | They're automatic with `ResourceController` |
+| Check permissions | Use `can?(:update, @product)` in views |
+
+### Generator Commands
+
+```bash
+# Generate a complete admin section (controller, views, routes)
+bin/rails g spree:admin:scaffold Spree::Brand
-For easier and faster development Spree provides [Spree::Admin::ResourceController](https://github.com/spree/spree/blob/main/admin/app/controllers/spree/admin/resource_controller.rb) which provides all the necessary CRUD (Create, Read, Update, Delete) functionality for managing resources in a RESTful way so you can focus on building your application.
+# Generate just a controller
+bin/rails g controller Spree::Admin::Brands --skip-routes
+```
+
+## Authentication & Authorization
+
+### Authentication
+
+Admin users must be authenticated to access the dashboard. Spree supports:
+
+- Built-in Devise authentication
+- Custom authentication adapters
+- SSO integration
-You will learn more about this in the [Creating new Admin sections guide](/developer/admin/new-admin-sections).
+<Info>
+ See [Authentication](/developer/admin/authentication) for setup details.
+</Info>
-## JavaScript
+### Authorization
+
+Spree uses [CanCanCan](https://github.com/CanCanCommunity/cancancan) for authorization:
+
+```ruby
+# Check permissions in controllers
+authorize! :update, @product
+
+# Check permissions in views
+<% if can?(:destroy, @product) %>
+ <%= link_to_delete(@product) %>
+<% end %>
+```
-Interactitivy in Spree Admin is handled by [Hotwire](https://hotwire.dev/) which is the default Ruby on Rails frontend framework. JavaScript bundling is done via [Importmaps](https://github.com/rails/importmap-rails), which is a modern JavaScript bundling solution that is easy to use and integrates well with Rails. Also, it doesn't require node at all.
+<Info>
+ See [Permissions](/developer/admin/permissions) for defining custom abilities.
+</Info>
+
+## Next Steps
+
+<CardGroup cols={2}>
+ <Card title="Tutorial: Build Admin UI" icon="graduation-cap" href="/developer/tutorial/admin">
+ Step-by-step guide to creating a complete admin section
+ </Card>
+ <Card title="Form Builder" icon="rectangle-list" href="/developer/admin/form-builder">
+ Learn all available form field helpers
+ </Card>
+ <Card title="Components" icon="puzzle-piece" href="/developer/admin/components">
+ Explore UI components like dropdowns, dialogs, and icons
+ </Card>
+ <Card title="Extending UI" icon="expand" href="/developer/admin/extending-ui">
+ Add custom content to existing admin pages
+ </Card>
+</CardGroup>
diff --git a/docs/developer/admin/authentication.mdx b/docs/developer/admin/authentication.mdx
index a1a07e4b9e..a86453ca9b 100644
--- a/docs/developer/admin/authentication.mdx
+++ b/docs/developer/admin/authentication.mdx
@@ -4,7 +4,8 @@ sidebarTitle: Authentication
description: How to customize the Spree admin panel authentication
---
-By default Spree uses the same model for the admin panel as the storefront. However you can customize it to use a different model.
+Spree allows you to use a different model for the admin panel than the storefront (that's the default since Spree 5.2).
+Here you can find how to customize the admin panel authentication to use a different model.
Let's assume you have an existing `AdminUser` model in your application and you're using Devise for authentication.
diff --git a/docs/developer/admin/components.mdx b/docs/developer/admin/components.mdx
new file mode 100644
index 0000000000..972a17e118
--- /dev/null
+++ b/docs/developer/admin/components.mdx
@@ -0,0 +1,725 @@
+---
+title: Admin Components
+sidebarTitle: Components
+---
+
+Spree Admin provides a set of reusable UI components that you can use in your custom admin views. These components are implemented as view helpers and integrate with Stimulus controllers for interactivity.
+
+## Dropdown
+
+The dropdown component creates accessible dropdown menus with automatic positioning using Floating UI.
+
+### Basic Usage
+
+```erb
+<%= dropdown do %>
+ <%= dropdown_toggle class: 'btn-light btn-sm' do %>
+ <%= icon('dots-vertical', class: 'mr-0') %>
+ <% end %>
+
+ <%= dropdown_menu do %>
+ <%= link_to_with_icon 'pencil', Spree.t(:edit), edit_path, class: 'dropdown-item' %>
+ <%= link_to_with_icon 'trash', Spree.t(:delete), delete_path,
+ class: 'dropdown-item text-danger',
+ data: { turbo_method: :delete, turbo_confirm: Spree.t(:are_you_sure) } %>
+ <% end %>
+<% end %>
+```
+
+### Features
+
+- **Automatic positioning** - Uses Floating UI to position the menu optimally
+- **Auto-flip** - Menu flips to stay within viewport
+- **Click outside to close** - Menu closes when clicking outside
+- **Escape to close** - Menu closes when pressing Escape key
+- **Keyboard navigation** - Full keyboard accessibility
+
+### `dropdown`
+
+Creates the dropdown container with Stimulus controller.
+
+```erb
+<%= dropdown do %>
+ <!-- toggle and menu -->
+<% end %>
+
+<%= dropdown placement: 'top-end' do %>
+ <!-- menu opens above, aligned to end -->
+<% end %>
+```
+
+| Option | Type | Default | Description |
+|--------|------|---------|-------------|
+| `class` | String | - | Additional CSS classes |
+| `placement` | String | `bottom-start` | Menu placement: `bottom-start`, `bottom-end`, `top-start`, `top-end` |
+| `direction` | String | - | Legacy option: `left` → `bottom-end`, `top` → `top-start`, `top-left` → `top-end` |
+| `portal` | Boolean | - | Whether to portal the dropdown to body |
+| `data` | Hash | - | Additional data attributes |
+
+### `dropdown_toggle`
+
+Creates the button that toggles the dropdown menu.
+
+```erb
+<%= dropdown_toggle class: 'btn-primary' do %>
+ Actions <%= icon('chevron-down', class: 'ml-2') %>
+<% end %>
+```
+
+| Option | Type | Default | Description |
+|--------|------|---------|-------------|
+| `class` | String | - | Additional CSS classes (added to `btn` base class) |
+| `data` | Hash | - | Additional data attributes |
+
+### `dropdown_menu`
+
+Creates the menu container for dropdown items.
+
+```erb
+<%= dropdown_menu do %>
+ <%= link_to 'Option 1', '#', class: 'dropdown-item' %>
+ <div class="dropdown-divider"></div>
+ <%= link_to 'Option 2', '#', class: 'dropdown-item text-danger' %>
+<% end %>
+```
+
+| Option | Type | Default | Description |
+|--------|------|---------|-------------|
+| `class` | String | - | Additional CSS classes |
+| `data` | Hash | - | Additional data attributes |
+
+### Complete Example
+
+```erb
+<%= content_for :page_actions do %>
+ <%= dropdown do %>
+ <%= dropdown_toggle class: 'btn-primary' do %>
+ <%= icon('settings', class: 'mr-2') %>
+ Actions
+ <%= icon('chevron-down', class: 'ml-2') %>
+ <% end %>
+
+ <%= dropdown_menu do %>
+ <%= link_to_with_icon 'download', 'Export CSV', export_path(format: :csv), class: 'dropdown-item' %>
+ <%= link_to_with_icon 'file-export', 'Export Excel', export_path(format: :xlsx), class: 'dropdown-item' %>
+ <div class="dropdown-divider"></div>
+ <%= link_to_with_icon 'upload', 'Import', import_path, class: 'dropdown-item' %>
+ <div class="dropdown-divider"></div>
+ <%= link_to_with_icon 'trash', 'Delete All', bulk_delete_path,
+ class: 'dropdown-item text-danger',
+ data: { turbo_method: :delete, turbo_confirm: Spree.t(:are_you_sure) } %>
+ <% end %>
+ <% end %>
+<% end %>
+```
+
+## Dialog
+
+Dialogs (modals) are used for focused interactions that require user attention. They overlay the page content and must be dismissed before continuing.
+
+### Basic Usage
+
+```erb
+<div class="dialog" data-controller="dialog">
+ <%= dialog_header('Edit Product') %>
+
+ <div class="dialog-body">
+ <!-- Dialog content -->
+ </div>
+
+ <div class="dialog-footer">
+ <%= dialog_discard_button %>
+ <%= turbo_save_button_tag %>
+ </div>
+</div>
+```
+
+### `dialog_header`
+
+Creates a dialog header with title and close button.
+
+```erb
+<%= dialog_header('Confirm Action') %>
+<%= dialog_header('Custom Dialog', 'my-dialog') %>
+```
+
+| Parameter | Type | Default | Description |
+|-----------|------|---------|-------------|
+| `title` | String | required | The dialog title |
+| `controller_name` | String | `dialog` | Stimulus controller name for the close action |
+
+**Renders:**
+
+```html
+<div class="dialog-header">
+ <h5 class="dialog-title">Confirm Action</h5>
+ <button type="button" class="btn-close" data-action="dialog#close" data-dismiss="dialog"></button>
+</div>
+```
+
+### `dialog_close_button`
+
+Creates a standalone close button for dialogs.
+
+```erb
+<%= dialog_close_button %>
+<%= dialog_close_button('custom-controller') %>
+```
+
+| Parameter | Type | Default | Description |
+|-----------|------|---------|-------------|
+| `controller_name` | String | `dialog` | Stimulus controller name |
+
+### `dialog_discard_button`
+
+Creates a "Discard" button that closes the dialog.
+
+```erb
+<%= dialog_discard_button %>
+```
+
+| Parameter | Type | Default | Description |
+|-----------|------|---------|-------------|
+| `controller_name` | String | `dialog` | Stimulus controller name |
+
+**Renders:**
+
+```html
+<button type="button" class="btn btn-light" data-action="dialog#close" data-dismiss="dialog">
+ Discard
+</button>
+```
+
+### Complete Dialog Example
+
+```erb
+<%= turbo_frame_tag 'main-dialog' do %>
+ <div class="dialog-backdrop" data-controller="dialog" data-action="click->dialog#backdropClose keydown.esc@window->dialog#close">
+ <div class="dialog">
+ <%= dialog_header('Add New Item') %>
+
+ <%= form_with model: @item, url: items_path, data: { turbo_frame: '_top' } do |f| %>
+ <div class="dialog-body">
+ <%= f.spree_text_field :name, required: true %>
+ <%= f.spree_text_area :description %>
+ </div>
+
+ <div class="dialog-footer">
+ <%= dialog_discard_button %>
+ <%= turbo_save_button_tag 'Create Item' %>
+ </div>
+ <% end %>
+ </div>
+ </div>
+<% end %>
+```
+
+## Drawer
+
+Drawers are slide-out panels typically used for filters, secondary forms, or detailed views without leaving the current page.
+
+### Basic Usage
+
+```erb
+<div class="drawer" data-controller="drawer">
+ <%= drawer_header('Filter Options') %>
+
+ <div class="drawer-body">
+ <!-- Drawer content -->
+ </div>
+
+ <div class="drawer-footer">
+ <%= drawer_discard_button %>
+ <button type="submit" class="btn btn-primary">Apply Filters</button>
+ </div>
+</div>
+```
+
+### `drawer_header`
+
+Creates a drawer header with title and close button.
+
+```erb
+<%= drawer_header('Filters') %>
+<%= drawer_header('Details', 'custom-drawer') %>
+```
+
+| Parameter | Type | Default | Description |
+|-----------|------|---------|-------------|
+| `title` | String | required | The drawer title |
+| `controller_name` | String | `drawer` | Stimulus controller name for the close action |
+
+**Renders:**
+
+```html
+<div class="drawer-header">
+ <h5 class="drawer-title">Filters</h5>
+ <button type="button" class="btn-close" data-action="drawer#close" data-dismiss="drawer"></button>
+</div>
+```
+
+### `drawer_close_button`
+
+Creates a standalone close button for drawers.
+
+```erb
+<%= drawer_close_button %>
+<%= drawer_close_button('custom-drawer') %>
+```
+
+| Parameter | Type | Default | Description |
+|-----------|------|---------|-------------|
+| `controller_name` | String | `drawer` | Stimulus controller name |
+
+### `drawer_discard_button`
+
+Creates a "Discard" button that closes the drawer.
+
+```erb
+<%= drawer_discard_button %>
+```
+
+| Parameter | Type | Default | Description |
+|-----------|------|---------|-------------|
+| `controller_name` | String | `drawer` | Stimulus controller name |
+
+## Icon
+
+Icons are rendered using the [Tabler Icons](https://tabler.io/icons) library.
+
+### Basic Usage
+
+```erb
+<%= icon('package') %>
+<%= icon('shopping-cart', class: 'text-primary') %>
+<%= icon('check', class: 'text-success', height: 24) %>
+```
+
+### Options
+
+| Option | Type | Default | Description |
+|--------|------|---------|-------------|
+| `class` | String | - | Additional CSS classes |
+| `height` | Integer | - | Icon size in pixels |
+| `style` | String | - | Additional inline styles |
+
+### Output
+
+```html
+<i class="ti ti-package"></i>
+<i class="ti ti-shopping-cart text-primary"></i>
+<i class="ti ti-check text-success" style="font-size: 24px !important;"></i>
+```
+
+### Legacy Icon Names
+
+For backwards compatibility, legacy icon names are automatically translated:
+
+| Legacy Name | Tabler Icon |
+|-------------|-------------|
+| `save` | `device-floppy` |
+| `edit` | `pencil` |
+| `delete` | `trash` |
+| `add` | `plus` |
+| `cancel` | `x` |
+
+### Common Icons
+
+| Icon | Name | Usage |
+|------|------|-------|
+| <i class="ti ti-pencil"></i> | `pencil` | Edit actions |
+| <i class="ti ti-trash"></i> | `trash` | Delete actions |
+| <i class="ti ti-plus"></i> | `plus` | Add/create actions |
+| <i class="ti ti-eye"></i> | `eye` | View/preview |
+| <i class="ti ti-download"></i> | `download` | Download/export |
+| <i class="ti ti-upload"></i> | `upload` | Upload/import |
+| <i class="ti ti-check"></i> | `check` | Success/confirm |
+| <i class="ti ti-x"></i> | `x` | Close/cancel |
+| <i class="ti ti-dots-vertical"></i> | `dots-vertical` | More options |
+| <i class="ti ti-chevron-down"></i> | `chevron-down` | Expand |
+| <i class="ti ti-chevron-right"></i> | `chevron-right` | Navigate |
+
+## Image
+
+Displays optimized images with automatic WebP conversion and retina support.
+
+### Basic Usage
+
+```erb
+<%= spree_image_tag(product.images.first, width: 100, height: 100) %>
+<%= spree_image_tag(current_store.logo, width: 200, height: 60) %>
+<%= spree_image_tag(taxon.image, width: 400, height: 300, class: 'rounded') %>
+```
+
+### Options
+
+| Option | Type | Default | Description |
+|--------|------|---------|-------------|
+| `image` | Asset/Attachment | required | `Spree::Asset` or ActiveStorage attachment |
+| `width` | Integer | - | Display width in pixels |
+| `height` | Integer | - | Display height in pixels |
+| `class` | String | - | CSS classes |
+| `alt` | String | - | Alt text for accessibility |
+| `loading` | Symbol | - | `:lazy` or `:eager` |
+
+### Features
+
+- **Retina support** - Automatically scales dimensions by 2x for sharp display
+- **WebP conversion** - Outputs optimized WebP format
+- **Smart cropping** - When both dimensions provided, crops to fill
+- **Aspect ratio preservation** - When one dimension provided, maintains ratio
+
+### Examples
+
+```erb
+<%# Product thumbnail in index table %>
+<% if product.images.any? %>
+ <%= spree_image_tag product.images.first, width: 48, height: 48, class: 'rounded' %>
+<% else %>
+ <div class="bg-light rounded d-flex align-items-center justify-content-center" style="width: 48px; height: 48px;">
+ <%= icon('photo-off', class: 'text-muted') %>
+ </div>
+<% end %>
+
+<%# Store logo in header %>
+<%= spree_image_tag current_store.logo, width: 120, height: 40, alt: current_store.name %>
+
+<%# Category image %>
+<%= spree_image_tag taxon.image, width: 300, height: 200, class: 'card-img-top' %>
+```
+
+### With Placeholder
+
+```erb
+<% if @brand.logo.attached? %>
+ <%= spree_image_tag @brand.logo, width: 100, height: 100 %>
+<% else %>
+ <div class="placeholder-image">
+ <%= icon('photo') %>
+ </div>
+<% end %>
+```
+
+<Info>
+ For comprehensive documentation on image handling, storage configuration, and best practices, see the [Images & Assets](/developer/core-concepts/images-assets) guide.
+</Info>
+
+## Tooltip
+
+Tooltips provide additional context on hover.
+
+### Basic Usage
+
+```erb
+<span data-controller="tooltip">
+ <%= icon('info-circle') %>
+ <%= tooltip('This is helpful information') %>
+</span>
+```
+
+### `tooltip`
+
+Creates a tooltip container.
+
+```erb
+<%= tooltip('Simple text tooltip') %>
+
+<%= tooltip do %>
+ <strong>Rich content</strong> with <em>formatting</em>
+<% end %>
+```
+
+| Parameter | Type | Description |
+|-----------|------|-------------|
+| `text` | String | Tooltip text (or use block for rich content) |
+
+### `help_bubble`
+
+Creates an info icon with a tooltip - commonly used for form field hints.
+
+```erb
+<%= help_bubble('This field is used for SEO optimization') %>
+<%= help_bubble('Shown below the field', 'bottom') %>
+<%= help_bubble('Custom styled', 'top', css: 'text-primary') %>
+```
+
+| Parameter | Type | Default | Description |
+|-----------|------|---------|-------------|
+| `text` | String | required | Tooltip text |
+| `placement` | String | `top` | Tooltip position: `top`, `bottom`, `left`, `right` |
+| `css` | String | `text-xs text-muted...` | CSS classes for the icon |
+
+**Output:**
+
+```html
+<span data-controller="tooltip" data-tooltip-placement-value="top">
+ <i class="ti ti-info-square-rounded text-xs text-muted cursor-default opacity-75"></i>
+ <span role="tooltip" data-tooltip-target="tooltip" class="tooltip-container">
+ This field is used for SEO optimization
+ </span>
+</span>
+```
+
+## Active Badge
+
+Displays a status badge indicating active/inactive state.
+
+### Basic Usage
+
+```erb
+<%= active_badge(product.active?) %>
+<%= active_badge(user.confirmed?) %>
+<%= active_badge(order.paid?, label: 'Paid') %>
+```
+
+### Options
+
+| Option | Type | Default | Description |
+|--------|------|---------|-------------|
+| `condition` | Boolean | required | The condition to evaluate |
+| `label` | String | Yes/No | Custom label text |
+
+### Output
+
+When condition is `true`:
+
+```html
+<span class="badge badge-active">
+ <i class="ti ti-check"></i> Yes
+</span>
+```
+
+When condition is `false`:
+
+```html
+<span class="badge badge-inactive">No</span>
+```
+
+### Custom Labels
+
+```erb
+<%= active_badge(subscription.active?, label: subscription.active? ? 'Active' : 'Expired') %>
+<%= active_badge(feature.enabled?, label: feature.enabled? ? 'Enabled' : 'Disabled') %>
+```
+
+## Avatar
+
+Renders a user avatar with automatic fallback to initials.
+
+### Basic Usage
+
+```erb
+<%= render_avatar(current_user) %>
+<%= render_avatar(user, width: 48, height: 48) %>
+<%= render_avatar(admin, class: 'avatar-lg') %>
+```
+
+### Options
+
+| Option | Type | Default | Description |
+|--------|------|---------|-------------|
+| `user` | Object | required | User object (must respond to `avatar` and `name`) |
+| `width` | Integer | 128 | Avatar width in pixels |
+| `height` | Integer | 128 | Avatar height in pixels |
+| `class` | String | `avatar` | CSS classes |
+
+### Behavior
+
+1. If user has an attached avatar image → displays the image
+2. Otherwise → displays user's initials on a colored background
+
+```erb
+<!-- With avatar image -->
+<img src="avatar.jpg" class="avatar" style="width: 128px; height: 128px;">
+
+<!-- Without avatar (fallback) -->
+<div class="avatar" style="width: 128px; height: 128px;">JD</div>
+```
+
+## Clipboard
+
+Copy-to-clipboard functionality with visual feedback.
+
+### Basic Usage
+
+```erb
+<%= clipboard_component(product.sku) %>
+<%= clipboard_component(api_key) %>
+```
+
+### `clipboard_component`
+
+Creates a complete clipboard component with hidden input and copy button.
+
+```erb
+<%= clipboard_component('ABC-123-XYZ') %>
+```
+
+| Parameter | Type | Description |
+|-----------|------|-------------|
+| `text` | String | The text to copy |
+
+**Output:**
+
+```html
+<span data-controller="clipboard" data-clipboard-success-content-value="<i class='ti ti-check mr-0 font-size-sm'></i>">
+ <input type="hidden" name="clipboard_source" value="ABC-123-XYZ" data-clipboard-target="source">
+ <button type="button" class="btn btn-clipboard" data-action="clipboard#copy" data-clipboard-target="button">
+ <i class="ti ti-copy mr-0 font-size-sm"></i>
+ <span role="tooltip" data-tooltip-target="tooltip" class="tooltip-container">Copy to clipboard</span>
+ </button>
+</span>
+```
+
+### `clipboard_button`
+
+Creates just the copy button (for custom layouts).
+
+```erb
+<div data-controller="clipboard">
+ <input type="text" data-clipboard-target="source" value="custom-value">
+ <%= clipboard_button %>
+</div>
+```
+
+### Inline with Text
+
+```erb
+<div class="d-flex align-items-center gap-2">
+ <code><%= product.sku %></code>
+ <%= clipboard_component(product.sku) %>
+</div>
+```
+
+## Progress Bar
+
+Displays a progress bar with customizable range.
+
+### Basic Usage
+
+```erb
+<%= progress_bar_component(75) %>
+<%= progress_bar_component(150, max: 200) %>
+<%= progress_bar_component(50, min: 0, max: 100) %>
+```
+
+### Options
+
+| Option | Type | Default | Description |
+|--------|------|---------|-------------|
+| `value` | Integer | required | Current progress value |
+| `min` | Integer | 0 | Minimum value |
+| `max` | Integer | 100 | Maximum value |
+
+### Output
+
+```html
+<div class="progress">
+ <div class="progress-bar"
+ role="progressbar"
+ style="width: 75%"
+ aria-valuenow="75"
+ aria-valuemin="0"
+ aria-valuemax="100">
+ </div>
+</div>
+```
+
+### Examples
+
+```erb
+<!-- Inventory level -->
+<%= progress_bar_component(stock_item.count_on_hand, max: stock_item.backorderable_threshold || 100) %>
+
+<!-- Order fulfillment -->
+<%= progress_bar_component(order.shipments.shipped.count, max: order.shipments.count) %>
+
+<!-- Upload progress -->
+<%= progress_bar_component(uploaded_count, max: total_count) %>
+```
+
+## Date & Time
+
+Helpers for displaying dates and times in the user's local timezone.
+
+### `spree_date`
+
+Renders a date in the user's local format.
+
+```erb
+<%= spree_date(order.created_at) %>
+<%= spree_date(product.available_on) %>
+```
+
+### `spree_time`
+
+Renders a date and time in the user's local format.
+
+```erb
+<%= spree_time(order.completed_at) %>
+<%= spree_time(shipment.shipped_at) %>
+```
+
+### `spree_time_ago`
+
+Renders a relative time (e.g., "2 hours ago") with a tooltip showing the full timestamp.
+
+```erb
+<%= spree_time_ago(order.completed_at) %>
+<%= spree_time_ago(comment.created_at) %>
+```
+
+**Output:**
+
+```html
+<span data-controller="tooltip">
+ <time datetime="2024-01-15T10:30:00Z" data-local="time-ago">2 hours ago</time>
+ <span role="tooltip" data-tooltip-target="tooltip" class="tooltip-container">
+ January 15, 2024 10:30 AM
+ </span>
+</span>
+```
+
+### `local_time`
+
+The underlying helper from [local_time gem](https://github.com/basecamp/local_time) - displays time in user's browser timezone.
+
+```erb
+<%= local_time(order.completed_at) %>
+<%= local_time(event.starts_at, format: '%B %e, %Y at %l:%M %p') %>
+```
+
+### Comparison
+
+| Helper | Output | Use Case |
+|--------|--------|----------|
+| `spree_date` | "Jan 15, 2024" | Date-only display |
+| `spree_time` | "Jan 15, 2024 10:30 AM" | Full timestamp |
+| `spree_time_ago` | "2 hours ago" | Relative time with tooltip |
+| `local_time` | "January 15, 2024 10:30 AM" | Customizable format |
+
+## Best Practices
+
+<Check>
+ **Use semantic components** - Choose the right component for the interaction (Dialog for focused tasks, Drawer for contextual panels)
+</Check>
+
+<Check>
+ **Provide feedback** - Use tooltips and badges to give users context about their actions
+</Check>
+
+<Check>
+ **Keep dropdowns focused** - Limit dropdown menus to related actions, use dividers to group items
+</Check>
+
+<Check>
+ **Use appropriate icons** - Choose icons that clearly represent the action
+</Check>
+
+<Check>
+ **Handle loading states** - Use `turbo_save_button_tag` for forms to show loading feedback
+</Check>
+
+<Check>
+ **Consider accessibility** - Components include ARIA attributes and keyboard navigation
+</Check>
diff --git a/docs/developer/admin/custom-css.mdx b/docs/developer/admin/custom-css.mdx
index a7e7eecf98..07e5f474a7 100644
--- a/docs/developer/admin/custom-css.mdx
+++ b/docs/developer/admin/custom-css.mdx
@@ -42,16 +42,25 @@ Besides SASS you can still include standard CSS files. To do so:
touch app/views/spree/admin/shared/custom_spree_admin_stylesheets.html.erb
```
-4. Use standard Ruby on Rails [stylesheet_link_tag](https://api.rubyonrails.org/v7.2/classes/ActionView/Helpers/AssetTagHelper.html#method-i-stylesheet_link_tag)
+4. Use standard Ruby on Rails [stylesheet_link_tag](https://api.rubyonrails.org/v8.0/classes/ActionView/Helpers/AssetTagHelper.html#method-i-stylesheet_link_tag)
- ```erb
+ ```erb app/views/spree/admin/shared/custom_spree_admin_stylesheets.html.erb
<%= stylesheet_link_tag 'custom_spree_admin' %>
```
5. Register this template in the Spree initializer (`config/initializers/spree.rb`):
- ```ruby
- Rails.application.config.spree_admin.head_partials << 'spree/admin/shared/custom_spree_admin_stylesheets'
- ```
-
-That's it! Now you're custom CSS code will be included after loading the standard Admin stylesheets.
+ <Tabs>
+ <Tab title="Spree 5.2+">
+ ```ruby config/initializers/spree.rb
+ Spree.admin.partials.head << 'spree/admin/shared/custom_spree_admin_stylesheets'
+ ```
+ </Tab>
+ <Tab title="Spree 5.1 and below">
+ ```ruby config/initializers/spree.rb
+ Rails.application.config.spree_admin.head_partials << 'spree/admin/shared/custom_spree_admin_stylesheets'
+ ```
+ </Tab>
+ </Tabs>
+
+That's it! Now your custom CSS code will be included after loading the standard Admin stylesheets.
diff --git a/docs/developer/admin/custom-javascript.mdx b/docs/developer/admin/custom-javascript.mdx
index 5db8c3209e..a2c5844ba8 100644
--- a/docs/developer/admin/custom-javascript.mdx
+++ b/docs/developer/admin/custom-javascript.mdx
@@ -94,9 +94,18 @@ If you need to add a small piece of JavaScript code (eg. tracking, marketing, an
1. Declaring a new head partial in the `config/initializers/spree.rb` file, eg.
- ```ruby
- Rails.application.config.spree_admin.head_partials << 'spree/admin/shared/my_tracking_code'
- ```
+ <Tabs>
+ <Tab title="Spree 5.2+">
+ ```ruby config/initializers/spree.rb
+ Spree.admin.partials.head << 'spree/admin/shared/my_tracking_code'
+ ```
+ </Tab>
+ <Tab title="Spree 5.1 and below">
+ ```ruby config/initializers/spree.rb
+ Rails.application.config.spree_admin.head_partials << 'spree/admin/shared/my_tracking_code'
+ ```
+ </Tab>
+ </Tabs>
2. Creating a new file in the `app/views/spree/admin/shared/my_tracking_code.html.erb`, where you can add your tracking code, eg.
diff --git a/docs/developer/admin/extending-ui.mdx b/docs/developer/admin/extending-ui.mdx
index 4661e00c03..34f8b58c59 100644
--- a/docs/developer/admin/extending-ui.mdx
+++ b/docs/developer/admin/extending-ui.mdx
@@ -7,7 +7,7 @@ Spree Admin Dashboard allows you easily extend existing pages and screens with y
## How it works
-The entire system works on the basis of injection points which are declared throughout the admin dashboard and allows you to push your own code there. Each injection point is identified by a key, eg. `body_end_partials`.
+The entire system works on the basis of injection points which are declared throughout the admin dashboard and allows you to push your own code there. Each injection point is identified by a key, eg. `body_end`.
Let's say you want to add a new footer to the admin dashboard. You'll need to generate a template in your application:
@@ -33,16 +33,30 @@ Let's say you want to add a new footer to the admin dashboard. You'll need to ge
4. Register your partial in `config/initializers/spree.rb`
- ```ruby
- Rails.application.config.spree_admin.body_end_partials << 'spree/admin/shared/additional_footer'
- ```
+ <Tabs>
+ <Tab title="Spree 5.2+">
+ ```ruby config/initializers/spree.rb
+ Spree.admin.partials.body_end << 'spree/admin/shared/additional_footer'
+ ```
+ </Tab>
+ <Tab title="Spree 5.1 and below">
+ ```ruby config/initializers/spree.rb
+ Rails.application.config.spree_admin.body_end << 'spree/admin/shared/additional_footer_partials'
+ ```
+
+ <Warning>
+ For older versions of Spree you need to add `_partials` suffix for all injection points,
+ eg. `body_end_partials` instead of `body_end`.
+ </Warning>
+ </Tab>
+ </Tabs>
<Info>
- The key is the name of the injection point, eg. `body_end_partials`.
+ The key is the name of the injection point, eg. `body_end`.
</Info>
<Info>
- Remember to use the correct path to your partial and skip the `_` prefix.
+ Remember to use the correct path to your template file and skip the `_` prefix.
</Info>
5. Restart your web server and you should see your new footer.
@@ -56,10 +70,59 @@ Let's say you want to add a new footer to the admin dashboard. You'll need to ge
</Info>
<Hint>
- To summarize, we're injecting our code into the `body_end_partials` array. This is a list of partials that will be rendered at the end of the body tag (before the closing `</body>` tag). The order of the partials in the array is the order in which they will be rendered.
+ To summarize, we're injecting our code into the `body_end` array. This is a list of partials that will be rendered at the end of the body tag (before the closing `</body>` tag). The order of the partials in the array is the order in which they will be rendered.
</Hint>
-## Admin Dashboard injection points
+## Partials API
+
+The `Spree.admin.partials` object provides a clean API for registering partials to injection points. This API is available in Spree 5.2 and later.
+
+### Accessing Available Injection Points
+
+You can list all available injection points programmatically:
+
+```ruby
+# In Rails console or initializer
+Spree.admin.partials.keys
+# => ["head", "body_start", "body_end", "dashboard_analytics", "product_form", ...]
+```
+
+### Registering Partials
+
+Each injection point is an array that you can append to:
+
+```ruby config/initializers/spree.rb
+
+# Add a single partial
+Spree.admin.partials.product_form << 'spree/admin/products/erp_section'
+
+# Add multiple partials
+Spree.admin.partials.dashboard_sidebar << 'spree/admin/dashboard/analytics_widget'
+Spree.admin.partials.dashboard_sidebar << 'spree/admin/dashboard/inventory_widget'
+```
+
+### Viewing Registered Partials
+
+To see which partials are registered for a specific injection point:
+
+```ruby
+Spree.admin.partials.product_form
+# => ["spree/admin/products/erp_section"]
+```
+
+### Replacing All Partials
+
+You can also replace all partials for an injection point:
+
+```ruby
+Spree.admin.partials.product_form = ['my/custom/partial']
+```
+
+<Warning>
+ Replacing all partials will remove any partials registered by other extensions. Use this with caution.
+</Warning>
+
+## List of all injection points
Here's a list of all places you can inject your custom code:
@@ -67,19 +130,19 @@ Here's a list of all places you can inject your custom code:
<AccordionGroup>
<Accordion title="<head>">
- `head_partials`
+ `head`
Injects code into the `<head>` tag
</Accordion>
<Accordion title="<body>">
- `body_start_partials`
+ `body_start`
Injects code into the `<body>` tag, before the main content
</Accordion>
<Accordion title="</body>">
- `body_end_partials`
+ `body_end`
Injects code into the `<body>` tag, after the main content
</Accordion>
@@ -89,7 +152,7 @@ Here's a list of all places you can inject your custom code:
<AccordionGroup>
<Accordion title="Analytics">
- `dashboard_analytics_partials`
+ `dashboard_analytics`
<Frame>
<img src="/images/developer/admin/dashboard_analytics_partials.png" />
@@ -110,7 +173,7 @@ Here's a list of all places you can inject your custom code:
</Accordion>
<Accordion title="Sidebar">
- `dashboard_sidebar_partials`
+ `dashboard_sidebar`
<Frame>
<img src="/images/developer/admin/dashboard_sidebar_partials.png" />
@@ -135,7 +198,7 @@ Here's a list of all places you can inject your custom code:
<AccordionGroup>
<Accordion title="Orders Actions">
- `orders_actions_partials`
+ `orders_actions`
Injects code into the page actions area (top right of the page) for the orders list page. This is useful for adding custom buttons, export options, or other actions.
@@ -145,7 +208,7 @@ Here's a list of all places you can inject your custom code:
</Accordion>
<Accordion title="Orders Header">
- `orders_header_partials`
+ `orders_header`
Injects code between the page header and the main content area for the orders list page. This is useful for adding notifications, alerts, or additional information.
@@ -157,7 +220,7 @@ Here's a list of all places you can inject your custom code:
</Accordion>
<Accordion title="Orders Filters">
- `orders_filters_partials`
+ `orders_filters`
<Frame>
<img src="/images/developer/admin/orders_filters_partials.png" />
@@ -165,26 +228,25 @@ Here's a list of all places you can inject your custom code:
#### Variables
- <ParamField path="f" type="ActionView::Helpers::FormBuilder">
- The [ActionView::Helpers::FormBuilder](https://api.rubyonrails.org/classes/ActionView/Helpers/FormBuilder.html) object.
+ <ParamField path="f" type="Spree::Admin::FormBuilder">
+ The [Spree::Admin::FormBuilder](/developer/admin/form-builder) object.
</ParamField>
- Injects code into the orders list filters, to add custom filters.
+ Injects code into the orders list filters, to add custom filters.
This partial has access to the `f` variable, which is the form builder for the filters, eg.
```erb
- <%= f.text_field :q_number_cont, class: "form-control", data: { filters_target: :input } %>
+ <%= f.spree_text_field :q_number_cont, data: { filters_target: :input } %>
```
<Tip>
- * `q_number_cont` - The name of the filter field. For filtering we're using [ransack](https://activerecord-hackery.github.io/ransack/) gem, so the name of the filter field is the name of the attribute we're filtering by. Learn more about [ransack search syntax](https://activerecord-hackery.github.io/ransack/getting-started/search-matches/).
- * `form-control` - A bootstrap class for styling the input field.
+ * `q_number_cont` - The name of the filter field. For filtering we're using [ransack](/developer/core-concepts/search-filtering) gem, so the name of the filter field is the name of the attribute we're filtering by.
* `data: { filters_target: :input }` - Needed for the [Stimulus Filters controller](https://github.com/spree/spree/blob/main/admin/app/javascript/spree/admin/controllers/filters_controller.js) to work.
</Tip>
</Accordion>
<Accordion title="Order Page Dropdown">
- `order_page_dropdown_partials`
+ `order_page_dropdown`
<Frame>
<img src="/images/developer/admin/order_page_dropdown_partials.png" />
@@ -211,7 +273,7 @@ Here's a list of all places you can inject your custom code:
</Accordion>
<Accordion title="Order Page Header">
- `order_page_header_partials`
+ `order_page_header`
<Frame>
<img src="/images/developer/admin/order_page_header_partials.png" />
@@ -259,7 +321,7 @@ Here's a list of all places you can inject your custom code:
</Accordion>
<Accordion title="Order Page Body">
- `order_page_body_partials`
+ `order_page_body`
<Frame>
<img src="/images/developer/admin/order_page_body_partials.png" />
@@ -299,7 +361,7 @@ Here's a list of all places you can inject your custom code:
</Accordion>
<Accordion title="Order Page Sidebar">
- `order_page_sidebar_partials`
+ `order_page_sidebar`
<Frame>
<img src="/images/developer/admin/order_page_sidebar_partials.png" />
@@ -319,7 +381,7 @@ Here's a list of all places you can inject your custom code:
<AccordionGroup>
<Accordion title="Customers Actions">
- `users_actions_partials`
+ `users_actions`
Injects code into the page actions area (top right of the page) for the customers list page. This is useful for adding custom buttons, export options, or other actions.
@@ -329,7 +391,7 @@ Here's a list of all places you can inject your custom code:
</Accordion>
<Accordion title="Customers Header">
- `users_header_partials`
+ `users_header`
Injects code between the page header and the main content area for the customers list page. This is useful for adding notifications, alerts, or additional information.
@@ -341,25 +403,22 @@ Here's a list of all places you can inject your custom code:
</Accordion>
<Accordion title="Customers Filters">
- `users_filters_partials`
+ `users_filters`
#### Variables
<ParamField path="f" type="ActionView::Helpers::FormBuilder">
- The [ActionView::Helpers::FormBuilder](https://api.rubyonrails.org/classes/ActionView/Helpers/FormBuilder.html) object.
+ The [Spree::Admin::FormBuilder](/developer/admin/form-builder) object.
</ParamField>
Injects code into the customers list filters. This partial has access to the `f` variable, which is the form builder for the filters.
```erb
- <div class="form-group">
- <%= f.label :custom_field_eq, "Customer Type" %>
- <%= f.select :custom_field_eq, options_for_select([["VIP", "vip"], ["Regular", "regular"]]), { include_blank: true }, { class: "custom-select", data: { filters_target: :input } } %>
- </div>
+ <%= f.spree_select :custom_field_eq, [["VIP", "vip"], ["Regular", "regular"]], { include_blank: true }, { data: { filters_target: :input } } %>
```
<Tip>
- * Use [ransack](https://activerecord-hackery.github.io/ransack/) search syntax for filter field names
+ * Use [ransack](/developer/core-concepts/search-filtering) search syntax for filter field names
* Include `data: { filters_target: :input }` for proper integration with the Stimulus Filters controller
</Tip>
</Accordion>
@@ -369,7 +428,7 @@ Here's a list of all places you can inject your custom code:
<AccordionGroup>
<Accordion title="Stock Items Actions">
- `stock_items_actions_partials`
+ `stock_items_actions`
Injects code into the page actions area for the stock items list page.
@@ -379,7 +438,7 @@ Here's a list of all places you can inject your custom code:
</Accordion>
<Accordion title="Stock Items Header">
- `stock_items_header_partials`
+ `stock_items_header`
Injects code between the page header and the main content area for the stock items list page.
@@ -391,22 +450,25 @@ Here's a list of all places you can inject your custom code:
</Accordion>
<Accordion title="Stock Items Filters">
- `stock_items_filters_partials`
+ `stock_items_filters`
#### Variables
- <ParamField path="f" type="ActionView::Helpers::FormBuilder">
- The [ActionView::Helpers::FormBuilder](https://api.rubyonrails.org/classes/ActionView/Helpers/FormBuilder.html) object.
+ <ParamField path="f" type="Spree::Admin::FormBuilder">
+ The [Spree::Admin::FormBuilder](/developer/admin/form-builder) object.
</ParamField>
Injects code into the stock items list filters.
```erb
- <div class="form-group">
- <%= f.label :count_on_hand_lt, "Stock Below" %>
- <%= f.number_field :count_on_hand_lt, class: "form-control", data: { filters_target: :input } %>
- </div>
+ <%= f.spree_number_field :count_on_hand_lt,
+ label: "Stock Below",
+ data: { filters_target: :input } %>
```
+
+ <Tip>
+ Use [ransack](/developer/core-concepts/search-filtering) search syntax for filter field names (e.g., `_lt` for "less than").
+ </Tip>
</Accordion>
</AccordionGroup>
@@ -414,7 +476,7 @@ Here's a list of all places you can inject your custom code:
<AccordionGroup>
<Accordion title="Admin Users Actions">
- `admin_users_actions_partials`
+ `admin_users_actions`
Injects code into the page actions area for the admin users list page.
@@ -424,7 +486,7 @@ Here's a list of all places you can inject your custom code:
</Accordion>
<Accordion title="Admin Users Header">
- `admin_users_header_partials`
+ `admin_users_header`
Injects code between the page header and the main content area for the admin users list page.
@@ -440,7 +502,7 @@ Here's a list of all places you can inject your custom code:
<AccordionGroup>
<Accordion title="Classifications Actions">
- `classifications_actions_partials`
+ `classifications_actions`
Injects code into the page actions area for the classifications list page.
@@ -450,7 +512,7 @@ Here's a list of all places you can inject your custom code:
</Accordion>
<Accordion title="Classifications Header">
- `classifications_header_partials`
+ `classifications_header`
Injects code between the page header and the main content area for the classifications list page.
@@ -466,7 +528,7 @@ Here's a list of all places you can inject your custom code:
<AccordionGroup>
<Accordion title="Coupon Codes Actions">
- `coupon_codes_actions_partials`
+ `coupon_codes_actions`
Injects code into the page actions area for the coupon codes list page.
@@ -476,7 +538,7 @@ Here's a list of all places you can inject your custom code:
</Accordion>
<Accordion title="Coupon Codes Header">
- `coupon_codes_header_partials`
+ `coupon_codes_header`
Injects code between the page header and the main content area for the coupon codes list page.
@@ -492,7 +554,7 @@ Here's a list of all places you can inject your custom code:
<AccordionGroup>
<Accordion title="Custom Domains Actions">
- `custom_domains_actions_partials`
+ `custom_domains_actions`
Injects code into the page actions area for the custom domains list page.
@@ -502,7 +564,7 @@ Here's a list of all places you can inject your custom code:
</Accordion>
<Accordion title="Custom Domains Header">
- `custom_domains_header_partials`
+ `custom_domains_header`
Injects code between the page header and the main content area for the custom domains list page.
@@ -518,7 +580,7 @@ Here's a list of all places you can inject your custom code:
<AccordionGroup>
<Accordion title="Customer Returns Actions">
- `customer_returns_actions_partials`
+ `customer_returns_actions`
Injects code into the page actions area for the customer returns list page.
@@ -528,7 +590,7 @@ Here's a list of all places you can inject your custom code:
</Accordion>
<Accordion title="Customer Returns Header">
- `customer_returns_header_partials`
+ `customer_returns_header`
Injects code between the page header and the main content area for the customer returns list page.
@@ -540,22 +602,26 @@ Here's a list of all places you can inject your custom code:
</Accordion>
<Accordion title="Customer Returns Filters">
- `customer_returns_filters_partials`
+ `customer_returns_filters`
#### Variables
- <ParamField path="f" type="ActionView::Helpers::FormBuilder">
- The [ActionView::Helpers::FormBuilder](https://api.rubyonrails.org/classes/ActionView/Helpers/FormBuilder.html) object.
+ <ParamField path="f" type="Spree::Admin::FormBuilder">
+ The [Spree::Admin::FormBuilder](/developer/admin/form-builder) object.
</ParamField>
Injects code into the customer returns list filters.
```erb
- <div class="form-group">
- <%= f.label :reason_eq, "Return Reason" %>
- <%= f.select :reason_eq, options_for_select([["Damaged", "damaged"], ["Wrong Item", "wrong_item"]]), { include_blank: true }, { class: "custom-select", data: { filters_target: :input } } %>
- </div>
+ <%= f.spree_select :reason_eq,
+ [["Damaged", "damaged"], ["Wrong Item", "wrong_item"]],
+ { include_blank: true, label: "Return Reason" },
+ { data: { filters_target: :input } } %>
```
+
+ <Tip>
+ Use [ransack](/developer/core-concepts/search-filtering) search syntax for filter field names (e.g., `_eq` for "equals").
+ </Tip>
</Accordion>
</AccordionGroup>
@@ -563,7 +629,7 @@ Here's a list of all places you can inject your custom code:
<AccordionGroup>
<Accordion title="Digital Assets Actions">
- `digital_assets_actions_partials`
+ `digital_assets_actions`
Injects code into the page actions area for the digital assets list page.
@@ -573,7 +639,7 @@ Here's a list of all places you can inject your custom code:
</Accordion>
<Accordion title="Digital Assets Header">
- `digital_assets_header_partials`
+ `digital_assets_header`
Injects code between the page header and the main content area for the digital assets list page.
@@ -589,7 +655,7 @@ Here's a list of all places you can inject your custom code:
<AccordionGroup>
<Accordion title="Exports Actions">
- `exports_actions_partials`
+ `exports_actions`
Injects code into the page actions area for the exports list page.
@@ -599,7 +665,7 @@ Here's a list of all places you can inject your custom code:
</Accordion>
<Accordion title="Exports Header">
- `exports_header_partials`
+ `exports_header`
Injects code between the page header and the main content area for the exports list page.
@@ -615,7 +681,7 @@ Here's a list of all places you can inject your custom code:
<AccordionGroup>
<Accordion title="Gift Cards Actions">
- `gift_cards_actions_partials`
+ `gift_cards_actions`
Injects code into the page actions area for the gift cards list page.
@@ -625,7 +691,7 @@ Here's a list of all places you can inject your custom code:
</Accordion>
<Accordion title="Gift Cards Header">
- `gift_cards_header_partials`
+ `gift_cards_header`
Injects code between the page header and the main content area for the gift cards list page.
@@ -637,22 +703,26 @@ Here's a list of all places you can inject your custom code:
</Accordion>
<Accordion title="Gift Cards Filters">
- `gift_cards_filters_partials`
+ `gift_cards_filters`
#### Variables
- <ParamField path="f" type="ActionView::Helpers::FormBuilder">
- The [ActionView::Helpers::FormBuilder](https://api.rubyonrails.org/classes/ActionView/Helpers/FormBuilder.html) object.
+ <ParamField path="f" type="Spree::Admin::FormBuilder">
+ The [Spree::Admin::FormBuilder](/developer/admin/form-builder) object.
</ParamField>
Injects code into the gift cards list filters.
```erb
- <div class="form-group">
- <%= f.label :balance_gt, "Balance Greater Than" %>
- <%= f.number_field :balance_gt, step: 0.01, class: "form-control", data: { filters_target: :input } %>
- </div>
+ <%= f.spree_number_field :balance_gt,
+ label: "Balance Greater Than",
+ step: 0.01,
+ data: { filters_target: :input } %>
```
+
+ <Tip>
+ Use [ransack](/developer/core-concepts/search-filtering) search syntax for filter field names (e.g., `_gt` for "greater than").
+ </Tip>
</Accordion>
</AccordionGroup>
@@ -660,7 +730,7 @@ Here's a list of all places you can inject your custom code:
<AccordionGroup>
<Accordion title="Integrations Actions">
- `integrations_actions_partials`
+ `integrations_actions`
Injects code into the page actions area for the integrations list page.
@@ -670,7 +740,7 @@ Here's a list of all places you can inject your custom code:
</Accordion>
<Accordion title="Integrations Header">
- `integrations_header_partials`
+ `integrations_header`
Injects code between the page header and the main content area for the integrations list page.
@@ -686,7 +756,7 @@ Here's a list of all places you can inject your custom code:
<AccordionGroup>
<Accordion title="Invitations Actions">
- `invitations_actions_partials`
+ `invitations_actions`
Injects code into the page actions area for the invitations list page.
@@ -696,7 +766,7 @@ Here's a list of all places you can inject your custom code:
</Accordion>
<Accordion title="Invitations Header">
- `invitations_header_partials`
+ `invitations_header`
Injects code between the page header and the main content area for the invitations list page.
@@ -712,7 +782,7 @@ Here's a list of all places you can inject your custom code:
<AccordionGroup>
<Accordion title="OAuth Applications Actions">
- `oauth_applications_actions_partials`
+ `oauth_applications_actions`
Injects code into the page actions area for the OAuth applications list page.
@@ -722,7 +792,7 @@ Here's a list of all places you can inject your custom code:
</Accordion>
<Accordion title="OAuth Applications Header">
- `oauth_applications_header_partials`
+ `oauth_applications_header`
Injects code between the page header and the main content area for the OAuth applications list page.
@@ -738,7 +808,7 @@ Here's a list of all places you can inject your custom code:
<AccordionGroup>
<Accordion title="Option Types Actions">
- `option_types_actions_partials`
+ `option_types_actions`
Injects code into the page actions area for the option types list page.
@@ -748,7 +818,7 @@ Here's a list of all places you can inject your custom code:
</Accordion>
<Accordion title="Option Types Header">
- `option_types_header_partials`
+ `option_types_header`
Injects code between the page header and the main content area for the option types list page.
@@ -764,7 +834,7 @@ Here's a list of all places you can inject your custom code:
<AccordionGroup>
<Accordion title="Pages Actions">
- `pages_actions_partials`
+ `pages_actions`
Injects code into the page actions area for the pages list page.
@@ -774,7 +844,7 @@ Here's a list of all places you can inject your custom code:
</Accordion>
<Accordion title="Pages Header">
- `pages_header_partials`
+ `pages_header`
Injects code between the page header and the main content area for the pages list page.
@@ -790,7 +860,7 @@ Here's a list of all places you can inject your custom code:
<AccordionGroup>
<Accordion title="Payment Methods Actions">
- `payment_methods_actions_partials`
+ `payment_methods_actions`
Injects code into the page actions area for the payment methods list page.
@@ -800,7 +870,7 @@ Here's a list of all places you can inject your custom code:
</Accordion>
<Accordion title="Payment Methods Header">
- `payment_methods_header_partials`
+ `payment_methods_header`
Injects code between the page header and the main content area for the payment methods list page.
@@ -816,7 +886,7 @@ Here's a list of all places you can inject your custom code:
<AccordionGroup>
<Accordion title="Post Categories Actions">
- `post_categories_actions_partials`
+ `post_categories_actions`
Injects code into the page actions area for the post categories list page.
@@ -826,7 +896,7 @@ Here's a list of all places you can inject your custom code:
</Accordion>
<Accordion title="Post Categories Header">
- `post_categories_header_partials`
+ `post_categories_header`
Injects code between the page header and the main content area for the post categories list page.
@@ -842,7 +912,7 @@ Here's a list of all places you can inject your custom code:
<AccordionGroup>
<Accordion title="Posts Actions">
- `posts_actions_partials`
+ `posts_actions`
Injects code into the page actions area for the posts list page.
@@ -852,7 +922,7 @@ Here's a list of all places you can inject your custom code:
</Accordion>
<Accordion title="Posts Header">
- `posts_header_partials`
+ `posts_header`
Injects code between the page header and the main content area for the posts list page.
@@ -864,22 +934,26 @@ Here's a list of all places you can inject your custom code:
</Accordion>
<Accordion title="Posts Filters">
- `posts_filters_partials`
+ `posts_filters`
#### Variables
- <ParamField path="f" type="ActionView::Helpers::FormBuilder">
- The [ActionView::Helpers::FormBuilder](https://api.rubyonrails.org/classes/ActionView/Helpers/FormBuilder.html) object.
+ <ParamField path="f" type="Spree::Admin::FormBuilder">
+ The [Spree::Admin::FormBuilder](/developer/admin/form-builder) object.
</ParamField>
Injects code into the posts list filters.
```erb
- <div class="form-group">
- <%= f.label :published_eq, "Publication Status" %>
- <%= f.select :published_eq, options_for_select([["Published", true], ["Draft", false]]), { include_blank: true }, { class: "custom-select", data: { filters_target: :input } } %>
- </div>
+ <%= f.spree_select :published_eq,
+ [["Published", true], ["Draft", false]],
+ { include_blank: true, label: "Publication Status" },
+ { data: { filters_target: :input } } %>
```
+
+ <Tip>
+ Use [ransack](/developer/core-concepts/search-filtering) search syntax for filter field names.
+ </Tip>
</Accordion>
</AccordionGroup>
@@ -887,7 +961,7 @@ Here's a list of all places you can inject your custom code:
<AccordionGroup>
<Accordion title="Promotions Actions">
- `promotions_actions_partials`
+ `promotions_actions`
Injects code into the page actions area for the promotions list page.
@@ -897,7 +971,7 @@ Here's a list of all places you can inject your custom code:
</Accordion>
<Accordion title="Promotions Header">
- `promotions_header_partials`
+ `promotions_header`
Injects code between the page header and the main content area for the promotions list page.
@@ -909,22 +983,26 @@ Here's a list of all places you can inject your custom code:
</Accordion>
<Accordion title="Promotions Filters">
- `promotions_filters_partials`
+ `promotions_filters`
#### Variables
- <ParamField path="f" type="ActionView::Helpers::FormBuilder">
- The [ActionView::Helpers::FormBuilder](https://api.rubyonrails.org/classes/ActionView/Helpers/FormBuilder.html) object.
+ <ParamField path="f" type="Spree::Admin::FormBuilder">
+ The [Spree::Admin::FormBuilder](/developer/admin/form-builder) object.
</ParamField>
Injects code into the promotions list filters.
```erb
- <div class="form-group">
- <%= f.label :active_eq, "Active Status" %>
- <%= f.select :active_eq, options_for_select([["Active", true], ["Inactive", false]]), { include_blank: true }, { class: "custom-select", data: { filters_target: :input } } %>
- </div>
+ <%= f.spree_select :active_eq,
+ [["Active", true], ["Inactive", false]],
+ { include_blank: true, label: "Active Status" },
+ { data: { filters_target: :input } } %>
```
+
+ <Tip>
+ Use [ransack](/developer/core-concepts/search-filtering) search syntax for filter field names.
+ </Tip>
</Accordion>
</AccordionGroup>
@@ -932,7 +1010,7 @@ Here's a list of all places you can inject your custom code:
<AccordionGroup>
<Accordion title="Properties Actions">
- `properties_actions_partials`
+ `properties_actions`
Injects code into the page actions area for the properties list page.
@@ -942,7 +1020,7 @@ Here's a list of all places you can inject your custom code:
</Accordion>
<Accordion title="Properties Header">
- `properties_header_partials`
+ `properties_header`
Injects code between the page header and the main content area for the properties list page.
@@ -958,7 +1036,7 @@ Here's a list of all places you can inject your custom code:
<AccordionGroup>
<Accordion title="Refund Reasons Actions">
- `refund_reasons_actions_partials`
+ `refund_reasons_actions`
Injects code into the page actions area for the refund reasons list page.
@@ -968,7 +1046,7 @@ Here's a list of all places you can inject your custom code:
</Accordion>
<Accordion title="Refund Reasons Header">
- `refund_reasons_header_partials`
+ `refund_reasons_header`
Injects code between the page header and the main content area for the refund reasons list page.
@@ -984,7 +1062,7 @@ Here's a list of all places you can inject your custom code:
<AccordionGroup>
<Accordion title="Reimbursement Types Actions">
- `reimbursement_types_actions_partials`
+ `reimbursement_types_actions`
Injects code into the page actions area for the reimbursement types list page.
@@ -994,7 +1072,7 @@ Here's a list of all places you can inject your custom code:
</Accordion>
<Accordion title="Reimbursement Types Header">
- `reimbursement_types_header_partials`
+ `reimbursement_types_header`
Injects code between the page header and the main content area for the reimbursement types list page.
@@ -1010,7 +1088,7 @@ Here's a list of all places you can inject your custom code:
<AccordionGroup>
<Accordion title="Reports Actions">
- `reports_actions_partials`
+ `reports_actions`
Injects code into the page actions area for the reports list page.
@@ -1020,7 +1098,7 @@ Here's a list of all places you can inject your custom code:
</Accordion>
<Accordion title="Reports Header">
- `reports_header_partials`
+ `reports_header`
Injects code between the page header and the main content area for the reports list page.
@@ -1036,7 +1114,7 @@ Here's a list of all places you can inject your custom code:
<AccordionGroup>
<Accordion title="Return Authorization Reasons Actions">
- `return_authorization_reasons_actions_partials`
+ `return_authorization_reasons_actions`
Injects code into the page actions area for the return authorization reasons list page.
@@ -1046,7 +1124,7 @@ Here's a list of all places you can inject your custom code:
</Accordion>
<Accordion title="Return Authorization Reasons Header">
- `return_authorization_reasons_header_partials`
+ `return_authorization_reasons_header`
Injects code between the page header and the main content area for the return authorization reasons list page.
@@ -1062,7 +1140,7 @@ Here's a list of all places you can inject your custom code:
<AccordionGroup>
<Accordion title="Return Authorizations Actions">
- `return_authorizations_actions_partials`
+ `return_authorizations_actions`
Injects code into the page actions area for the return authorizations list page.
@@ -1072,7 +1150,7 @@ Here's a list of all places you can inject your custom code:
</Accordion>
<Accordion title="Return Authorizations Header">
- `return_authorizations_header_partials`
+ `return_authorizations_header`
Injects code between the page header and the main content area for the return authorizations list page.
@@ -1088,7 +1166,7 @@ Here's a list of all places you can inject your custom code:
<AccordionGroup>
<Accordion title="Roles Actions">
- `roles_actions_partials`
+ `roles_actions`
Injects code into the page actions area for the roles list page.
@@ -1098,7 +1176,7 @@ Here's a list of all places you can inject your custom code:
</Accordion>
<Accordion title="Roles Header">
- `roles_header_partials`
+ `roles_header`
Injects code between the page header and the main content area for the roles list page.
@@ -1114,7 +1192,7 @@ Here's a list of all places you can inject your custom code:
<AccordionGroup>
<Accordion title="Shipping Categories Actions">
- `shipping_categories_actions_partials`
+ `shipping_categories_actions`
Injects code into the page actions area for the shipping categories list page.
@@ -1124,7 +1202,7 @@ Here's a list of all places you can inject your custom code:
</Accordion>
<Accordion title="Shipping Categories Header">
- `shipping_categories_header_partials`
+ `shipping_categories_header`
Injects code between the page header and the main content area for the shipping categories list page.
@@ -1140,7 +1218,7 @@ Here's a list of all places you can inject your custom code:
<AccordionGroup>
<Accordion title="Shipping Methods Actions">
- `shipping_methods_actions_partials`
+ `shipping_methods_actions`
Injects code into the page actions area for the shipping methods list page.
@@ -1150,7 +1228,7 @@ Here's a list of all places you can inject your custom code:
</Accordion>
<Accordion title="Shipping Methods Header">
- `shipping_methods_header_partials`
+ `shipping_methods_header`
Injects code between the page header and the main content area for the shipping methods list page.
@@ -1166,7 +1244,7 @@ Here's a list of all places you can inject your custom code:
<AccordionGroup>
<Accordion title="Stock Locations Actions">
- `stock_locations_actions_partials`
+ `stock_locations_actions`
Injects code into the page actions area for the stock locations list page.
@@ -1176,7 +1254,7 @@ Here's a list of all places you can inject your custom code:
</Accordion>
<Accordion title="Stock Locations Header">
- `stock_locations_header_partials`
+ `stock_locations_header`
Injects code between the page header and the main content area for the stock locations list page.
@@ -1192,7 +1270,7 @@ Here's a list of all places you can inject your custom code:
<AccordionGroup>
<Accordion title="Stock Transfers Actions">
- `stock_transfers_actions_partials`
+ `stock_transfers_actions`
Injects code into the page actions area for the stock transfers list page.
@@ -1202,7 +1280,7 @@ Here's a list of all places you can inject your custom code:
</Accordion>
<Accordion title="Stock Transfers Header">
- `stock_transfers_header_partials`
+ `stock_transfers_header`
Injects code between the page header and the main content area for the stock transfers list page.
@@ -1214,22 +1292,26 @@ Here's a list of all places you can inject your custom code:
</Accordion>
<Accordion title="Stock Transfers Filters">
- `stock_transfers_filters_partials`
+ `stock_transfers_filters`
#### Variables
- <ParamField path="f" type="ActionView::Helpers::FormBuilder">
- The [ActionView::Helpers::FormBuilder](https://api.rubyonrails.org/classes/ActionView/Helpers/FormBuilder.html) object.
+ <ParamField path="f" type="Spree::Admin::FormBuilder">
+ The [Spree::Admin::FormBuilder](/developer/admin/form-builder) object.
</ParamField>
Injects code into the stock transfers list filters.
```erb
- <div class="form-group">
- <%= f.label :status_eq, "Transfer Status" %>
- <%= f.select :status_eq, options_for_select([["Pending", "pending"], ["Completed", "completed"]]), { include_blank: true }, { class: "custom-select", data: { filters_target: :input } } %>
- </div>
+ <%= f.spree_select :status_eq,
+ [["Pending", "pending"], ["Completed", "completed"]],
+ { include_blank: true, label: "Transfer Status" },
+ { data: { filters_target: :input } } %>
```
+
+ <Tip>
+ Use [ransack](/developer/core-concepts/search-filtering) search syntax for filter field names.
+ </Tip>
</Accordion>
</AccordionGroup>
@@ -1237,7 +1319,7 @@ Here's a list of all places you can inject your custom code:
<AccordionGroup>
<Accordion title="Store Credit Categories Actions">
- `store_credit_categories_actions_partials`
+ `store_credit_categories_actions`
Injects code into the page actions area for the store credit categories list page.
@@ -1247,7 +1329,7 @@ Here's a list of all places you can inject your custom code:
</Accordion>
<Accordion title="Store Credit Categories Header">
- `store_credit_categories_header_partials`
+ `store_credit_categories_header`
Injects code between the page header and the main content area for the store credit categories list page.
@@ -1263,7 +1345,7 @@ Here's a list of all places you can inject your custom code:
<AccordionGroup>
<Accordion title="Store Credits Actions">
- `store_credits_actions_partials`
+ `store_credits_actions`
Injects code into the page actions area for the store credits list page.
@@ -1273,7 +1355,7 @@ Here's a list of all places you can inject your custom code:
</Accordion>
<Accordion title="Store Credits Header">
- `store_credits_header_partials`
+ `store_credits_header`
Injects code between the page header and the main content area for the store credits list page.
@@ -1289,7 +1371,7 @@ Here's a list of all places you can inject your custom code:
<AccordionGroup>
<Accordion title="Tax Categories Actions">
- `tax_categories_actions_partials`
+ `tax_categories_actions`
Injects code into the page actions area for the tax categories list page.
@@ -1299,7 +1381,7 @@ Here's a list of all places you can inject your custom code:
</Accordion>
<Accordion title="Tax Categories Header">
- `tax_categories_header_partials`
+ `tax_categories_header`
Injects code between the page header and the main content area for the tax categories list page.
@@ -1315,7 +1397,7 @@ Here's a list of all places you can inject your custom code:
<AccordionGroup>
<Accordion title="Tax Rates Actions">
- `tax_rates_actions_partials`
+ `tax_rates_actions`
Injects code into the page actions area for the tax rates list page.
@@ -1325,7 +1407,7 @@ Here's a list of all places you can inject your custom code:
</Accordion>
<Accordion title="Tax Rates Header">
- `tax_rates_header_partials`
+ `tax_rates_header`
Injects code between the page header and the main content area for the tax rates list page.
@@ -1341,7 +1423,7 @@ Here's a list of all places you can inject your custom code:
<AccordionGroup>
<Accordion title="Taxonomies Actions">
- `taxonomies_actions_partials`
+ `taxonomies_actions`
Injects code into the page actions area for the taxonomies list page.
@@ -1351,7 +1433,7 @@ Here's a list of all places you can inject your custom code:
</Accordion>
<Accordion title="Taxonomies Header">
- `taxonomies_header_partials`
+ `taxonomies_header`
Injects code between the page header and the main content area for the taxonomies list page.
@@ -1367,7 +1449,7 @@ Here's a list of all places you can inject your custom code:
<AccordionGroup>
<Accordion title="Themes Actions">
- `themes_actions_partials`
+ `themes_actions`
Injects code into the page actions area for the themes list page.
@@ -1377,7 +1459,7 @@ Here's a list of all places you can inject your custom code:
</Accordion>
<Accordion title="Themes Header">
- `themes_header_partials`
+ `themes_header`
Injects code between the page header and the main content area for the themes list page.
@@ -1393,7 +1475,7 @@ Here's a list of all places you can inject your custom code:
<AccordionGroup>
<Accordion title="Webhooks Subscribers Actions">
- `webhooks_subscribers_actions_partials`
+ `webhooks_subscribers_actions`
Injects code into the page actions area for the webhooks subscribers list page.
@@ -1403,7 +1485,7 @@ Here's a list of all places you can inject your custom code:
</Accordion>
<Accordion title="Webhooks Subscribers Header">
- `webhooks_subscribers_header_partials`
+ `webhooks_subscribers_header`
Injects code between the page header and the main content area for the webhooks subscribers list page.
@@ -1419,7 +1501,7 @@ Here's a list of all places you can inject your custom code:
<AccordionGroup>
<Accordion title="Zones Actions">
- `zones_actions_partials`
+ `zones_actions`
Injects code into the page actions area for the zones list page.
@@ -1429,7 +1511,7 @@ Here's a list of all places you can inject your custom code:
</Accordion>
<Accordion title="Zones Header">
- `zones_header_partials`
+ `zones_header`
Injects code between the page header and the main content area for the zones list page.
@@ -1445,7 +1527,7 @@ Here's a list of all places you can inject your custom code:
<AccordionGroup>
<Accordion title="Products Actions">
- `products_actions_partials`
+ `products_actions`
Injects code into the page actions area (top right of the page) for the products list page. This is useful for adding custom buttons, export options, or other actions.
@@ -1455,7 +1537,7 @@ Here's a list of all places you can inject your custom code:
</Accordion>
<Accordion title="Products Header">
- `products_header_partials`
+ `products_header`
Injects code between the page header and the main content area for the products list page. This is useful for adding notifications, alerts, or additional information.
@@ -1467,16 +1549,16 @@ Here's a list of all places you can inject your custom code:
</Accordion>
<Accordion title="Products Filters">
- `products_filters_partials`
+ `products_filters`
<Frame>
- <img src="/images/developer/admin/products_filters_partials.png" />
+ <img src="/images/developer/admin/products_filters.png" />
</Frame>
#### Variables
- <ParamField path="f" type="ActionView::Helpers::FormBuilder">
- The [ActionView::Helpers::FormBuilder](https://api.rubyonrails.org/classes/ActionView/Helpers/FormBuilder.html) object.
+ <ParamField path="f" type="Spree::Admin::FormBuilder">
+ The [Spree::Admin::FormBuilder](/developer/admin/form-builder) object.
</ParamField>
Injects code into the products list filters. This partial has access to the `f` variable, which is the form builder for the filters.
@@ -1484,21 +1566,20 @@ Here's a list of all places you can inject your custom code:
To add a new filter field, you can use the following code:
```erb
- <%= f.text_field :q_name_cont, class: "form-control", data: { filters_target: :input } %>
+ <%= f.spree_text_field :q_name_cont, data: { filters_target: :input } %>
```
<Tip>
- * `q_name_cont` is the name of the filter field. For filtering we're using [ransack](https://activerecord-hackery.github.io/ransack/) gem, so the name of the filter field is the name of the attribute we're filtering by. Learn more about [ransack search syntax](https://activerecord-hackery.github.io/ransack/getting-started/search-matches/).
- * `form-control` is a bootstrap class for styling the input field.
+ * `q_name_cont` is the name of the filter field. For filtering we're using [ransack](/developer/core-concepts/search-filtering) gem, so the name of the filter field is the name of the attribute we're filtering by.
* `data: { filters_target: :input }` is needed for the [Stimulus Filters controller](https://github.com/spree/spree/blob/main/admin/app/javascript/spree/admin/controllers/filters_controller.js) to work.
</Tip>
</Accordion>
<Accordion title="Products Page Dropdown">
- `product_dropdown_partials`
+ `product_dropdown`
<Frame>
- <img src="/images/developer/admin/product_dropdown_partials.png" />
+ <img src="/images/developer/admin/product_dropdown.png" />
</Frame>
Injects code into the products page dropdown. This partial has access to the `product` variable.
@@ -1515,16 +1596,16 @@ Here's a list of all places you can inject your custom code:
</Accordion>
<Accordion title="Products Page Form">
- `product_form_partials`
+ `product_form`
<Frame>
- <img src="/images/developer/admin/product_form_partials.png" />
+ <img src="/images/developer/admin/product_form.png" />
</Frame>
#### Variables
- <ParamField path="f" type="ActionView::Helpers::FormBuilder">
- The [ActionView::Helpers::FormBuilder](https://api.rubyonrails.org/classes/ActionView/Helpers/FormBuilder.html) object.
+ <ParamField path="f" type="Spree::Admin::FormBuilder">
+ The [Spree::Admin::FormBuilder](/developer/admin/form-builder) object.
</ParamField>
<ParamField path="product" type="Spree::Product">
@@ -1541,7 +1622,7 @@ Here's a list of all places you can inject your custom code:
<h5 class="card-title">ERP Integration</h5>
</div>
<div class="card-body">
- <%= f.text_field :erp_product_id, class: "form-control" %>
+ <%= f.spree_text_field :erp_product_id %>
</div>
</div>
```
@@ -1571,16 +1652,16 @@ Here's a list of all places you can inject your custom code:
</Accordion>
<Accordion title="Products Page Sidebar">
- `product_form_sidebar_partials`
+ `product_form_sidebar`
<Frame>
- <img src="/images/developer/admin/product_form_sidebar_partials.png" />
+ <img src="/images/developer/admin/product_form_sidebar.png" />
</Frame>
#### Variables
- <ParamField path="f" type="ActionView::Helpers::FormBuilder">
- The [ActionView::Helpers::FormBuilder](https://api.rubyonrails.org/classes/ActionView/Helpers/FormBuilder.html) object.
+ <ParamField path="f" type="Spree::Admin::FormBuilder">
+ The [Spree::Admin::FormBuilder](/developer/admin/form-builder) object.
</ParamField>
<ParamField path="product" type="Spree::Product">
@@ -1597,7 +1678,7 @@ Here's a list of all places you can inject your custom code:
<h5 class="card-title">ERP Integration</h5>
</div>
<div class="card-body">
- <%= f.text_field :erp_product_id, class: "form-control" %>
+ <%= f.spree_text_field :erp_product_id %>
</div>
</div>
```
@@ -1630,12 +1711,12 @@ Here's a list of all places you can inject your custom code:
<AccordionGroup>
<Accordion title="Shipping Methods Form">
- `shipping_method_form_partials`
+ `shipping_method_form`
#### Variables
- <ParamField path="f" type="ActionView::Helpers::FormBuilder">
- The [ActionView::Helpers::FormBuilder](https://api.rubyonrails.org/classes/ActionView/Helpers/FormBuilder.html) object.
+ <ParamField path="f" type="Spree::Admin::FormBuilder">
+ The [Spree::Admin::FormBuilder](/developer/admin/form-builder) object.
</ParamField>
<ParamField path="shipping_method" type="Spree::ShippingMethod">
@@ -1652,7 +1733,7 @@ Here's a list of all places you can inject your custom code:
<h5 class="card-title">ERP Integration</h5>
</div>
<div class="card-body">
- <%= f.text_field :erp_shipping_method_id, class: "form-control" %>
+ <%= f.spree_text_field :erp_shipping_method_id %>
</div>
</div>
```
@@ -1663,16 +1744,16 @@ Here's a list of all places you can inject your custom code:
<AccordionGroup>
<Accordion title="Store Settings Form">
- `store_form_partials`
+ `store_form`
<Frame>
- <img src="/images/developer/admin/store_form_partials.png" />
+ <img src="/images/developer/admin/store_form.png" />
</Frame>
#### Variables
- <ParamField path="f" type="ActionView::Helpers::FormBuilder">
- The [ActionView::Helpers::FormBuilder](https://api.rubyonrails.org/classes/ActionView/Helpers/FormBuilder.html) object.
+ <ParamField path="f" type="Spree::Admin::FormBuilder">
+ The [Spree::Admin::FormBuilder](/developer/admin/form-builder) object.
</ParamField>
<ParamField path="store" type="Spree::Store">
@@ -1689,7 +1770,7 @@ Here's a list of all places you can inject your custom code:
<h5 class="card-title">ERP Integration</h5>
</div>
<div class="card-body">
- <%= f.text_field :erp_store_id, class: "form-control" %>
+ <%= f.spree_text_field :erp_store_id %>
</div>
</div>
```
diff --git a/docs/developer/admin/form-builder.mdx b/docs/developer/admin/form-builder.mdx
new file mode 100644
index 0000000000..0d8be32f10
--- /dev/null
+++ b/docs/developer/admin/form-builder.mdx
@@ -0,0 +1,410 @@
+---
+title: Admin Form Builder API
+sidebarTitle: Form Builder
+---
+
+Spree provides a custom `Spree::Admin::FormBuilder` that extends Rails' standard FormBuilder with additional helper methods designed specifically for the admin interface. This form builder ensures consistent styling, error handling, and behavior across all admin forms.
+
+## Using the FormBuilder
+
+The FormBuilder is automatically available in admin forms when using `form_with`:
+
+```erb
+<%= form_with model: [:admin, @product] do |f| %>
+ <%= f.spree_text_field :name %>
+ <%= f.spree_text_area :description %>
+<% end %>
+```
+
+## Common Options
+
+All FormBuilder methods support these common options:
+
+| Option | Type | Description |
+|--------|------|-------------|
+| `:label` | String or `false` | Custom label text, or `false` to hide the label entirely |
+| `:required` | Boolean | Adds a red asterisk (*) indicator next to the label |
+| `:help` | String | Help text displayed below the field |
+| `:help_bubble` | String | Tooltip text displayed in a help bubble icon next to the label |
+| `:class` | String | Additional CSS classes for the input element |
+
+## Text Input Methods
+
+### spree_text_field
+
+Creates a text input field with Spree styling.
+
+```erb
+<%= f.spree_text_field :name %>
+<%= f.spree_text_field :sku, required: true %>
+<%= f.spree_text_field :code, help: "Leave blank to auto-generate" %>
+<%= f.spree_text_field :slug, help_bubble: "URL-friendly identifier" %>
+```
+
+**Options:**
+- All standard Rails `text_field` options
+- All common FormBuilder options
+
+### spree_number_field
+
+Creates a number input field with Spree styling.
+
+```erb
+<%= f.spree_number_field :price, required: true, step: 0.01 %>
+<%= f.spree_number_field :quantity, min: 0 %>
+```
+
+**Options:**
+- All standard Rails `number_field` options (`:min`, `:max`, `:step`)
+- All common FormBuilder options
+
+### spree_email_field
+
+Creates an email input field with Spree styling and HTML5 validation.
+
+```erb
+<%= f.spree_email_field :email, required: true %>
+<%= f.spree_email_field :contact_email,
+ help: "For customer support inquiries" %>
+```
+
+**Options:**
+- All standard Rails `email_field` options
+- All common FormBuilder options
+
+## Date and Time Methods
+
+### spree_date_field
+
+Creates a date picker input field.
+
+```erb
+<%= f.spree_date_field :available_on %>
+<%= f.spree_date_field :discontinue_on,
+ help: "Date when product will be discontinued" %>
+```
+
+**Options:**
+- All standard Rails `date_field` options (`:min`, `:max`)
+- All common FormBuilder options
+
+### spree_datetime_field
+
+Creates a datetime picker input field.
+
+```erb
+<%= f.spree_datetime_field :published_at %>
+<%= f.spree_datetime_field :sale_starts_at, required: true %>
+```
+
+**Options:**
+- All standard Rails `datetime_field` options
+- All common FormBuilder options
+
+## Text Area Methods
+
+### spree_text_area
+
+Creates a textarea with auto-grow functionality (expands as you type).
+
+```erb
+<%= f.spree_text_area :description %>
+<%= f.spree_text_area :notes, rows: 10 %>
+<%= f.spree_text_area :meta_description,
+ help: "Used for SEO, maximum 160 characters" %>
+```
+
+**Options:**
+- `:rows` - Number of visible rows (default: 5)
+- `:data` - Data attributes (default includes auto-grow Stimulus controller)
+- All standard Rails `text_area` options
+- All common FormBuilder options
+
+**Auto-grow behavior:**
+By default, the textarea automatically grows as the user types. This uses the `textarea-autogrow` Stimulus controller.
+
+### spree_rich_text_area
+
+Creates a rich text editor using Trix.
+
+```erb
+<%= f.spree_rich_text_area :description %>
+<%= f.spree_rich_text_area :content, label: "Page Content" %>
+```
+
+**Features:**
+- WYSIWYG editing
+- Basic formatting (bold, italic, lists, links)
+- File attachments via Active Storage
+- All common FormBuilder options
+
+## Select Methods
+
+### spree_select
+
+Creates a select dropdown field.
+
+```erb
+<%= f.spree_select :status,
+ ['draft', 'active', 'archived'],
+ {},
+ {} %>
+
+<%= f.spree_select :tax_category_id,
+ Spree::Category.pluck(:name, :id),
+ { include_blank: 'Select Tax Category' } %>
+```
+
+**With autocomplete:**
+
+```erb
+<%= f.spree_select :country_id,
+ Spree::Country.pluck(:name, :id),
+ { autocomplete: true } %>
+```
+
+**Parameters:**
+1. `method` - The attribute name
+2. `choices` - Array of options
+3. `options` - Select options (`:include_blank`, `:prompt`, `:autocomplete`)
+4. `html_options` - HTML attributes (`:class`, `:data`, `:disabled`)
+
+**Options:**
+- `:autocomplete` - Enables searchable dropdown with autocomplete functionality
+- All standard Rails `select` options
+- All common FormBuilder options
+
+### spree_collection_select
+
+Creates a select dropdown from a collection of objects.
+
+```erb
+<%= f.spree_collection_select :shipping_category_id,
+ ShippingCategory.all,
+ :id,
+ :name,
+ { include_blank: true },
+ {} %>
+
+<%= f.spree_collection_select :tax_category_id,
+ TaxCategory.all,
+ :id,
+ :name,
+ { autocomplete: true, required: true },
+ {} %>
+```
+
+**Parameters:**
+1. `method` - The attribute name
+2. `collection` - ActiveRecord collection or array of objects
+3. `value_method` - Method to call for option value (e.g., `:id`)
+4. `text_method` - Method to call for option text (e.g., `:name`)
+5. `options` - Select options (`:include_blank`, `:autocomplete`)
+6. `html_options` - HTML attributes
+
+**Options:**
+- `:autocomplete` - Enables searchable dropdown
+- All standard Rails `collection_select` options
+- All common FormBuilder options
+
+## Checkbox and Radio Methods
+
+### spree_check_box
+
+Creates a styled checkbox with custom controls.
+
+```erb
+<%= f.spree_check_box :active %>
+<%= f.spree_check_box :featured, label: "Feature on homepage" %>
+<%= f.spree_check_box :accept_terms, required: true %>
+```
+
+**Options:**
+- All standard Rails `check_box` options
+- All common FormBuilder options
+
+**Styling:**
+Uses custom control classes for consistent appearance across the admin interface.
+
+### spree_radio_button
+
+Creates a styled radio button with custom controls.
+
+```erb
+<%= f.spree_radio_button :status, 'draft', id: 'status_draft' %>
+<%= f.spree_radio_button :status, 'published', id: 'status_published' %>
+```
+
+**Parameters:**
+1. `method` - The attribute name
+2. `tag_value` - The value for this radio option
+3. `options` - Options hash (must include `:id`)
+
+**Options:**
+- `:id` - Required HTML ID for the radio button
+- All standard Rails `radio_button` options
+- All common FormBuilder options
+
+<Warning>
+ Radio buttons require unique IDs. Always specify the `:id` option.
+</Warning>
+
+## File Upload Methods
+
+### spree_file_field
+
+Creates a file upload field with image preview, drag-and-drop support, and optional cropping functionality.
+
+```erb
+<%= f.spree_file_field :image %>
+<%= f.spree_file_field :logo, width: 240, height: 240 %>
+<%= f.spree_file_field :avatar, crop: true %>
+<%= f.spree_file_field :featured_image, width: 1200, height: 600, crop: true %>
+```
+
+**Options:**
+
+| Option | Type | Default | Description |
+|--------|------|---------|-------------|
+| `:width` | Integer | 300 | Width of the image preview in pixels |
+| `:height` | Integer | 300 | Height of the image preview in pixels |
+| `:crop` | Boolean | `false` | Enable image cropping with recommended size indicator |
+| `:auto_submit` | Boolean | `false` | Automatically submit form when file is selected |
+| `:can_delete` | Boolean | `true` | Show delete button for removing uploaded image |
+| `:css` | String | `''` | Additional CSS classes for the upload placeholder area |
+
+All common FormBuilder options (`:label`, `:required`, `:help`, `:help_bubble`) are also supported.
+
+**Features:**
+- Drag-and-drop file upload
+- Image preview after upload
+- Optional image cropping with size recommendations
+- Delete button to remove uploaded files
+- Uses Active Storage direct upload
+
+**Example with all options:**
+
+```erb
+<%= f.spree_file_field :social_image,
+ width: 1200,
+ height: 630,
+ crop: true,
+ label: 'Preview image',
+ help_bubble: "This image will be used when shared on social media" %>
+```
+
+## Complete Form Example
+
+Here's a complete example showing various FormBuilder methods:
+
+```erb
+<div class="card mb-4">
+ <div class="card-header">
+ <h5 class="card-title">
+ <%= Spree.t(:general_settings) %>
+ </h5>
+ </div>
+
+ <div class="card-body">
+ <%= f.spree_text_field :name,
+ required: true,
+ help: "Product name as displayed to customers" %>
+
+ <%= f.spree_text_field :sku,
+ label: "SKU",
+ help_bubble: "Stock Keeping Unit - unique product identifier" %>
+
+ <%= f.spree_number_field :price,
+ required: true,
+ step: 0.01,
+ min: 0 %>
+
+ <%= f.spree_rich_text_area :description,
+ help: "Detailed product description with rich formatting" %>
+
+ <%= f.spree_collection_select :tax_category_id,
+ Spree::TaxCategory.all,
+ :id,
+ :name,
+ { include_blank: 'None', required: true },
+ {} %>
+
+ <%= f.spree_date_field :available_on,
+ label: "Available Date",
+ help: "Date when product becomes available for purchase" %>
+
+ <%= f.spree_check_box :active,
+ label: "Active" %>
+ </div>
+</div>
+```
+
+## Error Handling
+
+All FormBuilder methods automatically display validation errors below the field when present:
+
+```erb
+<%= f.spree_text_field :name %>
+```
+
+If `@product.errors[:name]` contains errors, they will be displayed automatically in red text below the input field.
+
+## Internationalization
+
+Labels are automatically translated using Rails I18n. The FormBuilder looks for translations in this order:
+
+1. Custom label passed via `:label` option
+2. `spree.{attribute_name}` key
+3. `activerecord.attributes.spree/{model_name}.{attribute_name}` key
+
+Example translations:
+
+```yaml
+# config/locales/en.yml
+en:
+ spree:
+ name: "Product Name"
+ sku: "SKU Code"
+ activerecord:
+ attributes:
+ spree/product:
+ available_on: "Available On Date"
+ discontinue_on: "Discontinuation Date"
+```
+
+## Styling and CSS Classes
+
+All FormBuilder methods use consistent styling:
+
+- **Form groups:** Each field is wrapped in a `.form-group` div
+- **Input classes:** Text inputs use `.form-control` class
+- **Select classes:** Dropdowns use `.custom-select` class
+- **Checkboxes/Radios:** Use `.custom-control`, `.custom-checkbox`, `.custom-radio` classes
+
+You can add additional classes via the `:class` option:
+
+```erb
+<%= f.spree_text_field :name, class: 'form-control-lg' %>
+```
+
+## Best Practices
+
+<Check>
+ **Use the Spree FormBuilder methods** instead of standard Rails helpers for consistent styling
+</Check>
+
+<Check>
+ **Add `:required` option** to required fields for visual indication
+</Check>
+
+<Check>
+ **Use `:help` text** to provide guidance for complex fields
+</Check>
+
+<Check>
+ **Use `:help_bubble`** for additional context without cluttering the form
+</Check>
+
+<Check>
+ **Enable autocomplete** on selects with many options (> 20 items)
+</Check>
diff --git a/docs/developer/admin/helper-methods.mdx b/docs/developer/admin/helper-methods.mdx
index e87dba2584..a337192112 100644
--- a/docs/developer/admin/helper-methods.mdx
+++ b/docs/developer/admin/helper-methods.mdx
@@ -6,75 +6,312 @@ sidebarTitle: Helper Methods
import SpreeStore from '/snippets/objects/spree_store.mdx'
import SpreeVendor from '/snippets/objects/spree_vendor.mdx'
-Here you can find a list of helper methods that are available in the Admin Dashboard that you can use in every template.
+Helper methods available in the Admin Dashboard for navigation, links, and utility functions.
-<Warning>
-The list is incomplete.
-</Warning>
+<Info>
+ For UI components that render HTML elements (Dropdowns, Dialogs, Icons, etc.), see the [Components](/developer/admin/components) documentation.
+</Info>
+
+## Navigation Helpers
+
+### `nav_item`
+
+Creates a navigation item with optional icon.
+
+```erb
+<%= nav_item 'Dashboard', spree.admin_dashboard_path %>
+<%= nav_item 'Products', spree.admin_products_path, icon: 'package' %>
+<%= nav_item 'Orders', spree.admin_orders_path, active: true %>
+```
+
+With a block for custom content:
+
+```erb
+<%= nav_item spree.admin_products_path do %>
+ Products <span class="badge badge-primary">New</span>
+<% end %>
+```
+
+| Option | Type | Description |
+|--------|------|-------------|
+| `label` | String | The text to display |
+| `url` | String | The URL for the link (required) |
+| `icon` | String | Icon name to prepend |
+| `active` | Boolean | Force active state |
+| `data` | Hash | Data attributes |
+
+### `link_to_with_icon`
+
+Creates a link with an icon.
+
+```erb
+<%= link_to_with_icon 'eye', "View Order", spree.admin_order_path(order), class: "btn btn-primary" %>
+<%= link_to_with_icon 'pencil', "Edit", edit_path, class: "dropdown-item" %>
+<%= link_to_with_icon 'trash', "Delete", delete_path, no_text: true, title: "Delete item" %>
+```
+
+| Parameter | Type | Description |
+|-----------|------|-------------|
+| `icon_name` | String | Icon name from [Tabler Icons](https://tabler.io/icons) |
+| `text` | String | Link text |
+| `url` | String | Link URL (use `spree.` routes for internal links) |
+| `no_text` | Boolean | Show only icon with text as tooltip |
+| `title` | String | Tooltip text |
+
+### `active_link_to_with_icon`
+
+Same as `link_to_with_icon`, but adds the `active` class if the current page matches the URL.
+
+```erb
+<%= active_link_to_with_icon 'package', "Products", spree.admin_products_path, class: "nav-link" %>
+```
+
+### `link_to_edit`
+
+Renders an edit button for a resource. Only renders if the user has `update` permission.
+
+```erb
+<%= link_to_edit(@product) %>
+<%= link_to_edit(@product, url: custom_edit_path(@product)) %>
+<%= link_to_edit(@order, class: 'btn btn-primary') %>
+```
+
+| Option | Type | Default | Description |
+|--------|------|---------|-------------|
+| `url` | String | auto | Custom URL (defaults to `edit_object_url(resource)`) |
+| `class` | String | `btn btn-light btn-sm` | CSS classes |
+| `data` | Hash | `{action: 'edit'}` | Data attributes |
+
+### `link_to_delete`
+
+Renders a delete button with confirmation. Only renders if the user has `destroy` permission.
+
+```erb
+<%= link_to_delete(@product) %>
+<%= link_to_delete(@product, name: 'Remove') %>
+<%= link_to_delete(@product, no_text: true) %>
+<%= link_to_delete(@product, icon: 'x') %>
+```
+
+| Option | Type | Default | Description |
+|--------|------|---------|-------------|
+| `url` | String | auto | Custom URL (defaults to `object_url(resource)`) |
+| `name` | String | "Delete" | Button text |
+| `icon` | String | `trash` | Custom icon |
+| `no_text` | Boolean | false | Show only icon |
+| `class` | String | `btn btn-danger btn-sm` | CSS classes |
+| `data` | Hash | confirm + method | Data attributes |
+
+### `button`
+
+Renders a submit button with optional icon and loading state.
+
+```erb
+<%= button(Spree.t('actions.save')) %>
+<%= button(Spree.t('actions.save'), 'device-floppy') %>
+<%= button('Submit', 'send', 'submit', class: 'btn-success') %>
+```
+
+| Parameter | Type | Default | Description |
+|-----------|------|---------|-------------|
+| `text` | String | required | Button text |
+| `icon_name` | String | nil | Optional icon |
+| `button_type` | String | `submit` | Button type |
+| `class` | String | `btn-primary` | CSS classes |
+
+### `external_link_to`
+
+Renders an external link that opens in a new tab with an indicator icon.
+
+```erb
+<%= external_link_to 'Documentation', 'https://docs.spreecommerce.org' %>
+<%= external_link_to 'GitHub', 'https://github.com/spree/spree' %>
+```
+
+With a block:
+
+```erb
+<%= external_link_to 'https://example.com' do %>
+ <strong>Custom content</strong>
+<% end %>
+```
+
+| Parameter | Type | Description |
+|-----------|------|-------------|
+| `label` | String | Link text |
+| `url` | String | External URL |
+| `target` | Symbol | Default: `:blank` |
+| `rel` | Symbol | Default: `:nofollow` |
+
+### `external_page_preview_link`
+
+Renders a link to preview a resource on the storefront.
+
+```erb
+<%= external_page_preview_link(@product) %>
+<%= external_page_preview_link(@post) %>
+```
+
+### `page_header_back_button`
+
+Renders a back button for page headers with smart return URL handling.
+
+```erb
+<%= page_header_back_button(spree.admin_products_path) %>
+<%= page_header_back_button(spree.admin_products_path, @product) %>
+<%= page_header_back_button(spree.admin_orders_path, @order, 'Back to Orders') %>
+```
+
+| Parameter | Type | Description |
+|-----------|------|-------------|
+| `default_url` | String | Default URL to navigate back to |
+| `object` | Object | Optional object to check for stored return URL in session |
+| `label` | String | Optional label text |
-## `active_badge`
+### `per_page_dropdown`
-Displays a badge with a color based on the condition.
+Renders a dropdown for selecting items per page on index pages.
```erb
-<%= active_badge(order.sent_to_erp_at.blank?) %>
+<%= per_page_dropdown %>
```
-If the condition is true, it will render
+Automatically detects the resource type and provides appropriate options based on configuration.
-```html
-<span class="badge badge-success">Active</span>
+### `link_to_export_modal`
+
+Renders a button to open the export modal. Only renders if user can create exports.
+
+```erb
+<%= link_to_export_modal %>
+```
+
+## Store Helpers
+
+Helpers for store-specific options and unit systems.
+
+### `weight_units`
+
+Returns weight unit options based on the store's unit system.
+
+```erb
+<%= f.select :weight_unit, weight_units %>
```
-If the condition is false, it will render
+**Returns:**
+- Metric: `[["Kilogram", "kg"], ["Gram", "g"]]`
+- Imperial: `[["Pound", "lb"], ["Ounce", "oz"]]`
+
+| Parameter | Type | Default | Description |
+|-----------|------|---------|-------------|
+| `store` | Spree::Store | `current_store` | Store to check unit system |
+
+### `dimension_units`
-```html
-<span class="badge badge-danger">Inactive</span>
+Returns dimension unit options based on the store's unit system.
+
+```erb
+<%= f.select :dimension_unit, dimension_units %>
```
-You can also pass a custom label to the badge:
+**Returns:**
+- Metric: `[["Centimeter", "cm"], ["Millimeter", "mm"]]`
+- Imperial: `[["Inch", "in"], ["Foot", "ft"]]`
-<ParamField query="label" type="string">
- Custom text to display in the badge. If not provided, will show "Active"/"Inactive" based on the condition.
-</ParamField>
+| Parameter | Type | Default | Description |
+|-----------|------|---------|-------------|
+| `store` | Spree::Store | `current_store` | Store to check unit system |
-## `active_link_to_with_icon`
+### `unit_systems`
-Same as [link_to_with_icon](/developer/admin/helper-methods#link-to-with-icon), but it will add the `active` class if the current page is the same as the link.
+Returns available unit system options.
```erb
-<%= active_link_to_with_icon 'eye', "View Order in ERP", spree.admin_order_path(order), class: "btn btn-primary" %>
+<%= f.select :unit_system, unit_systems %>
```
-You can also pass a custom `active` condition.
+**Returns:** `[["Metric System", "metric"], ["Imperial System", "imperial"]]`
+
+### `display_on_options`
+
+Returns display location options for calculators and payment/shipping methods.
```erb
-<%= active_link_to_with_icon 'eye', "View Order in ERP", spree.admin_order_path(order), class: "btn btn-primary", active: order.sent_to_erp_at.blank? %>
+<%= f.select :display_on, display_on_options %>
```
-## `current_currency`
+**Returns:** `[["Both", "both"], ["Backend", "back_end"], ["Frontend", "front_end"]]`
-Returns the currently selected currency. By default in Admin Dashboard this will be `store.default_currency`. This can be changed in the `Settings -> Store Defaults` page.
+## Turbo Helpers
+
+Helpers for Turbo Streams and Turbo-enhanced forms.
+
+### `turbo_close_dialog`
+
+Returns a Turbo Stream response that closes the main dialog.
```erb
-<%= current_currency %>
+<%# In a turbo_stream.erb response %>
+<%= turbo_close_dialog %>
```
-will return
+### `turbo_render_alerts`
+
+Returns a Turbo Stream response that updates the alerts frame.
+```erb
+<%= turbo_render_alerts %>
+<%= turbo_render_alerts(:custom_alerts) %>
```
-USD
+
+| Parameter | Type | Default | Description |
+|-----------|------|---------|-------------|
+| `frame_name` | Symbol | `:alerts` | Turbo frame to update |
+
+### `turbo_save_button_tag`
+
+Creates a save button with loading state for Turbo forms.
+
+```erb
+<%= turbo_save_button_tag %>
+<%= turbo_save_button_tag('Update Product') %>
+<%= turbo_save_button_tag('Save', class: 'btn btn-success') %>
```
-## `current_store`
+**Features:**
+- Shows spinner during submission
+- Integrates with `turbo-submit-button` Stimulus controller
+- Prevents double submissions
+
+| Parameter | Type | Default | Description |
+|-----------|------|---------|-------------|
+| `label` | String | "Save" | Button label |
+| `class` | String | `btn btn-primary text-center` | CSS classes |
+
+## Context Helpers
+
+### `current_store`
+
+Returns the current store instance.
<ResponseField name="current_store" type="Spree::Store" description="The current store object.">
<SpreeStore />
</ResponseField>
-Returns the current store [Spree::Store](https://github.com/spree/spree/blob/master/core/app/models/spree/store.rb) instance.
+```erb
+<%= current_store.name %>
+<%= current_store.default_currency %>
+```
+
+### `current_currency`
+
+Returns the currently selected currency for the admin session.
+
+```erb
+<%= current_currency %> <%# => "USD" %>
+```
-## `current_vendor`
+### `current_vendor`
<Info>
Available only in [Spree Enterprise Edition](https://spreecommerce.com/pricing).
@@ -84,93 +321,144 @@ Returns the current store [Spree::Store](https://github.com/spree/spree/blob/mas
<SpreeVendor />
</ResponseField>
-## `icon`
+### `supported_currencies`
-Displays an icon.
+Returns the list of supported currencies for the current store.
```erb
-<%= icon('eye') %>
+<%= supported_currencies %> <%# => ["USD", "EUR", "GBP"] %>
```
-Will render
+### `try_spree_current_user`
+
+Returns the current user object or `nil` if not signed in.
+
+```erb
+<%= try_spree_current_user&.email %>
-```html
-<i class="ti ti-eye"></i>
+<% if try_spree_current_user.present? %>
+ Signed in as <%= try_spree_current_user.email %>
+<% end %>
```
-We use [Tabler Icons](https://tabler.io/icons) library for icons.
+### `available_countries_iso`
-You can also pass additional options such as:
+Returns ISO codes for countries available for checkout in the current store.
-<ParamField query="class" type="string">
- Add additional CSS classes to the icon
-</ParamField>
+```erb
+<%= available_countries_iso %> <%# => ["US", "CA", "GB"] %>
+```
-<ParamField query="style" type="string">
- Add additional inline styles to the icon
-</ParamField>
+## Utility Helpers
-<ParamField query="height" type="integer">
- Set the height of the icon in pixels
-</ParamField>
+### `flag_emoji`
+
+Returns the flag emoji for a country ISO code.
```erb
-<%= icon('eye', class: 'mr-2', height: 20, style: 'color: red;') %>
+<%= flag_emoji('US') %> <%# => 🇺🇸 %>
+<%= flag_emoji('GB') %> <%# => 🇬🇧 %>
+<%= flag_emoji('JP') %> <%# => 🇯🇵 %>
```
-will render
+### `required_span_tag`
+
+Renders a red asterisk indicator for required fields.
-```html
-<i class="ti ti-eye mr-2" style="font-size: 20px; color: red;"></i>
+```erb
+<%= label_tag :name %>
+<%= required_span_tag %>
```
-## `local_time`
+**Renders:** `<span class="required font-weight-bold text-danger"> *</span>`
+
+### `error_message_on`
-Displays a time in the user's timezone in a human readable format (based on the browser's timezone).
+Renders validation error messages for a form field.
```erb
-<%= local_time(order.sent_to_erp_at) %>
+<%= error_message_on(@product, :name) %>
+<%= error_message_on(@order, :email) %>
```
-Provided by [local_time gem](https://github.com/basecamp/local_time).
+**Renders:** `<span class="formError">can't be blank</span>`
-## `link_to_with_icon`
+### `settings_area?`
-Creates a link with an icon.
+Returns `true` if the current page is in the settings area.
+
+```erb
+<% if settings_area? %>
+ <%= render 'spree/admin/shared/settings_sidebar' %>
+<% end %>
+```
+
+### `enterprise_edition?`
+
+Returns `true` if Spree Enterprise Edition is installed.
```erb
-<%= link_to_with_icon 'eye', "View Order in ERP", "https://erp.com/orders/#{order.number}", class: "btn btn-primary" %>
+<% if enterprise_edition? %>
+ <%= render 'spree/admin/vendors/selector' %>
+<% end %>
```
-* `eye` is the icon name.
-* `View Order in ERP` is the link text.
-* `https://erp.com/orders/#{order.number}` is the link url. For internal links, please use `spree.` routes helper, eg. `spree.admin_order_path(order)`.
-* `btn btn-primary` is the bootstrap class for styling the link
+### `allowed_file_types_for_upload`
+
+Returns allowed file types for Active Storage uploads.
+
+```erb
+<%= allowed_file_types_for_upload %>
+<%# => ["image/png", "image/jpeg", "image/gif", "image/webp"] %>
+```
-## `supported_currencies`
+### `render_admin_partials`
-Returns the list of supported currencies for the current store as an array of strings.
+Renders all registered partials for an injection point.
```erb
-<%= supported_currencies %>
+<%= render_admin_partials(:product_form, f: f, product: @product) %>
+<%= render_admin_partials(:order_page_sidebar, order: @order) %>
```
-will return
+See [Extending UI](/developer/admin/extending-ui) for more information about injection points.
-```ruby
-["USD", "EUR"]
+## Preference Helpers
+
+Helpers for rendering preference fields in settings forms.
+
+### `preference_fields`
+
+Renders all preference fields for an object.
+
+```erb
+<%= preference_fields(@payment_method, f) %>
+<%= preference_fields(@calculator, f, i18n_scope: 'spree.calculator') %>
```
-## `try_spree_current_user`
+### `preference_field`
-Returns the current user object (class depends on the `Spree.admin_user_class` configuration). If the user is not signed in, it will return `nil`.
+Renders a single preference field.
```erb
-<%= try_spree_current_user.email %>
+<%= preference_field(@payment_method, f, :api_key) %>
```
-If you want to check if the user is signed in, you can use the following:
+### `preference_field_for`
+
+Renders a form field based on preference type.
```erb
-<%= try_spree_current_user.present? %>
-```
\ No newline at end of file
+<%= preference_field_for(f, :preferred_api_key, type: :string) %>
+<%= preference_field_for(f, :preferred_test_mode, type: :boolean) %>
+<%= preference_field_for(f, :preferred_amount, type: :decimal, step: 0.01) %>
+```
+
+| Type | Rendered Field |
+|------|----------------|
+| `:integer` | Number field |
+| `:decimal` | Number field with step |
+| `:boolean` | Checkbox |
+| `:string` | Text field |
+| `:password` | Password field |
+| `:text` | Text area |
diff --git a/docs/developer/admin/navigation.mdx b/docs/developer/admin/navigation.mdx
index 8b80ee7327..0d8776b3b3 100644
--- a/docs/developer/admin/navigation.mdx
+++ b/docs/developer/admin/navigation.mdx
@@ -5,15 +5,412 @@ sidebarTitle: Navigation
Spree Admin Dashboard provides a flexible navigation system that allows you to easily extend the sidebar navigation with your own menu items without modifying the core codebase. This enables safe updates while maintaining your customizations.
-## How it works
+<Info>
+ Starting with Spree 5.2, the navigation system uses a declarative API accessible via `Spree.admin.navigation`. This allows you to programmatically add, modify, and remove navigation items directly in your initializers.
+</Info>
+
+## Basic Usage
+
+Add navigation items in your `config/initializers/spree.rb` file:
+
+```ruby config/initializers/spree.rb
+Rails.application.config.after_initialize do
+ sidebar_nav = Spree.admin.navigation.sidebar
+
+ sidebar_nav.add :brands,
+ label: :brands,
+ url: :admin_brands_path,
+ icon: 'award',
+ position: 35,
+ active: -> { controller_name == 'brands' },
+ if: -> { can?(:manage, Spree::Brand) }
+end
+```
+
+## Available Options
+
+All navigation items support the following options:
+
+<ParamField path="label" type="Symbol or String" required>
+ The text label for the navigation item. Can be a symbol (translation key using `Spree.t`) or a string.
+</ParamField>
+
+<ParamField path="url" type="Symbol or Lambda" required>
+ The URL for the navigation item. Can be a route helper symbol (`:admin_brands_path`) or a lambda returning a URL.
+</ParamField>
+
+<ParamField path="icon" type="String">
+ Icon name from [Tabler Icons](https://tabler.io/icons).
+</ParamField>
+
+<ParamField path="position" type="Integer" default="0">
+ Numeric position in the menu. Lower numbers appear first.
+</ParamField>
+
+<ParamField path="active" type="Lambda">
+ Lambda to determine if the link should be highlighted as active. Receives view context.
+</ParamField>
+
+<ParamField path="if" type="Lambda">
+ Conditional display logic. The item only appears if this lambda returns true. Has access to view context helpers like `can?`, `current_store`, etc.
+</ParamField>
+
+<ParamField path="badge" type="String or Lambda">
+ Badge text/count to display next to the label. Can be a string or lambda that returns a value.
+</ParamField>
+
+<ParamField path="badge_class" type="String">
+ CSS class for badge styling (e.g., `'badge-info'`, `'badge-warning'`).
+</ParamField>
+
+<ParamField path="tooltip" type="String">
+ Tooltip text shown on hover.
+</ParamField>
+
+<ParamField path="target" type="String">
+ Link target attribute (e.g., `'_blank'` to open in a new tab).
+</ParamField>
+
+<ParamField path="section_label" type="String">
+ Creates a section divider with the given label instead of a clickable link.
+</ParamField>
+
+## Navigation Contexts
+
+The navigation system supports multiple contexts. Spree provides predefined contexts for common use cases, and you can register custom contexts for your specific needs.
+
+### Sidebar Navigation
+
+The main sidebar navigation:
+
+```ruby
+sidebar_nav = Spree.admin.navigation.sidebar
+```
+
+### Settings Navigation
+
+Navigation in the Settings area:
+
+```ruby
+settings_nav = Spree.admin.navigation.settings
+```
+
+### Page Tab Navigation
+
+Spree provides several predefined tab contexts for common admin pages:
+
+```ruby
+tax_tabs = Spree.admin.navigation.tax_tabs
+shipping_tabs = Spree.admin.navigation.shipping_tabs
+team_tabs = Spree.admin.navigation.team_tabs
+stock_tabs = Spree.admin.navigation.stock_tabs
+returns_tabs = Spree.admin.navigation.returns_tabs
+developers_tabs = Spree.admin.navigation.developers_tabs
+audit_tabs = Spree.admin.navigation.audit_tabs
+```
+
+### Registering Contexts
+
+Use `register_context` to create a new navigation context:
+
+```ruby
+# Returns a Spree::Admin::Navigation instance
+custom_tabs = Spree.admin.navigation.register_context(:custom_tabs)
+```
+
+<ParamField path="name" type="Symbol or String" required>
+ The unique name for the navigation context. Will be converted to a symbol internally.
+</ParamField>
+
+**Returns:** `Spree::Admin::Navigation` - The navigation context instance
+
+**Note:** Calling `register_context` multiple times with the same name returns the same instance (idempotent).
+
+### Custom Tab Contexts
+
+You can create custom tab contexts for your own admin pages using `register_context`:
+
+```ruby config/initializers/spree.rb
+Rails.application.config.after_initialize do
+ # Register custom tab navigation for your brands page
+ brand_tabs = Spree.admin.navigation.register_context(:brand_tabs)
+
+ brand_tabs.add :active_brands,
+ label: 'Active Brands',
+ url: -> { spree.admin_brands_path(status: 'active') },
+ position: 10,
+ active: -> { params[:status] == 'active' }
+
+ brand_tabs.add :archived_brands,
+ label: 'Archived Brands',
+ url: -> { spree.admin_brands_path(status: 'archived') },
+ position: 20,
+ active: -> { params[:status] == 'archived' }
+end
+```
+
+Then render the tabs in your view using the `render_tab_navigation` helper:
+
+```erb app/views/spree/admin/brands/index.html.erb
+<%= render_tab_navigation(:brand_tabs) %>
+```
+
+<Tip>
+Always register custom contexts in your initializer before accessing them. Attempting to access an unregistered context will raise a `NoMethodError`.
+</Tip>
+
+### Listing All Contexts
+
+You can list all registered navigation contexts:
+
+```ruby
+# Returns an array of context names (symbols)
+Spree.admin.navigation.contexts
+# => [:sidebar, :settings, :brand_tabs, :inventory_tabs]
+```
+
+### Checking If a Context Exists
+
+```ruby
+# Check if a context has been created
+Spree.admin.navigation.context?(:brand_tabs)
+# => true or false
+```
+
+## Creating Submenus
+
+Add child items using a block:
+
+```ruby config/initializers/spree.rb
+sidebar_nav.add :brands,
+ label: :brands,
+ url: :admin_brands_path,
+ icon: 'award',
+ position: 35,
+ active: -> { %w[brands brand_categories].include?(controller_name) },
+ if: -> { can?(:manage, Spree::Brand) } do |brands|
+
+ brands.add :all_brands,
+ label: 'All Brands',
+ url: :admin_brands_path,
+ position: 10,
+ active: -> { controller_name == 'brands' }
+
+ brands.add :brand_categories,
+ label: 'Brand Categories',
+ url: :admin_brand_categories_path,
+ position: 20,
+ active: -> { controller_name == 'brand_categories' },
+ if: -> { can?(:manage, Spree::BrandCategory) }
+end
+```
+
+## Modifying Existing Navigation
+
+### Finding Navigation Items
+
+```ruby
+sidebar_nav = Spree.admin.navigation.sidebar
+products_nav = sidebar_nav.find(:products)
+```
+
+### Adding to Existing Submenus
+
+```ruby
+products_nav = sidebar_nav.find(:products)
+
+if products_nav
+ products_nav.add :brands,
+ label: :brands,
+ url: :admin_brands_path,
+ position: 50,
+ active: -> { controller_name == 'brands' },
+ if: -> { can?(:manage, Spree::Brand) }
+end
+```
+
+### Removing Navigation Items
+
+```ruby
+sidebar_nav.remove(:vendors)
+```
+
+### Updating Navigation Items
+
+```ruby
+sidebar_nav.update(:products, label: 'Catalog', icon: 'shopping-cart')
+```
+
+### Replacing Navigation Items
+
+```ruby
+sidebar_nav.replace(:products, label: 'Products', icon: 'package') do |products|
+ # Define new submenu structure
+end
+```
+
+### Moving Navigation Items
+
+```ruby
+# Move to specific position
+sidebar_nav.move(:brands, position: 25)
+
+# Move before another item
+sidebar_nav.move(:brands, before: :products)
+
+# Move after another item
+sidebar_nav.move(:brands, after: :products)
+
+# Move to first position
+sidebar_nav.move(:brands, position: :first)
+
+# Move to last position
+sidebar_nav.move(:brands, position: :last)
+```
+
+## Advanced Examples
+
+### Navigation with Dynamic Badge
+
+```ruby
+sidebar_nav.add :orders,
+ label: :orders,
+ url: :admin_orders_path,
+ icon: 'inbox',
+ position: 20,
+ active: -> { controller_name == 'orders' },
+ if: -> { can?(:manage, Spree::Order) },
+ badge: -> {
+ count = Spree::Order.ready_to_ship.count
+ count if count.positive?
+ },
+ badge_class: 'badge-warning'
+```
+
+### Section Dividers
+
+```ruby
+sidebar_nav.add :settings_section,
+ section_label: 'Settings',
+ position: 90
+```
+
+### Dynamic URLs
+
+```ruby
+sidebar_nav.add :store_settings,
+ label: :settings,
+ url: -> { spree.edit_admin_store_path(section: 'general-settings') },
+ icon: 'settings',
+ position: 100
+```
+
+### Complex Conditional Display
+
+```ruby
+sidebar_nav.add :vendors,
+ label: :vendors,
+ url: 'https://spreecommerce.org/marketplace-ecommerce/',
+ icon: 'heart-handshake',
+ position: 35,
+ if: -> { can?(:manage, current_store) && !defined?(SpreeEnterprise) },
+ badge: 'Enterprise',
+ tooltip: 'Multi-Vendor Marketplace is available in the Enterprise Edition',
+ target: '_blank'
+```
+
+### Complex Active State Logic
+
+```ruby
+sidebar_nav.add :products,
+ label: :products,
+ url: :admin_products_path,
+ icon: 'package',
+ position: 30,
+ active: -> {
+ %w[products external_categories taxons taxonomies option_types option_values
+ properties stock_items stock_transfers variants digital_assets].include?(controller_name)
+ },
+ if: -> { can?(:manage, Spree::Product) }
+```
+
+## Best Practices
+
+<CardGroup cols={2}>
+ <Card title="Authorization" icon="shield-check">
+ Always use `if: -> { can?(...) }` to ensure users only see navigation items they have permission to access.
+ </Card>
+
+ <Card title="Translations" icon="language">
+ Use symbols for labels (e.g., `label: :brands`) to support internationalization via `Spree.t`.
+ </Card>
+
+ <Card title="Active States" icon="pointer">
+ Define clear active state logic using lambdas to highlight the current section properly.
+ </Card>
+
+ <Card title="Positioning" icon="list-numbers">
+ Use consistent position intervals (e.g., 10, 20, 30) to leave room for future additions.
+ </Card>
+</CardGroup>
+
+### Common Positioning Reference
+
+Main sidebar navigation positions:
+
+- Getting Started: 5
+- Home: 10
+- Orders: 20
+- Returns: 25
+- Products: 30
+- Customers: 40
+- Promotions: 50
+- Reports: 60
+- Storefront: 70
+- Integrations: 80
+- Settings Section: 90
+- Settings: 100
+- Admin Users: 110
+
+### Troubleshooting
+
+<AccordionGroup>
+ <Accordion title="Navigation item not appearing">
+ - Restart your server after modifying initializers
+ - Check authorization: ensure `if: -> { can?(...) }` returns true
+ - Verify the item isn't hidden by a parent's `if` condition
+ </Accordion>
+
+ <Accordion title="Active state not working">
+ - Ensure `active:` lambda returns true/false
+ - Check that controller_name or other conditions match correctly
+ - For submenus, ensure parent uses same active logic as children
+ </Accordion>
+
+ <Accordion title="Badge not displaying">
+ - Ensure the badge lambda returns a non-nil value
+ - Check that the badge value is truthy (empty strings won't display)
+ - For numeric badges, ensure the count is greater than 0
+ </Accordion>
+</AccordionGroup>
+
+---
+
+## Previous versions
+
+<Warning>
+The following documentation applies to Spree 5.1 and earlier. If you're using Spree 5.2+, please refer to the documentation above.
+</Warning>
+
+### How it works
The admin navigation system works through injection points defined throughout the sidebar. You can inject custom navigation items into these predefined locations, add new top-level menu items, or create nested submenus.
-## Navigation Injection Points
+### Navigation Injection Points
The main navigation file is located at `admin/app/views/spree/admin/shared/sidebar/_store_nav.html.erb` and provides several injection points:
-### Available Injection Points
+#### Available Injection Points
<AccordionGroup>
<Accordion title="store_nav_partials">
@@ -61,7 +458,7 @@ The main navigation file is located at `admin/app/views/spree/admin/shared/sideb
</Accordion>
</AccordionGroup>
-## Using the nav_item Helper
+### Using the nav_item Helper
The `nav_item` helper method is provided by `Spree::Admin::NavigationHelper` and makes it easy to create properly formatted navigation items.
@@ -71,7 +468,7 @@ The `nav_item` helper method is provided by `Spree::Admin::NavigationHelper` and
nav_item(label = nil, url, icon: nil, active: nil, data: {})
```
-### Parameters
+#### Parameters
<ParamField path="label" type="String">
The text label for the navigation item. Can be HTML-safe content.
@@ -93,13 +490,13 @@ nav_item(label = nil, url, icon: nil, active: nil, data: {})
Additional data attributes to add to the link element.
</ParamField>
-### Basic Usage
+#### Basic Usage
```erb
<%= nav_item(Spree.t(:custom_section), spree.admin_custom_path, icon: 'star') %>
```
-### With Active State
+#### With Active State
```erb
<%= nav_item(
@@ -110,7 +507,7 @@ nav_item(label = nil, url, icon: nil, active: nil, data: {})
) %>
```
-### With Block Content
+#### With Block Content
```erb
<%= nav_item(nil, spree.admin_dashboard_path, icon: 'home') do %>
@@ -120,20 +517,20 @@ nav_item(label = nil, url, icon: nil, active: nil, data: {})
<% end %>
```
-## Adding a Simple Navigation Item
+### Adding a Simple Navigation Item
Let's add a new "Inventory" navigation item to the main sidebar.
-### Step 1: Create the Partial
+#### Step 1: Create the Partial
```bash
mkdir -p app/views/spree/admin/shared
touch app/views/spree/admin/shared/_inventory_nav.html.erb
```
-### Step 2: Add Navigation Code
+#### Step 2: Add Navigation Code
-```erb
+```erb app/views/spree/admin/shared/_inventory_nav.html.erb
<% if can?(:manage, Spree::Inventory) %>
<%= nav_item(
Spree.t(:inventory),
@@ -148,33 +545,42 @@ touch app/views/spree/admin/shared/_inventory_nav.html.erb
Always wrap your navigation items with authorization checks using `can?()` to ensure users only see menu items they have permission to access.
</Tip>
-### Step 3: Register the Partial
+#### Step 3: Register the Partial
Add this to your `config/initializers/spree.rb`:
-```ruby
-Rails.application.config.spree_admin.store_nav_partials << 'spree/admin/shared/inventory_nav'
-```
-
-### Step 4: Add Translations
+<Tabs>
+ <Tab title="Spree 5.2+">
+ ```ruby config/initializers/spree.rb
+ Spree.admin.navigation.store << 'spree/admin/shared/inventory_nav'
+ ```
+ </Tab>
+ <Tab title="Spree 5.1 and below">
+ ```ruby config/initializers/spree.rb
+ Rails.application.config.spree_admin.store_nav_partials << 'spree/admin/shared/inventory_nav'
+ ```
+ </Tab>
+</Tabs>
+
+#### Step 4: Add Translations
In your `config/locales/en.yml`:
-```yaml
+```yaml config/locales/en.yml
en:
spree:
inventory: "Inventory"
```
-### Step 5: Restart Your Server
+#### Step 5: Restart Your Server
Restart your web server to load the initializer changes. The navigation item should now appear in the sidebar.
-## Creating Nested Navigation (Submenus)
+### Creating Nested Navigation (Submenus)
To create a navigation item with a submenu, you need to use the `nav-submenu` class and manage the visibility based on the active state.
-### Example: Adding a Nested Menu
+#### Example: Adding a Nested Menu
```erb
<% inventory_active = %w[inventory warehouses stock_movements].include?(controller_name) %>
@@ -209,7 +615,7 @@ To create a navigation item with a submenu, you need to use the `nav-submenu` cl
<% end %>
```
-### Key Points for Submenus
+#### Key Points for Submenus
1. **Active State Variable**: Define a variable to track when any item in the menu group is active:
```erb
@@ -236,9 +642,9 @@ To create a navigation item with a submenu, you need to use the `nav-submenu` cl
<%= render_admin_partials(:store_inventory_nav_partials) %>
```
-## Advanced Examples
+### Advanced Examples
-### Navigation with Badge
+#### Navigation with Badge
```erb
<%= nav_item(nil, spree.admin_orders_path, icon: 'inbox', active: orders_active) do %>
@@ -248,7 +654,7 @@ To create a navigation item with a submenu, you need to use the `nav-submenu` cl
<% end %>
```
-### Navigation with Complex Active Logic
+#### Navigation with Complex Active Logic
```erb
<% products_active = %w[products external_categories taxons taxonomies option_types option_values properties stock_items stock_transfers].include?(controller_name) || request.path.include?('products') %>
@@ -261,7 +667,7 @@ To create a navigation item with a submenu, you need to use the `nav-submenu` cl
) %>
```
-### Extending Existing Submenus
+#### Extending Existing Submenus
To add an item to an existing submenu (e.g., Products), use the appropriate injection point:
@@ -279,11 +685,20 @@ To add an item to an existing submenu (e.g., Products), use the appropriate inje
**Register in** `config/initializers/spree.rb`:
-```ruby
-Rails.application.config.spree_admin.store_products_nav_partials << 'spree/admin/shared/custom_products_nav'
-```
-
-## Navigation in Settings Mode
+<Tabs>
+ <Tab title="Spree 5.2+">
+ ```ruby config/initializers/spree.rb
+ Spree.admin.navigation.store_products << 'spree/admin/shared/custom_products_nav'
+ ```
+ </Tab>
+ <Tab title="Spree 5.1 and below">
+ ```ruby config/initializers/spree.rb
+ Rails.application.config.spree_admin.store_products_nav_partials << 'spree/admin/shared/custom_products_nav'
+ ```
+ </Tab>
+</Tabs>
+
+### Navigation in Settings Mode
When the admin is in "Settings mode" (the dedicated settings view), use the `settings_nav_partials` injection point:
@@ -296,11 +711,20 @@ When the admin is in "Settings mode" (the dedicated settings view), use the `set
Register with:
-```ruby
-Rails.application.config.spree_admin.settings_nav_partials << 'spree/admin/shared/custom_settings_nav'
-```
-
-## Best Practices
+<Tabs>
+ <Tab title="Spree 5.2+">
+ ```ruby config/initializers/spree.rb
+ Spree.admin.navigation.settings << 'spree/admin/shared/custom_settings_nav'
+ ```
+ </Tab>
+ <Tab title="Spree 5.1 and below">
+ ```ruby config/initializers/spree.rb
+ Rails.application.config.spree_admin.settings_nav_partials << 'spree/admin/shared/custom_settings_nav'
+ ```
+ </Tab>
+</Tabs>
+
+### Best Practices
<CardGroup cols={2}>
<Card title="Authorization" icon="shield-check">
@@ -328,33 +752,33 @@ Rails.application.config.spree_admin.settings_nav_partials << 'spree/admin/share
</Card>
</CardGroup>
-## Common Patterns
+### Common Patterns
-### Multiple Controller Check
+#### Multiple Controller Check
```erb
<% active = %w[orders shipments payments].include?(controller_name) %>
```
-### Path-based Check
+#### Path-based Check
```erb
<% active = request.path.include?('products') %>
```
-### Controller and Action Check
+#### Controller and Action Check
```erb
<% active = controller_name == 'dashboard' && action_name == 'show' %>
```
-### Parameters-based Check
+#### Parameters-based Check
```erb
<% active = params[:section] == 'general-settings' %>
```
-## Troubleshooting
+### Troubleshooting
<AccordionGroup>
<Accordion title="Navigation item not appearing">
@@ -385,7 +809,7 @@ Rails.application.config.spree_admin.settings_nav_partials << 'spree/admin/share
</Accordion>
</AccordionGroup>
-## Related Documentation
+### Related Documentation
- [Extending Admin UI](/developer/admin/extending-ui) - Learn about other UI injection points
- [Helper Methods](/developer/admin/helper-methods) - Explore other admin helper methods
diff --git a/docs/developer/contributing/developing-spree.mdx b/docs/developer/contributing/developing-spree.mdx
index caa8bf2671..215478070d 100644
--- a/docs/developer/contributing/developing-spree.mdx
+++ b/docs/developer/contributing/developing-spree.mdx
@@ -29,6 +29,12 @@ Clone your fork repository
## Create a sandbox application
+Install gem dependencies:
+
+ ```bash
+ bundle install
+ ```
+
Bellow command will setup a Rails application with Spree pre-installed with some data seeded:
```bash
@@ -41,15 +47,15 @@ This script will automatically install the necessary dependencies such as Ruby,
Go to the `sandbox` directory:
-```bash
-cd sandbox
-```
+ ```bash
+ cd sandbox
+ ```
And run the application using the following command:
-```bash
-bin/dev
-```
+ ```bash
+ bin/dev
+ ```
This will start the web server and all the necessary processes (such as Tailwind CSS compiler).
@@ -59,10 +65,10 @@ To access the Admin Panel, you can go to [http://localhost:3000/admin](http://lo
The default credentials for the Admin Panel are:
-```
-Password: spree123
-```
+ ```
+ Password: spree123
+ ```
### Performance in development mode
@@ -72,9 +78,9 @@ You may notice that your Spree store runs slower in development environment. Thi
Caching is disabled by default. To turn on caching please run:
-```bash
-bin/rails dev:cache
-```
+ ```bash
+ bin/rails dev:cache
+ ```
You will need to restart rails server after this change.
@@ -85,6 +91,10 @@ Create a new branch for your changes. Do not push changes to the main branch. Br
* bug fixes: `fix/order-recalculation-total-bug`
* features: `feature/my-new-amazing-feature`
+### Using AI tools for development
+
+Spree is ready to work nicely with AI tools such as Cursor or Claude Code. We already have Cursor rules for each module and global ones, as well as a global Claude Code rules file.
+
## Running Tests
We use [CircleCI](https://circleci.com/) to run the tests for Spree.
@@ -93,39 +103,39 @@ You can see the build statuses at [https://circleci.com/gh/spree/spree](https://
Each gem contains its own series of tests, and for each directory, you need to do a quick one-time creation of a test application and then you can use it to run the tests. For example, to run the tests for the core project.
-```bash
-cd core
-bundle exec rake test_app
-bundle exec rspec
-```
+ ```bash
+ cd core
+ bundle exec rake test_app
+ bundle exec rspec
+ ```
If you would like to run specs against a particular database you may specify the dummy app's database, which defaults to sqlite3.
-```bash
-DB=postgres bundle exec rake test_app
-```
+ ```bash
+ DB=postgres DB_USERNAME=postgres DB_PASSWORD=password DB_HOST=localhost bundle exec rake test_app
+ ```
If you want to run specs for only a single spec file
-```bash
-cd core
-bundle exec rspec spec/models/spree/state_spec.rb
-```
+ ```bash
+ cd core
+ bundle exec rspec spec/models/spree/state_spec.rb
+ ```
If you want to run a particular line of spec
-```bash
-cd core
-bundle exec rspec spec/models/spree/state_spec.rb:7
-```
+ ```bash
+ cd core
+ bundle exec rspec spec/models/spree/state_spec.rb:7
+ ```
### Running integration tests on MacOS (only applicable for Admin Panel/Storefront)
We use chromedriver to run integration tests. To install it please use this command:
-```bash
-brew cask install chromedriver
-```
+ ```bash
+ brew cask install chromedriver
+ ```
## Submitting Changes
@@ -153,9 +163,9 @@ This section will help you troubleshoot common issues with Spree.
If you encounter the following libvips error:
-```bash
-LoadError: Could not open library 'vips.so.42'
-```
+ ```bash
+ LoadError: Could not open library 'vips.so.42'
+ ```
This error is usually an indication that you do not have libvips installed locally on your machine. Check that libvips is installed with `vips -v`, and if it is not installed, follow [installation instructions here](https://www.libvips.org/install.html).
diff --git a/docs/developer/contributing/updating-extensions.mdx b/docs/developer/contributing/updating-extensions.mdx
index 415ca7d866..df3e8f5711 100644
--- a/docs/developer/contributing/updating-extensions.mdx
+++ b/docs/developer/contributing/updating-extensions.mdx
@@ -14,9 +14,7 @@ To fix this we need to convert all `class_eval` decorators to modules and use [M
Example of an old decorator:
-`app/models/spree/order_decorator.rb`
-
-```ruby
+```ruby app/models/spree/order_decorator.rb
Spree::Order.class_eval do
has_many :new_custom_model
@@ -28,9 +26,7 @@ end
the same decorator in the new notation:
-`app/models/your_extension_name/order_decorator.rb`
-
-```ruby
+```ruby app/models/your_extension_name/order_decorator.rb
module YourExtensionName::OrderDecorator
def self.prepended(base)
base.has_many :new_custom_model
diff --git a/docs/developer/core-concepts/addresses.mdx b/docs/developer/core-concepts/addresses.mdx
index 995ecdd093..9a96eae9e4 100644
--- a/docs/developer/core-concepts/addresses.mdx
+++ b/docs/developer/core-concepts/addresses.mdx
@@ -1,6 +1,5 @@
---
title: Addresses
-icon: "map"
---
The `Spree::Address` model is used to track address information, mainly for orders. Address information can also be tied to the `Spree.user_class` which by default is `Spree::User` ([More on Users](users)).
diff --git a/docs/developer/core-concepts/adjustments.mdx b/docs/developer/core-concepts/adjustments.mdx
index fee1c4474e..66e044bc55 100644
--- a/docs/developer/core-concepts/adjustments.mdx
+++ b/docs/developer/core-concepts/adjustments.mdx
@@ -1,6 +1,5 @@
---
title: Adjustments
-icon: "pencil"
---
## Overview
@@ -102,7 +101,7 @@ order.shipment_adjustments
To create a new adjuster for Spree, create a new ruby object that inherits from `Spree::Adjustable::Adjuster::Base` and implements an `update` method:
-```ruby
+```ruby app/models/spree/adjustable/adjuster/my_adjuster.rb
module Spree
module Adjustable
module Adjuster
@@ -131,15 +130,27 @@ module Spree
end
```
-Next you need to add the class to spree `Rails.application.config.spree.adjusters` so it is included whenever adjustments are updated Promotion and Tax are included by default:
-
-```ruby
-# NOTE: it is advisable that that Tax be implemented last so Tax is calculated correctly
-app.config.spree.adjusters = [
- Spree::Adjustable::Adjuster::MyAdjuster,
- Spree::Adjustable::Adjuster::Promotion,
- Spree::Adjustable::Adjuster::Tax
- ]
-```
+Next you need to add the class to spree `Spree.adjusters` so it is included whenever adjustments are updated Promotion and Tax are included by default:
+
+<Tabs>
+ <Tab title="Spree 5.2+">
+ ```ruby config/initializers/spree.rb
+ Spree.adjusters = [
+ Spree::Adjustable::Adjuster::MyAdjuster,
+ Spree::Adjustable::Adjuster::Promotion,
+ Spree::Adjustable::Adjuster::Tax
+ ]
+ ```
+ </Tab>
+ <Tab title="Spree 5.1 and below">
+ ```ruby config/initializers/spree.rb
+ Rails.application.config.spree.adjusters = [
+ Spree::Adjustable::Adjuster::MyAdjuster,
+ Spree::Adjustable::Adjuster::Promotion,
+ Spree::Adjustable::Adjuster::Tax
+ ]
+ ```
+ </Tab>
+</Tabs>
That's it! Your custom adjuster is ready to go.
\ No newline at end of file
diff --git a/docs/developer/core-concepts/architecture.mdx b/docs/developer/core-concepts/architecture.mdx
index c1120eed94..5530ef5e2a 100644
--- a/docs/developer/core-concepts/architecture.mdx
+++ b/docs/developer/core-concepts/architecture.mdx
@@ -1,7 +1,6 @@
---
title: Architecture
description: Learn about the Spree architecture
-icon: "code"
---
Spree is a modular full-stack platform that can be used to build a wide range of e-commerce applications. It includes:
diff --git a/docs/developer/core-concepts/calculators.mdx b/docs/developer/core-concepts/calculators.mdx
index 51e632ee17..5fd7832a32 100644
--- a/docs/developer/core-concepts/calculators.mdx
+++ b/docs/developer/core-concepts/calculators.mdx
@@ -1,6 +1,5 @@
---
title: Calculators
-icon: "calculator"
---
## Overview
@@ -175,23 +174,43 @@ end
The second thing is to register this calculator as a tax, shipping, or promotion adjustment calculator by calling code like this at the end of `config/initializers/spree.rb` inside your application `config` variable defined for brevity:
-```ruby
-Rails.application.config.spree.calculators.tax_rates << CustomCalculator
-Rails.application.config.spree.calculators.shipping_methods << CustomCalculator
-Rails.application.config.spree.calculators.promotion_actions_create_adjustments << CustomCalculator
-```
+<Tabs>
+ <Tab title="Spree 5.2+">
+ ```ruby config/initializers/spree.rb
+ Spree.calculators.tax_rates << CustomCalculator
+ Spree.calculators.shipping_methods << CustomCalculator
+ Spree.calculators.promotion_actions_create_adjustments << CustomCalculator
+ ```
+ </Tab>
+ <Tab title="Spree 5.1 and below">
+ ```ruby config/initializers/spree.rb
+ Rails.application.config.spree.calculators.tax_rates << CustomCalculator
+ Rails.application.config.spree.calculators.shipping_methods << CustomCalculator
+ Rails.application.config.spree.calculators.promotion_actions_create_adjustments << CustomCalculator
+ ```
+ </Tab>
+</Tabs>
For example if your calculator is placed in `app/models/spree/calculator/shipping/my_own_calculator.rb` you should call:
-```ruby
-Rails.application.config.spree.calculators.shipping_methods << Spree::Calculator::Shipping::MyOwnCalculator
-```
+<Tabs>
+ <Tab title="Spree 5.2+">
+ ```ruby config/initializers/spree.rb
+ Spree.calculators.shipping_methods << Spree::Calculator::Shipping::MyOwnCalculator
+ ```
+ </Tab>
+ <Tab title="Spree 5.1 and below">
+ ```ruby config/initializers/spree.rb
+ Rails.application.config.spree.calculators.shipping_methods << Spree::Calculator::Shipping::MyOwnCalculator
+ ```
+ </Tab>
+</Tabs>
### Determining Availability
By default, all shipping method calculators are available at all times. If you wish to make this dependent on something from the order, you can re-define the `available?` method inside your calculator:
-```ruby
+```ruby app/models/custom_calculator.rb
class CustomCalculator < Spree::Calculator
def available?(object)
object.currency == "USD"
@@ -203,7 +222,7 @@ end
If you wish to use Spree's calculator functionality for your own application, you can include the `Spree::Core::CalculatedAdjustments` module into a model of your choosing.
-```ruby
+```ruby app/models/plan.rb
class Plan < ActiveRecord::Base
include Spree::Core::CalculatedAdjustments
end
@@ -211,9 +230,18 @@ end
To have calculators available for this class, you will need to register them:
-```ruby
-config.spree.calculators.plans << CustomCalculator
-```
+<Tabs>
+ <Tab title="Spree 5.2+">
+ ```ruby config/initializers/spree.rb
+ Spree.calculators.plans << CustomCalculator
+ ```
+ </Tab>
+ <Tab title="Spree 5.1 and below">
+ ```ruby config/initializers/spree.rb
+ Rails.application.config.spree.calculators.plans << CustomCalculator
+ ```
+ </Tab>
+</Tabs>
Then you can access these calculators by calling this method:
diff --git a/docs/developer/core-concepts/i18n.mdx b/docs/developer/core-concepts/i18n.mdx
index 73cc2dde6c..2688356cbb 100644
--- a/docs/developer/core-concepts/i18n.mdx
+++ b/docs/developer/core-concepts/i18n.mdx
@@ -1,6 +1,5 @@
---
title: Internationalization
-icon: "language"
description: >-
Spree is ready out of the box to make your brand a global one.
---
diff --git a/docs/developer/core-concepts/images-assets.mdx b/docs/developer/core-concepts/images-assets.mdx
new file mode 100644
index 0000000000..94f890dafe
--- /dev/null
+++ b/docs/developer/core-concepts/images-assets.mdx
@@ -0,0 +1,431 @@
+---
+title: Images & Assets
+sidebarTitle: "Images & Assets"
+---
+
+Spree uses [Rails Active Storage](https://guides.rubyonrails.org/active_storage_overview.html) for all file uploads and image handling. This guide covers how images are stored, processed, and displayed in Spree.
+
+## How Spree Stores Images
+
+Spree provides two storage service configurations:
+
+| Service | Purpose | Example Models |
+|---------|---------|----------------|
+| `public_storage_service_name` | Public assets (images, logos) | Product images, Store logo, Taxon images |
+| `private_storage_service_name` | Private assets (exports, imports) | CSV exports, Digital downloads |
+
+### Configuration
+
+Configure storage services in your Spree initializer:
+
+```ruby config/initializers/spree.rb
+Spree.public_storage_service_name = :amazon_public # S3 bucket for public assets
+Spree.private_storage_service_name = :amazon_private # S3 bucket for private assets
+```
+
+If not configured, Spree uses the default Active Storage service from `config/storage.yml`.
+
+<Info>
+ For production deployments, we recommend using cloud storage (S3, GCS, Azure) instead of local disk storage. See [Active Storage Configuration](/developer/deployment/assets) for details.
+</Info>
+
+## Adding Images to Your Models
+
+For most models, use Rails Active Storage directly with Spree's storage service:
+
+```ruby app/models/spree/brand.rb
+module Spree
+ class Brand < Spree::Base
+ # Public image (product photos, logos, etc.)
+ has_one_attached :logo, service: Spree.public_storage_service_name
+
+ # Multiple public images
+ has_many_attached :gallery_images, service: Spree.public_storage_service_name
+
+ # Private file (invoices, reports, etc.)
+ has_one_attached :contract, service: Spree.private_storage_service_name
+ end
+end
+```
+
+### Models Using Active Storage
+
+Most Spree models use Active Storage directly:
+
+| Model | Attachment | Type |
+|-------|------------|------|
+| `Spree::Store` | `logo`, `favicon_image`, `social_image`, `mailer_logo` | Public |
+| `Spree::Taxon` | `image`, `square_image` | Public |
+| `Spree::Post` | `image` | Public |
+| `Spree::User` | `avatar` | Public |
+| `Spree::PageSection` | `asset` | Public |
+| `Spree::PageBlock` | `asset` | Public |
+| `Spree::Digital` | `attachment` | Private |
+| `Spree::Export` | `attachment` | Private |
+| `Spree::Import` | `attachment` | Private |
+
+## Product & Variant Images
+
+Product images are a special case that use the `Spree::Image` model (a subclass of `Spree::Asset`). This provides additional features needed for e-commerce:
+
+- **Multiple images per variant** with ordering
+- **Alt text** for accessibility and SEO
+- **Position management** for image galleries
+- **Polymorphic association** to variants
+
+### How It Works
+
+```ruby
+# Images belong to variants, not products directly
+variant.images # => [Spree::Image, Spree::Image, ...]
+
+# Products access images through their variants
+product.images # => Images from master variant
+product.variant_images # => Images from all variants including master
+
+# Each image wraps an Active Storage attachment
+image = variant.images.first
+image.attachment # => ActiveStorage::Attached::One
+image.alt # => "Red T-Shirt Front View"
+image.position # => 1
+```
+
+### Creating Product Images
+
+```ruby
+# Add image to a variant
+variant.images.create!(
+ attachment: File.open('path/to/image.jpg'),
+ alt: 'Product front view'
+)
+
+# Or using Active Storage's attach method
+image = variant.images.new(alt: 'Product side view')
+image.attachment.attach(
+ io: File.open('path/to/image.jpg'),
+ filename: 'side-view.jpg',
+ content_type: 'image/jpeg'
+)
+image.save!
+```
+
+### Spree::Asset Class
+
+`Spree::Asset` is the base class for product images:
+
+```ruby
+# Key attributes and methods
+asset.attachment # ActiveStorage attachment
+asset.attached? # Check if file is attached
+asset.blob # ActiveStorage blob
+asset.filename # Original filename
+asset.key # Storage key
+asset.viewable # Parent record (e.g., Spree::Variant)
+asset.viewable_type # "Spree::Variant"
+asset.position # Order in gallery
+asset.alt # Alt text (Spree::Image only)
+```
+
+<Warning>
+ `Spree::Asset` and `Spree::Image` are only used for product/variant images. For all other models, use Active Storage directly with `has_one_attached` or `has_many_attached`.
+</Warning>
+
+## Image Processing
+
+Spree uses [libvips](https://www.libvips.org/) for image processing. Images are automatically:
+
+- Converted to **WebP format** for optimal file size
+- **Resized on-the-fly** using Active Storage variants
+- **Cached** for subsequent requests
+
+### Installing libvips
+
+```bash
+# macOS
+brew install vips
+
+# Ubuntu/Debian
+apt-get install libvips
+
+# Alpine Linux
+apk add vips
+```
+
+### Image Variants
+
+Transform images on-the-fly using Active Storage variants:
+
+```ruby
+# Resize to fit within dimensions (maintains aspect ratio)
+image.variant(resize_to_limit: [400, 400])
+
+# Resize and crop to exact dimensions
+image.variant(resize_to_fill: [200, 200])
+
+# Resize by width only
+image.variant(resize_to_limit: [300, nil])
+
+# Resize by height only
+image.variant(resize_to_limit: [nil, 300])
+```
+
+## Helpers
+
+Spree provides several helper methods for working with images. These are defined in [Spree::ImagesHelper](https://github.com/spree/spree/blob/main/core/app/helpers/spree/images_helper.rb) and are available in Admin, Storefront, and API.
+
+### `spree_image_tag`
+
+Generates an optimized image tag with automatic WebP conversion and retina support.
+
+```erb
+<%= spree_image_tag(
+ product.images.first,
+ width: 400,
+ height: 400,
+ loading: :lazy,
+ class: 'product-image',
+ alt: product.name
+) %>
+```
+
+**Output:**
+
+```html
+<img
+ width="400"
+ height="400"
+ loading="lazy"
+ class="product-image"
+ alt="Red T-Shirt"
+ src="https://example.com/rails/active_storage/representations/...">
+```
+
+**Features:**
+- Automatically scales dimensions by 2x for retina displays
+- Converts to WebP format
+- Works with both `Spree::Asset` objects and Active Storage attachments
+
+**Parameters:**
+
+| Parameter | Type | Description |
+|-----------|------|-------------|
+| `image` | Asset/Attachment | Spree::Asset or ActiveStorage attachment |
+| `width` | Integer | Display width in pixels |
+| `height` | Integer | Display height in pixels |
+| `loading` | Symbol | `:lazy` or `:eager` |
+| `class` | String | CSS classes |
+| `alt` | String | Alt text for accessibility |
+
+<Tip>
+ If both width and height are provided, the image is cropped to fill the dimensions. If only one is provided, the image maintains its aspect ratio.
+</Tip>
+
+### `spree_image_url`
+
+Generates a URL for an image with specified dimensions.
+
+```erb
+<%= spree_image_url(product.images.first, width: 800, height: 600) %>
+```
+
+**Output:**
+
+```
+https://example.com/rails/active_storage/representations/proxy/...
+```
+
+<Info>
+ URLs generated by this helper are static and can be cached by [CDNs](/developer/deployment/assets). Don't use this for private assets!
+</Info>
+
+### `spree_asset_aspect_ratio`
+
+Returns the aspect ratio of an image for CSS layouts.
+
+```erb
+<div style="aspect-ratio: <%= spree_asset_aspect_ratio(product.images.first) %>">
+ <%= spree_image_tag(product.images.first, width: 400) %>
+</div>
+```
+
+**Returns:** Float (e.g., `1.5`, `0.75`, `1.0`)
+
+## Displaying Images
+
+### Product Images in Views
+
+```erb
+<%# Display primary product image %>
+<% if product.images.any? %>
+ <%= spree_image_tag product.images.first,
+ width: 600,
+ height: 600,
+ alt: product.name,
+ class: 'product-main-image' %>
+<% end %>
+
+<%# Display image gallery %>
+<div class="product-gallery">
+ <% product.images.each do |image| %>
+ <%= spree_image_tag image,
+ width: 100,
+ height: 100,
+ alt: image.alt.presence || product.name,
+ class: 'gallery-thumbnail' %>
+ <% end %>
+</div>
+```
+
+### Active Storage Attachments
+
+```erb
+<%# Store logo %>
+<% if current_store.logo.attached? %>
+ <%= spree_image_tag current_store.logo,
+ width: 200,
+ height: 60,
+ alt: current_store.name %>
+<% end %>
+
+<%# Taxon image %>
+<% if taxon.image.attached? %>
+ <%= spree_image_tag taxon.image,
+ width: 400,
+ height: 300,
+ alt: taxon.name %>
+<% end %>
+
+<%# User avatar %>
+<% if user.avatar.attached? %>
+ <%= spree_image_tag user.avatar,
+ width: 48,
+ height: 48,
+ class: 'rounded-full' %>
+<% end %>
+```
+
+### Checking for Attached Images
+
+```erb
+<%# For Spree::Asset/Image %>
+<% if product.images.any? %>
+ <%= spree_image_tag product.images.first, width: 400 %>
+<% else %>
+ <%= image_tag 'placeholder.png', width: 400 %>
+<% end %>
+
+<%# For Active Storage attachments %>
+<% if @brand.logo.attached? %>
+ <%= spree_image_tag @brand.logo, width: 200 %>
+<% else %>
+ <div class="placeholder">No logo</div>
+<% end %>
+```
+
+## Admin Dashboard
+
+In the admin dashboard, use the `spree_file_field` form helper for image uploads:
+
+```erb
+<%= form_with model: @brand do |f| %>
+ <%= f.spree_file_field :logo,
+ width: 300,
+ height: 300,
+ crop: true,
+ help: "Recommended size: 300x300px" %>
+<% end %>
+```
+
+See the [Form Builder](/developer/admin/form-builder) and [Components](/developer/admin/components) documentation for more details.
+
+## API Serialization
+
+Product images are automatically serialized in API responses:
+
+```json
+{
+ "data": {
+ "id": "1",
+ "type": "product",
+ "attributes": {
+ "name": "Red T-Shirt"
+ },
+ "relationships": {
+ "images": {
+ "data": [
+ { "id": "1", "type": "image" }
+ ]
+ }
+ }
+ },
+ "included": [
+ {
+ "id": "1",
+ "type": "image",
+ "attributes": {
+ "position": 1,
+ "alt": "Front view",
+ "original_url": "https://...",
+ "styles": [
+ {
+ "url": "https://...",
+ "width": 650,
+ "height": 870,
+ "size": "650x870>"
+ }
+ ]
+ }
+ }
+ ]
+}
+```
+
+## Best Practices
+
+<Check>
+ **Use appropriate storage services** - Public assets use `public_storage_service_name`, private files use `private_storage_service_name`
+</Check>
+
+<Check>
+ **Always provide alt text** - For accessibility and SEO, always include meaningful alt text
+</Check>
+
+<Check>
+ **Use lazy loading** - Add `loading: :lazy` for images below the fold
+</Check>
+
+<Check>
+ **Specify dimensions** - Always provide width and height to prevent layout shifts
+</Check>
+
+<Check>
+ **Use CDN in production** - Configure Active Storage to use a [CDN](/developer/deployment/assets) for faster delivery
+</Check>
+
+<Check>
+ **Validate uploads** - Add file size and type validations to prevent abuse
+</Check>
+
+```ruby
+# Example validation
+class Brand < Spree::Base
+ has_one_attached :logo, service: Spree.public_storage_service_name
+
+ validate :acceptable_logo
+
+ private
+
+ def acceptable_logo
+ return unless logo.attached?
+
+ if logo.blob.byte_size > 5.megabytes
+ errors.add(:logo, 'must be less than 5MB')
+ end
+
+ acceptable = ['image/jpeg', 'image/png', 'image/webp']
+ unless acceptable.include?(logo.blob.content_type)
+ errors.add(:logo, 'must be JPEG, PNG, or WebP')
+ end
+ end
+end
+```
diff --git a/docs/developer/core-concepts/inventory.mdx b/docs/developer/core-concepts/inventory.mdx
index ee1cd1a2d3..e20dee696a 100644
--- a/docs/developer/core-concepts/inventory.mdx
+++ b/docs/developer/core-concepts/inventory.mdx
@@ -1,6 +1,5 @@
---
title: Inventory
-icon: "boxes-stacked"
---
## Overview
diff --git a/docs/developer/core-concepts/metafields.mdx b/docs/developer/core-concepts/metafields.mdx
index de99b5351d..9c18f940ec 100644
--- a/docs/developer/core-concepts/metafields.mdx
+++ b/docs/developer/core-concepts/metafields.mdx
@@ -1,6 +1,5 @@
---
title: Metafields
-icon: "database"
---
## Overview
@@ -16,15 +15,9 @@ Metafields enable you to extend resources with custom attributes without modifyi
- Order metadata with validation
<Note>
-Metafields are available from Spree 5.2 onwards. For earlier versions, use [metadata](/developer/customization/metadata) instead.
+Metafields are available from Spree 5.2 onwards.
</Note>
-<Warning>
-**Starting with Spree 5.2**, Metafields are the **recommended default** for storing custom product attributes, replacing the legacy [Product Properties](/developer/core-concepts/products#product-properties) system. For new projects, use Metafields instead of Properties.
-
-Product Properties are still supported for backward compatibility (until Spree 6.0) but require enabling via `config.product_properties_enabled = true`. See the [upgrade guide](/developer/upgrades/5.1-to-5.2#3-migrate-to-metafields-or-keep-using-properties) for migration details.
-</Warning>
-
## Architecture
The metafields system consists of two main models:
@@ -579,8 +572,8 @@ normalizes :value, with: ->(value) { value.to_b.to_s }
Create a custom metafield type:
```ruby
-# app/models/my_app/metafields/url.rb
-module MyApp
+# app/models/spree/metafields/url.rb
+module Spree
module Metafields
class Url < Spree::Metafield
validates :value, format: { with: URI::DEFAULT_PARSER.make_regexp }
@@ -599,20 +592,19 @@ end
Register it in an initializer:
-```ruby
-# config/initializers/spree.rb
-Rails.application.config.spree.metafield_types << 'MyApp::Metafields::Url'
+```ruby config/initializers/spree.rb
+Spree.metafields.types << 'Spree::Metafields::Url'
```
### Enabling Metafields for Custom Resources
-```ruby
-# config/initializers/spree.rb
-Rails.application.config.spree.metafield_enabled_resources << 'MyApp::CustomResource'
+```ruby config/initializers/spree.rb
+Spree.metafields.enabled_resources << 'Spree::Brand'
+```
-# app/models/my_app/custom_resource.rb
-module MyApp
- class CustomResource < ApplicationRecord
+```ruby app/models/spree/brand.rb
+module Spree
+ class Brand < Spree::Base
include Spree::Metafields
end
end
diff --git a/docs/developer/core-concepts/orders.mdx b/docs/developer/core-concepts/orders.mdx
index 5fd6ecb77a..9d0280a2e2 100644
--- a/docs/developer/core-concepts/orders.mdx
+++ b/docs/developer/core-concepts/orders.mdx
@@ -1,6 +1,5 @@
---
title: Orders
-icon: "cart-shopping"
---
## Overview
diff --git a/docs/developer/core-concepts/payments.mdx b/docs/developer/core-concepts/payments.mdx
index 8f671500c6..3ca00b16a2 100644
--- a/docs/developer/core-concepts/payments.mdx
+++ b/docs/developer/core-concepts/payments.mdx
@@ -1,6 +1,5 @@
---
title: Payments
-icon: "credit-card"
---
## Overview
@@ -225,11 +224,20 @@ end
Next, add your custom gateway to the list of available payment methods in `config/initializers/spree.rb`:
-```ruby
-Rails.application.config.after_initialize do
- Rails.application.config.spree.payment_methods << FancyPaymentMethod
-end
-```
+<Tabs>
+ <Tab title="Spree 5.2+">
+ ```ruby config/initializers/spree.rb
+ Spree.payment_methods << FancyPaymentMethod
+ ```
+ </Tab>
+ <Tab title="Spree 5.1 and below">
+ ```ruby config/initializers/spree.rb
+ Rails.application.config.after_initialize do
+ Rails.application.config.spree.payment_methods << FancyPaymentMethod
+ end
+ ```
+ </Tab>
+</Tabs>
## Payment Method visibility
diff --git a/docs/developer/core-concepts/products.mdx b/docs/developer/core-concepts/products.mdx
index 7c1a25c5c6..696faf5d5e 100644
--- a/docs/developer/core-concepts/products.mdx
+++ b/docs/developer/core-concepts/products.mdx
@@ -1,6 +1,5 @@
---
title: Products
-icon: "box"
---
## Overview
@@ -132,7 +131,7 @@ product.default_variant.images
Image order is determined by the `position` attribute, which is an integer. By default, images are ordered from left to right.
<Info>
-Under the hood we use [Rails Active Storage](https://guides.rubyonrails.org/active_storage_overview.html) to handle image storage and manipulation.
+Under the hood we use [Rails Active Storage](https://guides.rubyonrails.org/active_storage_overview.html) to handle image storage and manipulation. See the [Images & Assets](/developer/core-concepts/images-assets) guide for more details on image processing, helpers, and best practices.
</Info>
## Product Properties
diff --git a/docs/developer/core-concepts/promotions.mdx b/docs/developer/core-concepts/promotions.mdx
index 3a1a61540b..96fe774975 100644
--- a/docs/developer/core-concepts/promotions.mdx
+++ b/docs/developer/core-concepts/promotions.mdx
@@ -1,6 +1,5 @@
---
title: Promotions
-icon: "ticket"
---
## Overview
diff --git a/docs/developer/core-concepts/search-filtering.mdx b/docs/developer/core-concepts/search-filtering.mdx
new file mode 100644
index 0000000000..ef7366c9eb
--- /dev/null
+++ b/docs/developer/core-concepts/search-filtering.mdx
@@ -0,0 +1,508 @@
+---
+ title: Search & Filtering
+ sidebarTitle: Search & Filtering
+ description: "Learn how to search, filter and sort resources in Spree"
+---
+
+## Overview
+
+Spree uses the [Ransack](https://activerecord-hackery.github.io/ransack/) gem to provide powerful search, filtering, and sorting capabilities throughout the platform. Ransack is integrated into:
+
+- **Admin Dashboard** - For filtering and searching resources in index views
+- **Platform API** - For filtering collections via API requests
+
+Ransack allows you to build complex queries using URL parameters or API filters, supporting operations like:
+
+- Exact matches (`eq`)
+- Partial matches (`cont`, `start`, `end`)
+- Comparisons (`gt`, `lt`, `gteq`, `lteq`)
+- NULL checks (`null`, `not_null`)
+- Date ranges and much more
+
+## Security Model
+
+Spree uses a whitelist-based security model for Ransack to prevent unauthorized database queries. By default, models can only be searched on:
+
+- `id`
+- `name`
+- `created_at`
+- `updated_at`
+
+Additional attributes, associations, and scopes must be explicitly whitelisted in each model.
+
+## Making Models Searchable
+
+To enable searching on additional fields, inherit from `Spree::Base` and configure whitelisted attributes:
+
+### Basic Configuration
+
+```ruby
+module Spree
+ class Brand < Spree::Base
+ # Allow searching by these attributes
+ self.whitelisted_ransackable_attributes = %w[sku status available_on]
+
+ # Allow searching through these associations
+ self.whitelisted_ransackable_associations = %w[variants taxons master]
+
+ # Allow filtering by these scopes
+ self.whitelisted_ransackable_scopes = %w[active available in_stock]
+ end
+end
+```
+
+<Info>
+The attributes `id`, `name`, `created_at`, and `updated_at` are always searchable by default and don't need to be explicitly whitelisted.
+</Info>
+
+### Real-World Examples
+
+Here are examples from Spree's core models:
+
+#### User Model
+
+```ruby
+module Spree::UserMethods
+ included do
+ self.whitelisted_ransackable_associations = %w[bill_address ship_address addresses tags spree_roles]
+ self.whitelisted_ransackable_attributes = %w[id email first_name last_name accepts_email_marketing]
+ self.whitelisted_ransackable_scopes = %w[multi_search]
+ end
+end
+```
+
+#### Price Model
+
+```ruby
+module Spree
+ class Price < Spree.base_class
+ self.whitelisted_ransackable_attributes = %w[amount compare_at_amount]
+ end
+end
+```
+
+## Admin Dashboard Integration
+
+The `Spree::Admin::ResourceController` automatically integrates Ransack for all admin resources.
+
+### How It Works
+
+The `ResourceController` at [admin/app/controllers/spree/admin/resource_controller.rb:242-254](https://github.com/spree/spree/blob/main/admin/app/controllers/spree/admin/resource_controller.rb#L242-L254) implements:
+
+```ruby
+# keeping this as @search for backwards compatibility
+# @return [Ransack::Search]
+def search_collection
+ @search ||= begin
+ params[:q] ||= {}
+ params[:q][:s] ||= collection_default_sort if collection_default_sort.present?
+ scope.ransack(params[:q])
+ end
+end
+
+# Returns the filtered and paginated ransack results
+# @return [ActiveRecord::Relation]
+def collection
+ @collection ||= search_collection.result(distinct: true).page(params[:page]).per(params[:per_page])
+end
+```
+
+### Controller Configuration
+
+When building admin controllers, you can customize the search behavior:
+
+```ruby
+module Spree
+ module Admin
+ class BrandsController < ResourceController
+ # Set default sort order
+ def collection_default_sort
+ 'name asc'
+ end
+
+ # Eager load associations to avoid N+1 queries
+ def collection_includes
+ [:logo_attachment]
+ end
+
+ # Customize the base scope (optional)
+ def scope
+ super.active
+ end
+ end
+ end
+end
+```
+
+### Filters View
+
+Admin index views typically include a filters partial (`_filters.html.erb`) that builds search forms:
+
+```erb
+<%= search_form_for @search, url: spree.admin_brands_path, method: :get do |f| %>
+ <div class="row">
+ <div class="col-md-4">
+ <%= f.label :name_cont, Spree.t(:name) %>
+ <%= f.search_field :name_cont, class: 'form-control' %>
+ </div>
+
+ <div class="col-md-4">
+ <%= f.label :active_eq, Spree.t(:status) %>
+ <%= f.select :active_eq,
+ [[Spree.t(:active), true], [Spree.t(:inactive), false]],
+ { include_blank: Spree.t(:all) },
+ class: 'form-control' %>
+ </div>
+
+ <div class="col-md-4">
+ <%= f.label :created_at_gteq, Spree.t(:created_from) %>
+ <%= f.date_field :created_at_gteq, class: 'form-control' %>
+ </div>
+ </div>
+
+ <div class="form-actions">
+ <%= f.submit Spree.t(:search), class: 'btn btn-primary' %>
+ <%= link_to Spree.t(:clear), spree.admin_brands_path, class: 'btn btn-secondary' %>
+ </div>
+<% end %>
+```
+
+## Platform API Integration
+
+The Platform API uses Ransack via the `filter` parameter for all collection endpoints.
+
+### API Controller Implementation
+
+From [api/app/controllers/spree/api/v2/platform/resource_controller.rb:57-61](https://github.com/spree/spree/blob/main/api/app/controllers/spree/api/v2/platform/resource_controller.rb#L57-L61):
+
+### API Usage Examples
+
+#### Basic Filtering
+
+Filter products by name:
+
+```bash
+GET /api/v2/platform/products?filter[name_cont]=shirt
+```
+
+Filter users by email:
+
+```bash
+GET /api/v2/platform/users?filter[email_eq][email protected]
+```
+
+#### Advanced Filtering
+
+Filter products by multiple criteria:
+
+```bash
+GET /api/v2/platform/products?filter[status_eq]=active&filter[price_gteq]=20&filter[price_lteq]=100
+```
+
+Filter through associations:
+
+```bash
+GET /api/v2/platform/products?filter[taxons_name_cont]=shirts
+```
+
+Filter by date ranges:
+
+```bash
+GET /api/v2/platform/orders?filter[created_at_gteq]=2024-01-01&filter[created_at_lteq]=2024-12-31
+```
+
+#### Using Scopes
+
+If a model defines `whitelisted_ransackable_scopes`, you can filter using them:
+
+```bash
+GET /api/v2/platform/products?filter[in_stock]=true
+```
+
+<Warning>
+Only attributes, associations, and scopes explicitly whitelisted in models can be used for filtering. Attempting to filter on non-whitelisted fields will be silently ignored for security reasons.
+</Warning>
+
+## Search Predicates
+
+Ransack provides numerous predicates (matchers) for building complex queries. Here are the most commonly used ones in Spree:
+
+### Equality Predicates
+
+| Predicate | Description | Example |
+|-----------|-------------|---------|
+| `eq` | Equals | `name_eq=Nike` |
+| `not_eq` | Not equals | `status_not_eq=archived` |
+| `in` | In array | `id_in[]=1&id_in[]=2&id_in[]=3` |
+| `not_in` | Not in array | `status_not_in[]=draft&status_not_in[]=archived` |
+
+### String Predicates
+
+| Predicate | Description | Example |
+|-----------|-------------|---------|
+| `cont` | Contains | `name_cont=shirt` |
+| `not_cont` | Does not contain | `name_not_cont=vintage` |
+| `start` | Starts with | `email_start=admin` |
+| `end` | Ends with | `[email protected]` |
+| `i_cont` | Case-insensitive contains | `name_i_cont=SHIRT` |
+
+### Comparison Predicates
+
+| Predicate | Description | Example |
+|-----------|-------------|---------|
+| `gt` | Greater than | `price_gt=50` |
+| `gteq` | Greater than or equal | `quantity_gteq=10` |
+| `lt` | Less than | `price_lt=100` |
+| `lteq` | Less than or equal | `created_at_lteq=2024-12-31` |
+
+### NULL Predicates
+
+| Predicate | Description | Example |
+|-----------|-------------|---------|
+| `null` | Is NULL | `deleted_at_null=true` |
+| `not_null` | Is not NULL | `published_at_not_null=true` |
+| `blank` | Is NULL or empty | `description_blank=true` |
+| `present` | Is not NULL and not empty | `image_present=true` |
+
+### Date/Time Predicates
+
+```ruby
+# Products created this year
+products?filter[created_at_gteq]=2024-01-01
+
+# Orders completed today
+orders?filter[completed_at_gteq]=2024-01-15&filter[completed_at_lteq]=2024-01-15
+
+# Products available before a date
+products?filter[available_on_lteq]=2024-12-31
+```
+
+## Sorting
+
+### Admin Dashboard Sorting
+
+Ransack handles sorting via the `s` parameter in the `q` hash:
+
+```ruby
+# In controller
+params[:q][:s] = 'created_at desc' # Sort by created_at descending
+params[:q][:s] = 'name asc' # Sort by name ascending
+```
+
+In views, use `sort_link` helper:
+
+```erb
+<%= sort_link(@search, :name, Spree.t(:name)) %>
+<%= sort_link(@search, :created_at, Spree.t(:created_at)) %>
+<%= sort_link(@search, :status, Spree.t(:status)) %>
+```
+
+### Platform API Sorting
+
+The Platform API uses the standard JSON:API `sort` parameter:
+
+```bash
+# Sort by name ascending
+GET /api/v2/platform/products?sort=name
+
+# Sort by created_at descending
+GET /api/v2/platform/products?sort=-created_at
+
+# Multiple sorts
+GET /api/v2/platform/products?sort=status,-created_at
+```
+
+<Info>
+Platform API sorting is handled separately from Ransack's filter parameter and follows JSON:API conventions.
+</Info>
+
+## Custom Implementation Examples
+
+### Example 1: Brand Resource
+
+From the admin resources guide:
+
+```ruby
+module Spree
+ class Brand < Spree.base_class
+ include Spree::RansackableAttributes
+
+ # Enable searching
+ self.whitelisted_ransackable_attributes = %w[name slug status published_at]
+ self.whitelisted_ransackable_scopes = %w[published with_logo]
+
+ # Scopes that can be used in searches
+ scope :published, -> { where(status: 'published') }
+ scope :with_logo, -> { includes(:logo_attachment).where.not(logo_attachment: { blob: nil }) }
+ end
+end
+```
+
+Controller:
+
+```ruby
+module Spree
+ module Admin
+ class BrandsController < ResourceController
+ def collection_default_sort
+ 'name asc'
+ end
+ end
+ end
+end
+```
+
+### Example 2: Custom Search Scope
+
+```ruby
+module Spree
+ class Product < Spree.base_class
+ # Custom search scope
+ scope :multi_search, ->(query) {
+ where('name ILIKE ? OR description ILIKE ?', "%#{query}%", "%#{query}%")
+ }
+
+ # Whitelist the scope
+ self.whitelisted_ransackable_scopes = %w[multi_search]
+ end
+end
+```
+
+Usage in admin:
+
+```ruby
+# Search across multiple fields
+products?q[multi_search]=keyword
+```
+
+## Best Practices
+
+### 1. Always Whitelist Searchable Fields
+
+```ruby
+# ✅ Good - explicit whitelist
+self.whitelisted_ransackable_attributes = %w[name email status]
+
+# ❌ Bad - exposes all columns
+# Never override ransackable_attributes without proper authorization
+```
+
+### 2. Include Default Timestamps
+
+The default ransackable attributes include `created_at` and `updated_at`, so you don't need to whitelist them:
+
+```ruby
+# ❌ Redundant
+self.whitelisted_ransackable_attributes = %w[name created_at updated_at]
+
+# ✅ Better
+self.whitelisted_ransackable_attributes = %w[name]
+```
+
+### 3. Use Scopes for Complex Filters
+
+```ruby
+# ✅ Good - encapsulate complex logic in scopes
+scope :premium, -> { where('price >= ?', 100).where(featured: true) }
+self.whitelisted_ransackable_scopes = %w[premium]
+
+# ❌ Bad - exposing internal implementation details
+self.whitelisted_ransackable_attributes = %w[price featured]
+```
+
+### 4. Use Appropriate Predicates
+
+Choose predicates that match your use case:
+
+```ruby
+# ✅ Good - case-insensitive search for user input
+name_i_cont=search_term
+
+# ✅ Good - exact match for status
+status_eq=active
+
+# ❌ Bad - expensive LIKE queries on large datasets
+id_cont=123 # Use id_eq instead
+```
+
+### 5. Sanitize User Input
+
+When building search forms, use Ransack's helpers to prevent injection:
+
+```erb
+<%# ✅ Good - uses search_form_for helper %>
+<%= search_form_for @search do |f| %>
+ <%= f.search_field :name_cont %>
+<% end %>
+
+<%# ❌ Bad - raw params manipulation %>
+<%= text_field_tag 'q[name_cont]', params[:q][:name_cont] %>
+```
+
+### 6. Test Ransackable Configuration
+
+Always test that your ransackable configuration works as expected:
+
+```ruby
+# spec/models/spree/brand_spec.rb
+RSpec.describe Spree::Brand, type: :model do
+ describe 'ransackable attributes' do
+ it 'includes whitelisted attributes' do
+ expect(described_class.ransackable_attributes)
+ .to include('id', 'name', 'status', 'created_at', 'updated_at')
+ end
+ end
+
+ describe 'ransackable scopes' do
+ it 'includes whitelisted scopes' do
+ expect(described_class.ransackable_scopes).to include('published', 'with_logo')
+ end
+ end
+end
+```
+
+## Troubleshooting
+
+### Fields Not Searchable
+
+If you can't search by a field, check:
+
+1. Is it whitelisted in `whitelisted_ransackable_attributes`?
+2. Are you using the correct predicate (e.g., `_cont` for partial match)?
+
+### Associations Not Searchable
+
+For searching through associations:
+
+1. Whitelist the association in `whitelisted_ransackable_associations`
+2. Ensure the associated model also whitelists its attributes
+3. Use the correct syntax: `association_field_predicate`
+
+Example:
+
+```ruby
+# Search for products through taxon names
+products?q[taxons_name_cont]=shirts
+```
+
+### Scopes Not Working
+
+For scope filtering:
+
+1. Define the scope in your model
+2. Whitelist it in `whitelisted_ransackable_scopes`
+3. Pass a value (usually `true`) when filtering
+
+```ruby
+# Model
+scope :in_stock, -> { where('quantity > 0') }
+self.whitelisted_ransackable_scopes = %w[in_stock]
+
+# Usage
+products?q[in_stock]=true
+```
+
+## Additional Resources
+
+- [Ransack Search Matchers](https://activerecord-hackery.github.io/ransack/getting-started/search-matches/)
+- [Platform API Documentation](/developer/api/v2/platform)
diff --git a/docs/developer/core-concepts/shipments.mdx b/docs/developer/core-concepts/shipments.mdx
index f4f4677fb2..a2ac45f3a7 100644
--- a/docs/developer/core-concepts/shipments.mdx
+++ b/docs/developer/core-concepts/shipments.mdx
@@ -1,6 +1,5 @@
---
title: Shipments
-icon: "truck-fast"
---
## Overview
@@ -327,28 +326,58 @@ For an example of a simple splitter, take a look at Spree's [weight based splitt
After creating your splitter, you need to add it to the array of splitters Spree uses. To do this, add the following to your application's spree initializer `spree.rb` file:
-```ruby
-Rails.application.config.after_initialize do
- Rails.application.config.spree.stock_splitters << Spree::Stock::Splitter::CustomSplitter
-end
-```
+<Tabs>
+ <Tab title="Spree 5.2+">
+ ```ruby config/initializers/spree.rb
+ Spree.stock_splitters << Spree::Stock::Splitter::CustomSplitter
+ ```
+ </Tab>
+ <Tab title="Spree 5.1 and below">
+ ```ruby config/initializers/spree.rb
+ Rails.application.config.after_initialize do
+ Rails.application.config.spree.stock_splitters << Spree::Stock::Splitter::CustomSplitter
+ end
+ ```
+ </Tab>
+</Tabs>
You can also completely override the splitters used in Spree, rearrange them, etc. To do this, add the following to your `spree.rb` file:
-```ruby
-Rails.application.config.after_initialize do
- Rails.application.config.spree.stock_splitters = [
- Spree::Stock::Splitter::CustomSplitter,
- Spree::Stock::Splitter::ShippingCategory
- ]
-end
-```
+<Tabs>
+ <Tab title="Spree 5.2+">
+ ```ruby config/initializers/spree.rb
+ Spree.stock_splitters = [
+ Spree::Stock::Splitter::CustomSplitter,
+ Spree::Stock::Splitter::ShippingCategory
+ ]
+ ```
+ </Tab>
+ <Tab title="Spree 5.1 and below">
+ ```ruby config/initializers/spree.rb
+ Rails.application.config.after_initialize do
+ Rails.application.config.spree.stock_splitters = [
+ Spree::Stock::Splitter::CustomSplitter,
+ Spree::Stock::Splitter::ShippingCategory
+ ]
+ end
+ ```
+ </Tab>
+</Tabs>
Or if you don't want to split packages just set the option above to an empty array. e.g. a store with the following configuration in spree.rb won't have any package splitted.
-```ruby
-Rails.application.config.spree.stock_splitters = []
-```
+<Tabs>
+ <Tab title="Spree 5.2+">
+ ```ruby config/initializers/spree.rb
+ Spree.stock_splitters = []
+ ```
+ </Tab>
+ <Tab title="Spree 5.1 and below">
+ ```ruby config/initializers/spree.rb
+ Rails.application.config.spree.stock_splitters = []
+ ```
+ </Tab>
+</Tabs>
If you want to add different splitters for each `StockLocation`, you need to decorate the `Spree::Stock::Coordinator` class and override the `splitters` method.
@@ -365,9 +394,9 @@ The prioritizer is also a customization point. If you want to customize which pa
The `Adjuster` visits each package in an order and ensures the correct number of items are in each package. To customize this functionality, you need to do two things:
1. Subclass the [Spree::Stock::Adjuster](https://github.com/spree/spree/blob/main/core/app/models/spree/stock/adjuster.rb) class and override the the `adjust` method to get the desired functionality.
-2. Decorate the `Spree::Stock::Coordinator` and override the `prioritize_packages` method, passing in your custom adjuster class to the `Prioritizer` initializer. For example, if our adjuster was called `Spree::Stock::CustomAdjuster`, we would do the following in `app/my_store/spree/stock/coordinator_decorator.rb`:
+2. Decorate the `Spree::Stock::Coordinator` and override the `prioritize_packages` method, passing in your custom adjuster class to the `Prioritizer` initializer. For example, if our adjuster was called `Spree::Stock::CustomAdjuster`, we would do the following in `app/models/spree/stock/coordinator_decorator.rb`:
-```ruby
+```ruby app/models/spree/stock/coordinator_decorator.rb
module Spree
module Stock
module CoordinatorDecorator do
diff --git a/docs/developer/core-concepts/slugs.mdx b/docs/developer/core-concepts/slugs.mdx
new file mode 100644
index 0000000000..bbb4a137d3
--- /dev/null
+++ b/docs/developer/core-concepts/slugs.mdx
@@ -0,0 +1,851 @@
+---
+title: Slugs
+---
+
+## Overview
+
+Spree uses the [FriendlyId](https://github.com/norman/friendly_id) library to generate SEO-friendly URLs for resources like products, taxons, stores, and more. Instead of accessing resources via database IDs (e.g., `/products/123`), FriendlyId enables clean, readable URLs based on resource names (e.g., `/products/ruby-on-rails-tshirt`).
+
+Slugs are URL-safe strings derived from resource attributes (typically the `name` field) that:
+
+- Improve SEO by including relevant keywords in URLs
+- Enhance user experience with readable, memorable URLs
+- Maintain URL consistency across translations
+- Preserve historical URLs through slug history
+
+Slugs are primarily used in:
+
+- **Storefront**: Product pages, category pages (taxons), blog posts, and other customer-facing pages
+- **API**: Both Platform API and Storefront API accept slugs or IDs interchangeably for resource lookups
+
+<Info>
+Spree integrates FriendlyId with [Mobility](https://github.com/shioyama/mobility) for internationalization and [Paranoia](https://github.com/rubysherpas/paranoia) for soft-delete support, making slugs translation-aware and deletion-safe.
+</Info>
+
+## Core Concepts
+
+### Slug Generation
+
+Slugs are automatically generated from resource attributes using the `to_url` method (provided by the [Stringex](https://github.com/rsl/stringex) gem). This method:
+
+- Converts strings to lowercase
+- Replaces spaces and special characters with hyphens
+- Removes invalid URL characters
+- Ensures URL safety
+
+```ruby
+# Example slug generation
+"Ruby on Rails T-Shirt".to_url # => "ruby-on-rails-t-shirt"
+"Café & Restaurant".to_url # => "cafe-and-restaurant"
+```
+
+### Slug Candidates
+
+When FriendlyId generates a slug, it tries multiple "candidate" patterns to ensure uniqueness. If the first candidate is taken, it tries the next pattern, and so on.
+
+[Spree::Base](https://github.com/spree/spree/blob/main/core/app/models/spree/base.rb) provides a default `slug_candidates` method that all models inherit:
+
+```ruby
+def slug_candidates
+ if defined?(deleted_at) && deleted_at.present?
+ [
+ ['deleted', :name],
+ ['deleted', :name, :uuid_for_friendly_id]
+ ]
+ else
+ [
+ [:name],
+ [:name, :uuid_for_friendly_id]
+ ]
+ end
+end
+```
+
+For products, the slug candidates are customized to include SKU:
+
+```ruby
+# Product slug candidates (from core/app/models/spree/product/slugs.rb:66-78)
+[
+ [:name], # Try product name first
+ [:name, :sku], # If taken, append SKU
+ [:name, :uuid_for_friendly_id] # If still taken, append UUID
+]
+
+# Example progression:
+# 1st attempt: "ruby-on-rails-tshirt"
+# 2nd attempt: "ruby-on-rails-tshirt-TSHIRT-001" (includes SKU)
+# 3rd attempt: "ruby-on-rails-tshirt-a1b2c3d4-e5f6-..." (includes UUID)
+```
+
+### Reserved Words
+
+FriendlyId prevents using certain reserved words that would conflict with application routes:
+
+```ruby
+# From core/config/initializers/friendly_id.rb
+RESERVED_WORDS = %w(
+ new edit index session login logout users admin
+ stylesheets assets javascripts images
+)
+```
+
+## Models with Slugs
+
+### Product
+
+Products use the [Spree::Product::Slugs](https://github.com/spree/spree/blob/main/core/app/models/spree/product/slugs.rb) concern which provides comprehensive slug handling with translation support.
+
+```ruby
+include Spree::Product::Slugs
+```
+
+**Configuration:**
+- **Slug column**: `slug`
+- **Slug source**: `name`
+- **Modules**: `:history`, `:slugged`, `:scoped`, `:mobility`
+- **Scope**: `spree_base_uniqueness_scope` (typically `store_id`)
+- **Limit**: 255 characters
+
+**Key features:**
+- Translatable slugs (different slug per locale)
+- Slug history preserved when changed
+- Soft-delete slug renaming with `deleted-` prefix
+- Automatic fallback to SKU or UUID for uniqueness
+
+```ruby
+# Creating a product with a slug
+product = Spree::Product.create!(
+ name: 'Ruby on Rails T-Shirt',
+ stores: [store]
+)
+product.slug # => "ruby-on-rails-t-shirt"
+
+# Accessing by slug
+Spree::Product.friendly.find('ruby-on-rails-t-shirt')
+
+# Setting a custom slug
+product.update!(slug: 'custom-rails-shirt')
+
+# Translated slugs
+product.set_friendly_id('t-shirt-ruby-on-rails', :fr)
+product.save!
+```
+
+### Taxon
+
+Taxons use a custom implementation with hierarchical permalink generation. Unlike products, taxons use `permalink` as their slug column.
+
+```ruby
+# core/app/models/spree/taxon.rb:33
+friendly_id :permalink, slug_column: :permalink, use: :history
+```
+
+**Configuration:**
+- **Slug column**: `permalink` (not `slug`)
+- **Modules**: `:history` only
+- **Hierarchical**: Includes parent path
+
+**Key features:**
+- Parent path included in permalink (e.g., `categories/clothing/t-shirts`)
+- Automatically regenerates when parent changes
+- Translation support via custom implementation
+- Helper methods: `slug` and `slug=` alias to `permalink`
+
+```ruby
+# Creating a taxon
+taxonomy = store.taxonomies.first
+root = taxonomy.root
+clothing = root.children.create!(name: 'Clothing', taxonomy: taxonomy)
+tshirts = clothing.children.create!(name: 'T-Shirts', taxonomy: taxonomy)
+
+clothing.permalink # => "clothing"
+tshirts.permalink # => "clothing/t-shirts"
+tshirts.slug # => "clothing/t-shirts" (aliased)
+
+# When parent changes, children update automatically
+clothing.update!(name: 'Apparel')
+tshirts.reload.permalink # => "apparel/t-shirts"
+```
+
+### Store
+
+Stores use `code` as their slug column, and the slug is used for internal routing and multi-store identification.
+
+```ruby
+# core/app/models/spree/store.rb:24
+friendly_id :slug_candidates, use: [:slugged, :history], slug_column: :code
+```
+
+**Configuration:**
+- **Slug column**: `code` (not `slug`)
+- **Modules**: `:slugged`, `:history`
+- **Reserved codes**: Admin, default, app, api, www, cdn, files, assets, checkout, etc.
+
+**Key features:**
+- Code is parameterized from store name
+- Uniqueness enforced across soft-deleted stores
+- History tracking for code changes
+- Custom validation against reserved words
+
+```ruby
+# Creating a store
+store = Spree::Store.create!(
+ name: 'My Awesome Store',
+ url: 'mystore.example.com',
+ default_currency: 'USD',
+ default_country: Spree::Country.find_by(iso: 'US')
+)
+store.code # => "my-awesome-store"
+
+# Code is read-only after creation (doesn't regenerate on name change)
+store.update!(name: 'My Better Store')
+store.code # => "my-awesome-store" (unchanged)
+```
+
+### Other Models
+
+Other Spree models that use FriendlyId:
+
+- **Pages** (`Spree::Page`): Uses `slug` column with history
+- **Posts** (`Spree::Post`): Uses `slug` column with history and translations
+- **Post Categories** (`Spree::PostCategory`): Uses `slug` column with history
+- **Policies** (`Spree::Policy`): Uses `slug` column with history
+
+## Internationalization
+
+Spree integrates FriendlyId with Mobility for multi-language slug support using the `friendly_id-mobility` gem.
+
+### Translatable Models
+
+Products, Posts, and Post Categories support translatable slugs:
+
+```ruby
+# Products include TranslatableResourceSlug concern
+include Spree::TranslatableResourceSlug
+
+# Each translation has its own slug
+product = Spree::Product.create!(
+ name: 'Red Shoes',
+ stores: [store]
+)
+product.slug # => "red-shoes" (default locale)
+
+# Add French translation
+product.translations.create!(
+ locale: :fr,
+ name: 'Chaussures Rouges',
+ slug: nil # Auto-generated from name
+)
+
+# Access localized slugs
+I18n.with_locale(:fr) do
+ product.slug # => "chaussures-rouges"
+end
+
+# Or use the helper method
+product.localized_slugs_for_store(store)
+# => {
+# "en" => "red-shoes",
+# "fr" => "chaussures-rouges"
+# }
+```
+
+### Translation Slug Generation
+
+When creating translations, slugs are automatically generated with this priority:
+
+1. **Custom slug** - If provided, it's normalized (e.g., `'Custom Slug!'` → `'custom-slug'`)
+2. **Translated name** - Generated from the translation's name field
+3. **Fallback to default** - Uses default locale's name if translation name is blank
+
+```ruby
+# Example from core/app/models/spree/product/slugs.rb:29-36
+def generate_slug
+ if name.blank? && slug.blank?
+ translated_model.name.to_url # Use default locale name
+ elsif slug.blank?
+ name.to_url # Use translation name
+ else
+ slug.to_url # Use custom slug
+ end
+end
+```
+
+### Translation Uniqueness
+
+Slugs must be unique within the same locale but can be duplicated across locales:
+
+```ruby
+# Same slug in different locales - OK
+product1.translations.create!(locale: :fr, slug: 'tshirt')
+product2.translations.create!(locale: :es, slug: 'tshirt') # ✅ Allowed
+
+# Duplicate slug in same locale - Auto-fixed with UUID
+product1.translations.create!(locale: :fr, slug: 'tshirt')
+product2.translations.create!(locale: :fr, slug: 'tshirt') # ❌ "tshirt-<uuid>"
+```
+
+## Slug History
+
+FriendlyId's history feature preserves old slugs when they change, ensuring existing URLs continue to work. This is critical for:
+
+- SEO (avoiding broken links)
+- Bookmarks and external references
+- Graceful URL migration
+
+```ruby
+product = Spree::Product.create!(name: 'Original Name', stores: [store])
+product.slug # => "original-name"
+
+# Change the name (generates new slug)
+product.update!(name: 'New Name', slug: nil)
+product.slug # => "new-name"
+
+# Old slug still works (redirects to new slug)
+Spree::Product.friendly.find('original-name') # => Still finds the product
+
+# View slug history
+product.slugs.pluck(:slug)
+# => ["original-name", "new-name"]
+```
+
+### Slug History Table
+
+FriendlyId maintains a separate `friendly_id_slugs` table:
+
+```ruby
+# Schema
+create_table :friendly_id_slugs do |t|
+ t.string :slug, null: false
+ t.integer :sluggable_id, null: false
+ t.string :sluggable_type, limit: 50
+ t.string :scope
+ t.string :locale # Added by Spree for multi-language
+ t.datetime :created_at
+ t.datetime :deleted_at # Added by Spree for soft-delete
+end
+```
+
+## Soft Deletes and Slugs
+
+Spree extends FriendlyId to work with soft-deleted records (using Paranoia gem). When a resource is deleted:
+
+1. The record is marked as deleted (`deleted_at` timestamp)
+2. The slug is prefixed with `deleted-` and a UUID
+3. Slug history records are also soft-deleted
+4. Original slug becomes available for new records
+
+```ruby
+product = Spree::Product.create!(name: 'Test Product', stores: [store])
+product.slug # => "test-product"
+
+# Soft delete the product
+product.destroy!
+
+# Slug is renamed with deleted prefix
+product.slug # => "deleted-test-product-a1b2c3d4-..."
+
+# Original slug is now available
+new_product = Spree::Product.create!(name: 'Test Product', stores: [store])
+new_product.slug # => "test-product" ✅
+```
+
+### Restoration
+
+When restoring a soft-deleted record, the slug is regenerated:
+
+```ruby
+product.restore(recursive: true)
+product.slug # => "test-product" (original slug restored if available)
+```
+
+### Implementation
+
+```ruby
+# From core/app/models/spree/product/slugs.rb:93-107
+def punch_slugs
+ return if new_record? || frozen?
+
+ self.slug = nil
+ set_slug
+ update_column(:slug, slug)
+
+ new_slug = ->(rec) { "deleted-#{rec.slug}-#{uuid_for_friendly_id}"[..254] }
+
+ # Update both translations and slug history
+ translations.with_deleted.each { |rec| rec.update_columns(slug: new_slug.call(rec)) }
+ slugs.with_deleted.each { |rec| rec.update_column(:slug, new_slug.call(rec)) }
+end
+```
+
+## Working with Slugs
+
+### Finding by Slug
+
+Use the `friendly` scope to find records by slug:
+
+```ruby
+# Find by slug
+product = Spree::Product.friendly.find('ruby-on-rails-tshirt')
+
+# Find by ID still works
+product = Spree::Product.friendly.find(123)
+
+# Find by historical slug (auto-redirects)
+product = Spree::Product.friendly.find('old-slug-name')
+```
+
+### Setting Custom Slugs
+
+You can override auto-generated slugs:
+
+```ruby
+# Auto-generated slug
+product = Spree::Product.create!(
+ name: 'Ruby on Rails T-Shirt',
+ stores: [store]
+)
+product.slug # => "ruby-on-rails-t-shirt"
+
+# Custom slug
+product.update!(slug: 'rails-tshirt')
+product.slug # => "rails-tshirt"
+
+# Reset to auto-generate (set to nil)
+product.update!(slug: nil)
+product.slug # => "ruby-on-rails-t-shirt" (regenerated from name)
+```
+
+### Slug Normalization
+
+Slugs are automatically normalized on validation:
+
+```ruby
+product = Spree::Product.new(
+ name: 'Test',
+ slug: 'Hey//Joe', # Invalid format
+ stores: [store]
+)
+product.valid?
+product.slug # => "hey-joe" (normalized)
+```
+
+### Checking Slug Availability
+
+```ruby
+# Check if a slug is available
+Spree::Product.slug_available?('my-slug', product.id) # => true/false
+
+# Ensure slug uniqueness manually
+def ensure_unique_slug(candidate)
+ return candidate if Spree::Product.slug_available?(candidate, id)
+
+ "#{candidate}-#{SecureRandom.uuid}"
+end
+```
+
+### Localized Slug Retrieval
+
+For multi-store, multi-language applications:
+
+```ruby
+# Get all localized slugs for a store
+product.localized_slugs_for_store(store)
+# => {
+# "en" => "ruby-tshirt",
+# "fr" => "tshirt-ruby",
+# "es" => "camiseta-ruby"
+# }
+```
+
+## Adding Slugs to Custom Models
+
+To add FriendlyId slugs to your custom models, inherit from `Spree::Base` which provides the base slug functionality.
+
+### Basic Implementation
+
+```ruby
+# app/models/spree/brand.rb
+module Spree
+ class Brand < Spree::Base
+ extend FriendlyId
+ friendly_id :slug_candidates, use: [:slugged, :history]
+
+ validates :name, presence: true
+ validates :slug, presence: true, uniqueness: true
+
+ # slug_candidates is already defined in Spree::Base
+ # No need to override unless you need custom behavior
+ end
+end
+```
+
+<Info>
+Models inheriting from `Spree::Base` automatically get the `slug_candidates` and `uuid_for_friendly_id` methods. You only need to override `slug_candidates` if you need custom slug generation logic (like Product does with SKU).
+</Info>
+
+### With Translation Support
+
+```ruby
+# app/models/spree/brand.rb
+module Spree
+ class Brand < Spree::Base
+ extend FriendlyId
+ include Spree::TranslatableResource
+ include Spree::TranslatableResourceSlug
+
+ translates :name, :slug
+ friendly_id :slug_candidates,
+ use: [:history, :slugged, :scoped, :mobility],
+ scope: spree_base_uniqueness_scope
+
+ validates :name, presence: true
+ validates :slug, presence: true,
+ uniqueness: { scope: spree_base_uniqueness_scope }
+
+ # Inherited slug_candidates from Spree::Base work for most cases
+ # Override only if needed for custom logic
+ end
+end
+```
+
+### With Soft Deletes
+
+```ruby
+# app/models/spree/brand.rb
+module Spree
+ class Brand < Spree::Base
+ extend FriendlyId
+ acts_as_paranoid
+
+ friendly_id :slug_candidates, use: [:slugged, :history]
+
+ validates :name, presence: true
+ validates :slug, presence: true, uniqueness: { conditions: -> { with_deleted } }
+
+ after_destroy :rename_slug_on_delete
+ after_restore :regenerate_slug_on_restore
+
+ private
+
+ def rename_slug_on_delete
+ return if new_record?
+
+ new_slug = "deleted-#{slug}-#{uuid_for_friendly_id}"[..254]
+ update_column(:slug, new_slug)
+ end
+
+ def regenerate_slug_on_restore
+ self.slug = nil
+ save!
+ end
+
+ # slug_candidates inherited from Spree::Base handles deleted records
+ end
+end
+```
+
+## Routing
+
+Spree uses `:id` as the route parameter for all resources, but the `.friendly` finder allows both IDs and slugs to work interchangeably.
+
+### Default Spree Routes
+
+```ruby
+# Spree's default routes use :id parameter
+# GET /products/:id -> handles both numeric IDs and slugs
+
+# Both of these URLs work:
+# /products/123 (finds by ID)
+# /products/ruby-tshirt (finds by slug)
+```
+
+### Custom Resources with Slugs
+
+```ruby
+# config/routes.rb
+Spree::Core::Engine.routes.draw do
+ resources :brands, only: [:show]
+end
+```
+
+<Warning>
+Always use `:id` as the route parameter, not `:slug`. This allows FriendlyId's `.friendly` finder to accept both numeric IDs and slugs, maintaining backward compatibility.
+</Warning>
+
+### Controller Implementation
+
+```ruby
+# app/controllers/spree/brands_controller.rb
+module Spree
+ class BrandsController < Spree::StoreController
+ def show
+ # Use .friendly to find by both ID and slug
+ @brand = Spree::Brand.friendly.find(params[:id])
+
+ # Optional: Redirect if using old ID or non-canonical slug
+ redirect_if_legacy_path
+ end
+
+ private
+
+ def redirect_if_legacy_path
+ # If an old id or a numeric id was used to find the record,
+ # do a 301 redirect that uses the current friendly id.
+ if params[:id] != @brand.friendly_id
+ redirect_to brand_path(@brand), status: :moved_permanently
+ end
+ end
+ end
+end
+```
+
+### Storefront Examples
+
+```ruby
+# From storefront/app/controllers/spree/products_controller.rb:43-45
+def load_product
+ @product ||= find_with_fallback_default_locale do
+ current_store.products.friendly.find(params[:id])
+ end
+end
+
+# From storefront/app/controllers/spree/taxons_controller.rb:22-24
+def load_taxon
+ @taxon ||= find_with_fallback_default_locale do
+ current_store.taxons.friendly.find(params[:id])
+ end
+end
+```
+
+`find_with_fallback_default_locale` is a helper method that is used to find a resource in the current locale or the default store locale.
+
+### API Routes
+
+Both Storefront API and Platform API accept slugs or IDs:
+
+```ruby
+# From api/app/controllers/spree/api/v2/storefront/products_controller.rb:20
+@resource ||= find_with_fallback_default_locale do
+ scope.includes(variants: variant_includes, master: variant_includes)
+ .friendly.find(params[:id])
+end
+
+# API Examples:
+# GET /api/v2/storefront/products/123
+# GET /api/v2/storefront/products/ruby-on-rails-tshirt
+```
+
+## Best Practices
+
+### 1. Always Use the `friendly` Scope
+
+```ruby
+# ✅ Good - handles both slugs and IDs
+product = Spree::Product.friendly.find(params[:id])
+
+# ❌ Bad - only works with IDs
+product = Spree::Product.find(params[:id])
+```
+
+### 2. Set Slugs to `nil` to Regenerate
+
+```ruby
+# ✅ Good - regenerates slug from name
+product.update!(slug: nil)
+
+# ❌ Bad - keeps old slug even if name changed
+product.update!(name: 'New Name') # slug unchanged
+```
+
+### 3. Validate Slug Uniqueness with Scope
+
+```ruby
+# Always use the appropriate scope
+validates :slug,
+ presence: true,
+ uniqueness: {
+ scope: spree_base_uniqueness_scope, # eg [:tenant_id]
+ case_sensitive: true
+ }
+```
+
+### 4. Eager Load Slugs When Needed
+
+```ruby
+# ✅ Good - includes slug history
+products = Spree::Product.includes(:slugs)
+
+# For routing, slug history isn't needed
+products = Spree::Product.all # Just uses slug column
+```
+
+### 5. Preserve Slug History
+
+```ruby
+# ✅ Good - maintains URL consistency
+product.update!(name: 'New Name', slug: nil) # Old slug still works
+
+# ❌ Bad - breaks existing URLs
+product.update!(slug: 'completely-different') # Old slug breaks
+```
+
+### 6. Handle Locale-Specific Slugs
+
+```ruby
+# ✅ Good - provide translations
+product.translations.create!(
+ locale: :fr,
+ name: 'Nom Français',
+ slug: nil # Auto-generates
+)
+
+# ❌ Bad - reusing English slug
+product.translations.create!(
+ locale: :fr,
+ name: 'Nom Français',
+ slug: product.slug # Not SEO-friendly for French
+)
+```
+
+### 7. Use Route Helpers with :id Parameter
+
+```ruby
+# ✅ Good - uses Spree routes with :id parameter
+spree.product_path(product) # Works with both slug and ID
+# Generates: /products/ruby-tshirt (uses slug automatically)
+
+# ✅ Good - explicit slug
+spree.product_path(product.slug)
+# Generates: /products/ruby-tshirt
+
+# ✅ Good - explicit ID
+spree.product_path(product.id)
+# Generates: /products/123
+
+# ❌ Bad - manual URL construction
+"/products/#{product.slug}" # Doesn't handle edge cases
+
+# ❌ Bad - using :slug as route parameter
+resources :products, param: :slug # Don't do this - breaks ID lookup
+```
+
+### 8. Test Slug Behavior
+
+```ruby
+# Example spec
+RSpec.describe Spree::Brand, type: :model do
+ describe 'slugs' do
+ it 'generates slug from name' do
+ brand = create(:brand, name: 'Test Name')
+ expect(brand.slug).to eq('test-name')
+ end
+
+ it 'ensures slug uniqueness' do
+ create(:brand, name: 'Test')
+ duplicate = create(:brand, name: 'Test')
+ expect(duplicate.slug).to match(/test-.+/)
+ end
+
+ it 'preserves old slugs in history' do
+ brand = create(:brand, name: 'Original')
+ brand.update!(name: 'Changed', slug: nil)
+
+ expect(brand.slug).to eq('changed')
+ expect(brand.slugs.pluck(:slug)).to include('original')
+ end
+ end
+end
+```
+
+## Troubleshooting
+
+### Slug Not Updating When Name Changes
+
+**Problem**: Changing a product's name doesn't update the slug.
+
+**Solution**: Explicitly set slug to `nil` to trigger regeneration:
+
+```ruby
+product.update!(name: 'New Name', slug: nil)
+```
+
+### Duplicate Slug Errors
+
+**Problem**: Getting uniqueness validation errors on slug.
+
+**Solution**: Check if you're properly scoping uniqueness:
+
+```ruby
+# Ensure correct scope in validation
+validates :slug,
+ uniqueness: {
+ scope: spree_base_uniqueness_scope,
+ case_sensitive: true
+ }
+```
+
+### Slugs Not Working After Restore
+
+**Problem**: Restored products have `deleted-` prefix in slug.
+
+**Solution**: Ensure you have the `after_restore` callback:
+
+```ruby
+after_restore :regenerate_slug
+
+def regenerate_slug
+ self.slug = nil
+ save!
+end
+```
+
+### Translation Slugs Not Generated
+
+**Problem**: Translation slugs are blank or invalid.
+
+**Solution**: Ensure you're setting slugs correctly in Translation model:
+
+```ruby
+# In your Translation class
+before_validation :set_slug
+
+def set_slug
+ self.slug = generate_slug
+end
+
+def generate_slug
+ if name.blank? && slug.blank?
+ translated_model.name.to_url
+ elsif slug.blank?
+ name.to_url
+ else
+ slug.to_url
+ end
+end
+```
+
+## Reference
+
+### Key Files
+
+- `core/app/models/spree/product/slugs.rb` - Product slug implementation
+- `core/app/models/spree/taxon.rb` - Taxon permalink implementation (lines 33, 230-365)
+- `core/app/models/spree/store.rb` - Store code implementation (lines 24, 543-568)
+- `core/app/models/concerns/spree/translatable_resource_slug.rb` - Translation helper
+- `core/config/initializers/friendly_id.rb` - Global FriendlyId config
+- `core/lib/friendly_id/paranoia.rb` - Paranoia integration
+
+### Useful Methods
+
+| Method | Description |
+|--------|-------------|
+| `Model.friendly.find(slug)` | Find by slug or ID |
+| `resource.slug` | Get current slug |
+| `resource.slug = 'custom'` | Set custom slug |
+| `resource.slugs` | Access slug history |
+| `resource.localized_slugs_for_store(store)` | Get all locale slugs |
+| `Model.slug_available?(slug, id)` | Check slug availability |
+| `resource.friendly_id` | Current friendly ID |
+| `resource.set_friendly_id(slug, locale)` | Set slug for locale |
+
diff --git a/docs/developer/core-concepts/stores.mdx b/docs/developer/core-concepts/stores.mdx
index b04d232063..ed363b8bc8 100644
--- a/docs/developer/core-concepts/stores.mdx
+++ b/docs/developer/core-concepts/stores.mdx
@@ -1,6 +1,5 @@
---
title: Stores
-icon: "shop"
---
## Overview
diff --git a/docs/developer/core-concepts/taxes.mdx b/docs/developer/core-concepts/taxes.mdx
index 321f5f3485..e37e2b9eea 100644
--- a/docs/developer/core-concepts/taxes.mdx
+++ b/docs/developer/core-concepts/taxes.mdx
@@ -1,7 +1,6 @@
---
title: Taxes
description: Learn how to configure taxes in Spree
-icon: "percent"
---
diff --git a/docs/developer/core-concepts/users.mdx b/docs/developer/core-concepts/users.mdx
index c8feb64708..76f74ae061 100644
--- a/docs/developer/core-concepts/users.mdx
+++ b/docs/developer/core-concepts/users.mdx
@@ -1,6 +1,5 @@
---
title: Users
-icon: "users"
---
In your Spree application you will usually have 2 types of users:
diff --git a/docs/developer/customization/api.mdx b/docs/developer/customization/api.mdx
index 24fba3a544..8913588c45 100644
--- a/docs/developer/customization/api.mdx
+++ b/docs/developer/customization/api.mdx
@@ -1,6 +1,5 @@
---
title: API
-icon: code
description: >-
This page covers adding new Spree API endpoints and customization of
existing ones
diff --git a/docs/developer/customization/authentication.mdx b/docs/developer/customization/authentication.mdx
index 9b0d18d889..ac4056a589 100644
--- a/docs/developer/customization/authentication.mdx
+++ b/docs/developer/customization/authentication.mdx
@@ -2,7 +2,6 @@
title: Authentication
description: Learn how to use a custom authentication setup with Spree
version: v5
-icon: user
---
If you installed Spree following the [Quickstart guide](/developer/quickstart), you can completely skip this step - you are all set and integrated with the [Devise](https://github.com/plataformatec/devise) gem.
diff --git a/docs/developer/customization/checkout.mdx b/docs/developer/customization/checkout.mdx
index 0233438b60..e917f579e3 100644
--- a/docs/developer/customization/checkout.mdx
+++ b/docs/developer/customization/checkout.mdx
@@ -2,7 +2,6 @@
title: Checkout Flow
description: Learn how to customize the checkout process in Spree.
version: v5
-icon: "cart-shopping"
---
## Overview
@@ -78,15 +77,13 @@ This step is disabled by default, but can be enabled by two ways:
1. globally for all orders by setting a preference in `config/initializers/spree.rb`:
- ```ruby
+ ```ruby config/initializers/spree.rb
Spree::Config[:always_include_confirm_step] = true
```
2. conditionally for specific orders by overriding the `confirmation_required?` method in `Spree::Order` with a [decorator](/developer/customization/decorators), eg.
- `app/models/spree/order_decorator.rb` file:
-
- ```ruby
+ ```ruby app/models/spree/order_decorator.rb
module Spree
module OrderDecorator
# require confirmation for orders with a US billing address
@@ -103,7 +100,7 @@ The [state_machines](https://github.com/state-machines/state_machines) gem allow
So, for example, if you wanted to verify that the user provides a valid zip code before transitioning to the delivery step, you would first implement a `valid_zip_code?` method, and then tell the state machine to run this method before that transition, placing this code in a file called `app/models/spree/order_decorator.rb`:
-```ruby
+```ruby app/models/spree/order_decorator.rb
module Spree
module OrderDecorator
def self.prepended(base)
@@ -128,7 +125,7 @@ To add or remove steps to the checkout flow, you can use the
The `insert_checkout_step` method takes a `before` or `after` option to determine where to insert the step:
-```ruby
+```ruby app/models/spree/order_decorator.rb
module Spree
module OrderDecorator
def self.prepended(base)
@@ -144,7 +141,7 @@ end
The `remove_checkout_step` will remove just one checkout step at a time:
-```ruby
+```ruby app/models/spree/order_decorator.rb
module Spree
module OrderDecorator
def self.prepended(base)
@@ -161,7 +158,7 @@ What will happen here is that when a user goes to checkout, they will be asked t
To completely re-define the flow of the checkout, use the `checkout_flow` helper:
-```ruby
+```ruby app/models/spree/order_decorator.rb
module Spree
module OrderDecorator
def self.prepended(base)
diff --git a/docs/developer/customization/configuration.mdx b/docs/developer/customization/configuration.mdx
index c650191cee..5053223d03 100644
--- a/docs/developer/customization/configuration.mdx
+++ b/docs/developer/customization/configuration.mdx
@@ -1,6 +1,5 @@
---
title: "Configuration"
-icon: "sliders"
---
Here is a list of all the configuration options that are available in Spree.
diff --git a/docs/developer/customization/decorators.mdx b/docs/developer/customization/decorators.mdx
index 45c3369cd7..815d1c0d17 100644
--- a/docs/developer/customization/decorators.mdx
+++ b/docs/developer/customization/decorators.mdx
@@ -1,58 +1,121 @@
---
title: Decorators
description: Decorators allow you to add or modify behavior of Spree classes in your application.
-icon: "code"
---
+<Info>
+ Decorators should be used as a last resort. They make upgrades difficult. Please use [Spree Dependencies](/developer/customization/dependencies) if possible.
+</Info>
+
## Overview
-All of Spree's models, controllers, services,helpers, etc can easily be extended or overridden to meet your exact requirements using standard Ruby idioms.
+All of Spree's models, controllers, helpers, etc can easily be extended or overridden to meet your exact requirements using standard Ruby idioms.
-Standard practice for including such changes in your application or extension is to create a file within the relevant **app/models/spree** or **app/controllers/spree** directory with the original class name with **_decorator** appended, eg. for the `Spree::Product` model, create a file called `app/models/spree/product_decorator.rb`.
+Standard practice for including such changes in your application or extension is to create a file within the relevant **app/models/spree** or **app/controllers/spree** directory with the original class name with **_decorator** appended.
-## Decorating Models
+## Why Use Decorators?
-### Changing behavior of existing methods
+When working with Spree, you'll often need to add functionality to existing models like `Spree::Product` or `Spree::Order`. However, you shouldn't modify these files directly because:
-Changing the behavior of existing methods is the most common use case for decorators.
+1. **Upgrades** - Your changes would be lost when updating Spree
+2. **Maintainability** - It's hard to track what you've customized
+3. **Conflicts** - Direct modifications can conflict with Spree's code
-Let's say you want to change the behavior of the `available?` in the [Product](https://github.com/spree/spree/blob/main/core/app/models/spree/product.rb) model.
+Instead, we use **decorators** - a Ruby pattern that lets you add or modify behavior of existing classes without changing their original source code.
-1. Let's start with creating a file in `app/models/spree/product_decorator.rb`
+## How Decorators Work
- ```bash
- mkdir -p app/models/spree && touch app/models/spree/product_decorator.rb
- ```
+In Ruby, classes are "open" - you can add methods to them at any time. Decorators leverage this by:
-2. And add the following code to the file:
+1. Creating a module with your new methods
+2. Using `Module#prepend` to inject your module into the class's inheritance chain
+3. Your methods run first, and can call `super` to invoke the original method
- ```ruby
- module Spree
- module ProductDecorator
- def available?
- # your code here
- end
- end
+```ruby
+# This is the basic pattern
+module Spree
+ module ProductDecorator
+ # Add a new method
+ def my_new_method
+ "Hello from decorator!"
+ end
- Product.prepend(ProductDecorator)
+ # Override an existing method
+ def existing_method
+ # Do something before
+ result = super # Call the original method
+ # Do something after
+ result
end
- ```
+ end
+
+ Product.prepend(ProductDecorator)
+end
+```
-### Adding a new method to the model
+The key line is `Product.prepend(ProductDecorator)` - this inserts your module at the beginning of the method lookup chain, so your methods are found first.
-You can also add a new method to the model. Or even add custom validations, callbacks, etc.
+## Generating Decorators
+
+Spree provides generators to create decorator files with the correct structure:
+
+### Model Decorator Generator
+
+```bash
+bin/rails g spree:model_decorator Spree::Product
+```
+
+This creates `app/models/spree/product_decorator.rb`:
```ruby
module Spree
module ProductDecorator
def self.prepended(base)
- base.before_validation :strip_whitespaces
+ # Class-level configurations go here
end
+ end
+
+ Product.prepend(ProductDecorator)
+end
+```
- protected
+### Controller Decorator Generator
- def strip_whitespaces
- self.name = name.strip
+```bash
+bin/rails g spree:controller_decorator Spree::Admin::ProductsController
+```
+
+This creates `app/controllers/spree/admin/products_controller_decorator.rb`:
+
+```ruby
+module Spree
+ module Admin
+ module ProductsControllerDecorator
+ def self.prepended(base)
+ # Class-level configurations go here
+ end
+ end
+
+ ProductsController.prepend(ProductsControllerDecorator)
+ end
+end
+```
+
+## Decorating Models
+
+### Changing Behavior of Existing Methods
+
+The most common use case is changing the behavior of existing methods. When overriding a method, you can call `super` to invoke the original implementation:
+
+```ruby app/models/spree/product_decorator.rb
+module Spree
+ module ProductDecorator
+ def available?
+ # Add custom logic before
+ return false if discontinued?
+
+ # Call the original method
+ super
end
end
@@ -60,34 +123,72 @@ module Spree
end
```
-### Adding new associations to Spree models
+<Warning>
+ Always consider whether you need to call `super` when overriding methods. Omitting it completely replaces the original behavior, which may break functionality.
+</Warning>
-Assume you want to add a new model called `Video` associated to `Spree::Product`. Let's start with creating a database migration:
+### Adding New Methods
-```bash
-bin/rails g migration CreateSpreeVideos url:string product:references
-bin/rails db:migrate
+Add new instance methods directly in the decorator module:
+
+```ruby app/models/spree/product_decorator.rb
+module Spree
+ module ProductDecorator
+ def featured?
+ metadata[:featured] == true
+ end
+
+ def days_until_available
+ return 0 if available_on.nil? || available_on <= Time.current
+ (available_on.to_date - Date.current).to_i
+ end
+ end
+
+ Product.prepend(ProductDecorator)
+end
```
-Create a model and add the association to `Spree::Product`:
+### Adding Associations
-```ruby
+Use the `self.prepended(base)` callback to add associations:
+
+```ruby app/models/spree/product_decorator.rb
module Spree
- class Video < Spree.base_class
- belongs_to :product, class_name: 'Spree::Product'
+ module ProductDecorator
+ def self.prepended(base)
+ base.belongs_to :brand, class_name: 'Spree::Brand', optional: true
+ base.has_many :videos, class_name: 'Spree::Video', dependent: :destroy
+ end
+ end
- has_one_attached :video_file
+ Product.prepend(ProductDecorator)
+end
+```
+
+### Adding Validations
+
+```ruby app/models/spree/product_decorator.rb
+module Spree
+ module ProductDecorator
+ def self.prepended(base)
+ base.validates :external_id, presence: true, uniqueness: true
+ base.validates :weight, numericality: { greater_than: 0 }, allow_nil: true
+ end
end
+
+ Product.prepend(ProductDecorator)
end
```
-Finally add the association in `ProductDecorator` in `app/models/spree/product_decorator.rb`:
+### Adding Scopes
-```ruby
+```ruby app/models/spree/product_decorator.rb
module Spree
module ProductDecorator
def self.prepended(base)
- base.has_many :videos, class_name: 'Spree::Video', dependent: :destroy
+ base.scope :featured, -> { where("metadata->>'featured' = ?", 'true') }
+ base.scope :recently_added, -> { where('created_at > ?', 30.days.ago) }
+ base.scope :on_sale, -> { joins(:variants).where('spree_prices.compare_at_amount > spree_prices.amount') }
end
end
@@ -95,45 +196,86 @@ module Spree
end
```
-## Decorating Controllers
+### Adding Callbacks
+
+```ruby app/models/spree/product_decorator.rb
+module Spree
+ module ProductDecorator
+ def self.prepended(base)
+ base.before_validation :normalize_name
+ base.after_save :sync_to_external_service
+ base.after_destroy :cleanup_external_data
+ end
-Adding a custom action to the [ProductsController](https://github.com/spree/spree/blob/main/frontend/app/controllers/spree/products_controller.rb)
+ private
-1. Create a file in `app/controllers/spree/products_controller_decorator.rb`
+ def normalize_name
+ self.name = name.strip.titleize if name.present?
+ end
- ```bash
- mkdir -p app/controllers/spree && touch app/controllers/spree/products_controller_decorator.rb
- ```
+ def sync_to_external_service
+ ExternalSyncJob.perform_later(self) if saved_change_to_name?
+ end
-2. Add the following code:
+ def cleanup_external_data
+ ExternalCleanupJob.perform_later(id)
+ end
+ end
- ```ruby
- module Spree
- module ProductsControllerDecorator
- def some_action
- # your code here
- end
- end
+ Product.prepend(ProductDecorator)
+end
+```
+
+### Adding Class Methods
- ProductsController.prepend(ProductsControllerDecorator)
+Use `extend` within the `prepended` callback to add class methods:
+
+```ruby app/models/spree/product_decorator.rb
+module Spree
+ module ProductDecorator
+ def self.prepended(base)
+ base.extend ClassMethods
end
- ```
-The exact same format can be used to redefine an existing method.
+ module ClassMethods
+ def search_by_name(query)
+ where('LOWER(name) LIKE ?', "%#{query.downcase}%")
+ end
+ end
+ end
-### Accessing Product Data
+ Product.prepend(ProductDecorator)
+end
+```
-If you extend the Products controller with a new method, you may very well want to access product data in that method. You can do so by using the `:load_data before_action`.
+Usage:
```ruby
+Spree::Product.search_by_name('shirt')
+```
+
+## Decorating Controllers
+
+### Adding a New Action
+
+```ruby app/controllers/spree/products_controller_decorator.rb
module Spree
module ProductsControllerDecorator
def self.prepended(base)
- base.before_action :load_data, only: :some_action
+ base.before_action :load_product, only: [:quick_view]
end
- def some_action
- # your code here
+ def quick_view
+ respond_to do |format|
+ format.html { render partial: 'quick_view', locals: { product: @product } }
+ format.json { render json: @product }
+ end
+ end
+
+ private
+
+ def load_product
+ @product = current_store.products.friendly.find(params[:id])
end
end
@@ -141,4 +283,159 @@ module Spree
end
```
-`:load_data` will use `params[:id]` to lookup the product by its permalink.
\ No newline at end of file
+Don't forget to add the route:
+
+```ruby config/routes.rb
+Spree::Core::Engine.add_routes do
+ get 'products/:id/quick_view', to: 'products#quick_view', as: :product_quick_view
+end
+```
+
+### Modifying Existing Actions
+
+```ruby app/controllers/spree/admin/products_controller_decorator.rb
+module Spree
+ module Admin
+ module ProductsControllerDecorator
+ def create
+ # Add custom logic before
+ log_product_creation_attempt
+
+ # Call original method
+ super
+
+ # Add custom logic after
+ notify_team_of_new_product if @product.persisted?
+ end
+
+ private
+
+ def log_product_creation_attempt
+ Rails.logger.info "Product creation attempted by #{current_spree_user.email}"
+ end
+
+ def notify_team_of_new_product
+ ProductNotificationJob.perform_later(@product)
+ end
+ end
+
+ ProductsController.prepend(ProductsControllerDecorator)
+ end
+end
+```
+
+### Adding Before Actions
+
+```ruby app/controllers/spree/checkout_controller_decorator.rb
+module Spree
+ module CheckoutControllerDecorator
+ def self.prepended(base)
+ base.before_action :check_minimum_order, only: [:update]
+ end
+
+ private
+
+ def check_minimum_order
+ if @order.total < 25.0 && params[:state] == 'payment'
+ flash[:error] = 'Minimum order amount is $25'
+ redirect_to checkout_state_path(@order.state)
+ end
+ end
+ end
+
+ CheckoutController.prepend(CheckoutControllerDecorator)
+end
+```
+
+## Best Practices
+
+<CardGroup cols={2}>
+ <Card title="Use the prepended callback" icon="code">
+ Always use `self.prepended(base)` for class-level additions like associations, validations, scopes, and callbacks.
+ </Card>
+
+ <Card title="Keep decorators focused" icon="crosshairs">
+ Each decorator should have a single responsibility. Create multiple decorators for different concerns if needed.
+ </Card>
+
+ <Card title="Call super when overriding" icon="arrow-up">
+ When overriding methods, call `super` to preserve original behavior unless you intentionally want to replace it entirely.
+ </Card>
+
+ <Card title="Test decorated behavior" icon="flask-vial">
+ Write tests specifically for your decorated functionality to catch regressions during upgrades.
+ </Card>
+</CardGroup>
+
+### Organizing Multiple Decorators
+
+If you have many customizations for a single class, consider splitting them into focused decorators:
+
+```
+app/models/spree/
+├── product_decorator.rb # Main decorator (loads others)
+├── product/
+│ ├── brand_decorator.rb # Brand association
+│ ├── inventory_decorator.rb # Inventory customizations
+│ └── seo_decorator.rb # SEO-related methods
+```
+
+```ruby app/models/spree/product_decorator.rb
+# Load focused decorators
+require_dependency 'spree/product/brand_decorator'
+require_dependency 'spree/product/inventory_decorator'
+require_dependency 'spree/product/seo_decorator'
+```
+
+## Common Pitfalls
+
+### Forgetting to Call Super
+
+```ruby
+# ❌ Bad - completely replaces original behavior
+def available?
+ in_stock? && active?
+end
+
+# ✅ Good - extends original behavior
+def available?
+ super && custom_availability_check
+end
+```
+
+### Using Instance Variables in prepended
+
+```ruby
+# ❌ Bad - instance variables don't work in prepended
+def self.prepended(base)
+ @custom_setting = true # This won't work as expected
+end
+
+# ✅ Good - use class attributes or methods
+def self.prepended(base)
+ base.class_attribute :custom_setting, default: true
+end
+```
+
+### Circular Dependencies
+
+Be careful when decorators depend on each other:
+
+```ruby
+# ❌ Bad - can cause loading issues
+# product_decorator.rb
+def self.prepended(base)
+ base.has_many :variants # Variant decorator might not be loaded yet
+end
+
+# ✅ Good - use strings for class names
+def self.prepended(base)
+ base.has_many :variants, class_name: 'Spree::Variant'
+end
+```
+
+## Related Documentation
+
+- [Extending Core Models Tutorial](/developer/tutorial/extending-models) - Step-by-step guide to connecting custom models with Spree core
+- [Customization Overview](/developer/customization/overview) - General customization patterns
+- [Logic Customization](/developer/customization/logic) - Customizing business logic
diff --git a/docs/developer/customization/dependencies.mdx b/docs/developer/customization/dependencies.mdx
index 05d48382e9..9fd52f5533 100644
--- a/docs/developer/customization/dependencies.mdx
+++ b/docs/developer/customization/dependencies.mdx
@@ -1,7 +1,6 @@
---
title: Dependencies
section: customization
-icon: gears
---
## Overview
diff --git a/docs/developer/customization/extensions.mdx b/docs/developer/customization/extensions.mdx
index f46bc19bef..5960136716 100644
--- a/docs/developer/customization/extensions.mdx
+++ b/docs/developer/customization/extensions.mdx
@@ -1,6 +1,5 @@
---
title: Extensions
-icon: "plug"
description: >-
Extensions provide additional features and integrations for your Spree
application. Here's a list of the most popular ones.
diff --git a/docs/developer/customization/metadata.mdx b/docs/developer/customization/metadata.mdx
index ef171838db..237594907c 100644
--- a/docs/developer/customization/metadata.mdx
+++ b/docs/developer/customization/metadata.mdx
@@ -1,8 +1,11 @@
---
title: Metadata
-icon: "tags"
---
+<Warning>
+ It's recommended to use [Metafields](/developer/core-concepts/metafields) instead of Metadata. Metafields provide type-safe, validated custom attributes with better admin UI support.
+</Warning>
+
## Overview
Metadata is a way to add additional information to Spree objects. There are two types of metadata:
@@ -38,7 +41,3 @@ puts taxon.public_metadata["google_category_id"]
```ruby
Spree::Taxon.where("public_metadata->>'google_category_id' = ?", "123")
```
-
-<Warning>
- For Products it's recommended to use [Metafields](/developer/core-concepts/metafields) or [Option Types](/developer/core-concepts/products#option-types-and-option-values) instead of Metadata. Metafields provide type-safe, validated custom attributes with better admin UI support.
-</Warning>
diff --git a/docs/developer/customization/model-preferences.mdx b/docs/developer/customization/model-preferences.mdx
index 44b621fbbd..ccbc6f23b6 100644
--- a/docs/developer/customization/model-preferences.mdx
+++ b/docs/developer/customization/model-preferences.mdx
@@ -1,6 +1,5 @@
---
title: Model Preferences
-icon: "list"
---
Model preferences allow you to easily extend Spree models with configuration options. Thanks to this you can store useful information on Spree models, eg.
diff --git a/docs/developer/customization/permissions.mdx b/docs/developer/customization/permissions.mdx
index ab987831ff..283389a5e0 100644
--- a/docs/developer/customization/permissions.mdx
+++ b/docs/developer/customization/permissions.mdx
@@ -1,6 +1,5 @@
---
title: Permissions
-icon: "shield-halved"
---
## User and Roles
diff --git a/docs/developer/customization/promotions.mdx b/docs/developer/customization/promotions.mdx
index 78d8a1442d..3401da43a3 100644
--- a/docs/developer/customization/promotions.mdx
+++ b/docs/developer/customization/promotions.mdx
@@ -1,6 +1,5 @@
---
title: Custom Promotions
-icon: "ticket"
description: >-
In this guide we will show you how to create custom promotion rules and actions in Spree.
---
@@ -52,11 +51,22 @@ In this guide we will show you how to create custom promotion rules and actions
<Accordion title="4. Register the New Action">
Register the new action with Spree.
Open `config/initializers/spree.rb` and add the following line:
- ```ruby
- Rails.application.config.after_initialize do
- Rails.application.config.spree.promotions.actions << Spree::Promotion::Actions::MyPromotionAction
- end
- ```
+
+ <Tabs>
+ <Tab title="Spree 5.2+">
+ ```ruby config/initializers/spree.rb
+ Spree.promotions.actions << Spree::Promotion::Actions::MyPromotionAction
+ ```
+ </Tab>
+ <Tab title="Spree 5.1 and below">
+ ```ruby config/initializers/spree.rb
+ Rails.application.config.after_initialize do
+ Rails.application.config.spree.promotions.actions << Spree::Promotion::Actions::MyPromotionAction
+ end
+ ```
+ </Tab>
+ </Tabs>
+
Once this has been registered, it will be available within Spree's interface.
</Accordion>
@@ -133,12 +143,21 @@ In this guide we will show you how to create custom promotion rules and actions
<Accordion title="4. Register the Custom Rule">
To make your custom rule available, register it within Spree by adding the following block to your `config/initializers/spree.rb` file:
- ```ruby
- Rails.application.config.after_initialize do
- Rails.application.config.spree.promotions.rules << Spree::Promotion::Rules::MyPromotionRule
- end
- ```
-
+ <Tabs>
+ <Tab title="Spree 5.2+">
+ ```ruby config/initializers/spree.rb
+ Spree.promotions.rules << Spree::Promotion::Rules::MyPromotionRule
+ ```
+ </Tab>
+ <Tab title="Spree 5.1 and below">
+ ```ruby config/initializers/spree.rb
+ Rails.application.config.after_initialize do
+ Rails.application.config.spree.promotions.rules << Spree::Promotion::Rules::MyPromotionRule
+ end
+ ```
+ </Tab>
+ </Tabs>
+
This step ensures that your custom rule is recognized and can be utilized within the Spree ecosystem.
</Accordion>
diff --git a/docs/developer/customization/quickstart.mdx b/docs/developer/customization/quickstart.mdx
index a4cb4cd10b..68f23c0cab 100644
--- a/docs/developer/customization/quickstart.mdx
+++ b/docs/developer/customization/quickstart.mdx
@@ -2,7 +2,6 @@
title: Quickstart
og:title: Spree Customization Quickstart
description: Learn how to customize every part of the Spree stack
-icon: wrench
---
Spree is a very flexible platform allowing you to customize every part of it, to suit your business needs.
diff --git a/docs/developer/customization/routes.mdx b/docs/developer/customization/routes.mdx
index 7b112faa3f..49ae9a8355 100644
--- a/docs/developer/customization/routes.mdx
+++ b/docs/developer/customization/routes.mdx
@@ -1,7 +1,6 @@
---
title: Routes
description: Learn how to customize the routes in Spree
-icon: "route"
---
## Default configuration
diff --git a/docs/developer/deployment/assets.mdx b/docs/developer/deployment/assets.mdx
index c3eec84344..6aa864c8a1 100644
--- a/docs/developer/deployment/assets.mdx
+++ b/docs/developer/deployment/assets.mdx
@@ -1,6 +1,5 @@
---
title: Assets
-icon: "images"
---
Spree uses [Active Storage](https://guides.rubyonrails.org/active_storage_overview.html) to handle file uploads (eg. product images). By default, Active Storage uses local disk storage for attachments. This isn't suitable for production environments.
diff --git a/docs/developer/deployment/aws.mdx b/docs/developer/deployment/aws.mdx
index 2acc910f35..934e2c444a 100644
--- a/docs/developer/deployment/aws.mdx
+++ b/docs/developer/deployment/aws.mdx
@@ -1,7 +1,6 @@
---
title: Amazon Web Services (AWS)
description: Learn how to deploy your Spree Commerce application on Amazon Web Services (AWS).
-icon: "aws"
---
Amazon Web Services offers reliable, scalable, and inexpensive cloud computing services. AWS is also one of the most popular choices for hosting a Spree application.
diff --git a/docs/developer/deployment/caching.mdx b/docs/developer/deployment/caching.mdx
index 158b826c31..f3819c3b0e 100644
--- a/docs/developer/deployment/caching.mdx
+++ b/docs/developer/deployment/caching.mdx
@@ -3,7 +3,6 @@ title: Caching
description: >-
This guide will cover all sorts of topics related to Spree application
performance
-icon: "database"
---
Caching is a great way to improve the performance of your Spree application. In all modern web applications, usually the most time consuming operations are database queries and rendering templates. Caching allows you to store the results of these operations in memory and serve them from there.
diff --git a/docs/developer/deployment/cdn.mdx b/docs/developer/deployment/cdn.mdx
index 71177c1d58..7340cb93d5 100644
--- a/docs/developer/deployment/cdn.mdx
+++ b/docs/developer/deployment/cdn.mdx
@@ -2,7 +2,6 @@
title: CDN
description: >-
Learn how to improve performance of your Spree application by using a CDN (Content Delivery Network).
-icon: "cloud"
---
To improve performance of your Spree application, we recommend using a CDN (Content Delivery Network) to cache images and static files.
diff --git a/docs/developer/deployment/docker.mdx b/docs/developer/deployment/docker.mdx
index 6e65e73915..2c5bdffc37 100644
--- a/docs/developer/deployment/docker.mdx
+++ b/docs/developer/deployment/docker.mdx
@@ -1,7 +1,6 @@
---
title: Docker
description: Learn how to build a Docker image of your Spree application.
-icon: "docker"
---
Spree (when using Spree Starter template) comes with a Dockerfile that can be used to build a Docker image of your application.
diff --git a/docs/developer/deployment/emails.mdx b/docs/developer/deployment/emails.mdx
index af52f521a9..11d96dd956 100644
--- a/docs/developer/deployment/emails.mdx
+++ b/docs/developer/deployment/emails.mdx
@@ -1,7 +1,6 @@
---
title: Sending out Emails
sidebarTitle: Emails
-icon: "envelope"
description: Learn how to send transactional emails from your Spree application.
---
diff --git a/docs/developer/deployment/environment_variables.mdx b/docs/developer/deployment/environment_variables.mdx
index 03cbc9ab2e..e7f1d7caa7 100644
--- a/docs/developer/deployment/environment_variables.mdx
+++ b/docs/developer/deployment/environment_variables.mdx
@@ -1,6 +1,5 @@
---
title: Environment Variables
-icon: "terminal"
---
[Spree Starter](https://github.com/spree/spree_starter) uses several environment variables to configure the application.
diff --git a/docs/developer/deployment/render.mdx b/docs/developer/deployment/render.mdx
index ee2e5e972e..d6964a0701 100644
--- a/docs/developer/deployment/render.mdx
+++ b/docs/developer/deployment/render.mdx
@@ -1,7 +1,6 @@
---
title: Render
description: Deploy your Spree application to [Render.com](https://render.com) Platform as a Service platform
-icon: "server"
---
## Overview
diff --git a/docs/developer/getting-started/quickstart.mdx b/docs/developer/getting-started/quickstart.mdx
index 817513cd38..93c59741d6 100644
--- a/docs/developer/getting-started/quickstart.mdx
+++ b/docs/developer/getting-started/quickstart.mdx
@@ -1,16 +1,12 @@
---
-title: "Quickstart"
+title: "Installing Spree"
+sidebarTitle: Installation
description: "Start building awesome eCommerce applications with Spree open-source eg. multi-store, multi-vendor, multi-tenant, multi-language, multi-currency. B2B or B2C."
-icon: "rocket"
---
-<img alt="Spree Commerce - Open Source e-commerce platform" classname="block dark:hidden" src="https://vendo-production-res.cloudinary.com/image/upload/w_1920/q_auto/v1733327023/docs/Spree_Commerce_open_source_eCommerce_platform_Ruby_on_Rails_API_headless_tsnvap.png" />
+Follow the instructions below to learn how to build and deploy your Spree Commerce store.
-## Getting Started with Spree Commerce
-
-Welcome to the Spree Commerce [open-source eCommerce](https://spreecommerce.org) documentation guide. Follow the instructions below to learn how to build and deploy your Spree Commerce store.
-
-### 1. Installing Spree
+## 1. Installing Spree
<Tabs>
<Tab title="Spree Installer">
@@ -70,7 +66,7 @@ Welcome to the Spree Commerce [open-source eCommerce](https://spreecommerce.org)
</Tab>
</Tabs>
-### 2. Exploring Your Store
+## 2. Exploring Your Store
Feel free to explore your store. You can do so because Spree comes with a default pre-built Storefront and Admin Panel.
@@ -116,4 +112,4 @@ Congrats! You've set up your Spree Commerce and it's looking amazing!
Give Spree a [GitHub Star](https://github.com/spree/spree)<Icon icon="star" iconType="solid" color="#FFD43B" />, why dont't ya? Thank you for supporting Spree open-source! <Icon icon="heart" iconType="solid" color="#FF0000" />
-Need support or want to give some feedback? Join our [community](https://slack.spreecommerce.org/) with 6000+ members or drop us an email at [[email protected]](mailto:[email protected]).
+Need support or want to give some feedback? Join our [community](https://slack.spreecommerce.org/) with 6000+ members or drop us an email at [[email protected]](mailto:[email protected]).
\ No newline at end of file
diff --git a/docs/developer/multi-tenant/core-concepts.mdx b/docs/developer/multi-tenant/core-concepts.mdx
index cb09d4c800..abb630b804 100644
--- a/docs/developer/multi-tenant/core-concepts.mdx
+++ b/docs/developer/multi-tenant/core-concepts.mdx
@@ -18,12 +18,7 @@ All models that are tenanted inherit from `SpreeMultiTenant::Base` class. `spree
When creating a new model that you want to be tenanted remember to inherit from `SpreeMultiTenant::Base` and not from `Spree::Base` and add `tenant_id` column to the table, eg.
```bash
-bin/rails g model Spree::NewModel tenant:references name:string
-```
-
-```ruby
-class Spree::NewModel < SpreeMultiTenant::Base
-end
+bin/rails g model Spree::NewModel tenant:references name:string --parent SpreeMultiTenant::Base
```
<Info>
diff --git a/docs/developer/storefront/blocks.mdx b/docs/developer/storefront/blocks.mdx
index f8c518f50c..a11048c781 100644
--- a/docs/developer/storefront/blocks.mdx
+++ b/docs/developer/storefront/blocks.mdx
@@ -3,18 +3,283 @@ title: "Blocks"
description: "Learn how to utilize blocks to build your Spree Storefront"
---
-<Warning>Documentation on blocks is coming soon</Warning>
+Blocks are the lowest level of components in Spree Storefront. They are nested inside [sections](/developer/storefront/sections) and represent individual content elements like headings, text, buttons, and images.
-Blocks are the lowest level of components in Spree Storefront. They are nested inside sections.
+## How Blocks Work
-Similarly to sections each block can be customized in terms of its content, styles, and layout.
+Each section can contain multiple blocks that store staff can manage through the Page Builder:
-Every block has a set of default preferences, such as:
+- Add new blocks
+- Edit block content and settings
+- Reorder blocks via drag-and-drop
+- Remove blocks
-* `text_alignment`
-* `container_alignment`
-* `size`
-* `width_desktop`
-* `top_padding`
-* `bottom_padding`
+Not all sections support blocks. A section must explicitly enable block support by implementing `blocks_available?` and `available_blocks_to_add` methods.
+## Built-in Block Types
+
+Spree comes with several built-in block types:
+
+### Content Blocks
+
+| Block | Description | Class |
+|-------|-------------|-------|
+| Heading | Large text headings | [Spree::PageBlocks::Heading](https://github.com/spree/spree/blob/main/core/app/models/spree/page_blocks/heading.rb) |
+| Subheading | Smaller secondary headings | [Spree::PageBlocks::Subheading](https://github.com/spree/spree/blob/main/core/app/models/spree/page_blocks/subheading.rb) |
+| Text | Rich text content | [Spree::PageBlocks::Text](https://github.com/spree/spree/blob/main/core/app/models/spree/page_blocks/text.rb) |
+| Buttons | Call-to-action buttons with links | [Spree::PageBlocks::Buttons](https://github.com/spree/spree/blob/main/core/app/models/spree/page_blocks/buttons.rb) |
+| Image | Image with optional link | [Spree::PageBlocks::Image](https://github.com/spree/spree/blob/main/core/app/models/spree/page_blocks/image.rb) |
+
+### Navigation Blocks
+
+| Block | Description | Class |
+|-------|-------------|-------|
+| Nav | Simple navigation links | [Spree::PageBlocks::Nav](https://github.com/spree/spree/blob/main/core/app/models/spree/page_blocks/nav.rb) |
+| Mega Nav | Mega menu navigation | [Spree::PageBlocks::MegaNav](https://github.com/spree/spree/blob/main/core/app/models/spree/page_blocks/mega_nav.rb) |
+| Link | Single link item | [Spree::PageBlocks::Link](https://github.com/spree/spree/blob/main/core/app/models/spree/page_blocks/link.rb) |
+
+### Product Blocks
+
+These blocks are used in the Product Details section:
+
+| Block | Description | Class |
+|-------|-------------|-------|
+| Title | Product title | [Spree::PageBlocks::Products::Title](https://github.com/spree/spree/blob/main/core/app/models/spree/page_blocks/products/title.rb) |
+| Price | Product price display | [Spree::PageBlocks::Products::Price](https://github.com/spree/spree/blob/main/core/app/models/spree/page_blocks/products/price.rb) |
+| Description | Product description | [Spree::PageBlocks::Products::Description](https://github.com/spree/spree/blob/main/core/app/models/spree/page_blocks/products/description.rb) |
+| Variant Picker | Size/color selector | [Spree::PageBlocks::Products::VariantPicker](https://github.com/spree/spree/blob/main/core/app/models/spree/page_blocks/products/variant_picker.rb) |
+| Quantity Selector | Quantity input | [Spree::PageBlocks::Products::QuantitySelector](https://github.com/spree/spree/blob/main/core/app/models/spree/page_blocks/products/quantity_selector.rb) |
+| Buy Buttons | Add to cart button | [Spree::PageBlocks::Products::BuyButtons](https://github.com/spree/spree/blob/main/core/app/models/spree/page_blocks/products/buy_buttons.rb) |
+| Share | Social sharing buttons | [Spree::PageBlocks::Products::Share](https://github.com/spree/spree/blob/main/core/app/models/spree/page_blocks/products/share.rb) |
+
+## Architecture
+
+### Base Class
+
+All blocks inherit from [Spree::PageBlock](https://github.com/spree/spree/blob/main/core/app/models/spree/page_block.rb):
+
+```ruby
+module Spree
+ class PageBlock < Spree.base_class
+ include Spree::HasPageLinks
+
+ belongs_to :section, class_name: 'Spree::PageSection'
+
+ has_rich_text :text
+ has_one_attached :asset
+
+ # Default preferences
+ preference :text_alignment, :string, default: 'left'
+ preference :container_alignment, :string, default: 'left'
+ preference :size, :string, default: 'medium'
+ preference :width_desktop, :integer, default: 100
+ preference :top_padding, :integer, default: 0
+ preference :bottom_padding, :integer, default: 0
+ end
+end
+```
+
+### Default Preferences
+
+Every block has these default preferences:
+
+| Preference | Type | Default | Description |
+|------------|------|---------|-------------|
+| `text_alignment` | String | `left` | Text alignment (left, center, right) |
+| `container_alignment` | String | `left` | Container alignment |
+| `size` | String | `medium` | Block size (small, medium, large) |
+| `width_desktop` | Integer | `100` | Width percentage on desktop |
+| `top_padding` | Integer | `0` | Top padding in pixels |
+| `bottom_padding` | Integer | `0` | Bottom padding in pixels |
+
+### Associations
+
+- **Section**: Each block belongs to a section (`section`)
+- **Links**: Blocks can have multiple links (`links`) via `Spree::HasPageLinks`
+- **Asset**: Blocks can have an attached image (`asset`)
+- **Rich Text**: Blocks can have rich text content (`text`)
+
+## Accessing Blocks
+
+```ruby
+# Get all blocks for a section
+section.blocks
+
+# Get blocks with eager loading
+section.blocks.includes(:rich_text_text, :links)
+
+# Find specific block type
+section.blocks.where(type: 'Spree::PageBlocks::Heading')
+```
+
+## Rendering Blocks
+
+In storefront section views, blocks are rendered within their parent section:
+
+```erb
+<% section.blocks.each do |block| %>
+ <% case block.type %>
+ <% when 'Spree::PageBlocks::Heading' %>
+ <h2 <%= block_attributes(block) %>>
+ <%= block.text %>
+ </h2>
+ <% when 'Spree::PageBlocks::Text' %>
+ <div <%= block_attributes(block) %>>
+ <%= block.text %>
+ </div>
+ <% when 'Spree::PageBlocks::Buttons' %>
+ <div <%= block_attributes(block) %>>
+ <% if block.link %>
+ <%= page_builder_link_to block.link, class: 'btn-primary' %>
+ <% end %>
+ </div>
+ <% end %>
+<% end %>
+```
+
+The `block_attributes(block)` helper returns data attributes needed for Page Builder editing.
+
+## Creating a Custom Block
+
+### Step 1: Create the Model
+
+```ruby app/models/spree/page_blocks/quote.rb
+module Spree
+ module PageBlocks
+ class Quote < Spree::PageBlock
+ SIZE_DEFAULT = 'large'
+ TEXT_ALIGNMENT_DEFAULT = 'center'
+
+ preference :author_name, :string
+ preference :author_title, :string
+ preference :text_color, :string
+ preference :background_color, :string
+
+ def icon_name
+ 'quote'
+ end
+
+ def display_name
+ text.to_plain_text.truncate(30)
+ end
+ end
+ end
+end
+```
+
+### Step 2: Register the Block
+
+```ruby config/initializers/spree.rb
+Rails.application.config.after_initialize do
+ Spree.page_builder.page_blocks += [
+ Spree::PageBlocks::Quote
+ ]
+end
+```
+
+### Step 3: Add to Section's Available Blocks
+
+In your section model, add the new block type:
+
+```ruby
+def available_blocks_to_add
+ [
+ Spree::PageBlocks::Heading,
+ Spree::PageBlocks::Text,
+ Spree::PageBlocks::Quote # Your new block
+ ]
+end
+```
+
+### Step 4: Create Admin Form
+
+```erb app/views/spree/admin/page_blocks/forms/_quote.html.erb
+<div class="form-group">
+ <%= f.label :text, Spree.t(:quote_text) %>
+ <%= f.rich_text_area :text, data: { action: 'auto-submit#submit' } %>
+</div>
+
+<div class="form-group">
+ <%= f.label :preferred_author_name, Spree.t(:author_name) %>
+ <%= f.text_field :preferred_author_name,
+ class: 'form-control',
+ data: { action: 'auto-submit#submit' } %>
+</div>
+
+<div class="form-group">
+ <%= f.label :preferred_author_title, Spree.t(:author_title) %>
+ <%= f.text_field :preferred_author_title,
+ class: 'form-control',
+ data: { action: 'auto-submit#submit' } %>
+</div>
+```
+
+### Step 5: Render in Section View
+
+Add rendering logic to your section's storefront view:
+
+```erb
+<% when 'Spree::PageBlocks::Quote' %>
+ <blockquote <%= block_attributes(block) %> class="text-<%= block.preferred_text_alignment %>">
+ <p class="text-xl italic"><%= block.text %></p>
+ <% if block.preferred_author_name.present? %>
+ <footer class="mt-4">
+ <cite>
+ <strong><%= block.preferred_author_name %></strong>
+ <% if block.preferred_author_title.present? %>
+ <br><span class="text-sm text-gray-500"><%= block.preferred_author_title %></span>
+ <% end %>
+ </cite>
+ </footer>
+ <% end %>
+ </blockquote>
+```
+
+## Block with Links
+
+To add link support to your block, include the `Spree::HasOneLink` concern:
+
+```ruby
+module Spree
+ module PageBlocks
+ class CallToAction < Spree::PageBlock
+ include Spree::HasOneLink
+
+ preference :button_style, :string, default: 'primary'
+
+ # Called when the link is destroyed
+ def link_destroyed(_link)
+ destroy if page_links_count.zero?
+ end
+ end
+ end
+end
+```
+
+## Block with Image
+
+Blocks automatically have an `asset` attachment available:
+
+```ruby
+# Check if image is attached
+block.asset.attached?
+
+# Display image in view
+<% if block.asset.attached? %>
+ <%= spree_image_tag block.asset, width: 400, height: 300 %>
+<% end %>
+```
+
+## Key Methods
+
+| Method | Description |
+|--------|-------------|
+| `display_name` | Name shown in Page Builder sidebar |
+| `icon_name` | Icon from [Tabler Icons](https://tabler.io/icons) |
+| `form_partial_name` | Name of the admin form partial |
+
+## Related Documentation
+
+- [Sections](/developer/storefront/sections) - Parent containers for blocks
+- [Links](/developer/storefront/links) - Adding links to blocks
+- [Images & Assets](/developer/core-concepts/images-assets) - Working with images
diff --git a/docs/developer/storefront/custom-css.mdx b/docs/developer/storefront/custom-css.mdx
index e63b18b2d4..640feaef22 100644
--- a/docs/developer/storefront/custom-css.mdx
+++ b/docs/developer/storefront/custom-css.mdx
@@ -1,23 +1,46 @@
---
title: "Custom CSS for Spree Storefront"
sidebarTitle: "Custom CSS"
-description: "Learn how to add custom CSS stylesheets of your Spree storefront"
+description: "Learn how to add custom CSS stylesheets to your Spree storefront"
---
-Spree Storefront is built on top of Tailwind CSS. After installing Spree you should find 2 new files:
+Spree Storefront is built on top of [Tailwind CSS 4](https://tailwindcss.com/). After installing Spree you should find a main CSS file:
-* [app/assets/stylesheets/application.tailwind.css](https://github.com/spree/spree_starter/blob/main/app/assets/stylesheets/application.tailwind.css) - This is the main CSS file that includes all the Tailwind CSS classes and adds bare-bones styles to the storefront
-* [config/tailwind.config.js](https://github.com/spree/spree_starter/blob/main/config/tailwind.config.js) - This is the Tailwind CSS configuration (we recommend not changing this file, to allow for easier upgrades)
+* [app/assets/tailwind/application.css](https://github.com/spree/spree/blob/main/storefront/lib/generators/spree/storefront/install/templates/application.css) - This is the main CSS file that imports Tailwind and adds storefront styles
-You can add or modify styles to the storefront by adding new Tailwind classes to the `application.tailwind.css` but we recommend creating a new CSS file in the `app/assets/stylesheets` directory and then importing it in the `application.tailwind.css` file, eg.
+If you're missing this file, or migrating from a previous version of Spree, you can generate it using the following command:
-## Importing an additional CSS file
+```bash
+bin/rails g spree:storefront:install
+```
+
+<Info>
+ Tailwind 4 uses a CSS-first configuration approach. There's no `tailwind.config.js` file - all configuration is done directly in CSS using the `@theme` directive.
+</Info>
+
+## Basic Structure
+
+Your [application.css](https://github.com/spree/spree/blob/main/storefront/lib/generators/spree/storefront/install/templates/application.css) file should look something like this:
+
+```css app/assets/tailwind/application.css
+@import "tailwindcss";
+
+@theme {
+ /* Theme customizations go here */
+}
+
+/* Your custom styles */
+```
+
+## Importing Additional CSS Files
+
+Create a new CSS file in the `app/assets/stylesheets` directory:
```bash
-touch app/assets/stylesheets/my_custom_styles.css
+touch app/assets/tailwind/my_custom_styles.css
```
-in the `my_custom_styles.css` file, add the following:
+In the `my_custom_styles.css` file, add your styles:
```css
.my-custom-class {
@@ -25,27 +48,29 @@ in the `my_custom_styles.css` file, add the following:
}
```
-and on top of the `application.tailwind.css` file, add the following:
+Then import it in your `application.css` file:
-```css
-@import "my_custom_styles.css";
+```css app/assets/tailwind/application.css
+@import "tailwindcss";
+@import "my_custom_styles.css"; /* [!code ++] */
```
-## Importing a 3rd party CSS library
+## Importing 3rd Party CSS Libraries
-You can import a 3rd party CSS library directly from a CDN in the `application.tailwind.css` file, eg.
+You can import a 3rd party CSS library directly from a CDN:
-```css
-@import url("https://esm.sh/[email protected]/swiper-bundle.min.css");
+```css app/assets/tailwind/application.css
+@import "tailwindcss";
+@import url("https://esm.sh/[email protected]/swiper-bundle.min.css"); /* [!code ++] */
```
## CSS Variables
-Spree Storefront uses a handful of CSS variables that are automatically injected into the body tag. This allows customers to change colors, fonts, etc from the admin dashboard (via page builder).
+Spree Storefront uses CSS variables that are automatically injected into the page. This allows store owners to change colors, fonts, etc. from the admin dashboard via Page Builder.
-The default variables should be something like this:
+The default variables look like this:
-```css
+```css app/assets/tailwind/application.css
:root {
--primary: #000000;
--accent: #F0EFE9;
@@ -60,7 +85,6 @@ The default variables should be something like this:
--border-default-width: 1px;
--border-default-radius: 6px;
- /* --border-default-shadow: 0px 4px 5px rgba(0, 0, 0, 0); */
--button: #000000;
--button-rgb: 0, 0, 0;
--button-text: #ffffff;
@@ -97,3 +121,142 @@ The default variables should be something like this:
```
They are defined in the [app/views/themes/default/spree/shared/_css_variables.html.erb](https://github.com/spree/spree/blob/main/storefront/app/views/themes/default/spree/shared/_css_variables.html.erb) file which should be present in your theme.
+
+## Customizing with @theme
+
+Tailwind 4 uses the `@theme` directive for customizations. You can extend or override the default theme:
+
+```css app/assets/tailwind/application.css
+@import "tailwindcss";
+
+@theme {
+ /* Add custom colors using Spree's CSS variables */
+ --color-primary: var(--primary);
+ --color-accent: var(--accent);
+ --color-danger: var(--danger);
+ --color-success: var(--success);
+
+ /* Add custom fonts */
+ --font-display: "Playfair Display", serif;
+
+ /* Add custom spacing */
+ --spacing-18: 4.5rem;
+
+ /* Add custom border radius */
+ --radius-button: var(--button-border-radius);
+}
+```
+
+Then use them in your templates:
+
+```erb
+<div class="bg-primary text-white font-display p-18 rounded-button">
+ Custom styled content
+</div>
+```
+
+## Overriding Section Styles
+
+Each section has CSS classes you can target to customize its appearance:
+
+```css
+/* Section container classes follow the pattern: section-{section-type} */
+.section-image-with-text {
+ /* Custom styles for Image with Text section */
+}
+
+.section-featured-taxon {
+ /* Custom styles for Featured Taxon section */
+}
+
+/* Block-specific styles within sections */
+.image-with-text--heading {
+ font-family: serif;
+}
+
+.rich-text--text {
+ line-height: 1.8;
+}
+```
+
+## Using Tailwind Utility Classes
+
+You can use Tailwind utility classes directly in your templates:
+
+```erb
+<div class="flex items-center gap-4 p-6 bg-accent rounded-lg">
+ <%= product.name %>
+</div>
+```
+
+### Arbitrary Values
+
+Tailwind 4 supports arbitrary values for one-off customizations:
+
+```erb
+<div class="p-[17px] bg-[#1a1a1a] text-[13px] grid-cols-[1fr_2fr]">
+ Custom values
+</div>
+```
+
+### Variant Modifiers
+
+Use variant modifiers for responsive and state-based styles:
+
+```erb
+<div class="p-4 md:p-6 lg:p-8 hover:bg-accent active:scale-95">
+ Responsive and interactive
+</div>
+```
+
+## Adding Custom Utilities
+
+You can add custom utilities using standard CSS with the `@utility` directive:
+
+```css
+@import "tailwindcss";
+
+@utility content-auto {
+ content-visibility: auto;
+}
+
+@utility scrollbar-hidden {
+ scrollbar-width: none;
+ &::-webkit-scrollbar {
+ display: none;
+ }
+}
+```
+
+Then use them like any other utility:
+
+```erb
+<div class="content-auto scrollbar-hidden">
+ <!-- Content -->
+</div>
+```
+
+## Adding Custom Variants
+
+Create custom variants with the `@variant` directive:
+
+```css
+@import "tailwindcss";
+
+@variant pointer-coarse (@media (pointer: coarse));
+@variant theme-dark (&:where([data-theme="dark"], [data-theme="dark"] *));
+```
+
+Use them in your templates:
+
+```erb
+<button class="p-2 pointer-coarse:p-4 theme-dark:bg-gray-800">
+ Touch-friendly button
+</button>
+```
+
+## Related Documentation
+
+- [Themes](/developer/storefront/themes) - Theme settings and colors
+- [Custom JavaScript](/developer/storefront/custom-javascript) - Adding interactivity
+- [Tailwind CSS 4 Documentation](https://tailwindcss.com/docs) - Official Tailwind docs
diff --git a/docs/developer/storefront/custom-javascript.mdx b/docs/developer/storefront/custom-javascript.mdx
index e04a6656f3..96e878e834 100644
--- a/docs/developer/storefront/custom-javascript.mdx
+++ b/docs/developer/storefront/custom-javascript.mdx
@@ -94,18 +94,76 @@ If you need to add a small piece of JavaScript code (eg. tracking, marketing, an
1. Declaring a new head partial in the `config/initializers/spree.rb` file, eg.
- ```ruby
- Rails.application.config.spree_storefront.head_partials << 'spree/shared/my_tracking_code'
- ```
+ <Tabs>
+ <Tab title="Spree 5.2+">
+ ```ruby config/initializers/spree.rb
+ Spree.storefront.partials.head << 'spree/shared/my_tracking_code'
+ ```
+ </Tab>
+ <Tab title="Spree 5.1 and below">
+ ```ruby config/initializers/spree.rb
+ Rails.application.config.spree_storefront.head_partials << 'spree/shared/my_tracking_code'
+ ```
+ </Tab>
+ </Tabs>
2. Creating a new file in the `app/views/spree/shared/my_tracking_code.html.erb`, where you can add your tracking code, eg.
- ```erb
+ ```erb app/views/spree/shared/my_tracking_code.html.erb
<script>
console.log("I'm a spy!");
</script>
```
<Info>
-With Spree 5.1 we're going to release a new integrations feature which will allow you to easily connect your storefront to third party services, eg. Google Analytics, Facebook Pixel, etc.
-</Info>
\ No newline at end of file
+ Check out the [Integrations](/integrations) for existing integrations you can plug into your storefront.
+</Info>
+
+## Extending Existing Stimulus Controllers
+
+You can extend or override existing Storefront Stimulus controllers:
+
+```js
+// app/javascript/controllers/cart_controller.js
+import CartController from 'spree/storefront/controllers/cart_controller'
+
+export default class extends CartController {
+ connect() {
+ super.connect()
+ console.log('Extended cart controller connected!')
+ }
+
+ // Override existing method
+ addItem(event) {
+ // Custom logic before adding
+ console.log('Adding item...')
+ super.addItem(event)
+ // Custom logic after adding
+ }
+}
+```
+
+## Turbo Events
+
+Spree Storefront uses [Turbo](https://turbo.hotwired.dev/) for navigation. You can hook into Turbo events:
+
+```js
+// app/javascript/application.js
+document.addEventListener('turbo:load', () => {
+ console.log('Page loaded via Turbo')
+})
+
+document.addEventListener('turbo:before-visit', (event) => {
+ console.log('About to visit:', event.detail.url)
+})
+
+document.addEventListener('turbo:frame-load', (event) => {
+ console.log('Turbo frame loaded:', event.target.id)
+})
+```
+
+## Related Documentation
+
+- [Custom CSS](/developer/storefront/custom-css) - Styling your storefront
+- [Sections](/developer/storefront/sections) - Creating custom sections
+- [Blocks](/developer/storefront/blocks) - Creating custom blocks
\ No newline at end of file
diff --git a/docs/developer/storefront/helper-methods.mdx b/docs/developer/storefront/helper-methods.mdx
index f8af65e868..da7e988739 100644
--- a/docs/developer/storefront/helper-methods.mdx
+++ b/docs/developer/storefront/helper-methods.mdx
@@ -8,13 +8,63 @@ import SpreeOrder from '/snippets/objects/spree_order.mdx'
import SpreeStore from '/snippets/objects/spree_store.mdx'
import SpreeUser from '/snippets/objects/spree_user.mdx'
-Here you can find a list of helper methods provided by Spree that are available in the Storefront that you can use in every template.
+Here you can find a list of helper methods provided by Spree that are available in the Storefront. These methods can be used in every template.
-<Warning>
-The list is incomplete. We're working on it!
-</Warning>
+## Context Helpers
-## `current_currency`
+### `current_store`
+
+<ResponseField name="current_store" type="Spree::Store" description="The current store object.">
+ <SpreeStore />
+</ResponseField>
+
+Returns the current store [Spree::Store](https://github.com/spree/spree/blob/master/core/app/models/spree/store.rb) instance.
+
+### `current_theme`
+
+<ResponseField name="current_theme" type="Spree::Theme" description="The current theme object.">
+ <SpreeTheme />
+</ResponseField>
+
+Returns the current theme [Spree::Theme](https://github.com/spree/spree/blob/master/core/app/models/spree/theme.rb) instance.
+
+### `current_page`
+
+Returns the current [Spree::Page](https://github.com/spree/spree/blob/main/core/app/models/spree/page.rb) instance for the current route.
+
+```erb
+<%= current_page.name %>
+```
+
+### `current_order`
+
+<ResponseField name="current_order" type="Spree::Order" description="The current order object.">
+ <SpreeOrder />
+</ResponseField>
+
+Returns the current order object. If no order is found, it will return `nil`.
+
+<Tip>
+ Order is automatically created when a user adds a product to the cart.
+</Tip>
+
+### `try_spree_current_user`
+
+<ResponseField name="try_spree_current_user" type="Spree.user_class" description="The current user object.">
+ <SpreeUser />
+</ResponseField>
+
+Returns the current user object (class depends on the `Spree.user_class` configuration). If the user is not signed in, it will return `nil`.
+
+<Tip>
+ If you want to check if the user is signed in, you can use the following:
+
+ ```erb
+ <%= try_spree_current_user.present? %>
+ ```
+</Tip>
+
+### `current_currency`
Returns the currently selected currency. By default in the Storefront this will be `store.default_currency`. This can be changed in the `Settings -> Store Defaults` page.
@@ -28,7 +78,7 @@ will return
USD
```
-## `current_locale`
+### `current_locale`
Returns the currently selected locale. By default in the Storefront this will be `store.default_locale`. This can be changed in the `Settings -> Store Defaults` page. If there are multiple locales available, it will return the locale that is currently selected by the user.
@@ -40,45 +90,110 @@ Returns the currently selected locale. By default in the Storefront this will be
Locale also affects the storefront URLs. For example, if the default locale is `en` and the user selects `fr`, the URL will be `/fr/products/123`.
</Info>
-## `current_order`
+### `current_taxon`
-<ResponseField name="current_order" type="Spree::Order" description="The current order object.">
- <SpreeOrder />
-</ResponseField>
+Returns the current taxon when viewing a category/collection page.
-Returns the current order object. If no order is found, it will return `nil`.
+```erb
+<%= current_taxon&.name %>
+```
-<Tip>
- Order is automatically created when a user adds a product to the cart.
-</Tip>
+### `current_wishlist`
-## `current_store`
+Returns the current user's default wishlist for the current store.
-<ResponseField name="current_store" type="Spree::Store" description="The current store object.">
- <SpreeStore />
-</ResponseField>
+```erb
+<% if current_wishlist.present? %>
+ <%= current_wishlist.wished_items.count %> items
+<% end %>
+```
-Returns the current store [Spree::Store](https://github.com/spree/spree/blob/master/core/app/models/spree/store.rb) instance.
+## Page Rendering Helpers
-## `current_theme`
+### `render_page`
-<ResponseField name="current_theme" type="Spree::Theme" description="The current theme object.">
- <SpreeTheme />
-</ResponseField>
+Renders a page with all its sections. This is the main method for rendering page content.
-Returns the current theme [Spree::Theme](https://github.com/spree/spree/blob/master/core/app/models/spree/theme.rb) instance.
+```erb
+<%= render_page(current_page, pickup_locations: @pickup_locations) %>
+```
-## `local_time`
+**Parameters:**
+- `page` - The page to render (defaults to `current_page`)
+- `variables` - Hash of variables to pass to section templates
-Displays a time in the user's timezone in a human readable format (based on the browser's timezone).
+### `render_section`
+
+Renders a single section.
```erb
-<%= local_time(order.sent_to_erp_at) %>
+<%= render_section(section, product: @product) %>
```
-Provided by [local_time gem](https://github.com/basecamp/local_time).
+### `render_header_sections`
-## `supported_currencies`
+Renders all header sections (announcement bar, header).
+
+```erb
+<%= render_header_sections %>
+```
+
+### `render_footer_sections`
+
+Renders all footer sections (newsletter, footer).
+
+```erb
+<%= render_footer_sections %>
+```
+
+## Section & Block Helpers
+
+### `section_styles`
+
+Returns inline CSS styles for a section based on its preferences (padding, colors, borders).
+
+```erb
+<div style="<%= section_styles(section) %>">
+ <!-- Section content -->
+</div>
+```
+
+### `block_attributes`
+
+Returns data attributes for a block (used for Page Builder editing).
+
+```erb
+<h2 <%= block_attributes(block) %>>
+ <%= block.text %>
+</h2>
+```
+
+### `page_builder_enabled?`
+
+Returns `true` when the page is being viewed in Page Builder preview mode.
+
+```erb
+<% cache_unless page_builder_enabled?, cache_key do %>
+ <!-- Cached content -->
+<% end %>
+```
+
+### `page_builder_link_to`
+
+Renders a link from a `Spree::PageLink` object.
+
+```erb
+<%= page_builder_link_to section.link, class: 'btn-primary' %>
+
+<%# With custom content %>
+<%= page_builder_link_to section.link do %>
+ <span class="icon">→</span> Click here
+<% end %>
+```
+
+## Currency & Price Helpers
+
+### `supported_currencies`
Returns the list of supported currencies for the current store as an array of strings.
@@ -92,18 +207,129 @@ will return
["USD", "EUR"]
```
-## `try_spree_current_user`
+### `display_price`
-<ResponseField name="try_spree_current_user" type="Spree.user_class" description="The current user object.">
- <SpreeUser />
-</ResponseField>
+Displays a formatted price with currency symbol.
-Returns the current user object (class depends on the `Spree.admin_user_class` configuration). If the user is not signed in, it will return `nil`.
+```erb
+<%= display_price(product.price_in(current_currency)) %>
+```
-<Tip>
- If you want to check if the user is signed in, you can use the following:
+## Date & Time Helpers
- ```erb
- <%= try_spree_current_user.present? %>
- ```
-</Tip>
\ No newline at end of file
+### `local_time`
+
+Displays a time in the user's timezone in a human readable format (based on the browser's timezone).
+
+```erb
+<%= local_time(order.sent_to_erp_at) %>
+```
+
+Provided by [local_time gem](https://github.com/basecamp/local_time).
+
+## URL Helpers
+
+### `spree_storefront_resource_url`
+
+Generates a URL for a Spree resource (product, taxon, post, page).
+
+```erb
+<%= link_to product.name, spree_storefront_resource_url(product) %>
+<%= link_to taxon.name, spree_storefront_resource_url(taxon) %>
+```
+
+### `spree.nested_taxons_path`
+
+Generates a URL for a taxon using its full permalink.
+
+```erb
+<%= link_to taxon.name, spree.nested_taxons_path(taxon) %>
+<%# => /t/categories/clothing/shirts %>
+```
+
+## Image Helpers
+
+### `spree_image_tag`
+
+Renders an optimized image tag with automatic WebP conversion and retina support.
+
+```erb
+<%= spree_image_tag product.images.first,
+ width: 400,
+ height: 400,
+ alt: product.name,
+ loading: :lazy %>
+```
+
+### `spree_image_url`
+
+Generates a URL for an image with specified dimensions.
+
+```erb
+<%= spree_image_url(product.images.first, width: 800, height: 600) %>
+```
+
+<Info>
+ See [Images & Assets](/developer/core-concepts/images-assets) for more details on image helpers.
+</Info>
+
+## Product Helpers
+
+### `taxon_products`
+
+Returns products for a given taxon, useful in section templates.
+
+```erb
+<% taxon_products(section.taxon).limit(4).each do |product| %>
+ <%= render 'spree/products/card', product: product %>
+<% end %>
+```
+
+### `storefront_products`
+
+Returns products based on current filters and sorting.
+
+```erb
+<% storefront_products.each do |product| %>
+ <%= render 'spree/products/card', product: product %>
+<% end %>
+```
+
+## Cache Helpers
+
+### `spree_storefront_base_cache_key`
+
+Returns the base cache key for storefront caching.
+
+```erb
+<% cache [spree_storefront_base_cache_key, product] do %>
+ <%= render 'product_card', product: product %>
+<% end %>
+```
+
+### `spree_storefront_base_cache_scope`
+
+Returns a cache scope proc for section caching.
+
+```erb
+<% cache_unless page_builder_enabled?, spree_storefront_base_cache_scope.call(section) do %>
+ <!-- Section content -->
+<% end %>
+```
+
+## Preview Helpers
+
+These helpers are used for Page Builder preview functionality:
+
+| Helper | Description |
+|--------|-------------|
+| `current_theme_preview` | Returns the theme preview if in preview mode |
+| `current_page_preview` | Returns the page preview if in preview mode |
+| `current_theme_or_preview` | Returns theme preview or active theme |
+| `current_page_or_preview` | Returns page preview or active page |
+
+## Related Documentation
+
+- [Sections](/developer/storefront/sections) - Section rendering and customization
+- [Blocks](/developer/storefront/blocks) - Block rendering
+- [Images & Assets](/developer/core-concepts/images-assets) - Image helper methods
diff --git a/docs/developer/storefront/images.mdx b/docs/developer/storefront/images.mdx
deleted file mode 100644
index a9e0707dc0..0000000000
--- a/docs/developer/storefront/images.mdx
+++ /dev/null
@@ -1,88 +0,0 @@
----
-title: Images & Assets in Spree Storefront
-sidebarTitle: "Images & Assets"
----
-
-<Info>
-You need to be on Spree 5.0.1 or higher to use these helpers. If you're on 5.0.0 please run `bundle update spree` to update your Spree version.
-</Info>
-
-Spree comes with a handful of helper methods to make it easier to work with images and assets.
-
-## Helpers
-
-Spree provides several helper methods for working with images in your storefront. These methods are defined in `Spree::ImagesHelper` and are available in your views.
-
-### `spree_image_tag`
-
-This helper generates an image with specified width and height. It automatically scales the width and height by 2x to look great on retina screens. The output will be always in WebP format for great performance.
-
-``` erb
-<%= spree_image_tag(
- product.image,
- width: 100,
- height: 100,
- loading: :lazy,
- class: 'w-full group-hover:opacity-0 transition-opacity duration-500 z-10 relative h-full bg-background product-card !max-h-full object-cover object-center',
- title: 'Product Image',
- alt: 'Product Image')
-%>
-```
-
-this will generate HTML image element with the following attributes:
-
-```html
-<img
- width="100"
- height="100"
- loading="lazy"
- class="w-full group-hover:opacity-0 transition-opacity duration-500 z-10 relative h-full bg-background product-card !max-h-full object-cover object-center"
- src="https://yourspreestore.com/rails/active_storage/representations/proxy/eyJfcmFpbHMiOnsiZGF0YSI6MjEwNywicHVyIjoiYmxvYl9pZCJ9fQ==--61de214902195c6ad6cf382ef777b1ab737c9eea/eyJfcmFpbHMiOnsiZGF0YSI6eyJmb3JtYXQiOiJ3ZWJwIiwic2F2ZXIiOnsic3RyaXAiOnRydWUsInF1YWxpdHkiOjc1LCJsb3NzbGVzcyI6ZmFsc2UsImFscGhhX3EiOjg1LCJyZWR1Y3Rpb25fZWZmb3J0Ijo2LCJzbWFydF9zdWJzYW1wbGUiOnRydWV9LCJyZXNpemVfdG9fZmlsbCI6WzYwMCw2MDBdfSwicHVyIjoidmFyaWF0aW9uIn19--34a1e32c85a20d458ee056019da3ed415a92106e/Photo-8.png">
-```
-
-If both width and height are not provided, the helper will keep the image original aspect ratio. If necessary, will crop the image in the larger dimension.
-
-If only one of the width or height is provided, the helper will be resized only by the provided dimension.
-
-You can pass additional options same as with standard Rails `image_tag` helper.
-
-The first argument needs to be a either ActiveStorage attachment (eg. `taxon.image`) or a [Spree::Asset](https://github.com/spree/spree/blob/main/core/app/models/spree/asset.rb) object.
-
-Under the hood this helper uses `spree_image_url` to generate the image URL.
-
-### `spree_image_url`
-
-This helper generates a URL for a Spree image. It automatically scales the width and height by 2x to look great on retina screens. The output will be always in WebP format for great performance.
-
-```erb
-<%= spree_image_url(product.image, width: 100, height: 100) %>
-```
-
-This will generate a URL for the image with the specified width and height.
-
-```http
-https://yourspreestore.com/rails/active_storage/representations/proxy/eyJfcmFpbHMiOnsiZGF0YSI6MjEwNywicHVyIjoiYmxvYl9pZCJ9fQ==--61de214902195c6ad6cf382ef777b1ab737c9eea/eyJfcmFpbHMiOnsiZGF0YSI6eyJmb3JtYXQiOiJ3ZWJwIiwic2F2ZXIiOnsic3RyaXAiOnRydWUsInF1YWxpdHkiOjc1LCJsb3NzbGVzcyI6ZmFsc2UsImFscGhhX3EiOjg1LCJyZWR1Y3Rpb25fZWZmb3J0Ijo2LCJzbWFydF9zdWJzYW1wbGUiOnRydWV9LCJyZXNpemVfdG9fZmlsbCI6WzYwMCw2MDBdfSwicHVyIjoidmFyaWF0aW9uIn19--34a1e32c85a20d458ee056019da3ed415a92106e/Photo-8.png
-```
-
-If both width and height are not provided, the helper will keep the image original aspect ratio. If necessary, will crop the image in the larger dimension.
-
-<Info>
-URLs generated by this helper are always static and can be easily cached by [CDNs](/developer/deployment/cdn). You shouldn't use this helper method for private assets!
-</Info>
-
-### `spree_asset_aspect_ratio`
-
-This helper returns the aspect ratio of an image or video. It can be used in CSS to maintain the correct aspect ratio of an image.
-
-```erb
-<%= spree_asset_aspect_ratio(product.image) %>
-```
-
-This will return the aspect ratio of the image as a float.
-
-```ruby
-1.5
-```
-
-It can auto-detect if the asset is a portrait or landscape image and return the correct aspect ratio.
-If both width and height are equal, it will return `1`.
\ No newline at end of file
diff --git a/docs/developer/storefront/links.mdx b/docs/developer/storefront/links.mdx
index 409c4c3122..c2bb8e7c88 100644
--- a/docs/developer/storefront/links.mdx
+++ b/docs/developer/storefront/links.mdx
@@ -1,8 +1,298 @@
---
title: "Links"
sidebarTitle: "Links"
+description: "Learn how to use links for navigation in your Spree Storefront"
---
-<Warning>Documentation on links is coming soon</Warning>
+Links are used to create navigation throughout the storefront. They can be assigned to [sections](/developer/storefront/sections) and [blocks](/developer/storefront/blocks), enabling users to navigate to different pages, products, categories, or external URLs.
-Links are used to create the navigation of the storefront. They can be assigned to Sections and Blocks.
+## How Links Work
+
+The `Spree::PageLink` model provides a flexible way to link to various content types:
+
+- **Internal pages** - Link to Pages, Products, Taxons, Posts
+- **External URLs** - Link to any external website
+- **Special links** - Email (`mailto:`) and phone (`tel:`) links
+
+Links are managed through the Page Builder interface, where store staff can select what each link points to.
+
+## Link Model
+
+The [Spree::PageLink](https://github.com/spree/spree/blob/main/core/app/models/spree/page_link.rb) model has these key attributes:
+
+| Attribute | Type | Description |
+|-----------|------|-------------|
+| `label` | String | Display text for the link |
+| `url` | String | Custom URL (for external links) |
+| `linkable` | Polymorphic | Reference to internal content (Page, Product, etc.) |
+| `parent` | Polymorphic | Section or Block the link belongs to |
+| `open_in_new_tab` | Boolean | Whether to open in new browser tab |
+| `position` | Integer | Order when multiple links exist |
+
+## Linkable Types
+
+Links can point to various Spree models:
+
+| Linkable Type | Description |
+|---------------|-------------|
+| `Spree::Page` | Internal pages (Home, Shop All, Custom pages) |
+| `Spree::Product` | Product detail pages |
+| `Spree::Taxon` | Category/collection pages |
+| `Spree::Post` | Blog posts |
+| Custom URL | Any external or internal URL |
+
+## Using Links in Sections
+
+### Single Link
+
+For sections that need one link (like a banner):
+
+```ruby app/models/spree/page_sections/promo_banner.rb
+module Spree
+ module PageSections
+ class PromoBanner < Spree::PageSection
+ has_one :link, ->(ps) { ps.links },
+ class_name: 'Spree::PageLink',
+ as: :parent,
+ dependent: :destroy,
+ inverse_of: :parent
+ accepts_nested_attributes_for :link
+
+ def default_links
+ @default_links.presence || [
+ Spree::PageLink.new(label: Spree.t(:shop_now))
+ ]
+ end
+ end
+ end
+end
+```
+
+### Multiple Links
+
+For sections that need multiple links (like navigation):
+
+```ruby app/models/spree/page_sections/footer.rb
+module Spree
+ module PageSections
+ class Footer < Spree::PageSection
+ # Links are provided by Spree::HasPageLinks concern
+ # which is included in Spree::PageSection by default
+
+ def default_links
+ @default_links.presence || [
+ Spree::PageLink.new(label: 'About Us'),
+ Spree::PageLink.new(label: 'Contact'),
+ Spree::PageLink.new(label: 'Privacy Policy')
+ ]
+ end
+ end
+ end
+end
+```
+
+## Using Links in Blocks
+
+Blocks can also have links. Use the `Spree::HasOneLink` concern for single links:
+
+```ruby app/models/spree/page_blocks/cta_button.rb
+module Spree
+ module PageBlocks
+ class CtaButton < Spree::PageBlock
+ include Spree::HasOneLink
+
+ preference :button_style, :string, default: 'primary'
+
+ # Called when the link is deleted
+ def link_destroyed(_link)
+ destroy if page_links_count.zero?
+ end
+ end
+ end
+end
+```
+
+## Accessing Links
+
+```ruby
+# Single link on a section
+section.link
+section.link.label
+section.link.linkable_url
+
+# Multiple links on a section
+section.links
+section.links.each do |link|
+ link.label
+ link.linkable_url
+end
+
+# Link on a block
+block.link
+block.link.label if block.link.present?
+```
+
+## Rendering Links
+
+### Using the Helper
+
+The `page_builder_link_to` helper renders links with Page Builder support:
+
+```erb
+<%# Basic usage %>
+<%= page_builder_link_to section.link %>
+
+<%# With custom label %>
+<%= page_builder_link_to section.link, label: 'Click Here' %>
+
+<%# With CSS class %>
+<%= page_builder_link_to section.link, class: 'btn-primary' %>
+
+<%# Open in new tab %>
+<%= page_builder_link_to section.link,
+ target: (section.link.open_in_new_tab ? '_blank' : nil),
+ rel: (section.link.open_in_new_tab ? 'noopener noreferrer' : nil) %>
+
+<%# With block content %>
+<%= page_builder_link_to section.link do %>
+ <span class="icon">→</span>
+ <%= section.link.label %>
+<% end %>
+```
+
+### Manual Link Rendering
+
+For more control, you can render links manually:
+
+```erb
+<% if section.link.present? %>
+ <%= link_to section.link.linkable_url,
+ target: (section.link.open_in_new_tab ? '_blank' : nil),
+ rel: (section.link.open_in_new_tab ? 'noopener noreferrer' : nil),
+ class: 'btn-primary' do %>
+ <%= section.link.label %>
+ <% end %>
+<% end %>
+```
+
+### Rendering Multiple Links
+
+```erb
+<nav class="footer-links">
+ <% section.links.each do |link| %>
+ <%= page_builder_link_to link, class: 'footer-link' %>
+ <% end %>
+</nav>
+```
+
+## Admin Form for Links
+
+In your section's admin form, render the link editor:
+
+### Single Link
+
+```erb app/views/spree/admin/page_sections/forms/_promo_banner.html.erb
+<%= render 'spree/admin/shared/page_section_image', f: f %>
+
+<div class="py-2">
+ <%= f.fields_for :link do |lf| %>
+ <div class="form-group">
+ <%= lf.label :linkable_type, Spree.t(:link) %>
+ <%= lf.select :linkable_type,
+ @page_section.allowed_linkable_types,
+ { include_blank: false },
+ { class: 'custom-select mb-3', data: { action: 'auto-submit#submit' } } %>
+
+ <div id="linkable_type_dropdown">
+ <%= render 'spree/admin/page_links/linkable_type_dropdown',
+ page_link: lf.object,
+ form_name: 'page_section[link_attributes]' %>
+ </div>
+ </div>
+
+ <div class="custom-control custom-checkbox">
+ <%= lf.check_box :open_in_new_tab,
+ class: 'custom-control-input',
+ data: { action: 'auto-submit#submit' } %>
+ <%= lf.label :open_in_new_tab, class: 'custom-control-label' %>
+ </div>
+ <% end %>
+</div>
+```
+
+## Link URL Resolution
+
+The `linkable_url` method returns the appropriate URL:
+
+```ruby
+link = Spree::PageLink.new(linkable: product)
+link.linkable_url
+# => "/products/red-shirt"
+
+link = Spree::PageLink.new(url: "https://example.com")
+link.linkable_url
+# => "https://example.com"
+
+link = Spree::PageLink.new(url: "example.com")
+link.formatted_url
+# => "http://example.com" # Adds protocol automatically
+
+link = Spree::PageLink.new(url: "mailto:[email protected]")
+link.formatted_url
+# => "mailto:[email protected]" # Preserves mailto: protocol
+```
+
+## Creating Links Programmatically
+
+```ruby
+# Link to an internal page
+link = Spree::PageLink.create!(
+ parent: section,
+ label: 'Shop Now',
+ linkable: store.pages.find_by(type: 'Spree::Pages::ShopAll')
+)
+
+# Link to a product
+link = Spree::PageLink.create!(
+ parent: section,
+ label: product.name,
+ linkable: product
+)
+
+# Link to a taxon
+link = Spree::PageLink.create!(
+ parent: section,
+ label: 'New Arrivals',
+ linkable: store.taxons.find_by(name: 'New Arrivals')
+)
+
+# External link
+link = Spree::PageLink.create!(
+ parent: section,
+ label: 'Visit Our Blog',
+ url: 'https://blog.example.com',
+ open_in_new_tab: true
+)
+```
+
+## Automatic Label Setting
+
+When a link's `linkable` is set, the label is automatically populated from the linked resource:
+
+```ruby
+link = Spree::PageLink.new(linkable: product)
+link.valid?
+link.label
+# => "Red T-Shirt" (from product.name)
+```
+
+The label is derived from (in order):
+1. `linkable.title`
+2. `linkable.display_name`
+3. `linkable.name`
+
+## Related Documentation
+
+- [Sections](/developer/storefront/sections) - Adding links to sections
+- [Blocks](/developer/storefront/blocks) - Adding links to blocks
+- [Pages](/developer/storefront/pages) - Understanding internal page linking
diff --git a/docs/developer/storefront/pages.mdx b/docs/developer/storefront/pages.mdx
index d77879c15d..435123ced2 100644
--- a/docs/developer/storefront/pages.mdx
+++ b/docs/developer/storefront/pages.mdx
@@ -105,11 +105,20 @@ end
You will need to register the new page in the `config/initializers/spree.rb` file:
-```ruby
-Rails.application.config.after_initialize do
- Rails.application.config.spree.pages << Spree::Pages::PickupLocations
-end
-```
+<Tabs>
+ <Tab title="Spree 5.2+">
+ ```ruby config/initializers/spree.rb
+ Spree.page_builder.pages << Spree::Pages::PickupLocations
+ ```
+ </Tab>
+ <Tab title="Spree 5.1 and below">
+ ```ruby config/initializers/spree.rb
+ Rails.application.config.after_initialize do
+ Rails.application.config.spree.pages << Spree::Pages::PickupLocations
+ end
+ ```
+ </Tab>
+</Tabs>
Now, the controller:
diff --git a/docs/developer/storefront/sections.mdx b/docs/developer/storefront/sections.mdx
index 1c0759fe57..d9aff0a8c9 100644
--- a/docs/developer/storefront/sections.mdx
+++ b/docs/developer/storefront/sections.mdx
@@ -130,6 +130,455 @@ Each section has set of default [preferences](/developer/customization/model-pre
Particular sections can introduce their own preferences. For example, `Spree::PageSections::ImageWithText` has `desktop_image_alignment` and `vertical_alignment` preferences.
-## Creating a new section
-
-<Warning>Documentation on creating a new section is coming soon</Warning>
\ No newline at end of file
+## Creating a New Section
+
+This guide walks you through creating a custom section for your Spree storefront. We'll create a "Testimonials" section that displays customer reviews.
+
+### Step 1: Create the Model
+
+Create your section model that inherits from `Spree::PageSection`. Place it in `app/models/spree/page_sections/`:
+
+```ruby app/models/spree/page_sections/testimonials.rb
+module Spree
+ module PageSections
+ class Testimonials < Spree::PageSection
+ # Override default padding if needed
+ TOP_PADDING_DEFAULT = 60
+ BOTTOM_PADDING_DEFAULT = 60
+
+ # Define section-specific preferences
+ preference :heading, :string, default: 'What Our Customers Say'
+ preference :heading_size, :string, default: 'large'
+ preference :heading_alignment, :string, default: 'center'
+ preference :max_testimonials, :integer, default: 3
+ preference :show_rating, :boolean, default: true
+
+ # Validation for preferences
+ before_validation :ensure_valid_heading_size
+ before_validation :ensure_valid_alignment
+
+ # Icon displayed in the Page Builder sidebar
+ def icon_name
+ 'quote'
+ end
+
+ # Define default blocks that are created with this section
+ def default_blocks
+ @default_blocks.presence || [
+ Spree::PageBlocks::Heading.new(
+ text: preferred_heading,
+ preferred_text_alignment: preferred_heading_alignment
+ )
+ ]
+ end
+
+ # Which block types can be added to this section
+ def available_blocks_to_add
+ [
+ Spree::PageBlocks::Heading,
+ Spree::PageBlocks::Text
+ ]
+ end
+
+ # Enable block management in admin
+ def blocks_available?
+ true
+ end
+
+ # Allow reordering blocks
+ def can_sort_blocks?
+ true
+ end
+
+ private
+
+ def ensure_valid_heading_size
+ self.preferred_heading_size = 'medium' unless %w[small medium large].include?(preferred_heading_size)
+ end
+
+ def ensure_valid_alignment
+ self.preferred_heading_alignment = 'center' unless %w[left center right].include?(preferred_heading_alignment)
+ end
+ end
+ end
+end
+```
+
+### Step 2: Register the Section
+
+Add your section to `Spree.page_builder.page_sections` in your Spree initializer:
+
+```ruby config/initializers/spree.rb
+Rails.application.config.after_initialize do
+ Spree.page_builder.page_sections += [
+ Spree::PageSections::Testimonials
+ ]
+end
+```
+
+<Info>
+ Sections are filtered by their `role` method. By default, sections have role `'content'` which makes them available in the Page Builder. Sections with role `'header'` or `'footer'` are layout sections.
+</Info>
+
+### Step 3: Create the Admin Form
+
+Create the admin form partial for configuring the section in the Page Builder. Place it in `app/views/spree/admin/page_sections/forms/`:
+
+```erb app/views/spree/admin/page_sections/forms/_testimonials.html.erb
+<div class="form-group">
+ <%= f.label :preferred_heading, Spree.t(:heading) %>
+ <%= f.text_field :preferred_heading,
+ class: 'form-control',
+ data: { action: 'auto-submit#submit' } %>
+</div>
+
+<div class="form-group">
+ <%= f.label :preferred_heading_size, Spree.t(:heading_size) %>
+ <%= f.select :preferred_heading_size,
+ options_for_select([
+ [Spree.t(:small), 'small'],
+ [Spree.t(:medium), 'medium'],
+ [Spree.t(:large), 'large']
+ ], @page_section.preferred_heading_size),
+ {},
+ { class: 'custom-select', data: { action: 'auto-submit#submit' } } %>
+</div>
+
+<div class="form-group">
+ <%= f.label :preferred_heading_alignment, Spree.t(:alignment) %>
+ <%= f.select :preferred_heading_alignment,
+ options_for_select([
+ [Spree.t(:left), 'left'],
+ [Spree.t(:center), 'center'],
+ [Spree.t(:right), 'right']
+ ], @page_section.preferred_heading_alignment),
+ {},
+ { class: 'custom-select', data: { action: 'auto-submit#submit' } } %>
+</div>
+
+<div class="form-group">
+ <%= f.label :preferred_max_testimonials, Spree.t(:max_items) %>
+ <%= f.number_field :preferred_max_testimonials,
+ class: 'form-control',
+ min: 1,
+ max: 10,
+ data: { action: 'auto-submit#submit' } %>
+</div>
+
+<div class="custom-control custom-checkbox mb-3">
+ <%= f.check_box :preferred_show_rating,
+ class: 'custom-control-input',
+ data: { action: 'auto-submit#submit' } %>
+ <%= f.label :preferred_show_rating, Spree.t(:show_rating), class: 'custom-control-label' %>
+</div>
+
+<%# Add design settings to the Design tab %>
+<% content_for(:design_tab) do %>
+ <hr />
+<% end %>
+```
+
+<Info>
+ The `data: { action: 'auto-submit#submit' }` attribute enables live preview in the Page Builder - changes are saved automatically as the user types.
+</Info>
+
+### Step 4: Create the Storefront View
+
+Create the storefront partial that renders the section. Place it in your theme's views directory:
+
+```erb app/views/themes/default/spree/page_sections/_testimonials.html.erb
+<% cache_unless page_builder_enabled?, spree_storefront_base_cache_scope.call(section) do %>
+ <div style="<%= section_styles(section) %>" class="testimonials-section">
+ <div class="page-container">
+ <%# Heading %>
+ <% if section.preferred_heading.present? %>
+ <%
+ heading_class = case section.preferred_heading_size
+ when 'small' then 'text-lg'
+ when 'medium' then 'text-xl lg:text-2xl'
+ when 'large' then 'text-2xl lg:text-3xl'
+ end
+ %>
+ <h2 class="<%= heading_class %> font-medium mb-8 text-<%= section.preferred_heading_alignment %>">
+ <%= section.preferred_heading %>
+ </h2>
+ <% end %>
+
+ <%# Render blocks %>
+ <% section.blocks.includes(:rich_text_text).each do |block| %>
+ <% case block.type %>
+ <% when 'Spree::PageBlocks::Heading' %>
+ <h3 class="text-xl font-medium" <%= block_attributes(block) %>>
+ <%= block.text %>
+ </h3>
+ <% when 'Spree::PageBlocks::Text' %>
+ <div class="prose" <%= block_attributes(block) %>>
+ <%= block.text %>
+ </div>
+ <% end %>
+ <% end %>
+
+ <%# Your custom testimonials content %>
+ <div class="grid grid-cols-1 md:grid-cols-<%= section.preferred_max_testimonials %> gap-6">
+ <%# Add your testimonials rendering logic here %>
+ </div>
+ </div>
+ </div>
+<% end %>
+```
+
+### Section Roles
+
+Sections have different roles that determine where they appear:
+
+| Role | Description | Example |
+|------|-------------|---------|
+| `content` | Available in Page Builder, can be added to any page | Rich Text, Image Banner |
+| `system` | Core page functionality, usually not removable | Product Details, Cart |
+| `header` | Header layout sections | Header, Announcement Bar |
+| `footer` | Footer layout sections | Footer, Newsletter |
+
+To set a section's role, override the `self.role` class method:
+
+```ruby
+def self.role
+ 'content' # default
+end
+```
+
+### Section with Image Upload
+
+If your section needs an image, use the built-in `asset` attachment:
+
+```ruby app/models/spree/page_sections/hero_banner.rb
+module Spree
+ module PageSections
+ class HeroBanner < Spree::PageSection
+ include Spree::HasImageAltText
+
+ preference :image_alt, :string
+
+ def icon_name
+ 'photo'
+ end
+ end
+ end
+end
+```
+
+Admin form with image upload:
+
+```erb app/views/spree/admin/page_sections/forms/_hero_banner.html.erb
+<%= render 'spree/admin/shared/page_section_image', f: f %>
+
+<div class="form-group">
+ <%= f.label :preferred_image_alt, Spree.t(:alt_text) %>
+ <%= f.text_field :preferred_image_alt,
+ class: 'form-control',
+ data: { action: 'auto-submit#submit' } %>
+</div>
+```
+
+Display in storefront:
+
+```erb
+<% if section.asset.attached? %>
+ <%= spree_image_tag section.asset,
+ width: 1200,
+ height: 600,
+ alt: section.image_alt,
+ class: 'w-full object-cover' %>
+<% end %>
+```
+
+### Section with Links
+
+To add clickable links to your section, include the `Spree::HasPageLinks` concern (included by default) and define links:
+
+```ruby
+module Spree
+ module PageSections
+ class PromoBanner < Spree::PageSection
+ has_one :link, ->(ps) { ps.links },
+ class_name: 'Spree::PageLink',
+ as: :parent,
+ dependent: :destroy,
+ inverse_of: :parent
+ accepts_nested_attributes_for :link
+
+ def default_links
+ @default_links.presence || [
+ Spree::PageLink.new(label: Spree.t(:shop_now))
+ ]
+ end
+ end
+ end
+end
+```
+
+### Lazy Loading Sections
+
+For sections that load external data (products, taxons), implement lazy loading to improve page performance:
+
+```ruby
+def lazy?
+ !Rails.env.test?
+end
+
+def lazy_path(variables)
+ url_options = variables[:url_options] || {}
+ Spree::Core::Engine.routes.url_helpers.page_section_path(self, **url_options)
+end
+```
+
+### Helper Methods
+
+These helper methods are available in storefront section views:
+
+| Helper | Description |
+|--------|-------------|
+| `section_styles(section)` | Returns inline CSS for section padding, colors, borders |
+| `block_attributes(block)` | Returns data attributes for Page Builder editing |
+| `page_builder_enabled?` | Returns true when in Page Builder preview mode |
+| `spree_storefront_base_cache_scope` | Cache key scope for the section |
+| `section_heading_styles(section)` | Returns inline CSS for heading text color |
+| `page_builder_link_to(link, **options)` | Renders a link with Page Builder support |
+
+### Adding Translations
+
+Add translations for your section in your locale files:
+
+```yaml config/locales/en.yml
+en:
+ spree:
+ page_sections:
+ testimonials:
+ heading_default: "What Our Customers Say"
+ text_default: "Read reviews from our happy customers"
+```
+
+### Complete Example
+
+Here's a complete example putting it all together - a "Brand Story" section:
+
+<Steps>
+ <Step title="Create the model">
+ ```ruby app/models/spree/page_sections/brand_story.rb
+ module Spree
+ module PageSections
+ class BrandStory < Spree::PageSection
+ include Spree::HasImageAltText
+
+ TOP_PADDING_DEFAULT = 80
+ BOTTOM_PADDING_DEFAULT = 80
+
+ preference :image_position, :string, default: 'left'
+ preference :image_alt, :string
+
+ def icon_name
+ 'building-store'
+ end
+
+ def default_blocks
+ [
+ Spree::PageBlocks::Heading.new(text: 'Our Story'),
+ Spree::PageBlocks::Text.new(text: 'Share your brand story here...')
+ ]
+ end
+
+ def available_blocks_to_add
+ [Spree::PageBlocks::Heading, Spree::PageBlocks::Text, Spree::PageBlocks::Buttons]
+ end
+
+ def blocks_available?
+ true
+ end
+
+ def can_sort_blocks?
+ true
+ end
+ end
+ end
+ end
+ ```
+ </Step>
+
+ <Step title="Register the section">
+ ```ruby config/initializers/spree.rb
+ Rails.application.config.after_initialize do
+ Spree.page_builder.page_sections += [Spree::PageSections::BrandStory]
+ end
+ ```
+ </Step>
+
+ <Step title="Create admin form">
+ ```erb app/views/spree/admin/page_sections/forms/_brand_story.html.erb
+ <%= render 'spree/admin/shared/page_section_image', f: f %>
+
+ <div class="form-group">
+ <%= f.label :preferred_image_alt, Spree.t(:alt_text) %>
+ <%= f.text_field :preferred_image_alt,
+ class: 'form-control',
+ data: { action: 'auto-submit#submit' } %>
+ </div>
+
+ <% content_for(:design_tab) do %>
+ <div class="form-group">
+ <%= f.label :preferred_image_position, Spree.t(:image_position) %>
+ <%= f.select :preferred_image_position,
+ options_for_select([['Left', 'left'], ['Right', 'right']], @page_section.preferred_image_position),
+ {},
+ { class: 'custom-select', data: { action: 'auto-submit#submit' } } %>
+ </div>
+ <hr />
+ <% end %>
+ ```
+ </Step>
+
+ <Step title="Create storefront view">
+ ```erb app/views/themes/default/spree/page_sections/_brand_story.html.erb
+ <% cache_unless page_builder_enabled?, spree_storefront_base_cache_scope.call(section) do %>
+ <div style="<%= section_styles(section) %>" class="brand-story">
+ <div class="page-container">
+ <div class="grid grid-cols-1 lg:grid-cols-2 gap-8 items-center">
+ <% image_order = section.preferred_image_position == 'right' ? 'lg:order-2' : '' %>
+
+ <div class="<%= image_order %>">
+ <% if section.asset.attached? %>
+ <%= spree_image_tag section.asset,
+ width: 600,
+ height: 400,
+ alt: section.image_alt,
+ class: 'w-full rounded-lg' %>
+ <% end %>
+ </div>
+
+ <div>
+ <% section.blocks.each do |block| %>
+ <% case block.type %>
+ <% when 'Spree::PageBlocks::Heading' %>
+ <h2 class="text-2xl lg:text-3xl font-medium mb-4" <%= block_attributes(block) %>>
+ <%= block.text %>
+ </h2>
+ <% when 'Spree::PageBlocks::Text' %>
+ <div class="prose" <%= block_attributes(block) %>>
+ <%= block.text %>
+ </div>
+ <% when 'Spree::PageBlocks::Buttons' %>
+ <div class="mt-6" <%= block_attributes(block) %>>
+ <% if block.link %>
+ <%= page_builder_link_to block.link,
+ class: 'btn-primary',
+ target: (block.link.open_in_new_tab ? '_blank' : nil) %>
+ <% end %>
+ </div>
+ <% end %>
+ <% end %>
+ </div>
+ </div>
+ </div>
+ </div>
+ <% end %>
+ ```
+ </Step>
+</Steps>
\ No newline at end of file
diff --git a/docs/developer/storefront/storefront.mdx b/docs/developer/storefront/storefront.mdx
index 528df763b6..6eb2096cf8 100644
--- a/docs/developer/storefront/storefront.mdx
+++ b/docs/developer/storefront/storefront.mdx
@@ -16,10 +16,10 @@ Spree Storefront consists of:
<Card title="Pages" href="/developer/storefront/pages">
Pages are the main building blocks of the storefront. They are used to create the structure of the storefront. Each Theme comes with a set of default pages such as Home Page, Product Listing Page, Product Page, etc, but you can create your own custom landing pages as well.
</Card>
- <Card title="Sections" href="/developer/storefront/sections-blocks">
+ <Card title="Sections" href="/developer/storefront/sections">
Sections are the building blocks of the pages. They are used to create the structure of the pages. Each Section is a collection of Blocks.
</Card>
- <Card title="Blocks" href="/developer/storefront/sections-blocks#blocks">
+ <Card title="Blocks" href="/developer/storefront/blocks">
Blocks are the smallest building blocks of the storefront. They are used to create the content of the pages.
</Card>
<Card title="Links" href="/developer/storefront/links">
diff --git a/docs/developer/storefront/themes.mdx b/docs/developer/storefront/themes.mdx
index b623348adf..7fc7812b71 100644
--- a/docs/developer/storefront/themes.mdx
+++ b/docs/developer/storefront/themes.mdx
@@ -22,8 +22,8 @@ This command will create a new theme called `my_theme` in the `app/views/themes`
It will also add a line in your `config/initializers/spree.rb` file to load the new theme.
-```ruby
-Rails.application.config.spree.themes << Spree::Themes::MyTheme
+```ruby config/initializers/spree.rb
+Spree.page_builder.themes << Spree::Themes::MyTheme
```
Now you can go to **Admin Dashboard -> Storefront -> Themes**, you should see a new section **Add new theme** with your theme name. Click **Add** button to activate the theme.
diff --git a/docs/developer/tutorial/admin.mdx b/docs/developer/tutorial/admin.mdx
new file mode 100644
index 0000000000..13e9f9e63e
--- /dev/null
+++ b/docs/developer/tutorial/admin.mdx
@@ -0,0 +1,87 @@
+---
+title: Admin Dashboard
+description: Learn how to create Admin Dashboard UI to manage Brands
+---
+
+Now that we've created a complete "Brand" model, let's create an Admin Dashboard interface so our admins can manage the brands.
+
+## Step 1: Create the boilerplate Admin Dashboard UI
+
+Admin Scaffold generator is a tool that helps us create a complete Admin Dashboard UI for our new resource.
+
+Run the following command in our Spree application root directory:
+
+```bash
+bin/rails g spree:admin:scaffold Spree::Brand
+```
+
+This will create the following files:
+
+| File Type | Path | Description |
+|-----------|------|------|
+| Controller | `app/controllers/spree/admin/brands_controller.rb` | Handles the logic for the brands resource. |
+| View | `app/views/spree/admin/brands/index.html.erb` | Handles displaying the list of brands in the Admin Dashboard. |
+| View | `app/views/spree/admin/brands/new.html.erb` | Handles displaying the new brand form in the Admin Dashboard. |
+| View | `app/views/spree/admin/brands/edit.html.erb` | Handles displaying the edit brand form in the Admin Dashboard. |
+| Partial | `app/views/spree/admin/brands/_table_header.html.erb` | Handles displaying the table header in the brands index view. |
+| Partial | `app/views/spree/admin/brands/_table_row.html.erb` | Handles displaying the table row in the brands index view. |
+| Partial | `app/views/spree/admin/brands/_filters.html.erb` | Handles displaying the filters in the brands index view. |
+| Partial | `app/views/spree/admin/brands/_form.html.erb` | Handles displaying the form in the new and edit brand views. |
+
+It will also automatically add the following routes to your `config/routes.rb` file:
+
+```ruby config/routes.rb
+namespace :admin do
+ resources :brands
+end
+```
+
+You will now be able to access the brands resource at `http://localhost:3000/admin/brands` in your browser. To reference this route in your code, you can use the `spree.admin_brands_path` helper.
+
+## Step 2: Add Navigation Menu Item
+
+Now that we've created a complete Admin Dashboard UI for the brand resource, let's add a navigation menu item to the main sidebar so we can access it from the admin dashboard.
+
+Add the following to your `config/initializers/spree.rb` file:
+
+```ruby config/initializers/spree.rb
+Rails.application.config.after_initialize do
+ # Add Brands to the admin sidebar
+ sidebar_nav = Spree.admin.navigation.sidebar
+
+ sidebar_nav.add :brands,
+ label: :brands,
+ url: :admin_brands_path,
+ icon: 'award',
+ position: 35,
+ active: -> { controller_name == 'brands' },
+ if: -> { can?(:manage, Spree::Brand) }
+end
+```
+
+This will add a "Brands" link to the admin sidebar between Products (30) and Customers (40).
+
+### Adding to an Existing Submenu
+
+To add "Brands" to the Products submenu instead add a new submenu item:
+
+```ruby config/initializers/spree.rb
+Rails.application.config.after_initialize do
+ sidebar_nav = Spree.admin.navigation.sidebar
+
+ # Add brands as a child of products
+ sidebar_nav.add :brands,
+ label: :brands,
+ url: :admin_brands_path,
+ position: 50,
+ parent: :products,
+ active: -> { controller_name == 'brands' },
+ if: -> { can?(:manage, Spree::Brand) }
+end
+```
+
+After restarting your server, you'll see the new "Brands" navigation link in the admin sidebar!
+
+<Info>
+For complete navigation API documentation including all available options, submenu creation, badges, and more, see the [Admin Navigation](/developer/admin/navigation) guide.
+</Info>
diff --git a/docs/developer/tutorial/extending-models.mdx b/docs/developer/tutorial/extending-models.mdx
new file mode 100644
index 0000000000..b14f9bbb7c
--- /dev/null
+++ b/docs/developer/tutorial/extending-models.mdx
@@ -0,0 +1,352 @@
+---
+title: Extending Core Models
+description: Learn how to extend Spree's core models to connect Brands with Products
+---
+
+In this tutorial, we'll connect our custom Brand model with Spree's core Product model. This is a common pattern when building features that need to integrate with existing Spree functionality.
+
+<Info>
+ This guide assumes you've completed the [Model](/developer/tutorial/model), [Admin](/developer/tutorial/admin), and [File Uploads](/developer/tutorial/file-uploads) tutorials.
+</Info>
+
+## What We're Building
+
+By the end of this tutorial, you'll have:
+
+- Products associated with Brands
+- A brand selector in the Product admin form
+- Understanding of how to safely extend Spree core models
+
+## Understanding Decorators
+
+When working with Spree, you'll often need to add functionality to existing models like `Spree::Product` or `Spree::Order`. However, you shouldn't modify these files directly because:
+
+1. **Upgrades** - Your changes would be lost when updating Spree
+2. **Maintainability** - It's hard to track what you've customized
+3. **Conflicts** - Direct modifications can conflict with Spree's code
+
+Instead, we use **decorators** - a Ruby pattern that lets you add or modify behavior of existing classes without changing their original source code.
+
+### How Decorators Work
+
+In Ruby, classes are "open" - you can add methods to them at any time. Decorators leverage this by:
+
+1. Creating a module with your new methods
+2. Using `Module#prepend` to inject your module into the class's inheritance chain
+3. Your methods run first, and can call `super` to invoke the original method
+
+```ruby
+# This is the basic pattern
+module Spree
+ module ProductDecorator
+ # Add a new method
+ def my_new_method
+ "Hello from decorator!"
+ end
+
+ # Override an existing method
+ def existing_method
+ # Do something before
+ result = super # Call the original method
+ # Do something after
+ result
+ end
+ end
+
+ Product.prepend(ProductDecorator)
+end
+```
+
+The key line is `Product.prepend(ProductDecorator)` - this inserts your module at the beginning of the method lookup chain, so your methods are found first.
+
+## Step 1: Create the Migration
+
+First, add a `brand_id` column to the products table:
+
+```bash
+bin/rails g migration AddBrandIdToSpreeProducts brand_id:integer:index
+```
+
+Edit the migration to add an index (but no foreign key constraint, keeping it optional):
+
+```ruby db/migrate/XXXXXXXXXXXXXX_add_brand_id_to_spree_products.rb
+class AddBrandIdToSpreeProducts < ActiveRecord::Migration[8.0]
+ def change
+ add_column :spree_products, :brand_id, :integer
+ add_index :spree_products, :brand_id
+ end
+end
+```
+
+Run the migration:
+
+```bash
+bin/rails db:migrate
+```
+
+<Info>
+ We intentionally don't add a foreign key constraint. This keeps the association optional and avoids issues if brands are deleted. Spree follows this pattern for flexibility.
+</Info>
+
+## Step 2: Generate the Product Decorator
+
+Spree provides a generator to create decorator files with the correct structure:
+
+```bash
+bin/rails g spree:model_decorator Spree::Product
+```
+
+This creates `app/models/spree/product_decorator.rb`:
+
+```ruby app/models/spree/product_decorator.rb
+module Spree
+ module ProductDecorator
+ def self.prepended(base)
+ # Class-level configurations go here
+ end
+ end
+
+ Product.prepend(ProductDecorator)
+end
+```
+
+## Step 3: Add the Brand Association to Product
+
+Update the decorator to add the `belongs_to` association:
+
+```ruby app/models/spree/product_decorator.rb {4}
+module Spree
+ module ProductDecorator
+ def self.prepended(base)
+ base.belongs_to :brand, class_name: 'Spree::Brand', optional: true
+ end
+ end
+
+ Product.prepend(ProductDecorator)
+end
+```
+
+### Understanding the Code
+
+- `self.prepended(base)` - This callback runs when the module is prepended to a class. The `base` parameter is the class being decorated (`Spree::Product`)
+- `base.belongs_to` - We call class methods on `base` to add associations, validations, scopes, etc.
+- `optional: true` - Products don't require a brand (the `brand_id` can be `NULL`)
+
+## Step 4: Add Products Association to Brand
+
+Now update your Brand model to define the reverse association:
+
+```ruby app/models/spree/brand.rb {5}
+module Spree
+ class Brand < Spree::Base
+ # ... existing code ...
+
+ has_many :products, class_name: 'Spree::Product', dependent: :nullify
+
+ # ... rest of your model ...
+ end
+end
+```
+
+<Info>
+ We use `dependent: :nullify` instead of `dependent: :destroy`. When a brand is deleted, products will have their `brand_id` set to `NULL` rather than being deleted. This is safer for e-commerce data.
+</Info>
+
+## Step 5: Permit the Brand Parameter
+
+For the admin form to save the brand association, we need to permit the `brand_id` parameter.
+
+Add to your Spree initializer:
+
+```ruby config/initializers/spree.rb {3}
+# .. other code ..
+
+Spree::PermittedAttributes.product_attributes << :brand_id
+```
+
+## Step 6: Add Brand Selector to Product Admin Form
+
+Create a partial to inject the brand selector into the product form. Spree's admin product form has injection points for customization.
+
+Create the partial:
+
+```erb app/views/spree/admin/products/_brand_field.html.erb
+<div class="card mb-4">
+ <div class="card-header">
+ <h5 class="card-title"><%= Spree.t(:brand) %></h5>
+ </div>
+ <div class="card-body">
+ <%= f.spree_select :brand_id,
+ Spree::Brand.order(:name).pluck(:name, :id),
+ { include_blank: true, label: Spree.t(:brand) } %>
+</div>
+```
+
+Register this partial to appear in the product form. Add to your initializer:
+
+<Tabs>
+ <Tab title="Spree 5.2+">
+ ```ruby config/initializers/spree.rb
+ Spree.admin.partials.product_form_sidebar << 'spree/admin/products/brand_field'
+ ```
+ </Tab>
+ <Tab title="Spree 5.1 and below">
+ ```ruby config/initializers/spree.rb
+ Rails.application.config.spree_admin.product_form_sidebar_partials << 'spree/admin/products/brand_field'
+ ```
+ </Tab>
+</Tabs>
+
+## Step 7: Add Translation
+
+Add the translation for the brand label:
+
+```yaml config/locales/en.yml
+en:
+ spree:
+ brand: Brand
+```
+
+## Testing the Association
+
+Verify everything works in the Rails console:
+
+```ruby
+# Create a brand and product
+brand = Spree::Brand.create!(name: 'Nike')
+product = Spree::Product.first
+product.update!(brand: brand)
+
+# Test associations
+product.brand # => #<Spree::Brand id: 1, name: "Nike"...>
+brand.products # => [#<Spree::Product...>]
+brand.products.count # => 1
+```
+
+## Decorator Best Practices
+
+<CardGroup cols={2}>
+ <Card title="Use prepended callback" icon="code">
+ Always use `self.prepended(base)` for class-level additions like associations, validations, and scopes.
+ </Card>
+
+ <Card title="Keep decorators focused" icon="crosshairs">
+ Each decorator should have a single responsibility. Create multiple decorators if needed.
+ </Card>
+
+ <Card title="Call super when overriding" icon="arrow-up">
+ When overriding methods, call `super` to preserve original behavior unless you intentionally want to replace it.
+ </Card>
+
+ <Card title="Test decorated behavior" icon="flask-vial">
+ Write tests specifically for your decorated functionality to catch regressions.
+ </Card>
+</CardGroup>
+
+### Common Decorator Patterns
+
+#### Adding Validations
+
+```ruby
+def self.prepended(base)
+ base.validates :custom_field, presence: true
+end
+```
+
+#### Adding Scopes
+
+```ruby
+def self.prepended(base)
+ base.scope :featured, -> { where(featured: true) }
+end
+```
+
+#### Adding Callbacks
+
+```ruby
+def self.prepended(base)
+ base.before_save :do_something
+end
+
+def do_something
+ # Your callback logic
+end
+```
+
+#### Adding Class Methods
+
+```ruby
+def self.prepended(base)
+ base.extend ClassMethods
+end
+
+module ClassMethods
+ def my_class_method
+ # Class method logic
+ end
+end
+```
+
+## Complete Files
+
+### Product Decorator
+
+```ruby app/models/spree/product_decorator.rb
+module Spree
+ module ProductDecorator
+ def self.prepended(base)
+ base.belongs_to :brand, class_name: 'Spree::Brand', optional: true
+ end
+ end
+
+ Product.prepend(ProductDecorator)
+end
+```
+
+### Brand Model (Updated)
+
+```ruby app/models/spree/brand.rb
+module Spree
+ class Brand < Spree::Base
+ has_many :products, class_name: 'Spree::Product', dependent: :nullify
+
+ has_one_attached :logo
+ has_rich_text :description
+
+ validates :name, presence: true
+ end
+end
+```
+
+<Info>
+ SEO features like slugs, meta titles, and FriendlyId are covered in the [SEO](/developer/tutorial/seo) tutorial.
+</Info>
+
+### Spree Initializer Additions
+
+```ruby config/initializers/spree.rb
+# Permit brand_id in product params
+Spree::PermittedAttributes.product_attributes << :brand_id
+```
+
+<Tabs>
+ <Tab title="Spree 5.2+">
+ ```ruby config/initializers/spree.rb
+ # Add brand field to product form
+ Spree.admin.partials.product_form << 'spree/admin/products/brand_field'
+ ```
+ </Tab>
+ <Tab title="Spree 5.1 and below">
+ ```ruby config/initializers/spree.rb
+ # Add brand field to product form
+ Rails.application.config.spree_admin.product_form_partials << 'spree/admin/products/brand_field'
+ ```
+ </Tab>
+</Tabs>
+
+## Related Documentation
+
+- [Model Tutorial](/developer/tutorial/model) - Creating the Brand model
+- [Admin Tutorial](/developer/tutorial/admin) - Building the admin interface
+- [Customization Overview](/developer/customization/overview) - More customization patterns
+- [Products](/developer/core-concepts/products) - Product model documentation
diff --git a/docs/developer/tutorial/file-uploads.mdx b/docs/developer/tutorial/file-uploads.mdx
new file mode 100644
index 0000000000..31bc37dc54
--- /dev/null
+++ b/docs/developer/tutorial/file-uploads.mdx
@@ -0,0 +1,124 @@
+---
+title: File Uploads
+description: Learn how to add file uploads to the Brands feature
+---
+
+<Info>
+ This guide assumes you've completed the [Model](/developer/tutorial/model), [Admin](/developer/tutorial/admin), and [Rich Text](/developer/tutorial/rich-text) tutorials.
+</Info>
+
+In this tutorial, we'll add a logo image upload to our Brand model. Spree uses [Rails Active Storage](https://guides.rubyonrails.org/active_storage_overview.html) for handling file attachments, image processing, and storage.
+
+## Step 1: Add Attachment to the Model
+
+First, let's add a logo attachment to the Brand model:
+
+```ruby app/models/spree/brand.rb {3}
+module Spree
+ class Brand < Spree::Base
+ has_one_attached :logo
+
+ # ... existing code ...
+ end
+end
+```
+
+## Step 2: Permit the Attachment Attribute
+
+For the admin form to accept the file upload, we need to permit the `logo` attribute in the controller.
+
+Update your brands controller:
+
+```ruby app/controllers/spree/admin/brands_controller.rb {10}
+module Spree
+ module Admin
+ class BrandsController < ResourceController
+ private
+
+ def permitted_resource_params
+ params.require(:brand).permit(
+ :name,
+ :description,
+ :logo
+ )
+ end
+ end
+ end
+end
+```
+
+## Step 3: Add File Upload Field to the Admin Form
+
+Now let's add the file upload field to the brand form. Spree provides a `spree_file_field` helper that handles everything including:
+
+- Drag and drop upload
+- Image preview
+- Direct upload to storage
+- Optional image cropping
+
+Update your brand form partial:
+
+```erb app/views/spree/admin/brands/_form.html.erb {11-19}
+<div class="card mb-4">
+ <div class="card-header">
+ <h5 class="card-title"><%= Spree.t(:general_settings) %></h5>
+ </div>
+ <div class="card-body">
+ <%= f.spree_text_field :name, required: true %>
+ <%= f.spree_rich_text_area :description %>
+ </div>
+</div>
+
+<div class="card mb-4">
+ <div class="card-header">
+ <h5 class="card-title"><%= Spree.t(:logo) %></h5>
+ </div>
+ <div class="card-body">
+ <%= f.spree_file_field :logo, width: 300, height: 300 %>
+ </div>
+</div>
+```
+
+### Add cropping functionality
+
+To enable cropping functionality, add the `crop: true` option to the `spree_file_field` helper.
+
+## Step 4: Display the Logo in the Index Table
+
+Let's show a thumbnail of the brand logo in the admin index view.
+
+Update the table header partial:
+
+```erb app/views/spree/admin/brands/_table_header.html.erb {2}
+<tr>
+ <th><%= Spree.t(:logo) %></th>
+ <th><%= Spree.t(:name) %></th>
+ <th></th>
+</tr>
+```
+
+Update the table row partial to display the logo:
+
+```erb app/views/spree/admin/brands/_table_row.html.erb {3-12}
+<tr id="<%= spree_dom_id brand %>" class="cursor-pointer" data-controller="row-link">
+ <td data-action="click->row-link#openLink" class="w-70">
+ <div class="d-flex align-items-center gap-2">
+ <% if brand.logo.attached? %>
+ <%= spree_image_tag brand.logo, width: 48, height: 48, class: 'rounded' %>
+ <% else %>
+ <div class="bg-light rounded d-flex align-items-center justify-content-center" style="width: 48px; height: 48px;">
+ <%= icon('photo-off', class: 'text-muted') %>
+ </div>
+ <% end %>
+ <span class="font-weight-bold"><%= brand.name %></span>
+ </div>
+ </td>
+ <td data-action="click->row-link#openLink" class="w-20">
+ <%= spree_date(brand.created_at) %>
+ </td>
+ <td class="actions w-10">
+ <%= link_to_edit(brand, data: { row_link_target: :link, turbo_frame: '_top' }) if can? :edit, brand %>
+ </td>
+</tr>
+```
+
diff --git a/docs/developer/tutorial/introduction.mdx b/docs/developer/tutorial/introduction.mdx
new file mode 100644
index 0000000000..b7a21ca16a
--- /dev/null
+++ b/docs/developer/tutorial/introduction.mdx
@@ -0,0 +1,48 @@
+---
+title: Tutorial
+sidebarTitle: Introduction
+description: Learn how to build a custom feature from scratch, covering models, Admin dashboard, API and Storefront.
+---
+
+This tutorial walks you through creating a complete Spree feature from scratch, covering models, Admin dashboard, API and Storefront.
+You will also learn how to extend core Spree features to connect them with your new feature.
+By the end, you'll understand how to add new manageable features to the Spree platform.
+
+## Overview
+
+Spree is built on top of [Ruby on Rails framework](https://rubyonrails.org) and follows Model-View-Controller (MVC) architecture. To fully implement a new feature, you will typically create the following components:
+
+* Database model
+* Admin Dashboard controllers and views
+* Storefront views
+* Automated tests
+
+## Tutorial Sections
+
+<CardGroup cols={2}>
+ <Card title="1. Model" icon="database" href="/developer/tutorial/model">
+ Create the Brand model with migrations, validations, and associations
+ </Card>
+ <Card title="2. Admin Dashboard" icon="gauge" href="/developer/tutorial/admin">
+ Build admin interface for managing brands
+ </Card>
+ <Card title="3. Rich Text" icon="align-left" href="/developer/tutorial/rich-text">
+ Add rich text descriptions using Action Text
+ </Card>
+ <Card title="4. File Uploads" icon="image" href="/developer/tutorial/file-uploads">
+ Add logo images with Active Storage
+ </Card>
+ <Card title="5. Extending Core Models" icon="plug" href="/developer/tutorial/extending-models">
+ Connect Brands to Products using decorators
+ </Card>
+ <Card title="6. Storefront" icon="store" href="/developer/tutorial/storefront">
+ Create customer-facing brand pages
+ </Card>
+ <Card title="7. Testing" icon="flask-vial" href="/developer/tutorial/testing">
+ Write automated tests for your feature
+ </Card>
+</CardGroup>
+
+## Example: Building a Brands Feature
+
+In this guide we will create a complete "Brands" feature that allows admins to manage [Product](/developer/core-concepts/products) brands.
\ No newline at end of file
diff --git a/docs/developer/tutorial/model.mdx b/docs/developer/tutorial/model.mdx
new file mode 100644
index 0000000000..e9f3198eba
--- /dev/null
+++ b/docs/developer/tutorial/model.mdx
@@ -0,0 +1,41 @@
+---
+title: Model
+description: Learn how to create a database model for the Brands feature
+---
+
+## Step 1: Create the Model and Database Migration
+
+To create a new model and database migration file, run the following command:
+
+```bash
+bin/rails g spree:model Spree::Brand name:string:index
+```
+
+This will create a couple of files:
+- `app/models/spree/brand.rb` - the model file
+- `db/migrate/XXXXXXXXXXXXXX_create_spree_brands.rb` - the database migration file
+
+Now run the migration:
+
+```bash
+bin/rails db:migrate
+```
+
+This will create the table `spree_brands` with the column `name` in the database. The `name` column is indexed for faster lookups. Also the model file `app/models/spree/brand.rb` is created.
+
+## Step 2: Extend the Model file
+
+Now that the model file is created, let's add some additional functionality to it, starting with validations:
+
+```ruby app/models/spree/brand.rb {3-4}
+module Spree
+ class Brand < Spree::Base
+ # Validations
+ validates :name, presence: true
+ end
+end
+```
+
+This is a standard [Ruby on Rails ActiveRecord model](https://guides.rubyonrails.org/active_record_basics.html). Let's break down each part:
+- Inherits from `Spree::Base` to automatically inherit all Spree functionality. Also the model itself is namespaced under `Spree::` module, so it's available as `Spree::Brand` in the application.
+- `validates :name, presence: true` - using ActiveRecord validations to ensure that the name is present.
diff --git a/docs/developer/tutorial/page-builder.mdx b/docs/developer/tutorial/page-builder.mdx
new file mode 100644
index 0000000000..77869b73e6
--- /dev/null
+++ b/docs/developer/tutorial/page-builder.mdx
@@ -0,0 +1,489 @@
+---
+title: Page Builder Integration
+description: Learn how to connect your Brands feature to Page Builder for admin-manageable pages
+---
+
+In this tutorial, we'll enhance our brand pages by integrating them with Spree's Page Builder. This allows store administrators to customize page layouts, add sections, and modify designs without touching code.
+
+<Info>
+ This guide assumes you've completed the [Storefront](/developer/tutorial/storefront) tutorial and have working brand pages.
+</Info>
+
+## What We're Building
+
+By the end of this tutorial, you'll have:
+
+- A **Brand List** page type manageable via Page Builder
+- A **Brand** page type for individual brand pages
+- Custom sections: `BrandGrid` and `BrandBanner`
+- Full admin customization support
+
+## Understanding Page Builder Architecture
+
+Page Builder uses three main components:
+
+| Component | Purpose |
+|-----------|---------|
+| **Page** | Defines the page type (e.g., Homepage, Product Details, Brand List) |
+| **Section** | Reusable content blocks within a page (e.g., Hero Banner, Product Grid) |
+| **Block** | Smallest units within sections (e.g., Heading, Text, Button) |
+
+## Step 1: Create Page Types
+
+### Brand List Page
+
+Create a page type for the brands listing:
+
+```ruby app/models/spree/pages/brand_list.rb
+module Spree
+ module Pages
+ class BrandList < Spree::Page
+ def icon_name
+ 'building-store'
+ end
+
+ def customizable?
+ true
+ end
+
+ def page_builder_url
+ return unless page_builder_url_exists?(:brands_path)
+
+ Spree::Core::Engine.routes.url_helpers.brands_path
+ end
+
+ def default_sections
+ [
+ Spree::PageSections::PageTitle.new(
+ preferred_heading: Spree.t(:brands)
+ ),
+ Spree::PageSections::BrandGrid.new
+ ]
+ end
+ end
+ end
+end
+```
+
+### Brand Page
+
+Create a page type for individual brand pages:
+
+```ruby app/models/spree/pages/brand.rb
+module Spree
+ module Pages
+ class Brand < Spree::Page
+ def icon_name
+ 'tag'
+ end
+
+ def customizable?
+ true
+ end
+
+ def page_builder_url
+ return unless page_builder_url_exists?(:brands_path)
+
+ brand = Spree::Brand.first
+ return unless brand
+
+ Spree::Core::Engine.routes.url_helpers.brand_path(brand)
+ end
+
+ def default_sections
+ [
+ Spree::PageSections::BrandBanner.new,
+ Spree::PageSections::ProductGrid.new(
+ preferred_heading: Spree.t(:products)
+ )
+ ]
+ end
+ end
+ end
+end
+```
+
+## Step 2: Register Pages
+
+Add your pages to the Spree configuration:
+
+```ruby config/initializers/spree.rb
+Rails.application.config.after_initialize do
+ # Register custom pages
+ Spree.page_builder.pages += [
+ Spree::Pages::BrandList,
+ Spree::Pages::Brand
+ ]
+end
+```
+
+## Step 3: Create Custom Sections
+
+### Brand Grid Section
+
+This section displays a grid of all brands:
+
+```ruby app/models/spree/page_sections/brand_grid.rb
+module Spree
+ module PageSections
+ class BrandGrid < Spree::PageSection
+ TOP_PADDING_DEFAULT = 40
+ BOTTOM_PADDING_DEFAULT = 40
+
+ preference :show_description, :boolean, default: false
+
+ def icon_name
+ 'layout-grid'
+ end
+
+ # Content sections can be added/removed in Page Builder
+ def self.role
+ 'content'
+ end
+
+ def brands
+ Spree::Brand.order(:name)
+ end
+ end
+ end
+end
+```
+
+### Brand Banner Section
+
+This section displays the brand header with logo and description:
+
+```ruby app/models/spree/page_sections/brand_banner.rb
+module Spree
+ module PageSections
+ class BrandBanner < Spree::PageSection
+ TOP_PADDING_DEFAULT = 60
+ BOTTOM_PADDING_DEFAULT = 40
+
+ preference :show_logo, :boolean, default: true
+ preference :show_description, :boolean, default: true
+ preference :layout, :string, default: 'horizontal'
+
+ before_validation :ensure_valid_layout
+
+ def icon_name
+ 'id-badge'
+ end
+
+ # System sections are part of the core page functionality
+ def self.role
+ 'system'
+ end
+
+ def can_be_deleted?
+ false
+ end
+
+ private
+
+ def ensure_valid_layout
+ self.preferred_layout = 'horizontal' unless %w[horizontal vertical].include?(preferred_layout)
+ end
+ end
+ end
+end
+```
+
+## Step 4: Register Sections
+
+Add your sections to the configuration:
+
+```ruby config/initializers/spree.rb
+Rails.application.config.after_initialize do
+ # Register custom pages
+ Spree.page_builder.pages += [
+ Spree::Pages::BrandList,
+ Spree::Pages::Brand
+ ]
+
+ # Register custom sections
+ Spree.page_builder.page_sections += [
+ Spree::PageSections::BrandGrid,
+ Spree::PageSections::BrandBanner
+ ]
+end
+```
+
+## Step 5: Create Admin Forms
+
+Admin section forms use Spree's Admin Form Builder, which provides helper methods like `spree_select` and `spree_check_box` for consistent styling and functionality.
+
+### Brand Grid Admin Form
+
+```erb app/views/spree/admin/page_sections/forms/_brand_grid.html.erb
+<%= f.spree_check_box :preferred_show_description,
+ label: Spree.t(:show_description),
+ data: { action: 'auto-submit#submit' } %>
+```
+
+### Brand Banner Admin Form
+
+```erb app/views/spree/admin/page_sections/forms/_brand_banner.html.erb
+<%= f.spree_check_box :preferred_show_logo,
+ label: Spree.t(:show_logo),
+ data: { action: 'auto-submit#submit' } %>
+
+<%= f.spree_check_box :preferred_show_description,
+ label: Spree.t(:show_description),
+ data: { action: 'auto-submit#submit' } %>
+
+<% content_for(:design_tab) do %>
+ <%= f.spree_select :preferred_layout,
+ options_for_select([
+ [Spree.t(:horizontal), 'horizontal'],
+ [Spree.t(:vertical), 'vertical']
+ ], @page_section.preferred_layout),
+ { label: Spree.t(:layout) },
+ { data: { action: 'auto-submit#submit' } } %>
+ <hr />
+<% end %>
+```
+
+## Step 6: Create Storefront Views
+
+### Brand Grid Section View
+
+```erb app/views/themes/default/spree/page_sections/_brand_grid.html.erb
+<% cache_unless page_builder_enabled?, spree_storefront_base_cache_scope.call(section) do %>
+ <div style="<%= section_styles(section) %>">
+ <div class="page-container">
+ <% brands = section.brands %>
+ <% if brands.any? %>
+ <div class="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-6">
+ <% brands.each do |brand| %>
+ <%= link_to spree.brand_path(brand),
+ class: 'block group',
+ data: { turbo_frame: '_top' } do %>
+ <div class="aspect-square bg-accent rounded-lg overflow-hidden mb-3">
+ <% if brand.logo.attached? %>
+ <%= spree_image_tag brand.logo,
+ width: 300,
+ height: 300,
+ class: 'w-full h-full object-contain p-6 group-hover:scale-105 transition-transform',
+ alt: brand.name %>
+ <% else %>
+ <div class="w-full h-full flex items-center justify-center">
+ <span class="text-4xl font-medium text-neutral-400">
+ <%= brand.name.first.upcase %>
+ </span>
+ </div>
+ <% end %>
+ </div>
+ <h3 class="font-medium group-hover:text-primary transition-colors">
+ <%= brand.name %>
+ </h3>
+ <% if section.preferred_show_description && brand.description.present? %>
+ <p class="mt-1 text-sm text-neutral-600 line-clamp-2">
+ <%= brand.description.to_plain_text.truncate(100) %>
+ </p>
+ <% end %>
+ <% end %>
+ <% end %>
+ </div>
+ <% else %>
+ <p class="text-neutral-600"><%= Spree.t(:no_brands_found) %></p>
+ <% end %>
+ </div>
+ </div>
+<% end %>
+```
+
+### Brand Banner Section View
+
+```erb app/views/themes/default/spree/page_sections/_brand_banner.html.erb
+<% cache_unless page_builder_enabled?, spree_storefront_base_cache_scope.call(section) do %>
+ <div style="<%= section_styles(section) %>">
+ <div class="page-container">
+ <% if brand.present? %>
+ <div class="<%= section.preferred_layout == 'horizontal' ? 'flex flex-col md:flex-row gap-8 items-start' : 'text-center' %>">
+ <% if section.preferred_show_logo && brand.logo.attached? %>
+ <div class="<%= section.preferred_layout == 'horizontal' ? 'w-32 h-32 flex-shrink-0' : 'w-40 h-40 mx-auto mb-6' %> bg-accent rounded-lg">
+ <%= spree_image_tag brand.logo,
+ width: 160,
+ height: 160,
+ class: 'w-full h-full object-contain p-4',
+ alt: brand.name %>
+ </div>
+ <% end %>
+
+ <div>
+ <h1 class="text-2xl lg:text-3xl font-medium mb-4">
+ <%= brand.name %>
+ </h1>
+
+ <% if section.preferred_show_description && brand.description.present? %>
+ <div class="prose max-w-none text-neutral-600">
+ <%= brand.description %>
+ </div>
+ <% end %>
+ </div>
+ </div>
+ <% end %>
+ </div>
+ </div>
+<% end %>
+```
+
+## Step 7: Update the Controller
+
+Update your controller to use Page Builder pages:
+
+```ruby app/controllers/spree/brands_controller.rb
+module Spree
+ class BrandsController < StoreController
+ before_action :load_brand, only: [:show]
+
+ def index
+ # Load the Page Builder page
+ @current_page = current_theme.pages.find_by(type: 'Spree::Pages::BrandList')
+
+ # Fallback data if sections need it
+ @brands = Spree::Brand.order(:name)
+ end
+
+ def show
+ # Load the Page Builder page
+ @current_page = current_theme.pages.find_by(type: 'Spree::Pages::Brand')
+
+ # Load products for the ProductGrid section
+ @products = @brand.products
+ .active(current_currency)
+ .includes(storefront_products_includes)
+ .page(params[:page])
+ .per(12)
+ end
+
+ private
+
+ def load_brand
+ @brand = Spree::Brand.find(params[:id])
+ end
+
+ def accurate_title
+ if @brand
+ @brand.meta_title.presence || @brand.name
+ else
+ Spree.t(:brands)
+ end
+ end
+ end
+end
+```
+
+## Step 8: Update Views to Use Page Builder
+
+### Brand List Index View
+
+```erb app/views/themes/default/spree/brands/index.html.erb
+<%= render_page(@current_page, brands: @brands) %>
+```
+
+### Brand Show View
+
+```erb app/views/themes/default/spree/brands/show.html.erb
+<%= render_page(@current_page, brand: @brand, products: @products) %>
+```
+
+The `render_page` helper automatically renders all sections in the order defined in Page Builder.
+
+## Step 9: Passing Variables to Sections
+
+Section views receive variables passed to `render_page`. Update your section views to use them:
+
+```erb app/views/themes/default/spree/page_sections/_brand_banner.html.erb
+<% # 'brand' variable is passed from the controller via render_page %>
+<% cache_unless page_builder_enabled?, [spree_storefront_base_cache_scope.call(section), brand] do %>
+ <div style="<%= section_styles(section) %>">
+ <%# ... use 'brand' variable ... %>
+ </div>
+<% end %>
+```
+
+## Step 10: Add Translations
+
+```yaml config/locales/en.yml
+en:
+ spree:
+ brands: Brands
+ no_brands_found: No brands found.
+ products_by_brand: "Products by %{brand}"
+ show_description: Show description
+ show_logo: Show logo
+ layout: Layout
+ horizontal: Horizontal
+ vertical: Vertical
+```
+
+## Testing Page Builder Integration
+
+1. Start your Rails server
+2. Go to **Admin → Storefront → Pages**
+3. You should see "Brand List" and "Brand" pages
+4. Click on a page to customize it in Page Builder
+5. Add, remove, or reorder sections
+6. Customize section settings
+7. Preview changes in real-time
+
+## Section Roles Explained
+
+| Role | Description | Can Delete? | Example |
+|------|-------------|-------------|---------|
+| `content` | General content sections | Yes | BrandGrid, ImageBanner |
+| `system` | Core page functionality | No | BrandBanner, ProductDetails |
+| `header` | Layout header sections | No | Header, AnnouncementBar |
+| `footer` | Layout footer sections | No | Footer, Newsletter |
+
+## Complete File Structure
+
+After completing this tutorial, you should have:
+
+```
+app/
+├── controllers/spree/
+│ └── brands_controller.rb
+├── models/spree/
+│ ├── pages/
+│ │ ├── brand.rb
+│ │ └── brand_list.rb
+│ └── page_sections/
+│ ├── brand_banner.rb
+│ └── brand_grid.rb
+└── views/
+ ├── spree/admin/page_sections/forms/
+ │ ├── _brand_banner.html.erb
+ │ └── _brand_grid.html.erb
+ └── themes/default/spree/
+ ├── brands/
+ │ ├── index.html.erb
+ │ └── show.html.erb
+ └── page_sections/
+ ├── _brand_banner.html.erb
+ └── _brand_grid.html.erb
+
+config/
+├── initializers/
+│ └── spree.rb (updated)
+└── locales/
+ └── en.yml (updated)
+```
+
+## Benefits of Page Builder Integration
+
+| Without Page Builder | With Page Builder |
+|---------------------|-------------------|
+| Developers edit views for layout changes | Admins customize layouts in browser |
+| Code deployment required for design changes | Real-time preview and publish |
+| Fixed page structure | Drag-and-drop section ordering |
+| Hardcoded settings | Admin-configurable preferences |
+
+## Related Documentation
+
+- [Sections](/developer/storefront/sections) - Creating custom sections
+- [Blocks](/developer/storefront/blocks) - Adding blocks to sections
+- [Pages](/developer/storefront/pages) - Page types and routing
+- [Themes](/developer/storefront/themes) - Theme customization
diff --git a/docs/developer/tutorial/rich-text.mdx b/docs/developer/tutorial/rich-text.mdx
new file mode 100644
index 0000000000..f57acabbbf
--- /dev/null
+++ b/docs/developer/tutorial/rich-text.mdx
@@ -0,0 +1,75 @@
+---
+title: Rich Text
+description: Learn how to add rich text content to the Brands feature using Action Text
+---
+
+<Info>
+ This guide assumes you've completed the [Model](/developer/tutorial/model) and [Admin](/developer/tutorial/admin) tutorials.
+</Info>
+
+Our Brand model has a `name` attribute to store the brand name. However it's missing a description. That's because we're going to use [Action Text](https://guides.rubyonrails.org/action_text_overview.html) to handle the rich text content.
+
+## Step 1: Add Action Text to the Model
+
+```ruby app/models/spree/brand.rb {4-5}
+module Spree
+ class Brand < Spree::Base
+ # Action text for rich text content
+ has_rich_text :description
+
+ # ... other code ...
+ end
+end
+```
+
+You don't need to run any migrations, as we won't be adding any new columns to the `spree_brands` table. That's because [Action Text](https://guides.rubyonrails.org/action_text_overview.html) stores all the rich text content in a separate table called `action_text_rich_texts`.
+
+You can access the description content in code like this:
+
+```ruby
+brand.description.to_s
+# => "<h1>Hello</h1><p>World</p>"
+```
+
+Or if you prefer plain text:
+
+```ruby
+brand.description.to_plain_text
+# => "Hello World"
+```
+
+## Step 2: Add a WYSIWYG editor to the Admin Dashboard
+
+In the Admin dashboard we want to use a WYSIWYG editor to add formatted text to the brand description. To do this, edit the `app/views/spree/admin/brands/_form.html.erb` file and add the following code:
+
+```erb app/views/spree/admin/brands/_form.html.erb {4}
+<div class="card mb-4">
+ <div class="card-body">
+ <%= f.spree_text_field :name %>
+ <%= f.spree_rich_text_area :description %>
+ </div>
+</div>
+```
+
+This will render a WYSIWYG editor to the brand description field in the Admin dashboard.
+
+## Step 3: Update permitted parameters in controller
+
+To permit the `description` attribute to be saved, we need to update the permitted parameters in the controller. file and add the following code:
+
+```ruby app/controllers/spree/admin/brands_controller.rb {9}
+module Spree
+ module Admin
+ class BrandsController < ResourceController
+ private
+
+ def permitted_resource_params
+ params.require(:brand).permit(
+ :name,
+ :description
+ )
+ end
+ end
+ end
+end
+```
\ No newline at end of file
diff --git a/docs/developer/tutorial/seo.mdx b/docs/developer/tutorial/seo.mdx
new file mode 100644
index 0000000000..20f6f9b2b3
--- /dev/null
+++ b/docs/developer/tutorial/seo.mdx
@@ -0,0 +1,344 @@
+---
+title: SEO
+description: Learn how to optimize your Brands feature for search engines
+---
+
+<Info>
+ This guide assumes you've completed the [Storefront](/developer/tutorial/storefront) tutorial. You should have working brand pages.
+</Info>
+
+This guide covers SEO best practices for your custom Spree features, including friendly URLs, meta tags, and Open Graph data.
+
+## SEO-Friendly URLs
+
+Rather than using database IDs in URLs:
+
+```
+https://example.com/brands/1
+```
+
+Create human-readable URLs that help with SEO:
+
+```
+https://example.com/brands/nike-sportswear
+```
+
+### Step 1: Add SEO Columns
+
+Add columns for slug and meta fields:
+
+```bash
+bin/rails g migration AddSeoFieldsToSpreeBrands slug:string:uniq meta_title:string meta_description:text
+```
+
+```bash
+bin/rails db:migrate
+```
+
+This adds:
+- `slug` - SEO-friendly URL with unique index
+- `meta_title` - Custom page title for search engines
+- `meta_description` - Description shown in search results
+
+### Step 2: Add FriendlyId to the Model
+
+Add FriendlyId to generate SEO-friendly URLs automatically:
+
+```ruby app/models/spree/brand.rb {3-4,9}
+module Spree
+ class Brand < Spree::Base
+ extend FriendlyId
+ friendly_id :slug_candidates, use: %i[slugged]
+
+ # ... other code ...
+
+ validates :name, presence: true
+ validates :slug, presence: true, uniqueness: { scope: spree_base_uniqueness_scope }
+ end
+end
+```
+
+The `slug_candidates` method is already defined in `Spree::Base`:
+
+```ruby
+def slug_candidates
+ [
+ :name,
+ [:name, :uuid_for_friendly_id]
+ ]
+end
+```
+
+This generates the slug from the name. If the name is taken, it appends a UUID.
+
+### Step 3: Add SEO Fields to Admin
+
+Spree provides a reusable SEO partial that handles slug, meta title, and meta description with a live search preview. Update your admin form:
+
+```erb app/views/spree/admin/brands/_form.html.erb {1-2,5-12,15,25-32}
+<div class="row" data-controller="slug-form seo-form">
+ <div class="col-lg-8">
+ <div class="card mb-4">
+ <div class="card-body">
+ <%= f.spree_text_field :name,
+ required: true,
+ data: {
+ seo_form_target: 'sourceTitleInput',
+ slug_form_target: 'name',
+ action: 'slug-form#updateUrlFromName'
+ } %>
+ <%= f.spree_rich_text_area :description,
+ data: { seo_form_target: 'sourceDescriptionInput' } %>
+ </div>
+ </div>
+ </div>
+
+ <div class="col-lg-4">
+ <div class="card mb-4">
+ <div class="card-header">
+ <h5 class="card-title"><%= Spree.t(:logo) %></h5>
+ </div>
+ <div class="card-body">
+ <%= f.spree_file_field :logo, width: 300, height: 300, crop: true %>
+ </div>
+ </div>
+
+ <%= render 'spree/admin/shared/seo',
+ f: f,
+ title: @brand.name,
+ meta_title: @brand.meta_title,
+ description: @brand.description,
+ slug: @brand.slug,
+ slug_path: 'brands',
+ placeholder: 'Add a name and description to see how this brand might appear in a search engine listing' %>
+ </div>
+</div>
+```
+
+The SEO partial provides:
+- **Live preview** of how the page will appear in search results
+- **Meta title** field with character count
+- **Meta description** field
+- **Slug** field with auto-generation from name
+
+The `seo-form` Stimulus controller syncs the preview with your form inputs in real-time.
+
+Don't forget to permit the SEO attributes in your controller:
+
+```ruby app/controllers/spree/admin/brands_controller.rb {6-8}
+def permitted_resource_params
+ params.require(:brand).permit(
+ :name,
+ :description,
+ :logo,
+ :slug,
+ :meta_title,
+ :meta_description)
+end
+```
+
+### Step 4: Use Slugs in Storefront
+
+Update your controller to use `friendly.find`:
+
+```ruby app/controllers/spree/brands_controller.rb
+def load_brand
+ @brand = Spree::Brand.friendly.find(params[:id])
+end
+```
+
+The `friendly.find` method:
+- Finds by slug first (e.g., `/brands/nike-sportswear`)
+- Falls back to ID if no slug matches
+- Raises `ActiveRecord::RecordNotFound` if neither is found
+
+### URL Helpers
+
+Always pass the model object to path helpers:
+
+```erb
+<%= link_to brand.name, spree.brand_path(brand) %>
+<%# => /brands/nike-sportswear %>
+```
+
+FriendlyId overrides `to_param` to return the slug automatically.
+
+### Handling Slug Changes
+
+To redirect old URLs when slugs change, enable slug history:
+
+```ruby app/models/spree/brand.rb
+extend FriendlyId
+friendly_id :slug_candidates, use: %i[slugged history]
+```
+
+Old slugs will automatically resolve to the current slug.
+
+## Meta Tags & Open Graph
+
+Spree automatically generates meta tags and Open Graph data. The system uses a helper called `object` that finds the main instance variable based on your controller name.
+
+For `BrandsController`, Spree looks for `@brand` and generates:
+- Meta description
+- Open Graph tags (og:title, og:description, og:image)
+- Twitter Card tags
+
+### Page Title
+
+Override `accurate_title` in your controller to set the page `<title>`:
+
+```ruby app/controllers/spree/brands_controller.rb
+private
+
+def accurate_title
+ if @brand
+ @brand.meta_title.presence || @brand.name
+ else
+ Spree.t(:brands)
+ end
+end
+```
+
+### Meta Description
+
+Spree checks these sources in order:
+
+1. `@page_description` instance variable (if set)
+2. `@brand.meta_description` (if the model has this attribute)
+3. `current_store.meta_description` (fallback)
+
+#### Using the SEO Partial
+
+If you followed [Step 1](#step-1-add-seo-columns) and [Step 3](#step-3-add-seo-fields-to-admin), your model already has `meta_description` and the admin form uses the SEO partial. Spree will automatically use `@brand.meta_description` for the page description.
+
+#### Manual Override
+
+For custom logic, set `@page_description` directly:
+
+```ruby
+def show
+ @page_description = "Shop #{@brand.name} - #{@brand.products.count} products available"
+end
+```
+
+### Social Sharing Image
+
+For Open Graph images, Spree checks:
+
+1. `@page_image` instance variable (if set)
+2. `@brand.image` (if the model responds to `image`)
+3. `current_store.social_image` (fallback)
+
+If your Brand model has `logo` but not `image`, add an alias:
+
+```ruby app/models/spree/brand.rb
+def image
+ logo
+end
+```
+
+Or set it manually:
+
+```ruby
+def show
+ @page_image = @brand.logo if @brand.logo.attached?
+end
+```
+
+## Complete SEO-Optimized Model
+
+Here's a complete Brand model with full SEO support:
+
+```ruby app/models/spree/brand.rb
+module Spree
+ class Brand < Spree::Base
+ extend FriendlyId
+ friendly_id :slug_candidates, use: %i[slugged]
+
+ has_many :products, class_name: 'Spree::Product', dependent: :nullify
+
+ has_one_attached :logo
+ has_rich_text :description
+
+ # Database columns: slug, meta_title, meta_description
+
+ validates :name, presence: true
+ validates :slug, presence: true, uniqueness: { scope: spree_base_uniqueness_scope }
+
+ # SEO: Use logo as Open Graph image
+ def image
+ logo
+ end
+ end
+end
+```
+
+## Complete SEO-Optimized Controller
+
+```ruby app/controllers/spree/brands_controller.rb
+module Spree
+ class BrandsController < StoreController
+ before_action :load_brand, only: [:show]
+
+ def index
+ @brands = Spree::Brand.order(:name)
+ end
+
+ def show
+ @products = @brand.products
+ .active(current_currency)
+ .includes(storefront_products_includes)
+ .page(params[:page])
+ .per(12)
+
+ # Optional: Custom page description
+ # @page_description = "Shop #{@brand.name} products"
+
+ # Optional: Custom social image
+ # @page_image = @brand.logo if @brand.logo.attached?
+ end
+
+ private
+
+ def load_brand
+ @brand = Spree::Brand.friendly.find(params[:id])
+ end
+
+ def accurate_title
+ if @brand
+ @brand.meta_title.presence || @brand.name
+ else
+ Spree.t(:brands)
+ end
+ end
+ end
+end
+```
+
+## SEO Checklist
+
+<Check>
+ **Friendly URLs** - Use slugs instead of IDs (`/brands/nike` not `/brands/1`)
+</Check>
+
+<Check>
+ **Page Titles** - Override `accurate_title` for descriptive titles
+</Check>
+
+<Check>
+ **Meta Descriptions** - Add `meta_description` field or set `@page_description`
+</Check>
+
+<Check>
+ **Social Images** - Provide `image` method or set `@page_image` for Open Graph
+</Check>
+
+<Check>
+ **Slug History** - Enable FriendlyId history to handle URL changes gracefully
+</Check>
+
+## Related Documentation
+
+- [Storefront Tutorial](/developer/tutorial/storefront) - Building storefront pages
+- [Model Tutorial](/developer/tutorial/model) - Creating the Brand model
+- [Admin Tutorial](/developer/tutorial/admin) - Building the admin interface
diff --git a/docs/developer/tutorial/storefront.mdx b/docs/developer/tutorial/storefront.mdx
new file mode 100644
index 0000000000..160f582502
--- /dev/null
+++ b/docs/developer/tutorial/storefront.mdx
@@ -0,0 +1,366 @@
+---
+title: Storefront
+description: Learn how to create storefront pages for your Brands feature
+---
+
+In this tutorial, we'll create storefront pages to display brands to your customers. We'll start with a simple Rails approach using controllers and views, then in the next guide we'll connect it to Page Builder.
+
+<Info>
+ This guide assumes you've completed the [Model](/developer/tutorial/model), [Admin](/developer/tutorial/admin), [Rich Text](/developer/tutorial/rich-text), [File Uploads](/developer/tutorial/file-uploads), and [Extending Core Models](/developer/tutorial/extending-models) tutorials. You should have a working `Spree::Brand` model with products associated to brands.
+</Info>
+
+## What We're Building
+
+By the end of this tutorial, you'll have:
+
+- A custom theme for your store
+- A brands listing page at `/brands`
+- Individual brand pages at `/brands/:id`
+- Styled views using Tailwind CSS
+
+## Step 1: Create a Custom Theme
+
+Before adding custom views, create your own theme. This is important because:
+
+- **Upgrade safety** - Your customizations won't be overwritten when updating Spree
+- **Clean separation** - Your code stays separate from Spree's default theme
+- **Full control** - You get a complete copy of all templates to customize
+
+Run the theme generator:
+
+```bash
+bin/rails g spree:storefront:theme MyStore
+```
+
+This creates:
+- `app/views/themes/my_store/` - Copy of all storefront templates
+- `app/models/spree/themes/my_store.rb` - Theme configuration class
+
+The generator also updates your `config/initializers/spree.rb`:
+
+```ruby config/initializers/spree.rb
+Spree.page_builder.themes << Spree::Themes::MyStore
+```
+
+### Activate Your Theme
+
+1. Go to **Admin → Storefront → Themes**
+2. Find your new theme in the "Add new theme" section
+3. Click **Add** to activate it
+
+<Warning>
+ Always create a custom theme for production stores. Never modify the default theme directly - your changes will be lost during Spree upgrades.
+</Warning>
+
+## Step 2: Add Routes
+
+Now let's add routes for our brand pages. Create or update your routes file:
+
+```ruby config/routes.rb
+Spree::Core::Engine.add_routes do
+ scope '(:locale)', locale: /#{Spree.available_locales.join('|')}/, defaults: { locale: nil } do
+ resources :brands, only: [:index, :show]
+ end
+end
+```
+
+<Info>
+ The `scope '(:locale)'` wrapper enables internationalization - URLs like `/fr/brands` will work automatically if you have French locale enabled.
+</Info>
+
+## Step 3: Create the Controller
+
+Create a controller that inherits from `Spree::StoreController`. This base controller provides:
+
+- Access to `current_store`, `current_theme`, `current_currency`
+- User authentication helpers
+- Storefront layout and helpers
+- SEO and meta tag support
+
+```ruby app/controllers/spree/brands_controller.rb
+module Spree
+ class BrandsController < StoreController
+ before_action :load_brand, only: [:show]
+
+ def index
+ @brands = Spree::Brand.order(:name)
+ end
+
+ def show
+ @products = @brand.products.active(current_currency).includes(storefront_products_includes)
+ end
+
+ private
+
+ def load_brand
+ @brand = Spree::Brand.find(params[:id])
+ end
+
+ # Override to set page title for SEO
+ def accurate_title
+ if @brand
+ @brand.name
+ else
+ Spree.t(:brands)
+ end
+ end
+ end
+end
+```
+
+### Key Points
+
+- **Inherit from `Spree::StoreController`** - Not `ApplicationController`. This gives you access to all storefront functionality.
+- **Use `current_store`** - Always scope queries to the current store for multi-store support.
+- **Override `accurate_title`** - This sets the page `<title>` tag.
+
+<Tip>
+ Want SEO-friendly URLs like `/brands/nike` instead of `/brands/123`? See the [SEO](/developer/tutorial/seo) tutorial to add slug support.
+</Tip>
+
+## Step 4: Create the Views
+
+Storefront views live in your theme directory. Create the brands views in your custom theme:
+
+```bash
+mkdir -p app/views/themes/my_store/spree/brands
+```
+
+Your theme's view structure:
+
+```
+app/views/themes/my_store/spree/brands/
+├── index.html.erb
+├── show.html.erb
+└── _brand_card.html.erb
+```
+
+### Brands Listing Page
+
+```erb app/views/themes/my_store/spree/brands/index.html.erb
+<div class="page-container py-8">
+ <h1 class="text-2xl lg:text-3xl font-medium mb-8">
+ <%= Spree.t(:brands) %>
+ </h1>
+
+ <% if @brands.any? %>
+ <div class="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-6">
+ <% @brands.each do |brand| %>
+ <%= render 'brand_card', brand: brand %>
+ <% end %>
+ </div>
+ <% else %>
+ <p class="text-neutral-600">
+ <%= Spree.t(:no_brands_found) %>
+ </p>
+ <% end %>
+</div>
+```
+
+### Brand Card Partial
+
+```erb app/views/themes/my_store/spree/brands/_brand_card.html.erb
+<%= link_to spree.brand_path(brand),
+ class: 'block group',
+ data: { turbo_frame: '_top' } do %>
+ <div class="aspect-square bg-accent rounded-lg overflow-hidden mb-3">
+ <% if brand.logo.attached? %>
+ <%= spree_image_tag brand.logo,
+ width: 300,
+ height: 300,
+ class: 'w-full h-full object-contain p-6 group-hover:scale-105 transition-transform',
+ alt: brand.name %>
+ <% else %>
+ <div class="w-full h-full flex items-center justify-center">
+ <span class="text-4xl font-medium text-neutral-400">
+ <%= brand.name.first.upcase %>
+ </span>
+ </div>
+ <% end %>
+ </div>
+ <h2 class="font-medium group-hover:text-primary transition-colors">
+ <%= brand.name %>
+ </h2>
+<% end %>
+```
+
+### Single Brand Page
+
+```erb app/views/themes/my_store/spree/brands/show.html.erb
+<div class="page-container py-8">
+ <%# Brand Header %>
+ <div class="flex flex-col md:flex-row gap-8 mb-12">
+ <% if @brand.logo.attached? %>
+ <div class="w-32 h-32 bg-accent rounded-lg flex-shrink-0">
+ <%= spree_image_tag @brand.logo,
+ width: 128,
+ height: 128,
+ class: 'w-full h-full object-contain p-4',
+ alt: @brand.name %>
+ </div>
+ <% end %>
+
+ <div>
+ <h1 class="text-2xl lg:text-3xl font-medium mb-4">
+ <%= @brand.name %>
+ </h1>
+
+ <% if @brand.description.present? %>
+ <div class="prose max-w-none text-neutral-600">
+ <%= @brand.description %>
+ </div>
+ <% end %>
+ </div>
+ </div>
+
+ <%# Products Grid %>
+ <% if @products.any? %>
+ <h2 class="text-xl font-medium mb-6">
+ <%= Spree.t(:products_by_brand, brand: @brand.name) %>
+ </h2>
+
+ <div class="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-6">
+ <%= render 'spree/shared/products', products: @products %>
+ </div>
+ <% else %>
+ <p class="text-neutral-600">
+ <%= Spree.t(:no_products_found) %>
+ </p>
+ <% end %>
+</div>
+```
+
+## Step 5: Add Translations
+
+Add the necessary translations:
+
+```yaml config/locales/en.yml
+en:
+ spree:
+ brands: Brands
+ no_brands_found: No brands found.
+ products_by_brand: "Products by %{brand}"
+```
+
+## Step 6: Add Navigation Link (Optional)
+
+To add a link to brands in your header navigation, you can use the Admin Dashboard:
+
+1. Go to **Storefront → Theme Editor**
+2. Click on **Header** section
+3. Add a new navigation link pointing to `/brands`
+
+Or programmatically in your header partial:
+
+```erb
+<%= link_to Spree.t(:brands), spree.brands_path, class: 'nav-link' %>
+```
+
+## Understanding the View Structure
+
+### Theme Directory
+
+Views are organized by theme in `app/views/themes/{theme_name}/spree/`:
+
+```
+app/views/themes/my_store/spree/
+├── brands/ # Your brand views
+├── products/ # Product views
+├── shared/ # Shared partials
+└── page_sections/ # Page Builder sections
+```
+
+<Info>
+ Spree looks for views in your active theme first. If a view isn't found, it falls back to the default theme. This means you only need to copy and customize the files you want to change.
+</Info>
+
+### Key CSS Classes
+
+Spree's default theme uses these common patterns:
+
+| Class | Purpose |
+|-------|---------|
+| `page-container` | Centered container with max-width and padding |
+| `bg-accent` | Uses theme's accent background color |
+| `text-primary` | Uses theme's primary text color |
+| `btn-primary` | Primary button style |
+| `btn-secondary` | Secondary button style |
+
+### Using Spree Helpers
+
+```erb
+<%# Image helper with automatic optimization %>
+<%= spree_image_tag image, width: 400, height: 400 %>
+
+<%# URL helpers %>
+<%= spree.brands_path %>
+<%= spree.brand_path(brand) %>
+
+<%# Translation helper %>
+<%= Spree.t(:brands) %>
+
+<%# Price display %>
+<%= display_price(product.price_in(current_currency)) %>
+```
+
+## Testing Your Pages
+
+Start your Rails server and visit:
+
+- `http://localhost:3000/brands` - Brand listing
+- `http://localhost:3000/brands/1` - Single brand (using the brand's ID)
+
+<Tip>
+ Want SEO-friendly URLs like `/brands/nike` instead of `/brands/1`? See the [SEO](/developer/tutorial/seo) tutorial to add slug support, meta tags, and Open Graph data.
+</Tip>
+
+## What's Next?
+
+You now have working brand pages using standard Rails MVC patterns. In the next guide, [Testing](/developer/tutorial/testing), we'll write automated tests for your feature to make sure it works as expected, also in the future when you make changes to your code.
+
+## Complete Controller Example
+
+Here's the complete controller with all features:
+
+```ruby app/controllers/spree/brands_controller.rb
+module Spree
+ class BrandsController < StoreController
+ before_action :load_brand, only: [:show]
+
+ def index
+ @brands = Spree::Brand.order(:name)
+ .page(params[:page])
+ .per(24)
+ end
+
+ def show
+ @products = @brand.products.active(current_currency).includes(storefront_products_includes)
+ @page_description = @brand.description&.to_plain_text&.truncate(160)
+ end
+
+ private
+
+ def load_brand
+ @brand = Spree::Brand.find(params[:id])
+ end
+
+ def accurate_title
+ if @brand
+ @brand.name
+ else
+ Spree.t(:brands)
+ end
+ end
+ end
+end
+```
+
+<Info>
+ To use SEO-friendly slugs like `/brands/nike` instead of `/brands/1`, follow the [SEO](/developer/tutorial/seo) tutorial.
+</Info>
+
+## Related Documentation
+
+- [Storefront Overview](/developer/storefront/storefront) - Storefront architecture
+- [Custom CSS](/developer/storefront/custom-css) - Styling with Tailwind
+- [Helper Methods](/developer/storefront/helper-methods) - Available helpers
diff --git a/docs/developer/tutorial/testing.mdx b/docs/developer/tutorial/testing.mdx
new file mode 100644
index 0000000000..cd4fafb259
--- /dev/null
+++ b/docs/developer/tutorial/testing.mdx
@@ -0,0 +1,622 @@
+---
+title: Testing
+description: Learn how to write automated tests for the Brands feature
+---
+
+Automated testing is a crucial part of the development process. It helps you ensure that your code works as expected and catches bugs early.
+Spree uses [RSpec](https://rspec.info), [Factory Bot](https://github.com/thoughtbot/factory_bot_rails), and [Capybara](https://github.com/teamcapybara/capybara) for testing.
+We also provide the `spree_dev_tools` gem that helps you write Spree-specific tests.
+
+<Info>
+ This guide assumes you've completed all previous tutorials through [Page Builder](/developer/tutorial/page-builder). You should have a complete `Spree::Brand` model with admin, storefront, and SEO features.
+</Info>
+
+## Setup
+
+### Step 1: Set RSpec as the Test Framework
+
+```bash
+bin/rails g rspec:install
+```
+
+### Step 2: Run the spree_dev_tools Generator
+
+```bash
+bin/rails g spree_dev_tools:install
+```
+
+This adds Spree-specific test helpers to your `spec/support/` directory, including:
+- Authorization helpers (`stub_authorization!`)
+- Factory Bot configuration
+- Capybara setup for feature tests
+- and more...
+
+### Step 3: Generate Test Files
+
+```bash
+bin/rails g rspec:model Spree::Brand
+```
+
+This creates `spec/models/spree/brand_spec.rb`.
+
+## Writing Factories
+
+Factories provide a convenient way to create test data. Create a factory for your Brand model:
+
+```ruby spec/factories/spree/brand_factory.rb
+FactoryBot.define do
+ factory :brand, class: Spree::Brand do
+ sequence(:name) { |n| "Brand #{n}" }
+
+ trait :with_description do
+ description { '<div>A great brand for <strong>quality products</strong></div>' }
+ end
+
+ trait :with_logo do
+ after(:create) do |brand|
+ brand.logo.attach(
+ io: File.new(Rails.root.join('spec', 'fixtures', 'files', 'logo.png')),
+ filename: 'logo.png'
+ )
+ end
+ end
+
+ trait :with_products do
+ transient do
+ products_count { 3 }
+ store { nil }
+ end
+
+ after(:create) do |brand, evaluator|
+ store = evaluator.store || create(:store)
+ create_list(:product, evaluator.products_count, brand: brand, stores: [store])
+ end
+ end
+ end
+end
+```
+
+### Factory Usage Examples
+
+```ruby
+# Basic factory
+brand = create(:brand)
+
+# With traits
+brand = create(:brand, :with_description, :with_logo)
+
+# With custom attributes
+brand = create(:brand, name: 'Nike')
+
+# Build without persisting (faster for unit tests)
+brand = build(:brand)
+
+# Create multiple records
+brands = create_list(:brand, 5)
+
+# With associated products
+brand = create(:brand, :with_products)
+brand = create(:brand, :with_products, products_count: 5)
+```
+
+## Writing Model Tests
+
+Model tests verify your business logic, validations, associations, and scopes.
+
+```ruby spec/models/spree/brand_spec.rb
+require 'spec_helper'
+
+RSpec.describe Spree::Brand, type: :model do
+ describe 'associations' do
+ it { is_expected.to have_many(:products).class_name('Spree::Product') }
+ end
+
+ describe 'validations' do
+ subject { build(:brand) }
+
+ it { is_expected.to validate_presence_of(:name) }
+
+ describe 'slug uniqueness' do
+ let!(:existing_brand) { create(:brand, slug: 'nike') }
+
+ it 'validates uniqueness of slug' do
+ brand = build(:brand, slug: 'nike')
+ expect(brand).not_to be_valid
+ expect(brand.errors[:slug]).to include('has already been taken')
+ end
+ end
+ end
+
+ describe 'FriendlyId' do
+ it 'generates slug from name' do
+ brand = create(:brand, name: 'Nike Sportswear')
+ expect(brand.slug).to eq('nike-sportswear')
+ end
+
+ it 'handles duplicate names by appending UUID' do
+ create(:brand, name: 'Nike')
+ brand = create(:brand, name: 'Nike')
+ expect(brand.slug).to match(/nike-[a-f0-9-]+/)
+ end
+ end
+
+ describe '#image' do
+ let(:brand) { create(:brand, :with_logo) }
+
+ it 'returns logo as image for Open Graph' do
+ expect(brand.image).to eq(brand.logo)
+ end
+ end
+end
+```
+
+### Testing with Shared Examples
+
+Spree provides shared examples for common patterns. Use them to test metadata support:
+
+```ruby
+RSpec.describe Spree::Brand, type: :model do
+ it_behaves_like 'metadata'
+end
+```
+
+### Testing Decorators
+
+When you extend core Spree models with decorators (see [Extending Core Models](/developer/tutorial/extending-models)), test the added functionality:
+
+```ruby spec/models/spree/product_decorator_spec.rb
+require 'spec_helper'
+
+RSpec.describe 'Spree::Product brand association' do
+ let(:store) { @default_store }
+ let(:brand) { create(:brand) }
+ let(:product) { create(:product, stores: [store]) }
+
+ describe 'brand association' do
+ it 'can be assigned a brand' do
+ product.brand = brand
+ product.save!
+
+ expect(product.reload.brand).to eq(brand)
+ end
+
+ it 'is optional' do
+ product.brand = nil
+ expect(product).to be_valid
+ end
+ end
+
+ describe 'brand.products' do
+ let!(:product1) { create(:product, brand: brand, stores: [store]) }
+ let!(:product2) { create(:product, brand: brand, stores: [store]) }
+ let!(:other_product) { create(:product, stores: [store]) }
+
+ it 'returns products for the brand' do
+ expect(brand.products).to contain_exactly(product1, product2)
+ end
+
+ it 'nullifies brand_id when brand is destroyed' do
+ brand.destroy
+ expect(product1.reload.brand_id).to be_nil
+ end
+ end
+end
+```
+
+## Writing Controller Tests
+
+Controller tests verify that your endpoints respond correctly and perform the expected actions.
+
+### Admin Controller Tests
+
+```ruby spec/controllers/spree/admin/brands_controller_spec.rb
+require 'spec_helper'
+
+RSpec.describe Spree::Admin::BrandsController, type: :controller do
+ stub_authorization!
+ render_views
+
+ describe 'GET #index' do
+ let!(:brand1) { create(:brand, name: 'Adidas') }
+ let!(:brand2) { create(:brand, name: 'Nike') }
+
+ it 'returns a successful response' do
+ get :index
+ expect(response).to be_successful
+ end
+
+ it 'assigns all brands' do
+ get :index
+ expect(assigns(:collection)).to contain_exactly(brand1, brand2)
+ end
+ end
+
+ describe 'GET #new' do
+ it 'returns a successful response' do
+ get :new
+ expect(response).to be_successful
+ end
+
+ it 'assigns a new brand' do
+ get :new
+ expect(assigns(:brand)).to be_a_new(Spree::Brand)
+ end
+ end
+
+ describe 'POST #create' do
+ context 'with valid params' do
+ let(:valid_params) do
+ { brand: { name: 'New Brand' } }
+ end
+
+ it 'creates a new brand' do
+ expect {
+ post :create, params: valid_params
+ }.to change(Spree::Brand, :count).by(1)
+ end
+
+ it 'redirects to the edit page' do
+ post :create, params: valid_params
+ expect(response).to redirect_to(spree.edit_admin_brand_path(Spree::Brand.last))
+ end
+ end
+
+ context 'with invalid params' do
+ let(:invalid_params) do
+ { brand: { name: '' } }
+ end
+
+ it 'does not create a new brand' do
+ expect {
+ post :create, params: invalid_params
+ }.not_to change(Spree::Brand, :count)
+ end
+
+ it 'renders the new template' do
+ post :create, params: invalid_params
+ expect(response).to render_template(:new)
+ end
+ end
+ end
+
+ describe 'GET #edit' do
+ let(:brand) { create(:brand) }
+
+ it 'returns a successful response' do
+ get :edit, params: { id: brand.id }
+ expect(response).to be_successful
+ end
+ end
+
+ describe 'PUT #update' do
+ let(:brand) { create(:brand, name: 'Old Name') }
+
+ context 'with valid params' do
+ it 'updates the brand' do
+ put :update, params: { id: brand.id, brand: { name: 'New Name' } }
+ expect(brand.reload.name).to eq('New Name')
+ end
+
+ it 'redirects to the edit page' do
+ put :update, params: { id: brand.id, brand: { name: 'New Name' } }
+ expect(response).to redirect_to(spree.edit_admin_brand_path(brand))
+ end
+ end
+ end
+
+ describe 'DELETE #destroy' do
+ let!(:brand) { create(:brand) }
+
+ it 'removes the brand from the database' do
+ expect {
+ delete :destroy, params: { id: brand.id }, format: :turbo_stream
+ }.to change(Spree::Brand, :count).by(-1)
+ end
+ end
+end
+```
+
+### Storefront Controller Tests
+
+```ruby spec/controllers/spree/brands_controller_spec.rb
+require 'spec_helper'
+
+RSpec.describe Spree::BrandsController, type: :controller do
+ render_views
+
+ describe 'GET #index' do
+ let!(:brand1) { create(:brand, name: 'Nike') }
+ let!(:brand2) { create(:brand, name: 'Adidas') }
+
+ it 'returns a successful response' do
+ get :index
+ expect(response).to be_successful
+ end
+
+ it 'assigns all brands' do
+ get :index
+ expect(assigns(:brands)).to contain_exactly(brand1, brand2)
+ end
+ end
+
+ describe 'GET #show' do
+ let(:brand) { create(:brand) }
+
+ it 'returns a successful response' do
+ get :show, params: { id: brand.slug }
+ expect(response).to be_successful
+ end
+
+ it 'assigns the brand' do
+ get :show, params: { id: brand.slug }
+ expect(assigns(:brand)).to eq(brand)
+ end
+
+ context 'with non-existent brand' do
+ it 'raises RecordNotFound' do
+ expect {
+ get :show, params: { id: 'non-existent' }
+ }.to raise_error(ActiveRecord::RecordNotFound)
+ end
+ end
+ end
+end
+```
+
+## Writing Feature Tests
+
+Feature tests (also called system tests) simulate real user interactions using Capybara. They test the full stack including JavaScript.
+
+### Admin Feature Tests
+
+```ruby spec/features/spree/admin/brands_spec.rb
+require 'spec_helper'
+
+RSpec.feature 'Admin Brands', type: :feature do
+ stub_authorization!
+
+ describe 'listing brands' do
+ let!(:brand1) { create(:brand, name: 'Nike') }
+ let!(:brand2) { create(:brand, name: 'Adidas') }
+
+ it 'displays all brands' do
+ visit spree.admin_brands_path
+
+ expect(page).to have_content('Nike')
+ expect(page).to have_content('Adidas')
+ end
+ end
+
+ describe 'creating a brand' do
+ it 'creates a new brand successfully' do
+ visit spree.admin_brands_path
+ click_on 'New Brand'
+
+ fill_in 'Name', with: 'Puma'
+
+ click_on 'Create'
+ wait_for_turbo
+
+ expect(page).to have_content('Brand "Puma" has been successfully created!')
+ expect(Spree::Brand.find_by(name: 'Puma')).to be_present
+ end
+
+ it 'shows validation errors' do
+ visit spree.new_admin_brand_path
+
+ click_on 'Create'
+ wait_for_turbo
+
+ expect(page).to have_content("can't be blank")
+ end
+ end
+
+ describe 'editing a brand' do
+ let!(:brand) { create(:brand, name: 'Nike') }
+
+ it 'updates the brand successfully' do
+ visit spree.admin_brands_path
+ click_on 'Edit'
+
+ fill_in 'Name', with: 'Nike Inc.'
+ within('#page-header') { click_button 'Update' }
+
+ wait_for_turbo
+ expect(page).to have_content('Brand "Nike Inc." has been successfully updated!')
+ expect(brand.reload.name).to eq('Nike Inc.')
+ end
+ end
+
+ describe 'deleting a brand', js: true do
+ let!(:brand) { create(:brand, name: 'Nike') }
+
+ it 'removes the brand' do
+ visit spree.admin_brands_path
+ click_on 'Edit'
+
+ wait_for_turbo
+
+ accept_confirm do
+ click_on 'Delete'
+ end
+
+ wait_for_turbo
+ expect(page).to have_content('Brand "Nike" has been successfully removed!')
+ expect(Spree::Brand.find_by(name: 'Nike')).to be_nil
+ end
+ end
+end
+```
+
+### Storefront Feature Tests
+
+```ruby spec/features/spree/brands_spec.rb
+require 'spec_helper'
+
+RSpec.feature 'Storefront Brands', type: :feature do
+ let(:store) { @default_store }
+
+ describe 'brands listing page' do
+ let!(:nike) { create(:brand, name: 'Nike') }
+ let!(:adidas) { create(:brand, name: 'Adidas') }
+
+ it 'displays all brands' do
+ visit spree.brands_path
+
+ expect(page).to have_content('Nike')
+ expect(page).to have_content('Adidas')
+ end
+
+ it 'links to individual brand pages' do
+ visit spree.brands_path
+
+ click_link 'Nike'
+
+ expect(page).to have_current_path(spree.brand_path(nike))
+ end
+ end
+
+ describe 'brand detail page' do
+ let(:brand) { create(:brand, :with_description, name: 'Nike') }
+ let!(:product) { create(:product, brand: brand, stores: [store]) }
+
+ it 'displays brand information' do
+ visit spree.brand_path(brand)
+
+ expect(page).to have_content('Nike')
+ expect(page).to have_content(product.name)
+ end
+
+ it 'uses SEO-friendly URL' do
+ visit spree.brand_path(brand)
+
+ expect(page).to have_current_path("/brands/#{brand.slug}")
+ end
+ end
+end
+```
+
+## Test Helpers
+
+### Authorization Helper
+
+Use `stub_authorization!` to bypass authorization checks in admin tests:
+
+```ruby
+RSpec.describe Spree::Admin::BrandsController, type: :controller do
+ stub_authorization! # Grants full admin access
+
+ # ... your tests
+end
+```
+
+### wait_for_turbo Helper
+
+When testing with Turbo/Hotwire, use `wait_for_turbo` to ensure the page has fully loaded:
+
+```ruby
+click_on 'Create'
+wait_for_turbo
+expect(page).to have_content('Success!')
+```
+
+### JavaScript Tests
+
+Add `js: true` to tests that require JavaScript:
+
+```ruby
+it 'handles JavaScript interactions', js: true do
+ visit spree.admin_brands_path
+
+ accept_confirm do
+ click_on 'Delete'
+ end
+
+ expect(page).to have_content('Deleted!')
+end
+```
+
+## Running Tests
+
+```bash
+# Run all tests
+bundle exec rspec
+
+# Run specific test file
+bundle exec rspec spec/models/spree/brand_spec.rb
+
+# Run specific test
+bundle exec rspec spec/models/spree/brand_spec.rb:15
+
+# Run with documentation format
+bundle exec rspec --format documentation
+
+# Run only feature tests
+bundle exec rspec spec/features/
+```
+
+## Best Practices
+
+<CardGroup cols={2}>
+ <Card title="Use build over create" icon="bolt">
+ Use `build` instead of `create` when you don't need a persisted record. It's faster because it skips database operations.
+ </Card>
+
+ <Card title="Use let over instance variables" icon="code">
+ Prefer `let` and `let!` over instance variables. They're lazily evaluated and scoped to each example.
+ </Card>
+
+ <Card title="One assertion per test" icon="check">
+ Keep tests focused on a single behavior. Use `aggregate_failures` if you need multiple assertions.
+ </Card>
+
+ <Card title="Test behavior, not implementation" icon="eye">
+ Focus on what the code does, not how it does it. This makes tests more resilient to refactoring.
+ </Card>
+</CardGroup>
+
+### Example: aggregate_failures
+
+```ruby
+it 'creates brand with all attributes', :aggregate_failures do
+ brand = create(:brand, name: 'Nike')
+
+ expect(brand.name).to eq('Nike')
+ expect(brand.slug).to eq('nike')
+end
+```
+
+## Complete Test Suite Structure
+
+After completing this tutorial, your test structure should look like:
+
+```
+spec/
+├── factories/
+│ └── spree/
+│ └── brand_factory.rb
+├── models/
+│ └── spree/
+│ ├── brand_spec.rb
+│ └── product_decorator_spec.rb
+├── controllers/
+│ └── spree/
+│ ├── admin/
+│ │ └── brands_controller_spec.rb
+│ └── brands_controller_spec.rb
+├── features/
+│ └── spree/
+│ ├── admin/
+│ │ └── brands_spec.rb
+│ └── brands_spec.rb
+└── spec_helper.rb
+```
+
+## Related Documentation
+
+- [Model Tutorial](/developer/tutorial/model) - Creating the Brand model
+- [Admin Tutorial](/developer/tutorial/admin) - Building the admin interface
+- [Extending Core Models](/developer/tutorial/extending-models) - Connecting Brands to Products
+- [Storefront Tutorial](/developer/tutorial/storefront) - Creating storefront pages
+- [RSpec Documentation](https://rspec.info/documentation/) - Official RSpec docs
+- [Factory Bot Documentation](https://github.com/thoughtbot/factory_bot/blob/main/GETTING_STARTED.md) - Factory Bot guide
diff --git a/docs/docs.json b/docs/docs.json
index 54a1f52cbf..faf9787eaf 100644
--- a/docs/docs.json
+++ b/docs/docs.json
@@ -1,31 +1,86 @@
{
"$schema": "https://mintlify.com/docs.json",
"name": "Spree Commerce documentation",
- "theme": "maple",
+ "theme": "almond",
"colors": {
"primary": "#0A2242",
"light": "#D7DFE9",
"dark": "#0A2242"
},
+ "styling": {
+ "eyebrows": "breadcrumbs",
+ "codeblocks": {
+ "theme": "night-owl"
+ }
+ },
+ "interaction": {
+ "drilldown": true
+ },
"favicon": "/favicon.png",
"seo": {
"metatags": {
- "canonical": "https://spreecommerce.org/docs"
+ "canonical": "https://spreecommerce.org/docs",
+ "og:locale": "en_US",
+ "twitter:site": "@spreecommerce"
+ }
+ },
+ "icons": {
+ "library": "lucide"
+ },
+ "redirects": [
+ {
+ "source": "/developer/storefront/images",
+ "destination": "/developer/core-concepts/images-assets"
}
+ ],
+ "contextual": {
+ "options": [
+ "copy",
+ "view",
+ "chatgpt",
+ "claude",
+ "mcp",
+ "cursor",
+ "vscode"
+ ]
},
"navigation": {
"versions": [
{
"version": "v5",
"default": true,
+ "pages": [
+ "index"
+ ],
"tabs": [
{
"tab": "Developer Docs",
"groups": [
{
"group": "Getting started",
+ "icon": "rocket",
+ "pages": [
+ "developer/getting-started/quickstart"
+ ]
+ },
+ {
+ "group": "Tutorial",
+ "icon": "graduation-cap",
+ "pages": [
+ "developer/tutorial/introduction",
+ "developer/tutorial/model",
+ "developer/tutorial/admin",
+ "developer/tutorial/rich-text",
+ "developer/tutorial/file-uploads",
+ "developer/tutorial/extending-models",
+ "developer/tutorial/storefront",
+ "developer/tutorial/testing"
+ ]
+ },
+ {
+ "group": "Core Concepts",
+ "icon": "brain",
"pages": [
- "developer/getting-started/quickstart",
"developer/core-concepts/architecture",
"developer/core-concepts/stores",
"developer/core-concepts/orders",
@@ -39,45 +94,50 @@
"developer/core-concepts/calculators",
"developer/core-concepts/adjustments",
"developer/core-concepts/addresses",
+ "developer/core-concepts/metafields",
"developer/core-concepts/i18n",
- "developer/core-concepts/metafields"
+ "developer/core-concepts/search-filtering",
+ "developer/core-concepts/slugs",
+ "developer/core-concepts/images-assets"
+ ]
+ },
+ {
+ "group": "Admin Dashboard",
+ "icon": "gauge",
+ "pages": [
+ "developer/admin/admin",
+ "developer/admin/extending-ui",
+ "developer/admin/navigation",
+ "developer/admin/form-builder",
+ "developer/admin/components",
+ "developer/admin/helper-methods",
+ "developer/admin/authentication",
+ "developer/admin/permissions",
+ "developer/admin/custom-javascript",
+ "developer/admin/custom-css"
+ ]
+ },
+ {
+ "group": "Storefront",
+ "icon": "store",
+ "pages": [
+ "developer/storefront/storefront",
+ "developer/storefront/themes",
+ "developer/storefront/pages",
+ "developer/storefront/sections",
+ "developer/storefront/blocks",
+ "developer/storefront/links",
+ "developer/storefront/helper-methods",
+ "developer/storefront/custom-javascript",
+ "developer/storefront/custom-css"
]
},
{
- "group": "Customizing Spree",
+ "group": "Customization Reference",
+ "icon": "wrench",
"pages": [
"developer/customization/quickstart",
"developer/customization/configuration",
- {
- "group": "Storefront",
- "icon": "store",
- "pages": [
- "developer/storefront/storefront",
- "developer/storefront/themes",
- "developer/storefront/pages",
- "developer/storefront/sections",
- "developer/storefront/blocks",
- "developer/storefront/links",
- "developer/storefront/images",
- "developer/storefront/helper-methods",
- "developer/storefront/custom-javascript",
- "developer/storefront/custom-css"
- ]
- },
- {
- "group": "Admin Dashboard",
- "icon": "gauge",
- "pages": [
- "developer/admin/admin",
- "developer/admin/extending-ui",
- "developer/admin/navigation",
- "developer/admin/authentication",
- "developer/admin/permissions",
- "developer/admin/helper-methods",
- "developer/admin/custom-javascript",
- "developer/admin/custom-css"
- ]
- },
"developer/customization/authentication",
"developer/customization/checkout",
"developer/customization/permissions",
@@ -97,7 +157,6 @@
"pages": [
{
"group": "Multi-Store",
- "icon": "store",
"pages": [
"developer/multi-store/quickstart",
"developer/multi-store/setup"
@@ -105,7 +164,6 @@
},
{
"group": "Multi-Tenant",
- "icon": "building",
"pages": [
"developer/multi-tenant/quickstart",
"developer/multi-tenant/installation",
@@ -115,7 +173,6 @@
},
{
"group": "Multi-Vendor",
- "icon": "shop",
"pages": [
"developer/multi-vendor/quickstart",
"developer/multi-vendor/installation"
@@ -125,6 +182,7 @@
},
{
"group": "Deployment",
+ "icon": "server",
"pages": [
"developer/deployment/render",
"developer/deployment/aws",
@@ -138,6 +196,7 @@
},
{
"group": "Upgrading",
+ "icon": "circle-arrow-up",
"pages": [
"developer/upgrades/quickstart",
{
@@ -174,6 +233,7 @@
},
{
"group": "Contributing",
+ "icon": "heart",
"pages": [
"developer/contributing/quickstart",
"developer/contributing/developing-spree",
@@ -182,16 +242,11 @@
},
{
"group": "Security",
+ "icon": "shield",
"pages": [
"developer/security/security_policy",
"developer/security/pci_compliance"
]
- },
- {
- "group": "Advanced",
- "pages": [
- "developer/advanced/adding_spree_to_rails_app"
- ]
}
]
},
@@ -1124,7 +1179,7 @@
]
},
{
- "group": "Customizing Spree",
+ "group": "Customization Reference",
"pages": [
"developer/customization/quickstart",
"developer/customization/v4/authentication",
@@ -1923,28 +1978,24 @@
}
]
}
- ],
- "global": {
- "anchors": [
- {
- "anchor": "Community",
- "href": "http://slack.spreecommerce.org/",
- "icon": "slack"
- },
- {
- "anchor": "Github",
- "href": "https://github.com/spree/spree",
- "icon": "github"
- }
- ]
- }
+ ]
},
"logo": {
"light": "/logo/logo_light.png",
- "dark": "/logo/logo_dark.png",
- "href": "https://spreecommerce.org"
+ "dark": "/logo/logo_dark.png"
},
"api": {
+ "examples": {
+ "languages": [
+ "curl",
+ "javascript",
+ "ruby",
+ "python",
+ "php",
+ "java",
+ "c#"
+ ]
+ },
"openapi": [
"api-reference/storefront.yaml",
"api-reference/platform.yaml"
@@ -1957,15 +2008,9 @@
}
},
"navbar": {
- "links": [
- {
- "label": "Support",
- "href": "mailto:[email protected]"
- }
- ],
"primary": {
"type": "button",
- "label": "Get started",
+ "label": "Support",
"href": "https://spreecommerce.org/contact/"
}
},
diff --git a/docs/images/hero/api.png b/docs/images/hero/api.png
new file mode 100644
index 0000000000..c8190787ff
Binary files /dev/null and b/docs/images/hero/api.png differ
diff --git a/docs/images/hero/dev.png b/docs/images/hero/dev.png
new file mode 100644
index 0000000000..cdc7dc117c
Binary files /dev/null and b/docs/images/hero/dev.png differ
diff --git a/docs/images/hero/integrations.png b/docs/images/hero/integrations.png
new file mode 100644
index 0000000000..a8436cd1cb
Binary files /dev/null and b/docs/images/hero/integrations.png differ
diff --git a/docs/images/hero/user.png b/docs/images/hero/user.png
new file mode 100644
index 0000000000..ddd6de23e3
Binary files /dev/null and b/docs/images/hero/user.png differ
diff --git a/docs/index.mdx b/docs/index.mdx
new file mode 100644
index 0000000000..6f017d8ce5
--- /dev/null
+++ b/docs/index.mdx
@@ -0,0 +1,61 @@
+---
+title: "Introduction"
+description: "Start building your eCommerce solution with our flexible open source eCommerce platform."
+mode: "custom"
+---
+
+export const HeroCard = ({ filename, title, description, href }) => {
+ return (
+ <a className="group cursor-pointer pb-8" href={href}>
+ <img
+ src={`images/hero/${filename}.png`}
+ className="block dark:hidden pointer-events-none group-hover:scale-105 transition-all duration-100"
+ />
+ <img
+ src={`images/hero/${filename}.png`}
+ className="pointer-events-none group-hover:scale-105 transition-all duration-100 hidden dark:block"
+ />
+ <h3 className="mt-5 text-gray-900 dark:text-zinc-50 font-medium">
+ {title}
+ </h3>
+ <span className="mt-1.5">{description}</span>
+ </a>
+ );
+};
+
+<div className="relative">
+ <div className="relative z-10 px-4 py-16 max-w-3xl mx-auto">
+ <h1 className="block text-4xl font-medium text-center text-gray-900 dark:text-zinc-50 tracking-tight">
+ Spree Commerce Documentation
+ </h1>
+
+ <div className="max-w-xl mx-auto px-4 mt-4 text-lg text-center text-gray-500 dark:text-zinc-500">
+ Start building your eCommerce solution with our flexible open source eCommerce platform.
+ </div>
+
+ <div className="px-6 lg:px-0 mt-12 grid sm:grid-cols-2 gap-x-6 gap-y-4">
+ <HeroCard filename="dev" title="Developer Docs" description="Setup your Spree Commerce in minutes and start developing" href="/developer/getting-started" />
+
+ <HeroCard
+ filename="api"
+ title="API Reference"
+ description="Explore the Spree Commerce API reference"
+ href="/api-reference"
+ />
+
+ <HeroCard
+ filename="user"
+ title="User Documentation"
+ description="Learn how to use Spree Commerce as a store owner or operator"
+ href="/user"
+ />
+
+ <HeroCard
+ filename="integrations"
+ title="Integrations"
+ description="Integrate Spree Commerce with your favorite tools and services"
+ href="/integrations"
+ />
+ </div>
+ </div>
+</div>
\ No newline at end of file