<?php

namespace PHPMaker2021\rdigital21;

use Doctrine\DBAL\ParameterType;

/**
 * Page class
 */
class NilaiSumatifGrid extends NilaiSumatif
{
    use MessagesTrait;

    // Page ID
    public $PageID = "grid";

    // Project ID
    public $ProjectID = PROJECT_ID;

    // Table name
    public $TableName = 'nilai_sumatif';

    // Page object name
    public $PageObjName = "NilaiSumatifGrid";

    // Rendering View
    public $RenderingView = false;

    // Grid form hidden field names
    public $FormName = "fnilai_sumatifgrid";
    public $FormActionName = "k_action";
    public $FormBlankRowName = "k_blankrow";
    public $FormKeyCountName = "key_count";

    // Page URLs
    public $AddUrl;
    public $EditUrl;
    public $CopyUrl;
    public $DeleteUrl;
    public $ViewUrl;
    public $ListUrl;

    // Page headings
    public $Heading = "";
    public $Subheading = "";
    public $PageHeader;
    public $PageFooter;

    // Page terminated
    private $terminated = false;

    // Page heading
    public function pageHeading()
    {
        global $Language;
        if ($this->Heading != "") {
            return $this->Heading;
        }
        if (method_exists($this, "tableCaption")) {
            return $this->tableCaption();
        }
        return "";
    }

    // Page subheading
    public function pageSubheading()
    {
        global $Language;
        if ($this->Subheading != "") {
            return $this->Subheading;
        }
        if ($this->TableName) {
            return $Language->phrase($this->PageID);
        }
        return "";
    }

    // Page name
    public function pageName()
    {
        return CurrentPageName();
    }

    // Page URL
    public function pageUrl()
    {
        $url = ScriptName() . "?";
        if ($this->UseTokenInUrl) {
            $url .= "t=" . $this->TableVar . "&"; // Add page token
        }
        return $url;
    }

    // Show Page Header
    public function showPageHeader()
    {
        $header = $this->PageHeader;
        $this->pageDataRendering($header);
        if ($header != "") { // Header exists, display
            echo '<p id="ew-page-header">' . $header . '</p>';
        }
    }

    // Show Page Footer
    public function showPageFooter()
    {
        $footer = $this->PageFooter;
        $this->pageDataRendered($footer);
        if ($footer != "") { // Footer exists, display
            echo '<p id="ew-page-footer">' . $footer . '</p>';
        }
    }

    // Validate page request
    protected function isPageRequest()
    {
        global $CurrentForm;
        if ($this->UseTokenInUrl) {
            if ($CurrentForm) {
                return ($this->TableVar == $CurrentForm->getValue("t"));
            }
            if (Get("t") !== null) {
                return ($this->TableVar == Get("t"));
            }
        }
        return true;
    }

    // Constructor
    public function __construct()
    {
        global $Language, $DashboardReport, $DebugTimer;
        global $UserTable;

        // Initialize
        $this->FormActionName .= "_" . $this->FormName;
        $this->OldKeyName .= "_" . $this->FormName;
        $this->FormBlankRowName .= "_" . $this->FormName;
        $this->FormKeyCountName .= "_" . $this->FormName;
        $GLOBALS["Grid"] = &$this;

        // Language object
        $Language = Container("language");

        // Parent constuctor
        parent::__construct();

        // Table object (nilai_sumatif)
        if (!isset($GLOBALS["nilai_sumatif"]) || get_class($GLOBALS["nilai_sumatif"]) == PROJECT_NAMESPACE . "nilai_sumatif") {
            $GLOBALS["nilai_sumatif"] = &$this;
        }

        // Page URL
        $pageUrl = $this->pageUrl();
        $this->AddUrl = "NilaiSumatifAdd";

        // Table name (for backward compatibility only)
        if (!defined(PROJECT_NAMESPACE . "TABLE_NAME")) {
            define(PROJECT_NAMESPACE . "TABLE_NAME", 'nilai_sumatif');
        }

        // Start timer
        $DebugTimer = Container("timer");

        // Debug message
        LoadDebugMessage();

        // Open connection
        $GLOBALS["Conn"] = $GLOBALS["Conn"] ?? $this->getConnection();

        // User table object
        $UserTable = Container("usertable");

        // List options
        $this->ListOptions = new ListOptions();
        $this->ListOptions->TableVar = $this->TableVar;

        // Other options
        if (!$this->OtherOptions) {
            $this->OtherOptions = new ListOptionsArray();
        }
        $this->OtherOptions["addedit"] = new ListOptions("div");
        $this->OtherOptions["addedit"]->TagClassName = "ew-add-edit-option";
    }

    // Get content from stream
    public function getContents($stream = null): string
    {
        global $Response;
        return is_object($Response) ? $Response->getBody() : ob_get_clean();
    }

    // Is lookup
    public function isLookup()
    {
        return SameText(Route(0), Config("API_LOOKUP_ACTION"));
    }

    // Is AutoFill
    public function isAutoFill()
    {
        return $this->isLookup() && SameText(Post("ajax"), "autofill");
    }

    // Is AutoSuggest
    public function isAutoSuggest()
    {
        return $this->isLookup() && SameText(Post("ajax"), "autosuggest");
    }

    // Is modal lookup
    public function isModalLookup()
    {
        return $this->isLookup() && SameText(Post("ajax"), "modal");
    }

    // Is terminated
    public function isTerminated()
    {
        return $this->terminated;
    }

    /**
     * Terminate page
     *
     * @param string $url URL for direction
     * @return void
     */
    public function terminate($url = "")
    {
        if ($this->terminated) {
            return;
        }
        global $ExportFileName, $TempImages, $DashboardReport, $Response;

        // Page is terminated
        $this->terminated = true;

        // Export
        if ($this->CustomExport && $this->CustomExport == $this->Export && array_key_exists($this->CustomExport, Config("EXPORT_CLASSES"))) {
            $content = $this->getContents();
            if ($ExportFileName == "") {
                $ExportFileName = $this->TableVar;
            }
            $class = PROJECT_NAMESPACE . Config("EXPORT_CLASSES." . $this->CustomExport);
            if (class_exists($class)) {
                $doc = new $class(Container("nilai_sumatif"));
                $doc->Text = @$content;
                if ($this->isExport("email")) {
                    echo $this->exportEmail($doc->Text);
                } else {
                    $doc->export();
                }
                DeleteTempImages(); // Delete temp images
                return;
            }
        }
        unset($GLOBALS["Grid"]);
        if ($url === "") {
            return;
        }
        if (!IsApi() && method_exists($this, "pageRedirecting")) {
            $this->pageRedirecting($url);
        }

        // Return for API
        if (IsApi()) {
            $res = $url === true;
            if (!$res) { // Show error
                WriteJson(array_merge(["success" => false], $this->getMessages()));
            }
            return;
        } else { // Check if response is JSON
            if (StartsString("application/json", $Response->getHeaderLine("Content-type")) && $Response->getBody()->getSize()) { // With JSON response
                $this->clearMessages();
                return;
            }
        }

        // Go to URL if specified
        if ($url != "") {
            if (!Config("DEBUG") && ob_get_length()) {
                ob_end_clean();
            }
            SaveDebugMessage();
            Redirect(GetUrl($url));
        }
        return; // Return to controller
    }

    // Get records from recordset
    protected function getRecordsFromRecordset($rs, $current = false)
    {
        $rows = [];
        if (is_object($rs)) { // Recordset
            while ($rs && !$rs->EOF) {
                $this->loadRowValues($rs); // Set up DbValue/CurrentValue
                $row = $this->getRecordFromArray($rs->fields);
                if ($current) {
                    return $row;
                } else {
                    $rows[] = $row;
                }
                $rs->moveNext();
            }
        } elseif (is_array($rs)) {
            foreach ($rs as $ar) {
                $row = $this->getRecordFromArray($ar);
                if ($current) {
                    return $row;
                } else {
                    $rows[] = $row;
                }
            }
        }
        return $rows;
    }

    // Get record from array
    protected function getRecordFromArray($ar)
    {
        $row = [];
        if (is_array($ar)) {
            foreach ($ar as $fldname => $val) {
                if (array_key_exists($fldname, $this->Fields) && ($this->Fields[$fldname]->Visible || $this->Fields[$fldname]->IsPrimaryKey)) { // Primary key or Visible
                    $fld = &$this->Fields[$fldname];
                    if ($fld->HtmlTag == "FILE") { // Upload field
                        if (EmptyValue($val)) {
                            $row[$fldname] = null;
                        } else {
                            if ($fld->DataType == DATATYPE_BLOB) {
                                $url = FullUrl(GetApiUrl(Config("API_FILE_ACTION") .
                                    "/" . $fld->TableVar . "/" . $fld->Param . "/" . rawurlencode($this->getRecordKeyValue($ar))));
                                $row[$fldname] = ["type" => ContentType($val), "url" => $url, "name" => $fld->Param . ContentExtension($val)];
                            } elseif (!$fld->UploadMultiple || !ContainsString($val, Config("MULTIPLE_UPLOAD_SEPARATOR"))) { // Single file
                                $url = FullUrl(GetApiUrl(Config("API_FILE_ACTION") .
                                    "/" . $fld->TableVar . "/" . Encrypt($fld->physicalUploadPath() . $val)));
                                $row[$fldname] = ["type" => MimeContentType($val), "url" => $url, "name" => $val];
                            } else { // Multiple files
                                $files = explode(Config("MULTIPLE_UPLOAD_SEPARATOR"), $val);
                                $ar = [];
                                foreach ($files as $file) {
                                    $url = FullUrl(GetApiUrl(Config("API_FILE_ACTION") .
                                        "/" . $fld->TableVar . "/" . Encrypt($fld->physicalUploadPath() . $file)));
                                    if (!EmptyValue($file)) {
                                        $ar[] = ["type" => MimeContentType($file), "url" => $url, "name" => $file];
                                    }
                                }
                                $row[$fldname] = $ar;
                            }
                        }
                    } else {
                        $row[$fldname] = $val;
                    }
                }
            }
        }
        return $row;
    }

    // Get record key value from array
    protected function getRecordKeyValue($ar)
    {
        $key = "";
        if (is_array($ar)) {
            $key .= @$ar['nilai_s_id'];
        }
        return $key;
    }

    /**
     * Hide fields for add/edit
     *
     * @return void
     */
    protected function hideFieldsForAddEdit()
    {
        if ($this->isAdd() || $this->isCopy() || $this->isGridAdd()) {
            $this->nilai_s_id->Visible = false;
        }
    }

    // Lookup data
    public function lookup()
    {
        global $Language, $Security;

        // Get lookup object
        $fieldName = Post("field");
        $lookup = $this->Fields[$fieldName]->Lookup;

        // Get lookup parameters
        $lookupType = Post("ajax", "unknown");
        $pageSize = -1;
        $offset = -1;
        $searchValue = "";
        if (SameText($lookupType, "modal")) {
            $searchValue = Post("sv", "");
            $pageSize = Post("recperpage", 10);
            $offset = Post("start", 0);
        } elseif (SameText($lookupType, "autosuggest")) {
            $searchValue = Param("q", "");
            $pageSize = Param("n", -1);
            $pageSize = is_numeric($pageSize) ? (int)$pageSize : -1;
            if ($pageSize <= 0) {
                $pageSize = Config("AUTO_SUGGEST_MAX_ENTRIES");
            }
            $start = Param("start", -1);
            $start = is_numeric($start) ? (int)$start : -1;
            $page = Param("page", -1);
            $page = is_numeric($page) ? (int)$page : -1;
            $offset = $start >= 0 ? $start : ($page > 0 && $pageSize > 0 ? ($page - 1) * $pageSize : 0);
        }
        $userSelect = Decrypt(Post("s", ""));
        $userFilter = Decrypt(Post("f", ""));
        $userOrderBy = Decrypt(Post("o", ""));
        $keys = Post("keys");
        $lookup->LookupType = $lookupType; // Lookup type
        if ($keys !== null) { // Selected records from modal
            if (is_array($keys)) {
                $keys = implode(Config("MULTIPLE_OPTION_SEPARATOR"), $keys);
            }
            $lookup->FilterFields = []; // Skip parent fields if any
            $lookup->FilterValues[] = $keys; // Lookup values
            $pageSize = -1; // Show all records
        } else { // Lookup values
            $lookup->FilterValues[] = Post("v0", Post("lookupValue", ""));
        }
        $cnt = is_array($lookup->FilterFields) ? count($lookup->FilterFields) : 0;
        for ($i = 1; $i <= $cnt; $i++) {
            $lookup->FilterValues[] = Post("v" . $i, "");
        }
        $lookup->SearchValue = $searchValue;
        $lookup->PageSize = $pageSize;
        $lookup->Offset = $offset;
        if ($userSelect != "") {
            $lookup->UserSelect = $userSelect;
        }
        if ($userFilter != "") {
            $lookup->UserFilter = $userFilter;
        }
        if ($userOrderBy != "") {
            $lookup->UserOrderBy = $userOrderBy;
        }
        $lookup->toJson($this); // Use settings from current page
    }

    // Class variables
    public $ListOptions; // List options
    public $ExportOptions; // Export options
    public $SearchOptions; // Search options
    public $OtherOptions; // Other options
    public $FilterOptions; // Filter options
    public $ImportOptions; // Import options
    public $ListActions; // List actions
    public $SelectedCount = 0;
    public $SelectedIndex = 0;
    public $ShowOtherOptions = false;
    public $DisplayRecords = 32;
    public $StartRecord;
    public $StopRecord;
    public $TotalRecords = 0;
    public $RecordRange = 10;
    public $PageSizes = "10,15,20,32,50,100,250,500,1000"; // Page sizes (comma separated)
    public $DefaultSearchWhere = ""; // Default search WHERE clause
    public $SearchWhere = ""; // Search WHERE clause
    public $SearchPanelClass = "ew-search-panel collapse"; // Search Panel class
    public $SearchRowCount = 0; // For extended search
    public $SearchColumnCount = 0; // For extended search
    public $SearchFieldsPerRow = 1; // For extended search
    public $RecordCount = 0; // Record count
    public $EditRowCount;
    public $StartRowCount = 1;
    public $RowCount = 0;
    public $Attrs = []; // Row attributes and cell attributes
    public $RowIndex = 0; // Row index
    public $KeyCount = 0; // Key count
    public $RowAction = ""; // Row action
    public $MultiColumnClass = "col-sm";
    public $MultiColumnEditClass = "w-100";
    public $DbMasterFilter = ""; // Master filter
    public $DbDetailFilter = ""; // Detail filter
    public $MasterRecordExists;
    public $MultiSelectKey;
    public $Command;
    public $RestoreSearch = false;
    public $HashValue; // Hash value
    public $DetailPages;
    public $OldRecordset;

