<?php

namespace ProjectManagement\prjProjectManagement;

use Doctrine\DBAL\ParameterType;
use Doctrine\DBAL\Connection;
use Doctrine\DBAL\Query\QueryBuilder;
use Psr\Http\Message\ServerRequestInterface as Request;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Container\ContainerInterface;
use Slim\Routing\RouteCollectorProxy;
use Slim\App;
use PhpOffice\PhpSpreadsheet\Style\NumberFormat;
use Closure;

/**
 * Page class
 */
class MasterprojectUpdate extends Masterproject
{
    use MessagesTrait;

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

    // Project ID
    public $ProjectID = PROJECT_ID;

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

    // View file path
    public $View = null;

    // Title
    public $Title = null; // Title for <title> tag

    // Rendering View
    public $RenderingView = false;

    // CSS class/style
    public $CurrentPageName = "masterprojectupdate";

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

    // Page layout
    public $UseLayout = true;

    // 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($withArgs = true)
    {
        $route = GetRoute();
        $args = RemoveXss($route->getArguments());
        if (!$withArgs) {
            foreach ($args as $key => &$val) {
                $val = "";
            }
            unset($val);
        }
        return rtrim(UrlFor($route->getName(), $args), "/") . "?";
    }

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

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

    // Set field visibility
    public function setVisibility()
    {
        $this->_ProjectID->Visible = false;
        $this->ProjectName->setVisibility();
        $this->PlanStart->setVisibility();
        $this->PlanEnd->setVisibility();
        $this->StartDate->setVisibility();
        $this->EndDate->setVisibility();
        $this->WarrantyEnd->setVisibility();
        $this->Status->setVisibility();
        $this->Progress->Visible = false;
        $this->Target->setVisibility();
        $this->Track->setVisibility();
        $this->PaymentProgress->Visible = false;
        $this->PaymentDate->setVisibility();
        $this->PaymentComplete->Visible = false;
        $this->AgingPayment->setVisibility();
        $this->ClientID->setVisibility();
        $this->ManagerID->setVisibility();
        $this->ProjectTemplateID->setVisibility();
        $this->Priority->setVisibility();
        $this->Description->setVisibility();
        $this->ProjectValue->setVisibility();
        $this->ProjectDebt->setVisibility();
        $this->PONumber->setVisibility();
        $this->PaymentLink->setVisibility();
        $this->ClearingDate->setVisibility();
        $this->ClearingAging->setVisibility();
        $this->Active->setVisibility();
        $this->Created_Date->setVisibility();
        $this->Created_By->setVisibility();
        $this->Last_Updated_Date->setVisibility();
        $this->Last_Updated_By->setVisibility();
    }

    // Constructor
    public function __construct()
    {
        parent::__construct();
        global $Language, $DashboardReport, $DebugTimer, $UserTable;
        $this->TableVar = 'masterproject';
        $this->TableName = 'masterproject';

        // Table CSS class
        $this->TableClass = "table table-striped table-bordered table-hover table-sm ew-desktop-table ew-update-table";

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

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

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

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

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

        // Debug message
        LoadDebugMessage();

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

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

    // Get content from stream
    public function getContents(): string
    {
        global $Response;
        return $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 $TempImages, $DashboardReport, $Response;

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

        // Page Unload event
        if (method_exists($this, "pageUnload")) {
            $this->pageUnload();
        }
        DispatchEvent(new PageUnloadedEvent($this), PageUnloadedEvent::NAME);
        if (!IsApi() && method_exists($this, "pageRedirecting")) {
            $this->pageRedirecting($url);
        }

        // Close connection
        CloseConnections();

        // Return for API
        if (IsApi()) {
            $res = $url === true;
            if (!$res) { // Show response for API
                $ar = array_merge($this->getMessages(), $url ? ["url" => GetUrl($url)] : []);
                WriteJson($ar);
            }
            $this->clearMessages(); // Clear messages for API request
            return;
        } else { // Check if response is JSON
            if (WithJsonResponse()) { // 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
                $pageName = GetPageName($url);
                $result = ["url" => GetUrl($url), "modal" => "1"];  // Assume return to modal for simplicity
                if (
                    SameString($pageName, GetPageName($this->getListUrl())) ||
                    SameString($pageName, GetPageName($this->getViewUrl())) ||
                    SameString($pageName, GetPageName(CurrentMasterTable()?->getViewUrl() ?? ""))
                ) { // List / View / Master View page
                    if (!SameString($pageName, GetPageName($this->getListUrl()))) { // Not List page
                        $result["caption"] = $this->getModalCaption($pageName);
                        $result["view"] = SameString($pageName, "masterprojectview"); // If View page, no primary button
                    } else { // List page
                        $result["error"] = $this->getFailureMessage(); // List page should not be shown as modal => error
                        $this->clearFailureMessage();
                    }
                } else { // Other pages (add messages and then clear messages)
                    $result = array_merge($this->getMessages(), ["modal" => "1"]);
                    $this->clearMessages();
                }
                WriteJson($result);
            } else {
                SaveDebugMessage();
                Redirect(GetUrl($url));
            }
        }
        return; // Return to controller
    }

    // Get records from result set
    protected function getRecordsFromRecordset($rs, $current = false)
    {
        $rows = [];
        if (is_object($rs)) { // Result set
            while ($row = $rs->fetch()) {
                $this->loadRowValues($row); // Set up DbValue/CurrentValue
                $row = $this->getRecordFromArray($row);
                if ($current) {
                    return $row;
                } else {
                    $rows[] = $row;
                }
            }
        } 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['ProjectID'];
        }
        return $key;
    }

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

    // Lookup data
    public function lookup(array $req = [], bool $response = true)
    {
        global $Language, $Security;

        // Get lookup object
        $fieldName = $req["field"] ?? null;
        if (!$fieldName) {
            return [];
        }
        $fld = $this->Fields[$fieldName];
        $lookup = $fld->Lookup;
        $name = $req["name"] ?? "";
        if (ContainsString($name, "query_builder_rule")) {
            $lookup->FilterFields = []; // Skip parent fields if any
        }

        // Get lookup parameters
        $lookupType = $req["ajax"] ?? "unknown";
        $pageSize = -1;
        $offset = -1;
        $searchValue = "";
        if (SameText($lookupType, "modal") || SameText($lookupType, "filter")) {
            $searchValue = $req["q"] ?? $req["sv"] ?? "";
            $pageSize = $req["n"] ?? $req["recperpage"] ?? 10;
        } elseif (SameText($lookupType, "autosuggest")) {
            $searchValue = $req["q"] ?? "";
            $pageSize = $req["n"] ?? -1;
            $pageSize = is_numeric($pageSize) ? (int)$pageSize : -1;
            if ($pageSize <= 0) {
                $pageSize = Config("AUTO_SUGGEST_MAX_ENTRIES");
            }
        }
        $start = $req["start"] ?? -1;
        $start = is_numeric($start) ? (int)$start : -1;
        $page = $req["page"] ?? -1;
        $page = is_numeric($page) ? (int)$page : -1;
        $offset = $start >= 0 ? $start : ($page > 0 && $pageSize > 0 ? ($page - 1) * $pageSize : 0);
        $userSelect = Decrypt($req["s"] ?? "");
        $userFilter = Decrypt($req["f"] ?? "");
        $userOrderBy = Decrypt($req["o"] ?? "");
        $keys = $req["keys"] ?? null;
        $lookup->LookupType = $lookupType; // Lookup type
        $lookup->FilterValues = []; // Clear filter values first
        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[] = $req["v0"] ?? $req["lookupValue"] ?? "";
        }
        $cnt = is_array($lookup->FilterFields) ? count($lookup->FilterFields) : 0;
        for ($i = 1; $i <= $cnt; $i++) {
            $lookup->FilterValues[] = $req["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;
        }
        return $lookup->toJson($this, $response); // Use settings from current page
    }
    public $FormClassName = "ew-form ew-update-form";
    public $IsModal = false;
    public $IsMobileOrModal = false;
    public $RecKeys;
    public $Disabled;
    public $UpdateCount = 0;

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

        // Is modal
        $this->IsModal = ConvertToBool(Param("modal"));
        $this->UseLayout = $this->UseLayout && !$this->IsModal;

        // Use layout
        $this->UseLayout = $this->UseLayout && ConvertToBool(Param(Config("PAGE_LAYOUT"), true));

        // View
        $this->View = Get(Config("VIEW"));

        // Load user profile
        if (IsLoggedIn()) {
            Profile()->setUserName(CurrentUserName())->loadFromStorage();
        }

        // Create form object
        $CurrentForm = new HttpForm();
        $this->CurrentAction = Param("action"); // Set up current action
        $this->setVisibility();

        // Set lookup cache
        if (!in_array($this->PageID, Config("LOOKUP_CACHE_PAGE_IDS"))) {
            $this->setUseLookupCache(false);
        }

        // Global Page Loading event (in userfn*.php)
        DispatchEvent(new PageLoadingEvent($this), PageLoadingEvent::NAME);

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

        // Hide fields for add/edit
        if (!$this->UseAjaxActions) {
            $this->hideFieldsForAddEdit();
        }
        // Use inline delete
        if ($this->UseAjaxActions) {
            $this->InlineDelete = true;
        }

        // Set up lookup cache
        $this->setupLookupOptions($this->Status);
        $this->setupLookupOptions($this->ClientID);
        $this->setupLookupOptions($this->ManagerID);
        $this->setupLookupOptions($this->ProjectTemplateID);
        $this->setupLookupOptions($this->Priority);
        $this->setupLookupOptions($this->Active);

        // Check modal
        if ($this->IsModal) {
            $SkipHeaderFooter = true;
        }
        $this->IsMobileOrModal = IsMobile() || $this->IsModal;

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

        // Try to load keys from list form
        $this->RecKeys = $this->getRecordKeys(); // Load record keys
        if (Post("action") !== null && Post("action") !== "") {
            // Get action
            $this->CurrentAction = Post("action");
            $this->loadFormValues(); // Get form values

            // Validate form
            if (!$this->validateForm()) {
                $this->CurrentAction = "show"; // Form error, reset action
                if (!$this->hasInvalidFields()) { // No fields selected
                    $this->setFailureMessage($Language->phrase("NoFieldSelected"));
                }
            }
        } else {
            $this->loadMultiUpdateValues(); // Load initial values to form
        }
        if (count($this->RecKeys) <= 0) {
            $this->terminate("masterprojectlist"); // No records selected, return to list
            return;
        }
        if ($this->isUpdate()) {
                if ($this->updateRows()) { // Update Records based on key
                    if ($this->getSuccessMessage() == "") {
                        $this->setSuccessMessage($Language->phrase("UpdateSuccess")); // Set up update success message
                    }

                    // Do not return Json for UseAjaxActions
                    if ($this->IsModal && $this->UseAjaxActions) {
                        $this->IsModal = false;
                    }
                    $this->terminate($this->getReturnUrl()); // Return to caller
                    return;
                } elseif ($this->IsModal && $this->UseAjaxActions) { // Return JSON error message
                    WriteJson([
                        "success" => false,
                        "validation" => $this->getValidationErrors(),
                        "error" => $this->getFailureMessage()
                    ]);
                    $this->clearFailureMessage();
                    $this->terminate();
                    return;
                } else {
                    $this->restoreFormValues(); // Restore form values
                }
        }

        // Render row
        $this->RowType = RowType::EDIT; // Render edit
        $this->resetAttributes();
        $this->renderRow();

