To achieve the desired functionality—making the Issue Summary (subject) and Issue Details (message) fields optional and automatically filling them with a single space when a subcategory other than "Other" or "اخرى" is selected—you can modify the open.inc.php file as follows:
-
Identify the Selected Subcategory:
- After the form is submitted, determine which subcategory has been selected by the user.
- Check if the selected subcategory's name is neither "Other" nor "اخرى".
-
Modify the subject and message Fields:
- If the conditions are met, set the
subject and message fields to a single space.
- Ensure that these fields are treated as optional in the validation process.
Below is the step-by-step modification of your open.inc.php file with the necessary code additions and explanations.
Step 1: Locate the Form Processing Section
Typically, form processing occurs at the beginning of the PHP file, before any HTML or form rendering. In your open.inc.php, find the section where form submissions are handled. This is usually where $_POST data is processed.
Step 2: Add the Conditional Logic
Insert the following PHP code after the initial form submission handling but before the form is rendered. This ensures that when the form is submitted, the subject and message fields are appropriately modified based on the selected subcategory.
<?php
// ... [Existing code above]
// After handling $info and determining the topicId
if ($_POST && isset($_POST['topicId'])) {
$selectedTopic = Topic::lookup($_POST['topicId']);
if ($selectedTopic) {
$topicName = trim($selectedTopic->getName());
// Check if the topic name is neither "Other" nor "اخرى"
if (strcasecmp($topicName, 'other') !== 0 && $topicName !== 'اخرى') {
// Set subject and message to a single space
$_POST['subject'] = ' ';
$_POST['message'] = ' ';
// Optionally, remove errors related to these fields if they exist
if (isset($errors['subject'])) {
unset($errors['subject']);
}
if (isset($errors['message'])) {
unset($errors['message']);
}
// If using a validation library or custom validation, ensure these fields are optional
// This might vary depending on how validation is implemented in your system
}
}
}
// ... [Existing code continues]
?>
Explanation of the Added Code:
-
Form Submission Check:
if ($_POST && isset($_POST['topicId'])) { ... }
- Ensures that the code runs only when the form is submitted and a
topicId is present.
-
Retrieve the Selected Topic:
$selectedTopic = Topic::lookup($_POST['topicId']);
- Fetches the topic object based on the selected
topicId.
-
Determine the Topic Name:
$topicName = trim($selectedTopic->getName());
- Retrieves and trims the name of the selected topic for comparison.
-
Conditional Check:
if (strcasecmp($topicName, 'other') !== 0 && $topicName !== 'اخرى') { ... }
strcasecmp is used for a case-insensitive comparison with "other".
- Ensures that both "Other" and "اخرى" are excluded.
-
Modify subject and message:
- Sets both fields to a single space to bypass mandatory validation if necessary.
- Optionally removes any existing validation errors related to these fields to prevent false error messages.
-
Handling Validation:
- Depending on how your system handles validation, you might need to adjust the validation rules to treat these fields as optional when they're set to a single space.
- Ensure that the validation logic does not flag these fields as required when they're intentionally left with a space.
Step 3: Ensure Frontend Reflects Optional Fields
While the backend handles the logic, it's good practice to also reflect these changes on the frontend to enhance user experience. However, since you specified to "edit this file only" and the fields are likely part of dynamic forms included via dynamic-form.tmpl.php, extensive frontend modifications might not be straightforward. Nevertheless, ensuring the backend correctly handles the logic is crucial.
Final Modified open.inc.php
Here is your complete open.inc.php file with the necessary modifications highlighted:
<style>
/* [Existing CSS styles] */
</style>
<?php
if(!defined('OSTCLIENTINC')) die('Access Denied!');
$info=array();
if($thisclient && $thisclient->isValid()) {
$info=array('name'=>$thisclient->getName(),
'email'=>$thisclient->getEmail(),
'phone'=>$thisclient->getPhoneNumber());
}
$info=($_POST && $errors)?Format::htmlchars($_POST):$info;
$form = null;
if (!$info['topicId']) {
if (array_key_exists('topicId',$_GET) && preg_match('/^\d+$/',$_GET['topicId']) && Topic::lookup($_GET['topicId']))
$info['topicId'] = intval($_GET['topicId']);
else
$info['topicId'] = $cfg->getDefaultTopicId();
}
$forms = array();
if ($info['topicId'] && ($topic=Topic::lookup($info['topicId']))) {
foreach ($topic->getForms() as $F) {
if (!$F->hasAnyVisibleFields())
continue;
if ($_POST) {
$F = $F->instanciate();
$F->isValidForClient();
}
$forms[] = $F->getForm();
}
}
function organizeTopics($topics) {
$organized = [];
foreach ($topics as $id => $name) {
$parts = array_map('trim', explode('/', $name));
$current = &$organized;
foreach ($parts as $part) {
if (!isset($current[$part])) {
$current[$part] = [];
}
$current = &$current[$part];
}
$current['_id'] = $id;
$current['_full_name'] = $name;
}
return $organized;
}
$allTopics = Topic::getPublicHelpTopics();
$organizedTopics = organizeTopics($allTopics);
// ------------------- Added Code Starts Here -------------------
if ($_POST && isset($_POST['topicId'])) {
$selectedTopic = Topic::lookup($_POST['topicId']);
if ($selectedTopic) {
$topicName = trim($selectedTopic->getName());
// Check if the topic name is neither "Other" nor "اخرى"
if (strcasecmp($topicName, 'other') !== 0 && $topicName !== 'اخرى') {
// Set subject and message to a single space
$_POST['subject'] = ' ';
$_POST['message'] = ' ';
// Optionally, remove errors related to these fields if they exist
if (isset($errors['subject'])) {
unset($errors['subject']);
}
if (isset($errors['message'])) {
unset($errors['message']);
}
// If using a validation library or custom validation, ensure these fields are optional
// This might vary depending on how validation is implemented in your system
}
}
}
// ------------------- Added Code Ends Here -------------------
?>
<h1><?php echo __('Open a New Ticket');?></h1>
<p><?php echo __('Please fill in the form below to open a new ticket.');?></p>
<form id="ticketForm" method="post" action="open.php" enctype="multipart/form-data">
<?php csrf_token(); ?>
<input type="hidden" name="a" value="open">
<table width="800" cellpadding="1" cellspacing="0" border="0">
<tbody>
<?php
if (!$thisclient) {
$uform = UserForm::getUserForm()->getForm($_POST);
if ($_POST) $uform->isValid();
$uform->render(array('staff' => false, 'mode' => 'create'));
}
else { ?>
<tr><td colspan="2"><hr /></td></tr>
<tr><td><?php echo __('Email'); ?>:</td><td><?php
echo $thisclient->getEmail(); ?></td></tr>
<tr><td><?php echo __('Client'); ?>:</td><td><?php
echo Format::htmlchars($thisclient->getName()); ?></td></tr>
<?php } ?>
</tbody>
<tbody>
<td colspan="2">
<div class="form-header" style="margin-bottom:0.5em; margin-top:2em;">
<b><?php echo __('Help Topic'); ?></b>
<span class="error">*</span>
</div>
<div id="hierarchicalTopics">
<select name="topicLevel_0" class="topic-level" data-level="0">
<option value="">— <?php echo __('Select a Help Topic'); ?> —</option>
<?php
foreach ($organizedTopics as $topic => $subTopics) {
$hasSubTopics = !empty($subTopics) && !isset($subTopics['_id']);
echo sprintf('<option value="%s" data-has-subtopics="%s">%s</option>',
htmlspecialchars($topic),
$hasSubTopics ? '1' : '0',
htmlspecialchars($topic)
);
}
?>
</select>
</div>
<input type="hidden" name="topicId" id="finalTopicId" value="<?php echo $info['topicId']; ?>">
</td>
</tr>
</tbody>
<tbody id="dynamic-form">
<?php
$options = array('mode' => 'create');
foreach ($forms as $form) {
include(CLIENTINC_DIR . 'templates/dynamic-form.tmpl.php');
} ?>
</tbody>
<tbody>
<?php
if($cfg && $cfg->isCaptchaEnabled() && (!$thisclient || !$thisclient->isValid())) {
if($_POST && $errors && !$errors['captcha'])
$errors['captcha']=__('Please re-enter the text again');
?>
<tr class="captchaRow">
<td class="required"><?php echo __('CAPTCHA Text');?>:</td>
<td>
<span class="captcha"><img src="captcha.php" border="0" align="left"></span>
<input id="captcha" type="text" name="captcha" size="6" autocomplete="off">
<em><?php echo __('Enter the text shown on the image.');?></em>
<font class="error">* <?php echo $errors['captcha']; ?></font>
</td>
</tr>
<?php
} ?>
<tr><td colspan=2> </td></tr>
</tbody>
</table>
<hr/>
<p class="buttons" style="text-align:center;">
<input type="submit" value="<?php echo __('Create Ticket');?>">
<input type="reset" name="reset" value="<?php echo __('Reset');?>">
<input type="button" name="cancel" value="<?php echo __('Cancel'); ?>" onclick="javascript:
$('.richtext').each(function() {
var redactor = $(this).data('redactor');
if (redactor && redactor.opts.draftDelete)
redactor.plugin.draft.deleteDraft();
});
window.location.href='index.php';">
</p>
</form>
<script type="text/javascript">
$(document).ready(function() {
var topicData = <?php echo json_encode($organizedTopics); ?>;
function createSubTopicSelect(level, parentValue) {
var currentData = topicData;
// Navigate to the correct level in the data structure
for (var i = 0; i < level; i++) {
var selectedValue = $('select[name="topicLevel_' + i + '"]').val();
if (selectedValue && currentData[selectedValue]) {
currentData = currentData[selectedValue];
}
}
// If we've reached a leaf node or empty node, return null
if (!currentData || Object.keys(currentData).length === 0 ||
(currentData['_id'] !== undefined && Object.keys(currentData).length <= 2)) {
return null;
}
var select = $('<select>').attr({
'name': 'topicLevel_' + level,
'class': 'topic-level',
'data-level': level
});
select.append($('<option>').val('').text('— Select Subcategory —'));
$.each(currentData, function(key, value) {
if (key !== '_id' && key !== '_full_name') {
var hasSubTopics = value && !$.isEmptyObject(value) && value['_id'] === undefined;
select.append($('<option>')
.val(key)
.attr('data-has-subtopics', hasSubTopics ? '1' : '0')
.text(key));
}
});
return select;
}
function updateFinalTopicId() {
var selectedValues = [];
$('.topic-level').each(function() {
var value = $(this).val();
if (value) selectedValues.push(value);
});
var currentData = topicData;
var fullPath = '';
for (var i = 0; i < selectedValues.length; i++) {
if (currentData[selectedValues[i]]) {
currentData = currentData[selectedValues[i]];
fullPath += (i > 0 ? ' / ' : '') + selectedValues[i];
}
}
if (currentData['_id']) {
$('#finalTopicId').val(currentData['_id']);
} else {
$('#finalTopicId').val('');
}
}
$('#hierarchicalTopics').on('change', '.topic-level', function() {
var level = parseInt($(this).data('level'));
var value = $(this).val();
// Remove all subsequent levels
$('#hierarchicalTopics select').filter(function() {
return parseInt($(this).data('level')) > level;
}).remove();
if (value) {
var nextSelect = createSubTopicSelect(level + 1, value);
if (nextSelect) {
$('#hierarchicalTopics').append(nextSelect);
}
}
updateFinalTopicId();
// Trigger AJAX for form updates
if ($('#finalTopicId').val()) {
var data = $(':input[name]', '#dynamic-form').serialize();
$.ajax('ajax.php/form/help-topic/' + $('#finalTopicId').val(), {
data: data,
dataType: 'json',
success: function(json) {
$('#dynamic-form').empty().append(json.html);
$(document.head).append(json.media);
}
});
} else {
// Clear the dynamic form if no topic is selected
$('#dynamic-form').empty();
}
});
});
</script>
Additional Recommendations:
-
Validation Adjustments:
- Ensure that the backend validation logic recognizes when
subject and message are intentionally set to ' ' and treats them as optional.
- If you have custom validation rules or use a validation library, update the rules accordingly to prevent these fields from being flagged as required under the specified conditions.
-
User Feedback:
- Consider providing visual cues or messages to users indicating that when certain subcategories are selected, the Issue Summary and Issue Details are optional.
- This enhances user experience by making the form's behavior more transparent.
-
Testing:
- After implementing the changes, thoroughly test the form by selecting various subcategories, including "Other" and "اخرى", to ensure that the
subject and message fields behave as expected.
- Check both frontend behavior and backend processing to confirm that the fields are correctly set and validated.
By following the above modifications, your open.inc.php file will now conditionally set the Issue Summary and Issue Details fields to be optional and automatically filled with a single space when a non-"Other" subcategory is selected.