    /**
     * Page run
     *
     * @return void
     */
    public function run()
    {
        global $ExportType, $CustomExportType, $ExportFileName, $UserProfile, $Language, $Security, $CurrentForm;

        // Get grid add count
        $gridaddcnt = Get(Config("TABLE_GRID_ADD_ROW_COUNT"), "");
        if (is_numeric($gridaddcnt) && $gridaddcnt > 0) {
            $this->GridAddRowCount = $gridaddcnt;
        }

        // Set up list options
        $this->setupListOptions();
        $this->nilai_s_id->setVisibility();
        $this->kode_tapel->Visible = false;
        $this->penilaian_id->Visible = false;
        $this->guru_id->setVisibility();
        $this->kode_mapel->setVisibility();
        $this->kelas->setVisibility();
        $this->nis->setVisibility();
        $this->nisn->setVisibility();
        $this->nama->setVisibility();
        $this->jk->setVisibility();
        $this->s1->setVisibility();
        $this->s2->setVisibility();
        $this->s3->setVisibility();
        $this->s4->setVisibility();
        $this->s5->setVisibility();
        $this->s6->setVisibility();
        $this->s7->setVisibility();
        $this->s8->setVisibility();
        $this->nas->setVisibility();
        $this->sts->setVisibility();
        $this->sas->setVisibility();
        $this->nr1->setVisibility();
        $this->nr2->setVisibility();
        $this->hideFieldsForAddEdit();

        // Global Page Loading event (in userfn*.php)
        Page_Loading();

        // Page Load event
        if (method_exists($this, "pageLoad")) {
            $this->pageLoad();
        }

        // Set up master detail parameters
        $this->setupMasterParms();

        // Setup other options
        $this->setupOtherOptions();

        // Set up lookup cache

        // Search filters
        $srchAdvanced = ""; // Advanced search filter
        $srchBasic = ""; // Basic search filter
        $filter = "";

        // Get command
        $this->Command = strtolower(Get("cmd"));
        if ($this->isPageRequest()) {
            // Set up records per page
            $this->setupDisplayRecords();

            // Handle reset command
            $this->resetCmd();

            // Hide list options
            if ($this->isExport()) {
                $this->ListOptions->hideAllOptions(["sequence"]);
                $this->ListOptions->UseDropDownButton = false; // Disable drop down button
                $this->ListOptions->UseButtonGroup = false; // Disable button group
            } elseif ($this->isGridAdd() || $this->isGridEdit()) {
                $this->ListOptions->hideAllOptions();
                $this->ListOptions->UseDropDownButton = false; // Disable drop down button
                $this->ListOptions->UseButtonGroup = false; // Disable button group
            }

            // Show grid delete link for grid add / grid edit
            if ($this->AllowAddDeleteRow) {
                if ($this->isGridAdd() || $this->isGridEdit()) {
                    $item = $this->ListOptions["griddelete"];
                    if ($item) {
                        $item->Visible = true;
                    }
                }
            }

            // Set up sorting order
            $this->setupSortOrder();
        }

        // Restore display records
        if ($this->Command != "json" && $this->getRecordsPerPage() != "") {
            $this->DisplayRecords = $this->getRecordsPerPage(); // Restore from Session
        } else {
            $this->DisplayRecords = 32; // Load default
            $this->setRecordsPerPage($this->DisplayRecords); // Save default to Session
        }

        // Load Sorting Order
        if ($this->Command != "json") {
            $this->loadSortOrder();
        }

        // Build filter
        $filter = "";
        if (!$Security->canList()) {
            $filter = "(0=1)"; // Filter all records
        }

        // Restore master/detail filter
        $this->DbMasterFilter = $this->getMasterFilter(); // Restore master filter
        $this->DbDetailFilter = $this->getDetailFilter(); // Restore detail filter

        // Add master User ID filter
        if ($Security->currentUserID() != "" && !$Security->isAdmin()) { // Non system admin
                if ($this->getCurrentMasterTable() == "penilaian") {
                    $this->DbMasterFilter = $this->addMasterUserIDFilter($this->DbMasterFilter, "penilaian"); // Add master User ID filter
                }
        }
        AddFilter($filter, $this->DbDetailFilter);
        AddFilter($filter, $this->SearchWhere);

        // Load master record
        if ($this->CurrentMode != "add" && $this->getMasterFilter() != "" && $this->getCurrentMasterTable() == "penilaian") {
            $masterTbl = Container("penilaian");
            $rsmaster = $masterTbl->loadRs($this->DbMasterFilter)->fetch(\PDO::FETCH_ASSOC);
            $this->MasterRecordExists = $rsmaster !== false;
            if (!$this->MasterRecordExists) {
                $this->setFailureMessage($Language->phrase("NoRecord")); // Set no record found
                $this->terminate("PenilaianList"); // Return to master page
                return;
            } else {
                $masterTbl->loadListRowValues($rsmaster);
                $masterTbl->RowType = ROWTYPE_MASTER; // Master row
                $masterTbl->renderListRow();
            }
        }

        // Set up filter
        if ($this->Command == "json") {
            $this->UseSessionForListSql = false; // Do not use session for ListSQL
            $this->CurrentFilter = $filter;
        } else {
            $this->setSessionWhere($filter);
            $this->CurrentFilter = "";
        }
        if ($this->isGridAdd()) {
            if ($this->CurrentMode == "copy") {
                $this->TotalRecords = $this->listRecordCount();
                $this->StartRecord = 1;
                $this->DisplayRecords = $this->TotalRecords;
                $this->Recordset = $this->loadRecordset($this->StartRecord - 1, $this->DisplayRecords);
            } else {
                $this->CurrentFilter = "0=1";
                $this->StartRecord = 1;
                $this->DisplayRecords = $this->GridAddRowCount;
            }
            $this->TotalRecords = $this->DisplayRecords;
            $this->StopRecord = $this->DisplayRecords;
        } else {
            $this->TotalRecords = $this->listRecordCount();
            $this->StartRecord = 1;
            $this->DisplayRecords = $this->TotalRecords; // Display all records
            $this->Recordset = $this->loadRecordset($this->StartRecord - 1, $this->DisplayRecords);
        }

        // Normal return
        if (IsApi()) {
            $rows = $this->getRecordsFromRecordset($this->Recordset);
            $this->Recordset->close();
            WriteJson(["success" => true, $this->TableVar => $rows, "totalRecordCount" => $this->TotalRecords]);
            $this->terminate(true);
            return;
        }

        // Set up pager
        $this->Pager = new PrevNextPager($this->StartRecord, $this->getRecordsPerPage(), $this->TotalRecords, $this->PageSizes, $this->RecordRange, $this->AutoHidePager, $this->AutoHidePageSizeSelector);

        // Set LoginStatus / Page_Rendering / Page_Render
        if (!IsApi() && !$this->isTerminated()) {
            // Pass table and field properties to client side
            $this->toClientVar(["tableCaption"], ["caption", "Visible", "Required", "IsInvalid", "Raw"]);

            // Setup login status
            SetupLoginStatus();

            // Pass login status to client side
            SetClientVar("login", LoginStatus());

            // Global Page Rendering event (in userfn*.php)
            Page_Rendering();

            // Page Render event
            if (method_exists($this, "pageRender")) {
                $this->pageRender();
            }
        }
    }

    // Set up number of records displayed per page
    protected function setupDisplayRecords()
    {
        $wrk = Get(Config("TABLE_REC_PER_PAGE"), "");
        if ($wrk != "") {
            if (is_numeric($wrk)) {
                $this->DisplayRecords = (int)$wrk;
            } else {
                if (SameText($wrk, "all")) { // Display all records
                    $this->DisplayRecords = -1;
                } else {
                    $this->DisplayRecords = 32; // Non-numeric, load default
                }
            }
            $this->setRecordsPerPage($this->DisplayRecords); // Save to Session
            // Reset start position
            $this->StartRecord = 1;
            $this->setStartRecordNumber($this->StartRecord);
        }
    }

    // Exit inline mode
    protected function clearInlineMode()
    {
        $this->LastAction = $this->CurrentAction; // Save last action
        $this->CurrentAction = ""; // Clear action
        $_SESSION[SESSION_INLINE_MODE] = ""; // Clear inline mode
    }

    // Switch to Grid Add mode
    protected function gridAddMode()
    {
        $this->CurrentAction = "gridadd";
        $_SESSION[SESSION_INLINE_MODE] = "gridadd";
        $this->hideFieldsForAddEdit();
    }

    // Switch to Grid Edit mode
    protected function gridEditMode()
    {
        $this->CurrentAction = "gridedit";
        $_SESSION[SESSION_INLINE_MODE] = "gridedit";
        $this->hideFieldsForAddEdit();
    }

    // Perform update to grid
    public function gridUpdate()
    {
        global $Language, $CurrentForm;
        $gridUpdate = true;

        // Get old recordset
        $this->CurrentFilter = $this->buildKeyFilter();
        if ($this->CurrentFilter == "") {
            $this->CurrentFilter = "0=1";
        }
        $sql = $this->getCurrentSql();
        $conn = $this->getConnection();
        if ($rs = $conn->executeQuery($sql)) {
            $rsold = $rs->fetchAll();
            $rs->closeCursor();
        }

        // Call Grid Updating event
        if (!$this->gridUpdating($rsold)) {
            if ($this->getFailureMessage() == "") {
                $this->setFailureMessage($Language->phrase("GridEditCancelled")); // Set grid edit cancelled message
            }
            return false;
        }
        $key = "";

        // Update row index and get row key
        $CurrentForm->Index = -1;
        $rowcnt = strval($CurrentForm->getValue($this->FormKeyCountName));
        if ($rowcnt == "" || !is_numeric($rowcnt)) {
            $rowcnt = 0;
        }

        // Update all rows based on key
        for ($rowindex = 1; $rowindex <= $rowcnt; $rowindex++) {
            $CurrentForm->Index = $rowindex;
            $this->setKey($CurrentForm->getValue($this->OldKeyName));
            $rowaction = strval($CurrentForm->getValue($this->FormActionName));

            // Load all values and keys
            if ($rowaction != "insertdelete") { // Skip insert then deleted rows
                $this->loadFormValues(); // Get form values
                if ($rowaction == "" || $rowaction == "edit" || $rowaction == "delete") {
                    $gridUpdate = $this->OldKey != ""; // Key must not be empty
                } else {
                    $gridUpdate = true;
                }

                // Skip empty row
                if ($rowaction == "insert" && $this->emptyRow()) {
                // Validate form and insert/update/delete record
                } elseif ($gridUpdate) {
                    if ($rowaction == "delete") {
                        $this->CurrentFilter = $this->getRecordFilter();
                        $gridUpdate = $this->deleteRows(); // Delete this row
                    //} elseif (!$this->validateForm()) { // Already done in validateGridForm
                    //    $gridUpdate = false; // Form error, reset action
                    } else {
                        if ($rowaction == "insert") {
                            $gridUpdate = $this->addRow(); // Insert this row
                        } else {
                            if ($this->OldKey != "") {
                                $this->SendEmail = false; // Do not send email on update success
                                $gridUpdate = $this->editRow(); // Update this row
                            }
                        } // End update
                    }
                }
                if ($gridUpdate) {
                    if ($key != "") {
                        $key .= ", ";
                    }
                    $key .= $this->OldKey;
                } else {
                    break;
                }
            }
        }
        if ($gridUpdate) {
            // Get new records
            $rsnew = $conn->fetchAll($sql);

            // Call Grid_Updated event
            $this->gridUpdated($rsold, $rsnew);
            $this->clearInlineMode(); // Clear inline edit mode
        } else {
            if ($this->getFailureMessage() == "") {
                $this->setFailureMessage($Language->phrase("UpdateFailed")); // Set update failed message
            }
        }
        return $gridUpdate;
    }

    // Build filter for all keys
    protected function buildKeyFilter()
    {
        global $CurrentForm;
        $wrkFilter = "";

        // Update row index and get row key
        $rowindex = 1;
        $CurrentForm->Index = $rowindex;
        $thisKey = strval($CurrentForm->getValue($this->OldKeyName));
        while ($thisKey != "") {
            $this->setKey($thisKey);
            if ($this->OldKey != "") {
                $filter = $this->getRecordFilter();
                if ($wrkFilter != "") {
                    $wrkFilter .= " OR ";
                }
                $wrkFilter .= $filter;
            } else {
                $wrkFilter = "0=1";
                break;
            }

            // Update row index and get row key
            $rowindex++; // Next row
            $CurrentForm->Index = $rowindex;
            $thisKey = strval($CurrentForm->getValue($this->OldKeyName));
        }
        return $wrkFilter;
    }

    // Perform Grid Add
    public function gridInsert()
    {
        global $Language, $CurrentForm;
        $rowindex = 1;
        $gridInsert = false;
        $conn = $this->getConnection();

        // Call Grid Inserting event
        if (!$this->gridInserting()) {
            if ($this->getFailureMessage() == "") {
                $this->setFailureMessage($Language->phrase("GridAddCancelled")); // Set grid add cancelled message
            }
            return false;
        }

        // Init key filter
        $wrkfilter = "";
        $addcnt = 0;
        $key = "";

        // Get row count
        $CurrentForm->Index = -1;
        $rowcnt = strval($CurrentForm->getValue($this->FormKeyCountName));
        if ($rowcnt == "" || !is_numeric($rowcnt)) {
            $rowcnt = 0;
        }

        // Insert all rows
        for ($rowindex = 1; $rowindex <= $rowcnt; $rowindex++) {
            // Load current row values
            $CurrentForm->Index = $rowindex;
            $rowaction = strval($CurrentForm->getValue($this->FormActionName));
            if ($rowaction != "" && $rowaction != "insert") {
                continue; // Skip
            }
            if ($rowaction == "insert") {
                $this->OldKey = strval($CurrentForm->getValue($this->OldKeyName));
                $this->loadOldRecord(); // Load old record
            }
            $this->loadFormValues(); // Get form values
            if (!$this->emptyRow()) {
                $addcnt++;
                $this->SendEmail = false; // Do not send email on insert success

                // Validate form // Already done in validateGridForm
                //if (!$this->validateForm()) {
                //    $gridInsert = false; // Form error, reset action
                //} else {
                    $gridInsert = $this->addRow($this->OldRecordset); // Insert this row
                //}
                if ($gridInsert) {
                    if ($key != "") {
                        $key .= Config("COMPOSITE_KEY_SEPARATOR");
                    }
                    $key .= $this->nilai_s_id->CurrentValue;

                    // Add filter for this record
                    $filter = $this->getRecordFilter();
                    if ($wrkfilter != "") {
                        $wrkfilter .= " OR ";
                    }
                    $wrkfilter .= $filter;
                } else {
                    break;
                }
            }
        }
        if ($addcnt == 0) { // No record inserted
            $this->clearInlineMode(); // Clear grid add mode and return
            return true;
        }
        if ($gridInsert) {
            // Get new records
            $this->CurrentFilter = $wrkfilter;
            $sql = $this->getCurrentSql();
            $rsnew = $conn->fetchAll($sql);

            // Call Grid_Inserted event
            $this->gridInserted($rsnew);
            $this->clearInlineMode(); // Clear grid add mode
        } else {
            if ($this->getFailureMessage() == "") {
                $this->setFailureMessage($Language->phrase("InsertFailed")); // Set insert failed message
            }
        }
        return $gridInsert;
    }

