Search documentation of phoenix_kit

# PhoenixKit.Entities (phoenix_kit v1.6.19)

View Source

Dynamic entity system for PhoenixKit - WordPress ACF equivalent.

This module provides both the Ecto schema definition and business logic for managing custom content types (entities) with flexible field schemas.

## Schema Fields

- `name`: Unique identifier for the entity (e.g., "brand", "product")
- `display_name`: Human-readable singular name shown in UI (e.g., "Brand")
- `display_name_plural`: Human-readable plural name (e.g., "Brands")
- `description`: Description of what this entity represents
- `icon`: Icon identifier for UI display (hero icons)
- `status`: Workflow status string - one of "draft", "published", or "archived"
- `fields_definition`: JSONB array of field definitions
- `settings`: JSONB map of entity-specific settings
- `created_by`: User ID of the admin who created the entity
- `date_created`: When the entity was created
- `date_updated`: When the entity was last modified

## Field Definition Structure

Each field in `fields_definition` is a map with:

- `type`: Field type (text, textarea, number, boolean, date, select, etc.)
- `key`: Unique field identifier (snake_case)
- `label`: Display label for the field
- `required`: Whether the field is required
- `default`: Default value
- `validation`: Map of validation rules
- `options`: Array of options (for select, radio, checkbox types)

## Core Functions

### Entity Management

- `list_entities/0` - Get all entities
- `list_active_entities/0` - Get only active entities
- `get_entity!/1` - Get an entity by ID (raises if not found)
- `get_entity_by_name/1` - Get an entity by its name
- `create_entity/1` - Create a new entity
- `update_entity/2` - Update an existing entity
- `delete_entity/1` - Delete an entity (and all its data)
- `change_entity/2` - Get changeset for forms

### System Settings

- `enabled?/0` - Check if entities system is enabled
- `enable_system/0` - Enable the entities system
- `disable_system/0` - Disable the entities system
- `get_config/0` - Get current system configuration
- `get_max_per_user/0` - Get max entities per user limit
- `validate_user_entity_limit/1` - Check if user can create more entities

## Usage Examples

    # Check if system is enabled
    if PhoenixKit.Entities.enabled?() do
      # System is active
    end

    # Create a brand entity
    # Note: fields_definition requires string keys, not atom keys
    {:ok, entity} = PhoenixKit.Entities.create_entity(%{
      name: "brand",
      display_name: "Brand",
      display_name_plural: "Brands",
      description: "Brand content type for company profiles",
      icon: "hero-building-office",
      created_by: admin_user.id,
      fields_definition: [
        %{"type" => "text", "key" => "name", "label" => "Name", "required" => true},
        %{"type" => "textarea", "key" => "tagline", "label" => "Tagline"},
        %{"type" => "rich_text", "key" => "description", "label" => "Description", "required" => true},
        %{"type" => "select", "key" => "industry", "label" => "Industry",
          "options" => ["Technology", "Manufacturing", "Retail"]},
        %{"type" => "date", "key" => "founded_date", "label" => "Founded Date"},
        %{"type" => "boolean", "key" => "featured", "label" => "Featured Brand"}
      ]
    })

    # Get entity by name
    entity = PhoenixKit.Entities.get_entity_by_name("brand")

    # List all active entities
    entities = PhoenixKit.Entities.list_active_entities()

# Summary

## Functions

change_entity(entity, attrs \\ %{})

Returns an `%Ecto.Changeset{}` for tracking entity changes.

changeset(entity, attrs)

Creates a changeset for entity creation and updates.

count_all_entity_data()

Counts the total number of entity data records across all entities.

count_entities()

Counts the total number of entities in the system.

count_user_entities(user_id)

Counts the total number of entities created by a user.

create_entity(attrs \\ %{})

Creates an entity.

delete_entity(entity)

Deletes an entity.

disable_system()

Disables the entities system.

enable_system()

Enables the entities system.

enabled?()

Checks if the entities system is enabled.

get_config()

Gets the current entities system configuration.

get_entity(id)

Gets a single entity by ID.

get_entity!(id)

Gets a single entity by ID.

get_entity_by_name(name)

Gets a single entity by its unique name.

get_max_per_user()

Gets the maximum number of entities a single user can create.

get_system_stats()

Gets summary statistics for the entities system.

list_active_entities()

Returns the list of active (published) entities.

list_entities()

Returns the list of entities ordered by creation date.

update_entity(entity, attrs)

Updates an entity.

validate_user_entity_limit(user_id)

Validates that a user hasn't exceeded their entity creation limit.

# Functions

# change_entity(entity, attrs \\ %{})

Returns an `%Ecto.Changeset{}` for tracking entity changes.

## Examples

    iex> PhoenixKit.Entities.change_entity(entity)
    %Ecto.Changeset{data: %PhoenixKit.Entities{}}

# changeset(entity, attrs)

Creates a changeset for entity creation and updates.

