Fixed the error: Uncaught TypeError: can't access property 'getElementsByTag', b is null
Root Cause:
- CKEditor was not properly destroyed before reinitialization
- No error handling for editor state transitions
- Missing timing delays for DOM readiness when loaded via AJAX
- Inconsistent checking for CKEditor availability
Improvements:
1. Safe destroy pattern - wrap destroy() in try-catch to handle state issues
2. Added typeof check for CKEDITOR instead of window.CKEDITOR
3. Added 100ms setTimeout delay before CKEDITOR.replace() to ensure cleanup
4. Added 150ms delay for initial editor load (especially for AJAX loads)
5. Wrapped all setData() calls in try-catch with textarea fallback
6. Added console warnings for debugging instead of silent failures
7. Check document.readyState before initialization
8. Re-initialize editor check after AJAX template load
9. Added element existence validation before replace()
Changes follow the working pattern from:
- app/Views/PathLab_Report/ultrasound_report_edit.php (safeReplace pattern)
- app/Views/diagnosis/lab_final_report_editor.php (typeof checks)
This ensures the editor works properly when:
- Page loads normally
- Page loads via AJAX (load_form_div)
- User switches between templates using Edit button
- User cancels edit and resets form
Tested scenarios:
- Initial page load
- Edit template -> load data -> CKEditor shows content
- Cancel -> CKEditor resets
- Multiple edit/cancel cycles