    // Check if empty row
    public function emptyRow()
    {
        global $CurrentForm;
        if ($CurrentForm->hasValue("x_guru_id") && $CurrentForm->hasValue("o_guru_id") && $this->guru_id->CurrentValue != $this->guru_id->OldValue) {
            return false;
        }
        if ($CurrentForm->hasValue("x_kode_mapel") && $CurrentForm->hasValue("o_kode_mapel") && $this->kode_mapel->CurrentValue != $this->kode_mapel->OldValue) {
            return false;
        }
        if ($CurrentForm->hasValue("x_kelas") && $CurrentForm->hasValue("o_kelas") && $this->kelas->CurrentValue != $this->kelas->OldValue) {
            return false;
        }
        if ($CurrentForm->hasValue("x_nis") && $CurrentForm->hasValue("o_nis") && $this->nis->CurrentValue != $this->nis->OldValue) {
            return false;
        }
        if ($CurrentForm->hasValue("x_nisn") && $CurrentForm->hasValue("o_nisn") && $this->nisn->CurrentValue != $this->nisn->OldValue) {
            return false;
        }
        if ($CurrentForm->hasValue("x_nama") && $CurrentForm->hasValue("o_nama") && $this->nama->CurrentValue != $this->nama->OldValue) {
            return false;
        }
        if ($CurrentForm->hasValue("x_jk") && $CurrentForm->hasValue("o_jk") && $this->jk->CurrentValue != $this->jk->OldValue) {
            return false;
        }
        if ($CurrentForm->hasValue("x_s1") && $CurrentForm->hasValue("o_s1") && $this->s1->CurrentValue != $this->s1->OldValue) {
            return false;
        }
        if ($CurrentForm->hasValue("x_s2") && $CurrentForm->hasValue("o_s2") && $this->s2->CurrentValue != $this->s2->OldValue) {
            return false;
        }
        if ($CurrentForm->hasValue("x_s3") && $CurrentForm->hasValue("o_s3") && $this->s3->CurrentValue != $this->s3->OldValue) {
            return false;
        }
        if ($CurrentForm->hasValue("x_s4") && $CurrentForm->hasValue("o_s4") && $this->s4->CurrentValue != $this->s4->OldValue) {
            return false;
        }
        if ($CurrentForm->hasValue("x_s5") && $CurrentForm->hasValue("o_s5") && $this->s5->CurrentValue != $this->s5->OldValue) {
            return false;
        }
        if ($CurrentForm->hasValue("x_s6") && $CurrentForm->hasValue("o_s6") && $this->s6->CurrentValue != $this->s6->OldValue) {
            return false;
        }
        if ($CurrentForm->hasValue("x_s7") && $CurrentForm->hasValue("o_s7") && $this->s7->CurrentValue != $this->s7->OldValue) {
            return false;
        }
        if ($CurrentForm->hasValue("x_s8") && $CurrentForm->hasValue("o_s8") && $this->s8->CurrentValue != $this->s8->OldValue) {
            return false;
        }
        if ($CurrentForm->hasValue("x_nas") && $CurrentForm->hasValue("o_nas") && $this->nas->CurrentValue != $this->nas->OldValue) {
            return false;
        }
        if ($CurrentForm->hasValue("x_sts") && $CurrentForm->hasValue("o_sts") && $this->sts->CurrentValue != $this->sts->OldValue) {
            return false;
        }
        if ($CurrentForm->hasValue("x_sas") && $CurrentForm->hasValue("o_sas") && $this->sas->CurrentValue != $this->sas->OldValue) {
            return false;
        }
        if ($CurrentForm->hasValue("x_nr1") && $CurrentForm->hasValue("o_nr1") && $this->nr1->CurrentValue != $this->nr1->OldValue) {
            return false;
        }
        if ($CurrentForm->hasValue("x_nr2") && $CurrentForm->hasValue("o_nr2") && $this->nr2->CurrentValue != $this->nr2->OldValue) {
            return false;
        }
        return true;
    }

    // Validate grid form
    public function validateGridForm()
    {
        global $CurrentForm;
        // Get row count
        $CurrentForm->Index = -1;
        $rowcnt = strval($CurrentForm->getValue($this->FormKeyCountName));
        if ($rowcnt == "" || !is_numeric($rowcnt)) {
            $rowcnt = 0;
        }

        // Validate all records
        for ($rowindex = 1; $rowindex <= $rowcnt; $rowindex++) {
            // Load current row values
            $CurrentForm->Index = $rowindex;
            $rowaction = strval($CurrentForm->getValue($this->FormActionName));
            if ($rowaction != "delete" && $rowaction != "insertdelete") {
                $this->loadFormValues(); // Get form values
                if ($rowaction == "insert" && $this->emptyRow()) {
                    // Ignore
                } elseif (!$this->validateForm()) {
                    return false;
                }
            }
        }
        return true;
    }

    // Get all form values of the grid
    public function getGridFormValues()
    {
        global $CurrentForm;
        // Get row count
        $CurrentForm->Index = -1;
        $rowcnt = strval($CurrentForm->getValue($this->FormKeyCountName));
        if ($rowcnt == "" || !is_numeric($rowcnt)) {
            $rowcnt = 0;
        }
        $rows = [];

        // Loop through all records
        for ($rowindex = 1; $rowindex <= $rowcnt; $rowindex++) {
            // Load current row values
            $CurrentForm->Index = $rowindex;
            $rowaction = strval($CurrentForm->getValue($this->FormActionName));
            if ($rowaction != "delete" && $rowaction != "insertdelete") {
                $this->loadFormValues(); // Get form values
                if ($rowaction == "insert" && $this->emptyRow()) {
                    // Ignore
                } else {
                    $rows[] = $this->getFieldValues("FormValue"); // Return row as array
                }
            }
        }
        return $rows; // Return as array of array
    }

    // Restore form values for current row
    public function restoreCurrentRowFormValues($idx)
    {
        global $CurrentForm;

        // Get row based on current index
        $CurrentForm->Index = $idx;
        $rowaction = strval($CurrentForm->getValue($this->FormActionName));
        $this->loadFormValues(); // Load form values
        // Set up invalid status correctly
        $this->resetFormError();
        if ($rowaction == "insert" && $this->emptyRow()) {
            // Ignore
        } else {
            $this->validateForm();
        }
    }

    // Reset form status
    public function resetFormError()
    {
        $this->nilai_s_id->clearErrorMessage();
        $this->guru_id->clearErrorMessage();
        $this->kode_mapel->clearErrorMessage();
        $this->kelas->clearErrorMessage();
        $this->nis->clearErrorMessage();
        $this->nisn->clearErrorMessage();
        $this->nama->clearErrorMessage();
        $this->jk->clearErrorMessage();
        $this->s1->clearErrorMessage();
        $this->s2->clearErrorMessage();
        $this->s3->clearErrorMessage();
        $this->s4->clearErrorMessage();
        $this->s5->clearErrorMessage();
        $this->s6->clearErrorMessage();
        $this->s7->clearErrorMessage();
        $this->s8->clearErrorMessage();
        $this->nas->clearErrorMessage();
        $this->sts->clearErrorMessage();
        $this->sas->clearErrorMessage();
        $this->nr1->clearErrorMessage();
        $this->nr2->clearErrorMessage();
    }

    // Set up sort parameters
    protected function setupSortOrder()
    {
        // Check for "order" parameter
        if (Get("order") !== null) {
            $this->CurrentOrder = Get("order");
            $this->CurrentOrderType = Get("ordertype", "");
            $this->setStartRecordNumber(1); // Reset start position
        }
    }

    // Load sort order parameters
    protected function loadSortOrder()
    {
        $orderBy = $this->getSessionOrderBy(); // Get ORDER BY from Session
        if ($orderBy == "") {
            $this->DefaultSort = "";
            if ($this->getSqlOrderBy() != "") {
                $useDefaultSort = true;
                if ($useDefaultSort) {
                    $orderBy = $this->getSqlOrderBy();
                    $this->setSessionOrderBy($orderBy);
                } else {
                    $this->setSessionOrderBy("");
                }
            }
        }
    }

    // Reset command
    // - cmd=reset (Reset search parameters)
    // - cmd=resetall (Reset search and master/detail parameters)
    // - cmd=resetsort (Reset sort parameters)
    protected function resetCmd()
    {
        // Check if reset command
        if (StartsString("reset", $this->Command)) {
            // Reset master/detail keys
            if ($this->Command == "resetall") {
                $this->setCurrentMasterTable(""); // Clear master table
                $this->DbMasterFilter = "";
                $this->DbDetailFilter = "";
                        $this->penilaian_id->setSessionValue("");
            }

            // Reset (clear) sorting order
            if ($this->Command == "resetsort") {
                $orderBy = "";
                $this->setSessionOrderBy($orderBy);
            }

            // Reset start position
            $this->StartRecord = 1;
            $this->setStartRecordNumber($this->StartRecord);
        }
    }

    // Set up list options
    protected function setupListOptions()
    {
        global $Security, $Language;

        // "griddelete"
        if ($this->AllowAddDeleteRow) {
            $item = &$this->ListOptions->add("griddelete");
            $item->CssClass = "text-nowrap";
            $item->OnLeft = true;
            $item->Visible = false; // Default hidden
        }

        // Add group option item
        $item = &$this->ListOptions->add($this->ListOptions->GroupOptionName);
        $item->Body = "";
        $item->OnLeft = true;
        $item->Visible = false;

        // "edit"
        $item = &$this->ListOptions->add("edit");
        $item->CssClass = "text-nowrap";
        $item->Visible = $Security->canEdit();
        $item->OnLeft = true;

        // "sequence"
        $item = &$this->ListOptions->add("sequence");
        $item->CssClass = "text-nowrap";
        $item->Visible = true;
        $item->OnLeft = true; // Always on left
        $item->ShowInDropDown = false;
        $item->ShowInButtonGroup = false;

        // Drop down button for ListOptions
        $this->ListOptions->UseDropDownButton = false;
        $this->ListOptions->DropDownButtonPhrase = $Language->phrase("ButtonListOptions");
        $this->ListOptions->UseButtonGroup = false;
        if ($this->ListOptions->UseButtonGroup && IsMobile()) {
            $this->ListOptions->UseDropDownButton = true;
        }

        //$this->ListOptions->ButtonClass = ""; // Class for button group

        // Call ListOptions_Load event
        $this->listOptionsLoad();
        $item = $this->ListOptions[$this->ListOptions->GroupOptionName];
        $item->Visible = $this->ListOptions->groupOptionVisible();
    }

    // Render list options
    public function renderListOptions()
    {
        global $Security, $Language, $CurrentForm;
        $this->ListOptions->loadDefault();

        // Call ListOptions_Rendering event
        $this->listOptionsRendering();

        // Set up row action and key
        if ($CurrentForm && is_numeric($this->RowIndex) && $this->RowType != "view") {
            $CurrentForm->Index = $this->RowIndex;
            $actionName = str_replace("k_", "k" . $this->RowIndex . "_", $this->FormActionName);
            $oldKeyName = str_replace("k_", "k" . $this->RowIndex . "_", $this->OldKeyName);
            $blankRowName = str_replace("k_", "k" . $this->RowIndex . "_", $this->FormBlankRowName);
            if ($this->RowAction != "") {
                $this->MultiSelectKey .= "<input type=\"hidden\" name=\"" . $actionName . "\" id=\"" . $actionName . "\" value=\"" . $this->RowAction . "\">";
            }
            $oldKey = $this->getKey(false); // Get from OldValue
            if ($oldKeyName != "" && $oldKey != "") {
                $this->MultiSelectKey .= "<input type=\"hidden\" name=\"" . $oldKeyName . "\" id=\"" . $oldKeyName . "\" value=\"" . HtmlEncode($oldKey) . "\">";
            }
            if ($this->RowAction == "insert" && $this->isConfirm() && $this->emptyRow()) {
                $this->MultiSelectKey .= "<input type=\"hidden\" name=\"" . $blankRowName . "\" id=\"" . $blankRowName . "\" value=\"1\">";
            }
        }

        // "delete"
        if ($this->AllowAddDeleteRow) {
            if ($this->CurrentMode == "add" || $this->CurrentMode == "copy" || $this->CurrentMode == "edit") {
                $options = &$this->ListOptions;
                $options->UseButtonGroup = true; // Use button group for grid delete button
                $opt = $options["griddelete"];
                if (!$Security->canDelete() && is_numeric($this->RowIndex) && ($this->RowAction == "" || $this->RowAction == "edit")) { // Do not allow delete existing record
                    $opt->Body = "&nbsp;";
                } else {
                    $opt->Body = "<a class=\"ew-grid-link ew-grid-delete\" title=\"" . HtmlTitle($Language->phrase("DeleteLink")) . "\" data-caption=\"" . HtmlTitle($Language->phrase("DeleteLink")) . "\" onclick=\"return ew.deleteGridRow(this, " . $this->RowIndex . ");\">" . $Language->phrase("DeleteLink") . "</a>";
                }
            }
        }

        // "sequence"
        $opt = $this->ListOptions["sequence"];
        $opt->Body = FormatSequenceNumber($this->RecordCount);
        if ($this->CurrentMode == "view") {
            // "edit"
            $opt = $this->ListOptions["edit"];
            $editcaption = HtmlTitle($Language->phrase("EditLink"));
            if ($Security->canEdit()) {
                $opt->Body = "<a class=\"ew-row-link ew-edit\" title=\"" . HtmlTitle($Language->phrase("EditLink")) . "\" data-caption=\"" . HtmlTitle($Language->phrase("EditLink")) . "\" href=\"" . HtmlEncode(GetUrl($this->EditUrl)) . "\">" . $Language->phrase("EditLink") . "</a>";
            } else {
                $opt->Body = "";
            }
        } // End View mode
        $this->renderListOptionsExt();

        // Call ListOptions_Rendered event
        $this->listOptionsRendered();
    }

    // Set up other options
    protected function setupOtherOptions()
    {
        global $Language, $Security;
        $option = $this->OtherOptions["addedit"];
        $option->UseDropDownButton = false;
        $option->DropDownButtonPhrase = $Language->phrase("ButtonAddEdit");
        $option->UseButtonGroup = true;
        //$option->ButtonClass = ""; // Class for button group
        $item = &$option->add($option->GroupOptionName);
        $item->Body = "";
        $item->Visible = false;

        // Add
        if ($this->CurrentMode == "view") { // Check view mode
            $item = &$option->add("add");
            $addcaption = HtmlTitle($Language->phrase("AddLink"));
            $this->AddUrl = $this->getAddUrl();
            $item->Body = "<a class=\"ew-add-edit ew-add\" title=\"" . $addcaption . "\" data-caption=\"" . $addcaption . "\" href=\"" . HtmlEncode(GetUrl($this->AddUrl)) . "\">" . $Language->phrase("AddLink") . "</a>";
            $item->Visible = $this->AddUrl != "" && $Security->canAdd();
        }
    }

