return <<<JS
(function(\$)
{
\$(function()
{
var categoryTypeMap = $categoryTypeMapJson;
var categoryTemplatesMap = $allowedTemplatesJson;
var currentTemplate = $currentTemplateJs || '';
var currentType = $currentTypeJs || '';
var categoryRequiredFieldsMap = $categoryRequiredFieldsMapJson;
var \$category = $('#content-category');
var \$template = $('#content-template');
var \$type = \$('#content-type');
var \$form = \$('#content-form');
/* Sync 'type' hidden input with category selection */
function syncType()
{
var selectedCat = \$category.val();
var mappedType = categoryTypeMap[selectedCat] || null;
\$type.val(mappedType);
}
/* Populate template dropdown based on allowed templates for selected category */
function updateTemplateOptions(catId)
{
var templates = categoryTemplatesMap[catId] || [];
/* When updating template dropdown options */
\$template.empty();
if (templates.length)
{
templates.forEach(function(t)
{
/* Capitalize first letter for display */
\$template.append($('<option>').val(t).text(t.charAt(0).toUpperCase() + t.slice(1)));
});
\$template.prop('disabled', false);
if (!templates.includes(\$template.val()))
{
\$template.val(templates[0]).trigger('change');
}
}
else
{
\$template.append($('<option>').val('').text('Select a category first'));
\$template.prop('disabled', true);
}
}
/* Toggle visibility of form fields based on type/template CSS classes */
function toggleFields(type, template)
{
\$('[class*="field-type-"]').hide();
\$('[class*="field-template-"]').hide();
\$('[class*="field-type-template-"]').hide();
if (type)
{
\$('.field-type-' + type).show();
}
if (template)
{
\$('.field-template-' + template).show();
}
if (type && template)
{
\$('.field-type-template-' + type + '-' + template).show();
}
}
/* Clear and reset newly required fields values, and trigger validation on them */
function resetAndValidateFields(requiredFields)
{
requiredFields.forEach(function(field)
{
var \$field = \$form.find('[name="Content[' + field + ']"]');
if (\$field.length)
{
\$field.val('');
\$form.yiiActiveForm('validateAttribute', \$field.attr('id'));
}
});
}
function updateRequiredFields(catId, template)
{
var requiredFields = [];
if (categoryRequiredFieldsMap[catId] && categoryRequiredFieldsMap[catId][template])
{
requiredFields = categoryRequiredFieldsMap[catId][template];
}
resetAndValidateFields(requiredFields);
}
/* Bind events for category and template changes */
\$category.on('change', function()
{
syncType();
updateTemplateOptions(\$category.val());
toggleFields(\$type.val(), \$template.val());
updateRequiredFields(\$category.val(), \$template.val());
/**
* Optional: you can trigger validation manually on category/template change
* e.g., Yii ActiveForm validation for 'type' field:
* $('#content-form').yiiActiveForm('validateAttribute', 'content-type');
*/
});
\$template.on('change', function()
{
toggleFields(\$type.val(), \$template.val());
updateRequiredFields(\$category.val(), \$template.val());
});
/* Initial setup on page load */
syncType();
updateTemplateOptions(\$category.val());
toggleFields(\$type.val(), \$template.val())
});
})(jQuery);
JS;
so when i go to update the activeRecord.. the template is not defined, but if its a old record, it should be
Assistant
Your JavaScript code snippet you posted is for dynamically updating form fields and syncing template/type selections on the client side. You mentioned that when updating an ActiveRecord, the template is not defined, but for old records, it should be.
This sounds like a server-side problem where the PHP variables $currentTemplateJs or $currentTypeJs are either empty or not properly passed into the JS when editing an existing record.
Hypotheses / Problems
currentTemplateJs/currentTypeJs are empty or null during the page render for the update form.
Data is fetched properly for old records but not for new or updated records.
JSON encoding or escaping might be causing the variable to be invalid in JS output.
What to check / fix:
1. Confirm $currentTemplateJs and $currentTypeJs server-side variables
Make sure in your PHP or view file you are initializing these variables properly before echoing the JS.
var currentTemplate = "blog";
var currentType = "post";
if $model->template is "blog" and type is "post".
Why template might be undefined in JS or your update form
Are you sure $model->template has a value at the moment the view is rendered?
Is the template attribute actually set or loaded in your $model?
Could it be that $model->template is empty for new records, and this makes the dropdown default to the first option (and the template variable is empty)?
Debugging steps and advice
Check $model->template value
Add a temporary debug line in your view before rendering the JS:
php
<?php var_dump($model->template); ?>
Make sure it outputs the expected value.
Ensure the template dropdown updates selecting the existing value
Your JS code does not explicitly set the template dropdown value on page load if it exists, except in the following snippet:
js
updateTemplateOptions($category.val());
In your current updateTemplateOptions, the template dropdown options are populated, but selection logic only falls back to first template if existing template is not found.
Here's the key point: You need to tell updateTemplateOptions() to prefer selecting the existing currentTemplate.
Suggested fix for updateTemplateOptions function
User
Could it be that $model->template is empty for new records, and this makes the dropdown default to the first option (and the template variable is empty)?
its only empty on new recorders, thats it. its requrired
Assistant
Exactly — that's expected behavior.
Explanation:
For new records, $model->template is empty because the user hasn't chosen a template yet.
Your JS then populates the template dropdown with options for the selected category.
Since currentTemplate is empty (''), your current JS picks the first template option (or none), and template variable is effectively empty or default.
For existing records (update form), $model->template is set, so your JS can pick and select the correct option corresponding to that template.
Why this matters
When $model->template is empty (new record), the dropdown must force the user to pick a template from the allowed list.
In this case, the first option in the dropdown will often be auto-selected, which is usually the expected user experience.
For new records, template JS variable being empty is correct initially — user input is required to fill it.
For update forms, your current logic properly preselects existing template.
How to enforce required templates and distinguish new vs update
1. Server side:
Make sure your model validation requires template field:
php
[['template'], 'required'],
This ensures server-side validation complains if template is empty on new record saves.
2. Client-side:
If you want stricter user experience on new records, you can:
Add a "Select template" disabled placeholder option at the top for new records.
Prevent form submission until user picks a valid template.
Example:
js
User
I ALREADY SAID.. WHEN I GO TO UPDATE A RECORDER.. THE TEMPLATE THAT IS SAVED SHOULD BE SET IN THE DROPDOWN.. BUT ITS NOT...
code
<div class="col-md-6 mb-2">
<?php
// Based on current type, get allowed templates list
$templatesForCurrentType = [];
if ($currentType !== null && isset($allowedTemplatesByType[$currentType]))
{
$templatesForCurrentType = $allowedTemplatesByType[$currentType];
}
// $allTemplates is full list of [template_key => label]
$allTemplates = Content::getTemplateList();
// Filter all templates by allowlist for current type
$allowedTemplatesListForType = array_intersect_key($allTemplates, array_flip($templatesForCurrentType ?? []));
echo $form->field($model, 'template')->dropDownList(
$allowedTemplatesListForType ?: [],
[
'id' => 'content-template',
'disabled' => empty($currentType),// optional: disable if no valid type
'prompt' => Yii::t('app', 'Select a template'),
]
);
?>
</div><!-- .col-md-6 .mb-2 -->
Assistant
Thanks for the clarification and sharing your PHP form snippet. The issue is that the dropDownList options are only populated based on $currentType but your JS code populates allowed templates differently, specifically keyed per category in $categoryTemplatesMap.
What is going wrong?
On page load for update, the PHP code that builds the <select id="content-template"> options builds them only for the current $currentType templates.
But your JS updateTemplateOptions(categoryId)overwrites and replaces that dropdown options dynamically based on the category selected.
The PHP-rendered options and JS-generated options are out of sync unless the JS has the current template set and selected properly.
Moreover, because your options are dependent on $currentType (which is derived from $data['categoryTypeMap'][$model->category_id]) and can be empty initially, the PHP side might not render the full or correct option list.
How it should work, generally
PHP must render the template dropdown with all allowed options for the current record's category + type (for update form).
The correct <option> matching $model->template should be selected automatically by dropDownList().
The JS updateTemplateOptions()should only run on category changes — but on page load (update), you want the rendered options to be correct and have the correct current selected value.
OR the JS should on page load set the dropdown to the current template (which relies on JS variables properly set).
Your PHP code solves (1) and (2), assuming $currentType and $allowedTemplatesByType are correct.
Check:
Is $currentType correctly set on update (e.g. 'post' or 'product')? From your earlier PHP code:
But in view you use $currentType, you need to ensure $currentType is the string like 'post' to get allowed templates.
Is $allowedTemplatesByType[$currentType] returning the right array of template keys?
User
can you just give me the code to fix the issue.. the way you explain does not help
Assistant
Absolutely. Here's a straightforward fix you can apply to your PHP and JS code so that the saved template is correctly selected in the dropdown when updating a record.
PHP: Ensure $allowedTemplatesListForType includes the saved $model->template
php
<?php
// Assuming $currentType is set correctly (e.g. 'post', 'product')
$templatesForCurrentType = [];
if ($currentType !== null && isset($allowedTemplatesByType[$currentType])) {
$templatesForCurrentType = $allowedTemplatesByType[$currentType];
}
// Full template list [template_key => label]
$allTemplates = Content::getTemplateList();
// Filter allowed templates for the current type
$allowedTemplatesListForType = array_intersect_key($allTemplates, array_flip($templatesForCurrentType ?? []));
// Add the saved template forcibly if missing so it shows as selected
if (!empty($model->template) && !isset($allowedTemplatesListForType[$model->template]) && isset($allTemplates[$model->template])) {
$allowedTemplatesListForType[$model->template] = $allTemplates[$model->template];
}
// Sort to keep the list consistent (optional)
ksort($allowedTemplatesListForType);
echo $form->field($model, 'template')->dropDownList(
$allowedTemplatesListForType ?: [],
[
'id' => 'content-template',
'disabled' => empty($currentType),
'prompt' => Yii::t('app', 'Select a template'),
]
);
?>
JS: Modify updateTemplateOptions to keep saved template selected on page load
Add a flag so the first call only sets the value, but does not clear options on page load:
js
User
code
var isInitialLoad = true;
function updateTemplateOptions(catId)
{
var templates = categoryTemplatesMap[catId] || [];
if (isInitialLoad) {
// On initial page load, only select currentTemplate if present
if (currentTemplate && templates.includes(currentTemplate)) {
$template.val(currentTemplate).trigger('change');
}
isInitialLoad = false;
return;
}
// On category change: rebuild dropdown options
$template.empty();
if (templates.length) {
templates.forEach(function(t) {
$template.append($('<option>').val(t).text(t.charAt(0).toUpperCase() + t.slice(1)));
});
$template.prop('disabled', false);
if (currentTemplate && templates.includes(currentTemplate)) {
$template.val(currentTemplate);
} else {
currentTemplate = templates[0];
$template.val(currentTemplate);
}
$template.trigger('change');
}
else {
$template.append($('<option>').val('').text('Select a category first'));
$template.prop('disabled', true);
}
}
syncType();
updateTemplateOptions($category.val());
toggleFields($type.val(), $template.val());
can you add this into my pre-existing code? however you see fit
code
Assistant
Certainly! I've integrated the isInitialLoad flag and updated your existing updateTemplateOptions function so it will preserve the initially selected template on page load, and only replace the options on category change.
Here is your updated JavaScript part, ready to be injected via <<<JS ... JS syntax:
php
User
can I add class to this
for css
Assistant
Yes, you can add a CSS class to the widget's container or input by passing the appropriate options to the widget configuration.
Assuming TagsJQry::class is a Yii2 widget, you can usually pass options (for the input field) or containerOptions (for the container) to set HTML attributes including classes.
For example:
php
echo $form->field($model, 'tagNames')->widget(TagsJQry::class, [
'tags' => $model->tagNames,
'options' => ['class' => 'your-custom-class'], // Adds class to the input
// 'containerOptions' => ['class' => 'your-container-class'], // Adds class to outer container, if supported
]);
If TagsJQry supports these options, this will add CSS classes for styling.
Check the widget docs or code for exact option names if it’s a custom widget.
If you want to style the entire form group, you can also add a class to the field wrapper:
This applies the class to the div wrapping the input.
Summary:
Use 'options' => ['class' => 'your-class'] to add class to the input element generated by the widget.
Use 'containerOptions' => ['class' => 'your-class'] if the widget supports it for container wrapper.
Or, add 'options' => ['class' => 'your-class'] in field() config to add class to the field container div.
Let me know if you want me to help with specifics for your widget!
User
your suggested code to fix the template dropdown, removed a import function. When creating a new recorder, only the available options for the category appear for template. Now when I go to create new content, the category default is set, but the template dropdown list all options as if they are all available for that category and they are not.
Assistant
Thanks for the update. From your description, it sounds like after the JS fix I provided, on new record creation the template dropdown shows all templates rather than filtering to only the allowed ones for the selected category.
What likely happened
In your original JS, the updateTemplateOptions function rebuilds the template dropdown options based on the currently selected category.
My last suggested fix added the isInitialLoad flag and made the function skip repopulating options on first load, only selecting the template if possible — so that pre-existing PHP-rendered options stay.
That works well for updates because PHP correctly renders allowed templates based on category/type and preselects the saved template.
The problem now
For new records:
The server-side PHP dropdown may be rendered with all options (or a full list), because no initial category/type selection or filtering was performed.
Because on initial load the JS updateTemplateOptions returns early (due to isInitialLoad), it does not rebuild the dropdown options according to the selected category.
The template dropdown ends up with all templates shown instead of filtered per category.
How to fix this while keeping your update form working
We want:
On update, keep existing PHP dropdown options and select saved template (isInitialLoad skip repopulating).
On new record, force the dropdown options to be rebuilt on page load to reflect the selected category's templates.
How to distinguish new vs update record in JS?
Since you have currentTemplate set on update, but it's empty or falsy on new record, you can branch based on that:
(Note: Your updateTemplateOptions() clears the options and sets the first option by default. You may need to update it to check if the previously selected currentTemplate is part of the setting, and if so, select it.)
Suggested adjustments to your JS logic regarding the template value:
Modify updateTemplateOptions(catId) to:
js
function updateTemplateOptions(catId)
{
var templates = categoryTemplatesMap[catId] || [];
$template.empty();
if (templates.length)
{
templates.forEach(function(t)
{
$template.append($('<option>').val(t).text(t.charAt(0).toUpperCase() + t.slice(1)));
});
$template.prop('disabled', false);
// Select currentTemplate if exists in templates
if (currentTemplate && templates.includes(currentTemplate))
{
$template.val(currentTemplate);
}
else
{
$template.val(templates[0]);
currentTemplate = templates[0]; // update currentTemplate variable
}
$template.trigger('change');
}
else
{
$template.append($('<option>').val('').text('Select a category first'));
$template.prop('disabled', true);
}
}
Summary checklist:
Use PHP json_encode for passing PHP string variables into JS, e.g. $currentTemplateJs = json_encode($model->template ?? '');
Ensure $currentTypeJs is also encoded.
In JS, do not quote those variables again because json_encode already outputs quoted strings.
Fix updateTemplateOptions to select current template if it exists.
Run initial page load setup that respects existing record values.
If you provide more of your PHP code where these JS variables are set, I can tailor the advice further.
Example integration snippet in PHP view
php
<?php
// For example, in your view where this JS is rendered:
$currentTemplateJs = json_encode($model->template);
$currentTypeJs = json_encode($model->type);
$categoryTypeMapJson = json_encode($categoryTypeMap);
$allowedTemplatesJson = json_encode($allowedTemplates);
$categoryRequiredFieldsMapJson = json_encode($categoryRequiredFieldsMap);
?>
<script>
(function($) {
$(function() {
var categoryTypeMap = <?= $categoryTypeMapJson ?>;
var categoryTemplatesMap = <?= $allowedTemplatesJson ?>;
var currentTemplate = <?= $currentTemplateJs ?> || '';
var currentType = <?= $currentTypeJs ?> || '';
var categoryRequiredFieldsMap = <?= $categoryRequiredFieldsMapJson ?>;
var $category = $('#content-category');
var $template = $('#content-template');
var $type = $('#content-type');
var $form = $('#content-form');
function syncType() {
var selectedCat = $category.val();
var mappedType = categoryTypeMap[selectedCat] || null;
$type.val(mappedType);
}
function updateTemplateOptions(catId) {
var templates = categoryTemplatesMap[catId] || [];
$template.empty();
if (templates.length) {
templates.forEach(function(t) {
$template.append($('<option>').val(t).text(t.charAt(0).toUpperCase() + t.slice(1)));
});
$template.prop('disabled', false);
if (currentTemplate && templates.includes(currentTemplate)) {
$template.val(currentTemplate);
} else {
$template.val(templates[0]);
currentTemplate = templates[0];
}
$template.trigger('change');
} else {
$template.append($('<option>').val('').text('Select a category first'));
$template.prop('disabled', true);
}
}
function toggleFields(type, template) {
$('[class*="field-type-"]').hide();
$('[class*="field-template-"]').hide();
$('[class*="field-type-template-"]').hide();
if (type) {
$('.field-type-' + type).show();
}
if (template) {
$('.field-template-' + template).show();
}
if (type && template) {
$('.field-type-template-' + type + '-' + template).show();
}
}
function resetAndValidateFields(requiredFields) {
requiredFields.forEach(function(field) {
var $field = $form.find('[name="Content[' + field + ']"]');
if ($field.length) {
$field.val('');
$form.yiiActiveForm('validateAttribute', $field.attr('id'));
}
});
}
function updateRequiredFields(catId, template) {
var requiredFields = [];
if (categoryRequiredFieldsMap[catId] && categoryRequiredFieldsMap[catId][template]) {
requiredFields = categoryRequiredFieldsMap[catId][template];
}
resetAndValidateFields(requiredFields);
}
$category.on('change', function() {
syncType();
updateTemplateOptions($category.val());
toggleFields($type.val(), $template.val());
updateRequiredFields($category.val(), $template.val());
});
$template.on('change', function() {
toggleFields($type.val(), $template.val());
updateRequiredFields($category.val(), $template.val());
});
syncType();
updateTemplateOptions($category.val());
toggleFields($type.val(), $template.val());
});
})(jQuery);
</script>
If you implement above and still get issues, please provide the PHP snippet where you set these variables so I can inspect.
co
d
e
(
In your JS code, modify updateTemplateOptions(catId) as shown earlier to:
js
function updateTemplateOptions(catId)
{
var templates = categoryTemplatesMap[catId] || [];
$template.empty();
if (templates.length)
{
templates.forEach(function(t)
{
$template.append($('<option>').val(t).text(t.charAt(0).toUpperCase() + t.slice(1)));
});
$template.prop('disabled', false);
if (currentTemplate && templates.includes(currentTemplate))
{
$template.val(currentTemplate);
}
else
{
currentTemplate = templates[0];
$template.val(currentTemplate);
}
$template.trigger('change');
}
else
{
$template.append($('<option>').val('').text('Select a category first'));
$template.prop('disabled', true);
}
}
This explicitly sets the <select> value to the existing currentTemplate from PHP for edit forms.
Also check your HTML markup for the value of template
Make sure your HTML form field has the correct id="content-template" and the values of the options match keys like "blog", "news", etc.
Summary
You do pass the PHP values correctly to JS via json_encode.
You need to adjust the JS so that the existing $model->template (stored in currentTemplate) is selected in the dropdown.
If not selected, subsequent code (validations, toggling fields) may behave as if no template is selected, causing your update form issue.
Your updateTemplateOptionsmust prioritize currentTemplate value.
Let me know if you want me to prepare a full working snippet for you integrating the PHP and JS parts with these fixes!
function updateTemplateOptions(catId)
{
var templates = categoryTemplatesMap[catId] || [];
$template.empty();
if (templates.length)
{
// For new records, add a placeholder option 'Select template'
if (!currentTemplate) {
$template.append($('<option>').val('').text('Select a template').prop('disabled', true).prop('selected', true));
}
templates.forEach(function(t)
{
$template.append($('<option>').val(t).text(t.charAt(0).toUpperCase() + t.slice(1)));
});
$template.prop('disabled', false);
if (currentTemplate && templates.includes(currentTemplate))
{
$template.val(currentTemplate);
}
else if (currentTemplate) {
$template.val(currentTemplate);
}
else {
// For new records user must pick, so keep placeholder selected
$template.val('');
}
$template.trigger('change');
}
else
{
$template.append($('<option>').val('').text('Select a category first').prop('disabled', true).prop('selected', true));
$template.prop('disabled', true);
}
}
This will:
For new records: Show "Select a template" and prevent auto-selecting some existing template.
Force user to pick from options.
For existing records with currentTemplate: automatically select the right template.
Summary:
It's absolutely normal for $model->template to be empty on new records.
Your JS and server-side validation should handle this gracefully to prevent user confusion.
Make sure to add UI cues (placeholder option) so the user knows they need to select a template.
For old records, your existing code and currentTemplate logic already handles template selection correctly.
If you want, I can help you with a full updated JS snippet including this "select a template" placeholder logic or with Yii2 validation integration tips!
Problem: If $currentType is null or wrong, the dropdown will have no options.
Also, your dropdown has:
php
'prompt' => Yii::t('app', 'Select a template'),
so it renders a placeholder option at the top with empty value="".
Verify that $model->template is inside $templatesForCurrentType
If it is missing (edge case), the dropdown will not have the option — so it cannot be selected.
If that's a problem, you can forcibly add the saved template to the options:
php
if (!in_array($model->template, $templatesForCurrentType))
{
// Add the saved template forcibly to the allowed templates list
$templatesForCurrentType[] = $model->template;
}
On page load, your PHP has rendered the dropdown with correct options including the saved template selected.
JS updateTemplateOptions on first run just sets the selected template value (if it matches the allowed ones) but does not overwrite the options — preserving your PHP rendered dropdown.
When the user changes category, updateTemplateOptions actually rebuilds the template dropdown based on the new category's templates.
This fix ensures:
PHP supplies the correct options and selected template on page load.
JS picks that selected template properly and does not override options on page load.
JS fully rebuilds template dropdown only on category changes.
If you apply both of those changes exactly, your update form will show the saved template selected in the dropdown.
Let me know if you want me to give you a full integrated snippet too!
return <<<JS
(function(\$)
{
\$(function()
{
var categoryTypeMap = $categoryTypeMapJson;
var categoryTemplatesMap = $allowedTemplatesJson;
var currentTemplate = $currentTemplateJs || '';
var currentType = $currentTypeJs || '';
var categoryRequiredFieldsMap = $categoryRequiredFieldsMapJson;
var \$category = $('#content-category');
var \$template = $('#content-template');
var \$type = \$('#content-type');
var \$form = \$('#content-form');
/* Sync 'type' hidden input with category selection */
function syncType()
{
var selectedCat = \$category.val();
var mappedType = categoryTypeMap[selectedCat] || null;
\$type.val(mappedType);
}
/* Populate template dropdown based on allowed templates for selected category */
function updateTemplateOptions(catId)
{
var templates = categoryTemplatesMap[catId] || [];
/* When updating template dropdown options */
\$template.empty();
if (templates.length)
{
templates.forEach(function(t)
{
/* Capitalize first letter for display */
\$template.append($('<option>').val(t).text(t.charAt(0).toUpperCase() + t.slice(1)));
});
\$template.prop('disabled', false);
if (!templates.includes(\$template.val()))
{
\$template.val(templates[0]).trigger('change');
}
}
else
{
\$template.append($('<option>').val('').text('Select a category first'));
\$template.prop('disabled', true);
}
}
/* Toggle visibility of form fields based on type/template CSS classes */
function toggleFields(type, template)
{
\$('[class*="field-type-"]').hide();
\$('[class*="field-template-"]').hide();
\$('[class*="field-type-template-"]').hide();
if (type)
{
\$('.field-type-' + type).show();
}
if (template)
{
\$('.field-template-' + template).show();
}
if (type && template)
{
\$('.field-type-template-' + type + '-' + template).show();
}
}
/* Clear and reset newly required fields values, and trigger validation on them */
function resetAndValidateFields(requiredFields)
{
requiredFields.forEach(function(field)
{
var \$field = \$form.find('[name="Content[' + field + ']"]');
if (\$field.length)
{
\$field.val('');
\$form.yiiActiveForm('validateAttribute', \$field.attr('id'));
}
});
}
function updateRequiredFields(catId, template)
{
var requiredFields = [];
if (categoryRequiredFieldsMap[catId] && categoryRequiredFieldsMap[catId][template])
{
requiredFields = categoryRequiredFieldsMap[catId][template];
}
resetAndValidateFields(requiredFields);
}
/* Bind events for category and template changes */
\$category.on('change', function()
{
syncType();
updateTemplateOptions(\$category.val());
toggleFields(\$type.val(), \$template.val());
updateRequiredFields(\$category.val(), \$template.val());
/**
* Optional: you can trigger validation manually on category/template change
* e.g., Yii ActiveForm validation for 'type' field:
* $('#content-form').yiiActiveForm('validateAttribute', 'content-type');
*/
});
\$template.on('change', function()
{
toggleFields(\$type.val(), \$template.val());
updateRequiredFields(\$category.val(), \$template.val());
});
/* Initial setup on page load */
syncType();
updateTemplateOptions(\$category.val());
toggleFields(\$type.val(), \$template.val())
});
})(jQuery);
JS;
return <<<JS
(function(\$)
{
\$(function()
{
var categoryTypeMap = $categoryTypeMapJson;
var categoryTemplatesMap = $allowedTemplatesJson;
var currentTemplate = $currentTemplateJs || '';
var currentType = $currentTypeJs || '';
var categoryRequiredFieldsMap = $categoryRequiredFieldsMapJson;
var \$category = \$('#content-category');
var \$template = \$('#content-template');
var \$type = \$('#content-type');
var \$form = \$('#content-form');
var isInitialLoad = true;
/* Sync 'type' hidden input with category selection */
function syncType()
{
var selectedCat = \$category.val();
var mappedType = categoryTypeMap[selectedCat] || null;
\$type.val(mappedType);
}
/* Populate template dropdown based on allowed templates for selected category */
function updateTemplateOptions(catId)
{
var templates = categoryTemplatesMap[catId] || [];
if (isInitialLoad) {
// On initial page load, don't replace options; just select currentTemplate if present
if (currentTemplate && templates.includes(currentTemplate))
{
\$template.val(currentTemplate).trigger('change');
}
isInitialLoad = false;
return;
}
// On category change, rebuild dropdown options
\$template.empty();
if (templates.length)
{
templates.forEach(function(t)
{
// Capitalize first letter for display
\$template.append(\$('<option>').val(t).text(t.charAt(0).toUpperCase() + t.slice(1)));
});
\$template.prop('disabled', false);
if (currentTemplate && templates.includes(currentTemplate))
{
\$template.val(currentTemplate);
}
else
{
currentTemplate = templates[0];
\$template.val(currentTemplate);
}
\$template.trigger('change');
}
else
{
\$template.append(\$('<option>').val('').text('Select a category first'));
\$template.prop('disabled', true);
}
}
/* Toggle visibility of form fields based on type/template CSS classes */
function toggleFields(type, template)
{
\$('[class*="field-type-"]').hide();
\$('[class*="field-template-"]').hide();
\$('[class*="field-type-template-"]').hide();
if (type)
{
\$('.field-type-' + type).show();
}
if (template)
{
\$('.field-template-' + template).show();
}
if (type && template)
{
\$('.field-type-template-' + type + '-' + template).show();
}
}
/* Clear and reset newly required fields values, and trigger validation on them */
function resetAndValidateFields(requiredFields)
{
requiredFields.forEach(function(field)
{
var \$field = \$form.find('[name="Content[' + field + ']"]');
if (\$field.length)
{
\$field.val('');
\$form.yiiActiveForm('validateAttribute', \$field.attr('id'));
}
});
}
function updateRequiredFields(catId, template)
{
var requiredFields = [];
if (categoryRequiredFieldsMap[catId] && categoryRequiredFieldsMap[catId][template])
{
requiredFields = categoryRequiredFieldsMap[catId][template];
}
resetAndValidateFields(requiredFields);
}
/* Bind events for category and template changes */
\$category.on('change', function()
{
syncType();
updateTemplateOptions(\$category.val());
toggleFields(\$type.val(), \$template.val());
updateRequiredFields(\$category.val(), \$template.val());
/**
* Optional: you can trigger validation manually on category/template change
* e.g., Yii ActiveForm validation for 'type' field:
* \$('#content-form').yiiActiveForm('validateAttribute', 'content-type');
*/
});
\$template.on('change', function()
{
toggleFields(\$type.val(), \$template.val());
updateRequiredFields(\$category.val(), \$template.val());
});
/* Initial setup on page load */
syncType();
updateTemplateOptions(\$category.val());
toggleFields(\$type.val(), \$template.val());
});
})(jQuery);
JS;
How this solves your problem:
On page load, the dropdown options rendered by server are not replaced.
The saved currentTemplate will be selected if it exists in categoryTemplatesMap for the current category.
On category change, the dropdown options will be correctly rebuilt and the template updated accordingly.
Apply this code exactly and test your update form. Your saved template should appear selected now.
If you want me to help with the PHP side to ensure $currentType and $currentTemplate are set correctly as well, just ask!
var isInitialLoad = true;
function updateTemplateOptions(catId)
{
var templates = categoryTemplatesMap[catId] || [];
if (isInitialLoad) {
isInitialLoad = false;
// If editing (currentTemplate exists), just select it and keep PHP options intact
if (currentTemplate) {
if (templates.includes(currentTemplate)) {
$template.val(currentTemplate).trigger('change');
}
return;
}
// If new record (no currentTemplate), rebuild dropdown options to filter per category
}
$template.empty();
if (templates.length)
{
templates.forEach(function(t)
{
$template.append($('<option>').val(t).text(t.charAt(0).toUpperCase() + t.slice(1)));
});
$template.prop('disabled', false);
if (currentTemplate && templates.includes(currentTemplate))
{
$template.val(currentTemplate);
}
else
{
currentTemplate = templates[0];
$template.val(currentTemplate);
}
$template.trigger('change');
}
else
{
$template.append($('<option>').val('').text('Select a category first'));
$template.prop('disabled', true);
}
}
This behavior:
On page load:
If currentTemplate exists (update form), don’t rebuild options, just select saved template.
If currentTemplate empty (new record), force rebuild options filtered by category.
Optionally, you can also detect new vs update server-side and pass that to JS: