I'm editing osticket, open.inc.php. If there is any subcategory chosen but not with name "other" or "اخرى" and it chosen then Issue Summary and Issue Details are totally optional and fill them with just one space. there variables names are subject and message.
code
Assistant
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();
}
});
});
To achieve your goal of making the Issue Summary (subject) and Issue Details (message) optional when a subcategory other than "other" or "اخرى" is selected in osTicket, you'll need to modify both the form validation and the form rendering parts of open.inc.php. Additionally, you'll ensure that if these fields are left empty under the specified conditions, they are automatically filled with a single space.
Here's a step-by-step guide along with the necessary code snippets to help you implement these changes:
1. Understand the Workflow
Before making changes, it's essential to understand how osTicket handles form submissions:
Form Rendering: The form is displayed to the user, allowing them to input data.
Form Submission: When the form is submitted, the data is processed, validated, and a ticket is created.
Your changes will primarily affect the form processing stage by adjusting validation rules based on the selected subcategory.
2. Modify Form Processing Logic
a. Locate the Form Processing Section
In open.inc.php, locate the section where the form submission is handled. This typically involves checking if $_POST data exists and then validating the input.
Look for code blocks that resemble the following:
php
if ($_POST) {
// Form processing and validation logic
}
b. Add Logic to Make subject and message Optional
Within the form processing section, add logic to:
Determine the Selected Subcategory:
Retrieve the topicId from $_POST.
Lookup the corresponding Topic object.
Check if the topic's name is neither "other" nor "اخرى".
Adjust Validation:
If the above condition is met, bypass the required validation for subject and message.
If these fields are empty, set them to a single space.
Here's how you can implement this:
php
<?php
// ... [Existing code above]
// After loading $info and before rendering the form
if ($_POST && !$errors) {
// Retrieve the selected topic ID
$selectedTopicId = intval($_POST['topicId']);
$selectedTopic = Topic::lookup($selectedTopicId);
if ($selectedTopic) {
$topicName = strtolower($selectedTopic->getName()); // Convert to lowercase for comparison
// Check if the topic is not "other" or "اخرى"
if ($topicName !== 'other' && $topicName !== 'اخرى') {
// Make Issue Summary (subject) and Issue Details (message) optional
// Check if 'subject' is empty
if (empty(trim($_POST['subject']))) {
$_POST['subject'] = ' '; // Set to single space
$info['subject'] = ' '; // Update $info array if used later
unset($errors['subject']); // Remove any existing errors related to 'subject'
}
// Check if 'message' is empty
if (empty(trim($_POST['message']))) {
$_POST['message'] = ' '; // Set to single space
$info['message'] = ' '; // Update $info array if used later
unset($errors['message']); // Remove any existing errors related to 'message'
}
// Optionally, adjust the form requirements or validation logic here
// For example, you might want to skip certain checks
}
}
}
// ... [Rest of the existing code]
?>
Explanation of the Code:
Retrieve and Normalize Topic Name:
The topic name is converted to lowercase to ensure the comparison is case-insensitive.
Check for "other" or "اخرى":
The condition ensures that only when the topic name is not "other" or "اخرى" do we proceed to make the fields optional.
Set Fields to Single Space if Empty:
If subject or message are empty after trimming whitespace, they're set to a single space.
Remove Validation Errors:
Any existing errors related to these fields are removed to prevent validation from failing.
3. Adjust Form Rendering to Reflect Optional Fields
To provide a better user experience, you should also adjust the form to indicate that Issue Summary and Issue Details are optional when the specified subcategories are selected.
a. Modify the Form Labels
Locate the form fields for Issue Summary (subject) and Issue Details (message). They might look something like this:
b. Make Labels Dynamic Based on Selected Subcategory
To dynamically adjust the required attribute and the accompanying labels, you can use JavaScript to listen for changes in the topic selection and update the form accordingly.
Add the following JavaScript code within your <script> tag:
javascript
<script type="text/javascript">
$(document).ready(function() {
var topicData = <?php echo json_encode($organizedTopics); ?>;
function createSubTopicSelect(level, parentValue) {
// Existing function code...
}
function updateFinalTopicId() {
// Existing function code...
}
$('#hierarchicalTopics').on('change', '.topic-level', function() {
// Existing change handler code...
// After updating the finalTopicId, adjust the form fields
adjustFormFields();
});
function adjustFormFields() {
var finalTopicId = $('#finalTopicId').val();
if (finalTopicId) {
$.ajax('ajax.php/topic/' + finalTopicId, {
dataType: 'json',
success: function(topic) {
var topicName = topic.name.toLowerCase();
if (topicName !== 'other' && topicName !== 'اخرى') {
// Make fields optional
$('input[name="subject"]').prop('required', false);
$('textarea[name="message"]').prop('required', false);
// Optionally, update the label to indicate optional
$('label[for="subject"]').html('<?php echo __('Issue Summary'); ?> (Optional):');
$('label[for="message"]').html('<?php echo __('Issue Details'); ?> (Optional):');
} else {
// Make fields required
$('input[name="subject"]').prop('required', true);
$('textarea[name="message"]').prop('required', true);
// Update the labels to indicate required
$('label[for="subject"]').html('<?php echo __('Issue Summary'); ?>:');
$('label[for="message"]').html('<?php echo __('Issue Details'); ?>:');
}
}
});
}
}
// Initial adjustment on page load
adjustFormFields();
});
</script>
Explanation of the Code:
AJAX Call to Retrieve Topic Name:
When the topic selection changes, an AJAX request fetches the selected topic's name.
Adjust required Attributes:
Based on the topic name, the required attributes for subject and message fields are dynamically set.
Update Labels:
The labels for these fields are updated to indicate whether they are optional or required.
c. Ensure Labels Have for Attributes
To make the JavaScript code effective in updating labels, ensure that your labels have corresponding for attributes:
Even though you've adjusted the client-side validation, it's crucial to ensure that the server-side validation aligns with these changes to maintain data integrity.
Ensure that if subject or message are empty and set to a space, they don't cause issues elsewhere in the system.
b. Test Different Scenarios
Select a Subcategory Other Than "other" or "اخرى":
Issue Summary and Issue Details should become optional.
If left empty, they should be set to a single space.
Select "other" or "اخرى" Subcategory:
Issue Summary and Issue Details should remain required.
Form Submission:
Verify that the ticket is created correctly in both scenarios.
Ensure that no unintended validation errors occur.
User Experience:
Check that the form clearly indicates when fields are optional or required based on the subcategory selection.
5. Final Code Integration
Here's how you can integrate the changes into your existing open.inc.php file. Make sure to place the PHP logic before the form rendering and adjust the JavaScript appropriately.
a. PHP Form Processing Adjustment
php
<?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;
if ($_POST && !$errors) {
// Retrieve the selected topic ID
$selectedTopicId = intval($_POST['topicId']);
$selectedTopic = Topic::lookup($selectedTopicId);
if ($selectedTopic) {
$topicName = strtolower($selectedTopic->getName());
// Check if the topic is not "other" or "اخرى"
if ($topicName !== 'other' && $topicName !== 'اخرى') {
// Make Issue Summary (subject) and Issue Details (message) optional
if (empty(trim($_POST['subject']))) {
$_POST['subject'] = ' ';
$info['subject'] = ' ';
unset($errors['subject']);
}
if (empty(trim($_POST['message']))) {
$_POST['message'] = ' ';
$info['message'] = ' ';
unset($errors['message']);
}
}
}
// Continue with the existing ticket creation logic
// ...
}
// ... [Rest of the existing code]
?>
b. JavaScript Form Adjustment
Ensure that the JavaScript is placed after the form HTML to effectively manipulate the DOM elements.
html
Notes:
AJAX Endpoint (ajax.php/topic/):
Ensure that this endpoint returns a JSON object with the topic's name. You might need to adjust the AJAX URL based on your osTicket version and setup.
Handling Labels and Errors:
The JavaScript code updates labels to indicate whether fields are optional or required.
It also shows or hides error messages accordingly.
6. Final Testing
After implementing the above changes:
Clear Cache:
Clear your browser cache and osTicket cache if applicable to ensure that changes take effect.
Test All Scenarios:
Selecting "other" or "اخرى":
Ensure that Issue Summary and Issue Details are marked as required.
Attempting to submit the form without filling these fields should trigger validation errors.
Selecting Other Subcategories:
Issue Summary and Issue Details should be optional.
Submitting the form without filling these fields should succeed, and the fields should contain a single space.
Verify Ticket Creation:
Check the backend to ensure that tickets are created correctly with the expected values for subject and message.
User Experience:
Ensure that the form clearly communicates the requirements based on the selected subcategory, enhancing usability.
By following the above steps, you can successfully modify open.inc.php in osTicket to make the Issue Summary and Issue Details fields optional based on the selected subcategory, ensuring they contain at least a single space when left empty. This approach maintains data integrity while providing flexibility in your ticketing system.
If you encounter any issues or need further assistance, feel free to ask!