<?php

namespace PHPMaker2021\rdigital21;

use Doctrine\DBAL\ParameterType;

/**
 * Page class
 */
class ExtraAbsensiEdit extends ExtraAbsensi
{
    use MessagesTrait;

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

    // Project ID
    public $ProjectID = PROJECT_ID;

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

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

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

        // Custom template
        $this->UseCustomTemplate = true;

        // Initialize
        $GLOBALS["Page"] = &$this;

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

        // Parent constuctor
        parent::__construct();

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

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

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

        // 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;
        if (Post("customexport") === null) {
             // 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"))) {
            if (is_array(Session(SESSION_TEMP_IMAGES))) { // Restore temp images
                $TempImages = Session(SESSION_TEMP_IMAGES);
            }
            if (Post("data") !== null) {
                $content = Post("data");
            }
            $ExportFileName = Post("filename", "");
            if ($ExportFileName == "") {
                $ExportFileName = $this->TableVar;
            }
            $class = PROJECT_NAMESPACE . Config("EXPORT_CLASSES." . $this->CustomExport);
            if (class_exists($class)) {
                $doc = new $class(Container("extra_absensi"));
                $doc->Text = @$content;
                if ($this->isExport("email")) {
                    echo $this->exportEmail($doc->Text);
                } else {
                    $doc->export();
                }
                DeleteTempImages(); // Delete temp images
                return;
            }
        }
        if ($this->CustomExport) { // Save temp images array for custom export
            if (is_array($TempImages)) {
                $_SESSION[SESSION_TEMP_IMAGES] = $TempImages;
            }
        }
        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 == "ExtraAbsensiView") {
                        $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['absen_id'];
        }
        return $key;
    }

    /**
     * Hide fields for add/edit
     *
     * @return void
     */
    protected function hideFieldsForAddEdit()
    {
    }

    // 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->absen_id->Visible = false;
        $this->kode_tapel->setVisibility();
        $this->kelas->setVisibility();
        $this->nisn->setVisibility();
        $this->nis->setVisibility();
        $this->nama->setVisibility();
        $this->jk->setVisibility();
        $this->s->setVisibility();
        $this->_i->setVisibility();
        $this->a->setVisibility();
        $this->ekstra1->setVisibility();
        $this->deskripsi1->setVisibility();
        $this->ekstra2->setVisibility();
        $this->deskripsi2->setVisibility();
        $this->ekstra3->setVisibility();
        $this->deskripsi3->setVisibility();
        $this->ekstra4->setVisibility();
        $this->deskripsi4->setVisibility();
        $this->catatan_siswa->Visible = false;
        $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->ekstra1);
        $this->setupLookupOptions($this->ekstra2);
        $this->setupLookupOptions($this->ekstra3);
        $this->setupLookupOptions($this->ekstra4);

        // 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("absen_id") ?? Key(0) ?? Route(2)) !== null) {
                $this->absen_id->setQueryStringValue($keyValue);
                $this->absen_id->setOldValue($this->absen_id->QueryStringValue);
            } elseif (Post("absen_id") !== null) {
                $this->absen_id->setFormValue(Post("absen_id"));
                $this->absen_id->setOldValue($this->absen_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("absen_id") ?? Route("absen_id")) !== null) {
                    $this->absen_id->setQueryStringValue($keyValue);
                    $loadByQuery = true;
                } else {
                    $this->absen_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
        }

        // 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("ExtraAbsensiList"); // No matching record, return to list
                    return;
                }
                break;
            case "update": // Update
                $returnUrl = $this->getReturnUrl();
                if (GetPageName($returnUrl) == "ExtraAbsensiList") {
                    $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 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 '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 '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 '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);
            }
        }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    // Restore form values
    public function restoreFormValues()
    {
        global $CurrentForm;
        $this->absen_id->CurrentValue = $this->absen_id->FormValue;
        $this->kode_tapel->CurrentValue = $this->kode_tapel->FormValue;
        $this->kelas->CurrentValue = $this->kelas->FormValue;
        $this->nisn->CurrentValue = $this->nisn->FormValue;
        $this->nis->CurrentValue = $this->nis->FormValue;
        $this->nama->CurrentValue = $this->nama->FormValue;
        $this->jk->CurrentValue = $this->jk->FormValue;
        $this->s->CurrentValue = $this->s->FormValue;
        $this->_i->CurrentValue = $this->_i->FormValue;
        $this->a->CurrentValue = $this->a->FormValue;
        $this->ekstra1->CurrentValue = $this->ekstra1->FormValue;
        $this->deskripsi1->CurrentValue = $this->deskripsi1->FormValue;
        $this->ekstra2->CurrentValue = $this->ekstra2->FormValue;
        $this->deskripsi2->CurrentValue = $this->deskripsi2->FormValue;
        $this->ekstra3->CurrentValue = $this->ekstra3->FormValue;
        $this->deskripsi3->CurrentValue = $this->deskripsi3->FormValue;
        $this->ekstra4->CurrentValue = $this->ekstra4->FormValue;
        $this->deskripsi4->CurrentValue = $this->deskripsi4->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
        }
        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->absen_id->setDbValue($row['absen_id']);
        $this->kode_tapel->setDbValue($row['kode_tapel']);
        $this->kelas->setDbValue($row['kelas']);
        $this->nisn->setDbValue($row['nisn']);
        $this->nis->setDbValue($row['nis']);
        $this->nama->setDbValue($row['nama']);
        $this->jk->setDbValue($row['jk']);
        $this->s->setDbValue($row['s']);
        $this->_i->setDbValue($row['i']);
        $this->a->setDbValue($row['a']);
        $this->ekstra1->setDbValue($row['ekstra1']);
        $this->deskripsi1->setDbValue($row['deskripsi1']);
        $this->ekstra2->setDbValue($row['ekstra2']);
        $this->deskripsi2->setDbValue($row['deskripsi2']);
        $this->ekstra3->setDbValue($row['ekstra3']);
        $this->deskripsi3->setDbValue($row['deskripsi3']);
        $this->ekstra4->setDbValue($row['ekstra4']);
        $this->deskripsi4->setDbValue($row['deskripsi4']);
        $this->catatan_siswa->setDbValue($row['catatan_siswa']);
    }

    // Return a row with default values
    protected function newRow()
    {
        $row = [];
        $row['absen_id'] = null;
        $row['kode_tapel'] = null;
        $row['kelas'] = null;
        $row['nisn'] = null;
        $row['nis'] = null;
        $row['nama'] = null;
        $row['jk'] = null;
        $row['s'] = null;
        $row['i'] = null;
        $row['a'] = null;
        $row['ekstra1'] = null;
        $row['deskripsi1'] = null;
        $row['ekstra2'] = null;
        $row['deskripsi2'] = null;
        $row['ekstra3'] = null;
        $row['deskripsi3'] = null;
        $row['ekstra4'] = null;
        $row['deskripsi4'] = null;
        $row['catatan_siswa'] = 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

        // absen_id

        // kode_tapel

        // kelas

        // nisn

        // nis

        // nama

        // jk

        // s

        // i

        // a

        // ekstra1

        // deskripsi1

        // ekstra2

        // deskripsi2

        // ekstra3

        // deskripsi3

        // ekstra4

        // deskripsi4

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

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

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

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

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

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

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

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

            // i
            $this->_i->ViewValue = $this->_i->CurrentValue;
            $this->_i->ViewCustomAttributes = "";

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

            // ekstra1
            $curVal = trim(strval($this->ekstra1->CurrentValue));
            if ($curVal != "") {
                $this->ekstra1->ViewValue = $this->ekstra1->lookupCacheOption($curVal);
                if ($this->ekstra1->ViewValue === null) { // Lookup from database
                    $filterWrk = "\"ektrakurikuler\"" . SearchString("=", $curVal, DATATYPE_STRING, "");
                    $lookupFilter = function() {
                        return "`kode_tapel`='".kode_tapel()."'";
                    };
                    $lookupFilter = $lookupFilter->bindTo($this);
                    $sqlWrk = $this->ekstra1->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->ekstra1->Lookup->renderViewRow($rswrk[0]);
                        $this->ekstra1->ViewValue = $this->ekstra1->displayValue($arwrk);
                    } else {
                        $this->ekstra1->ViewValue = $this->ekstra1->CurrentValue;
                    }
                }
            } else {
                $this->ekstra1->ViewValue = null;
            }
            $this->ekstra1->ViewCustomAttributes = "";

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

            // ekstra2
            $curVal = trim(strval($this->ekstra2->CurrentValue));
            if ($curVal != "") {
                $this->ekstra2->ViewValue = $this->ekstra2->lookupCacheOption($curVal);
                if ($this->ekstra2->ViewValue === null) { // Lookup from database
                    $filterWrk = "\"ektrakurikuler\"" . SearchString("=", $curVal, DATATYPE_STRING, "");
                    $lookupFilter = function() {
                        return "`kode_tapel`='".kode_tapel()."'";
                    };
                    $lookupFilter = $lookupFilter->bindTo($this);
                    $sqlWrk = $this->ekstra2->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->ekstra2->Lookup->renderViewRow($rswrk[0]);
                        $this->ekstra2->ViewValue = $this->ekstra2->displayValue($arwrk);
                    } else {
                        $this->ekstra2->ViewValue = $this->ekstra2->CurrentValue;
                    }
                }
            } else {
                $this->ekstra2->ViewValue = null;
            }
            $this->ekstra2->ViewCustomAttributes = "";

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

            // ekstra3
            $curVal = trim(strval($this->ekstra3->CurrentValue));
            if ($curVal != "") {
                $this->ekstra3->ViewValue = $this->ekstra3->lookupCacheOption($curVal);
                if ($this->ekstra3->ViewValue === null) { // Lookup from database
                    $filterWrk = "\"ektrakurikuler\"" . SearchString("=", $curVal, DATATYPE_STRING, "");
                    $lookupFilter = function() {
                        return "`kode_tapel`='".kode_tapel()."'";
                    };
                    $lookupFilter = $lookupFilter->bindTo($this);
                    $sqlWrk = $this->ekstra3->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->ekstra3->Lookup->renderViewRow($rswrk[0]);
                        $this->ekstra3->ViewValue = $this->ekstra3->displayValue($arwrk);
                    } else {
                        $this->ekstra3->ViewValue = $this->ekstra3->CurrentValue;
                    }
                }
            } else {
                $this->ekstra3->ViewValue = null;
            }
            $this->ekstra3->ViewCustomAttributes = "";

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

            // ekstra4
            $curVal = trim(strval($this->ekstra4->CurrentValue));
            if ($curVal != "") {
                $this->ekstra4->ViewValue = $this->ekstra4->lookupCacheOption($curVal);
                if ($this->ekstra4->ViewValue === null) { // Lookup from database
                    $filterWrk = "\"ektrakurikuler\"" . SearchString("=", $curVal, DATATYPE_STRING, "");
                    $lookupFilter = function() {
                        return "`kode_tapel`='".kode_tapel()."'";
                    };
                    $lookupFilter = $lookupFilter->bindTo($this);
                    $sqlWrk = $this->ekstra4->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->ekstra4->Lookup->renderViewRow($rswrk[0]);
                        $this->ekstra4->ViewValue = $this->ekstra4->displayValue($arwrk);
                    } else {
                        $this->ekstra4->ViewValue = $this->ekstra4->CurrentValue;
                    }
                }
            } else {
                $this->ekstra4->ViewValue = null;
            }
            $this->ekstra4->ViewCustomAttributes = "";

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

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

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

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

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

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

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

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

            // i
            $this->_i->LinkCustomAttributes = "";
            $this->_i->HrefValue = "";
            $this->_i->TooltipValue = "";

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

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

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

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

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

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

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

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

            // deskripsi4
            $this->deskripsi4->LinkCustomAttributes = "";
            $this->deskripsi4->HrefValue = "";
            $this->deskripsi4->TooltipValue = "";
        } elseif ($this->RowType == ROWTYPE_EDIT) {
            // kode_tapel

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

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

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

            // 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 = "";

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

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

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

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

            // deskripsi1
            $this->deskripsi1->EditAttrs["class"] = "form-control";
            $this->deskripsi1->EditCustomAttributes = "";
            $this->deskripsi1->EditValue = $this->deskripsi1->options(true);

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

            // deskripsi2
            $this->deskripsi2->EditAttrs["class"] = "form-control";
            $this->deskripsi2->EditCustomAttributes = "";
            $this->deskripsi2->EditValue = $this->deskripsi2->options(true);

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

            // deskripsi3
            $this->deskripsi3->EditAttrs["class"] = "form-control";
            $this->deskripsi3->EditCustomAttributes = "";
            $this->deskripsi3->EditValue = $this->deskripsi3->options(true);

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

            // deskripsi4
            $this->deskripsi4->EditAttrs["class"] = "form-control";
            $this->deskripsi4->EditCustomAttributes = "";
            $this->deskripsi4->EditValue = $this->deskripsi4->options(true);

            // Edit refer script

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

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

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

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

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

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

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

            // i
            $this->_i->LinkCustomAttributes = "";
            $this->_i->HrefValue = "";

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

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

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

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

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

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

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

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

            // deskripsi4
            $this->deskripsi4->LinkCustomAttributes = "";
            $this->deskripsi4->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();
        }

        // Save data for Custom Template
        if ($this->RowType == ROWTYPE_VIEW || $this->RowType == ROWTYPE_EDIT || $this->RowType == ROWTYPE_ADD) {
            $this->Rows[] = $this->customTemplateFieldValues();
        }
    }

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

        // Check if validation required
        if (!Config("SERVER_VALIDATE")) {
            return true;
        }
        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->kelas->Required) {
            if (!$this->kelas->IsDetailKey && EmptyValue($this->kelas->FormValue)) {
                $this->kelas->addErrorMessage(str_replace("%s", $this->kelas->caption(), $this->kelas->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->nis->Required) {
            if (!$this->nis->IsDetailKey && EmptyValue($this->nis->FormValue)) {
                $this->nis->addErrorMessage(str_replace("%s", $this->nis->caption(), $this->nis->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->s->Required) {
            if (!$this->s->IsDetailKey && EmptyValue($this->s->FormValue)) {
                $this->s->addErrorMessage(str_replace("%s", $this->s->caption(), $this->s->RequiredErrorMessage));
            }
        }
        if ($this->_i->Required) {
            if (!$this->_i->IsDetailKey && EmptyValue($this->_i->FormValue)) {
                $this->_i->addErrorMessage(str_replace("%s", $this->_i->caption(), $this->_i->RequiredErrorMessage));
            }
        }
        if ($this->a->Required) {
            if (!$this->a->IsDetailKey && EmptyValue($this->a->FormValue)) {
                $this->a->addErrorMessage(str_replace("%s", $this->a->caption(), $this->a->RequiredErrorMessage));
            }
        }
        if ($this->ekstra1->Required) {
            if (!$this->ekstra1->IsDetailKey && EmptyValue($this->ekstra1->FormValue)) {
                $this->ekstra1->addErrorMessage(str_replace("%s", $this->ekstra1->caption(), $this->ekstra1->RequiredErrorMessage));
            }
        }
        if ($this->deskripsi1->Required) {
            if (!$this->deskripsi1->IsDetailKey && EmptyValue($this->deskripsi1->FormValue)) {
                $this->deskripsi1->addErrorMessage(str_replace("%s", $this->deskripsi1->caption(), $this->deskripsi1->RequiredErrorMessage));
            }
        }
        if ($this->ekstra2->Required) {
            if (!$this->ekstra2->IsDetailKey && EmptyValue($this->ekstra2->FormValue)) {
                $this->ekstra2->addErrorMessage(str_replace("%s", $this->ekstra2->caption(), $this->ekstra2->RequiredErrorMessage));
            }
        }
        if ($this->deskripsi2->Required) {
            if (!$this->deskripsi2->IsDetailKey && EmptyValue($this->deskripsi2->FormValue)) {
                $this->deskripsi2->addErrorMessage(str_replace("%s", $this->deskripsi2->caption(), $this->deskripsi2->RequiredErrorMessage));
            }
        }
        if ($this->ekstra3->Required) {
            if (!$this->ekstra3->IsDetailKey && EmptyValue($this->ekstra3->FormValue)) {
                $this->ekstra3->addErrorMessage(str_replace("%s", $this->ekstra3->caption(), $this->ekstra3->RequiredErrorMessage));
            }
        }
        if ($this->deskripsi3->Required) {
            if (!$this->deskripsi3->IsDetailKey && EmptyValue($this->deskripsi3->FormValue)) {
                $this->deskripsi3->addErrorMessage(str_replace("%s", $this->deskripsi3->caption(), $this->deskripsi3->RequiredErrorMessage));
            }
        }
        if ($this->ekstra4->Required) {
            if (!$this->ekstra4->IsDetailKey && EmptyValue($this->ekstra4->FormValue)) {
                $this->ekstra4->addErrorMessage(str_replace("%s", $this->ekstra4->caption(), $this->ekstra4->RequiredErrorMessage));
            }
        }
        if ($this->deskripsi4->Required) {
            if (!$this->deskripsi4->IsDetailKey && EmptyValue($this->deskripsi4->FormValue)) {
                $this->deskripsi4->addErrorMessage(str_replace("%s", $this->deskripsi4->caption(), $this->deskripsi4->RequiredErrorMessage));
            }
        }

        // 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 {
            // Save old values
            $this->loadDbValues($rsold);
            $rsnew = [];

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

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

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

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

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

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

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

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

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

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

            // deskripsi4
            $this->deskripsi4->setDbValueDef($rsnew, $this->deskripsi4->CurrentValue, null, $this->deskripsi4->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) {
                }
            } 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;
    }

    // Set up Breadcrumb
    protected function setupBreadcrumb()
    {
        global $Breadcrumb, $Language;
        $Breadcrumb = new Breadcrumb("index");
        $url = CurrentUrl();
        $Breadcrumb->add("list", $this->TableVar, $this->addMasterUrl("ExtraAbsensiList"), "", $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_kelas":
                    $lookupFilter = function () {
                        return "\"kode_tapel\"='".kode_tapel()."'";
                    };
                    $lookupFilter = $lookupFilter->bindTo($this);
                    break;
                case "x_ekstra1":
                    $lookupFilter = function () {
                        return "`kode_tapel`='".kode_tapel()."'";
                    };
                    $lookupFilter = $lookupFilter->bindTo($this);
                    break;
                case "x_deskripsi1":
                    break;
                case "x_ekstra2":
                    $lookupFilter = function () {
                        return "`kode_tapel`='".kode_tapel()."'";
                    };
                    $lookupFilter = $lookupFilter->bindTo($this);
                    break;
                case "x_deskripsi2":
                    break;
                case "x_ekstra3":
                    $lookupFilter = function () {
                        return "`kode_tapel`='".kode_tapel()."'";
                    };
                    $lookupFilter = $lookupFilter->bindTo($this);
                    break;
                case "x_deskripsi3":
                    break;
                case "x_ekstra4":
                    $lookupFilter = function () {
                        return "`kode_tapel`='".kode_tapel()."'";
                    };
                    $lookupFilter = $lookupFilter->bindTo($this);
                    break;
                case "x_deskripsi4":
                    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;
    }
}