    // Render other options
    public function renderOtherOptions()
    {
        global $Language, $Security;
        $options = &$this->OtherOptions;
        if (($this->CurrentMode == "add" || $this->CurrentMode == "copy" || $this->CurrentMode == "edit") && !$this->isConfirm()) { // Check add/copy/edit mode
            if ($this->AllowAddDeleteRow) {
                $option = $options["addedit"];
                $option->UseDropDownButton = false;
                $item = &$option->add("addblankrow");
                $item->Body = "<a class=\"ew-add-edit ew-add-blank-row\" title=\"" . HtmlTitle($Language->phrase("AddBlankRow")) . "\" data-caption=\"" . HtmlTitle($Language->phrase("AddBlankRow")) . "\" href=\"#\" onclick=\"return ew.addGridRow(this);\">" . $Language->phrase("AddBlankRow") . "</a>";
                $item->Visible = $Security->canAdd();
                $this->ShowOtherOptions = $item->Visible;
            }
        }
        if ($this->CurrentMode == "view") { // Check view mode
            $option = $options["addedit"];
            $item = $option["add"];
            $this->ShowOtherOptions = $item && $item->Visible;
        }
    }

    // Set up list options (extended codes)
    protected function setupListOptionsExt()
    {
    }

    // Render list options (extended codes)
    protected function renderListOptionsExt()
    {
    }

    // Get upload files
    protected function getUploadFiles()
    {
        global $CurrentForm, $Language;
    }

    // Load default values
    protected function loadDefaultValues()
    {
        $this->nilai_s_id->CurrentValue = null;
        $this->nilai_s_id->OldValue = $this->nilai_s_id->CurrentValue;
        $this->kode_tapel->CurrentValue = null;
        $this->kode_tapel->OldValue = $this->kode_tapel->CurrentValue;
        $this->penilaian_id->CurrentValue = null;
        $this->penilaian_id->OldValue = $this->penilaian_id->CurrentValue;
        $this->guru_id->CurrentValue = null;
        $this->guru_id->OldValue = $this->guru_id->CurrentValue;
        $this->kode_mapel->CurrentValue = null;
        $this->kode_mapel->OldValue = $this->kode_mapel->CurrentValue;
        $this->kelas->CurrentValue = null;
        $this->kelas->OldValue = $this->kelas->CurrentValue;
        $this->nis->CurrentValue = null;
        $this->nis->OldValue = $this->nis->CurrentValue;
        $this->nisn->CurrentValue = null;
        $this->nisn->OldValue = $this->nisn->CurrentValue;
        $this->nama->CurrentValue = null;
        $this->nama->OldValue = $this->nama->CurrentValue;
        $this->jk->CurrentValue = null;
        $this->jk->OldValue = $this->jk->CurrentValue;
        $this->s1->CurrentValue = 0;
        $this->s1->OldValue = $this->s1->CurrentValue;
        $this->s2->CurrentValue = 0;
        $this->s2->OldValue = $this->s2->CurrentValue;
        $this->s3->CurrentValue = 0;
        $this->s3->OldValue = $this->s3->CurrentValue;
        $this->s4->CurrentValue = 0;
        $this->s4->OldValue = $this->s4->CurrentValue;
        $this->s5->CurrentValue = 0;
        $this->s5->OldValue = $this->s5->CurrentValue;
        $this->s6->CurrentValue = 0;
        $this->s6->OldValue = $this->s6->CurrentValue;
        $this->s7->CurrentValue = 0;
        $this->s7->OldValue = $this->s7->CurrentValue;
        $this->s8->CurrentValue = 0;
        $this->s8->OldValue = $this->s8->CurrentValue;
        $this->nas->CurrentValue = 0;
        $this->nas->OldValue = $this->nas->CurrentValue;
        $this->sts->CurrentValue = 0;
        $this->sts->OldValue = $this->sts->CurrentValue;
        $this->sas->CurrentValue = 0;
        $this->sas->OldValue = $this->sas->CurrentValue;
        $this->nr1->CurrentValue = 0;
        $this->nr1->OldValue = $this->nr1->CurrentValue;
        $this->nr2->CurrentValue = 0;
        $this->nr2->OldValue = $this->nr2->CurrentValue;
    }

    // Load form values
    protected function loadFormValues()
    {
        // Load from form
        global $CurrentForm;
        $CurrentForm->FormName = $this->FormName;

        // Check field name 'nilai_s_id' first before field var 'x_nilai_s_id'
        $val = $CurrentForm->hasValue("nilai_s_id") ? $CurrentForm->getValue("nilai_s_id") : $CurrentForm->getValue("x_nilai_s_id");
        if (!$this->nilai_s_id->IsDetailKey && !$this->isGridAdd() && !$this->isAdd()) {
            $this->nilai_s_id->setFormValue($val);
        }

        // Check field name 'guru_id' first before field var 'x_guru_id'
        $val = $CurrentForm->hasValue("guru_id") ? $CurrentForm->getValue("guru_id") : $CurrentForm->getValue("x_guru_id");
        if (!$this->guru_id->IsDetailKey) {
            if (IsApi() && $val === null) {
                $this->guru_id->Visible = false; // Disable update for API request
            } else {
                $this->guru_id->setFormValue($val);
            }
        }
        if ($CurrentForm->hasValue("o_guru_id")) {
            $this->guru_id->setOldValue($CurrentForm->getValue("o_guru_id"));
        }

        // Check field name 'kode_mapel' first before field var 'x_kode_mapel'
        $val = $CurrentForm->hasValue("kode_mapel") ? $CurrentForm->getValue("kode_mapel") : $CurrentForm->getValue("x_kode_mapel");
        if (!$this->kode_mapel->IsDetailKey) {
            if (IsApi() && $val === null) {
                $this->kode_mapel->Visible = false; // Disable update for API request
            } else {
                $this->kode_mapel->setFormValue($val);
            }
        }
        if ($CurrentForm->hasValue("o_kode_mapel")) {
            $this->kode_mapel->setOldValue($CurrentForm->getValue("o_kode_mapel"));
        }

        // Check field name 'kelas' first before field var 'x_kelas'
        $val = $CurrentForm->hasValue("kelas") ? $CurrentForm->getValue("kelas") : $CurrentForm->getValue("x_kelas");
        if (!$this->kelas->IsDetailKey) {
            if (IsApi() && $val === null) {
                $this->kelas->Visible = false; // Disable update for API request
            } else {
                $this->kelas->setFormValue($val);
            }
        }
        if ($CurrentForm->hasValue("o_kelas")) {
            $this->kelas->setOldValue($CurrentForm->getValue("o_kelas"));
        }

        // Check field name 'nis' first before field var 'x_nis'
        $val = $CurrentForm->hasValue("nis") ? $CurrentForm->getValue("nis") : $CurrentForm->getValue("x_nis");
        if (!$this->nis->IsDetailKey) {
            if (IsApi() && $val === null) {
                $this->nis->Visible = false; // Disable update for API request
            } else {
                $this->nis->setFormValue($val);
            }
        }
        if ($CurrentForm->hasValue("o_nis")) {
            $this->nis->setOldValue($CurrentForm->getValue("o_nis"));
        }

        // Check field name 'nisn' first before field var 'x_nisn'
        $val = $CurrentForm->hasValue("nisn") ? $CurrentForm->getValue("nisn") : $CurrentForm->getValue("x_nisn");
        if (!$this->nisn->IsDetailKey) {
            if (IsApi() && $val === null) {
                $this->nisn->Visible = false; // Disable update for API request
            } else {
                $this->nisn->setFormValue($val);
            }
        }
        if ($CurrentForm->hasValue("o_nisn")) {
            $this->nisn->setOldValue($CurrentForm->getValue("o_nisn"));
        }

        // Check field name 'nama' first before field var 'x_nama'
        $val = $CurrentForm->hasValue("nama") ? $CurrentForm->getValue("nama") : $CurrentForm->getValue("x_nama");
        if (!$this->nama->IsDetailKey) {
            if (IsApi() && $val === null) {
                $this->nama->Visible = false; // Disable update for API request
            } else {
                $this->nama->setFormValue($val);
            }
        }
        if ($CurrentForm->hasValue("o_nama")) {
            $this->nama->setOldValue($CurrentForm->getValue("o_nama"));
        }

        // Check field name 'jk' first before field var 'x_jk'
        $val = $CurrentForm->hasValue("jk") ? $CurrentForm->getValue("jk") : $CurrentForm->getValue("x_jk");
        if (!$this->jk->IsDetailKey) {
            if (IsApi() && $val === null) {
                $this->jk->Visible = false; // Disable update for API request
            } else {
                $this->jk->setFormValue($val);
            }
        }
        if ($CurrentForm->hasValue("o_jk")) {
            $this->jk->setOldValue($CurrentForm->getValue("o_jk"));
        }

        // Check field name 's1' first before field var 'x_s1'
        $val = $CurrentForm->hasValue("s1") ? $CurrentForm->getValue("s1") : $CurrentForm->getValue("x_s1");
        if (!$this->s1->IsDetailKey) {
            if (IsApi() && $val === null) {
                $this->s1->Visible = false; // Disable update for API request
            } else {
                $this->s1->setFormValue($val);
            }
        }
        if ($CurrentForm->hasValue("o_s1")) {
            $this->s1->setOldValue($CurrentForm->getValue("o_s1"));
        }

        // Check field name 's2' first before field var 'x_s2'
        $val = $CurrentForm->hasValue("s2") ? $CurrentForm->getValue("s2") : $CurrentForm->getValue("x_s2");
        if (!$this->s2->IsDetailKey) {
            if (IsApi() && $val === null) {
                $this->s2->Visible = false; // Disable update for API request
            } else {
                $this->s2->setFormValue($val);
            }
        }
        if ($CurrentForm->hasValue("o_s2")) {
            $this->s2->setOldValue($CurrentForm->getValue("o_s2"));
        }

        // Check field name 's3' first before field var 'x_s3'
        $val = $CurrentForm->hasValue("s3") ? $CurrentForm->getValue("s3") : $CurrentForm->getValue("x_s3");
        if (!$this->s3->IsDetailKey) {
            if (IsApi() && $val === null) {
                $this->s3->Visible = false; // Disable update for API request
            } else {
                $this->s3->setFormValue($val);
            }
        }
        if ($CurrentForm->hasValue("o_s3")) {
            $this->s3->setOldValue($CurrentForm->getValue("o_s3"));
        }

        // Check field name 's4' first before field var 'x_s4'
        $val = $CurrentForm->hasValue("s4") ? $CurrentForm->getValue("s4") : $CurrentForm->getValue("x_s4");
        if (!$this->s4->IsDetailKey) {
            if (IsApi() && $val === null) {
                $this->s4->Visible = false; // Disable update for API request
            } else {
                $this->s4->setFormValue($val);
            }
        }
        if ($CurrentForm->hasValue("o_s4")) {
            $this->s4->setOldValue($CurrentForm->getValue("o_s4"));
        }

        // Check field name 's5' first before field var 'x_s5'
        $val = $CurrentForm->hasValue("s5") ? $CurrentForm->getValue("s5") : $CurrentForm->getValue("x_s5");
        if (!$this->s5->IsDetailKey) {
            if (IsApi() && $val === null) {
                $this->s5->Visible = false; // Disable update for API request
            } else {
                $this->s5->setFormValue($val);
            }
        }
        if ($CurrentForm->hasValue("o_s5")) {
            $this->s5->setOldValue($CurrentForm->getValue("o_s5"));
        }

        // Check field name 's6' first before field var 'x_s6'
        $val = $CurrentForm->hasValue("s6") ? $CurrentForm->getValue("s6") : $CurrentForm->getValue("x_s6");
        if (!$this->s6->IsDetailKey) {
            if (IsApi() && $val === null) {
                $this->s6->Visible = false; // Disable update for API request
            } else {
                $this->s6->setFormValue($val);
            }
        }
        if ($CurrentForm->hasValue("o_s6")) {
            $this->s6->setOldValue($CurrentForm->getValue("o_s6"));
        }

        // Check field name 's7' first before field var 'x_s7'
        $val = $CurrentForm->hasValue("s7") ? $CurrentForm->getValue("s7") : $CurrentForm->getValue("x_s7");
        if (!$this->s7->IsDetailKey) {
            if (IsApi() && $val === null) {
                $this->s7->Visible = false; // Disable update for API request
            } else {
                $this->s7->setFormValue($val);
            }
        }
        if ($CurrentForm->hasValue("o_s7")) {
            $this->s7->setOldValue($CurrentForm->getValue("o_s7"));
        }

        // Check field name 's8' first before field var 'x_s8'
        $val = $CurrentForm->hasValue("s8") ? $CurrentForm->getValue("s8") : $CurrentForm->getValue("x_s8");
        if (!$this->s8->IsDetailKey) {
            if (IsApi() && $val === null) {
                $this->s8->Visible = false; // Disable update for API request
            } else {
                $this->s8->setFormValue($val);
            }
        }
        if ($CurrentForm->hasValue("o_s8")) {
            $this->s8->setOldValue($CurrentForm->getValue("o_s8"));
        }

        // Check field name 'nas' first before field var 'x_nas'
        $val = $CurrentForm->hasValue("nas") ? $CurrentForm->getValue("nas") : $CurrentForm->getValue("x_nas");
        if (!$this->nas->IsDetailKey) {
            if (IsApi() && $val === null) {
                $this->nas->Visible = false; // Disable update for API request
            } else {
                $this->nas->setFormValue($val);
            }
        }
        if ($CurrentForm->hasValue("o_nas")) {
            $this->nas->setOldValue($CurrentForm->getValue("o_nas"));
        }

        // Check field name 'sts' first before field var 'x_sts'
        $val = $CurrentForm->hasValue("sts") ? $CurrentForm->getValue("sts") : $CurrentForm->getValue("x_sts");
        if (!$this->sts->IsDetailKey) {
            if (IsApi() && $val === null) {
                $this->sts->Visible = false; // Disable update for API request
            } else {
                $this->sts->setFormValue($val);
            }
        }
        if ($CurrentForm->hasValue("o_sts")) {
            $this->sts->setOldValue($CurrentForm->getValue("o_sts"));
        }

        // Check field name 'sas' first before field var 'x_sas'
        $val = $CurrentForm->hasValue("sas") ? $CurrentForm->getValue("sas") : $CurrentForm->getValue("x_sas");
        if (!$this->sas->IsDetailKey) {
            if (IsApi() && $val === null) {
                $this->sas->Visible = false; // Disable update for API request
            } else {
                $this->sas->setFormValue($val);
            }
        }
        if ($CurrentForm->hasValue("o_sas")) {
            $this->sas->setOldValue($CurrentForm->getValue("o_sas"));
        }

        // Check field name 'nr1' first before field var 'x_nr1'
        $val = $CurrentForm->hasValue("nr1") ? $CurrentForm->getValue("nr1") : $CurrentForm->getValue("x_nr1");
        if (!$this->nr1->IsDetailKey) {
            if (IsApi() && $val === null) {
                $this->nr1->Visible = false; // Disable update for API request
            } else {
                $this->nr1->setFormValue($val);
            }
        }
        if ($CurrentForm->hasValue("o_nr1")) {
            $this->nr1->setOldValue($CurrentForm->getValue("o_nr1"));
        }

        // Check field name 'nr2' first before field var 'x_nr2'
        $val = $CurrentForm->hasValue("nr2") ? $CurrentForm->getValue("nr2") : $CurrentForm->getValue("x_nr2");
        if (!$this->nr2->IsDetailKey) {
            if (IsApi() && $val === null) {
                $this->nr2->Visible = false; // Disable update for API request
            } else {
                $this->nr2->setFormValue($val);
            }
        }
        if ($CurrentForm->hasValue("o_nr2")) {
            $this->nr2->setOldValue($CurrentForm->getValue("o_nr2"));
        }
    }

