Untitled conversation
- User
class ContentController extends BaseController { public function actionCreate(): Response|string { $model = new Content(); if (!$model) { throw new YiiWebNotFoundHttpException(\Yii::t('app', 'Content not found')); } // Get category options early for category type map etc. $data = $this->getCategoryOptions(true); // For actionCreate only! Assign a default category_id if none is set (e.g. first in dropdown) if (!$model->category_id && !empty($data['categoryOptions'])) { reset($data['categoryOptions']); $defaultCategoryId = key($data['categoryOptions']); $model->category_id = $defaultCategoryId; } $session = \Yii::$app->session; $request = \Yii::$app->request; if ($this->_debugMode) { LogHelper::debug('POST data (before load): ' . json_encode($request->post()), [ 'post data' => json_encode($request->post()), 'method' => __METHOD__ ]); } if ($request->isPost) //if (($request->isPost) && ($model->load($request->post()) && $model->validate())) { if ($this->_debugMode) { // Should be empty on create LogHelper::debug('Model and POST data after loading:', [ 'model_attributes_json' => json_encode($model->attributes), 'model_attributes_array' => $model->getAttributes(), 'post_data' => $request->post(), 'method' => __METHOD__, ]); } // Load and validate using the assignScenarioThenLoad() $postData = $request->post('Content', []); if ($this->assignScenarioThenLoad($model, $postData, $data['categoryTypeMap'] ?? [])) { if ($this->_debugMode) { LogHelper::debug("Content update scenario and key attributes after scenario set", [ 'type' => $model->type, 'scenario' => $model->getScenario(), 'combinedScenario' => $combinedScenario, 'allScenarios' => implode(', ', array_keys($scenarios)), 'attributes' => $model->getAttributes(), 'keyAttributes' => [ 'type' => $model->type, 'template' => $model->template, 'category_id' => $model->category_id, 'price' => $model->price, 'purchase_options' => $model->purchase_options, 'quantity' => $model->quantity, // Add more if needed ], 'method' => __METHOD__, ]); } if ($model->validate()) { if ($model->save()) { if ($this->_debugMode) { LogHelper::debug('Saved content ID: ' . $model->id, [ 'model ID' => $model->id, //'price' => $model->price,// etc 'method' => __METHOD__ ]); //$model->refresh(); } $session->setFlash('success', \Yii::t('app', 'Created successfully.')); return $this->redirect(['view', 'id' => $model->id]); } } else { if ($this->_debugMode) { LogHelper::debug("Validation errors:\n" . print_r($model->errors, true), [ 'errors' => print_r($model->errors, true), 'method' => __METHOD__ ]); } } } } else { // Pre-populate default data $model->loadDefaultValues(); } // Gather categoryTemplatesMap and categoryTypeMap data $allowedTemplatesJson = Json::encode($data['categoryTemplatesMap'] ?? []); $categoryTypeMapJson = Json::encode($data['categoryTypeMap'] ?? []); // For actionCreate only! Set current template and type JS vars from model (category_id already set!) $currentTemplateJs = Json::encode($model->template ?? ''); $currentTypeJs = Json::encode( $data['categoryTypeMap'][$model->category_id] ?? null ); // Render JS with updated values $this->renderJS($allowedTemplatesJson, $categoryTypeMapJson, $currentTemplateJs, $currentTypeJs); return $this->render('create', [ 'model' => $model, 'allowedTemplatesByType' => Content::getAllAllowedTemplates(), 'categoryOptions' => $data['categoryOptions'], 'categoryTypeMap' => $data['categoryTypeMap'], 'contentSummaryLength' => $this->_contentSummaryLength, 'mediaBlogImageRecSize' => $this->_mediaBlogImageRecSize, 'mediaProductImageRecSize' => $this->_mediaProductImageRecSize, ]); } public function actionUpdate(int $id): Response|string { $model = $this->findModel($id); // Early get category options for JS and form rendering $data = $this->getCategoryOptions(true); // Assign a default category_id if none is set (e.g. first in dropdown) if (!$model->category_id && !empty($data['categoryOptions'])) { reset($data['categoryOptions']); $defaultCategoryId = key($data['categoryOptions']); $model->category_id = $defaultCategoryId; } $session = \Yii::$app->session; $request = \Yii::$app->request; if ($this->_debugMode) { LogHelper::debug('POST data (before load): ' . json_encode($request->post()), [ 'post data' => json_encode($request->post()), 'method' => __METHOD__ ]); } if ($request->isPost) //if (($request->isPost) && ($model->load($request->post()) && $model->validate())) { if ($this->_debugMode) { // Should be empty on create LogHelper::debug('Model and POST data after loading:', [ 'model_attributes_json' => json_encode($model->attributes), 'model_attributes_array' => $model->getAttributes(), 'post_data' => $request->post(), 'method' => __METHOD__, ]); } // Load and validate using the assignScenarioThenLoad() $postData = $request->post('Content', []); if ($this->assignScenarioThenLoad($model, $postData, $data['categoryTypeMap'] ?? [])) { if ($this->_debugMode) { LogHelper::debug("Content update scenario and key attributes after scenario set", [ 'type' => $model->type, 'scenario' => $model->getScenario(), 'combinedScenario' => $combinedScenario, 'allScenarios' => implode(', ', array_keys($scenarios)), 'attributes' => $model->getAttributes(), 'keyAttributes' => [ 'type' => $model->type, 'template' => $model->template, 'category_id' => $model->category_id, 'price' => $model->price, 'purchase_options' => $model->purchase_options, 'quantity' => $model->quantity, // Add more if needed ], 'method' => __METHOD__, ]); } if ($model->validate()) { if ($model->save()) { if ($this->_debugMode) { LogHelper::debug('Saved content ID: ' . $model->id, [ 'model ID' => $model->id, //'price' => $model->price,// etc 'method' => __METHOD__ ]); //$model->refresh(); } $session->setFlash('success', \Yii::t('app', 'Updated successfully.')); return $this->redirect(['view', 'id' => $model->id]); } } else { if ($this->_debugMode) { LogHelper::debug("Validation errors:\n" . print_r($model->errors, true), [ 'errors' => print_r($model->errors, true), 'method' => __METHOD__ ]); } } } } // Gather categoryTemplatesMap and categoryTypeMap data $allowedTemplatesJson = Json::encode($data['categoryTemplatesMap'] ?? []); $categoryTypeMapJson = Json::encode($data['categoryTypeMap'] ?? []); // For actionCreate only! Set current template and type JS vars from model (category_id already set!) $currentTemplateJs = Json::encode($model->template ?? ''); $currentTypeJs = Json::encode( $data['categoryTypeMap'][$model->category_id] ?? null ); // Render JS with updated values $this->renderJS($allowedTemplatesJson, $categoryTypeMapJson, $currentTemplateJs, $currentTypeJs); return $this->render('create', [ 'model' => $model, 'allowedTemplatesByType' => Content::getAllAllowedTemplates(), 'categoryOptions' => $data['categoryOptions'], 'categoryTypeMap' => $data['categoryTypeMap'], 'contentSummaryLength' => $this->_contentSummaryLength, 'mediaBlogImageRecSize' => $this->_mediaBlogImageRecSize, 'mediaProductImageRecSize' => $this->_mediaProductImageRecSize, ]); } private function assignScenarioThenLoad(Content $model, array $postData, array $categoryTypeMap): bool { // Extract category_id and template from posted data $categoryId = $postData['category_id'] ?? null; $template = $postData['template'] ?? null; // Determine the content type based on the category ID $type = $categoryTypeMap[$categoryId] ?? null; // Assign to model $model->type = $type; $model->template = $template; // Determine scenario based on type and template $typeKey = $model->type ?: 'default'; $combinedScenario = $typeKey . '_' . $model->template; $scenarios = $model->scenarios(); if (isset($scenarios[$combinedScenario])) { $model->setScenario($combinedScenario); } elseif (isset($scenarios[$typeKey])) { $model->setScenario($typeKey); } else { $model->setScenario('default'); } // Load the model with POST data return $model->load($postData); } private function getCategoryOptions(bool $includeTypeMap = true): array { $categories = ContentCategory::find()->all(); if (!$categories) { return [ 'categoryOptions' => [], 'categoryTypeMap' => $includeTypeMap ? [] : null, 'categoryTemplatesMap' => $includeTypeMap ? [] : null, ]; } // Build hierarchical and flat category list $hierarchicalCategories = ContentCategory::structureCategories($categories); $flatCategories = ContentCategory::flattenCategoriesDropdown($hierarchicalCategories); if (!is_array($flatCategories)) { $flatCategories = []; } // Map integer type IDs to string keys expected in JS/toggle logic $typeLabels = [ ContentCategory::TYPE_POST => 'post', ContentCategory::TYPE_PRODUCT => 'product', // Add other type mappings as needed ]; $categoryTypeMap = null; $categoryTemplatesMap = null; if ($includeTypeMap) { // Build categoryTypeMap and categoryTemplatesMap with type strings (not numeric IDs) $categoryTypeMap = []; $categoryTemplatesMap = []; foreach ($categories as $category) { $categoryTypeMap[$category->id] = $typeLabels[$category->type] ?? null; $allowedTemplates = $category->getAllowedTemplates(); if (empty($allowedTemplates)) { // fallback to global allowed templates by type $typeKey = $categoryTypeMap[$category->id] ?? ''; $allowedTemplates = Content::getAllowedTemplatesByType($typeKey); } $categoryTemplatesMap[$category->id] = $allowedTemplates; } } return [ 'categoryOptions' => $flatCategories, 'categoryTypeMap' => $categoryTypeMap, 'categoryTemplatesMap' => $categoryTemplatesMap, ]; } protected function findModel(int $id): Content { if ($this->_isGuest) { return $this->goHome(); } $model = Content::find()->id($id)->one(); if ($model !== null) { return $model; } //throw new YiiWebNotFoundHttpException(ErrorMessageHelper::badRequest()); throw new YiiWebNotFoundHttpException( \Yii::t('app', 'No Content found with `{value}`', ['value' => $id]) ); } private function renderJS( string $allowedTemplatesJson, string $categoryTypeMapJson, string $currentTemplateJs, string $currentTypeJs ): void { $uniqueId = uniqid('', false);// Create 13-char unique string based on time $cacheKey = $this->_cacheKeyPrefix . $uniqueId . '_js_block_'; $jsBlock = $this->getCachedJsBlock($cacheKey, function () use ( $allowedTemplatesJson, $categoryTypeMapJson, $currentTemplateJs, $currentTypeJs ) { /** * JavaScript * CSS Classes to control field visibility: * - Apply the class `.field-type-{type}` to all form fields shown for a specific content type, * for example `.field-type-post` or `.field-type-product`. * - Apply the class `.field-template-{template}` to all form fields shown for a specific template, * for example `.field-template-artwork` or `.field-template-exhibition`. * - Apply the class `.field-type-template-{type}-{template}` to form fields that should only be * visible for the combined content type and template, for example `.field-type-template-product-artwork`. * * Examples: * Shows 'start_date' field only if content type is 'post': * * <?= $form->field($model, 'start_date', ['options' => ['class' => 'field-type-post']]); ?> * * Shows 'end_date' field only if template is 'exhibition' (regardless of type): * * <?= $form->field($model, 'end_date', ['options' => ['class' => 'field-template-exhibition']]); ?> * * Shows 'artist' field only if content type is 'product' and template is 'artwork': * * <?= $form->field($model, 'artist', ['options' => [ * 'class' => 'field-type-product field-template-artwork field-type-template-product-artwork' * ]]); ?> */ return <<<js (function(\$) { \$(function() { /* Map: category ID => array of allowed templates for that category e.g. { "1": ["article", "exhibition"], "2": ["item", "artwork"] } */ var categoryTemplatesMap = $allowedTemplatesJson; /* Map: category ID => content type string ('post', 'product', etc.) e.g. { "1": "post", "2": "product" } */ var categoryTypeMap = $categoryTypeMapJson; /* Initialize current template and type from PHP passed values, with fallback values */ var currentTemplate = $currentTemplateJs || ''; var currentType = $currentTypeJs || null; var \$category = \$('#content-category'); var \$template = \$('#content-template'); /* Given a category ID, return the content type as string ("post", "product", etc) */ function getTypeForCategory(catId) { /* JSON keys are strings */ catId = String(catId); return categoryTypeMap.hasOwnProperty(catId) ? categoryTypeMap[catId] : null; } /* Update template dropdown options based on category ID's allowed templates */ function updateTemplateOptions(catId) { var templates = categoryTemplatesMap[catId] || []; \$template.empty(); if (templates.length === 0) { /* No valid templates: disable dropdown and prompt user */ \$template.append(\$('<option>').val('').text('Select a template')); \$template.prop('disabled', true); } else { /* Populate dropdown with templates, label capitalized for user friendliness */ \$.each(templates, function(i, val) { var label = val.charAt(0).toUpperCase() + val.slice(1); \$template.append(\$('<option>').val(val).text(label)); }); \$template.prop('disabled', false); } /* Set the current template if it is present in the new options, else default to first option Array.prototype.includes is ES6+ */ if (\$.inArray(currentTemplate, templates) !== -1) { \$template.val(currentTemplate); } else { \$template.val(templates[0] || ''); } } /* Show/hide form fields based on the current type and template using class conventions */ function toggleFields(type, template) { /*console.log('toggleFields called with:', type, template);*/ /* Hide all fields that are tagged by any type or template CSS classes */ \$('[class*="field-type-"]').hide(); \$('[class*="field-template-"]').hide(); \$('[class*="field-type-template-"]').hide(); /* Show all fields matching current type e.g., '.field-type-post' */ if (type) { \$('.field-type-' + type).show(); } /* Show all fields matching current template e.g., '.field-template-artwork' */ if (template) { \$('.field-template-' + template).show(); } /* Show fields that require both specific type and template, e.g., '.field-type-template-product-artwork' */ if (type && template) { \$('.field-type-template-' + type + '-' + template).show(); } } /* Initialization on page load: */ var initialCategoryId = \$category.val(); var initialType = getTypeForCategory(initialCategoryId) || currentType; if (!categoryTemplatesMap || Object.keys(categoryTemplatesMap).length === 0 || !initialCategoryId) { /* No categories/templates data available OR no category selected: disable template dropdown & hide fields */ \$template.empty() .append(\$('<option>').val('').text('Select a category first')) .prop('disabled', true); toggleFields(null, null); } else { /* Otherwise, fill templates for selected category and toggle fields accordingly */ updateTemplateOptions(initialCategoryId); var initialTemplate = \$template.val(); toggleFields(initialType, initialTemplate); } /* Event handler: when category selection changes, update type and templates accordingly */ \$category.on('change', function() { var catId = \$(this).val(); /*console.log('Category changed to:', catId); console.log('Allowed templates:', categoryTemplatesMap[catId]); console.log('Current template before update:', currentTemplate);*/ var type = getTypeForCategory(catId); if (!catId || !type) { /* No valid category or type: disable templates, hide all fields */ \$template.empty() .append($('<option>').val('').text('Select a category first')) .prop('disabled', true); toggleFields(null, null); return; } /* Update globals so changes are tracked for template changes as well */ currentType = type; updateTemplateOptions(catId); currentTemplate = \$template.val(); toggleFields(currentType, currentTemplate); }); /* Event handler: when template selection changes, toggle fields based on new template */ \$template.on('change', function() { var template = \$(this).val(); var type = getTypeForCategory(\$category.val()) || currentType; toggleFields(type, template); /* track current template for persistence */ currentTemplate = template; }); }); })(jQuery); js; }); $this->view->registerJs($jsBlock, View::POS_END); } } - Assistant
- User
"purchase_options gets set to a numeric value (3) correctly (derived from purchaseOptionsArray?), but not other attributes like price or quantity." only handles how items can be bought, its array for checkboxes.
- Assistant
- User
- Assistant
- User
xplanation why price and quantity not loaded in post_artwork scenario Look at 'post_artwork' scenario: 'post_artwork' => array_merge($baseAttributes, [ 'artist', 'dimensions', 'medium', 'year', 'quantity', 'product_image_one', 'product_image_two', 'product_image_three', ]), price is missing here. So if your controller sets scenario 'post_artwork', then: Posted price will not be assigned, because it is not in the safe attributes list. quantity is in this scenario, so it should be loaded, but your logs show it's null. This suggests the scenario assigned at runtime might not match what you expect, or the type is different.Thiers a difference between post_artwork and product_artwork
- Assistant
- User
Example mismatch explanation In controller: $typeKey = $model->type ?: 'default'; // $model->type is a number (e.g., 1 or 2) $combinedScenario = $typeKey . '_' . $model->template; // e.g. '1_artwork' $scenarios = $model->scenarios(); Your model's scenarios() keys are: Numeric keys: 1 for ContentCategory::TYPE_POST (say) String keys: 'post_artwork' But the $combinedScenario will be like '1_artwork' (because $typeKey is a number), which does not match 'post_artwork'. Hence: $scenarios['1_artwork'] does not exist, and so it'll fallback to $scenarios[1]. $scenarios[1] has base attributes but no price or other template-specific attributes.maybe this is the main issue.. having int and string for some reason
- Assistant
- User
perhaps i should restore these
protected static array $allowedTemplatesByType = [ ContentCategory::TYPE_POST => ['article', 'artwork', 'exhibition', 'artist', 'catalog'], ContentCategory::TYPE_PRODUCT => ['artwork', 'exhibition', 'item', 'catalog'], //ContentCategory::TYPE_CATALOG => [],// no templates or as needed ]; /** * Map string keys to ContentCategory constants * @return array */ protected static array $typeMap = [ 'post' => ContentCategory::TYPE_POST, 'product' => ContentCategory::TYPE_PRODUCT, // 'catalog' => ContentCategory::TYPE_CATALOG, ];and just change $allowedTemplatesBy... and add the name 'post and 'product' instead of cententCategory that is int from consts
- Assistant
- User
Example in getCategoryOptions(): $typeLabels = [ ContentCategory::TYPE_POST => 'post', ContentCategory::TYPE_PRODUCT => 'product', ]; $categoryTypeMap = []; foreach ($categories as $category) { $categoryTypeMap[$category->id] = $typeLabels[$category->type] ?? null; }Why cant this use:
protected static array $typeMap = [ 'post' => ContentCategory::TYPE_POST, 'product' => ContentCategory::TYPE_PRODUCT, // 'catalog' => ContentCategory::TYPE_CATALOG, ]; - Assistant
- User
Bonus tip: For DB storage (if your type column is int) Use getters/setters or enum-casting to map the string value post <=> int 1 transparently. For example, in your ActiveRecord model: public function getType(): ?string { return array_search($this->getAttributes()['type'], self::$typeMap, true) ?: null; } public function setType(string $value): void { $this->setAttribute('type', self::$typeMap[$value] ?? null); } This way your model's $type property is always string 'post', 'product' for usage in forms and scenarios, and gets properly stored as int in DB.its set as a string
- Assistant
- User
ahh i was wrong...
'type' => $this->integer()->notNull()->defaultValue(1),// Post = 1, Product = 2, Catalog = 3
- Assistant
- User
Example getter/setter for type attribute in your model // Map strings to integers (for saving to DB) protected static array $typeMap = [ 'post' => ContentCategory::TYPE_POST, // 1 'product' => ContentCategory::TYPE_PRODUCT, // 2 // ... ]; // Map integers to strings (for reading from DB) protected static array $typeLabels = [ ContentCategory::TYPE_POST => 'post', ContentCategory::TYPE_PRODUCT => 'product', // ... ]; /** * Override getter to return string type */ public function getType(): ?string { $intType = $this->getAttribute('type'); // integer from DB return self::$typeLabels[$intType] ?? null; } /** * Override setter to accept string type and store int */ public function setType(string $value): void { if (isset(self::$typeMap[$value])) { $this->setAttribute('type', self::$typeMap[$value]); } else { $this->setAttribute('type', null); } }how are these being used?
- Assistant
- User
can you write comments explaining this for these new functions
- Assistant
- User
what was that debugging code you suggested?
- Assistant
The debugging code I suggested is a Yii debug log inside your
assignScenarioThenLoad()method that helps verify which scenario is being set and which attributes are safe to be loaded. This is crucial to understand why some attributes may not be assigned from POST.Here’s the snippet with comments and usage:
- User
- Assistant
- User
- Assistant
- User
public function beforeValidate(): bool { if (!parent::beforeValidate()) { return false; }
if ($this->price === '') { $this->price = null; } if ($this->quantity === '') { $this->quantity = null; } // ...existing code... // rest of your beforeValidate() // ...}
for all of them?
- Assistant
Yes, it’s a good idea to normalize all attributes that can be submitted as empty strings but should be stored as
nullwhen empty, especially for fields that are numerical or nullable in the DB.
What attributes typically benefit from this?
- User
- Assistant