<?php

namespace PHPMaker2021\rdigital21;

use Doctrine\DBAL\ParameterType;

/**
 * Page class
 */
class SekolahEdit extends Sekolah
{
    use MessagesTrait;

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

    // Project ID
    public $ProjectID = PROJECT_ID;

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

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

    // 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 (sekolah)
        if (!isset($GLOBALS["sekolah"]) || get_class($GLOBALS["sekolah"]) == PROJECT_NAMESPACE . "sekolah") {
            $GLOBALS["sekolah"] = &$this;
        }

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

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

        // 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("sekolah"));
                $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 == "SekolahView") {
                        $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['sekolah_id'];
        }
        return $key;
    }

    /**
     * Hide fields for add/edit
     *
     * @return void
     */
    protected function hideFieldsForAddEdit()
    {
        if ($this->isAdd() || $this->isCopy() || $this->isGridAdd()) {
            $this->sekolah_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->sekolah_id->Visible = false;
        $this->npsn->setVisibility();
        $this->nss->setVisibility();
        $this->nama_sekolah->setVisibility();
        $this->status->setVisibility();
        $this->website->setVisibility();
        $this->_email->setVisibility();
        $this->alamat->setVisibility();
        $this->desa_kelurahan->setVisibility();
        $this->kecamatan->setVisibility();
        $this->kabupaten->setVisibility();
        $this->namaks->setVisibility();
        $this->nipks->setVisibility();
        $this->datetime->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

        // 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("sekolah_id") ?? Key(0) ?? Route(2)) !== null) {
                $this->sekolah_id->setQueryStringValue($keyValue);
                $this->sekolah_id->setOldValue($this->sekolah_id->QueryStringValue);
            } elseif (Post("sekolah_id") !== null) {
                $this->sekolah_id->setFormValue(Post("sekolah_id"));
                $this->sekolah_id->setOldValue($this->sekolah_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("sekolah_id") ?? Route("sekolah_id")) !== null) {
                    $this->sekolah_id->setQueryStringValue($keyValue);
                    $loadByQuery = true;
                } else {
                    $this->sekolah_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("SekolahList"); // No matching record, return to list
                    return;
                }
                break;
            case "update": // Update
                $returnUrl = $this->getReturnUrl();
                if (GetPageName($returnUrl) == "SekolahList") {
                    $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 'npsn' first before field var 'x_npsn'
        $val = $CurrentForm->hasValue("npsn") ? $CurrentForm->getValue("npsn") : $CurrentForm->getValue("x_npsn");
        if (!$this->npsn->IsDetailKey) {
            if (IsApi() && $val === null) {
                $this->npsn->Visible = false; // Disable update for API request
            } else {
                $this->npsn->setFormValue($val);
            }
        }

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

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

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

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

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

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

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

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

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

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

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

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

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

    // Restore form values
    public function restoreFormValues()
    {
        global $CurrentForm;
        $this->sekolah_id->CurrentValue = $this->sekolah_id->FormValue;
        $this->npsn->CurrentValue = $this->npsn->FormValue;
        $this->nss->CurrentValue = $this->nss->FormValue;
        $this->nama_sekolah->CurrentValue = $this->nama_sekolah->FormValue;
        $this->status->CurrentValue = $this->status->FormValue;
        $this->website->CurrentValue = $this->website->FormValue;
        $this->_email->CurrentValue = $this->_email->FormValue;
        $this->alamat->CurrentValue = $this->alamat->FormValue;
        $this->desa_kelurahan->CurrentValue = $this->desa_kelurahan->FormValue;
        $this->kecamatan->CurrentValue = $this->kecamatan->FormValue;
        $this->kabupaten->CurrentValue = $this->kabupaten->FormValue;
        $this->namaks->CurrentValue = $this->namaks->FormValue;
        $this->nipks->CurrentValue = $this->nipks->FormValue;
        $this->datetime->CurrentValue = $this->datetime->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->sekolah_id->setDbValue($row['sekolah_id']);
        $this->npsn->setDbValue($row['npsn']);
        $this->nss->setDbValue($row['nss']);
        $this->nama_sekolah->setDbValue($row['nama_sekolah']);
        $this->status->setDbValue($row['status']);
        $this->website->setDbValue($row['website']);
        $this->_email->setDbValue($row['email']);
        $this->alamat->setDbValue($row['alamat']);
        $this->desa_kelurahan->setDbValue($row['desa_kelurahan']);
        $this->kecamatan->setDbValue($row['kecamatan']);
        $this->kabupaten->setDbValue($row['kabupaten']);
        $this->namaks->setDbValue($row['namaks']);
        $this->nipks->setDbValue($row['nipks']);
        $this->datetime->setDbValue($row['datetime']);
    }

    // Return a row with default values
    protected function newRow()
    {
        $row = [];
        $row['sekolah_id'] = null;
        $row['npsn'] = null;
        $row['nss'] = null;
        $row['nama_sekolah'] = null;
        $row['status'] = null;
        $row['website'] = null;
        $row['email'] = null;
        $row['alamat'] = null;
        $row['desa_kelurahan'] = null;
        $row['kecamatan'] = null;
        $row['kabupaten'] = null;
        $row['namaks'] = null;
        $row['nipks'] = null;
        $row['datetime'] = 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

        // sekolah_id

        // npsn

        // nss

        // nama_sekolah

        // status

        // website

        // email

        // alamat

        // desa_kelurahan

        // kecamatan

        // kabupaten

        // namaks

        // nipks

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

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

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

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

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

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

            // email
            $this->_email->ViewValue = $this->_email->CurrentValue;
            $this->_email->ViewCustomAttributes = "";

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

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

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

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

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

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

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

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

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

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

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

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

            // email
            $this->_email->LinkCustomAttributes = "";
            $this->_email->HrefValue = "";
            $this->_email->TooltipValue = "";

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

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

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

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

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

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

            // datetime
            $this->datetime->LinkCustomAttributes = "";
            $this->datetime->HrefValue = "";
            $this->datetime->TooltipValue = "";
        } elseif ($this->RowType == ROWTYPE_EDIT) {
            // npsn
            $this->npsn->EditAttrs["class"] = "form-control";
            $this->npsn->EditCustomAttributes = "";
            if (!$this->npsn->Raw) {
                $this->npsn->CurrentValue = HtmlDecode($this->npsn->CurrentValue);
            }
            $this->npsn->EditValue = HtmlEncode($this->npsn->CurrentValue);

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

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

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

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

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

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

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

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

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

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

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

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

            // Edit refer script

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

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

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

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

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

            // email
            $this->_email->LinkCustomAttributes = "";
            $this->_email->HrefValue = "";

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

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

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

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

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

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

            // datetime
            $this->datetime->LinkCustomAttributes = "";
            $this->datetime->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->npsn->Required) {
            if (!$this->npsn->IsDetailKey && EmptyValue($this->npsn->FormValue)) {
                $this->npsn->addErrorMessage(str_replace("%s", $this->npsn->caption(), $this->npsn->RequiredErrorMessage));
            }
        }
        if ($this->nss->Required) {
            if (!$this->nss->IsDetailKey && EmptyValue($this->nss->FormValue)) {
                $this->nss->addErrorMessage(str_replace("%s", $this->nss->caption(), $this->nss->RequiredErrorMessage));
            }
        }
        if ($this->nama_sekolah->Required) {
            if (!$this->nama_sekolah->IsDetailKey && EmptyValue($this->nama_sekolah->FormValue)) {
                $this->nama_sekolah->addErrorMessage(str_replace("%s", $this->nama_sekolah->caption(), $this->nama_sekolah->RequiredErrorMessage));
            }
        }
        if ($this->status->Required) {
            if ($this->status->FormValue == "") {
                $this->status->addErrorMessage(str_replace("%s", $this->status->caption(), $this->status->RequiredErrorMessage));
            }
        }
        if ($this->website->Required) {
            if (!$this->website->IsDetailKey && EmptyValue($this->website->FormValue)) {
                $this->website->addErrorMessage(str_replace("%s", $this->website->caption(), $this->website->RequiredErrorMessage));
            }
        }
        if ($this->_email->Required) {
            if (!$this->_email->IsDetailKey && EmptyValue($this->_email->FormValue)) {
                $this->_email->addErrorMessage(str_replace("%s", $this->_email->caption(), $this->_email->RequiredErrorMessage));
            }
        }
        if ($this->alamat->Required) {
            if (!$this->alamat->IsDetailKey && EmptyValue($this->alamat->FormValue)) {
                $this->alamat->addErrorMessage(str_replace("%s", $this->alamat->caption(), $this->alamat->RequiredErrorMessage));
            }
        }
        if ($this->desa_kelurahan->Required) {
            if (!$this->desa_kelurahan->IsDetailKey && EmptyValue($this->desa_kelurahan->FormValue)) {
                $this->desa_kelurahan->addErrorMessage(str_replace("%s", $this->desa_kelurahan->caption(), $this->desa_kelurahan->RequiredErrorMessage));
            }
        }
        if ($this->kecamatan->Required) {
            if (!$this->kecamatan->IsDetailKey && EmptyValue($this->kecamatan->FormValue)) {
                $this->kecamatan->addErrorMessage(str_replace("%s", $this->kecamatan->caption(), $this->kecamatan->RequiredErrorMessage));
            }
        }
        if ($this->kabupaten->Required) {
            if (!$this->kabupaten->IsDetailKey && EmptyValue($this->kabupaten->FormValue)) {
                $this->kabupaten->addErrorMessage(str_replace("%s", $this->kabupaten->caption(), $this->kabupaten->RequiredErrorMessage));
            }
        }
        if ($this->namaks->Required) {
            if (!$this->namaks->IsDetailKey && EmptyValue($this->namaks->FormValue)) {
                $this->namaks->addErrorMessage(str_replace("%s", $this->namaks->caption(), $this->namaks->RequiredErrorMessage));
            }
        }
        if ($this->nipks->Required) {
            if (!$this->nipks->IsDetailKey && EmptyValue($this->nipks->FormValue)) {
                $this->nipks->addErrorMessage(str_replace("%s", $this->nipks->caption(), $this->nipks->RequiredErrorMessage));
            }
        }
        if ($this->datetime->Required) {
            if (!$this->datetime->IsDetailKey && EmptyValue($this->datetime->FormValue)) {
                $this->datetime->addErrorMessage(str_replace("%s", $this->datetime->caption(), $this->datetime->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 = [];

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

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

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

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

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

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

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

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

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

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

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

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

            // datetime
            $this->datetime->setDbValueDef($rsnew, $this->datetime->CurrentValue, null, $this->datetime->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("SekolahList"), "", $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_status":
                    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;
    }
}