    // Restore form values
    public function restoreFormValues()
    {
        global $CurrentForm;
        if (!$this->isGridAdd() && !$this->isAdd()) {
            $this->nilai_s_id->CurrentValue = $this->nilai_s_id->FormValue;
        }
        $this->guru_id->CurrentValue = $this->guru_id->FormValue;
        $this->kode_mapel->CurrentValue = $this->kode_mapel->FormValue;
        $this->kelas->CurrentValue = $this->kelas->FormValue;
        $this->nis->CurrentValue = $this->nis->FormValue;
        $this->nisn->CurrentValue = $this->nisn->FormValue;
        $this->nama->CurrentValue = $this->nama->FormValue;
        $this->jk->CurrentValue = $this->jk->FormValue;
        $this->s1->CurrentValue = $this->s1->FormValue;
        $this->s2->CurrentValue = $this->s2->FormValue;
        $this->s3->CurrentValue = $this->s3->FormValue;
        $this->s4->CurrentValue = $this->s4->FormValue;
        $this->s5->CurrentValue = $this->s5->FormValue;
        $this->s6->CurrentValue = $this->s6->FormValue;
        $this->s7->CurrentValue = $this->s7->FormValue;
        $this->s8->CurrentValue = $this->s8->FormValue;
        $this->nas->CurrentValue = $this->nas->FormValue;
        $this->sts->CurrentValue = $this->sts->FormValue;
        $this->sas->CurrentValue = $this->sas->FormValue;
        $this->nr1->CurrentValue = $this->nr1->FormValue;
        $this->nr2->CurrentValue = $this->nr2->FormValue;
    }

    // Load recordset
    public function loadRecordset($offset = -1, $rowcnt = -1)
    {
        // Load List page SQL (QueryBuilder)
        $sql = $this->getListSql();

        // Load recordset
        if ($offset > -1) {
            $sql->setFirstResult($offset);
        }
        if ($rowcnt > 0) {
            $sql->setMaxResults($rowcnt);
        }
        $stmt = $sql->execute();
        $rs = new Recordset($stmt, $sql);

        // Call Recordset Selected event
        $this->recordsetSelected($rs);
        return $rs;
    }

    /**
     * Load row based on key values
     *
     * @return void
     */
    public function loadRow()
    {
        global $Security, $Language;
        $filter = $this->getRecordFilter();

        // Call Row Selecting event
        $this->rowSelecting($filter);

        // Load SQL based on filter
        $this->CurrentFilter = $filter;
        $sql = $this->getCurrentSql();
        $conn = $this->getConnection();
        $res = false;
        $row = $conn->fetchAssoc($sql);
        if ($row) {
            $res = true;
            $this->loadRowValues($row); // Load row values
        }
        return $res;
    }

    /**
     * Load row values from recordset or record
     *
     * @param Recordset|array $rs Record
     * @return void
     */
    public function loadRowValues($rs = null)
    {
        if (is_array($rs)) {
            $row = $rs;
        } elseif ($rs && property_exists($rs, "fields")) { // Recordset
            $row = $rs->fields;
        } else {
            $row = $this->newRow();
        }

        // Call Row Selected event
        $this->rowSelected($row);
        if (!$rs) {
            return;
        }
        $this->nilai_s_id->setDbValue($row['nilai_s_id']);
        $this->kode_tapel->setDbValue($row['kode_tapel']);
        $this->penilaian_id->setDbValue($row['penilaian_id']);
        $this->guru_id->setDbValue($row['guru_id']);
        $this->kode_mapel->setDbValue($row['kode_mapel']);
        $this->kelas->setDbValue($row['kelas']);
        $this->nis->setDbValue($row['nis']);
        $this->nisn->setDbValue($row['nisn']);
        $this->nama->setDbValue($row['nama']);
        $this->jk->setDbValue($row['jk']);
        $this->s1->setDbValue($row['s1']);
        $this->s2->setDbValue($row['s2']);
        $this->s3->setDbValue($row['s3']);
        $this->s4->setDbValue($row['s4']);
        $this->s5->setDbValue($row['s5']);
        $this->s6->setDbValue($row['s6']);
        $this->s7->setDbValue($row['s7']);
        $this->s8->setDbValue($row['s8']);
        $this->nas->setDbValue($row['nas']);
        $this->sts->setDbValue($row['sts']);
        $this->sas->setDbValue($row['sas']);
        $this->nr1->setDbValue($row['nr1']);
        $this->nr2->setDbValue($row['nr2']);
    }

    // Return a row with default values
    protected function newRow()
    {
        $this->loadDefaultValues();
        $row = [];
        $row['nilai_s_id'] = $this->nilai_s_id->CurrentValue;
        $row['kode_tapel'] = $this->kode_tapel->CurrentValue;
        $row['penilaian_id'] = $this->penilaian_id->CurrentValue;
        $row['guru_id'] = $this->guru_id->CurrentValue;
        $row['kode_mapel'] = $this->kode_mapel->CurrentValue;
        $row['kelas'] = $this->kelas->CurrentValue;
        $row['nis'] = $this->nis->CurrentValue;
        $row['nisn'] = $this->nisn->CurrentValue;
        $row['nama'] = $this->nama->CurrentValue;
        $row['jk'] = $this->jk->CurrentValue;
        $row['s1'] = $this->s1->CurrentValue;
        $row['s2'] = $this->s2->CurrentValue;
        $row['s3'] = $this->s3->CurrentValue;
        $row['s4'] = $this->s4->CurrentValue;
        $row['s5'] = $this->s5->CurrentValue;
        $row['s6'] = $this->s6->CurrentValue;
        $row['s7'] = $this->s7->CurrentValue;
        $row['s8'] = $this->s8->CurrentValue;
        $row['nas'] = $this->nas->CurrentValue;
        $row['sts'] = $this->sts->CurrentValue;
        $row['sas'] = $this->sas->CurrentValue;
        $row['nr1'] = $this->nr1->CurrentValue;
        $row['nr2'] = $this->nr2->CurrentValue;
        return $row;
    }

    // Load old record
    protected function loadOldRecord()
    {
        // Load old record
        $this->OldRecordset = null;
        $validKey = $this->OldKey != "";
        if ($validKey) {
            $this->CurrentFilter = $this->getRecordFilter();
            $sql = $this->getCurrentSql();
            $conn = $this->getConnection();
            $this->OldRecordset = LoadRecordset($sql, $conn);
        }
        $this->loadRowValues($this->OldRecordset); // Load row values
        return $validKey;
    }

