the model [code] the controller [code] the _form view code [code] The issue is when…
- User
the model
class Content extends ActiveRecord { use BitmaskTrait; /** * Type * @see app\models\ContentCategory.php * Note: Types are handled via ContentCategory and automatically handled * const TYPE_POST = 'post'; const TYPE_PRODUCT = 'product'; //public const TYPE_CATALOG = 'catalog';//*/ // Status const STATUS_DRAFT = 0; const STATUS_PUBLISH = 1; const STATUS_SOLDOUT = 3; // Purchase options public const PURCHASE_OPTIONS_CART = 1;// 2^0 public const PURCHASE_OPTIONS_INQUIRE = 2;// 2^1 public const PURCHASE_OPTIONS_BUYNOW = 4;// 2^2 public static $templates = ['item', 'artwork', 'article', 'exhibition', 'artist', 'catalog']; protected static array $allowedTemplatesByType = [ ContentCategory::TYPE_POST => ['article', 'exhibition', 'artist', 'catalog'], ContentCategory::TYPE_PRODUCT => ['artwork', 'exhibition', 'item', 'catalog'], //ContentCategory::TYPE_CATALOG => [],// no templates or as needed ]; protected static array $typeMap = [ 'post' => ContentCategory::TYPE_POST, 'product' => ContentCategory::TYPE_PRODUCT, // 'catalog' => ContentCategory::TYPE_CATALOG, ]; public function scenarios(): array { $baseAttributes = [ 'type', 'template', 'category_id', 'category_title', 'status', 'title', 'slug', 'body', 'image_header', 'meta_description', 'meta_keywords', /** * Handled by TimestampBehavior 'created_at', 'updated_at',//*/ /** * Handled by BlameableBehavior 'created_by', 'updated_by',//*/ ]; // Add purchaseOptionsArray here because it's used virtually $baseAttributes[] = 'purchaseOptionsArray'; return [ /** * Base type-only fallback scenarios for safety * * Note: array_merge function will append the scenario rules to the base rules, but * it doesn't handle potential conflicts or overwriting of rules. */ ContentCategory::TYPE_POST => $baseAttributes, ContentCategory::TYPE_PRODUCT => array_merge($baseAttributes, [ 'artist', 'dimensions', 'medium', 'year', 'price', 'purchase_options', 'hide_price', 'quantity', 'product_image_one', 'product_image_two', 'product_image_three', ]), //ContentCategory::TYPE_CATALOG => $baseAttributes, /** * Post type + template scenarios for specific validation */ 'post_article' => $baseAttributes, 'post_exhibition' => array_merge($baseAttributes, [ 'start_date', 'end_date', ]), 'post_catalog' => $baseAttributes, /** * Product type + template scenario */ 'product_artwork' => array_merge($baseAttributes, [ 'artist', 'dimensions', 'medium', 'year', 'price', 'purchase_options', 'hide_price', 'quantity', 'product_image_one', 'product_image_two', 'product_image_three', ]), 'product_item' => array_merge($baseAttributes, [ 'artist', 'price', 'purchase_options', 'quantity', 'product_image_one', 'product_image_two', 'product_image_three', ]), 'product_catalog' => $baseAttributes, /** * Default */ 'default' => $baseAttributes, ]; } public function rules(): array { /** * Rules * Rules are handled by either app\models\forms\** for user access validation, or * handled directly within the model and than view file skipping form model validation * for administration only. */ $rules = [ /** * Required */ [['type', 'template', 'category_id', 'status', 'title', 'body', 'meta_description' /* 'created_by', 'created_at' - handled by BlameableBehavior */], 'required'], /** * Integers * Note: Price is handled as a float/string until custom validation. See below. */ [['category_id', 'status', 'year', 'quantity', /*'price'*, 'purchase_options', Note: Empty int until declared via purchaseOptionsArray */ 'created_by', 'updated_by', 'created_at', 'updated_at'], 'integer'], /** * Strings */ [['body', 'template', 'meta_description', 'meta_keywords', 'category_title'], 'string'], [['title', 'artist', 'dimensions', 'medium', 'category_title', 'meta_keywords', 'slug'], 'string', 'max' => 255], [['image_header','product_image_one', 'product_image_two', 'product_image_three'], 'string', 'max' => 2000], ['meta_description', 'string', 'max' => $this->_contentSummaryLength], ['template', 'string', 'max' => 50], /** * Boolean */ ['hide_price', 'boolean'], ['hide_price', 'default', 'value' => false], /** * Safe */ ['purchaseOptionsArray', 'safe'],// Allow purchaseOptionsArray for form binding as safe /** * Defaults */ ['status', 'default', 'value' => self::STATUS_DRAFT], ['status', 'in', 'range' => [self::STATUS_DRAFT, self::STATUS_PUBLISH], 'when' => fn($model) => $model->type === ContentCategory::TYPE_POST], ['status', 'in', 'range' => [self::STATUS_DRAFT, self::STATUS_PUBLISH, self:: STATUS_SOLDOUT], 'when' => fn($model) => $model->type === ContentCategory::TYPE_PRODUCT], ['type', 'default', 'value' => ContentCategory::TYPE_POST], ['template', 'default', 'value' => 'article', 'when' => fn($model) => $model->type === ContentCategory::TYPE_POST], ['template', 'default', 'value' => 'item', 'when' => fn($model) => $model->type === ContentCategory::TYPE_PRODUCT], ['purchase_options', 'default', 'value' => self::PURCHASE_OPTIONS_CART | self::PURCHASE_OPTIONS_INQUIRE], /** * Custom validations * A rule must specify both attribute names and validator type */ [['template'], 'validateTemplateByType'], [['meta_description'], 'summaryLength'], //[['price'], 'validateMoney', 'skipOnError' => true],// TODO [['purchaseOptionsArray'], 'validatePurchaseOptions'],// Handled by getter and setter /** * Validation messages within form */ [['price'], 'match', 'pattern' => '/^\d+(\.\d{1,2})?$/', 'message' => \Yii::t('app', 'The price must be a valid decimal number with up to two decimal places.') ], [['price'], 'number', 'min' => 2.00, 'max' => 5000000.00, 'message' => \Yii::t('app', 'The price must be a valid number between $2.00 and $5,000,000.00.') ], [['product_image_one', 'product_image_two', 'product_image_three'], 'url', 'skipOnEmpty' => true, 'message' => \Yii::t('app', 'Product Image URL is not valid.')], /** * Relationships */ ['category_id', 'exist', 'skipOnEmpty' => false, 'skipOnError' => true, 'targetClass' => ContentCategory::class, 'targetAttribute' => ['category_id' => 'id'], 'message' => \Yii::t('app', 'Please select a valid category.')], ['created_by', 'exist', 'skipOnError' => true, 'targetClass' => User::class, 'targetAttribute' => ['created_by' => 'id']], ['updated_by', 'exist', 'skipOnError' => true, 'targetClass' => User::class, 'targetAttribute' => ['updated_by' => 'id']], ]; $rulesByScenario = [ /** * Post + exhibition requires start and end date maybe (example) */ 'post_exhibition' => [ [['start_date', 'end_date'], 'required'], ], /** * Product specific validations */ 'product_artwork' => [ [['artist', 'price', 'purchase_options', 'quantity', 'product_image_one'], 'required'], ], 'product_item' => [ [['price', 'quantity', 'purchase_options', 'product_image_one'], 'required'], ], ]; /** * Merge rules: rules + scenario rules if any * * Note: array_merge function will append the scenario rules to the base rules, but it * doesn't handle potential conflicts or overwriting of rules. */ $mergedRules = array_merge($rules, $rulesByScenario[$this->scenario] ?? []); //\yii\helpers\VarDumper::dump($mergedRules, 10, true);// TODO Debug scenarios tool return $mergedRules; } public function validateTemplateByType($attribute, $params = []): void { // Can't validate without type set if (!$this->type) { return; } // @see below for getAllowedTemplates(); $allowedTemplates = $this->getAllowedTemplates(); if ($this->$attribute !== null && !in_array($this->$attribute, $allowedTemplates, true)) { $this->addError( $attribute, \Yii::t('app', 'The selected template "{template}" is not allowed for this category.', [ 'template' => $this->$attribute ]) ); return; } } public function beforeValidate(): bool { if (!parent::beforeValidate()) { return false; } // ...custom code here... /** * Set scenario automatically based on `type` and `template` to ensure validation * rules apply correctly. */ if ($this->type && $this->template) { // Construct the combined scenario name by concatenating type and template with an underscore // For example: 'product_artwork', 'post_exhibition' $combinedScenario = $this->type . '_' . $this->template; // Check if scenario exists: use combined, else fallback to type or 'default' if (isset($this->scenarios()[$combinedScenario])) { // If the combined scenario exists, set it as the current scenario $this->setScenario($combinedScenario); } // If combined scenario does not exist, check if a scenario matching just the type exists elseif (isset($this->scenarios()[$this->type])) { // Set the scenario to the type-only scenario (e.g., 'product' or 'post') $this->setScenario($this->type); } // If neither combined nor type-only scenario exists, else { // Fallback to a default scenario to prevent validation errors $this->setScenario('default'); } } // If only 'type' is set (no template) elseif ($this->type) { // Set the scenario to the type scenario $this->setScenario($this->type); } // If neither 'type' nor 'template' is set, else { // Set a generic default scenario so validation can still proceed without errors $this->setScenario('default'); } return true; } public function getAllowedTemplates(): array { // Check if the category relation is loaded and has allowed templates if ($this->category && $this->category->getAllowedTemplates()) { return $this->category->getAllowedTemplates(); } // fallback to global allowed templates by 'type' return self::$allowedTemplatesByType[$this->type] ?? []; } /** * Returns the allowed templates for a given content type statically. * @param int|string $type * @return array * * Use this method when you want the list of allowed templates for a specific * content type without needing an instance of Content. * Example usage: * * print_r(Content::getAllowedTemplatesByType(ContentCategory::TYPE_POST)); * // Output: ['article', 'exhibition', 'artist', 'catalog'] * * print_r(Content::getAllowedTemplatesByType('post')); * // Output: ['article', 'exhibition', 'artist', 'catalog'] * * print_r(Content::getAllowedTemplatesByType('PRODUCT')); * // Output: ['item', 'artwork', 'exhibition', 'catalog'] */ public static function getAllowedTemplatesByType(int|string $type): array { if (is_string($type)) { $type = strtolower($type);// normalize if (isset(self::$typeMap[$type])) { $type = self::$typeMap[$type]; } else { // Unknown string type, return empty or error as you prefer return []; } } return self::$allowedTemplatesByType[$type] ?? []; } /** * Returns the entire mapping of content types to their allowed templates. * @return array * * Use when you want all allowed templates grouped by type. * Example usage: * * $allTemplates = Content::getAllAllowedTemplates(); * * Result: * [ * 'post' => ['article', 'exhibition', 'artist', 'catalog'], * 'product' => ['item', 'artwork', 'exhibition', 'catalog'], * ] */ public static function getAllAllowedTemplates(): array { return self::$allowedTemplatesByType; } /** * Returns a key-value list mapping template keys to their human-friendly labels. * @return array Associative array of template keys and their labels. * * This is useful for generating dropdown lists, checkbox lists, or for displaying * template labels in views. * * Example usage: * * $templateOptions = Content::getTemplateList(); * * Result: * [ * 'item' => 'Item', * 'artwork' => 'Artwork', * 'article' => 'Article', * ... * ] */ public static function getTemplateList(): array { $templates = self::$templates; // Use keys and values the same or map them to friendly labels $labels = [ 'item' => \Yii::t('app', 'Item'), 'artwork' => \Yii::t('app', 'Artwork'), 'article' => \Yii::t('app', 'Article'), 'exhibition' => \Yii::t('app', 'Exhibition'), 'artist' => \Yii::t('app', 'Artist'), 'catalog' => \Yii::t('app', 'Catalog'), ]; $list = []; foreach ($templates as $template) { $list[$template] = $labels[$template] ?? ucfirst($template); } return $list; } - Assistant