Validates that name is unique, fields_definition is valid, and all required fields are present. Automatically sets date_created on new records.

# count_all_entity_data()

Counts the total number of entity data records across all entities.

## Examples

    iex> PhoenixKit.Entities.count_all_entity_data()
    243

# count_entities()

Counts the total number of entities in the system.

## Examples

    iex> PhoenixKit.Entities.count_entities()
    15

# count_user_entities(user_id)

Counts the total number of entities created by a user.

## Examples

    iex> PhoenixKit.Entities.count_user_entities(1)
    5

# create_entity(attrs \\ %{})

Creates an entity.

## Examples

    iex> PhoenixKit.Entities.create_entity(%{name: "brand", display_name: "Brand"})
    {:ok, %PhoenixKit.Entities{}}

    iex> PhoenixKit.Entities.create_entity(%{name: ""})
    {:error, %Ecto.Changeset{}}

Note: `created_by` is auto-filled with the first admin or user ID if not provided, but only if at least one user exists in the system. If no users exist, the changeset will fail with a validation error on `created_by`.

# delete_entity(entity)

Deletes an entity.

Note: This will also delete all associated entity_data records due to the ON DELETE CASCADE constraint defined in the database migration (V17).

## Examples

    iex> PhoenixKit.Entities.delete_entity(entity)
    {:ok, %PhoenixKit.Entities{}}

    iex> PhoenixKit.Entities.delete_entity(entity)
    {:error, %Ecto.Changeset{}}

# disable_system()

Disables the entities system.

Sets the "entities_enabled" setting to false.

## Examples

    iex> PhoenixKit.Entities.disable_system()
    {:ok, %Setting{}}

# enable_system()

Enables the entities system.

Sets the "entities_enabled" setting to true.

## Examples

    iex> PhoenixKit.Entities.enable_system()
    {:ok, %Setting{}}

# enabled?()

Checks if the entities system is enabled.

Returns true if the "entities_enabled" setting is true.

## Examples

    iex> PhoenixKit.Entities.enabled?()
    false

# get_config()

Gets the current entities system configuration.

Returns a map with the current settings.

## Examples

    iex> PhoenixKit.Entities.get_config()
    %{enabled: false, max_per_user: 100, allow_relations: true, file_upload: false, entity_count: 0, total_data_count: 0}

# get_entity(id)

Gets a single entity by ID.

Returns the entity if found, nil otherwise.

## Examples

    iex> PhoenixKit.Entities.get_entity(123)
    %PhoenixKit.Entities{}

    iex> PhoenixKit.Entities.get_entity(456)
    nil

# get_entity!(id)

Gets a single entity by ID.

Raises `Ecto.NoResultsError` if the entity does not exist.

## Examples

    iex> PhoenixKit.Entities.get_entity!(123)
    %PhoenixKit.Entities{}

    iex> PhoenixKit.Entities.get_entity!(456)
    ** (Ecto.NoResultsError)

# get_entity_by_name(name)

Gets a single entity by its unique name.

Returns the entity if found, nil otherwise.

## Examples

    iex> PhoenixKit.Entities.get_entity_by_name("brand")
    %PhoenixKit.Entities{}

    iex> PhoenixKit.Entities.get_entity_by_name("invalid")
    nil

# get_max_per_user()

Gets the maximum number of entities a single user can create.

Returns the system-wide limit for entity creation per user. Defaults to 100 if not set.

## Examples

    iex> PhoenixKit.Entities.get_max_per_user()
    100

# get_system_stats()

Gets summary statistics for the entities system.

Returns counts and metrics useful for admin dashboards.

## Examples

    iex> PhoenixKit.Entities.get_system_stats()
    %{total_entities: 5, active_entities: 4, total_data_records: 150}

# list_active_entities()

Returns the list of active (published) entities.

## Examples

    iex> PhoenixKit.Entities.list_active_entities()
    [%PhoenixKit.Entities{status: "published"}, ...]

# list_entities()

Returns the list of entities ordered by creation date.

## Examples

    iex> PhoenixKit.Entities.list_entities()
    [%PhoenixKit.Entities{}, ...]

# update_entity(entity, attrs)

Updates an entity.

## Examples

    iex> PhoenixKit.Entities.update_entity(entity, %{display_name: "Updated"})
    {:ok, %PhoenixKit.Entities{}}

    iex> PhoenixKit.Entities.update_entity(entity, %{name: ""})
    {:error, %Ecto.Changeset{}}

# validate_user_entity_limit(user_id)

Validates that a user hasn't exceeded their entity creation limit.

Checks the current number of entities created by the user against the system limit. Returns `{:ok, :valid}` if within limits, `{:error, reason}` if limit exceeded.

## Examples

    iex> PhoenixKit.Entities.validate_user_entity_limit(1)
    {:ok, :valid}

    iex> PhoenixKit.Entities.validate_user_entity_limit(1)
    {:error, "You have reached the maximum limit of 100 entities"}