    // Render row values based on field settings
    public function renderRow()
    {
        global $Security, $Language, $CurrentLanguage;

        // Initialize URLs
        $this->ViewUrl = $this->getViewUrl();
        $this->EditUrl = $this->getEditUrl();
        $this->CopyUrl = $this->getCopyUrl();
        $this->DeleteUrl = $this->getDeleteUrl();

        // Call Row_Rendering event
        $this->rowRendering();

        // Common render codes for all row types

        // nilai_s_id
        $this->nilai_s_id->CellCssStyle = "white-space: nowrap;";

        // kode_tapel
        $this->kode_tapel->CellCssStyle = "white-space: nowrap;";

        // penilaian_id
        $this->penilaian_id->CellCssStyle = "white-space: nowrap;";

        // guru_id
        $this->guru_id->CellCssStyle = "white-space: nowrap;";

        // kode_mapel
        $this->kode_mapel->CellCssStyle = "white-space: nowrap;";

        // kelas
        $this->kelas->CellCssStyle = "white-space: nowrap;";

        // nis
        $this->nis->CellCssStyle = "white-space: nowrap;";

        // nisn

        // nama
        $this->nama->CellCssStyle = "white-space: nowrap;";

        // jk
        $this->jk->CellCssStyle = "white-space: nowrap;";

        // s1
        $this->s1->CellCssStyle = "white-space: nowrap;";

        // s2
        $this->s2->CellCssStyle = "white-space: nowrap;";

        // s3
        $this->s3->CellCssStyle = "white-space: nowrap;";

        // s4
        $this->s4->CellCssStyle = "white-space: nowrap;";

        // s5
        $this->s5->CellCssStyle = "white-space: nowrap;";

        // s6
        $this->s6->CellCssStyle = "white-space: nowrap;";

        // s7
        $this->s7->CellCssStyle = "white-space: nowrap;";

        // s8
        $this->s8->CellCssStyle = "white-space: nowrap;";

        // nas
        $this->nas->CellCssStyle = "white-space: nowrap;";

        // sts
        $this->sts->CellCssStyle = "white-space: nowrap;";

        // sas
        $this->sas->CellCssStyle = "white-space: nowrap;";

        // nr1
        $this->nr1->CellCssStyle = "white-space: nowrap;";

        // nr2
        $this->nr2->CellCssStyle = "white-space: nowrap;";
        if ($this->RowType == ROWTYPE_VIEW) {
            // nilai_s_id
            $this->nilai_s_id->ViewValue = $this->nilai_s_id->CurrentValue;
            $this->nilai_s_id->ViewCustomAttributes = "";

            // kode_tapel
            $this->kode_tapel->ViewValue = $this->kode_tapel->CurrentValue;
            $this->kode_tapel->ViewCustomAttributes = "";

            // penilaian_id
            $this->penilaian_id->ViewValue = $this->penilaian_id->CurrentValue;
            $this->penilaian_id->ViewCustomAttributes = "";

            // guru_id
            $this->guru_id->ViewValue = $this->guru_id->CurrentValue;
            $this->guru_id->ViewCustomAttributes = "";

            // kode_mapel
            $this->kode_mapel->ViewValue = $this->kode_mapel->CurrentValue;
            $this->kode_mapel->ViewCustomAttributes = "";

            // kelas
            $this->kelas->ViewValue = $this->kelas->CurrentValue;
            $this->kelas->ViewCustomAttributes = "";

            // nis
            $this->nis->ViewValue = $this->nis->CurrentValue;
            $this->nis->ViewCustomAttributes = "";

            // nisn
            $this->nisn->ViewValue = $this->nisn->CurrentValue;
            $this->nisn->ViewCustomAttributes = "";

            // nama
            $this->nama->ViewValue = $this->nama->CurrentValue;
            $this->nama->ViewCustomAttributes = "";

            // jk
            $this->jk->ViewValue = $this->jk->CurrentValue;
            $this->jk->ViewCustomAttributes = "";

            // s1
            $this->s1->ViewValue = $this->s1->CurrentValue;
            $this->s1->ViewCustomAttributes = "";

            // s2
            $this->s2->ViewValue = $this->s2->CurrentValue;
            $this->s2->ViewCustomAttributes = "";

            // s3
            $this->s3->ViewValue = $this->s3->CurrentValue;
            $this->s3->ViewCustomAttributes = "";

            // s4
            $this->s4->ViewValue = $this->s4->CurrentValue;
            $this->s4->ViewCustomAttributes = "";

            // s5
            $this->s5->ViewValue = $this->s5->CurrentValue;
            $this->s5->ViewCustomAttributes = "";

            // s6
            $this->s6->ViewValue = $this->s6->CurrentValue;
            $this->s6->ViewCustomAttributes = "";

            // s7
            $this->s7->ViewValue = $this->s7->CurrentValue;
            $this->s7->ViewCustomAttributes = "";

            // s8
            $this->s8->ViewValue = $this->s8->CurrentValue;
            $this->s8->ViewCustomAttributes = "";

            // nas
            $this->nas->ViewValue = $this->nas->CurrentValue;
            $this->nas->CssClass = "font-weight-bold font-italic";
            $this->nas->ViewCustomAttributes = "";

            // sts
            $this->sts->ViewValue = $this->sts->CurrentValue;
            $this->sts->ViewCustomAttributes = "";

            // sas
            $this->sas->ViewValue = $this->sas->CurrentValue;
            $this->sas->ViewCustomAttributes = "";

            // nr1
            $this->nr1->ViewValue = $this->nr1->CurrentValue;
            $this->nr1->CssClass = "font-weight-bold font-italic";
            $this->nr1->ViewCustomAttributes = "";

            // nr2
            $this->nr2->ViewValue = $this->nr2->CurrentValue;
            $this->nr2->CssClass = "font-weight-bold font-italic";
            $this->nr2->ViewCustomAttributes = "";

            // nilai_s_id
            $this->nilai_s_id->LinkCustomAttributes = "";
            $this->nilai_s_id->HrefValue = "";
            $this->nilai_s_id->TooltipValue = "";

            // guru_id
            $this->guru_id->LinkCustomAttributes = "";
            $this->guru_id->HrefValue = "";
            $this->guru_id->TooltipValue = "";

            // kode_mapel
            $this->kode_mapel->LinkCustomAttributes = "";
            $this->kode_mapel->HrefValue = "";
            $this->kode_mapel->TooltipValue = "";

            // kelas
            $this->kelas->LinkCustomAttributes = "";
            $this->kelas->HrefValue = "";
            $this->kelas->TooltipValue = "";

            // nis
            $this->nis->LinkCustomAttributes = "";
            $this->nis->HrefValue = "";
            $this->nis->TooltipValue = "";

            // nisn
            $this->nisn->LinkCustomAttributes = "";
            $this->nisn->HrefValue = "";
            $this->nisn->TooltipValue = "";

            // nama
            $this->nama->LinkCustomAttributes = "";
            $this->nama->HrefValue = "";
            $this->nama->TooltipValue = "";

            // jk
            $this->jk->LinkCustomAttributes = "";
            $this->jk->HrefValue = "";
            $this->jk->TooltipValue = "";

            // s1
            $this->s1->LinkCustomAttributes = "";
            $this->s1->HrefValue = "";
            $this->s1->TooltipValue = "";

            // s2
            $this->s2->LinkCustomAttributes = "";
            $this->s2->HrefValue = "";
            $this->s2->TooltipValue = "";

            // s3
            $this->s3->LinkCustomAttributes = "";
            $this->s3->HrefValue = "";
            $this->s3->TooltipValue = "";

            // s4
            $this->s4->LinkCustomAttributes = "";
            $this->s4->HrefValue = "";
            $this->s4->TooltipValue = "";

            // s5
            $this->s5->LinkCustomAttributes = "";
            $this->s5->HrefValue = "";
            $this->s5->TooltipValue = "";

            // s6
            $this->s6->LinkCustomAttributes = "";
            $this->s6->HrefValue = "";
            $this->s6->TooltipValue = "";

            // s7
            $this->s7->LinkCustomAttributes = "";
            $this->s7->HrefValue = "";
            $this->s7->TooltipValue = "";

            // s8
            $this->s8->LinkCustomAttributes = "";
            $this->s8->HrefValue = "";
            $this->s8->TooltipValue = "";

            // nas
            $this->nas->LinkCustomAttributes = "";
            $this->nas->HrefValue = "";
            $this->nas->TooltipValue = "";

            // sts
            $this->sts->LinkCustomAttributes = "";
            $this->sts->HrefValue = "";
            $this->sts->TooltipValue = "";

            // sas
            $this->sas->LinkCustomAttributes = "";
            $this->sas->HrefValue = "";
            $this->sas->TooltipValue = "";

            // nr1
            $this->nr1->LinkCustomAttributes = "";
            $this->nr1->HrefValue = "";
            $this->nr1->TooltipValue = "";

            // nr2
            $this->nr2->LinkCustomAttributes = "";
            $this->nr2->HrefValue = "";
            $this->nr2->TooltipValue = "";
        } elseif ($this->RowType == ROWTYPE_ADD) {
            // nilai_s_id

            // guru_id
            $this->guru_id->EditAttrs["class"] = "form-control";
            $this->guru_id->EditCustomAttributes = "";
            if (!$this->guru_id->Raw) {
                $this->guru_id->CurrentValue = HtmlDecode($this->guru_id->CurrentValue);
            }
            $this->guru_id->EditValue = HtmlEncode($this->guru_id->CurrentValue);

            // kode_mapel
            $this->kode_mapel->EditAttrs["class"] = "form-control";
            $this->kode_mapel->EditCustomAttributes = "";
            $curVal = trim(strval($this->kode_mapel->CurrentValue));
            if ($curVal != "") {
                $this->kode_mapel->ViewValue = $this->kode_mapel->lookupCacheOption($curVal);
            } else {
                $this->kode_mapel->ViewValue = $this->kode_mapel->Lookup !== null && is_array($this->kode_mapel->Lookup->Options) ? $curVal : null;
            }
            if ($this->kode_mapel->ViewValue !== null) { // Load from cache
                $this->kode_mapel->EditValue = array_values($this->kode_mapel->Lookup->Options);
            } else { // Lookup from database
                if ($curVal == "") {
                    $filterWrk = "0=1";
                } else {
                    $filterWrk = "\"kode_mapel\"" . SearchString("=", $this->kode_mapel->CurrentValue, DATATYPE_MEMO, "");
                }
                $sqlWrk = $this->kode_mapel->Lookup->getSql(true, $filterWrk, '', $this, false, true);
                $rswrk = Conn()->executeQuery($sqlWrk)->fetchAll(\PDO::FETCH_BOTH);
                $ari = count($rswrk);
                $arwrk = $rswrk;
                $this->kode_mapel->EditValue = $arwrk;
            }

            // kelas
            $this->kelas->EditAttrs["class"] = "form-control";
            $this->kelas->EditCustomAttributes = "";
            $curVal = trim(strval($this->kelas->CurrentValue));
            if ($curVal != "") {
                $this->kelas->ViewValue = $this->kelas->lookupCacheOption($curVal);
            } else {
                $this->kelas->ViewValue = $this->kelas->Lookup !== null && is_array($this->kelas->Lookup->Options) ? $curVal : null;
            }
            if ($this->kelas->ViewValue !== null) { // Load from cache
                $this->kelas->EditValue = array_values($this->kelas->Lookup->Options);
            } else { // Lookup from database
                if ($curVal == "") {
                    $filterWrk = "0=1";
                } else {
                    $filterWrk = "\"kelas\"" . SearchString("=", $this->kelas->CurrentValue, DATATYPE_MEMO, "");
                }
                $lookupFilter = function() {
                    return "`kode_tapel`='".kode_tapel()."'";
                };
                $lookupFilter = $lookupFilter->bindTo($this);
                $sqlWrk = $this->kelas->Lookup->getSql(true, $filterWrk, $lookupFilter, $this, false, true);
                $rswrk = Conn()->executeQuery($sqlWrk)->fetchAll(\PDO::FETCH_BOTH);
                $ari = count($rswrk);
                $arwrk = $rswrk;
                $this->kelas->EditValue = $arwrk;
            }

            // nis
            $this->nis->EditAttrs["class"] = "form-control";
            $this->nis->EditCustomAttributes = "";
            if (!$this->nis->Raw) {
                $this->nis->CurrentValue = HtmlDecode($this->nis->CurrentValue);
            }
            $this->nis->EditValue = HtmlEncode($this->nis->CurrentValue);

            // nisn
            $this->nisn->EditAttrs["class"] = "form-control";
            $this->nisn->EditCustomAttributes = "";
            if (!$this->nisn->Raw) {
                $this->nisn->CurrentValue = HtmlDecode($this->nisn->CurrentValue);
            }
            $this->nisn->EditValue = HtmlEncode($this->nisn->CurrentValue);

            // nama
            $this->nama->EditAttrs["class"] = "form-control";
            $this->nama->EditCustomAttributes = "";
            if (!$this->nama->Raw) {
                $this->nama->CurrentValue = HtmlDecode($this->nama->CurrentValue);
            }
            $this->nama->EditValue = HtmlEncode($this->nama->CurrentValue);

            // jk
            $this->jk->EditAttrs["class"] = "form-control";
            $this->jk->EditCustomAttributes = "";
            if (!$this->jk->Raw) {
                $this->jk->CurrentValue = HtmlDecode($this->jk->CurrentValue);
            }
            $this->jk->EditValue = HtmlEncode($this->jk->CurrentValue);

            // s1
            $this->s1->EditAttrs["class"] = "form-control";
            $this->s1->EditCustomAttributes = "";
            if (!$this->s1->Raw) {
                $this->s1->CurrentValue = HtmlDecode($this->s1->CurrentValue);
            }
            $this->s1->EditValue = HtmlEncode($this->s1->CurrentValue);

            // s2
            $this->s2->EditAttrs["class"] = "form-control";
            $this->s2->EditCustomAttributes = "";
            if (!$this->s2->Raw) {
                $this->s2->CurrentValue = HtmlDecode($this->s2->CurrentValue);
            }
            $this->s2->EditValue = HtmlEncode($this->s2->CurrentValue);

            // s3
            $this->s3->EditAttrs["class"] = "form-control";
            $this->s3->EditCustomAttributes = "";
            if (!$this->s3->Raw) {
                $this->s3->CurrentValue = HtmlDecode($this->s3->CurrentValue);
            }
            $this->s3->EditValue = HtmlEncode($this->s3->CurrentValue);

            // s4
            $this->s4->EditAttrs["class"] = "form-control";
            $this->s4->EditCustomAttributes = "";
            if (!$this->s4->Raw) {
                $this->s4->CurrentValue = HtmlDecode($this->s4->CurrentValue);
            }
            $this->s4->EditValue = HtmlEncode($this->s4->CurrentValue);

            // s5
            $this->s5->EditAttrs["class"] = "form-control";
            $this->s5->EditCustomAttributes = "";
            if (!$this->s5->Raw) {
                $this->s5->CurrentValue = HtmlDecode($this->s5->CurrentValue);
            }
            $this->s5->EditValue = HtmlEncode($this->s5->CurrentValue);

            // s6
            $this->s6->EditAttrs["class"] = "form-control";
            $this->s6->EditCustomAttributes = "";
            if (!$this->s6->Raw) {
                $this->s6->CurrentValue = HtmlDecode($this->s6->CurrentValue);
            }
            $this->s6->EditValue = HtmlEncode($this->s6->CurrentValue);

            // s7
            $this->s7->EditAttrs["class"] = "form-control";
            $this->s7->EditCustomAttributes = "";
            if (!$this->s7->Raw) {
                $this->s7->CurrentValue = HtmlDecode($this->s7->CurrentValue);
            }
            $this->s7->EditValue = HtmlEncode($this->s7->CurrentValue);

            // s8
            $this->s8->EditAttrs["class"] = "form-control";
            $this->s8->EditCustomAttributes = "";
            if (!$this->s8->Raw) {
                $this->s8->CurrentValue = HtmlDecode($this->s8->CurrentValue);
            }
            $this->s8->EditValue = HtmlEncode($this->s8->CurrentValue);

            // nas
            $this->nas->EditAttrs["class"] = "form-control";
            $this->nas->EditCustomAttributes = "";
            if (!$this->nas->Raw) {
                $this->nas->CurrentValue = HtmlDecode($this->nas->CurrentValue);
            }
            $this->nas->EditValue = HtmlEncode($this->nas->CurrentValue);

            // sts
            $this->sts->EditAttrs["class"] = "form-control";
            $this->sts->EditCustomAttributes = "";
            if (!$this->sts->Raw) {
                $this->sts->CurrentValue = HtmlDecode($this->sts->CurrentValue);
            }
            $this->sts->EditValue = HtmlEncode($this->sts->CurrentValue);

            // sas
            $this->sas->EditAttrs["class"] = "form-control";
            $this->sas->EditCustomAttributes = "";
            if (!$this->sas->Raw) {
                $this->sas->CurrentValue = HtmlDecode($this->sas->CurrentValue);
            }
            $this->sas->EditValue = HtmlEncode($this->sas->CurrentValue);

            // nr1
            $this->nr1->EditAttrs["class"] = "form-control";
            $this->nr1->EditCustomAttributes = "";
            if (!$this->nr1->Raw) {
                $this->nr1->CurrentValue = HtmlDecode($this->nr1->CurrentValue);
            }
            $this->nr1->EditValue = HtmlEncode($this->nr1->CurrentValue);

            // nr2
            $this->nr2->EditAttrs["class"] = "form-control";
            $this->nr2->EditCustomAttributes = "";
            if (!$this->nr2->Raw) {
                $this->nr2->CurrentValue = HtmlDecode($this->nr2->CurrentValue);
            }
            $this->nr2->EditValue = HtmlEncode($this->nr2->CurrentValue);

            // Add refer script

            // nilai_s_id
            $this->nilai_s_id->LinkCustomAttributes = "";
            $this->nilai_s_id->HrefValue = "";

            // guru_id
            $this->guru_id->LinkCustomAttributes = "";
            $this->guru_id->HrefValue = "";

            // kode_mapel
            $this->kode_mapel->LinkCustomAttributes = "";
            $this->kode_mapel->HrefValue = "";

            // kelas
            $this->kelas->LinkCustomAttributes = "";
            $this->kelas->HrefValue = "";

            // nis
            $this->nis->LinkCustomAttributes = "";
            $this->nis->HrefValue = "";

            // nisn
            $this->nisn->LinkCustomAttributes = "";
            $this->nisn->HrefValue = "";

            // nama
            $this->nama->LinkCustomAttributes = "";
            $this->nama->HrefValue = "";

            // jk
            $this->jk->LinkCustomAttributes = "";
            $this->jk->HrefValue = "";

            // s1
            $this->s1->LinkCustomAttributes = "";
            $this->s1->HrefValue = "";

            // s2
            $this->s2->LinkCustomAttributes = "";
            $this->s2->HrefValue = "";

            // s3
            $this->s3->LinkCustomAttributes = "";
            $this->s3->HrefValue = "";

            // s4
            $this->s4->LinkCustomAttributes = "";
            $this->s4->HrefValue = "";

            // s5
            $this->s5->LinkCustomAttributes = "";
            $this->s5->HrefValue = "";

            // s6
            $this->s6->LinkCustomAttributes = "";
            $this->s6->HrefValue = "";

            // s7
            $this->s7->LinkCustomAttributes = "";
            $this->s7->HrefValue = "";

            // s8
            $this->s8->LinkCustomAttributes = "";
            $this->s8->HrefValue = "";

            // nas
            $this->nas->LinkCustomAttributes = "";
            $this->nas->HrefValue = "";

            // sts
            $this->sts->LinkCustomAttributes = "";
            $this->sts->HrefValue = "";

            // sas
            $this->sas->LinkCustomAttributes = "";
            $this->sas->HrefValue = "";

            // nr1
            $this->nr1->LinkCustomAttributes = "";
            $this->nr1->HrefValue = "";

            // nr2
            $this->nr2->LinkCustomAttributes = "";
            $this->nr2->HrefValue = "";
        } elseif ($this->RowType == ROWTYPE_EDIT) {
            // nilai_s_id
            $this->nilai_s_id->EditAttrs["class"] = "form-control";
            $this->nilai_s_id->EditCustomAttributes = "";
            $this->nilai_s_id->EditValue = $this->nilai_s_id->CurrentValue;
            $this->nilai_s_id->ViewCustomAttributes = "";

            // guru_id
            $this->guru_id->EditAttrs["class"] = "form-control";
            $this->guru_id->EditCustomAttributes = "";
            $this->guru_id->EditValue = $this->guru_id->CurrentValue;
            $this->guru_id->ViewCustomAttributes = "";

            // kode_mapel
            $this->kode_mapel->EditAttrs["class"] = "form-control";
            $this->kode_mapel->EditCustomAttributes = "";
            $this->kode_mapel->EditValue = $this->kode_mapel->CurrentValue;
            $this->kode_mapel->ViewCustomAttributes = "";

            // kelas
            $this->kelas->EditAttrs["class"] = "form-control";
            $this->kelas->EditCustomAttributes = "";
            $this->kelas->EditValue = $this->kelas->CurrentValue;
            $this->kelas->ViewCustomAttributes = "";

            // nis
            $this->nis->EditAttrs["class"] = "form-control";
            $this->nis->EditCustomAttributes = "";
            $this->nis->EditValue = $this->nis->CurrentValue;
            $this->nis->ViewCustomAttributes = "";

            // nisn
            $this->nisn->EditAttrs["class"] = "form-control";
            $this->nisn->EditCustomAttributes = "";
            if (!$this->nisn->Raw) {
                $this->nisn->CurrentValue = HtmlDecode($this->nisn->CurrentValue);
            }
            $this->nisn->EditValue = HtmlEncode($this->nisn->CurrentValue);

            // nama
            $this->nama->EditAttrs["class"] = "form-control";
            $this->nama->EditCustomAttributes = "";
            $this->nama->EditValue = $this->nama->CurrentValue;
            $this->nama->ViewCustomAttributes = "";

            // jk
            $this->jk->EditAttrs["class"] = "form-control";
            $this->jk->EditCustomAttributes = "";
            $this->jk->EditValue = $this->jk->CurrentValue;
            $this->jk->ViewCustomAttributes = "";

            // s1
            $this->s1->EditAttrs["class"] = "form-control";
            $this->s1->EditCustomAttributes = "";
            if (!$this->s1->Raw) {
                $this->s1->CurrentValue = HtmlDecode($this->s1->CurrentValue);
            }
            $this->s1->EditValue = HtmlEncode($this->s1->CurrentValue);

            // s2
            $this->s2->EditAttrs["class"] = "form-control";
            $this->s2->EditCustomAttributes = "";
            if (!$this->s2->Raw) {
                $this->s2->CurrentValue = HtmlDecode($this->s2->CurrentValue);
            }
            $this->s2->EditValue = HtmlEncode($this->s2->CurrentValue);

            // s3
            $this->s3->EditAttrs["class"] = "form-control";
            $this->s3->EditCustomAttributes = "";
            if (!$this->s3->Raw) {
                $this->s3->CurrentValue = HtmlDecode($this->s3->CurrentValue);
            }
            $this->s3->EditValue = HtmlEncode($this->s3->CurrentValue);

            // s4
            $this->s4->EditAttrs["class"] = "form-control";
            $this->s4->EditCustomAttributes = "";
            if (!$this->s4->Raw) {
                $this->s4->CurrentValue = HtmlDecode($this->s4->CurrentValue);
            }
            $this->s4->EditValue = HtmlEncode($this->s4->CurrentValue);

            // s5
            $this->s5->EditAttrs["class"] = "form-control";
            $this->s5->EditCustomAttributes = "";
            if (!$this->s5->Raw) {
                $this->s5->CurrentValue = HtmlDecode($this->s5->CurrentValue);
            }
            $this->s5->EditValue = HtmlEncode($this->s5->CurrentValue);

            // s6
            $this->s6->EditAttrs["class"] = "form-control";
            $this->s6->EditCustomAttributes = "";
            if (!$this->s6->Raw) {
                $this->s6->CurrentValue = HtmlDecode($this->s6->CurrentValue);
            }
            $this->s6->EditValue = HtmlEncode($this->s6->CurrentValue);

            // s7
            $this->s7->EditAttrs["class"] = "form-control";
            $this->s7->EditCustomAttributes = "";
            if (!$this->s7->Raw) {
                $this->s7->CurrentValue = HtmlDecode($this->s7->CurrentValue);
            }
            $this->s7->EditValue = HtmlEncode($this->s7->CurrentValue);

            // s8
            $this->s8->EditAttrs["class"] = "form-control";
            $this->s8->EditCustomAttributes = "";
            if (!$this->s8->Raw) {
                $this->s8->CurrentValue = HtmlDecode($this->s8->CurrentValue);
            }
            $this->s8->EditValue = HtmlEncode($this->s8->CurrentValue);

            // nas
            $this->nas->EditAttrs["class"] = "form-control";
            $this->nas->EditCustomAttributes = "";
            if (!$this->nas->Raw) {
                $this->nas->CurrentValue = HtmlDecode($this->nas->CurrentValue);
            }
            $this->nas->EditValue = HtmlEncode($this->nas->CurrentValue);

            // sts
            $this->sts->EditAttrs["class"] = "form-control";
            $this->sts->EditCustomAttributes = "";
            if (!$this->sts->Raw) {
                $this->sts->CurrentValue = HtmlDecode($this->sts->CurrentValue);
            }
            $this->sts->EditValue = HtmlEncode($this->sts->CurrentValue);

            // sas
            $this->sas->EditAttrs["class"] = "form-control";
            $this->sas->EditCustomAttributes = "";
            if (!$this->sas->Raw) {
                $this->sas->CurrentValue = HtmlDecode($this->sas->CurrentValue);
            }
            $this->sas->EditValue = HtmlEncode($this->sas->CurrentValue);

            // nr1
            $this->nr1->EditAttrs["class"] = "form-control";
            $this->nr1->EditCustomAttributes = "";
            if (!$this->nr1->Raw) {
                $this->nr1->CurrentValue = HtmlDecode($this->nr1->CurrentValue);
            }
            $this->nr1->EditValue = HtmlEncode($this->nr1->CurrentValue);

            // nr2
            $this->nr2->EditAttrs["class"] = "form-control";
            $this->nr2->EditCustomAttributes = "";
            if (!$this->nr2->Raw) {
                $this->nr2->CurrentValue = HtmlDecode($this->nr2->CurrentValue);
            }
            $this->nr2->EditValue = HtmlEncode($this->nr2->CurrentValue);

            // Edit refer script

            // nilai_s_id
            $this->nilai_s_id->LinkCustomAttributes = "";
            $this->nilai_s_id->HrefValue = "";

            // guru_id
            $this->guru_id->LinkCustomAttributes = "";
            $this->guru_id->HrefValue = "";
            $this->guru_id->TooltipValue = "";

            // kode_mapel
            $this->kode_mapel->LinkCustomAttributes = "";
            $this->kode_mapel->HrefValue = "";
            $this->kode_mapel->TooltipValue = "";

            // kelas
            $this->kelas->LinkCustomAttributes = "";
            $this->kelas->HrefValue = "";
            $this->kelas->TooltipValue = "";

            // nis
            $this->nis->LinkCustomAttributes = "";
            $this->nis->HrefValue = "";
            $this->nis->TooltipValue = "";

            // nisn
            $this->nisn->LinkCustomAttributes = "";
            $this->nisn->HrefValue = "";

            // nama
            $this->nama->LinkCustomAttributes = "";
            $this->nama->HrefValue = "";
            $this->nama->TooltipValue = "";

            // jk
            $this->jk->LinkCustomAttributes = "";
            $this->jk->HrefValue = "";
            $this->jk->TooltipValue = "";

            // s1
            $this->s1->LinkCustomAttributes = "";
            $this->s1->HrefValue = "";

            // s2
            $this->s2->LinkCustomAttributes = "";
            $this->s2->HrefValue = "";

            // s3
            $this->s3->LinkCustomAttributes = "";
            $this->s3->HrefValue = "";

            // s4
            $this->s4->LinkCustomAttributes = "";
            $this->s4->HrefValue = "";

            // s5
            $this->s5->LinkCustomAttributes = "";
            $this->s5->HrefValue = "";

            // s6
            $this->s6->LinkCustomAttributes = "";
            $this->s6->HrefValue = "";

            // s7
            $this->s7->LinkCustomAttributes = "";
            $this->s7->HrefValue = "";

            // s8
            $this->s8->LinkCustomAttributes = "";
            $this->s8->HrefValue = "";

            // nas
            $this->nas->LinkCustomAttributes = "";
            $this->nas->HrefValue = "";

            // sts
            $this->sts->LinkCustomAttributes = "";
            $this->sts->HrefValue = "";

            // sas
            $this->sas->LinkCustomAttributes = "";
            $this->sas->HrefValue = "";

            // nr1
            $this->nr1->LinkCustomAttributes = "";
            $this->nr1->HrefValue = "";

            // nr2
            $this->nr2->LinkCustomAttributes = "";
            $this->nr2->HrefValue = "";
        }
        if ($this->RowType == ROWTYPE_ADD || $this->RowType == ROWTYPE_EDIT || $this->RowType == ROWTYPE_SEARCH) { // Add/Edit/Search row
            $this->setupFieldTitles();
        }

        // Call Row Rendered event
        if ($this->RowType != ROWTYPE_AGGREGATEINIT) {
            $this->rowRendered();
        }
    }

