<?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 MasterprojectAdd extends Masterproject
{
    use MessagesTrait;

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

    // Project ID
    public $ProjectID = PROJECT_ID;

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

    // View file path
    public $View = null;

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

    // Rendering View
    public $RenderingView = false;

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

    // 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->Visible = false;
        $this->Track->Visible = false;
        $this->PaymentProgress->Visible = false;
        $this->PaymentDate->Visible = false;
        $this->PaymentComplete->Visible = false;
        $this->AgingPayment->Visible = false;
        $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-add-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-add-form";
    public $IsModal = false;
    public $IsMobileOrModal = false;
    public $DbMasterFilter = "";
    public $DbDetailFilter = "";
    public $StartRecord;
    public $Priv = 0;
    public $CopyRecord;
    public $MultiPages; // Multi pages object
    public $DetailPages; // Detail pages object

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

        // Set up multi page object
        $this->setupMultiPages();

        // Set up detail page object
        $this->setupDetailPages();

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

        // Load default values for add
        $this->loadDefaultValues();

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

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

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

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

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

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

        // Perform current action
        switch ($this->CurrentAction) {
            case "copy": // Copy an existing record
                if (!$rsold) { // Record not loaded
                    if ($this->getFailureMessage() == "") {
                        $this->setFailureMessage($Language->phrase("NoRecord")); // No record found
                    }
                    $this->terminate("masterprojectlist"); // No matching record, return to list
                    return;
                }

                // Set up detail parameters
                $this->setupDetailParms();
                break;
            case "insert": // Add new record
                $this->SendEmail = true; // Send email on add success
                if ($this->addRow($rsold)) { // Add successful
                    if ($this->getSuccessMessage() == "" && Post("addopt") != "1") { // Skip success message for addopt (done in JavaScript)
                        $this->setSuccessMessage($Language->phrase("AddSuccess")); // Set up success message
                    }
                    if ($this->getCurrentDetailTable() != "") { // Master/detail add
                        $returnUrl = $this->getDetailUrl();
                    } else {
                        $returnUrl = $this->getReturnUrl();
                    }
                    if (GetPageName($returnUrl) == "masterprojectlist") {
                        $returnUrl = $this->addMasterUrl($returnUrl); // List page, return to List page with correct master key if necessary
                    } elseif (GetPageName($returnUrl) == "masterprojectview") {
                        $returnUrl = $this->getViewUrl(); // View page, return to View page with keyurl directly
                    }

                    // Handle UseAjaxActions
                    if ($this->IsModal && $this->UseAjaxActions) {
                        $this->IsModal = false;
                        if (GetPageName($returnUrl) != "masterprojectlist") {
                            Container("app.flash")->addMessage("Return-Url", $returnUrl); // Save return URL
                            $returnUrl = "masterprojectlist"; // Return list page content
                        }
                    }
                    if (IsJsonResponse()) { // Return to caller
                        $this->terminate(true);
                        return;
                    } else {
                        $this->terminate($returnUrl);
                        return;
                    }
                } elseif (IsApi()) { // API request, return
                    $this->terminate();
                    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->EventCancelled = true; // Event cancelled
                    $this->restoreFormValues(); // Add failed, restore form values

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

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

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

        // Render row
        $this->resetAttributes();
        $this->renderRow();

        // Set LoginStatus / Page_Rendering / Page_Render
        if (!IsApi() && !$this->isTerminated()) {
            // 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();
            }
        }
    }

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

    // Load default values
    protected function loadDefaultValues()
    {
        $this->PlanStart->DefaultValue = $this->PlanStart->getDefault(); // PHP
        $this->PlanStart->OldValue = $this->PlanStart->DefaultValue;
        $this->StartDate->DefaultValue = $this->StartDate->getDefault(); // PHP
        $this->StartDate->OldValue = $this->StartDate->DefaultValue;
        $this->Status->DefaultValue = $this->Status->getDefault(); // PHP
        $this->Status->OldValue = $this->Status->DefaultValue;
        $this->Progress->DefaultValue = $this->Progress->getDefault(); // PHP
        $this->Progress->OldValue = $this->Progress->DefaultValue;
        $this->PaymentProgress->DefaultValue = $this->PaymentProgress->getDefault(); // PHP
        $this->PaymentProgress->OldValue = $this->PaymentProgress->DefaultValue;
        $this->Priority->DefaultValue = $this->Priority->getDefault(); // PHP
        $this->Priority->OldValue = $this->Priority->DefaultValue;
        $this->Active->DefaultValue = $this->Active->getDefault(); // PHP
        $this->Active->OldValue = $this->Active->DefaultValue;
        $this->Created_Date->DefaultValue = $this->Created_Date->getDefault(); // PHP
        $this->Created_Date->OldValue = $this->Created_Date->DefaultValue;
        $this->Created_By->DefaultValue = $this->Created_By->getDefault(); // PHP
        $this->Created_By->OldValue = $this->Created_By->DefaultValue;
        $this->Last_Updated_Date->DefaultValue = $this->Last_Updated_Date->getDefault(); // PHP
        $this->Last_Updated_Date->OldValue = $this->Last_Updated_Date->DefaultValue;
        $this->Last_Updated_By->DefaultValue = $this->Last_Updated_By->getDefault(); // PHP
        $this->Last_Updated_By->OldValue = $this->Last_Updated_By->DefaultValue;
    }

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

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

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

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

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

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

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

        // Check field name '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);
            }
        }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    // Restore form values
    public function restoreFormValues()
    {
        global $CurrentForm;
        $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->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 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;
    }

    // Load old record
    protected function loadOldRecord()
    {
        // Load old record
        if ($this->OldKey != "") {
            $this->setKey($this->OldKey);
            $this->CurrentFilter = $this->getRecordFilter();
            $sql = $this->getCurrentSql();
            $conn = $this->getConnection();
            $rs = ExecuteQuery($sql, $conn);
            if ($row = $rs->fetch()) {
                $this->loadRowValues($row); // Load row values
                return $row;
            }
        }
        $this->loadRowValues(); // Load default row values
        return null;
    }

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

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

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

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

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

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

            // Status
            $this->Status->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 = "";
        } elseif ($this->RowType == RowType::ADD) {
            // 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());

            // 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->getDefault(), $this->Created_Date->formatPattern());

            // Created_By
            $this->Created_By->setupEditAttributes();
            $this->Created_By->CurrentValue = $this->Created_By->getDefault();

            // Last_Updated_Date

            // Last_Updated_By

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

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

        // Check if validation required
        if (!Config("SERVER_VALIDATE")) {
            return true;
        }
        $validateForm = true;
            if ($this->ProjectName->Visible && $this->ProjectName->Required) {
                if (!$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->IsDetailKey && EmptyValue($this->PlanStart->FormValue)) {
                    $this->PlanStart->addErrorMessage(str_replace("%s", $this->PlanStart->caption(), $this->PlanStart->RequiredErrorMessage));
                }
            }
            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->IsDetailKey && EmptyValue($this->PlanEnd->FormValue)) {
                    $this->PlanEnd->addErrorMessage(str_replace("%s", $this->PlanEnd->caption(), $this->PlanEnd->RequiredErrorMessage));
                }
            }
            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->IsDetailKey && EmptyValue($this->StartDate->FormValue)) {
                    $this->StartDate->addErrorMessage(str_replace("%s", $this->StartDate->caption(), $this->StartDate->RequiredErrorMessage));
                }
            }
            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->IsDetailKey && EmptyValue($this->EndDate->FormValue)) {
                    $this->EndDate->addErrorMessage(str_replace("%s", $this->EndDate->caption(), $this->EndDate->RequiredErrorMessage));
                }
            }
            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->IsDetailKey && EmptyValue($this->WarrantyEnd->FormValue)) {
                    $this->WarrantyEnd->addErrorMessage(str_replace("%s", $this->WarrantyEnd->caption(), $this->WarrantyEnd->RequiredErrorMessage));
                }
            }
            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->IsDetailKey && EmptyValue($this->Status->FormValue)) {
                    $this->Status->addErrorMessage(str_replace("%s", $this->Status->caption(), $this->Status->RequiredErrorMessage));
                }
            }
            if ($this->ClientID->Visible && $this->ClientID->Required) {
                if (!$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->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->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->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->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->IsDetailKey && EmptyValue($this->ProjectValue->FormValue)) {
                    $this->ProjectValue->addErrorMessage(str_replace("%s", $this->ProjectValue->caption(), $this->ProjectValue->RequiredErrorMessage));
                }
            }
            if (!CheckNumber($this->ProjectValue->FormValue)) {
                $this->ProjectValue->addErrorMessage($this->ProjectValue->getErrorMessage(false));
            }
            if ($this->ProjectDebt->Visible && $this->ProjectDebt->Required) {
                if (!$this->ProjectDebt->IsDetailKey && EmptyValue($this->ProjectDebt->FormValue)) {
                    $this->ProjectDebt->addErrorMessage(str_replace("%s", $this->ProjectDebt->caption(), $this->ProjectDebt->RequiredErrorMessage));
                }
            }
            if (!CheckNumber($this->ProjectDebt->FormValue)) {
                $this->ProjectDebt->addErrorMessage($this->ProjectDebt->getErrorMessage(false));
            }
            if ($this->PONumber->Visible && $this->PONumber->Required) {
                if (!$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->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->IsDetailKey && EmptyValue($this->ClearingDate->FormValue)) {
                    $this->ClearingDate->addErrorMessage(str_replace("%s", $this->ClearingDate->caption(), $this->ClearingDate->RequiredErrorMessage));
                }
            }
            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->IsDetailKey && EmptyValue($this->ClearingAging->FormValue)) {
                    $this->ClearingAging->addErrorMessage(str_replace("%s", $this->ClearingAging->caption(), $this->ClearingAging->RequiredErrorMessage));
                }
            }
            if (!CheckInteger($this->ClearingAging->FormValue)) {
                $this->ClearingAging->addErrorMessage($this->ClearingAging->getErrorMessage(false));
            }
            if ($this->Active->Visible && $this->Active->Required) {
                if ($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->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->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->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->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));
                }
            }

        // Validate detail grid
        $detailTblVar = explode(",", $this->getCurrentDetailTable());
        $detailPage = Container("ProjectmemberGrid");
        if (in_array("projectmember", $detailTblVar) && $detailPage->DetailAdd) {
            $detailPage->run();
            $validateForm = $validateForm && $detailPage->validateGridForm();
        }
        $detailPage = Container("ProjecttaskGrid");
        if (in_array("projecttask", $detailTblVar) && $detailPage->DetailAdd) {
            $detailPage->run();
            $validateForm = $validateForm && $detailPage->validateGridForm();
        }
        $detailPage = Container("ProjectresultGrid");
        if (in_array("projectresult", $detailTblVar) && $detailPage->DetailAdd) {
            $detailPage->run();
            $validateForm = $validateForm && $detailPage->validateGridForm();
        }
        $detailPage = Container("ProjectmomGrid");
        if (in_array("projectmom", $detailTblVar) && $detailPage->DetailAdd) {
            $detailPage->run();
            $validateForm = $validateForm && $detailPage->validateGridForm();
        }
        $detailPage = Container("ProjectdocumentsGrid");
        if (in_array("projectdocuments", $detailTblVar) && $detailPage->DetailAdd) {
            $detailPage->run();
            $validateForm = $validateForm && $detailPage->validateGridForm();
        }
        $detailPage = Container("ProjectpaymentprocessGrid");
        if (in_array("projectpaymentprocess", $detailTblVar) && $detailPage->DetailAdd) {
            $detailPage->run();
            $validateForm = $validateForm && $detailPage->validateGridForm();
        }
        $detailPage = Container("ProjectproblemsGrid");
        if (in_array("projectproblems", $detailTblVar) && $detailPage->DetailAdd) {
            $detailPage->run();
            $validateForm = $validateForm && $detailPage->validateGridForm();
        }

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

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

    // Add record
    protected function addRow($rsold = null)
    {
        global $Language, $Security;

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

        // Update current values
        $this->setCurrentValues($rsnew);
        if ($this->ProjectName->CurrentValue != "") { // Check field with unique index
            $filter = "(`ProjectName` = '" . AdjustSql($this->ProjectName->CurrentValue, $this->Dbid) . "')";
            $rsChk = $this->loadRs($filter)->fetch();
            if ($rsChk !== false) {
                $idxErrMsg = str_replace("%f", $this->ProjectName->caption(), $Language->phrase("DupIndex"));
                $idxErrMsg = str_replace("%v", $this->ProjectName->CurrentValue, $idxErrMsg);
                $this->setFailureMessage($idxErrMsg);
                return false;
            }
        }
        $conn = $this->getConnection();

        // Begin transaction
        if ($this->getCurrentDetailTable() != "" && $this->UseTransaction) {
            $conn->beginTransaction();
        }

        // Load db values from old row
        $this->loadDbValues($rsold);

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

        // Add detail records
        if ($addRow) {
            $detailTblVar = explode(",", $this->getCurrentDetailTable());
            $detailPage = Container("ProjectmemberGrid");
            if (in_array("projectmember", $detailTblVar) && $detailPage->DetailAdd && $addRow) {
                $detailPage->_ProjectID->setSessionValue($this->_ProjectID->CurrentValue); // Set master key
                $Security->loadCurrentUserLevel($this->ProjectID . "projectmember"); // Load user level of detail table
                $addRow = $detailPage->gridInsert();
                $Security->loadCurrentUserLevel($this->ProjectID . $this->TableName); // Restore user level of master table
                if (!$addRow) {
                $detailPage->_ProjectID->setSessionValue(""); // Clear master key if insert failed
                }
            }
            $detailPage = Container("ProjecttaskGrid");
            if (in_array("projecttask", $detailTblVar) && $detailPage->DetailAdd && $addRow) {
                $detailPage->_ProjectID->setSessionValue($this->_ProjectID->CurrentValue); // Set master key
                $Security->loadCurrentUserLevel($this->ProjectID . "projecttask"); // Load user level of detail table
                $addRow = $detailPage->gridInsert();
                $Security->loadCurrentUserLevel($this->ProjectID . $this->TableName); // Restore user level of master table
                if (!$addRow) {
                $detailPage->_ProjectID->setSessionValue(""); // Clear master key if insert failed
                }
            }
            $detailPage = Container("ProjectresultGrid");
            if (in_array("projectresult", $detailTblVar) && $detailPage->DetailAdd && $addRow) {
                $detailPage->_ProjectID->setSessionValue($this->_ProjectID->CurrentValue); // Set master key
                $Security->loadCurrentUserLevel($this->ProjectID . "projectresult"); // Load user level of detail table
                $addRow = $detailPage->gridInsert();
                $Security->loadCurrentUserLevel($this->ProjectID . $this->TableName); // Restore user level of master table
                if (!$addRow) {
                $detailPage->_ProjectID->setSessionValue(""); // Clear master key if insert failed
                }
            }
            $detailPage = Container("ProjectmomGrid");
            if (in_array("projectmom", $detailTblVar) && $detailPage->DetailAdd && $addRow) {
                $detailPage->_ProjectID->setSessionValue($this->_ProjectID->CurrentValue); // Set master key
                $Security->loadCurrentUserLevel($this->ProjectID . "projectmom"); // Load user level of detail table
                $addRow = $detailPage->gridInsert();
                $Security->loadCurrentUserLevel($this->ProjectID . $this->TableName); // Restore user level of master table
                if (!$addRow) {
                $detailPage->_ProjectID->setSessionValue(""); // Clear master key if insert failed
                }
            }
            $detailPage = Container("ProjectdocumentsGrid");
            if (in_array("projectdocuments", $detailTblVar) && $detailPage->DetailAdd && $addRow) {
                $detailPage->_ProjectID->setSessionValue($this->_ProjectID->CurrentValue); // Set master key
                $Security->loadCurrentUserLevel($this->ProjectID . "projectdocuments"); // Load user level of detail table
                $addRow = $detailPage->gridInsert();
                $Security->loadCurrentUserLevel($this->ProjectID . $this->TableName); // Restore user level of master table
                if (!$addRow) {
                $detailPage->_ProjectID->setSessionValue(""); // Clear master key if insert failed
                }
            }
            $detailPage = Container("ProjectpaymentprocessGrid");
            if (in_array("projectpaymentprocess", $detailTblVar) && $detailPage->DetailAdd && $addRow) {
                $detailPage->_ProjectID->setSessionValue($this->_ProjectID->CurrentValue); // Set master key
                $Security->loadCurrentUserLevel($this->ProjectID . "projectpaymentprocess"); // Load user level of detail table
                $addRow = $detailPage->gridInsert();
                $Security->loadCurrentUserLevel($this->ProjectID . $this->TableName); // Restore user level of master table
                if (!$addRow) {
                $detailPage->_ProjectID->setSessionValue(""); // Clear master key if insert failed
                }
            }
            $detailPage = Container("ProjectproblemsGrid");
            if (in_array("projectproblems", $detailTblVar) && $detailPage->DetailAdd && $addRow) {
                $detailPage->_ProjectID->setSessionValue($this->_ProjectID->CurrentValue); // Set master key
                $Security->loadCurrentUserLevel($this->ProjectID . "projectproblems"); // Load user level of detail table
                $addRow = $detailPage->gridInsert();
                $Security->loadCurrentUserLevel($this->ProjectID . $this->TableName); // Restore user level of master table
                if (!$addRow) {
                $detailPage->_ProjectID->setSessionValue(""); // Clear master key if insert failed
                }
            }
        }

        // Commit/Rollback transaction
        if ($this->getCurrentDetailTable() != "") {
            if ($addRow) {
                if ($this->UseTransaction) { // Commit transaction
                    $conn->commit();
                }
            } else {
                if ($this->UseTransaction) { // Rollback transaction
                    $conn->rollback();
                }
            }
        }
        if ($addRow) {
            // Call Row Inserted event
            $this->rowInserted($rsold, $rsnew);
        }

        // Write JSON response
        if (IsJsonResponse() && $addRow) {
            $row = $this->getRecordsFromRecordset([$rsnew], true);
            $table = $this->TableVar;
            WriteJson(["success" => true, "action" => Config("API_ADD_ACTION"), $table => $row]);
        }
        return $addRow;
    }

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

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

        // PlanStart
        $this->PlanStart->setDbValueDef($rsnew, UnFormatDateTime($this->PlanStart->CurrentValue, $this->PlanStart->formatPattern()), false);

        // PlanEnd
        $this->PlanEnd->setDbValueDef($rsnew, UnFormatDateTime($this->PlanEnd->CurrentValue, $this->PlanEnd->formatPattern()), false);

        // StartDate
        $this->StartDate->setDbValueDef($rsnew, UnFormatDateTime($this->StartDate->CurrentValue, $this->StartDate->formatPattern()), false);

        // EndDate
        $this->EndDate->setDbValueDef($rsnew, UnFormatDateTime($this->EndDate->CurrentValue, $this->EndDate->formatPattern()), false);

        // WarrantyEnd
        $this->WarrantyEnd->setDbValueDef($rsnew, UnFormatDateTime($this->WarrantyEnd->CurrentValue, $this->WarrantyEnd->formatPattern()), false);

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

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

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

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

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

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

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

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

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

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

        // ClearingDate
        $this->ClearingDate->setDbValueDef($rsnew, UnFormatDateTime($this->ClearingDate->CurrentValue, $this->ClearingDate->formatPattern()), false);

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

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

        // Created_Date
        $this->Created_Date->setDbValueDef($rsnew, UnFormatDateTime($this->Created_Date->CurrentValue, $this->Created_Date->formatPattern()), false);

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

        // 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 add form from row
     * @param array $row Row
     */
    protected function restoreAddFormFromRow($row)
    {
        if (isset($row['ProjectName'])) { // ProjectName
            $this->ProjectName->setFormValue($row['ProjectName']);
        }
        if (isset($row['PlanStart'])) { // PlanStart
            $this->PlanStart->setFormValue($row['PlanStart']);
        }
        if (isset($row['PlanEnd'])) { // PlanEnd
            $this->PlanEnd->setFormValue($row['PlanEnd']);
        }
        if (isset($row['StartDate'])) { // StartDate
            $this->StartDate->setFormValue($row['StartDate']);
        }
        if (isset($row['EndDate'])) { // EndDate
            $this->EndDate->setFormValue($row['EndDate']);
        }
        if (isset($row['WarrantyEnd'])) { // WarrantyEnd
            $this->WarrantyEnd->setFormValue($row['WarrantyEnd']);
        }
        if (isset($row['Status'])) { // Status
            $this->Status->setFormValue($row['Status']);
        }
        if (isset($row['ClientID'])) { // ClientID
            $this->ClientID->setFormValue($row['ClientID']);
        }
        if (isset($row['ManagerID'])) { // ManagerID
            $this->ManagerID->setFormValue($row['ManagerID']);
        }
        if (isset($row['ProjectTemplateID'])) { // ProjectTemplateID
            $this->ProjectTemplateID->setFormValue($row['ProjectTemplateID']);
        }
        if (isset($row['Priority'])) { // Priority
            $this->Priority->setFormValue($row['Priority']);
        }
        if (isset($row['Description'])) { // Description
            $this->Description->setFormValue($row['Description']);
        }
        if (isset($row['ProjectValue'])) { // ProjectValue
            $this->ProjectValue->setFormValue($row['ProjectValue']);
        }
        if (isset($row['ProjectDebt'])) { // ProjectDebt
            $this->ProjectDebt->setFormValue($row['ProjectDebt']);
        }
        if (isset($row['PONumber'])) { // PONumber
            $this->PONumber->setFormValue($row['PONumber']);
        }
        if (isset($row['PaymentLink'])) { // PaymentLink
            $this->PaymentLink->setFormValue($row['PaymentLink']);
        }
        if (isset($row['ClearingDate'])) { // ClearingDate
            $this->ClearingDate->setFormValue($row['ClearingDate']);
        }
        if (isset($row['ClearingAging'])) { // ClearingAging
            $this->ClearingAging->setFormValue($row['ClearingAging']);
        }
        if (isset($row['Active'])) { // Active
            $this->Active->setFormValue($row['Active']);
        }
        if (isset($row['Created_Date'])) { // Created_Date
            $this->Created_Date->setFormValue($row['Created_Date']);
        }
        if (isset($row['Created_By'])) { // Created_By
            $this->Created_By->setFormValue($row['Created_By']);
        }
        if (isset($row['Last_Updated_Date'])) { // Last_Updated_Date
            $this->Last_Updated_Date->setFormValue($row['Last_Updated_Date']);
        }
        if (isset($row['Last_Updated_By'])) { // Last_Updated_By
            $this->Last_Updated_By->setFormValue($row['Last_Updated_By']);
        }
    }

    // Set up detail parms based on QueryString
    protected function setupDetailParms()
    {
        // Get the keys for master table
        $detailTblVar = Get(Config("TABLE_SHOW_DETAIL"));
        if ($detailTblVar !== null) {
            $this->setCurrentDetailTable($detailTblVar);
        } else {
            $detailTblVar = $this->getCurrentDetailTable();
        }
        if ($detailTblVar != "") {
            $detailTblVar = explode(",", $detailTblVar);
            if (in_array("projectmember", $detailTblVar)) {
                $detailPageObj = Container("ProjectmemberGrid");
                if ($detailPageObj->DetailAdd) {
                    $detailPageObj->EventCancelled = $this->EventCancelled;
                    if ($this->CopyRecord) {
                        $detailPageObj->CurrentMode = "copy";
                    } else {
                        $detailPageObj->CurrentMode = "add";
                    }
                    $detailPageObj->CurrentAction = "gridadd";

                    // Save current master table to detail table
                    $detailPageObj->setCurrentMasterTable($this->TableVar);
                    $detailPageObj->setStartRecordNumber(1);
                    $detailPageObj->_ProjectID->IsDetailKey = true;
                    $detailPageObj->_ProjectID->CurrentValue = $this->_ProjectID->CurrentValue;
                    $detailPageObj->_ProjectID->setSessionValue($detailPageObj->_ProjectID->CurrentValue);
                }
            }
            if (in_array("projecttask", $detailTblVar)) {
                $detailPageObj = Container("ProjecttaskGrid");
                if ($detailPageObj->DetailAdd) {
                    $detailPageObj->EventCancelled = $this->EventCancelled;
                    if ($this->CopyRecord) {
                        $detailPageObj->CurrentMode = "copy";
                    } else {
                        $detailPageObj->CurrentMode = "add";
                    }
                    $detailPageObj->CurrentAction = "gridadd";

                    // Save current master table to detail table
                    $detailPageObj->setCurrentMasterTable($this->TableVar);
                    $detailPageObj->setStartRecordNumber(1);
                    $detailPageObj->_ProjectID->IsDetailKey = true;
                    $detailPageObj->_ProjectID->CurrentValue = $this->_ProjectID->CurrentValue;
                    $detailPageObj->_ProjectID->setSessionValue($detailPageObj->_ProjectID->CurrentValue);
                }
            }
            if (in_array("projectresult", $detailTblVar)) {
                $detailPageObj = Container("ProjectresultGrid");
                if ($detailPageObj->DetailAdd) {
                    $detailPageObj->EventCancelled = $this->EventCancelled;
                    if ($this->CopyRecord) {
                        $detailPageObj->CurrentMode = "copy";
                    } else {
                        $detailPageObj->CurrentMode = "add";
                    }
                    $detailPageObj->CurrentAction = "gridadd";

                    // Save current master table to detail table
                    $detailPageObj->setCurrentMasterTable($this->TableVar);
                    $detailPageObj->setStartRecordNumber(1);
                    $detailPageObj->_ProjectID->IsDetailKey = true;
                    $detailPageObj->_ProjectID->CurrentValue = $this->_ProjectID->CurrentValue;
                    $detailPageObj->_ProjectID->setSessionValue($detailPageObj->_ProjectID->CurrentValue);
                }
            }
            if (in_array("projectmom", $detailTblVar)) {
                $detailPageObj = Container("ProjectmomGrid");
                if ($detailPageObj->DetailAdd) {
                    $detailPageObj->EventCancelled = $this->EventCancelled;
                    if ($this->CopyRecord) {
                        $detailPageObj->CurrentMode = "copy";
                    } else {
                        $detailPageObj->CurrentMode = "add";
                    }
                    $detailPageObj->CurrentAction = "gridadd";

                    // Save current master table to detail table
                    $detailPageObj->setCurrentMasterTable($this->TableVar);
                    $detailPageObj->setStartRecordNumber(1);
                    $detailPageObj->_ProjectID->IsDetailKey = true;
                    $detailPageObj->_ProjectID->CurrentValue = $this->_ProjectID->CurrentValue;
                    $detailPageObj->_ProjectID->setSessionValue($detailPageObj->_ProjectID->CurrentValue);
                }
            }
            if (in_array("projectdocuments", $detailTblVar)) {
                $detailPageObj = Container("ProjectdocumentsGrid");
                if ($detailPageObj->DetailAdd) {
                    $detailPageObj->EventCancelled = $this->EventCancelled;
                    if ($this->CopyRecord) {
                        $detailPageObj->CurrentMode = "copy";
                    } else {
                        $detailPageObj->CurrentMode = "add";
                    }
                    $detailPageObj->CurrentAction = "gridadd";

                    // Save current master table to detail table
                    $detailPageObj->setCurrentMasterTable($this->TableVar);
                    $detailPageObj->setStartRecordNumber(1);
                    $detailPageObj->_ProjectID->IsDetailKey = true;
                    $detailPageObj->_ProjectID->CurrentValue = $this->_ProjectID->CurrentValue;
                    $detailPageObj->_ProjectID->setSessionValue($detailPageObj->_ProjectID->CurrentValue);
                }
            }
            if (in_array("projectpaymentprocess", $detailTblVar)) {
                $detailPageObj = Container("ProjectpaymentprocessGrid");
                if ($detailPageObj->DetailAdd) {
                    $detailPageObj->EventCancelled = $this->EventCancelled;
                    if ($this->CopyRecord) {
                        $detailPageObj->CurrentMode = "copy";
                    } else {
                        $detailPageObj->CurrentMode = "add";
                    }
                    $detailPageObj->CurrentAction = "gridadd";

                    // Save current master table to detail table
                    $detailPageObj->setCurrentMasterTable($this->TableVar);
                    $detailPageObj->setStartRecordNumber(1);
                    $detailPageObj->_ProjectID->IsDetailKey = true;
                    $detailPageObj->_ProjectID->CurrentValue = $this->_ProjectID->CurrentValue;
                    $detailPageObj->_ProjectID->setSessionValue($detailPageObj->_ProjectID->CurrentValue);
                }
            }
            if (in_array("projectproblems", $detailTblVar)) {
                $detailPageObj = Container("ProjectproblemsGrid");
                if ($detailPageObj->DetailAdd) {
                    $detailPageObj->EventCancelled = $this->EventCancelled;
                    if ($this->CopyRecord) {
                        $detailPageObj->CurrentMode = "copy";
                    } else {
                        $detailPageObj->CurrentMode = "add";
                    }
                    $detailPageObj->CurrentAction = "gridadd";

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

    // 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 = ($this->isCopy()) ? "Copy" : "Add";
        $Breadcrumb->add("add", $pageId, $url);
    }

    // Set up multi pages
    protected function setupMultiPages()
    {
        $pages = new SubPages();
        $pages->Style = "tabs";
        if ($pages->isAccordion()) {
            $pages->Parent = "#accordion_" . $this->PageObjName;
        }
        $pages->add(0);
        $pages->add(1);
        $pages->add(2);
        $pages->add(3);
        $this->MultiPages = $pages;
    }

    // Set up detail pages
    protected function setupDetailPages()
    {
        $pages = new SubPages();
        $pages->Style = "tabs";
        if ($pages->isAccordion()) {
            $pages->Parent = "#accordion_" . $this->PageObjName;
        }
        $pages->add('projectmember');
        $pages->add('projecttask');
        $pages->add('projectresult');
        $pages->add('projectmom');
        $pages->add('projectdocuments');
        $pages->add('projectpaymentprocess');
        $pages->add('projectproblems');
        $this->DetailPages = $pages;
    }

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