        // Set LoginStatus / Page_Rendering / Page_Render
        if (!IsApi() && !$this->isTerminated()) {
            // Setup login status
            SetupLoginStatus();

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

            // Global Page Rendering event (in userfn*.php)
            DispatchEvent(new PageRenderingEvent($this), PageRenderingEvent::NAME);

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

            // Render search option
            if (method_exists($this, "renderSearchOptions")) {
                $this->renderSearchOptions();
            }
        }
    }

    // Load initial values to form if field values are identical in all selected records
    protected function loadMultiUpdateValues()
    {
        $this->CurrentFilter = $this->getFilterFromRecordKeys();

        // Load result set
        if ($rs = $this->loadRecordset()) {
            $i = 1;
            while ($row = $rs->fetch()) {
                if ($i == 1) {
                    $this->ProjectName->setDbValue($row['ProjectName']);
                    $this->PlanStart->setDbValue($row['PlanStart']);
                    $this->PlanEnd->setDbValue($row['PlanEnd']);
                    $this->StartDate->setDbValue($row['StartDate']);
                    $this->EndDate->setDbValue($row['EndDate']);
                    $this->WarrantyEnd->setDbValue($row['WarrantyEnd']);
                    $this->Status->setDbValue($row['Status']);
                    $this->Target->setDbValue($row['Target']);
                    $this->Track->setDbValue($row['Track']);
                    $this->PaymentDate->setDbValue($row['PaymentDate']);
                    $this->AgingPayment->setDbValue($row['AgingPayment']);
                    $this->ClientID->setDbValue($row['ClientID']);
                    $this->ManagerID->setDbValue($row['ManagerID']);
                    $this->ProjectTemplateID->setDbValue($row['ProjectTemplateID']);
                    $this->Priority->setDbValue($row['Priority']);
                    $this->Description->setDbValue($row['Description']);
                    $this->ProjectValue->setDbValue($row['ProjectValue']);
                    $this->ProjectDebt->setDbValue($row['ProjectDebt']);
                    $this->PONumber->setDbValue($row['PONumber']);
                    $this->PaymentLink->setDbValue($row['PaymentLink']);
                    $this->ClearingDate->setDbValue($row['ClearingDate']);
                    $this->ClearingAging->setDbValue($row['ClearingAging']);
                    $this->Active->setDbValue($row['Active']);
                    $this->Created_Date->setDbValue($row['Created_Date']);
                    $this->Created_By->setDbValue($row['Created_By']);
                    $this->Last_Updated_Date->setDbValue($row['Last_Updated_Date']);
                    $this->Last_Updated_By->setDbValue($row['Last_Updated_By']);
                } else {
                    if (!CompareValue($this->ProjectName->DbValue, $row['ProjectName'])) {
                        $this->ProjectName->CurrentValue = null;
                    }
                    if (!CompareValue($this->PlanStart->DbValue, $row['PlanStart'])) {
                        $this->PlanStart->CurrentValue = null;
                    }
                    if (!CompareValue($this->PlanEnd->DbValue, $row['PlanEnd'])) {
                        $this->PlanEnd->CurrentValue = null;
                    }
                    if (!CompareValue($this->StartDate->DbValue, $row['StartDate'])) {
                        $this->StartDate->CurrentValue = null;
                    }
                    if (!CompareValue($this->EndDate->DbValue, $row['EndDate'])) {
                        $this->EndDate->CurrentValue = null;
                    }
                    if (!CompareValue($this->WarrantyEnd->DbValue, $row['WarrantyEnd'])) {
                        $this->WarrantyEnd->CurrentValue = null;
                    }
                    if (!CompareValue($this->Status->DbValue, $row['Status'])) {
                        $this->Status->CurrentValue = null;
                    }
                    if (!CompareValue($this->Target->DbValue, $row['Target'])) {
                        $this->Target->CurrentValue = null;
                    }
                    if (!CompareValue($this->Track->DbValue, $row['Track'])) {
                        $this->Track->CurrentValue = null;
                    }
                    if (!CompareValue($this->PaymentDate->DbValue, $row['PaymentDate'])) {
                        $this->PaymentDate->CurrentValue = null;
                    }
                    if (!CompareValue($this->AgingPayment->DbValue, $row['AgingPayment'])) {
                        $this->AgingPayment->CurrentValue = null;
                    }
                    if (!CompareValue($this->ClientID->DbValue, $row['ClientID'])) {
                        $this->ClientID->CurrentValue = null;
                    }
                    if (!CompareValue($this->ManagerID->DbValue, $row['ManagerID'])) {
                        $this->ManagerID->CurrentValue = null;
                    }
                    if (!CompareValue($this->ProjectTemplateID->DbValue, $row['ProjectTemplateID'])) {
                        $this->ProjectTemplateID->CurrentValue = null;
                    }
                    if (!CompareValue($this->Priority->DbValue, $row['Priority'])) {
                        $this->Priority->CurrentValue = null;
                    }
                    if (!CompareValue($this->Description->DbValue, $row['Description'])) {
                        $this->Description->CurrentValue = null;
                    }
                    if (!CompareValue($this->ProjectValue->DbValue, $row['ProjectValue'])) {
                        $this->ProjectValue->CurrentValue = null;
                    }
                    if (!CompareValue($this->ProjectDebt->DbValue, $row['ProjectDebt'])) {
                        $this->ProjectDebt->CurrentValue = null;
                    }
                    if (!CompareValue($this->PONumber->DbValue, $row['PONumber'])) {
                        $this->PONumber->CurrentValue = null;
                    }
                    if (!CompareValue($this->PaymentLink->DbValue, $row['PaymentLink'])) {
                        $this->PaymentLink->CurrentValue = null;
                    }
                    if (!CompareValue($this->ClearingDate->DbValue, $row['ClearingDate'])) {
                        $this->ClearingDate->CurrentValue = null;
                    }
                    if (!CompareValue($this->ClearingAging->DbValue, $row['ClearingAging'])) {
                        $this->ClearingAging->CurrentValue = null;
                    }
                    if (!CompareValue($this->Active->DbValue, $row['Active'])) {
                        $this->Active->CurrentValue = null;
                    }
                    if (!CompareValue($this->Created_Date->DbValue, $row['Created_Date'])) {
                        $this->Created_Date->CurrentValue = null;
                    }
                    if (!CompareValue($this->Created_By->DbValue, $row['Created_By'])) {
                        $this->Created_By->CurrentValue = null;
                    }
                    if (!CompareValue($this->Last_Updated_Date->DbValue, $row['Last_Updated_Date'])) {
                        $this->Last_Updated_Date->CurrentValue = null;
                    }
                    if (!CompareValue($this->Last_Updated_By->DbValue, $row['Last_Updated_By'])) {
                        $this->Last_Updated_By->CurrentValue = null;
                    }
                }
                $i++;
            }
            $rs->free();
        }
    }

    // Set up key value
    protected function setupKeyValues($key)
    {
        $keyFld = $key;
        if (!is_numeric($keyFld)) {
            return false;
        }
        $this->_ProjectID->OldValue = $keyFld;
        return true;
    }

    // Update all selected rows
    protected function updateRows()
    {
        global $Language;
        $conn = $this->getConnection();
        if ($this->UseTransaction) {
            $conn->beginTransaction();
        }

        // Get old records
        $this->CurrentFilter = $this->getFilterFromRecordKeys(false);
        $sql = $this->getCurrentSql();
        $rsold = $conn->fetchAllAssociative($sql);

        // Update all rows
        $successKeys = [];
        $failKeys = [];
        foreach ($this->RecKeys as $reckey) {
            if ($this->setupKeyValues($reckey)) {
                $thisKey = $reckey;
                $this->SendEmail = false; // Do not send email on update success
                $this->UpdateCount += 1; // Update record count for records being updated
                $rowUpdated = $this->editRow(); // Update this row
            } else {
                $rowUpdated = false;
            }
            if (!$rowUpdated) {
                if ($this->UseTransaction) { // Update failed
                    $successKeys = []; // Reset success keys
                    break;
                }
                $failKeys[] = $thisKey;
            } else {
                $successKeys[] = $thisKey;
            }
        }

        // Check if any rows updated
        if (count($successKeys) > 0) {
            if ($this->UseTransaction) { // Commit transaction
                $conn->commit();
            }

            // Set warning message if update some records failed
            if (count($failKeys) > 0) {
                $this->setWarningMessage(str_replace("%k", explode(", ", $failKeys), $Language->phrase("UpdateSomeRecordsFailed")));
            }

            // Get new records
            $rsnew = $conn->fetchAllAssociative($sql);
            return true;
        } else {
            if ($this->UseTransaction) { // Rollback transaction
                $conn->rollback();
            }
            return false;
        }
    }

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

    // Load form values
    protected function loadFormValues()
    {
        // Load from form
        global $CurrentForm;
        $validate = !Config("SERVER_VALIDATE");

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

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

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

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

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

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

        // 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);
            }
        }
        $this->Status->MultiUpdate = $CurrentForm->getValue("u_Status");

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    // Restore form values
    public function restoreFormValues()
    {
        global $CurrentForm;
        $this->_ProjectID->CurrentValue = $this->_ProjectID->FormValue;
        $this->ProjectName->CurrentValue = $this->ProjectName->FormValue;
        $this->PlanStart->CurrentValue = $this->PlanStart->FormValue;
        $this->PlanStart->CurrentValue = UnFormatDateTime($this->PlanStart->CurrentValue, $this->PlanStart->formatPattern());
        $this->PlanEnd->CurrentValue = $this->PlanEnd->FormValue;
        $this->PlanEnd->CurrentValue = UnFormatDateTime($this->PlanEnd->CurrentValue, $this->PlanEnd->formatPattern());
        $this->StartDate->CurrentValue = $this->StartDate->FormValue;
        $this->StartDate->CurrentValue = UnFormatDateTime($this->StartDate->CurrentValue, $this->StartDate->formatPattern());
        $this->EndDate->CurrentValue = $this->EndDate->FormValue;
        $this->EndDate->CurrentValue = UnFormatDateTime($this->EndDate->CurrentValue, $this->EndDate->formatPattern());
        $this->WarrantyEnd->CurrentValue = $this->WarrantyEnd->FormValue;
        $this->WarrantyEnd->CurrentValue = UnFormatDateTime($this->WarrantyEnd->CurrentValue, $this->WarrantyEnd->formatPattern());
        $this->Status->CurrentValue = $this->Status->FormValue;
        $this->Target->CurrentValue = $this->Target->FormValue;
        $this->Track->CurrentValue = $this->Track->FormValue;
        $this->PaymentDate->CurrentValue = $this->PaymentDate->FormValue;
        $this->PaymentDate->CurrentValue = UnFormatDateTime($this->PaymentDate->CurrentValue, $this->PaymentDate->formatPattern());
        $this->AgingPayment->CurrentValue = $this->AgingPayment->FormValue;
        $this->ClientID->CurrentValue = $this->ClientID->FormValue;
        $this->ManagerID->CurrentValue = $this->ManagerID->FormValue;
        $this->ProjectTemplateID->CurrentValue = $this->ProjectTemplateID->FormValue;
        $this->Priority->CurrentValue = $this->Priority->FormValue;
        $this->Description->CurrentValue = $this->Description->FormValue;
        $this->ProjectValue->CurrentValue = $this->ProjectValue->FormValue;
        $this->ProjectDebt->CurrentValue = $this->ProjectDebt->FormValue;
        $this->PONumber->CurrentValue = $this->PONumber->FormValue;
        $this->PaymentLink->CurrentValue = $this->PaymentLink->FormValue;
        $this->ClearingDate->CurrentValue = $this->ClearingDate->FormValue;
        $this->ClearingDate->CurrentValue = UnFormatDateTime($this->ClearingDate->CurrentValue, $this->ClearingDate->formatPattern());
        $this->ClearingAging->CurrentValue = $this->ClearingAging->FormValue;
        $this->Active->CurrentValue = $this->Active->FormValue;
        $this->Created_Date->CurrentValue = $this->Created_Date->FormValue;
        $this->Created_Date->CurrentValue = UnFormatDateTime($this->Created_Date->CurrentValue, $this->Created_Date->formatPattern());
        $this->Created_By->CurrentValue = $this->Created_By->FormValue;
        $this->Last_Updated_Date->CurrentValue = $this->Last_Updated_Date->FormValue;
        $this->Last_Updated_Date->CurrentValue = UnFormatDateTime($this->Last_Updated_Date->CurrentValue, $this->Last_Updated_Date->formatPattern());
        $this->Last_Updated_By->CurrentValue = $this->Last_Updated_By->FormValue;
    }

    /**
     * Load result set
     *
     * @param int $offset Offset
     * @param int $rowcnt Maximum number of rows
     * @return Doctrine\DBAL\Result Result
     */
    public function loadRecordset($offset = -1, $rowcnt = -1)
    {
        // Load List page SQL (QueryBuilder)
        $sql = $this->getListSql();

        // Load result set
        if ($offset > -1) {
            $sql->setFirstResult($offset);
        }
        if ($rowcnt > 0) {
            $sql->setMaxResults($rowcnt);
        }
        $result = $sql->executeQuery();
        if (property_exists($this, "TotalRecords") && $rowcnt < 0) {
            $this->TotalRecords = $result->rowCount();
            if ($this->TotalRecords <= 0) { // Handle database drivers that does not return rowCount()
                $this->TotalRecords = $this->getRecordCount($this->getListSql());
            }
        }

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

    /**
     * Load records as associative array
     *
     * @param int $offset Offset
     * @param int $rowcnt Maximum number of rows
     * @return void
     */
    public function loadRows($offset = -1, $rowcnt = -1)
    {
        // Load List page SQL (QueryBuilder)
        $sql = $this->getListSql();

        // Load result set
        if ($offset > -1) {
            $sql->setFirstResult($offset);
        }
        if ($rowcnt > 0) {
            $sql->setMaxResults($rowcnt);
        }
        $result = $sql->executeQuery();
        return $result->fetchAllAssociative();
    }

    /**
     * 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->fetchAssociative($sql);
        if ($row) {
            $res = true;
            $this->loadRowValues($row); // Load row values
        }
        return $res;
    }

    /**
     * Load row values from result set or record
     *
     * @param array $row Record
     * @return void
     */
    public function loadRowValues($row = null)
    {
        $row = is_array($row) ? $row : $this->newRow();

        // Call Row Selected event
        $this->rowSelected($row);
        $this->_ProjectID->setDbValue($row['ProjectID']);
        $this->ProjectName->setDbValue($row['ProjectName']);
        $this->PlanStart->setDbValue($row['PlanStart']);
        $this->PlanEnd->setDbValue($row['PlanEnd']);
        $this->StartDate->setDbValue($row['StartDate']);
        $this->EndDate->setDbValue($row['EndDate']);
        $this->WarrantyEnd->setDbValue($row['WarrantyEnd']);
        $this->Status->setDbValue($row['Status']);
        $this->Progress->setDbValue($row['Progress']);
        $this->Target->setDbValue($row['Target']);
        $this->Track->setDbValue($row['Track']);
        $this->PaymentProgress->setDbValue($row['PaymentProgress']);
        $this->PaymentDate->setDbValue($row['PaymentDate']);
        $this->PaymentComplete->setDbValue($row['PaymentComplete']);
        $this->AgingPayment->setDbValue($row['AgingPayment']);
        $this->ClientID->setDbValue($row['ClientID']);
        $this->ManagerID->setDbValue($row['ManagerID']);
        $this->ProjectTemplateID->setDbValue($row['ProjectTemplateID']);
        $this->Priority->setDbValue($row['Priority']);
        $this->Description->setDbValue($row['Description']);
        $this->ProjectValue->setDbValue($row['ProjectValue']);
        $this->ProjectDebt->setDbValue($row['ProjectDebt']);
        $this->PONumber->setDbValue($row['PONumber']);
        $this->PaymentLink->setDbValue($row['PaymentLink']);
        $this->ClearingDate->setDbValue($row['ClearingDate']);
        $this->ClearingAging->setDbValue($row['ClearingAging']);
        $this->Active->setDbValue($row['Active']);
        $this->Created_Date->setDbValue($row['Created_Date']);
        $this->Created_By->setDbValue($row['Created_By']);
        $this->Last_Updated_Date->setDbValue($row['Last_Updated_Date']);
        $this->Last_Updated_By->setDbValue($row['Last_Updated_By']);
    }

    // Return a row with default values
    protected function newRow()
    {
        $row = [];
        $row['ProjectID'] = $this->_ProjectID->DefaultValue;
        $row['ProjectName'] = $this->ProjectName->DefaultValue;
        $row['PlanStart'] = $this->PlanStart->DefaultValue;
        $row['PlanEnd'] = $this->PlanEnd->DefaultValue;
        $row['StartDate'] = $this->StartDate->DefaultValue;
        $row['EndDate'] = $this->EndDate->DefaultValue;
        $row['WarrantyEnd'] = $this->WarrantyEnd->DefaultValue;
        $row['Status'] = $this->Status->DefaultValue;
        $row['Progress'] = $this->Progress->DefaultValue;
        $row['Target'] = $this->Target->DefaultValue;
        $row['Track'] = $this->Track->DefaultValue;
        $row['PaymentProgress'] = $this->PaymentProgress->DefaultValue;
        $row['PaymentDate'] = $this->PaymentDate->DefaultValue;
        $row['PaymentComplete'] = $this->PaymentComplete->DefaultValue;
        $row['AgingPayment'] = $this->AgingPayment->DefaultValue;
        $row['ClientID'] = $this->ClientID->DefaultValue;
        $row['ManagerID'] = $this->ManagerID->DefaultValue;
        $row['ProjectTemplateID'] = $this->ProjectTemplateID->DefaultValue;
        $row['Priority'] = $this->Priority->DefaultValue;
        $row['Description'] = $this->Description->DefaultValue;
        $row['ProjectValue'] = $this->ProjectValue->DefaultValue;
        $row['ProjectDebt'] = $this->ProjectDebt->DefaultValue;
        $row['PONumber'] = $this->PONumber->DefaultValue;
        $row['PaymentLink'] = $this->PaymentLink->DefaultValue;
        $row['ClearingDate'] = $this->ClearingDate->DefaultValue;
        $row['ClearingAging'] = $this->ClearingAging->DefaultValue;
        $row['Active'] = $this->Active->DefaultValue;
        $row['Created_Date'] = $this->Created_Date->DefaultValue;
        $row['Created_By'] = $this->Created_By->DefaultValue;
        $row['Last_Updated_Date'] = $this->Last_Updated_Date->DefaultValue;
        $row['Last_Updated_By'] = $this->Last_Updated_By->DefaultValue;
        return $row;
    }

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

        // ProjectID
        $this->_ProjectID->RowCssClass = "row";

        // ProjectName
        $this->ProjectName->RowCssClass = "row";

        // PlanStart
        $this->PlanStart->RowCssClass = "row";

        // PlanEnd
        $this->PlanEnd->RowCssClass = "row";

        // StartDate
        $this->StartDate->RowCssClass = "row";

        // EndDate
        $this->EndDate->RowCssClass = "row";

        // WarrantyEnd
        $this->WarrantyEnd->RowCssClass = "row";

        // Status
        $this->Status->RowCssClass = "row";

        // Progress
        $this->Progress->RowCssClass = "row";

        // Target
        $this->Target->RowCssClass = "row";

        // Track
        $this->Track->RowCssClass = "row";

        // PaymentProgress
        $this->PaymentProgress->RowCssClass = "row";

        // PaymentDate
        $this->PaymentDate->RowCssClass = "row";

        // PaymentComplete
        $this->PaymentComplete->RowCssClass = "row";

        // AgingPayment
        $this->AgingPayment->RowCssClass = "row";

        // ClientID
        $this->ClientID->RowCssClass = "row";

        // ManagerID
        $this->ManagerID->RowCssClass = "row";

        // ProjectTemplateID
        $this->ProjectTemplateID->RowCssClass = "row";

        // Priority
        $this->Priority->RowCssClass = "row";

        // Description
        $this->Description->RowCssClass = "row";

        // ProjectValue
        $this->ProjectValue->RowCssClass = "row";

        // ProjectDebt
        $this->ProjectDebt->RowCssClass = "row";

        // PONumber
        $this->PONumber->RowCssClass = "row";

        // PaymentLink
        $this->PaymentLink->RowCssClass = "row";

        // ClearingDate
        $this->ClearingDate->RowCssClass = "row";

        // ClearingAging
        $this->ClearingAging->RowCssClass = "row";

        // Active
        $this->Active->RowCssClass = "row";

        // Created_Date
        $this->Created_Date->RowCssClass = "row";

        // Created_By
        $this->Created_By->RowCssClass = "row";

        // Last_Updated_Date
        $this->Last_Updated_Date->RowCssClass = "row";

        // Last_Updated_By
        $this->Last_Updated_By->RowCssClass = "row";

        // View row
        if ($this->RowType == RowType::VIEW) {
            // ProjectID
            $this->_ProjectID->ViewValue = $this->_ProjectID->CurrentValue;

            // ProjectName
            $this->ProjectName->ViewValue = $this->ProjectName->CurrentValue;

            // PlanStart
            $this->PlanStart->ViewValue = $this->PlanStart->CurrentValue;
            $this->PlanStart->ViewValue = FormatDateTime($this->PlanStart->ViewValue, $this->PlanStart->formatPattern());

            // PlanEnd
            $this->PlanEnd->ViewValue = $this->PlanEnd->CurrentValue;
            $this->PlanEnd->ViewValue = FormatDateTime($this->PlanEnd->ViewValue, $this->PlanEnd->formatPattern());

            // StartDate
            $this->StartDate->ViewValue = $this->StartDate->CurrentValue;
            $this->StartDate->ViewValue = FormatDateTime($this->StartDate->ViewValue, $this->StartDate->formatPattern());

            // EndDate
            $this->EndDate->ViewValue = $this->EndDate->CurrentValue;
            $this->EndDate->ViewValue = FormatDateTime($this->EndDate->ViewValue, $this->EndDate->formatPattern());

            // WarrantyEnd
            $this->WarrantyEnd->ViewValue = $this->WarrantyEnd->CurrentValue;
            $this->WarrantyEnd->ViewValue = FormatDateTime($this->WarrantyEnd->ViewValue, $this->WarrantyEnd->formatPattern());

            // Status
            $curVal = strval($this->Status->CurrentValue);
            if ($curVal != "") {
                $this->Status->ViewValue = $this->Status->lookupCacheOption($curVal);
                if ($this->Status->ViewValue === null) { // Lookup from database
                    $filterWrk = SearchFilter($this->Status->Lookup->getTable()->Fields["Status"]->searchExpression(), "=", $curVal, $this->Status->Lookup->getTable()->Fields["Status"]->searchDataType(), "");
                    $sqlWrk = $this->Status->Lookup->getSql(false, $filterWrk, '', $this, true, true);
                    $conn = Conn();
                    $config = $conn->getConfiguration();
                    $config->setResultCache($this->Cache);
                    $rswrk = $conn->executeCacheQuery($sqlWrk, [], [], $this->CacheProfile)->fetchAll();
                    $ari = count($rswrk);
                    if ($ari > 0) { // Lookup values found
                        $arwrk = $this->Status->Lookup->renderViewRow($rswrk[0]);
                        $this->Status->ViewValue = $this->Status->displayValue($arwrk);
                    } else {
                        $this->Status->ViewValue = $this->Status->CurrentValue;
                    }
                }
            } else {
                $this->Status->ViewValue = null;
            }

            // Progress
            $this->Progress->ViewValue = $this->Progress->CurrentValue;
            $this->Progress->ViewValue = FormatPercent($this->Progress->ViewValue, $this->Progress->formatPattern());
            $this->Progress->CellCssStyle .= "text-align: right;";

            // Target
            $this->Target->ViewValue = $this->Target->CurrentValue;
            $this->Target->ViewValue = FormatPercent($this->Target->ViewValue, $this->Target->formatPattern());
            $this->Target->CellCssStyle .= "text-align: right;";

            // Track
            $this->Track->ViewValue = $this->Track->CurrentValue;
            $this->Track->CellCssStyle .= "text-align: right;";

            // PaymentProgress
            $this->PaymentProgress->ViewValue = $this->PaymentProgress->CurrentValue;
            $this->PaymentProgress->ViewValue = FormatPercent($this->PaymentProgress->ViewValue, $this->PaymentProgress->formatPattern());
            $this->PaymentProgress->CellCssStyle .= "text-align: right;";

            // PaymentDate
            $this->PaymentDate->ViewValue = $this->PaymentDate->CurrentValue;
            $this->PaymentDate->ViewValue = FormatDateTime($this->PaymentDate->ViewValue, $this->PaymentDate->formatPattern());

            // PaymentComplete
            $this->PaymentComplete->ViewValue = $this->PaymentComplete->CurrentValue;

            // AgingPayment
            $this->AgingPayment->ViewValue = $this->AgingPayment->CurrentValue;
            $this->AgingPayment->ViewValue = FormatNumber($this->AgingPayment->ViewValue, $this->AgingPayment->formatPattern());
            $this->AgingPayment->CellCssStyle .= "text-align: right;";

            // ClientID
            $curVal = strval($this->ClientID->CurrentValue);
            if ($curVal != "") {
                $this->ClientID->ViewValue = $this->ClientID->lookupCacheOption($curVal);
                if ($this->ClientID->ViewValue === null) { // Lookup from database
                    $filterWrk = SearchFilter($this->ClientID->Lookup->getTable()->Fields["ClientID"]->searchExpression(), "=", $curVal, $this->ClientID->Lookup->getTable()->Fields["ClientID"]->searchDataType(), "");
                    $lookupFilter = $this->ClientID->getSelectFilter($this); // PHP
                    $sqlWrk = $this->ClientID->Lookup->getSql(false, $filterWrk, $lookupFilter, $this, true, true);
                    $conn = Conn();
                    $config = $conn->getConfiguration();
                    $config->setResultCache($this->Cache);
                    $rswrk = $conn->executeCacheQuery($sqlWrk, [], [], $this->CacheProfile)->fetchAll();
                    $ari = count($rswrk);
                    if ($ari > 0) { // Lookup values found
                        $arwrk = $this->ClientID->Lookup->renderViewRow($rswrk[0]);
                        $this->ClientID->ViewValue = $this->ClientID->displayValue($arwrk);
                    } else {
                        $this->ClientID->ViewValue = FormatNumber($this->ClientID->CurrentValue, $this->ClientID->formatPattern());
                    }
                }
            } else {
                $this->ClientID->ViewValue = null;
            }

            // ManagerID
            $curVal = strval($this->ManagerID->CurrentValue);
            if ($curVal != "") {
                $this->ManagerID->ViewValue = $this->ManagerID->lookupCacheOption($curVal);
                if ($this->ManagerID->ViewValue === null) { // Lookup from database
                    $filterWrk = SearchFilter($this->ManagerID->Lookup->getTable()->Fields["EmployeeID"]->searchExpression(), "=", $curVal, $this->ManagerID->Lookup->getTable()->Fields["EmployeeID"]->searchDataType(), "");
                    $lookupFilter = $this->ManagerID->getSelectFilter($this); // PHP
                    $sqlWrk = $this->ManagerID->Lookup->getSql(false, $filterWrk, $lookupFilter, $this, true, true);
                    $conn = Conn();
                    $config = $conn->getConfiguration();
                    $config->setResultCache($this->Cache);
                    $rswrk = $conn->executeCacheQuery($sqlWrk, [], [], $this->CacheProfile)->fetchAll();
                    $ari = count($rswrk);
                    if ($ari > 0) { // Lookup values found
                        $arwrk = $this->ManagerID->Lookup->renderViewRow($rswrk[0]);
                        $this->ManagerID->ViewValue = $this->ManagerID->displayValue($arwrk);
                    } else {
                        $this->ManagerID->ViewValue = FormatNumber($this->ManagerID->CurrentValue, $this->ManagerID->formatPattern());
                    }
                }
            } else {
                $this->ManagerID->ViewValue = null;
            }

            // ProjectTemplateID
            $curVal = strval($this->ProjectTemplateID->CurrentValue);
            if ($curVal != "") {
                $this->ProjectTemplateID->ViewValue = $this->ProjectTemplateID->lookupCacheOption($curVal);
                if ($this->ProjectTemplateID->ViewValue === null) { // Lookup from database
                    $filterWrk = SearchFilter($this->ProjectTemplateID->Lookup->getTable()->Fields["ID"]->searchExpression(), "=", $curVal, $this->ProjectTemplateID->Lookup->getTable()->Fields["ID"]->searchDataType(), "");
                    $lookupFilter = $this->ProjectTemplateID->getSelectFilter($this); // PHP
                    $sqlWrk = $this->ProjectTemplateID->Lookup->getSql(false, $filterWrk, $lookupFilter, $this, true, true);
                    $conn = Conn();
                    $config = $conn->getConfiguration();
                    $config->setResultCache($this->Cache);
                    $rswrk = $conn->executeCacheQuery($sqlWrk, [], [], $this->CacheProfile)->fetchAll();
                    $ari = count($rswrk);
                    if ($ari > 0) { // Lookup values found
                        $arwrk = $this->ProjectTemplateID->Lookup->renderViewRow($rswrk[0]);
                        $this->ProjectTemplateID->ViewValue = $this->ProjectTemplateID->displayValue($arwrk);
                    } else {
                        $this->ProjectTemplateID->ViewValue = FormatNumber($this->ProjectTemplateID->CurrentValue, $this->ProjectTemplateID->formatPattern());
                    }
                }
            } else {
                $this->ProjectTemplateID->ViewValue = null;
            }

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

            // Description
            $this->Description->ViewValue = $this->Description->CurrentValue;

            // ProjectValue
            $this->ProjectValue->ViewValue = $this->ProjectValue->CurrentValue;
            $this->ProjectValue->ViewValue = FormatNumber($this->ProjectValue->ViewValue, $this->ProjectValue->formatPattern());
            $this->ProjectValue->CellCssStyle .= "text-align: right;";

            // ProjectDebt
            $this->ProjectDebt->ViewValue = $this->ProjectDebt->CurrentValue;
            $this->ProjectDebt->ViewValue = FormatNumber($this->ProjectDebt->ViewValue, $this->ProjectDebt->formatPattern());
            $this->ProjectDebt->CellCssStyle .= "text-align: right;";

            // PONumber
            $this->PONumber->ViewValue = $this->PONumber->CurrentValue;

            // PaymentLink
            $this->PaymentLink->ViewValue = $this->PaymentLink->CurrentValue;

            // ClearingDate
            $this->ClearingDate->ViewValue = $this->ClearingDate->CurrentValue;
            $this->ClearingDate->ViewValue = FormatDateTime($this->ClearingDate->ViewValue, $this->ClearingDate->formatPattern());

            // ClearingAging
            $this->ClearingAging->ViewValue = $this->ClearingAging->CurrentValue;
            $this->ClearingAging->ViewValue = FormatNumber($this->ClearingAging->ViewValue, $this->ClearingAging->formatPattern());
            $this->ClearingAging->CellCssStyle .= "text-align: right;";

            // Active
            if (ConvertToBool($this->Active->CurrentValue)) {
                $this->Active->ViewValue = $this->Active->tagCaption(1) != "" ? $this->Active->tagCaption(1) : "Yes";
            } else {
                $this->Active->ViewValue = $this->Active->tagCaption(2) != "" ? $this->Active->tagCaption(2) : "No";
            }
            $this->Active->CellCssStyle .= "text-align: center;";

            // Created_Date
            $this->Created_Date->ViewValue = $this->Created_Date->CurrentValue;
            $this->Created_Date->ViewValue = FormatDateTime($this->Created_Date->ViewValue, $this->Created_Date->formatPattern());

            // Created_By
            $this->Created_By->ViewValue = $this->Created_By->CurrentValue;

            // Last_Updated_Date
            $this->Last_Updated_Date->ViewValue = $this->Last_Updated_Date->CurrentValue;
            $this->Last_Updated_Date->ViewValue = FormatDateTime($this->Last_Updated_Date->ViewValue, $this->Last_Updated_Date->formatPattern());

            // Last_Updated_By
            $this->Last_Updated_By->ViewValue = $this->Last_Updated_By->CurrentValue;

            // ProjectName
            $this->ProjectName->HrefValue = "";
            $this->ProjectName->TooltipValue = "";

            // PlanStart
            $this->PlanStart->HrefValue = "";
            $this->PlanStart->TooltipValue = "";

            // PlanEnd
            $this->PlanEnd->HrefValue = "";
            $this->PlanEnd->TooltipValue = "";

            // StartDate
            $this->StartDate->HrefValue = "";
            $this->StartDate->TooltipValue = "";

            // EndDate
            $this->EndDate->HrefValue = "";
            $this->EndDate->TooltipValue = "";

            // WarrantyEnd
            $this->WarrantyEnd->HrefValue = "";
            $this->WarrantyEnd->TooltipValue = "";

            // Status
            $this->Status->HrefValue = "";
            $this->Status->TooltipValue = "";

            // Target
            $this->Target->HrefValue = "";
            $this->Target->TooltipValue = "";

            // Track
            $this->Track->HrefValue = "";
            $this->Track->TooltipValue = "";

            // PaymentDate
            $this->PaymentDate->HrefValue = "";
            $this->PaymentDate->TooltipValue = "";

            // AgingPayment
            $this->AgingPayment->HrefValue = "";
            $this->AgingPayment->TooltipValue = "";

            // ClientID
            $this->ClientID->HrefValue = "";
            $this->ClientID->TooltipValue = "";

            // ManagerID
            $this->ManagerID->HrefValue = "";
            $this->ManagerID->TooltipValue = "";

            // ProjectTemplateID
            $this->ProjectTemplateID->HrefValue = "";
            $this->ProjectTemplateID->TooltipValue = "";

            // Priority
            $this->Priority->HrefValue = "";
            $this->Priority->TooltipValue = "";

            // Description
            $this->Description->HrefValue = "";
            $this->Description->TooltipValue = "";

            // ProjectValue
            $this->ProjectValue->HrefValue = "";
            $this->ProjectValue->TooltipValue = "";

            // ProjectDebt
            $this->ProjectDebt->HrefValue = "";
            $this->ProjectDebt->TooltipValue = "";

            // PONumber
            $this->PONumber->HrefValue = "";
            $this->PONumber->TooltipValue = "";

            // PaymentLink
            $this->PaymentLink->HrefValue = "";
            $this->PaymentLink->TooltipValue = "";

            // ClearingDate
            $this->ClearingDate->HrefValue = "";
            $this->ClearingDate->TooltipValue = "";

            // ClearingAging
            $this->ClearingAging->HrefValue = "";
            $this->ClearingAging->TooltipValue = "";

            // Active
            $this->Active->HrefValue = "";
            $this->Active->TooltipValue = "";

            // Created_Date
            $this->Created_Date->HrefValue = "";
            $this->Created_Date->TooltipValue = "";

            // Created_By
            $this->Created_By->HrefValue = "";
            $this->Created_By->TooltipValue = "";

            // Last_Updated_Date
            $this->Last_Updated_Date->HrefValue = "";
            $this->Last_Updated_Date->TooltipValue = "";

            // Last_Updated_By
            $this->Last_Updated_By->HrefValue = "";
            $this->Last_Updated_By->TooltipValue = "";
        } elseif ($this->RowType == RowType::EDIT) {
            // ProjectName
            $this->ProjectName->setupEditAttributes();
            if (!$this->ProjectName->Raw) {
                $this->ProjectName->CurrentValue = HtmlDecode($this->ProjectName->CurrentValue);
            }
            $this->ProjectName->EditValue = HtmlEncode($this->ProjectName->CurrentValue);
            $this->ProjectName->PlaceHolder = RemoveHtml($this->ProjectName->caption());

            // PlanStart
            $this->PlanStart->setupEditAttributes();
            $this->PlanStart->EditValue = HtmlEncode(FormatDateTime($this->PlanStart->CurrentValue, $this->PlanStart->formatPattern()));
            $this->PlanStart->PlaceHolder = RemoveHtml($this->PlanStart->caption());

            // PlanEnd
            $this->PlanEnd->setupEditAttributes();
            $this->PlanEnd->EditValue = HtmlEncode(FormatDateTime($this->PlanEnd->CurrentValue, $this->PlanEnd->formatPattern()));
            $this->PlanEnd->PlaceHolder = RemoveHtml($this->PlanEnd->caption());

            // StartDate
            $this->StartDate->setupEditAttributes();
            $this->StartDate->EditValue = HtmlEncode(FormatDateTime($this->StartDate->CurrentValue, $this->StartDate->formatPattern()));
            $this->StartDate->PlaceHolder = RemoveHtml($this->StartDate->caption());

            // EndDate
            $this->EndDate->setupEditAttributes();
            $this->EndDate->EditValue = HtmlEncode(FormatDateTime($this->EndDate->CurrentValue, $this->EndDate->formatPattern()));
            $this->EndDate->PlaceHolder = RemoveHtml($this->EndDate->caption());

            // WarrantyEnd
            $this->WarrantyEnd->setupEditAttributes();
            $this->WarrantyEnd->EditValue = HtmlEncode(FormatDateTime($this->WarrantyEnd->CurrentValue, $this->WarrantyEnd->formatPattern()));
            $this->WarrantyEnd->PlaceHolder = RemoveHtml($this->WarrantyEnd->caption());

            // Status
            $this->Status->setupEditAttributes();
            $curVal = trim(strval($this->Status->CurrentValue));
            if ($curVal != "") {
                $this->Status->ViewValue = $this->Status->lookupCacheOption($curVal);
            } else {
                $this->Status->ViewValue = $this->Status->Lookup !== null && is_array($this->Status->lookupOptions()) && count($this->Status->lookupOptions()) > 0 ? $curVal : null;
            }
            if ($this->Status->ViewValue !== null) { // Load from cache
                $this->Status->EditValue = array_values($this->Status->lookupOptions());
            } else { // Lookup from database
                if ($curVal == "") {
                    $filterWrk = "0=1";
                } else {
                    $filterWrk = SearchFilter($this->Status->Lookup->getTable()->Fields["Status"]->searchExpression(), "=", $this->Status->CurrentValue, $this->Status->Lookup->getTable()->Fields["Status"]->searchDataType(), "");
                }
                $sqlWrk = $this->Status->Lookup->getSql(true, $filterWrk, '', $this, false, true);
                $conn = Conn();
                $config = $conn->getConfiguration();
                $config->setResultCache($this->Cache);
                $rswrk = $conn->executeCacheQuery($sqlWrk, [], [], $this->CacheProfile)->fetchAll();
                $ari = count($rswrk);
                $arwrk = $rswrk;
                $this->Status->EditValue = $arwrk;
            }
            $this->Status->PlaceHolder = RemoveHtml($this->Status->caption());

            // Target
            $this->Target->setupEditAttributes();
            $this->Target->EditValue = $this->Target->CurrentValue;
            $this->Target->PlaceHolder = RemoveHtml($this->Target->caption());
            if (strval($this->Target->EditValue) != "" && is_numeric($this->Target->EditValue)) {
                $this->Target->EditValue = FormatNumber($this->Target->EditValue, null);
            }

            // Track
            $this->Track->setupEditAttributes();
            if (!$this->Track->Raw) {
                $this->Track->CurrentValue = HtmlDecode($this->Track->CurrentValue);
            }
            $this->Track->EditValue = HtmlEncode($this->Track->CurrentValue);
            $this->Track->PlaceHolder = RemoveHtml($this->Track->caption());

            // PaymentDate
            $this->PaymentDate->setupEditAttributes();
            $this->PaymentDate->EditValue = $this->PaymentDate->CurrentValue;
            $this->PaymentDate->EditValue = FormatDateTime($this->PaymentDate->EditValue, $this->PaymentDate->formatPattern());

            // AgingPayment
            $this->AgingPayment->setupEditAttributes();
            $this->AgingPayment->EditValue = $this->AgingPayment->CurrentValue;
            $this->AgingPayment->PlaceHolder = RemoveHtml($this->AgingPayment->caption());
            if (strval($this->AgingPayment->EditValue) != "" && is_numeric($this->AgingPayment->EditValue)) {
                $this->AgingPayment->EditValue = FormatNumber($this->AgingPayment->EditValue, null);
            }

            // ClientID
            $this->ClientID->setupEditAttributes();
            $curVal = trim(strval($this->ClientID->CurrentValue));
            if ($curVal != "") {
                $this->ClientID->ViewValue = $this->ClientID->lookupCacheOption($curVal);
            } else {
                $this->ClientID->ViewValue = $this->ClientID->Lookup !== null && is_array($this->ClientID->lookupOptions()) && count($this->ClientID->lookupOptions()) > 0 ? $curVal : null;
            }
            if ($this->ClientID->ViewValue !== null) { // Load from cache
                $this->ClientID->EditValue = array_values($this->ClientID->lookupOptions());
            } else { // Lookup from database
                if ($curVal == "") {
                    $filterWrk = "0=1";
                } else {
                    $filterWrk = SearchFilter($this->ClientID->Lookup->getTable()->Fields["ClientID"]->searchExpression(), "=", $this->ClientID->CurrentValue, $this->ClientID->Lookup->getTable()->Fields["ClientID"]->searchDataType(), "");
                }
                $lookupFilter = $this->ClientID->getSelectFilter($this); // PHP
                $sqlWrk = $this->ClientID->Lookup->getSql(true, $filterWrk, $lookupFilter, $this, false, true);
                $conn = Conn();
                $config = $conn->getConfiguration();
                $config->setResultCache($this->Cache);
                $rswrk = $conn->executeCacheQuery($sqlWrk, [], [], $this->CacheProfile)->fetchAll();
                $ari = count($rswrk);
                $arwrk = $rswrk;
                $this->ClientID->EditValue = $arwrk;
            }
            $this->ClientID->PlaceHolder = RemoveHtml($this->ClientID->caption());

            // ManagerID
            $this->ManagerID->setupEditAttributes();
            $curVal = trim(strval($this->ManagerID->CurrentValue));
            if ($curVal != "") {
                $this->ManagerID->ViewValue = $this->ManagerID->lookupCacheOption($curVal);
            } else {
                $this->ManagerID->ViewValue = $this->ManagerID->Lookup !== null && is_array($this->ManagerID->lookupOptions()) && count($this->ManagerID->lookupOptions()) > 0 ? $curVal : null;
            }
            if ($this->ManagerID->ViewValue !== null) { // Load from cache
                $this->ManagerID->EditValue = array_values($this->ManagerID->lookupOptions());
            } else { // Lookup from database
                if ($curVal == "") {
                    $filterWrk = "0=1";
                } else {
                    $filterWrk = SearchFilter($this->ManagerID->Lookup->getTable()->Fields["EmployeeID"]->searchExpression(), "=", $this->ManagerID->CurrentValue, $this->ManagerID->Lookup->getTable()->Fields["EmployeeID"]->searchDataType(), "");
                }
                $lookupFilter = $this->ManagerID->getSelectFilter($this); // PHP
                $sqlWrk = $this->ManagerID->Lookup->getSql(true, $filterWrk, $lookupFilter, $this, false, true);
                $conn = Conn();
                $config = $conn->getConfiguration();
                $config->setResultCache($this->Cache);
                $rswrk = $conn->executeCacheQuery($sqlWrk, [], [], $this->CacheProfile)->fetchAll();
                $ari = count($rswrk);
                $arwrk = $rswrk;
                $this->ManagerID->EditValue = $arwrk;
            }
            $this->ManagerID->PlaceHolder = RemoveHtml($this->ManagerID->caption());

            // ProjectTemplateID
            $this->ProjectTemplateID->setupEditAttributes();
            $curVal = trim(strval($this->ProjectTemplateID->CurrentValue));
            if ($curVal != "") {
                $this->ProjectTemplateID->ViewValue = $this->ProjectTemplateID->lookupCacheOption($curVal);
            } else {
                $this->ProjectTemplateID->ViewValue = $this->ProjectTemplateID->Lookup !== null && is_array($this->ProjectTemplateID->lookupOptions()) && count($this->ProjectTemplateID->lookupOptions()) > 0 ? $curVal : null;
            }
            if ($this->ProjectTemplateID->ViewValue !== null) { // Load from cache
                $this->ProjectTemplateID->EditValue = array_values($this->ProjectTemplateID->lookupOptions());
            } else { // Lookup from database
                if ($curVal == "") {
                    $filterWrk = "0=1";
                } else {
                    $filterWrk = SearchFilter($this->ProjectTemplateID->Lookup->getTable()->Fields["ID"]->searchExpression(), "=", $this->ProjectTemplateID->CurrentValue, $this->ProjectTemplateID->Lookup->getTable()->Fields["ID"]->searchDataType(), "");
                }
                $lookupFilter = $this->ProjectTemplateID->getSelectFilter($this); // PHP
                $sqlWrk = $this->ProjectTemplateID->Lookup->getSql(true, $filterWrk, $lookupFilter, $this, false, true);
                $conn = Conn();
                $config = $conn->getConfiguration();
                $config->setResultCache($this->Cache);
                $rswrk = $conn->executeCacheQuery($sqlWrk, [], [], $this->CacheProfile)->fetchAll();
                $ari = count($rswrk);
                $arwrk = $rswrk;
                $this->ProjectTemplateID->EditValue = $arwrk;
            }
            $this->ProjectTemplateID->PlaceHolder = RemoveHtml($this->ProjectTemplateID->caption());

            // Priority
            $this->Priority->setupEditAttributes();
            $this->Priority->EditValue = $this->Priority->options(true);
            $this->Priority->PlaceHolder = RemoveHtml($this->Priority->caption());

            // Description
            $this->Description->setupEditAttributes();
            $this->Description->EditValue = HtmlEncode($this->Description->CurrentValue);
            $this->Description->PlaceHolder = RemoveHtml($this->Description->caption());

            // ProjectValue
            $this->ProjectValue->setupEditAttributes();
            $this->ProjectValue->EditValue = $this->ProjectValue->CurrentValue;
            $this->ProjectValue->PlaceHolder = RemoveHtml($this->ProjectValue->caption());
            if (strval($this->ProjectValue->EditValue) != "" && is_numeric($this->ProjectValue->EditValue)) {
                $this->ProjectValue->EditValue = FormatNumber($this->ProjectValue->EditValue, null);
            }

            // ProjectDebt
            $this->ProjectDebt->setupEditAttributes();
            $this->ProjectDebt->EditValue = $this->ProjectDebt->CurrentValue;
            $this->ProjectDebt->PlaceHolder = RemoveHtml($this->ProjectDebt->caption());
            if (strval($this->ProjectDebt->EditValue) != "" && is_numeric($this->ProjectDebt->EditValue)) {
                $this->ProjectDebt->EditValue = FormatNumber($this->ProjectDebt->EditValue, null);
            }

            // PONumber
            $this->PONumber->setupEditAttributes();
            if (!$this->PONumber->Raw) {
                $this->PONumber->CurrentValue = HtmlDecode($this->PONumber->CurrentValue);
            }
            $this->PONumber->EditValue = HtmlEncode($this->PONumber->CurrentValue);
            $this->PONumber->PlaceHolder = RemoveHtml($this->PONumber->caption());

            // PaymentLink
            $this->PaymentLink->setupEditAttributes();
            $this->PaymentLink->EditValue = HtmlEncode($this->PaymentLink->CurrentValue);
            $this->PaymentLink->PlaceHolder = RemoveHtml($this->PaymentLink->caption());

            // ClearingDate
            $this->ClearingDate->setupEditAttributes();
            $this->ClearingDate->EditValue = HtmlEncode(FormatDateTime($this->ClearingDate->CurrentValue, $this->ClearingDate->formatPattern()));
            $this->ClearingDate->PlaceHolder = RemoveHtml($this->ClearingDate->caption());

            // ClearingAging
            $this->ClearingAging->setupEditAttributes();
            $this->ClearingAging->EditValue = $this->ClearingAging->CurrentValue;
            $this->ClearingAging->PlaceHolder = RemoveHtml($this->ClearingAging->caption());
            if (strval($this->ClearingAging->EditValue) != "" && is_numeric($this->ClearingAging->EditValue)) {
                $this->ClearingAging->EditValue = FormatNumber($this->ClearingAging->EditValue, null);
            }

            // Active
            $this->Active->EditValue = $this->Active->options(false);
            $this->Active->PlaceHolder = RemoveHtml($this->Active->caption());

            // Created_Date
            $this->Created_Date->setupEditAttributes();
            $this->Created_Date->CurrentValue = FormatDateTime($this->Created_Date->CurrentValue, $this->Created_Date->formatPattern());

            // Created_By
            $this->Created_By->setupEditAttributes();

            // Last_Updated_Date

            // Last_Updated_By

            // Edit refer script

            // ProjectName
            $this->ProjectName->HrefValue = "";

            // PlanStart
            $this->PlanStart->HrefValue = "";

            // PlanEnd
            $this->PlanEnd->HrefValue = "";

            // StartDate
            $this->StartDate->HrefValue = "";

            // EndDate
            $this->EndDate->HrefValue = "";

            // WarrantyEnd
            $this->WarrantyEnd->HrefValue = "";

            // Status
            $this->Status->HrefValue = "";

            // Target
            $this->Target->HrefValue = "";

            // Track
            $this->Track->HrefValue = "";

            // PaymentDate
            $this->PaymentDate->HrefValue = "";
            $this->PaymentDate->TooltipValue = "";

            // AgingPayment
            $this->AgingPayment->HrefValue = "";

            // ClientID
            $this->ClientID->HrefValue = "";

            // ManagerID
            $this->ManagerID->HrefValue = "";

            // ProjectTemplateID
            $this->ProjectTemplateID->HrefValue = "";

            // Priority
            $this->Priority->HrefValue = "";

            // Description
            $this->Description->HrefValue = "";

            // ProjectValue
            $this->ProjectValue->HrefValue = "";

            // ProjectDebt
            $this->ProjectDebt->HrefValue = "";

            // PONumber
            $this->PONumber->HrefValue = "";

            // PaymentLink
            $this->PaymentLink->HrefValue = "";

            // ClearingDate
            $this->ClearingDate->HrefValue = "";

            // ClearingAging
            $this->ClearingAging->HrefValue = "";

            // Active
            $this->Active->HrefValue = "";

            // Created_Date
            $this->Created_Date->HrefValue = "";

            // Created_By
            $this->Created_By->HrefValue = "";

            // Last_Updated_Date
            $this->Last_Updated_Date->HrefValue = "";

            // Last_Updated_By
            $this->Last_Updated_By->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, $Security;
        $updateCnt = 0;
        if ($this->ProjectName->multiUpdateSelected()) {
            $updateCnt++;
        }
        if ($this->PlanStart->multiUpdateSelected()) {
            $updateCnt++;
        }
        if ($this->PlanEnd->multiUpdateSelected()) {
            $updateCnt++;
        }
        if ($this->StartDate->multiUpdateSelected()) {
            $updateCnt++;
        }
        if ($this->EndDate->multiUpdateSelected()) {
            $updateCnt++;
        }
        if ($this->WarrantyEnd->multiUpdateSelected()) {
            $updateCnt++;
        }
        if ($this->Status->multiUpdateSelected()) {
            $updateCnt++;
        }
        if ($this->Target->multiUpdateSelected()) {
            $updateCnt++;
        }
        if ($this->Track->multiUpdateSelected()) {
            $updateCnt++;
        }
        if ($this->PaymentDate->multiUpdateSelected()) {
            $updateCnt++;
        }
        if ($this->AgingPayment->multiUpdateSelected()) {
            $updateCnt++;
        }
        if ($this->ClientID->multiUpdateSelected()) {
            $updateCnt++;
        }
        if ($this->ManagerID->multiUpdateSelected()) {
            $updateCnt++;
        }
        if ($this->ProjectTemplateID->multiUpdateSelected()) {
            $updateCnt++;
        }
        if ($this->Priority->multiUpdateSelected()) {
            $updateCnt++;
        }
        if ($this->Description->multiUpdateSelected()) {
            $updateCnt++;
        }
        if ($this->ProjectValue->multiUpdateSelected()) {
            $updateCnt++;
        }
        if ($this->ProjectDebt->multiUpdateSelected()) {
            $updateCnt++;
        }
        if ($this->PONumber->multiUpdateSelected()) {
            $updateCnt++;
        }
        if ($this->PaymentLink->multiUpdateSelected()) {
            $updateCnt++;
        }
        if ($this->ClearingDate->multiUpdateSelected()) {
            $updateCnt++;
        }
        if ($this->ClearingAging->multiUpdateSelected()) {
            $updateCnt++;
        }
        if ($this->Active->multiUpdateSelected()) {
            $updateCnt++;
        }
        if ($this->Created_Date->multiUpdateSelected()) {
            $updateCnt++;
        }
        if ($this->Created_By->multiUpdateSelected()) {
            $updateCnt++;
        }
        if ($this->Last_Updated_Date->multiUpdateSelected()) {
            $updateCnt++;
        }
        if ($this->Last_Updated_By->multiUpdateSelected()) {
            $updateCnt++;
        }
        if ($updateCnt == 0) {
            return false;
        }

        // Check if validation required
        if (!Config("SERVER_VALIDATE")) {
            return true;
        }
        $validateForm = true;
            if ($this->ProjectName->Visible && $this->ProjectName->Required) {
                if ($this->ProjectName->MultiUpdate != "" && !$this->ProjectName->IsDetailKey && EmptyValue($this->ProjectName->FormValue)) {
                    $this->ProjectName->addErrorMessage(str_replace("%s", $this->ProjectName->caption(), $this->ProjectName->RequiredErrorMessage));
                }
            }
            if ($this->PlanStart->Visible && $this->PlanStart->Required) {
                if ($this->PlanStart->MultiUpdate != "" && !$this->PlanStart->IsDetailKey && EmptyValue($this->PlanStart->FormValue)) {
                    $this->PlanStart->addErrorMessage(str_replace("%s", $this->PlanStart->caption(), $this->PlanStart->RequiredErrorMessage));
                }
            }
            if ($this->PlanStart->MultiUpdate != "") {
                if (!CheckDate($this->PlanStart->FormValue, $this->PlanStart->formatPattern())) {
                    $this->PlanStart->addErrorMessage($this->PlanStart->getErrorMessage(false));
                }
            }
            if ($this->PlanEnd->Visible && $this->PlanEnd->Required) {
                if ($this->PlanEnd->MultiUpdate != "" && !$this->PlanEnd->IsDetailKey && EmptyValue($this->PlanEnd->FormValue)) {
                    $this->PlanEnd->addErrorMessage(str_replace("%s", $this->PlanEnd->caption(), $this->PlanEnd->RequiredErrorMessage));
                }
            }
            if ($this->PlanEnd->MultiUpdate != "") {
                if (!CheckDate($this->PlanEnd->FormValue, $this->PlanEnd->formatPattern())) {
                    $this->PlanEnd->addErrorMessage($this->PlanEnd->getErrorMessage(false));
                }
            }
            if ($this->StartDate->Visible && $this->StartDate->Required) {
                if ($this->StartDate->MultiUpdate != "" && !$this->StartDate->IsDetailKey && EmptyValue($this->StartDate->FormValue)) {
                    $this->StartDate->addErrorMessage(str_replace("%s", $this->StartDate->caption(), $this->StartDate->RequiredErrorMessage));
                }
            }
            if ($this->StartDate->MultiUpdate != "") {
                if (!CheckDate($this->StartDate->FormValue, $this->StartDate->formatPattern())) {
                    $this->StartDate->addErrorMessage($this->StartDate->getErrorMessage(false));
                }
            }
            if ($this->EndDate->Visible && $this->EndDate->Required) {
                if ($this->EndDate->MultiUpdate != "" && !$this->EndDate->IsDetailKey && EmptyValue($this->EndDate->FormValue)) {
                    $this->EndDate->addErrorMessage(str_replace("%s", $this->EndDate->caption(), $this->EndDate->RequiredErrorMessage));
                }
            }
            if ($this->EndDate->MultiUpdate != "") {
                if (!CheckDate($this->EndDate->FormValue, $this->EndDate->formatPattern())) {
                    $this->EndDate->addErrorMessage($this->EndDate->getErrorMessage(false));
                }
            }
            if ($this->WarrantyEnd->Visible && $this->WarrantyEnd->Required) {
                if ($this->WarrantyEnd->MultiUpdate != "" && !$this->WarrantyEnd->IsDetailKey && EmptyValue($this->WarrantyEnd->FormValue)) {
                    $this->WarrantyEnd->addErrorMessage(str_replace("%s", $this->WarrantyEnd->caption(), $this->WarrantyEnd->RequiredErrorMessage));
                }
            }
            if ($this->WarrantyEnd->MultiUpdate != "") {
                if (!CheckDate($this->WarrantyEnd->FormValue, $this->WarrantyEnd->formatPattern())) {
                    $this->WarrantyEnd->addErrorMessage($this->WarrantyEnd->getErrorMessage(false));
                }
            }
            if ($this->Status->Visible && $this->Status->Required) {
                if ($this->Status->MultiUpdate != "" && !$this->Status->IsDetailKey && EmptyValue($this->Status->FormValue)) {
                    $this->Status->addErrorMessage(str_replace("%s", $this->Status->caption(), $this->Status->RequiredErrorMessage));
                }
            }
            if ($this->Target->Visible && $this->Target->Required) {
                if ($this->Target->MultiUpdate != "" && !$this->Target->IsDetailKey && EmptyValue($this->Target->FormValue)) {
                    $this->Target->addErrorMessage(str_replace("%s", $this->Target->caption(), $this->Target->RequiredErrorMessage));
                }
            }
            if ($this->Target->MultiUpdate != "") {
                if (!CheckNumber($this->Target->FormValue)) {
                    $this->Target->addErrorMessage($this->Target->getErrorMessage(false));
                }
            }
            if ($this->Track->Visible && $this->Track->Required) {
                if ($this->Track->MultiUpdate != "" && !$this->Track->IsDetailKey && EmptyValue($this->Track->FormValue)) {
                    $this->Track->addErrorMessage(str_replace("%s", $this->Track->caption(), $this->Track->RequiredErrorMessage));
                }
            }
            if ($this->PaymentDate->Visible && $this->PaymentDate->Required) {
                if ($this->PaymentDate->MultiUpdate != "" && !$this->PaymentDate->IsDetailKey && EmptyValue($this->PaymentDate->FormValue)) {
                    $this->PaymentDate->addErrorMessage(str_replace("%s", $this->PaymentDate->caption(), $this->PaymentDate->RequiredErrorMessage));
                }
            }
            if ($this->AgingPayment->Visible && $this->AgingPayment->Required) {
                if ($this->AgingPayment->MultiUpdate != "" && !$this->AgingPayment->IsDetailKey && EmptyValue($this->AgingPayment->FormValue)) {
                    $this->AgingPayment->addErrorMessage(str_replace("%s", $this->AgingPayment->caption(), $this->AgingPayment->RequiredErrorMessage));
                }
            }
            if ($this->AgingPayment->MultiUpdate != "") {
                if (!CheckInteger($this->AgingPayment->FormValue)) {
                    $this->AgingPayment->addErrorMessage($this->AgingPayment->getErrorMessage(false));
                }
            }
            if ($this->ClientID->Visible && $this->ClientID->Required) {
                if ($this->ClientID->MultiUpdate != "" && !$this->ClientID->IsDetailKey && EmptyValue($this->ClientID->FormValue)) {
                    $this->ClientID->addErrorMessage(str_replace("%s", $this->ClientID->caption(), $this->ClientID->RequiredErrorMessage));
                }
            }
            if ($this->ManagerID->Visible && $this->ManagerID->Required) {
                if ($this->ManagerID->MultiUpdate != "" && !$this->ManagerID->IsDetailKey && EmptyValue($this->ManagerID->FormValue)) {
                    $this->ManagerID->addErrorMessage(str_replace("%s", $this->ManagerID->caption(), $this->ManagerID->RequiredErrorMessage));
                }
            }
            if ($this->ProjectTemplateID->Visible && $this->ProjectTemplateID->Required) {
                if ($this->ProjectTemplateID->MultiUpdate != "" && !$this->ProjectTemplateID->IsDetailKey && EmptyValue($this->ProjectTemplateID->FormValue)) {
                    $this->ProjectTemplateID->addErrorMessage(str_replace("%s", $this->ProjectTemplateID->caption(), $this->ProjectTemplateID->RequiredErrorMessage));
                }
            }
            if ($this->Priority->Visible && $this->Priority->Required) {
                if ($this->Priority->MultiUpdate != "" && !$this->Priority->IsDetailKey && EmptyValue($this->Priority->FormValue)) {
                    $this->Priority->addErrorMessage(str_replace("%s", $this->Priority->caption(), $this->Priority->RequiredErrorMessage));
                }
            }
            if ($this->Description->Visible && $this->Description->Required) {
                if ($this->Description->MultiUpdate != "" && !$this->Description->IsDetailKey && EmptyValue($this->Description->FormValue)) {
                    $this->Description->addErrorMessage(str_replace("%s", $this->Description->caption(), $this->Description->RequiredErrorMessage));
                }
            }
            if ($this->ProjectValue->Visible && $this->ProjectValue->Required) {
                if ($this->ProjectValue->MultiUpdate != "" && !$this->ProjectValue->IsDetailKey && EmptyValue($this->ProjectValue->FormValue)) {
                    $this->ProjectValue->addErrorMessage(str_replace("%s", $this->ProjectValue->caption(), $this->ProjectValue->RequiredErrorMessage));
                }
            }
            if ($this->ProjectValue->MultiUpdate != "") {
                if (!CheckNumber($this->ProjectValue->FormValue)) {
                    $this->ProjectValue->addErrorMessage($this->ProjectValue->getErrorMessage(false));
                }
            }
            if ($this->ProjectDebt->Visible && $this->ProjectDebt->Required) {
                if ($this->ProjectDebt->MultiUpdate != "" && !$this->ProjectDebt->IsDetailKey && EmptyValue($this->ProjectDebt->FormValue)) {
                    $this->ProjectDebt->addErrorMessage(str_replace("%s", $this->ProjectDebt->caption(), $this->ProjectDebt->RequiredErrorMessage));
                }
            }
            if ($this->ProjectDebt->MultiUpdate != "") {
                if (!CheckNumber($this->ProjectDebt->FormValue)) {
                    $this->ProjectDebt->addErrorMessage($this->ProjectDebt->getErrorMessage(false));
                }
            }
            if ($this->PONumber->Visible && $this->PONumber->Required) {
                if ($this->PONumber->MultiUpdate != "" && !$this->PONumber->IsDetailKey && EmptyValue($this->PONumber->FormValue)) {
                    $this->PONumber->addErrorMessage(str_replace("%s", $this->PONumber->caption(), $this->PONumber->RequiredErrorMessage));
                }
            }
            if ($this->PaymentLink->Visible && $this->PaymentLink->Required) {
                if ($this->PaymentLink->MultiUpdate != "" && !$this->PaymentLink->IsDetailKey && EmptyValue($this->PaymentLink->FormValue)) {
                    $this->PaymentLink->addErrorMessage(str_replace("%s", $this->PaymentLink->caption(), $this->PaymentLink->RequiredErrorMessage));
                }
            }
            if ($this->ClearingDate->Visible && $this->ClearingDate->Required) {
                if ($this->ClearingDate->MultiUpdate != "" && !$this->ClearingDate->IsDetailKey && EmptyValue($this->ClearingDate->FormValue)) {
                    $this->ClearingDate->addErrorMessage(str_replace("%s", $this->ClearingDate->caption(), $this->ClearingDate->RequiredErrorMessage));
                }
            }
            if ($this->ClearingDate->MultiUpdate != "") {
                if (!CheckDate($this->ClearingDate->FormValue, $this->ClearingDate->formatPattern())) {
                    $this->ClearingDate->addErrorMessage($this->ClearingDate->getErrorMessage(false));
                }
            }
            if ($this->ClearingAging->Visible && $this->ClearingAging->Required) {
                if ($this->ClearingAging->MultiUpdate != "" && !$this->ClearingAging->IsDetailKey && EmptyValue($this->ClearingAging->FormValue)) {
                    $this->ClearingAging->addErrorMessage(str_replace("%s", $this->ClearingAging->caption(), $this->ClearingAging->RequiredErrorMessage));
                }
            }
            if ($this->ClearingAging->MultiUpdate != "") {
                if (!CheckInteger($this->ClearingAging->FormValue)) {
                    $this->ClearingAging->addErrorMessage($this->ClearingAging->getErrorMessage(false));
                }
            }
            if ($this->Active->Visible && $this->Active->Required) {
                if ($this->Active->MultiUpdate != "" && $this->Active->FormValue == "") {
                    $this->Active->addErrorMessage(str_replace("%s", $this->Active->caption(), $this->Active->RequiredErrorMessage));
                }
            }
            if ($this->Created_Date->Visible && $this->Created_Date->Required) {
                if ($this->Created_Date->MultiUpdate != "" && !$this->Created_Date->IsDetailKey && EmptyValue($this->Created_Date->FormValue)) {
                    $this->Created_Date->addErrorMessage(str_replace("%s", $this->Created_Date->caption(), $this->Created_Date->RequiredErrorMessage));
                }
            }
            if ($this->Created_By->Visible && $this->Created_By->Required) {
                if ($this->Created_By->MultiUpdate != "" && !$this->Created_By->IsDetailKey && EmptyValue($this->Created_By->FormValue)) {
                    $this->Created_By->addErrorMessage(str_replace("%s", $this->Created_By->caption(), $this->Created_By->RequiredErrorMessage));
                }
            }
            if ($this->Last_Updated_Date->Visible && $this->Last_Updated_Date->Required) {
                if ($this->Last_Updated_Date->MultiUpdate != "" && !$this->Last_Updated_Date->IsDetailKey && EmptyValue($this->Last_Updated_Date->FormValue)) {
                    $this->Last_Updated_Date->addErrorMessage(str_replace("%s", $this->Last_Updated_Date->caption(), $this->Last_Updated_Date->RequiredErrorMessage));
                }
            }
            if ($this->Last_Updated_By->Visible && $this->Last_Updated_By->Required) {
                if ($this->Last_Updated_By->MultiUpdate != "" && !$this->Last_Updated_By->IsDetailKey && EmptyValue($this->Last_Updated_By->FormValue)) {
                    $this->Last_Updated_By->addErrorMessage(str_replace("%s", $this->Last_Updated_By->caption(), $this->Last_Updated_By->RequiredErrorMessage));
                }
            }

        // Return validate result
        $validateForm = $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();

        // Load old row
        $this->CurrentFilter = $filter;
        $sql = $this->getCurrentSql();
        $rsold = $conn->fetchAssociative($sql);
        if (!$rsold) {
            $this->setFailureMessage($Language->phrase("NoRecord")); // Set no record message
            return false; // Update Failed
        } else {
            // Load old values
            $this->loadDbValues($rsold);
        }

        // Get new row
        $rsnew = $this->getEditRow($rsold);

        // Update current values
        $this->setCurrentValues($rsnew);

        // Check field with unique index (ProjectName)
        if ($this->ProjectName->CurrentValue != "") {
            $filterChk = "(`ProjectName` = '" . AdjustSql($this->ProjectName->CurrentValue, $this->Dbid) . "')";
            $filterChk .= " AND NOT (" . $filter . ")";
            $this->CurrentFilter = $filterChk;
            $sqlChk = $this->getCurrentSql();
            $rsChk = $conn->executeQuery($sqlChk);
            if (!$rsChk) {
                return false;
            }
            if ($rsChk->fetch()) {
                $idxErrMsg = str_replace("%f", $this->ProjectName->caption(), $Language->phrase("DupIndex"));
                $idxErrMsg = str_replace("%v", $this->ProjectName->CurrentValue, $idxErrMsg);
                $this->setFailureMessage($idxErrMsg);
                return false;
            }
        }

        // Call Row Updating event
        $updateRow = $this->rowUpdating($rsold, $rsnew);
        if ($updateRow) {
            if (count($rsnew) > 0) {
                $this->CurrentFilter = $filter; // Set up current filter
                $editRow = $this->update($rsnew, "", $rsold);
                if (!$editRow && !EmptyValue($this->DbErrorMessage)) { // Show database error
                    $this->setFailureMessage($this->DbErrorMessage);
                }
            } 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);
        }
        return $editRow;
    }

    /**
     * Get edit row
     *
     * @return array
     */
    protected function getEditRow($rsold)
    {
        global $Security;
        $rsnew = [];

        // ProjectName
        $this->ProjectName->setDbValueDef($rsnew, $this->ProjectName->CurrentValue, $this->ProjectName->ReadOnly || $this->ProjectName->MultiUpdate != "1");

        // PlanStart
        $this->PlanStart->setDbValueDef($rsnew, UnFormatDateTime($this->PlanStart->CurrentValue, $this->PlanStart->formatPattern()), $this->PlanStart->ReadOnly || $this->PlanStart->MultiUpdate != "1");

        // PlanEnd
        $this->PlanEnd->setDbValueDef($rsnew, UnFormatDateTime($this->PlanEnd->CurrentValue, $this->PlanEnd->formatPattern()), $this->PlanEnd->ReadOnly || $this->PlanEnd->MultiUpdate != "1");

        // StartDate
        $this->StartDate->setDbValueDef($rsnew, UnFormatDateTime($this->StartDate->CurrentValue, $this->StartDate->formatPattern()), $this->StartDate->ReadOnly || $this->StartDate->MultiUpdate != "1");

        // EndDate
        $this->EndDate->setDbValueDef($rsnew, UnFormatDateTime($this->EndDate->CurrentValue, $this->EndDate->formatPattern()), $this->EndDate->ReadOnly || $this->EndDate->MultiUpdate != "1");

        // WarrantyEnd
        $this->WarrantyEnd->setDbValueDef($rsnew, UnFormatDateTime($this->WarrantyEnd->CurrentValue, $this->WarrantyEnd->formatPattern()), $this->WarrantyEnd->ReadOnly || $this->WarrantyEnd->MultiUpdate != "1");

        // Status
        $this->Status->setDbValueDef($rsnew, $this->Status->CurrentValue, $this->Status->ReadOnly || $this->Status->MultiUpdate != "1");

        // Target
        $this->Target->setDbValueDef($rsnew, $this->Target->CurrentValue, $this->Target->ReadOnly || $this->Target->MultiUpdate != "1");

        // Track
        $this->Track->setDbValueDef($rsnew, $this->Track->CurrentValue, $this->Track->ReadOnly || $this->Track->MultiUpdate != "1");

        // AgingPayment
        $this->AgingPayment->setDbValueDef($rsnew, $this->AgingPayment->CurrentValue, $this->AgingPayment->ReadOnly || $this->AgingPayment->MultiUpdate != "1");

        // ClientID
        $this->ClientID->setDbValueDef($rsnew, $this->ClientID->CurrentValue, $this->ClientID->ReadOnly || $this->ClientID->MultiUpdate != "1");

        // ManagerID
        $this->ManagerID->setDbValueDef($rsnew, $this->ManagerID->CurrentValue, $this->ManagerID->ReadOnly || $this->ManagerID->MultiUpdate != "1");

        // ProjectTemplateID
        $this->ProjectTemplateID->setDbValueDef($rsnew, $this->ProjectTemplateID->CurrentValue, $this->ProjectTemplateID->ReadOnly || $this->ProjectTemplateID->MultiUpdate != "1");

        // Priority
        $this->Priority->setDbValueDef($rsnew, $this->Priority->CurrentValue, $this->Priority->ReadOnly || $this->Priority->MultiUpdate != "1");

        // Description
        $this->Description->setDbValueDef($rsnew, $this->Description->CurrentValue, $this->Description->ReadOnly || $this->Description->MultiUpdate != "1");

        // ProjectValue
        $this->ProjectValue->setDbValueDef($rsnew, $this->ProjectValue->CurrentValue, $this->ProjectValue->ReadOnly || $this->ProjectValue->MultiUpdate != "1");

        // ProjectDebt
        $this->ProjectDebt->setDbValueDef($rsnew, $this->ProjectDebt->CurrentValue, $this->ProjectDebt->ReadOnly || $this->ProjectDebt->MultiUpdate != "1");

        // PONumber
        $this->PONumber->setDbValueDef($rsnew, $this->PONumber->CurrentValue, $this->PONumber->ReadOnly || $this->PONumber->MultiUpdate != "1");

        // PaymentLink
        $this->PaymentLink->setDbValueDef($rsnew, $this->PaymentLink->CurrentValue, $this->PaymentLink->ReadOnly || $this->PaymentLink->MultiUpdate != "1");

        // ClearingDate
        $this->ClearingDate->setDbValueDef($rsnew, UnFormatDateTime($this->ClearingDate->CurrentValue, $this->ClearingDate->formatPattern()), $this->ClearingDate->ReadOnly || $this->ClearingDate->MultiUpdate != "1");

        // ClearingAging
        $this->ClearingAging->setDbValueDef($rsnew, $this->ClearingAging->CurrentValue, $this->ClearingAging->ReadOnly || $this->ClearingAging->MultiUpdate != "1");

        // Active
        $tmpBool = $this->Active->CurrentValue;
        if ($tmpBool != "1" && $tmpBool != "0") {
            $tmpBool = !empty($tmpBool) ? "1" : "0";
        }
        $this->Active->setDbValueDef($rsnew, $tmpBool, $this->Active->ReadOnly || $this->Active->MultiUpdate != "1");

        // Created_Date
        $this->Created_Date->setDbValueDef($rsnew, UnFormatDateTime($this->Created_Date->CurrentValue, $this->Created_Date->formatPattern()), $this->Created_Date->ReadOnly || $this->Created_Date->MultiUpdate != "1");

        // Created_By
        $this->Created_By->setDbValueDef($rsnew, $this->Created_By->CurrentValue, $this->Created_By->ReadOnly || $this->Created_By->MultiUpdate != "1");

        // Last_Updated_Date
        $this->Last_Updated_Date->CurrentValue = $this->Last_Updated_Date->getAutoUpdateValue(); // PHP
        $this->Last_Updated_Date->setDbValueDef($rsnew, UnFormatDateTime($this->Last_Updated_Date->CurrentValue, $this->Last_Updated_Date->formatPattern()));

        // Last_Updated_By
        $this->Last_Updated_By->CurrentValue = $this->Last_Updated_By->getAutoUpdateValue(); // PHP
        $this->Last_Updated_By->setDbValueDef($rsnew, $this->Last_Updated_By->CurrentValue);
        return $rsnew;
    }

    /**
     * Restore edit form from row
     * @param array $row Row
     */
    protected function restoreEditFormFromRow($row)
    {
        if (isset($row['ProjectName'])) { // ProjectName
            $this->ProjectName->CurrentValue = $row['ProjectName'];
        }
        if (isset($row['PlanStart'])) { // PlanStart
            $this->PlanStart->CurrentValue = $row['PlanStart'];
        }
        if (isset($row['PlanEnd'])) { // PlanEnd
            $this->PlanEnd->CurrentValue = $row['PlanEnd'];
        }
        if (isset($row['StartDate'])) { // StartDate
            $this->StartDate->CurrentValue = $row['StartDate'];
        }
        if (isset($row['EndDate'])) { // EndDate
            $this->EndDate->CurrentValue = $row['EndDate'];
        }
        if (isset($row['WarrantyEnd'])) { // WarrantyEnd
            $this->WarrantyEnd->CurrentValue = $row['WarrantyEnd'];
        }
        if (isset($row['Status'])) { // Status
            $this->Status->CurrentValue = $row['Status'];
        }
        if (isset($row['Target'])) { // Target
            $this->Target->CurrentValue = $row['Target'];
        }
        if (isset($row['Track'])) { // Track
            $this->Track->CurrentValue = $row['Track'];
        }
        if (isset($row['AgingPayment'])) { // AgingPayment
            $this->AgingPayment->CurrentValue = $row['AgingPayment'];
        }
        if (isset($row['ClientID'])) { // ClientID
            $this->ClientID->CurrentValue = $row['ClientID'];
        }
        if (isset($row['ManagerID'])) { // ManagerID
            $this->ManagerID->CurrentValue = $row['ManagerID'];
        }
        if (isset($row['ProjectTemplateID'])) { // ProjectTemplateID
            $this->ProjectTemplateID->CurrentValue = $row['ProjectTemplateID'];
        }
        if (isset($row['Priority'])) { // Priority
            $this->Priority->CurrentValue = $row['Priority'];
        }
        if (isset($row['Description'])) { // Description
            $this->Description->CurrentValue = $row['Description'];
        }
        if (isset($row['ProjectValue'])) { // ProjectValue
            $this->ProjectValue->CurrentValue = $row['ProjectValue'];
        }
        if (isset($row['ProjectDebt'])) { // ProjectDebt
            $this->ProjectDebt->CurrentValue = $row['ProjectDebt'];
        }
        if (isset($row['PONumber'])) { // PONumber
            $this->PONumber->CurrentValue = $row['PONumber'];
        }
        if (isset($row['PaymentLink'])) { // PaymentLink
            $this->PaymentLink->CurrentValue = $row['PaymentLink'];
        }
        if (isset($row['ClearingDate'])) { // ClearingDate
            $this->ClearingDate->CurrentValue = $row['ClearingDate'];
        }
        if (isset($row['ClearingAging'])) { // ClearingAging
            $this->ClearingAging->CurrentValue = $row['ClearingAging'];
        }
        if (isset($row['Active'])) { // Active
            $this->Active->CurrentValue = $row['Active'];
        }
        if (isset($row['Created_Date'])) { // Created_Date
            $this->Created_Date->CurrentValue = $row['Created_Date'];
        }
        if (isset($row['Created_By'])) { // Created_By
            $this->Created_By->CurrentValue = $row['Created_By'];
        }
        if (isset($row['Last_Updated_Date'])) { // Last_Updated_Date
            $this->Last_Updated_Date->CurrentValue = $row['Last_Updated_Date'];
        }
        if (isset($row['Last_Updated_By'])) { // Last_Updated_By
            $this->Last_Updated_By->CurrentValue = $row['Last_Updated_By'];
        }
    }

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

    // Setup lookup options
    public function setupLookupOptions($fld)
    {
        if ($fld->Lookup && $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;
                case "x_ClientID":
                    $lookupFilter = $fld->getSelectFilter(); // PHP
                    break;
                case "x_ManagerID":
                    $lookupFilter = $fld->getSelectFilter(); // PHP
                    break;
                case "x_ProjectTemplateID":
                    $lookupFilter = $fld->getSelectFilter(); // PHP
                    break;
                case "x_Priority":
                    break;
                case "x_Active":
                    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->hasLookupOptions() && $fld->UseLookupCache && $sql != "" && count($fld->Lookup->Options) == 0 && count($fld->Lookup->FilterFields) == 0) {
                $totalCnt = $this->getRecordCount($sql, $conn);
                if ($totalCnt > $fld->LookupCacheCount) { // Total count > cache count, do not cache
                    return;
                }
                $rows = $conn->executeQuery($sql)->fetchAll();
                $ar = [];
                foreach ($rows as $row) {
                    $row = $fld->Lookup->renderViewRow($row, Container($fld->Lookup->LinkTable));
                    $key = $row["lf"];
                    if (IsFloatType($fld->Type)) { // Handle float field
                        $key = (float)$key;
                    }
                    $ar[strval($key)] = $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";
    }

    // Page Breaking event
    public function pageBreaking(&$break, &$content)
    {
        // Example:
        //$break = false; // Skip page break, or
        //$content = "<div style=\"break-after:page;\"></div>"; // Modify page break content
    }

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