    // Validate form
    protected function validateForm()
    {
        global $Language;

        // Check if validation required
        if (!Config("SERVER_VALIDATE")) {
            return true;
        }
        if ($this->nilai_s_id->Required) {
            if (!$this->nilai_s_id->IsDetailKey && EmptyValue($this->nilai_s_id->FormValue)) {
                $this->nilai_s_id->addErrorMessage(str_replace("%s", $this->nilai_s_id->caption(), $this->nilai_s_id->RequiredErrorMessage));
            }
        }
        if ($this->guru_id->Required) {
            if (!$this->guru_id->IsDetailKey && EmptyValue($this->guru_id->FormValue)) {
                $this->guru_id->addErrorMessage(str_replace("%s", $this->guru_id->caption(), $this->guru_id->RequiredErrorMessage));
            }
        }
        if ($this->kode_mapel->Required) {
            if (!$this->kode_mapel->IsDetailKey && EmptyValue($this->kode_mapel->FormValue)) {
                $this->kode_mapel->addErrorMessage(str_replace("%s", $this->kode_mapel->caption(), $this->kode_mapel->RequiredErrorMessage));
            }
        }
        if ($this->kelas->Required) {
            if (!$this->kelas->IsDetailKey && EmptyValue($this->kelas->FormValue)) {
                $this->kelas->addErrorMessage(str_replace("%s", $this->kelas->caption(), $this->kelas->RequiredErrorMessage));
            }
        }
        if ($this->nis->Required) {
            if (!$this->nis->IsDetailKey && EmptyValue($this->nis->FormValue)) {
                $this->nis->addErrorMessage(str_replace("%s", $this->nis->caption(), $this->nis->RequiredErrorMessage));
            }
        }
        if ($this->nisn->Required) {
            if (!$this->nisn->IsDetailKey && EmptyValue($this->nisn->FormValue)) {
                $this->nisn->addErrorMessage(str_replace("%s", $this->nisn->caption(), $this->nisn->RequiredErrorMessage));
            }
        }
        if ($this->nama->Required) {
            if (!$this->nama->IsDetailKey && EmptyValue($this->nama->FormValue)) {
                $this->nama->addErrorMessage(str_replace("%s", $this->nama->caption(), $this->nama->RequiredErrorMessage));
            }
        }
        if ($this->jk->Required) {
            if (!$this->jk->IsDetailKey && EmptyValue($this->jk->FormValue)) {
                $this->jk->addErrorMessage(str_replace("%s", $this->jk->caption(), $this->jk->RequiredErrorMessage));
            }
        }
        if ($this->s1->Required) {
            if (!$this->s1->IsDetailKey && EmptyValue($this->s1->FormValue)) {
                $this->s1->addErrorMessage(str_replace("%s", $this->s1->caption(), $this->s1->RequiredErrorMessage));
            }
        }
        if ($this->s2->Required) {
            if (!$this->s2->IsDetailKey && EmptyValue($this->s2->FormValue)) {
                $this->s2->addErrorMessage(str_replace("%s", $this->s2->caption(), $this->s2->RequiredErrorMessage));
            }
        }
        if ($this->s3->Required) {
            if (!$this->s3->IsDetailKey && EmptyValue($this->s3->FormValue)) {
                $this->s3->addErrorMessage(str_replace("%s", $this->s3->caption(), $this->s3->RequiredErrorMessage));
            }
        }
        if ($this->s4->Required) {
            if (!$this->s4->IsDetailKey && EmptyValue($this->s4->FormValue)) {
                $this->s4->addErrorMessage(str_replace("%s", $this->s4->caption(), $this->s4->RequiredErrorMessage));
            }
        }
        if ($this->s5->Required) {
            if (!$this->s5->IsDetailKey && EmptyValue($this->s5->FormValue)) {
                $this->s5->addErrorMessage(str_replace("%s", $this->s5->caption(), $this->s5->RequiredErrorMessage));
            }
        }
        if ($this->s6->Required) {
            if (!$this->s6->IsDetailKey && EmptyValue($this->s6->FormValue)) {
                $this->s6->addErrorMessage(str_replace("%s", $this->s6->caption(), $this->s6->RequiredErrorMessage));
            }
        }
        if ($this->s7->Required) {
            if (!$this->s7->IsDetailKey && EmptyValue($this->s7->FormValue)) {
                $this->s7->addErrorMessage(str_replace("%s", $this->s7->caption(), $this->s7->RequiredErrorMessage));
            }
        }
        if ($this->s8->Required) {
            if (!$this->s8->IsDetailKey && EmptyValue($this->s8->FormValue)) {
                $this->s8->addErrorMessage(str_replace("%s", $this->s8->caption(), $this->s8->RequiredErrorMessage));
            }
        }
        if ($this->nas->Required) {
            if (!$this->nas->IsDetailKey && EmptyValue($this->nas->FormValue)) {
                $this->nas->addErrorMessage(str_replace("%s", $this->nas->caption(), $this->nas->RequiredErrorMessage));
            }
        }
        if ($this->sts->Required) {
            if (!$this->sts->IsDetailKey && EmptyValue($this->sts->FormValue)) {
                $this->sts->addErrorMessage(str_replace("%s", $this->sts->caption(), $this->sts->RequiredErrorMessage));
            }
        }
        if ($this->sas->Required) {
            if (!$this->sas->IsDetailKey && EmptyValue($this->sas->FormValue)) {
                $this->sas->addErrorMessage(str_replace("%s", $this->sas->caption(), $this->sas->RequiredErrorMessage));
            }
        }
        if ($this->nr1->Required) {
            if (!$this->nr1->IsDetailKey && EmptyValue($this->nr1->FormValue)) {
                $this->nr1->addErrorMessage(str_replace("%s", $this->nr1->caption(), $this->nr1->RequiredErrorMessage));
            }
        }
        if ($this->nr2->Required) {
            if (!$this->nr2->IsDetailKey && EmptyValue($this->nr2->FormValue)) {
                $this->nr2->addErrorMessage(str_replace("%s", $this->nr2->caption(), $this->nr2->RequiredErrorMessage));
            }
        }

        // Return validate result
        $validateForm = !$this->hasInvalidFields();

        // Call Form_CustomValidate event
        $formCustomError = "";
        $validateForm = $validateForm && $this->formCustomValidate($formCustomError);
        if ($formCustomError != "") {
            $this->setFailureMessage($formCustomError);
        }
        return $validateForm;
    }

    // Delete records based on current filter
    protected function deleteRows()
    {
        global $Language, $Security;
        if (!$Security->canDelete()) {
            $this->setFailureMessage($Language->phrase("NoDeletePermission")); // No delete permission
            return false;
        }
        $deleteRows = true;
        $sql = $this->getCurrentSql();
        $conn = $this->getConnection();
        $rows = $conn->fetchAll($sql);
        if (count($rows) == 0) {
            $this->setFailureMessage($Language->phrase("NoRecord")); // No record found
            return false;
        }

        // Clone old rows
        $rsold = $rows;

        // Call row deleting event
        if ($deleteRows) {
            foreach ($rsold as $row) {
                $deleteRows = $this->rowDeleting($row);
                if (!$deleteRows) {
                    break;
                }
            }
        }
        if ($deleteRows) {
            $key = "";
            foreach ($rsold as $row) {
                $thisKey = "";
                if ($thisKey != "") {
                    $thisKey .= Config("COMPOSITE_KEY_SEPARATOR");
                }
                $thisKey .= $row['nilai_s_id'];
                if (Config("DELETE_UPLOADED_FILES")) { // Delete old files
                    $this->deleteUploadedFiles($row);
                }
                $deleteRows = $this->delete($row); // Delete
                if ($deleteRows === false) {
                    break;
                }
                if ($key != "") {
                    $key .= ", ";
                }
                $key .= $thisKey;
            }
        }
        if (!$deleteRows) {
            // Set up error message
            if ($this->getSuccessMessage() != "" || $this->getFailureMessage() != "") {
                // Use the message, do nothing
            } elseif ($this->CancelMessage != "") {
                $this->setFailureMessage($this->CancelMessage);
                $this->CancelMessage = "";
            } else {
                $this->setFailureMessage($Language->phrase("DeleteCancelled"));
            }
        }

        // Call Row Deleted event
        if ($deleteRows) {
            foreach ($rsold as $row) {
                $this->rowDeleted($row);
            }
        }

        // Write JSON for API request
        if (IsApi() && $deleteRows) {
            $row = $this->getRecordsFromRecordset($rsold);
            WriteJson(["success" => true, $this->TableVar => $row]);
        }
        return $deleteRows;
    }

