<?php

namespace PHPMaker2021\gudang_ubi;

use Doctrine\DBAL\ParameterType;

/**
 * Page class
 */
class KedatanganAdd extends Kedatangan
{
    // Page ID
    public $PageID = "add";

    // Project ID
    public $ProjectID = PROJECT_ID;

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

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

    // Rendering View
    public $RenderingView = false;

    // Custom template
    public $UseCustomTemplate = 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;
    }

    // Messages
    private $message = "";
    private $failureMessage = "";
    private $successMessage = "";
    private $warningMessage = "";

    // Get message
    public function getMessage()
    {
        return $_SESSION[SESSION_MESSAGE] ?? $this->message;
    }

    // Set message
    public function setMessage($v)
    {
        AddMessage($this->message, $v);
        $_SESSION[SESSION_MESSAGE] = $this->message;
    }

    // Get failure message
    public function getFailureMessage()
    {
        return $_SESSION[SESSION_FAILURE_MESSAGE] ?? $this->failureMessage;
    }

    // Set failure message
    public function setFailureMessage($v)
    {
        AddMessage($this->failureMessage, $v);
        $_SESSION[SESSION_FAILURE_MESSAGE] = $this->failureMessage;
    }

    // Get success message
    public function getSuccessMessage()
    {
        return $_SESSION[SESSION_SUCCESS_MESSAGE] ?? $this->successMessage;
    }

    // Set success message
    public function setSuccessMessage($v)
    {
        AddMessage($this->successMessage, $v);
        $_SESSION[SESSION_SUCCESS_MESSAGE] = $this->successMessage;
    }

    // Get warning message
    public function getWarningMessage()
    {
        return $_SESSION[SESSION_WARNING_MESSAGE] ?? $this->warningMessage;
    }

    // Set warning message
    public function setWarningMessage($v)
    {
        AddMessage($this->warningMessage, $v);
        $_SESSION[SESSION_WARNING_MESSAGE] = $this->warningMessage;
    }

    // Clear message
    public function clearMessage()
    {
        $this->message = "";
        $_SESSION[SESSION_MESSAGE] = "";
    }

    // Clear failure message
    public function clearFailureMessage()
    {
        $this->failureMessage = "";
        $_SESSION[SESSION_FAILURE_MESSAGE] = "";
    }

    // Clear success message
    public function clearSuccessMessage()
    {
        $this->successMessage = "";
        $_SESSION[SESSION_SUCCESS_MESSAGE] = "";
    }

    // Clear warning message
    public function clearWarningMessage()
    {
        $this->warningMessage = "";
        $_SESSION[SESSION_WARNING_MESSAGE] = "";
    }

    // Clear messages
    public function clearMessages()
    {
        $this->clearMessage();
        $this->clearFailureMessage();
        $this->clearSuccessMessage();
        $this->clearWarningMessage();
    }

    // Show message
    public function showMessage()
    {
        $hidden = true;
        $html = "";
        // Message
        $message = $this->getMessage();
        if (method_exists($this, "messageShowing")) {
            $this->messageShowing($message, "");
        }
        if ($message != "") { // Message in Session, display
            if (!$hidden) {
                $message = '<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>' . $message;
            }
            $html .= '<div class="alert alert-info alert-dismissible ew-info"><i class="icon fas fa-info"></i>' . $message . '</div>';
            $_SESSION[SESSION_MESSAGE] = ""; // Clear message in Session
        }
        // Warning message
        $warningMessage = $this->getWarningMessage();
        if (method_exists($this, "messageShowing")) {
            $this->messageShowing($warningMessage, "warning");
        }
        if ($warningMessage != "") { // Message in Session, display
            if (!$hidden) {
                $warningMessage = '<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>' . $warningMessage;
            }
            $html .= '<div class="alert alert-warning alert-dismissible ew-warning"><i class="icon fas fa-exclamation"></i>' . $warningMessage . '</div>';
            $_SESSION[SESSION_WARNING_MESSAGE] = ""; // Clear message in Session
        }
        // Success message
        $successMessage = $this->getSuccessMessage();
        if (method_exists($this, "messageShowing")) {
            $this->messageShowing($successMessage, "success");
        }
        if ($successMessage != "") { // Message in Session, display
            if (!$hidden) {
                $successMessage = '<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>' . $successMessage;
            }
            $html .= '<div class="alert alert-success alert-dismissible ew-success"><i class="icon fas fa-check"></i>' . $successMessage . '</div>';
            $_SESSION[SESSION_SUCCESS_MESSAGE] = ""; // Clear message in Session
        }
        // Failure message
        $errorMessage = $this->getFailureMessage();
        if (method_exists($this, "messageShowing")) {
            $this->messageShowing($errorMessage, "failure");
        }
        if ($errorMessage != "") { // Message in Session, display
            if (!$hidden) {
                $errorMessage = '<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>' . $errorMessage;
            }
            $html .= '<div class="alert alert-danger alert-dismissible ew-error"><i class="icon fas fa-ban"></i>' . $errorMessage . '</div>';
            $_SESSION[SESSION_FAILURE_MESSAGE] = ""; // Clear message in Session
        }
        echo '<div class="ew-message-dialog' . ($hidden ? ' d-none' : '') . '">' . $html . '</div>';
    }

    // Get message as array
    public function getMessages()
    {
        $ar = [];
        // Message
        $message = $this->getMessage();
        if ($message != "") { // Message in Session, display
            $ar["message"] = $message;
            $_SESSION[SESSION_MESSAGE] = ""; // Clear message in Session
        }
        // Warning message
        $warningMessage = $this->getWarningMessage();
        if ($warningMessage != "") { // Message in Session, display
            $ar["warningMessage"] = $warningMessage;
            $_SESSION[SESSION_WARNING_MESSAGE] = ""; // Clear message in Session
        }
        // Success message
        $successMessage = $this->getSuccessMessage();
        if ($successMessage != "") { // Message in Session, display
            $ar["successMessage"] = $successMessage;
            $_SESSION[SESSION_SUCCESS_MESSAGE] = ""; // Clear message in Session
        }
        // Failure message
        $failureMessage = $this->getFailureMessage();
        if ($failureMessage != "") { // Message in Session, display
            $ar["failureMessage"] = $failureMessage;
            $_SESSION[SESSION_FAILURE_MESSAGE] = ""; // Clear message in Session
        }
        return $ar;
    }

    // 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;
        $this->TokenTimeout = SessionTimeoutTime();

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

        // Parent constuctor
        parent::__construct();

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

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

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

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

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

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

        // 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 == "KedatanganView") {
                        $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['datang_id'];
        }
        return $key;
    }

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

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

        // Get lookup object
        $fieldName = Post("field");
        if (!array_key_exists($fieldName, $this->Fields)) {
            return false;
        }
        $lookupField = $this->Fields[$fieldName];
        $lookup = $lookupField->Lookup;
        if ($lookup === null) {
            return false;
        }
        $tbl = $lookup->getTable();
        if (!$Security->allowLookup(PROJECT_ID . $tbl->TableName)) { // Lookup permission
            return false;
        }

        // 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-add-form";
    public $IsModal = false;
    public $IsMobileOrModal = false;
    public $DbMasterFilter = "";
    public $DbDetailFilter = "";
    public $StartRecord;
    public $Priv = 0;
    public $OldRecordset;
    public $CopyRecord;

    /**
     * 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
        $this->datang_id->Visible = false;
        $this->datang_petugas->setVisibility();
        $this->datang_tanggal->setVisibility();
        $this->datang_varietas->setVisibility();
        $this->datang_jumlah->setVisibility();
        $this->datang_sup->setVisibility();
        $this->datang_catatan->setVisibility();
        $this->hideFieldsForAddEdit();

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

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

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

        // Set up lookup cache
        $this->setupLookupOptions($this->datang_petugas);
        $this->setupLookupOptions($this->datang_varietas);
        $this->setupLookupOptions($this->datang_sup);

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

        // Set up current action
        if (IsApi()) {
            $this->CurrentAction = "insert"; // Add record directly
            $postBack = true;
        } elseif (Post("action") !== null) {
            $this->CurrentAction = Post("action"); // Get form action
            $postBack = true;
        } else {
            // Load key values from QueryString
            $this->CopyRecord = true;
            if (($keyValue = Get("datang_id") ?? Route("datang_id")) !== null) {
                $this->datang_id->setQueryStringValue($keyValue);
                $this->setKey("datang_id", $this->datang_id->CurrentValue); // Set up key
            } else {
                $this->setKey("datang_id", ""); // Clear key
                $this->CopyRecord = false;
            }
            if ($this->CopyRecord) {
                $this->CurrentAction = "copy"; // Copy record
            } else {
                $this->CurrentAction = "show"; // Display blank record
            }
        }

        // Load old record / default values
        $loaded = $this->loadOldRecord();

        // Load form values
        if ($postBack) {
            $this->loadFormValues(); // Load form values
        }

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

        // Perform current action
        switch ($this->CurrentAction) {
            case "copy": // Copy an existing record
                if (!$loaded) { // Record not loaded
                    if ($this->getFailureMessage() == "") {
                        $this->setFailureMessage($Language->phrase("NoRecord")); // No record found
                    }
                    $this->terminate("KedatanganList"); // No matching record, return to list
                    return;
                }
                break;
            case "insert": // Add new record
                $this->SendEmail = true; // Send email on add success
                if ($this->addRow($this->OldRecordset)) { // Add successful
                    if ($this->getSuccessMessage() == "" && Post("addopt") != "1") { // Skip success message for addopt (done in JavaScript)
                        $this->setSuccessMessage($Language->phrase("AddSuccess")); // Set up success message
                    }
                    $returnUrl = $this->getReturnUrl();
                    if (GetPageName($returnUrl) == "KedatanganList") {
                        $returnUrl = $this->addMasterUrl($returnUrl); // List page, return to List page with correct master key if necessary
                    } elseif (GetPageName($returnUrl) == "KedatanganView") {
                        $returnUrl = $this->getViewUrl(); // View page, return to View page with keyurl directly
                    }
                    if (IsApi()) { // Return to caller
                        $this->terminate(true);
                        return;
                    } else {
                        $this->terminate($returnUrl);
                        return;
                    }
                } elseif (IsApi()) { // API request, return
                    $this->terminate();
                    return;
                } else {
                    $this->EventCancelled = true; // Event cancelled
                    $this->restoreFormValues(); // Add failed, restore form values
                }
        }

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

        // Render row based on row type
        $this->RowType = ROWTYPE_ADD; // Render add type

        // Render row
        $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", "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 Rendering event
            if (method_exists($this, "pageRender")) {
                $this->pageRender();
            }
        }
    }

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

    // Load default values
    protected function loadDefaultValues()
    {
        $this->datang_id->CurrentValue = null;
        $this->datang_id->OldValue = $this->datang_id->CurrentValue;
        $this->datang_petugas->CurrentValue = null;
        $this->datang_petugas->OldValue = $this->datang_petugas->CurrentValue;
        $this->datang_tanggal->CurrentValue = null;
        $this->datang_tanggal->OldValue = $this->datang_tanggal->CurrentValue;
        $this->datang_varietas->CurrentValue = null;
        $this->datang_varietas->OldValue = $this->datang_varietas->CurrentValue;
        $this->datang_jumlah->CurrentValue = null;
        $this->datang_jumlah->OldValue = $this->datang_jumlah->CurrentValue;
        $this->datang_sup->CurrentValue = null;
        $this->datang_sup->OldValue = $this->datang_sup->CurrentValue;
        $this->datang_catatan->CurrentValue = null;
        $this->datang_catatan->OldValue = $this->datang_catatan->CurrentValue;
    }

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

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

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

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

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

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

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

        // Check field name 'datang_id' first before field var 'x_datang_id'
        $val = $CurrentForm->hasValue("datang_id") ? $CurrentForm->getValue("datang_id") : $CurrentForm->getValue("x_datang_id");
    }

    // Restore form values
    public function restoreFormValues()
    {
        global $CurrentForm;
        $this->datang_petugas->CurrentValue = $this->datang_petugas->FormValue;
        $this->datang_tanggal->CurrentValue = $this->datang_tanggal->FormValue;
        $this->datang_tanggal->CurrentValue = UnFormatDateTime($this->datang_tanggal->CurrentValue, 0);
        $this->datang_varietas->CurrentValue = $this->datang_varietas->FormValue;
        $this->datang_jumlah->CurrentValue = $this->datang_jumlah->FormValue;
        $this->datang_sup->CurrentValue = $this->datang_sup->FormValue;
        $this->datang_catatan->CurrentValue = $this->datang_catatan->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->datang_id->setDbValue($row['datang_id']);
        $this->datang_petugas->setDbValue($row['datang_petugas']);
        $this->datang_tanggal->setDbValue($row['datang_tanggal']);
        $this->datang_varietas->setDbValue($row['datang_varietas']);
        $this->datang_jumlah->setDbValue($row['datang_jumlah']);
        $this->datang_sup->setDbValue($row['datang_sup']);
        $this->datang_catatan->setDbValue($row['datang_catatan']);
    }

    // Return a row with default values
    protected function newRow()
    {
        $this->loadDefaultValues();
        $row = [];
        $row['datang_id'] = $this->datang_id->CurrentValue;
        $row['datang_petugas'] = $this->datang_petugas->CurrentValue;
        $row['datang_tanggal'] = $this->datang_tanggal->CurrentValue;
        $row['datang_varietas'] = $this->datang_varietas->CurrentValue;
        $row['datang_jumlah'] = $this->datang_jumlah->CurrentValue;
        $row['datang_sup'] = $this->datang_sup->CurrentValue;
        $row['datang_catatan'] = $this->datang_catatan->CurrentValue;
        return $row;
    }

    // Load old record
    protected function loadOldRecord()
    {
        // Load key values from Session
        $validKey = true;
        if (strval($this->getKey("datang_id")) != "") {
            $this->datang_id->OldValue = $this->getKey("datang_id"); // datang_id
        } else {
            $validKey = false;
        }

        // Load old record
        $this->OldRecordset = null;
        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

        // Convert decimal values if posted back
        if ($this->datang_jumlah->FormValue == $this->datang_jumlah->CurrentValue && is_numeric(ConvertToFloatString($this->datang_jumlah->CurrentValue))) {
            $this->datang_jumlah->CurrentValue = ConvertToFloatString($this->datang_jumlah->CurrentValue);
        }

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

        // Common render codes for all row types

        // datang_id

        // datang_petugas

        // datang_tanggal

        // datang_varietas

        // datang_jumlah

        // datang_sup

        // datang_catatan
        if ($this->RowType == ROWTYPE_VIEW) {
            // datang_id
            $this->datang_id->ViewValue = $this->datang_id->CurrentValue;
            $this->datang_id->ViewValue = FormatNumber($this->datang_id->ViewValue, 0, -2, -2, -2);
            $this->datang_id->ViewCustomAttributes = "";

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

            // datang_tanggal
            $this->datang_tanggal->ViewValue = $this->datang_tanggal->CurrentValue;
            $this->datang_tanggal->ViewValue = FormatDateTime($this->datang_tanggal->ViewValue, 0);
            $this->datang_tanggal->ViewCustomAttributes = "";

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

            // datang_jumlah
            $this->datang_jumlah->ViewValue = $this->datang_jumlah->CurrentValue;
            $this->datang_jumlah->ViewValue = FormatNumber($this->datang_jumlah->ViewValue, 2, -2, -2, -2);
            $this->datang_jumlah->ViewCustomAttributes = "";

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

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

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

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

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

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

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

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

            // datang_tanggal
            $this->datang_tanggal->EditAttrs["class"] = "form-control";
            $this->datang_tanggal->EditCustomAttributes = "";
            $this->datang_tanggal->EditValue = HtmlEncode(FormatDateTime($this->datang_tanggal->CurrentValue, 8));
            $this->datang_tanggal->PlaceHolder = RemoveHtml($this->datang_tanggal->caption());

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

            // datang_jumlah
            $this->datang_jumlah->EditAttrs["class"] = "form-control";
            $this->datang_jumlah->EditCustomAttributes = "";
            $this->datang_jumlah->EditValue = HtmlEncode($this->datang_jumlah->CurrentValue);
            $this->datang_jumlah->PlaceHolder = RemoveHtml($this->datang_jumlah->caption());
            if (strval($this->datang_jumlah->EditValue) != "" && is_numeric($this->datang_jumlah->EditValue)) {
                $this->datang_jumlah->EditValue = FormatNumber($this->datang_jumlah->EditValue, -2, -2, -2, -2);
            }

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

            // datang_catatan
            $this->datang_catatan->EditAttrs["class"] = "form-control";
            $this->datang_catatan->EditCustomAttributes = "";
            $this->datang_catatan->EditValue = HtmlEncode($this->datang_catatan->CurrentValue);
            $this->datang_catatan->PlaceHolder = RemoveHtml($this->datang_catatan->caption());

            // Add refer script

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

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

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

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

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

            // datang_catatan
            $this->datang_catatan->LinkCustomAttributes = "";
            $this->datang_catatan->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->datang_petugas->Required) {
            if (!$this->datang_petugas->IsDetailKey && EmptyValue($this->datang_petugas->FormValue)) {
                $this->datang_petugas->addErrorMessage(str_replace("%s", $this->datang_petugas->caption(), $this->datang_petugas->RequiredErrorMessage));
            }
        }
        if ($this->datang_tanggal->Required) {
            if (!$this->datang_tanggal->IsDetailKey && EmptyValue($this->datang_tanggal->FormValue)) {
                $this->datang_tanggal->addErrorMessage(str_replace("%s", $this->datang_tanggal->caption(), $this->datang_tanggal->RequiredErrorMessage));
            }
        }
        if (!CheckDate($this->datang_tanggal->FormValue)) {
            $this->datang_tanggal->addErrorMessage($this->datang_tanggal->getErrorMessage(false));
        }
        if ($this->datang_varietas->Required) {
            if (!$this->datang_varietas->IsDetailKey && EmptyValue($this->datang_varietas->FormValue)) {
                $this->datang_varietas->addErrorMessage(str_replace("%s", $this->datang_varietas->caption(), $this->datang_varietas->RequiredErrorMessage));
            }
        }
        if ($this->datang_jumlah->Required) {
            if (!$this->datang_jumlah->IsDetailKey && EmptyValue($this->datang_jumlah->FormValue)) {
                $this->datang_jumlah->addErrorMessage(str_replace("%s", $this->datang_jumlah->caption(), $this->datang_jumlah->RequiredErrorMessage));
            }
        }
        if (!CheckNumber($this->datang_jumlah->FormValue)) {
            $this->datang_jumlah->addErrorMessage($this->datang_jumlah->getErrorMessage(false));
        }
        if ($this->datang_sup->Required) {
            if (!$this->datang_sup->IsDetailKey && EmptyValue($this->datang_sup->FormValue)) {
                $this->datang_sup->addErrorMessage(str_replace("%s", $this->datang_sup->caption(), $this->datang_sup->RequiredErrorMessage));
            }
        }
        if ($this->datang_catatan->Required) {
            if (!$this->datang_catatan->IsDetailKey && EmptyValue($this->datang_catatan->FormValue)) {
                $this->datang_catatan->addErrorMessage(str_replace("%s", $this->datang_catatan->caption(), $this->datang_catatan->RequiredErrorMessage));
            }
        }

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

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

    // Add record
    protected function addRow($rsold = null)
    {
        global $Language, $Security;
        $conn = $this->getConnection();

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

        // datang_petugas
        $this->datang_petugas->CurrentValue = CurrentUserName();
        $this->datang_petugas->setDbValueDef($rsnew, $this->datang_petugas->CurrentValue, 0);

        // datang_tanggal
        $this->datang_tanggal->setDbValueDef($rsnew, UnFormatDateTime($this->datang_tanggal->CurrentValue, 0), CurrentDate(), false);

        // datang_varietas
        $this->datang_varietas->setDbValueDef($rsnew, $this->datang_varietas->CurrentValue, 0, false);

        // datang_jumlah
        $this->datang_jumlah->setDbValueDef($rsnew, $this->datang_jumlah->CurrentValue, 0, false);

        // datang_sup
        $this->datang_sup->setDbValueDef($rsnew, $this->datang_sup->CurrentValue, 0, false);

        // datang_catatan
        $this->datang_catatan->setDbValueDef($rsnew, $this->datang_catatan->CurrentValue, "", false);

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

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

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

    // Set up Breadcrumb
    protected function setupBreadcrumb()
    {
        global $Breadcrumb, $Language;
        $Breadcrumb = new Breadcrumb("KedatanganList");
        $url = CurrentUrl();
        $Breadcrumb->add("list", $this->TableVar, $this->addMasterUrl("KedatanganList"), "", $this->TableVar, true);
        $pageId = ($this->isCopy()) ? "Copy" : "Add";
        $Breadcrumb->add("add", $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_datang_petugas":
                    break;
                case "x_datang_varietas":
                    break;
                case "x_datang_sup":
                    break;
                default:
                    $lookupFilter = "";
                    break;
            }

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

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

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

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

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

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

    // Page Render event
    public function pageRender()
    {
        //Log("Page Render");
    }

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

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

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