<?php

namespace PHPMaker2021\rdigital21;

use Doctrine\DBAL\ParameterType;

/**
 * Page class
 */
class PenilaianEdit extends Penilaian
{
    use MessagesTrait;

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

    // Project ID
    public $ProjectID = PROJECT_ID;

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

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

    // Rendering View
    public $RenderingView = false;

    // 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
        $GLOBALS["Page"] = &$this;

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

        // Parent constuctor
        parent::__construct();

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

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

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

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

        // Debug message
        LoadDebugMessage();

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

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

    // 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;
        global $OldSkipHeaderFooter, $SkipHeaderFooter;
        $SkipHeaderFooter = $OldSkipHeaderFooter;

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

        // Global Page Unloaded event (in userfn*.php)
        Page_Unloaded();

        // 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("penilaian"));
                $doc->Text = @$content;
                if ($this->isExport("email")) {
                    echo $this->exportEmail($doc->Text);
                } else {
                    $doc->export();
                }
                DeleteTempImages(); // Delete temp images
                return;
            }
        }
        if (!IsApi() && method_exists($this, "pageRedirecting")) {
            $this->pageRedirecting($url);
        }

        // Close connection
        CloseConnections();

        // 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();
            }

            // Handle modal response
            if ($this->IsModal) { // Show as modal
                $row = ["url" => GetUrl($url), "modal" => "1"];
                $pageName = GetPageName($url);
                if ($pageName != $this->getListUrl()) { // Not List page
                    $row["caption"] = $this->getModalCaption($pageName);
                    if ($pageName == "PenilaianView") {
                        $row["view"] = "1";
                    }
                } else { // List page should not be shown as modal => error
                    $row["error"] = $this->getFailureMessage();
                    $this->clearFailureMessage();
                }
                WriteJson($row);
            } else {
                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['penilaian_id'];
        }
        return $key;
    }

    /**
     * Hide fields for add/edit
     *
     * @return void
     */
    protected function hideFieldsForAddEdit()
    {
        if ($this->isAdd() || $this->isCopy() || $this->isGridAdd()) {
            $this->penilaian_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
    }
    public $FormClassName = "ew-horizontal ew-form ew-edit-form";
    public $IsModal = false;
    public $IsMobileOrModal = false;
    public $DbMasterFilter;
    public $DbDetailFilter;
    public $HashValue; // Hash Value
    public $DisplayRecords = 1;
    public $StartRecord;
    public $StopRecord;
    public $TotalRecords = 0;
    public $RecordRange = 10;
    public $RecordCount;

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

        // Is modal
        $this->IsModal = Param("modal") == "1";

        // Create form object
        $CurrentForm = new HttpForm();
        $this->CurrentAction = Param("action"); // Set up current action
        global $OldSkipHeaderFooter, $SkipHeaderFooter;
        $OldSkipHeaderFooter = $SkipHeaderFooter;
        $SkipHeaderFooter = true;
        $this->penilaian_id->setVisibility();
        $this->kode_tapel->setVisibility();
        $this->guru_id->setVisibility();
        $this->mapel_id->setVisibility();
        $this->kelas->setVisibility();
        $this->materi->setVisibility();
        $this->tujuan_pembelajaran->setVisibility();
        $this->fase->setVisibility();
        $this->hideFieldsForAddEdit();

        // Do not use lookup cache
        $this->setUseLookupCache(false);

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

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

        // Set up lookup cache
        $this->setupLookupOptions($this->guru_id);
        $this->setupLookupOptions($this->mapel_id);
        $this->setupLookupOptions($this->kelas);
        $this->setupLookupOptions($this->materi);
        $this->setupLookupOptions($this->tujuan_pembelajaran);

        // Check modal
        if ($this->IsModal) {
            $SkipHeaderFooter = true;
        }
        $this->IsMobileOrModal = IsMobile() || $this->IsModal;
        $this->FormClassName = "ew-form ew-edit-form ew-horizontal";
        $loaded = false;
        $postBack = false;

        // Set up current action and primary key
        if (IsApi()) {
            // Load key values
            $loaded = true;
            if (($keyValue = Get("penilaian_id") ?? Key(0) ?? Route(2)) !== null) {
                $this->penilaian_id->setQueryStringValue($keyValue);
                $this->penilaian_id->setOldValue($this->penilaian_id->QueryStringValue);
            } elseif (Post("penilaian_id") !== null) {
                $this->penilaian_id->setFormValue(Post("penilaian_id"));
                $this->penilaian_id->setOldValue($this->penilaian_id->FormValue);
            } else {
                $loaded = false; // Unable to load key
            }

            // Load record
            if ($loaded) {
                $loaded = $this->loadRow();
            }
            if (!$loaded) {
                $this->setFailureMessage($Language->phrase("NoRecord")); // Set no record message
                $this->terminate();
                return;
            }
            $this->CurrentAction = "update"; // Update record directly
            $this->OldKey = $this->getKey(true); // Get from CurrentValue
            $postBack = true;
        } else {
            if (Post("action") !== null) {
                $this->CurrentAction = Post("action"); // Get action code
                if (!$this->isShow()) { // Not reload record, handle as postback
                    $postBack = true;
                }

                // Get key from Form
                $this->setKey(Post($this->OldKeyName), $this->isShow());
            } else {
                $this->CurrentAction = "show"; // Default action is display

                // Load key from QueryString
                $loadByQuery = false;
                if (($keyValue = Get("penilaian_id") ?? Route("penilaian_id")) !== null) {
                    $this->penilaian_id->setQueryStringValue($keyValue);
                    $loadByQuery = true;
                } else {
                    $this->penilaian_id->CurrentValue = null;
                }
            }

            // Load recordset
            if ($this->isShow()) {
                // Load current record
                $loaded = $this->loadRow();
                $this->OldKey = $loaded ? $this->getKey(true) : ""; // Get from CurrentValue
            }
        }

        // Process form if post back
        if ($postBack) {
            $this->loadFormValues(); // Get form values

            // Set up detail parameters
            $this->setupDetailParms();
        }

        // Validate form if post back
        if ($postBack) {
            if (!$this->validateForm()) {
                $this->EventCancelled = true; // Event cancelled
                $this->restoreFormValues();
                if (IsApi()) {
                    $this->terminate();
                    return;
                } else {
                    $this->CurrentAction = ""; // Form error, reset action
                }
            }
        }

        // Perform current action
        switch ($this->CurrentAction) {
            case "show": // Get a record to display
                if (!$loaded) { // Load record based on key
                    if ($this->getFailureMessage() == "") {
                        $this->setFailureMessage($Language->phrase("NoRecord")); // No record found
                    }
                    $this->terminate("PenilaianList"); // No matching record, return to list
                    return;
                }

                // Set up detail parameters
                $this->setupDetailParms();
                break;
            case "update": // Update
                if ($this->getCurrentDetailTable() != "") { // Master/detail edit
                    $returnUrl = $this->getViewUrl(Config("TABLE_SHOW_DETAIL") . "=" . $this->getCurrentDetailTable()); // Master/Detail view page
                } else {
                    $returnUrl = $this->getReturnUrl();
                }
                if (GetPageName($returnUrl) == "PenilaianList") {
                    $returnUrl = $this->addMasterUrl($returnUrl); // List page, return to List page with correct master key if necessary
                }
                $this->SendEmail = true; // Send email on update success
                if ($this->editRow()) { // Update record based on key
                    if ($this->getSuccessMessage() == "") {
                        $this->setSuccessMessage($Language->phrase("UpdateSuccess")); // Update success
                    }
                    if (IsApi()) {
                        $this->terminate(true);
                        return;
                    } else {
                        $this->terminate($returnUrl); // Return to caller
                        return;
                    }
                } elseif (IsApi()) { // API request, return
                    $this->terminate();
                    return;
                } elseif ($this->getFailureMessage() == $Language->phrase("NoRecord")) {
                    $this->terminate($returnUrl); // Return to caller
                    return;
                } else {
                    $this->EventCancelled = true; // Event cancelled
                    $this->restoreFormValues(); // Restore form values if update failed

                    // Set up detail parameters
                    $this->setupDetailParms();
                }
        }

        // Set up Breadcrumb
        $this->setupBreadcrumb();

        // Render the record
        $this->RowType = ROWTYPE_EDIT; // Render as Edit
        $this->resetAttributes();
        $this->renderRow();

        // 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();
            }
        }
    }

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

    // Load form values
    protected function loadFormValues()
    {
        // Load from form
        global $CurrentForm;

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

        // Check field name 'kode_tapel' first before field var 'x_kode_tapel'
        $val = $CurrentForm->hasValue("kode_tapel") ? $CurrentForm->getValue("kode_tapel") : $CurrentForm->getValue("x_kode_tapel");
        if (!$this->kode_tapel->IsDetailKey) {
            if (IsApi() && $val === null) {
                $this->kode_tapel->Visible = false; // Disable update for API request
            } else {
                $this->kode_tapel->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);
            }
        }

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

        // 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);
            }
        }

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

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

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

    // Restore form values
    public function restoreFormValues()
    {
        global $CurrentForm;
        $this->penilaian_id->CurrentValue = $this->penilaian_id->FormValue;
        $this->kode_tapel->CurrentValue = $this->kode_tapel->FormValue;
        $this->guru_id->CurrentValue = $this->guru_id->FormValue;
        $this->mapel_id->CurrentValue = $this->mapel_id->FormValue;
        $this->kelas->CurrentValue = $this->kelas->FormValue;
        $this->materi->CurrentValue = $this->materi->FormValue;
        $this->tujuan_pembelajaran->CurrentValue = $this->tujuan_pembelajaran->FormValue;
        $this->fase->CurrentValue = $this->fase->FormValue;
    }

    /**
     * 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
        }

        // Check if valid User ID
        if ($res) {
            $res = $this->showOptionLink("edit");
            if (!$res) {
                $userIdMsg = DeniedMessage();
                $this->setFailureMessage($userIdMsg);
            }
        }
        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->penilaian_id->setDbValue($row['penilaian_id']);
        $this->kode_tapel->setDbValue($row['kode_tapel']);
        $this->guru_id->setDbValue($row['guru_id']);
        $this->mapel_id->setDbValue($row['mapel_id']);
        $this->kelas->setDbValue($row['kelas']);
        $this->materi->setDbValue($row['materi']);
        $this->tujuan_pembelajaran->setDbValue($row['tujuan_pembelajaran']);
        $this->fase->setDbValue($row['fase']);
    }

    // Return a row with default values
    protected function newRow()
    {
        $row = [];
        $row['penilaian_id'] = null;
        $row['kode_tapel'] = null;
        $row['guru_id'] = null;
        $row['mapel_id'] = null;
        $row['kelas'] = null;
        $row['materi'] = null;
        $row['tujuan_pembelajaran'] = null;
        $row['fase'] = null;
        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

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

        // Common render codes for all row types

        // penilaian_id

        // kode_tapel

        // guru_id

        // mapel_id

        // kelas

        // materi

        // tujuan_pembelajaran

        // fase
        if ($this->RowType == ROWTYPE_VIEW) {
            // penilaian_id
            $this->penilaian_id->ViewValue = $this->penilaian_id->CurrentValue;
            $this->penilaian_id->ViewCustomAttributes = "";

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

            // guru_id
            $curVal = trim(strval($this->guru_id->CurrentValue));
            if ($curVal != "") {
                $this->guru_id->ViewValue = $this->guru_id->lookupCacheOption($curVal);
                if ($this->guru_id->ViewValue === null) { // Lookup from database
                    $filterWrk = "\"guru_id\"" . SearchString("=", $curVal, DATATYPE_NUMBER, "");
                    $lookupFilter = function() {
                        return "`kode_tapel`='".kode_tapel()."'";
                    };
                    $lookupFilter = $lookupFilter->bindTo($this);
                    $sqlWrk = $this->guru_id->Lookup->getSql(false, $filterWrk, $lookupFilter, $this, true, true);
                    $rswrk = Conn()->executeQuery($sqlWrk)->fetchAll(\PDO::FETCH_BOTH);
                    $ari = count($rswrk);
                    if ($ari > 0) { // Lookup values found
                        $arwrk = $this->guru_id->Lookup->renderViewRow($rswrk[0]);
                        $this->guru_id->ViewValue = $this->guru_id->displayValue($arwrk);
                    } else {
                        $this->guru_id->ViewValue = $this->guru_id->CurrentValue;
                    }
                }
            } else {
                $this->guru_id->ViewValue = null;
            }
            $this->guru_id->ViewCustomAttributes = "";

            // mapel_id
            $curVal = trim(strval($this->mapel_id->CurrentValue));
            if ($curVal != "") {
                $this->mapel_id->ViewValue = $this->mapel_id->lookupCacheOption($curVal);
                if ($this->mapel_id->ViewValue === null) { // Lookup from database
                    $filterWrk = "\"kode_mapel\"" . SearchString("=", $curVal, DATATYPE_STRING, "");
                    $sqlWrk = $this->mapel_id->Lookup->getSql(false, $filterWrk, '', $this, true, true);
                    $rswrk = Conn()->executeQuery($sqlWrk)->fetchAll(\PDO::FETCH_BOTH);
                    $ari = count($rswrk);
                    if ($ari > 0) { // Lookup values found
                        $arwrk = $this->mapel_id->Lookup->renderViewRow($rswrk[0]);
                        $this->mapel_id->ViewValue = $this->mapel_id->displayValue($arwrk);
                    } else {
                        $this->mapel_id->ViewValue = $this->mapel_id->CurrentValue;
                    }
                }
            } else {
                $this->mapel_id->ViewValue = null;
            }
            $this->mapel_id->ViewCustomAttributes = "";

            // kelas
            $curVal = trim(strval($this->kelas->CurrentValue));
            if ($curVal != "") {
                $this->kelas->ViewValue = $this->kelas->lookupCacheOption($curVal);
                if ($this->kelas->ViewValue === null) { // Lookup from database
                    $filterWrk = "\"kelas\"" . SearchString("=", $curVal, DATATYPE_MEMO, "");
                    $lookupFilter = function() {
                        return "`kode_tapel`='".kode_tapel()."'";
                    };
                    $lookupFilter = $lookupFilter->bindTo($this);
                    $sqlWrk = $this->kelas->Lookup->getSql(false, $filterWrk, $lookupFilter, $this, true, true);
                    $rswrk = Conn()->executeQuery($sqlWrk)->fetchAll(\PDO::FETCH_BOTH);
                    $ari = count($rswrk);
                    if ($ari > 0) { // Lookup values found
                        $arwrk = $this->kelas->Lookup->renderViewRow($rswrk[0]);
                        $this->kelas->ViewValue = $this->kelas->displayValue($arwrk);
                    } else {
                        $this->kelas->ViewValue = $this->kelas->CurrentValue;
                    }
                }
            } else {
                $this->kelas->ViewValue = null;
            }
            $this->kelas->ViewCustomAttributes = "";

            // materi
            $curVal = trim(strval($this->materi->CurrentValue));
            if ($curVal != "") {
                $this->materi->ViewValue = $this->materi->lookupCacheOption($curVal);
                if ($this->materi->ViewValue === null) { // Lookup from database
                    $arwrk = explode(",", $curVal);
                    $filterWrk = "";
                    foreach ($arwrk as $wrk) {
                        if ($filterWrk != "") {
                            $filterWrk .= " OR ";
                        }
                        $filterWrk .= "\"materi_id\"" . SearchString("=", trim($wrk), DATATYPE_NUMBER, "");
                    }
                    $sqlWrk = $this->materi->Lookup->getSql(false, $filterWrk, '', $this, true, true);
                    $rswrk = Conn()->executeQuery($sqlWrk)->fetchAll(\PDO::FETCH_BOTH);
                    $ari = count($rswrk);
                    if ($ari > 0) { // Lookup values found
                        $this->materi->ViewValue = new OptionValues();
                        foreach ($rswrk as $row) {
                            $arwrk = $this->materi->Lookup->renderViewRow($row);
                            $this->materi->ViewValue->add($this->materi->displayValue($arwrk));
                        }
                    } else {
                        $this->materi->ViewValue = $this->materi->CurrentValue;
                    }
                }
            } else {
                $this->materi->ViewValue = null;
            }
            $this->materi->CellCssStyle .= "text-align: justify;";
            $this->materi->ViewCustomAttributes = "";

            // tujuan_pembelajaran
            $curVal = trim(strval($this->tujuan_pembelajaran->CurrentValue));
            if ($curVal != "") {
                $this->tujuan_pembelajaran->ViewValue = $this->tujuan_pembelajaran->lookupCacheOption($curVal);
                if ($this->tujuan_pembelajaran->ViewValue === null) { // Lookup from database
                    $arwrk = explode(",", $curVal);
                    $filterWrk = "";
                    foreach ($arwrk as $wrk) {
                        if ($filterWrk != "") {
                            $filterWrk .= " OR ";
                        }
                        $filterWrk .= "\"tp_id\"" . SearchString("=", trim($wrk), DATATYPE_NUMBER, "");
                    }
                    $sqlWrk = $this->tujuan_pembelajaran->Lookup->getSql(false, $filterWrk, '', $this, true, true);
                    $rswrk = Conn()->executeQuery($sqlWrk)->fetchAll(\PDO::FETCH_BOTH);
                    $ari = count($rswrk);
                    if ($ari > 0) { // Lookup values found
                        $this->tujuan_pembelajaran->ViewValue = new OptionValues();
                        foreach ($rswrk as $row) {
                            $arwrk = $this->tujuan_pembelajaran->Lookup->renderViewRow($row);
                            $this->tujuan_pembelajaran->ViewValue->add($this->tujuan_pembelajaran->displayValue($arwrk));
                        }
                    } else {
                        $this->tujuan_pembelajaran->ViewValue = $this->tujuan_pembelajaran->CurrentValue;
                    }
                }
            } else {
                $this->tujuan_pembelajaran->ViewValue = null;
            }
            $this->tujuan_pembelajaran->CellCssStyle .= "text-align: justify;";
            $this->tujuan_pembelajaran->ViewCustomAttributes = "";

            // fase
            if (strval($this->fase->CurrentValue) != "") {
                $this->fase->ViewValue = $this->fase->optionCaption($this->fase->CurrentValue);
            } else {
                $this->fase->ViewValue = null;
            }
            $this->fase->ViewCustomAttributes = "";

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

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

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

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

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

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

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

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

            // kode_tapel

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

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

            // kelas
            $this->kelas->EditAttrs["class"] = "form-control";
            $this->kelas->EditCustomAttributes = "";
            if (!$Security->isAdmin() && $Security->isLoggedIn() && !$this->userIDAllow("edit")) { // Non system admin
                $this->kelas->CurrentValue = CurrentUserID();
                $curVal = trim(strval($this->kelas->CurrentValue));
                if ($curVal != "") {
                    $this->kelas->EditValue = $this->kelas->lookupCacheOption($curVal);
                    if ($this->kelas->EditValue === null) { // Lookup from database
                        $filterWrk = "\"kelas\"" . SearchString("=", $curVal, DATATYPE_MEMO, "");
                        $lookupFilter = function() {
                            return "`kode_tapel`='".kode_tapel()."'";
                        };
                        $lookupFilter = $lookupFilter->bindTo($this);
                        $sqlWrk = $this->kelas->Lookup->getSql(false, $filterWrk, $lookupFilter, $this, true, true);
                        $rswrk = Conn()->executeQuery($sqlWrk)->fetchAll(\PDO::FETCH_BOTH);
                        $ari = count($rswrk);
                        if ($ari > 0) { // Lookup values found
                            $arwrk = $this->kelas->Lookup->renderViewRow($rswrk[0]);
                            $this->kelas->EditValue = $this->kelas->displayValue($arwrk);
                        } else {
                            $this->kelas->EditValue = $this->kelas->CurrentValue;
                        }
                    }
                } else {
                    $this->kelas->EditValue = null;
                }
                $this->kelas->ViewCustomAttributes = "";
            } else {
                $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;
                }
            }

            // materi
            $this->materi->EditCustomAttributes = "";
            $curVal = trim(strval($this->materi->CurrentValue));
            if ($curVal != "") {
                $this->materi->ViewValue = $this->materi->lookupCacheOption($curVal);
            } else {
                $this->materi->ViewValue = $this->materi->Lookup !== null && is_array($this->materi->Lookup->Options) ? $curVal : null;
            }
            if ($this->materi->ViewValue !== null) { // Load from cache
                $this->materi->EditValue = array_values($this->materi->Lookup->Options);
                if ($this->materi->ViewValue == "") {
                    $this->materi->ViewValue = $Language->phrase("PleaseSelect");
                }
            } else { // Lookup from database
                if ($curVal == "") {
                    $filterWrk = "0=1";
                } else {
                    $arwrk = explode(",", $curVal);
                    $filterWrk = "";
                    foreach ($arwrk as $wrk) {
                        if ($filterWrk != "") {
                            $filterWrk .= " OR ";
                        }
                        $filterWrk .= "\"materi_id\"" . SearchString("=", trim($wrk), DATATYPE_NUMBER, "");
                    }
                }
                $sqlWrk = $this->materi->Lookup->getSql(true, $filterWrk, '', $this, false, true);
                $rswrk = Conn()->executeQuery($sqlWrk)->fetchAll(\PDO::FETCH_BOTH);
                $ari = count($rswrk);
                if ($ari > 0) { // Lookup values found
                    $this->materi->ViewValue = new OptionValues();
                    foreach ($rswrk as $row) {
                        $arwrk = $this->materi->Lookup->renderViewRow($row);
                        $this->materi->ViewValue->add($this->materi->displayValue($arwrk));
                        $ari++;
                    }
                } else {
                    $this->materi->ViewValue = $Language->phrase("PleaseSelect");
                }
                $arwrk = $rswrk;
                $this->materi->EditValue = $arwrk;
            }

            // tujuan_pembelajaran
            $this->tujuan_pembelajaran->EditCustomAttributes = "";
            $curVal = trim(strval($this->tujuan_pembelajaran->CurrentValue));
            if ($curVal != "") {
                $this->tujuan_pembelajaran->ViewValue = $this->tujuan_pembelajaran->lookupCacheOption($curVal);
            } else {
                $this->tujuan_pembelajaran->ViewValue = $this->tujuan_pembelajaran->Lookup !== null && is_array($this->tujuan_pembelajaran->Lookup->Options) ? $curVal : null;
            }
            if ($this->tujuan_pembelajaran->ViewValue !== null) { // Load from cache
                $this->tujuan_pembelajaran->EditValue = array_values($this->tujuan_pembelajaran->Lookup->Options);
                if ($this->tujuan_pembelajaran->ViewValue == "") {
                    $this->tujuan_pembelajaran->ViewValue = $Language->phrase("PleaseSelect");
                }
            } else { // Lookup from database
                if ($curVal == "") {
                    $filterWrk = "0=1";
                } else {
                    $arwrk = explode(",", $curVal);
                    $filterWrk = "";
                    foreach ($arwrk as $wrk) {
                        if ($filterWrk != "") {
                            $filterWrk .= " OR ";
                        }
                        $filterWrk .= "\"tp_id\"" . SearchString("=", trim($wrk), DATATYPE_NUMBER, "");
                    }
                }
                $sqlWrk = $this->tujuan_pembelajaran->Lookup->getSql(true, $filterWrk, '', $this, false, true);
                $rswrk = Conn()->executeQuery($sqlWrk)->fetchAll(\PDO::FETCH_BOTH);
                $ari = count($rswrk);
                if ($ari > 0) { // Lookup values found
                    $this->tujuan_pembelajaran->ViewValue = new OptionValues();
                    foreach ($rswrk as $row) {
                        $arwrk = $this->tujuan_pembelajaran->Lookup->renderViewRow($row);
                        $this->tujuan_pembelajaran->ViewValue->add($this->tujuan_pembelajaran->displayValue($arwrk));
                        $ari++;
                    }
                } else {
                    $this->tujuan_pembelajaran->ViewValue = $Language->phrase("PleaseSelect");
                }
                $arwrk = $rswrk;
                $this->tujuan_pembelajaran->EditValue = $arwrk;
            }

            // fase
            $this->fase->EditCustomAttributes = "";
            $this->fase->EditValue = $this->fase->options(false);

            // Edit refer script

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

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

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

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

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

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

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

            // fase
            $this->fase->LinkCustomAttributes = "";
            $this->fase->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->penilaian_id->Required) {
            if (!$this->penilaian_id->IsDetailKey && EmptyValue($this->penilaian_id->FormValue)) {
                $this->penilaian_id->addErrorMessage(str_replace("%s", $this->penilaian_id->caption(), $this->penilaian_id->RequiredErrorMessage));
            }
        }
        if ($this->kode_tapel->Required) {
            if (!$this->kode_tapel->IsDetailKey && EmptyValue($this->kode_tapel->FormValue)) {
                $this->kode_tapel->addErrorMessage(str_replace("%s", $this->kode_tapel->caption(), $this->kode_tapel->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->mapel_id->Required) {
            if (!$this->mapel_id->IsDetailKey && EmptyValue($this->mapel_id->FormValue)) {
                $this->mapel_id->addErrorMessage(str_replace("%s", $this->mapel_id->caption(), $this->mapel_id->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->materi->Required) {
            if ($this->materi->FormValue == "") {
                $this->materi->addErrorMessage(str_replace("%s", $this->materi->caption(), $this->materi->RequiredErrorMessage));
            }
        }
        if ($this->tujuan_pembelajaran->Required) {
            if ($this->tujuan_pembelajaran->FormValue == "") {
                $this->tujuan_pembelajaran->addErrorMessage(str_replace("%s", $this->tujuan_pembelajaran->caption(), $this->tujuan_pembelajaran->RequiredErrorMessage));
            }
        }
        if ($this->fase->Required) {
            if ($this->fase->FormValue == "") {
                $this->fase->addErrorMessage(str_replace("%s", $this->fase->caption(), $this->fase->RequiredErrorMessage));
            }
        }

        // Validate detail grid
        $detailTblVar = explode(",", $this->getCurrentDetailTable());
        $detailPage = Container("NilaiSumatifGrid");
        if (in_array("nilai_sumatif", $detailTblVar) && $detailPage->DetailEdit) {
            $detailPage->validateGridForm();
        }
        $detailPage = Container("NilaiFormatifGrid");
        if (in_array("nilai_formatif", $detailTblVar) && $detailPage->DetailEdit) {
            $detailPage->validateGridForm();
        }

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

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

    // 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 {
            // Begin transaction
            if ($this->getCurrentDetailTable() != "") {
                $conn->beginTransaction();
            }

            // Save old values
            $this->loadDbValues($rsold);
            $rsnew = [];

            // kode_tapel
            $this->kode_tapel->CurrentValue = kode_tapel();
            $this->kode_tapel->setDbValueDef($rsnew, $this->kode_tapel->CurrentValue, null);

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

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

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

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

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

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

            // 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) {
                }

                // Update detail records
                $detailTblVar = explode(",", $this->getCurrentDetailTable());
                if ($editRow) {
                    $detailPage = Container("NilaiSumatifGrid");
                    if (in_array("nilai_sumatif", $detailTblVar) && $detailPage->DetailEdit) {
                        $Security->loadCurrentUserLevel($this->ProjectID . "nilai_sumatif"); // Load user level of detail table
                        $editRow = $detailPage->gridUpdate();
                        $Security->loadCurrentUserLevel($this->ProjectID . $this->TableName); // Restore user level of master table
                    }
                }
                if ($editRow) {
                    $detailPage = Container("NilaiFormatifGrid");
                    if (in_array("nilai_formatif", $detailTblVar) && $detailPage->DetailEdit) {
                        $Security->loadCurrentUserLevel($this->ProjectID . "nilai_formatif"); // Load user level of detail table
                        $editRow = $detailPage->gridUpdate();
                        $Security->loadCurrentUserLevel($this->ProjectID . $this->TableName); // Restore user level of master table
                    }
                }

                // Commit/Rollback transaction
                if ($this->getCurrentDetailTable() != "") {
                    if ($editRow) {
                        $conn->commit(); // Commit transaction
                    } else {
                        $conn->rollback(); // Rollback transaction
                    }
                }
            } 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;
    }

    // Show link optionally based on User ID
    protected function showOptionLink($id = "")
    {
        global $Security;
        if ($Security->isLoggedIn() && !$Security->isAdmin() && !$this->userIDAllow($id)) {
            return $Security->isValidUserID($this->kelas->CurrentValue);
        }
        return true;
    }

    // Set up detail parms based on QueryString
    protected function setupDetailParms()
    {
        // Get the keys for master table
        $detailTblVar = Get(Config("TABLE_SHOW_DETAIL"));
        if ($detailTblVar !== null) {
            $this->setCurrentDetailTable($detailTblVar);
        } else {
            $detailTblVar = $this->getCurrentDetailTable();
        }
        if ($detailTblVar != "") {
            $detailTblVar = explode(",", $detailTblVar);
            if (in_array("nilai_sumatif", $detailTblVar)) {
                $detailPageObj = Container("NilaiSumatifGrid");
                if ($detailPageObj->DetailEdit) {
                    $detailPageObj->CurrentMode = "edit";
                    $detailPageObj->CurrentAction = "gridedit";

                    // Save current master table to detail table
                    $detailPageObj->setCurrentMasterTable($this->TableVar);
                    $detailPageObj->setStartRecordNumber(1);
                    $detailPageObj->penilaian_id->IsDetailKey = true;
                    $detailPageObj->penilaian_id->CurrentValue = $this->penilaian_id->CurrentValue;
                    $detailPageObj->penilaian_id->setSessionValue($detailPageObj->penilaian_id->CurrentValue);
                }
            }
            if (in_array("nilai_formatif", $detailTblVar)) {
                $detailPageObj = Container("NilaiFormatifGrid");
                if ($detailPageObj->DetailEdit) {
                    $detailPageObj->CurrentMode = "edit";
                    $detailPageObj->CurrentAction = "gridedit";

                    // Save current master table to detail table
                    $detailPageObj->setCurrentMasterTable($this->TableVar);
                    $detailPageObj->setStartRecordNumber(1);
                    $detailPageObj->penilaian_id->IsDetailKey = true;
                    $detailPageObj->penilaian_id->CurrentValue = $this->penilaian_id->CurrentValue;
                    $detailPageObj->penilaian_id->setSessionValue($detailPageObj->penilaian_id->CurrentValue);
                }
            }
        }
    }

    // Set up Breadcrumb
    protected function setupBreadcrumb()
    {
        global $Breadcrumb, $Language;
        $Breadcrumb = new Breadcrumb("index");
        $url = CurrentUrl();
        $Breadcrumb->add("list", $this->TableVar, $this->addMasterUrl("PenilaianList"), "", $this->TableVar, true);
        $pageId = "edit";
        $Breadcrumb->add("edit", $pageId, $url);
    }

    // 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_guru_id":
                    $lookupFilter = function () {
                        return "`kode_tapel`='".kode_tapel()."'";
                    };
                    $lookupFilter = $lookupFilter->bindTo($this);
                    break;
                case "x_mapel_id":
                    break;
                case "x_kelas":
                    $lookupFilter = function () {
                        return "`kode_tapel`='".kode_tapel()."'";
                    };
                    $lookupFilter = $lookupFilter->bindTo($this);
                    break;
                case "x_materi":
                    break;
                case "x_tujuan_pembelajaran":
                    break;
                case "x_fase":
                    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;
            }
        }
    }

    // Set up starting record parameters
    public function setupStartRecord()
    {
        if ($this->DisplayRecords == 0) {
            return;
        }
        if ($this->isPageRequest()) { // Validate request
            $startRec = Get(Config("TABLE_START_REC"));
            $pageNo = Get(Config("TABLE_PAGE_NO"));
            if ($pageNo !== null) { // Check for "pageno" parameter first
                if (is_numeric($pageNo)) {
                    $this->StartRecord = ($pageNo - 1) * $this->DisplayRecords + 1;
                    if ($this->StartRecord <= 0) {
                        $this->StartRecord = 1;
                    } elseif ($this->StartRecord >= (int)(($this->TotalRecords - 1) / $this->DisplayRecords) * $this->DisplayRecords + 1) {
                        $this->StartRecord = (int)(($this->TotalRecords - 1) / $this->DisplayRecords) * $this->DisplayRecords + 1;
                    }
                    $this->setStartRecordNumber($this->StartRecord);
                }
            } elseif ($startRec !== null) { // Check for "start" parameter
                $this->StartRecord = $startRec;
                $this->setStartRecordNumber($this->StartRecord);
            }
        }
        $this->StartRecord = $this->getStartRecordNumber();

        // Check if correct start record counter
        if (!is_numeric($this->StartRecord) || $this->StartRecord == "") { // Avoid invalid start record counter
            $this->StartRecord = 1; // Reset start record counter
            $this->setStartRecordNumber($this->StartRecord);
        } elseif ($this->StartRecord > $this->TotalRecords) { // Avoid starting record > total records
            $this->StartRecord = (int)(($this->TotalRecords - 1) / $this->DisplayRecords) * $this->DisplayRecords + 1; // Point to last page first record
            $this->setStartRecordNumber($this->StartRecord);
        } elseif (($this->StartRecord - 1) % $this->DisplayRecords != 0) {
            $this->StartRecord = (int)(($this->StartRecord - 1) / $this->DisplayRecords) * $this->DisplayRecords + 1; // Point to page boundary
            $this->setStartRecordNumber($this->StartRecord);
        }
    }

    // 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()
    {
        //Log("Page Render");
    }

    // Page Data Rendering event
    public function pageDataRendering(&$header)
    {
        // Example:
        $header = '<div class="card card-outline card-primary card-body"';
    }

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

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