    // Update record based on key values
    protected function editRow()
    {
        global $Security, $Language;
        $oldKeyFilter = $this->getRecordFilter();
        $filter = $this->applyUserIDFilters($oldKeyFilter);
        $conn = $this->getConnection();
        $this->CurrentFilter = $filter;
        $sql = $this->getCurrentSql();
        $rsold = $conn->fetchAssoc($sql);
        $editRow = false;
        if (!$rsold) {
            $this->setFailureMessage($Language->phrase("NoRecord")); // Set no record message
            $editRow = false; // Update Failed
        } else {
            // Save old values
            $this->loadDbValues($rsold);
            $rsnew = [];

            // nisn
            $this->nisn->setDbValueDef($rsnew, $this->nisn->CurrentValue, null, $this->nisn->ReadOnly);

            // s1
            $this->s1->setDbValueDef($rsnew, $this->s1->CurrentValue, null, $this->s1->ReadOnly);

            // s2
            $this->s2->setDbValueDef($rsnew, $this->s2->CurrentValue, null, $this->s2->ReadOnly);

            // s3
            $this->s3->setDbValueDef($rsnew, $this->s3->CurrentValue, null, $this->s3->ReadOnly);

            // s4
            $this->s4->setDbValueDef($rsnew, $this->s4->CurrentValue, null, $this->s4->ReadOnly);

            // s5
            $this->s5->setDbValueDef($rsnew, $this->s5->CurrentValue, null, $this->s5->ReadOnly);

            // s6
            $this->s6->setDbValueDef($rsnew, $this->s6->CurrentValue, null, $this->s6->ReadOnly);

            // s7
            $this->s7->setDbValueDef($rsnew, $this->s7->CurrentValue, null, $this->s7->ReadOnly);

            // s8
            $this->s8->setDbValueDef($rsnew, $this->s8->CurrentValue, null, $this->s8->ReadOnly);

            // nas
            $this->nas->setDbValueDef($rsnew, $this->nas->CurrentValue, null, $this->nas->ReadOnly);

            // sts
            $this->sts->setDbValueDef($rsnew, $this->sts->CurrentValue, null, $this->sts->ReadOnly);

            // sas
            $this->sas->setDbValueDef($rsnew, $this->sas->CurrentValue, null, $this->sas->ReadOnly);

            // nr1
            $this->nr1->setDbValueDef($rsnew, $this->nr1->CurrentValue, null, $this->nr1->ReadOnly);

            // nr2
            $this->nr2->setDbValueDef($rsnew, $this->nr2->CurrentValue, null, $this->nr2->ReadOnly);

            // Check referential integrity for master table 'penilaian'
            $validMasterRecord = true;
            $masterFilter = $this->sqlMasterFilter_penilaian();
            $keyValue = $rsnew['penilaian_id'] ?? $rsold['penilaian_id'];
            if (strval($keyValue) != "") {
                $masterFilter = str_replace("@penilaian_id@", AdjustSql($keyValue), $masterFilter);
            } else {
                $validMasterRecord = false;
            }
            if ($validMasterRecord) {
                $rsmaster = Container("penilaian")->loadRs($masterFilter)->fetch();
                $validMasterRecord = $rsmaster !== false;
            }
            if (!$validMasterRecord) {
                $relatedRecordMsg = str_replace("%t", "penilaian", $Language->phrase("RelatedRecordRequired"));
                $this->setFailureMessage($relatedRecordMsg);
                return false;
            }

            // Call Row Updating event
            $updateRow = $this->rowUpdating($rsold, $rsnew);
            if ($updateRow) {
                if (count($rsnew) > 0) {
                    try {
                        $editRow = $this->update($rsnew, "", $rsold);
                    } catch (\Exception $e) {
                        $this->setFailureMessage($e->getMessage());
                    }
                } else {
                    $editRow = true; // No field to update
                }
                if ($editRow) {
                }
            } else {
                if ($this->getSuccessMessage() != "" || $this->getFailureMessage() != "") {
                    // Use the message, do nothing
                } elseif ($this->CancelMessage != "") {
                    $this->setFailureMessage($this->CancelMessage);
                    $this->CancelMessage = "";
                } else {
                    $this->setFailureMessage($Language->phrase("UpdateCancelled"));
                }
                $editRow = false;
            }
        }

        // Call Row_Updated event
        if ($editRow) {
            $this->rowUpdated($rsold, $rsnew);
        }

        // Clean upload path if any
        if ($editRow) {
        }

        // Write JSON for API request
        if (IsApi() && $editRow) {
            $row = $this->getRecordsFromRecordset([$rsnew], true);
            WriteJson(["success" => true, $this->TableVar => $row]);
        }
        return $editRow;
    }

    // Add record
    protected function addRow($rsold = null)
    {
        global $Language, $Security;

        // Check if valid key values for master user
        if ($Security->currentUserID() != "" && !$Security->isAdmin()) { // Non system admin
            $masterFilter = $this->sqlMasterFilter_penilaian();
            if (strval($this->penilaian_id->CurrentValue) != "") {
                $masterFilter = str_replace("@penilaian_id@", AdjustSql($this->penilaian_id->CurrentValue, "DB"), $masterFilter);
            } else {
                $masterFilter = "";
            }
            if ($masterFilter != "") {
                $rsmaster = Container("penilaian")->loadRs($masterFilter)->fetch(\PDO::FETCH_ASSOC);
                $masterRecordExists = $rsmaster !== false;
                $validMasterKey = true;
                if ($masterRecordExists) {
                    $validMasterKey = $Security->isValidUserID($rsmaster['guru_id']);
                } elseif ($this->getCurrentMasterTable() == "penilaian") {
                    $validMasterKey = false;
                }
                if (!$validMasterKey) {
                    $masterUserIdMsg = str_replace("%c", CurrentUserID(), $Language->phrase("UnAuthorizedMasterUserID"));
                    $masterUserIdMsg = str_replace("%f", $masterFilter, $masterUserIdMsg);
                    $this->setFailureMessage($masterUserIdMsg);
                    return false;
                }
            }
        }

        // Set up foreign key field value from Session
        if ($this->getCurrentMasterTable() == "penilaian") {
            $this->penilaian_id->CurrentValue = $this->penilaian_id->getSessionValue();
        }

        // Check referential integrity for master table 'nilai_sumatif'
        $validMasterRecord = true;
        $masterFilter = $this->sqlMasterFilter_penilaian();
        if ($this->penilaian_id->getSessionValue() != "") {
        $masterFilter = str_replace("@penilaian_id@", AdjustSql($this->penilaian_id->getSessionValue(), "DB"), $masterFilter);
        } else {
            $validMasterRecord = false;
        }
        if ($validMasterRecord) {
            $rsmaster = Container("penilaian")->loadRs($masterFilter)->fetch();
            $validMasterRecord = $rsmaster !== false;
        }
        if (!$validMasterRecord) {
            $relatedRecordMsg = str_replace("%t", "penilaian", $Language->phrase("RelatedRecordRequired"));
            $this->setFailureMessage($relatedRecordMsg);
            return false;
        }
        $conn = $this->getConnection();

        // Load db values from rsold
        $this->loadDbValues($rsold);
        if ($rsold) {
        }
        $rsnew = [];

        // guru_id
        $this->guru_id->setDbValueDef($rsnew, $this->guru_id->CurrentValue, null, false);

        // kode_mapel
        $this->kode_mapel->setDbValueDef($rsnew, $this->kode_mapel->CurrentValue, null, false);

        // kelas
        $this->kelas->setDbValueDef($rsnew, $this->kelas->CurrentValue, null, false);

        // nis
        $this->nis->setDbValueDef($rsnew, $this->nis->CurrentValue, null, false);

        // nisn
        $this->nisn->setDbValueDef($rsnew, $this->nisn->CurrentValue, null, false);

        // nama
        $this->nama->setDbValueDef($rsnew, $this->nama->CurrentValue, null, false);

        // jk
        $this->jk->setDbValueDef($rsnew, $this->jk->CurrentValue, null, false);

        // s1
        $this->s1->setDbValueDef($rsnew, $this->s1->CurrentValue, null, false);

        // s2
        $this->s2->setDbValueDef($rsnew, $this->s2->CurrentValue, null, false);

        // s3
        $this->s3->setDbValueDef($rsnew, $this->s3->CurrentValue, null, false);

        // s4
        $this->s4->setDbValueDef($rsnew, $this->s4->CurrentValue, null, false);

        // s5
        $this->s5->setDbValueDef($rsnew, $this->s5->CurrentValue, null, false);

        // s6
        $this->s6->setDbValueDef($rsnew, $this->s6->CurrentValue, null, false);

        // s7
        $this->s7->setDbValueDef($rsnew, $this->s7->CurrentValue, null, false);

        // s8
        $this->s8->setDbValueDef($rsnew, $this->s8->CurrentValue, null, false);

        // nas
        $this->nas->setDbValueDef($rsnew, $this->nas->CurrentValue, null, false);

        // sts
        $this->sts->setDbValueDef($rsnew, $this->sts->CurrentValue, null, false);

        // sas
        $this->sas->setDbValueDef($rsnew, $this->sas->CurrentValue, null, false);

        // nr1
        $this->nr1->setDbValueDef($rsnew, $this->nr1->CurrentValue, null, false);

        // nr2
        $this->nr2->setDbValueDef($rsnew, $this->nr2->CurrentValue, null, false);

        // penilaian_id
        if ($this->penilaian_id->getSessionValue() != "") {
            $rsnew['penilaian_id'] = $this->penilaian_id->getSessionValue();
        }

        // Call Row Inserting event
        $insertRow = $this->rowInserting($rsold, $rsnew);
        $addRow = false;
        if ($insertRow) {
            try {
                $addRow = $this->insert($rsnew);
            } catch (\Exception $e) {
                $this->setFailureMessage($e->getMessage());
            }
            if ($addRow) {
            }
        } else {
            if ($this->getSuccessMessage() != "" || $this->getFailureMessage() != "") {
                // Use the message, do nothing
            } elseif ($this->CancelMessage != "") {
                $this->setFailureMessage($this->CancelMessage);
                $this->CancelMessage = "";
            } else {
                $this->setFailureMessage($Language->phrase("InsertCancelled"));
            }
            $addRow = false;
        }
        if ($addRow) {
            // Call Row Inserted event
            $this->rowInserted($rsold, $rsnew);
        }

        // Clean upload path if any
        if ($addRow) {
        }

        // Write JSON for API request
        if (IsApi() && $addRow) {
            $row = $this->getRecordsFromRecordset([$rsnew], true);
            WriteJson(["success" => true, $this->TableVar => $row]);
        }
        return $addRow;
    }

    // Set up master/detail based on QueryString
    protected function setupMasterParms()
    {
        // Hide foreign keys
        $masterTblVar = $this->getCurrentMasterTable();
        if ($masterTblVar == "penilaian") {
            $masterTbl = Container("penilaian");
            $this->penilaian_id->Visible = false;
            if ($masterTbl->EventCancelled) {
                $this->EventCancelled = true;
            }
        }
        $this->DbMasterFilter = $this->getMasterFilter(); // Get master filter
        $this->DbDetailFilter = $this->getDetailFilter(); // Get detail filter
    }

    // Setup lookup options
    public function setupLookupOptions($fld)
    {
        if ($fld->Lookup !== null && $fld->Lookup->Options === null) {
            // Get default connection and filter
            $conn = $this->getConnection();
            $lookupFilter = "";

            // No need to check any more
            $fld->Lookup->Options = [];

            // Set up lookup SQL and connection
            switch ($fld->FieldVar) {
                case "x_kode_mapel":
                    break;
                case "x_kelas":
                    $lookupFilter = function () {
                        return "`kode_tapel`='".kode_tapel()."'";
                    };
                    $lookupFilter = $lookupFilter->bindTo($this);
                    break;
                default:
                    $lookupFilter = "";
                    break;
            }

            // Always call to Lookup->getSql so that user can setup Lookup->Options in Lookup_Selecting server event
            $sql = $fld->Lookup->getSql(false, "", $lookupFilter, $this);

            // Set up lookup cache
            if ($fld->UseLookupCache && $sql != "" && count($fld->Lookup->Options) == 0) {
                $totalCnt = $this->getRecordCount($sql, $conn);
                if ($totalCnt > $fld->LookupCacheCount) { // Total count > cache count, do not cache
                    return;
                }
                $rows = $conn->executeQuery($sql)->fetchAll(\PDO::FETCH_BOTH);
                $ar = [];
                foreach ($rows as $row) {
                    $row = $fld->Lookup->renderViewRow($row);
                    $ar[strval($row[0])] = $row;
                }
                $fld->Lookup->Options = $ar;
            }
        }
    }

    // Page Load event
    public function pageLoad()
    {
        //Log("Page Load");
    }

    // Page Unload event
    public function pageUnload()
    {
        //Log("Page Unload");
    }

    // Page Redirecting event
    public function pageRedirecting(&$url)
    {
        // Example:
        //$url = "your URL";
    }

    // Message Showing event
    // $type = ''|'success'|'failure'|'warning'
    public function messageShowing(&$msg, $type)
    {
        if ($type == 'success') {
            //$msg = "your success message";
        } elseif ($type == 'failure') {
            //$msg = "your failure message";
        } elseif ($type == 'warning') {
            //$msg = "your warning message";
        } else {
            //$msg = "your message";
        }
    }

    // Page Render event
    public function pageRender()
    {
        $this->OtherOptions["addedit"]->UseDropDownButton = FALSE;
        $my_options = &$this->OtherOptions;
        $my_option = $my_options["addedit"];

        // Tambahkan tombol "Reload" dengan script
        $my_item = &$my_option->Add("Reload");
        $my_item->Body = "
            <a 
                class=\"ewAddEdit ewAdd btn btn-success m-1\" 
                href=\"PenilaianList\" 
                data-caption=\"Reload\">
                << Kembali
            </a>
            <a 
                class=\"ewAddEdit ewAdd btn btn-warning m-1\" 
                href=\"act.php?pis=" . base64_encode($_GET['fk_penilaian_id']) . "\" 
                data-caption=\"Reload\">
                Hitung Nilai
            </a>
        ";
    }

    // Page Data Rendering event
    public function pageDataRendering(&$header)
    {
        // Example:
         include "tool/petunjuk.php";
        //$header = "your header";
    }

    // Page Data Rendered event
    public function pageDataRendered(&$footer)
    {
        // Example:
        //$footer = "your footer";
    }

    // Form Custom Validate event
    public function formCustomValidate(&$customError)
    {
        // Return error message in CustomError
        return true;
    }

    // ListOptions Load event
    public function listOptionsLoad()
    {
        // Example:
        //$opt = &$this->ListOptions->Add("new");
        //$opt->Header = "xxx";
        //$opt->OnLeft = true; // Link on left
        //$opt->MoveTo(0); // Move to first column
    }

    // ListOptions Rendering event
    public function listOptionsRendering()
    {
        //Container("DetailTableGrid")->DetailAdd = (...condition...); // Set to true or false conditionally
        //Container("DetailTableGrid")->DetailEdit = (...condition...); // Set to true or false conditionally
        //Container("DetailTableGrid")->DetailView = (...condition...); // Set to true or false conditionally
    }

    // ListOptions Rendered event
    public function listOptionsRendered()
    {
        // Example:
        //$this->ListOptions["new"]->Body = "xxx";
    }
}
