<?php
namespace PHPMaker2020\hostelmgr20;

/**
 * Page class
 */
class admission_add extends admission
{

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

	// Project ID
	public $ProjectID = "{9D95FE21-5D89-4075-ACEB-258B1CE35B16}";

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

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

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

	// Token
	public $Token = "";
	public $TokenTimeout = 0;
	public $CheckToken;

	// Page heading
	public function pageHeading()
	{
		global $Language;
		if ($this->Heading != "")
			return $this->Heading;
		if (method_exists($this, "tableCaption"))
			return $this->tableCaption();
		return "";
	}

	// Page subheading
	public function pageSubheading()
	{
		global $Language;
		if ($this->Subheading != "")
			return $this->Subheading;
		if ($this->TableName)
			return $Language->phrase($this->PageID);
		return "";
	}

	// Page name
	public function pageName()
	{
		return CurrentPageName();
	}

	// Page URL
	public function pageUrl()
	{
		$url = CurrentPageName() . "?";
		if ($this->UseTokenInUrl)
			$url .= "t=" . $this->TableVar . "&"; // Add page token
		return $url;
	}

	// Messages
	private $_message = "";
	private $_failureMessage = "";
	private $_successMessage = "";
	private $_warningMessage = "";

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

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

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

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

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

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

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

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

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

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

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

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

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

	// Show message
	public function showMessage()
	{
		$hidden = FALSE;
		$html = "";

		// Message
		$message = $this->getMessage();
		if (method_exists($this, "Message_Showing"))
			$this->Message_Showing($message, "");
		if ($message != "") { // Message in Session, display
			if (!$hidden)
				$message = '<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>' . $message;
			$html .= '<div class="alert alert-info alert-dismissible ew-info"><i class="icon fas fa-info"></i>' . $message . '</div>';
			$_SESSION[SESSION_MESSAGE] = ""; // Clear message in Session
		}

		// Warning message
		$warningMessage = $this->getWarningMessage();
		if (method_exists($this, "Message_Showing"))
			$this->Message_Showing($warningMessage, "warning");
		if ($warningMessage != "") { // Message in Session, display
			if (!$hidden)
				$warningMessage = '<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>' . $warningMessage;
			$html .= '<div class="alert alert-warning alert-dismissible ew-warning"><i class="icon fas fa-exclamation"></i>' . $warningMessage . '</div>';
			$_SESSION[SESSION_WARNING_MESSAGE] = ""; // Clear message in Session
		}

		// Success message
		$successMessage = $this->getSuccessMessage();
		if (method_exists($this, "Message_Showing"))
			$this->Message_Showing($successMessage, "success");
		if ($successMessage != "") { // Message in Session, display
			if (!$hidden)
				$successMessage = '<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>' . $successMessage;
			$html .= '<div class="alert alert-success alert-dismissible ew-success"><i class="icon fas fa-check"></i>' . $successMessage . '</div>';
			$_SESSION[SESSION_SUCCESS_MESSAGE] = ""; // Clear message in Session
		}

		// Failure message
		$errorMessage = $this->getFailureMessage();
		if (method_exists($this, "Message_Showing"))
			$this->Message_Showing($errorMessage, "failure");
		if ($errorMessage != "") { // Message in Session, display
			if (!$hidden)
				$errorMessage = '<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>' . $errorMessage;
			$html .= '<div class="alert alert-danger alert-dismissible ew-error"><i class="icon fas fa-ban"></i>' . $errorMessage . '</div>';
			$_SESSION[SESSION_FAILURE_MESSAGE] = ""; // Clear message in Session
		}
		echo '<div class="ew-message-dialog' . (($hidden) ? ' d-none' : "") . '">' . $html . '</div>';
	}

	// Get message as array
	public function getMessages()
	{
		$ar = [];

		// Message
		$message = $this->getMessage();

		//if (method_exists($this, "Message_Showing"))
		//	$this->Message_Showing($message, "");

		if ($message != "") { // Message in Session, display
			$ar["message"] = $message;
			$_SESSION[SESSION_MESSAGE] = ""; // Clear message in Session
		}

		// Warning message
		$warningMessage = $this->getWarningMessage();

		//if (method_exists($this, "Message_Showing"))
		//	$this->Message_Showing($warningMessage, "warning");

		if ($warningMessage != "") { // Message in Session, display
			$ar["warningMessage"] = $warningMessage;
			$_SESSION[SESSION_WARNING_MESSAGE] = ""; // Clear message in Session
		}

		// Success message
		$successMessage = $this->getSuccessMessage();

		//if (method_exists($this, "Message_Showing"))
		//	$this->Message_Showing($successMessage, "success");

		if ($successMessage != "") { // Message in Session, display
			$ar["successMessage"] = $successMessage;
			$_SESSION[SESSION_SUCCESS_MESSAGE] = ""; // Clear message in Session
		}

		// Failure message
		$failureMessage = $this->getFailureMessage();

		//if (method_exists($this, "Message_Showing"))
		//	$this->Message_Showing($failureMessage, "failure");

		if ($failureMessage != "") { // Message in Session, display
			$ar["failureMessage"] = $failureMessage;
			$_SESSION[SESSION_FAILURE_MESSAGE] = ""; // Clear message in Session
		}
		return $ar;
	}

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

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

	// Validate page request
	protected function isPageRequest()
	{
		global $CurrentForm;
		if ($this->UseTokenInUrl) {
			if ($CurrentForm)
				return ($this->TableVar == $CurrentForm->getValue("t"));
			if (Get("t") !== NULL)
				return ($this->TableVar == Get("t"));
		}
		return TRUE;
	}

	// Valid Post
	protected function validPost()
	{
		if (!$this->CheckToken || !IsPost() || IsApi())
			return TRUE;
		if (Post(Config("TOKEN_NAME")) === NULL)
			return FALSE;
		$fn = Config("CHECK_TOKEN_FUNC");
		if (is_callable($fn))
			return $fn(Post(Config("TOKEN_NAME")), $this->TokenTimeout);
		return FALSE;
	}

	// Create Token
	public function createToken()
	{
		global $CurrentToken;
		$fn = Config("CREATE_TOKEN_FUNC"); // Always create token, required by API file/lookup request
		if ($this->Token == "" && is_callable($fn)) // Create token
			$this->Token = $fn();
		$CurrentToken = $this->Token; // Save to global variable
	}

	// Constructor
	public function __construct()
	{
		global $Language, $DashboardReport;
		global $UserTable;

		// Check token
		$this->CheckToken = Config("CHECK_TOKEN");

		// Initialize
		$GLOBALS["Page"] = &$this;
		$this->TokenTimeout = SessionTimeoutTime();

		// Language object
		if (!isset($Language))
			$Language = new Language();

		// Parent constuctor
		parent::__construct();

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

		// Table object (staff)
		if (!isset($GLOBALS['staff']))
			$GLOBALS['staff'] = new staff();

		// Page ID (for backward compatibility only)
		if (!defined(PROJECT_NAMESPACE . "PAGE_ID"))
			define(PROJECT_NAMESPACE . "PAGE_ID", 'add');

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

		// Start timer
		if (!isset($GLOBALS["DebugTimer"]))
			$GLOBALS["DebugTimer"] = new Timer();

		// Debug message
		LoadDebugMessage();

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

		// User table object (staff)
		$UserTable = $UserTable ?: new staff();
	}

	// Terminate page
	public function terminate($url = "")
	{
		global $ExportFileName, $TempImages, $DashboardReport;

		// Page Unload event
		$this->Page_Unload();

		// Global Page Unloaded event (in userfn*.php)
		Page_Unloaded();

		// Export
		global $admission;
		if ($this->CustomExport && $this->CustomExport == $this->Export && array_key_exists($this->CustomExport, Config("EXPORT_CLASSES"))) {
				$content = ob_get_contents();
			if ($ExportFileName == "")
				$ExportFileName = $this->TableVar;
			$class = PROJECT_NAMESPACE . Config("EXPORT_CLASSES." . $this->CustomExport);
			if (class_exists($class)) {
				$doc = new $class($admission);
				$doc->Text = @$content;
				if ($this->isExport("email"))
					echo $this->exportEmail($doc->Text);
				else
					$doc->export();
				DeleteTempImages(); // Delete temp images
				exit();
			}
		}
		if (!IsApi())
			$this->Page_Redirecting($url);

		// Close connection
		CloseConnections();

		// Return for API
		if (IsApi()) {
			$res = $url === TRUE;
			if (!$res) // Show error
				WriteJson(array_merge(["success" => FALSE], $this->getMessages()));
			return;
		}

		// Go to URL if specified
		if ($url != "") {
			if (!Config("DEBUG") && ob_get_length())
				ob_end_clean();

			// Handle modal response
			if ($this->IsModal) { // Show as modal
				$row = ["url" => $url, "modal" => "1"];
				$pageName = GetPageName($url);
				if ($pageName != $this->getListUrl()) { // Not List page
					$row["caption"] = $this->getModalCaption($pageName);
					if ($pageName == "admissionview.php")
						$row["view"] = "1";
				} else { // List page should not be shown as modal => error
					$row["error"] = $this->getFailureMessage();
					$this->clearFailureMessage();
				}
				WriteJson($row);
			} else {
				SaveDebugMessage();
				AddHeader("Location", $url);
			}
		}
		exit();
	}

	// Get records from recordset
	protected function getRecordsFromRecordset($rs, $current = FALSE)
	{
		$rows = [];
		if (is_object($rs)) { // Recordset
			while ($rs && !$rs->EOF) {
				$this->loadRowValues($rs); // Set up DbValue/CurrentValue
				$row = $this->getRecordFromArray($rs->fields);
				if ($current)
					return $row;
				else
					$rows[] = $row;
				$rs->moveNext();
			}
		} elseif (is_array($rs)) {
			foreach ($rs as $ar) {
				$row = $this->getRecordFromArray($ar);
				if ($current)
					return $row;
				else
					$rows[] = $row;
			}
		}
		return $rows;
	}

	// Get record from array
	protected function getRecordFromArray($ar)
	{
		$row = [];
		if (is_array($ar)) {
			foreach ($ar as $fldname => $val) {
				if (array_key_exists($fldname, $this->fields) && ($this->fields[$fldname]->Visible || $this->fields[$fldname]->IsPrimaryKey)) { // Primary key or Visible
					$fld = &$this->fields[$fldname];
					if ($fld->HtmlTag == "FILE") { // Upload field
						if (EmptyValue($val)) {
							$row[$fldname] = NULL;
						} else {
							if ($fld->DataType == DATATYPE_BLOB) {
								$url = FullUrl(GetApiUrl(Config("API_FILE_ACTION"),
									Config("API_OBJECT_NAME") . "=" . $fld->TableVar . "&" .
									Config("API_FIELD_NAME") . "=" . $fld->Param . "&" .
									Config("API_KEY_NAME") . "=" . rawurlencode($this->getRecordKeyValue($ar)))); //*** need to add this? API may not be in the same folder
								$row[$fldname] = ["mimeType" => ContentType($val), "url" => $url];
							} elseif (!$fld->UploadMultiple || !ContainsString($val, Config("MULTIPLE_UPLOAD_SEPARATOR"))) { // Single file
								$row[$fldname] = ["mimeType" => MimeContentType($val), "url" => FullUrl($fld->hrefPath() . $val)];
							} else { // Multiple files
								$files = explode(Config("MULTIPLE_UPLOAD_SEPARATOR"), $val);
								$ar = [];
								foreach ($files as $file) {
									if (!EmptyValue($file))
										$ar[] = ["type" => MimeContentType($file), "url" => FullUrl($fld->hrefPath() . $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['id'];
		}
		return $key;
	}

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

	// Lookup data
	public function lookup()
	{
		global $Language, $Security;
		if (!isset($Language))
			$Language = new Language(Config("LANGUAGE_FOLDER"), Post("language", ""));

		// Set up API request
		if (!$this->setupApiRequest())
			return FALSE;

		// Get lookup object
		$fieldName = Post("field");
		if (!array_key_exists($fieldName, $this->fields))
			return FALSE;
		$lookupField = $this->fields[$fieldName];
		$lookup = $lookupField->Lookup;
		if ($lookup === NULL)
			return FALSE;
		$tbl = $lookup->getTable();
		if (!$Security->allowLookup(Config("PROJECT_ID") . $tbl->TableName)) // Lookup permission
			return FALSE;

		// Get lookup parameters
		$lookupType = Post("ajax", "unknown");
		$pageSize = -1;
		$offset = -1;
		$searchValue = "";
		if (SameText($lookupType, "modal")) {
			$searchValue = Post("sv", "");
			$pageSize = Post("recperpage", 10);
			$offset = Post("start", 0);
		} elseif (SameText($lookupType, "autosuggest")) {
			$searchValue = Get("q", "");
			$pageSize = Param("n", -1);
			$pageSize = is_numeric($pageSize) ? (int)$pageSize : -1;
			if ($pageSize <= 0)
				$pageSize = Config("AUTO_SUGGEST_MAX_ENTRIES");
			$start = Param("start", -1);
			$start = is_numeric($start) ? (int)$start : -1;
			$page = Param("page", -1);
			$page = is_numeric($page) ? (int)$page : -1;
			$offset = $start >= 0 ? $start : ($page > 0 && $pageSize > 0 ? ($page - 1) * $pageSize : 0);
		}
		$userSelect = Decrypt(Post("s", ""));
		$userFilter = Decrypt(Post("f", ""));
		$userOrderBy = Decrypt(Post("o", ""));
		$keys = Post("keys");
		$lookup->LookupType = $lookupType; // Lookup type
		if ($keys !== NULL) { // Selected records from modal
			if (is_array($keys))
				$keys = implode(Config("MULTIPLE_OPTION_SEPARATOR"), $keys);
			$lookup->FilterFields = []; // Skip parent fields if any
			$lookup->FilterValues[] = $keys; // Lookup values
			$pageSize = -1; // Show all records
		} else { // Lookup values
			$lookup->FilterValues[] = Post("v0", Post("lookupValue", ""));
		}
		$cnt = is_array($lookup->FilterFields) ? count($lookup->FilterFields) : 0;
		for ($i = 1; $i <= $cnt; $i++)
			$lookup->FilterValues[] = Post("v" . $i, "");
		$lookup->SearchValue = $searchValue;
		$lookup->PageSize = $pageSize;
		$lookup->Offset = $offset;
		if ($userSelect != "")
			$lookup->UserSelect = $userSelect;
		if ($userFilter != "")
			$lookup->UserFilter = $userFilter;
		if ($userOrderBy != "")
			$lookup->UserOrderBy = $userOrderBy;
		$lookup->toJson($this); // Use settings from current page
	}

	// Set up API request
	public function setupApiRequest()
	{
		global $Security;

		// Check security for API request
		If (ValidApiRequest()) {
			if ($Security->isLoggedIn()) $Security->TablePermission_Loading();
			$Security->loadCurrentUserLevel(Config("PROJECT_ID") . $this->TableName);
			if ($Security->isLoggedIn()) $Security->TablePermission_Loaded();
			return TRUE;
		}
		return FALSE;
	}
	public $FormClassName = "ew-horizontal ew-form ew-add-form";
	public $IsModal = FALSE;
	public $IsMobileOrModal = FALSE;
	public $DbMasterFilter = "";
	public $DbDetailFilter = "";
	public $StartRecord;
	public $Priv = 0;
	public $OldRecordset;
	public $CopyRecord;

	//
	// Page run
	//

	public function run()
	{
		global $ExportType, $CustomExportType, $ExportFileName, $UserProfile, $Language, $Security, $CurrentForm,
			$FormError, $SkipHeaderFooter;

		// Is modal
		$this->IsModal = (Param("modal") == "1");

		// User profile
		$UserProfile = new UserProfile();

		// Security
		if (!$this->setupApiRequest()) {
			$Security = new AdvancedSecurity();
			if (!$Security->isLoggedIn())
				$Security->autoLogin();
			if ($Security->isLoggedIn())
				$Security->TablePermission_Loading();
			$Security->loadCurrentUserLevel($this->ProjectID . $this->TableName);
			if ($Security->isLoggedIn())
				$Security->TablePermission_Loaded();
			if (!$Security->canAdd()) {
				$Security->saveLastUrl();
				$this->setFailureMessage(DeniedMessage()); // Set no permission
				if ($Security->canList())
					$this->terminate(GetUrl("admissionlist.php"));
				else
					$this->terminate(GetUrl("login.php"));
				return;
			}
		}

		// Create form object
		$CurrentForm = new HttpForm();
		$this->CurrentAction = Param("action"); // Set up current action
		$this->id->Visible = FALSE;
		$this->AdmDate->setVisibility();
		$this->HostelID->setVisibility();
		$this->RollNo->setVisibility();
		$this->Name->setVisibility();
		$this->Hostel->setVisibility();
		$this->Floor->setVisibility();
		$this->RoomNo->setVisibility();
		$this->Bed->setVisibility();
		$this->AdmYear->setVisibility();
		$this->Academic->setVisibility();
		$this->Updatedby->setVisibility();
		$this->Updated_Date->setVisibility();
		$this->Status->setVisibility();
		$this->hideFieldsForAddEdit();

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

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

		// Page Load event
		$this->Page_Load();

		// Check token
		if (!$this->validPost()) {
			Write($Language->phrase("InvalidPostRequest"));
			$this->terminate();
		}

		// Create Token
		$this->createToken();

		// Set up lookup cache
		$this->setupLookupOptions($this->Hostel);
		$this->setupLookupOptions($this->Floor);
		$this->setupLookupOptions($this->RoomNo);
		$this->setupLookupOptions($this->Academic);

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

		// Set up current action
		if (IsApi()) {
			$this->CurrentAction = "insert"; // Add record directly
			$postBack = TRUE;
		} elseif (Post("action") !== NULL) {
			$this->CurrentAction = Post("action"); // Get form action
			$postBack = TRUE;
		} else { // Not post back

			// Load key values from QueryString
			$this->CopyRecord = TRUE;
			if (Get("id") !== NULL) {
				$this->id->setQueryStringValue(Get("id"));
				$this->setKey("id", $this->id->CurrentValue); // Set up key
			} else {
				$this->setKey("id", ""); // Clear key
				$this->CopyRecord = FALSE;
			}
			if ($this->CopyRecord) {
				$this->CurrentAction = "copy"; // Copy record
			} else {
				$this->CurrentAction = "show"; // Display blank record
			}
		}

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

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

		// 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
				$this->setFailureMessage($FormError);
				if (IsApi()) {
					$this->terminate();
					return;
				} else {
					$this->CurrentAction = "show"; // Form error, reset action
				}
			}
		}

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

				// Set up detail parameters
				$this->setupDetailParms();
				break;
			case "insert": // Add new record
				$this->SendEmail = TRUE; // Send email on add success
				if ($this->addRow($this->OldRecordset)) { // Add successful
					if ($this->getSuccessMessage() == "")
						$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) == "admissionlist.php")
						$returnUrl = $this->addMasterUrl($returnUrl); // List page, return to List page with correct master key if necessary
					elseif (GetPageName($returnUrl) == "admissionview.php")
						$returnUrl = $this->getViewUrl(); // View page, return to View page with keyurl directly
					if (IsApi()) { // Return to caller
						$this->terminate(TRUE);
						return;
					} else {
						$this->terminate($returnUrl);
					}
				} elseif (IsApi()) { // API request, return
					$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();
	}

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

	// Load default values
	protected function loadDefaultValues()
	{
		$this->id->CurrentValue = NULL;
		$this->id->OldValue = $this->id->CurrentValue;
		$this->AdmDate->CurrentValue = CurrentDate();
		$this->HostelID->CurrentValue = NULL;
		$this->HostelID->OldValue = $this->HostelID->CurrentValue;
		$this->RollNo->CurrentValue = NULL;
		$this->RollNo->OldValue = $this->RollNo->CurrentValue;
		$this->Name->CurrentValue = NULL;
		$this->Name->OldValue = $this->Name->CurrentValue;
		$this->Hostel->CurrentValue = NULL;
		$this->Hostel->OldValue = $this->Hostel->CurrentValue;
		$this->Floor->CurrentValue = NULL;
		$this->Floor->OldValue = $this->Floor->CurrentValue;
		$this->RoomNo->CurrentValue = NULL;
		$this->RoomNo->OldValue = $this->RoomNo->CurrentValue;
		$this->Bed->CurrentValue = NULL;
		$this->Bed->OldValue = $this->Bed->CurrentValue;
		$this->AdmYear->CurrentValue = NULL;
		$this->AdmYear->OldValue = $this->AdmYear->CurrentValue;
		$this->Academic->CurrentValue = NULL;
		$this->Academic->OldValue = $this->Academic->CurrentValue;
		$this->Updatedby->CurrentValue = NULL;
		$this->Updatedby->OldValue = $this->Updatedby->CurrentValue;
		$this->Updated_Date->CurrentValue = NULL;
		$this->Updated_Date->OldValue = $this->Updated_Date->CurrentValue;
		$this->Status->CurrentValue = 1;
	}

	// Load form values
	protected function loadFormValues()
	{

		// Load from form
		global $CurrentForm;

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

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

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

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

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

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

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

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

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

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

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

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

		// 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 'id' first before field var 'x_id'
		$val = $CurrentForm->hasValue("id") ? $CurrentForm->getValue("id") : $CurrentForm->getValue("x_id");
	}

	// Restore form values
	public function restoreFormValues()
	{
		global $CurrentForm;
		$this->AdmDate->CurrentValue = $this->AdmDate->FormValue;
		$this->AdmDate->CurrentValue = UnFormatDateTime($this->AdmDate->CurrentValue, 0);
		$this->HostelID->CurrentValue = $this->HostelID->FormValue;
		$this->RollNo->CurrentValue = $this->RollNo->FormValue;
		$this->Name->CurrentValue = $this->Name->FormValue;
		$this->Hostel->CurrentValue = $this->Hostel->FormValue;
		$this->Floor->CurrentValue = $this->Floor->FormValue;
		$this->RoomNo->CurrentValue = $this->RoomNo->FormValue;
		$this->Bed->CurrentValue = $this->Bed->FormValue;
		$this->AdmYear->CurrentValue = $this->AdmYear->FormValue;
		$this->Academic->CurrentValue = $this->Academic->FormValue;
		$this->Updatedby->CurrentValue = $this->Updatedby->FormValue;
		$this->Updated_Date->CurrentValue = $this->Updated_Date->FormValue;
		$this->Updated_Date->CurrentValue = UnFormatDateTime($this->Updated_Date->CurrentValue, 0);
		$this->Status->CurrentValue = $this->Status->FormValue;
	}

	// Load row based on key values
	public function loadRow()
	{
		global $Security, $Language;
		$filter = $this->getRecordFilter();

		// Call Row Selecting event
		$this->Row_Selecting($filter);

		// Load SQL based on filter
		$this->CurrentFilter = $filter;
		$sql = $this->getCurrentSql();
		$conn = $this->getConnection();
		$res = FALSE;
		$rs = LoadRecordset($sql, $conn);
		if ($rs && !$rs->EOF) {
			$res = TRUE;
			$this->loadRowValues($rs); // Load row values
			$rs->close();
		}
		return $res;
	}

	// Load row values from recordset
	public function loadRowValues($rs = NULL)
	{
		if ($rs && !$rs->EOF)
			$row = $rs->fields;
		else
			$row = $this->newRow();

		// Call Row Selected event
		$this->Row_Selected($row);
		if (!$rs || $rs->EOF)
			return;
		$this->id->setDbValue($row['id']);
		$this->AdmDate->setDbValue($row['AdmDate']);
		$this->HostelID->setDbValue($row['HostelID']);
		$this->RollNo->setDbValue($row['RollNo']);
		$this->Name->setDbValue($row['Name']);
		$this->Hostel->setDbValue($row['Hostel']);
		$this->Floor->setDbValue($row['Floor']);
		$this->RoomNo->setDbValue($row['RoomNo']);
		$this->Bed->setDbValue($row['Bed']);
		$this->AdmYear->setDbValue($row['AdmYear']);
		$this->Academic->setDbValue($row['Academic']);
		$this->Updatedby->setDbValue($row['Updatedby']);
		$this->Updated_Date->setDbValue($row['Updated_Date']);
		$this->Status->setDbValue($row['Status']);
	}

	// Return a row with default values
	protected function newRow()
	{
		$this->loadDefaultValues();
		$row = [];
		$row['id'] = $this->id->CurrentValue;
		$row['AdmDate'] = $this->AdmDate->CurrentValue;
		$row['HostelID'] = $this->HostelID->CurrentValue;
		$row['RollNo'] = $this->RollNo->CurrentValue;
		$row['Name'] = $this->Name->CurrentValue;
		$row['Hostel'] = $this->Hostel->CurrentValue;
		$row['Floor'] = $this->Floor->CurrentValue;
		$row['RoomNo'] = $this->RoomNo->CurrentValue;
		$row['Bed'] = $this->Bed->CurrentValue;
		$row['AdmYear'] = $this->AdmYear->CurrentValue;
		$row['Academic'] = $this->Academic->CurrentValue;
		$row['Updatedby'] = $this->Updatedby->CurrentValue;
		$row['Updated_Date'] = $this->Updated_Date->CurrentValue;
		$row['Status'] = $this->Status->CurrentValue;
		return $row;
	}

	// Load old record
	protected function loadOldRecord()
	{

		// Load key values from Session
		$validKey = TRUE;
		if (strval($this->getKey("id")) != "")
			$this->id->OldValue = $this->getKey("id"); // id
		else
			$validKey = FALSE;

		// Load old record
		$this->OldRecordset = NULL;
		if ($validKey) {
			$this->CurrentFilter = $this->getRecordFilter();
			$sql = $this->getCurrentSql();
			$conn = $this->getConnection();
			$this->OldRecordset = LoadRecordset($sql, $conn);
		}
		$this->loadRowValues($this->OldRecordset); // Load row values
		return $validKey;
	}

	// Render row values based on field settings
	public function renderRow()
	{
		global $Security, $Language, $CurrentLanguage;

		// Initialize URLs
		// Call Row_Rendering event

		$this->Row_Rendering();

		// Common render codes for all row types
		// id
		// AdmDate
		// HostelID
		// RollNo
		// Name
		// Hostel
		// Floor
		// RoomNo
		// Bed
		// AdmYear
		// Academic
		// Updatedby
		// Updated_Date
		// Status

		if ($this->RowType == ROWTYPE_VIEW) { // View row

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

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

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

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

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

			// Hostel
			$curVal = strval($this->Hostel->CurrentValue);
			if ($curVal != "") {
				$this->Hostel->ViewValue = $this->Hostel->lookupCacheOption($curVal);
				if ($this->Hostel->ViewValue === NULL) { // Lookup from database
					$filterWrk = "`id`" . SearchString("=", $curVal, DATATYPE_NUMBER, "");
					$sqlWrk = $this->Hostel->Lookup->getSql(FALSE, $filterWrk, '', $this);
					$rswrk = Conn()->execute($sqlWrk);
					if ($rswrk && !$rswrk->EOF) { // Lookup values found
						$arwrk = [];
						$arwrk[1] = $rswrk->fields('df');
						$this->Hostel->ViewValue = $this->Hostel->displayValue($arwrk);
						$rswrk->Close();
					} else {
						$this->Hostel->ViewValue = $this->Hostel->CurrentValue;
					}
				}
			} else {
				$this->Hostel->ViewValue = NULL;
			}
			$this->Hostel->ViewCustomAttributes = "";

			// Floor
			$curVal = strval($this->Floor->CurrentValue);
			if ($curVal != "") {
				$this->Floor->ViewValue = $this->Floor->lookupCacheOption($curVal);
				if ($this->Floor->ViewValue === NULL) { // Lookup from database
					$filterWrk = "`id`" . SearchString("=", $curVal, DATATYPE_NUMBER, "");
					$sqlWrk = $this->Floor->Lookup->getSql(FALSE, $filterWrk, '', $this);
					$rswrk = Conn()->execute($sqlWrk);
					if ($rswrk && !$rswrk->EOF) { // Lookup values found
						$arwrk = [];
						$arwrk[1] = $rswrk->fields('df');
						$this->Floor->ViewValue = $this->Floor->displayValue($arwrk);
						$rswrk->Close();
					} else {
						$this->Floor->ViewValue = $this->Floor->CurrentValue;
					}
				}
			} else {
				$this->Floor->ViewValue = NULL;
			}
			$this->Floor->ViewCustomAttributes = "";

			// RoomNo
			$curVal = strval($this->RoomNo->CurrentValue);
			if ($curVal != "") {
				$this->RoomNo->ViewValue = $this->RoomNo->lookupCacheOption($curVal);
				if ($this->RoomNo->ViewValue === NULL) { // Lookup from database
					$filterWrk = "`Room_No`" . SearchString("=", $curVal, DATATYPE_NUMBER, "");
					$sqlWrk = $this->RoomNo->Lookup->getSql(FALSE, $filterWrk, '', $this);
					$rswrk = Conn()->execute($sqlWrk);
					if ($rswrk && !$rswrk->EOF) { // Lookup values found
						$arwrk = [];
						$arwrk[1] = FormatNumber($rswrk->fields('df'), 0, -2, -2, -2);
						$this->RoomNo->ViewValue = $this->RoomNo->displayValue($arwrk);
						$rswrk->Close();
					} else {
						$this->RoomNo->ViewValue = $this->RoomNo->CurrentValue;
					}
				}
			} else {
				$this->RoomNo->ViewValue = NULL;
			}
			$this->RoomNo->ViewCustomAttributes = "";

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

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

			// Academic
			$curVal = strval($this->Academic->CurrentValue);
			if ($curVal != "") {
				$this->Academic->ViewValue = $this->Academic->lookupCacheOption($curVal);
				if ($this->Academic->ViewValue === NULL) { // Lookup from database
					$filterWrk = "`id`" . SearchString("=", $curVal, DATATYPE_NUMBER, "");
					$lookupFilter = function() {
						return "`Status`=1";
					};
					$lookupFilter = $lookupFilter->bindTo($this);
					$sqlWrk = $this->Academic->Lookup->getSql(FALSE, $filterWrk, $lookupFilter, $this);
					$rswrk = Conn()->execute($sqlWrk);
					if ($rswrk && !$rswrk->EOF) { // Lookup values found
						$arwrk = [];
						$arwrk[1] = $rswrk->fields('df');
						$this->Academic->ViewValue = $this->Academic->displayValue($arwrk);
						$rswrk->Close();
					} else {
						$this->Academic->ViewValue = $this->Academic->CurrentValue;
					}
				}
			} else {
				$this->Academic->ViewValue = NULL;
			}
			$this->Academic->ViewCustomAttributes = "";

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

			// Status
			$this->Status->LinkCustomAttributes = "";
			$this->Status->HrefValue = "";
			$this->Status->TooltipValue = "";
		} elseif ($this->RowType == ROWTYPE_ADD) { // Add row

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

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

			// RollNo
			$this->RollNo->EditAttrs["class"] = "form-control";
			$this->RollNo->EditCustomAttributes = "";
			if (!$this->RollNo->Raw)
				$this->RollNo->CurrentValue = HtmlDecode($this->RollNo->CurrentValue);
			$this->RollNo->EditValue = HtmlEncode($this->RollNo->CurrentValue);
			$this->RollNo->PlaceHolder = RemoveHtml($this->RollNo->caption());

			// Name
			$this->Name->EditAttrs["class"] = "form-control";
			$this->Name->EditCustomAttributes = "";
			if (!$this->Name->Raw)
				$this->Name->CurrentValue = HtmlDecode($this->Name->CurrentValue);
			$this->Name->EditValue = HtmlEncode($this->Name->CurrentValue);
			$this->Name->PlaceHolder = RemoveHtml($this->Name->caption());

			// Hostel
			$this->Hostel->EditAttrs["class"] = "form-control";
			$this->Hostel->EditCustomAttributes = "";
			$curVal = trim(strval($this->Hostel->CurrentValue));
			if ($curVal != "")
				$this->Hostel->ViewValue = $this->Hostel->lookupCacheOption($curVal);
			else
				$this->Hostel->ViewValue = $this->Hostel->Lookup !== NULL && is_array($this->Hostel->Lookup->Options) ? $curVal : NULL;
			if ($this->Hostel->ViewValue !== NULL) { // Load from cache
				$this->Hostel->EditValue = array_values($this->Hostel->Lookup->Options);
			} else { // Lookup from database
				if ($curVal == "") {
					$filterWrk = "0=1";
				} else {
					$filterWrk = "`id`" . SearchString("=", $this->Hostel->CurrentValue, DATATYPE_NUMBER, "");
				}
				$sqlWrk = $this->Hostel->Lookup->getSql(TRUE, $filterWrk, '', $this);
				$rswrk = Conn()->execute($sqlWrk);
				$arwrk = $rswrk ? $rswrk->getRows() : [];
				if ($rswrk)
					$rswrk->close();
				$this->Hostel->EditValue = $arwrk;
			}

			// Floor
			$this->Floor->EditAttrs["class"] = "form-control";
			$this->Floor->EditCustomAttributes = "";
			$curVal = trim(strval($this->Floor->CurrentValue));
			if ($curVal != "")
				$this->Floor->ViewValue = $this->Floor->lookupCacheOption($curVal);
			else
				$this->Floor->ViewValue = $this->Floor->Lookup !== NULL && is_array($this->Floor->Lookup->Options) ? $curVal : NULL;
			if ($this->Floor->ViewValue !== NULL) { // Load from cache
				$this->Floor->EditValue = array_values($this->Floor->Lookup->Options);
			} else { // Lookup from database
				if ($curVal == "") {
					$filterWrk = "0=1";
				} else {
					$filterWrk = "`id`" . SearchString("=", $this->Floor->CurrentValue, DATATYPE_NUMBER, "");
				}
				$sqlWrk = $this->Floor->Lookup->getSql(TRUE, $filterWrk, '', $this);
				$rswrk = Conn()->execute($sqlWrk);
				$arwrk = $rswrk ? $rswrk->getRows() : [];
				if ($rswrk)
					$rswrk->close();
				$this->Floor->EditValue = $arwrk;
			}

			// RoomNo
			$this->RoomNo->EditAttrs["class"] = "form-control";
			$this->RoomNo->EditCustomAttributes = "";
			$curVal = trim(strval($this->RoomNo->CurrentValue));
			if ($curVal != "")
				$this->RoomNo->ViewValue = $this->RoomNo->lookupCacheOption($curVal);
			else
				$this->RoomNo->ViewValue = $this->RoomNo->Lookup !== NULL && is_array($this->RoomNo->Lookup->Options) ? $curVal : NULL;
			if ($this->RoomNo->ViewValue !== NULL) { // Load from cache
				$this->RoomNo->EditValue = array_values($this->RoomNo->Lookup->Options);
			} else { // Lookup from database
				if ($curVal == "") {
					$filterWrk = "0=1";
				} else {
					$filterWrk = "`Room_No`" . SearchString("=", $this->RoomNo->CurrentValue, DATATYPE_NUMBER, "");
				}
				$sqlWrk = $this->RoomNo->Lookup->getSql(TRUE, $filterWrk, '', $this);
				$rswrk = Conn()->execute($sqlWrk);
				$arwrk = $rswrk ? $rswrk->getRows() : [];
				if ($rswrk)
					$rswrk->close();
				$rowcnt = count($arwrk);
				for ($i = 0; $i < $rowcnt; $i++) {
					$arwrk[$i][1] = FormatNumber($arwrk[$i][1], 0, -2, -2, -2);
				}
				$this->RoomNo->EditValue = $arwrk;
			}

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

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

			// Academic
			$this->Academic->EditAttrs["class"] = "form-control";
			$this->Academic->EditCustomAttributes = "";
			$curVal = trim(strval($this->Academic->CurrentValue));
			if ($curVal != "")
				$this->Academic->ViewValue = $this->Academic->lookupCacheOption($curVal);
			else
				$this->Academic->ViewValue = $this->Academic->Lookup !== NULL && is_array($this->Academic->Lookup->Options) ? $curVal : NULL;
			if ($this->Academic->ViewValue !== NULL) { // Load from cache
				$this->Academic->EditValue = array_values($this->Academic->Lookup->Options);
			} else { // Lookup from database
				if ($curVal == "") {
					$filterWrk = "0=1";
				} else {
					$filterWrk = "`id`" . SearchString("=", $this->Academic->CurrentValue, DATATYPE_NUMBER, "");
				}
				$lookupFilter = function() {
					return "`Status`=1";
				};
				$lookupFilter = $lookupFilter->bindTo($this);
				$sqlWrk = $this->Academic->Lookup->getSql(TRUE, $filterWrk, $lookupFilter, $this);
				$rswrk = Conn()->execute($sqlWrk);
				$arwrk = $rswrk ? $rswrk->getRows() : [];
				if ($rswrk)
					$rswrk->close();
				$this->Academic->EditValue = $arwrk;
			}

			// Updatedby
			// Updated_Date
			// Status

			$this->Status->EditAttrs["class"] = "form-control";
			$this->Status->EditCustomAttributes = "";
			$this->Status->EditValue = $this->Status->options(TRUE);

			// Add refer script
			// AdmDate

			$this->AdmDate->LinkCustomAttributes = "";
			$this->AdmDate->HrefValue = "";

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

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

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

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

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

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

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

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

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

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

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

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

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

		// Initialize form error message
		$FormError = "";

		// Check if validation required
		if (!Config("SERVER_VALIDATE"))
			return ($FormError == "");
		if ($this->AdmDate->Required) {
			if (!$this->AdmDate->IsDetailKey && $this->AdmDate->FormValue != NULL && $this->AdmDate->FormValue == "") {
				AddMessage($FormError, str_replace("%s", $this->AdmDate->caption(), $this->AdmDate->RequiredErrorMessage));
			}
		}
		if (!CheckDate($this->AdmDate->FormValue)) {
			AddMessage($FormError, $this->AdmDate->errorMessage());
		}
		if ($this->HostelID->Required) {
			if (!$this->HostelID->IsDetailKey && $this->HostelID->FormValue != NULL && $this->HostelID->FormValue == "") {
				AddMessage($FormError, str_replace("%s", $this->HostelID->caption(), $this->HostelID->RequiredErrorMessage));
			}
		}
		if (!CheckInteger($this->HostelID->FormValue)) {
			AddMessage($FormError, $this->HostelID->errorMessage());
		}
		if ($this->RollNo->Required) {
			if (!$this->RollNo->IsDetailKey && $this->RollNo->FormValue != NULL && $this->RollNo->FormValue == "") {
				AddMessage($FormError, str_replace("%s", $this->RollNo->caption(), $this->RollNo->RequiredErrorMessage));
			}
		}
		if ($this->Name->Required) {
			if (!$this->Name->IsDetailKey && $this->Name->FormValue != NULL && $this->Name->FormValue == "") {
				AddMessage($FormError, str_replace("%s", $this->Name->caption(), $this->Name->RequiredErrorMessage));
			}
		}
		if ($this->Hostel->Required) {
			if (!$this->Hostel->IsDetailKey && $this->Hostel->FormValue != NULL && $this->Hostel->FormValue == "") {
				AddMessage($FormError, str_replace("%s", $this->Hostel->caption(), $this->Hostel->RequiredErrorMessage));
			}
		}
		if ($this->Floor->Required) {
			if (!$this->Floor->IsDetailKey && $this->Floor->FormValue != NULL && $this->Floor->FormValue == "") {
				AddMessage($FormError, str_replace("%s", $this->Floor->caption(), $this->Floor->RequiredErrorMessage));
			}
		}
		if ($this->RoomNo->Required) {
			if (!$this->RoomNo->IsDetailKey && $this->RoomNo->FormValue != NULL && $this->RoomNo->FormValue == "") {
				AddMessage($FormError, str_replace("%s", $this->RoomNo->caption(), $this->RoomNo->RequiredErrorMessage));
			}
		}
		if ($this->Bed->Required) {
			if (!$this->Bed->IsDetailKey && $this->Bed->FormValue != NULL && $this->Bed->FormValue == "") {
				AddMessage($FormError, str_replace("%s", $this->Bed->caption(), $this->Bed->RequiredErrorMessage));
			}
		}
		if (!CheckInteger($this->Bed->FormValue)) {
			AddMessage($FormError, $this->Bed->errorMessage());
		}
		if ($this->AdmYear->Required) {
			if (!$this->AdmYear->IsDetailKey && $this->AdmYear->FormValue != NULL && $this->AdmYear->FormValue == "") {
				AddMessage($FormError, str_replace("%s", $this->AdmYear->caption(), $this->AdmYear->RequiredErrorMessage));
			}
		}
		if (!CheckInteger($this->AdmYear->FormValue)) {
			AddMessage($FormError, $this->AdmYear->errorMessage());
		}
		if ($this->Academic->Required) {
			if (!$this->Academic->IsDetailKey && $this->Academic->FormValue != NULL && $this->Academic->FormValue == "") {
				AddMessage($FormError, str_replace("%s", $this->Academic->caption(), $this->Academic->RequiredErrorMessage));
			}
		}
		if ($this->Updatedby->Required) {
			if (!$this->Updatedby->IsDetailKey && $this->Updatedby->FormValue != NULL && $this->Updatedby->FormValue == "") {
				AddMessage($FormError, str_replace("%s", $this->Updatedby->caption(), $this->Updatedby->RequiredErrorMessage));
			}
		}
		if ($this->Updated_Date->Required) {
			if (!$this->Updated_Date->IsDetailKey && $this->Updated_Date->FormValue != NULL && $this->Updated_Date->FormValue == "") {
				AddMessage($FormError, str_replace("%s", $this->Updated_Date->caption(), $this->Updated_Date->RequiredErrorMessage));
			}
		}
		if ($this->Status->Required) {
			if (!$this->Status->IsDetailKey && $this->Status->FormValue != NULL && $this->Status->FormValue == "") {
				AddMessage($FormError, str_replace("%s", $this->Status->caption(), $this->Status->RequiredErrorMessage));
			}
		}

		// Validate detail grid
		$detailTblVar = explode(",", $this->getCurrentDetailTable());
		if (in_array("activity", $detailTblVar) && $GLOBALS["activity"]->DetailAdd) {
			if (!isset($GLOBALS["activity_grid"]))
				$GLOBALS["activity_grid"] = new activity_grid(); // Get detail page object
			$GLOBALS["activity_grid"]->validateGridForm();
		}

		// Return validate result
		$validateForm = ($FormError == "");

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

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

		// Begin transaction
		if ($this->getCurrentDetailTable() != "")
			$conn->beginTrans();

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

		// AdmDate
		$this->AdmDate->setDbValueDef($rsnew, UnFormatDateTime($this->AdmDate->CurrentValue, 0), CurrentDate(), FALSE);

		// HostelID
		$this->HostelID->setDbValueDef($rsnew, $this->HostelID->CurrentValue, 0, FALSE);

		// RollNo
		$this->RollNo->setDbValueDef($rsnew, $this->RollNo->CurrentValue, "", FALSE);

		// Name
		$this->Name->setDbValueDef($rsnew, $this->Name->CurrentValue, "", FALSE);

		// Hostel
		$this->Hostel->setDbValueDef($rsnew, $this->Hostel->CurrentValue, 0, FALSE);

		// Floor
		$this->Floor->setDbValueDef($rsnew, $this->Floor->CurrentValue, 0, FALSE);

		// RoomNo
		$this->RoomNo->setDbValueDef($rsnew, $this->RoomNo->CurrentValue, 0, FALSE);

		// Bed
		$this->Bed->setDbValueDef($rsnew, $this->Bed->CurrentValue, 0, FALSE);

		// AdmYear
		$this->AdmYear->setDbValueDef($rsnew, $this->AdmYear->CurrentValue, 0, FALSE);

		// Academic
		$this->Academic->setDbValueDef($rsnew, $this->Academic->CurrentValue, 0, FALSE);

		// Updatedby
		$this->Updatedby->setDbValueDef($rsnew, CurrentUserName(), "");
		$rsnew['Updatedby'] = &$this->Updatedby->DbValue;

		// Updated_Date
		$this->Updated_Date->setDbValueDef($rsnew, CurrentDateTime(), CurrentDate());
		$rsnew['Updated_Date'] = &$this->Updated_Date->DbValue;

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

		// Call Row Inserting event
		$rs = ($rsold) ? $rsold->fields : NULL;
		$insertRow = $this->Row_Inserting($rs, $rsnew);
		if ($insertRow) {
			$conn->raiseErrorFn = Config("ERROR_FUNC");
			$addRow = $this->insert($rsnew);
			$conn->raiseErrorFn = "";
			if ($addRow) {
			}
		} else {
			if ($this->getSuccessMessage() != "" || $this->getFailureMessage() != "") {

				// Use the message, do nothing
			} elseif ($this->CancelMessage != "") {
				$this->setFailureMessage($this->CancelMessage);
				$this->CancelMessage = "";
			} else {
				$this->setFailureMessage($Language->phrase("InsertCancelled"));
			}
			$addRow = FALSE;
		}

		// Add detail records
		if ($addRow) {
			$detailTblVar = explode(",", $this->getCurrentDetailTable());
			if (in_array("activity", $detailTblVar) && $GLOBALS["activity"]->DetailAdd) {
				$GLOBALS["activity"]->HotelID->setSessionValue($this->HostelID->CurrentValue); // Set master key
				$GLOBALS["activity"]->RollNo->setSessionValue($this->RollNo->CurrentValue); // Set master key
				$GLOBALS["activity"]->Name->setSessionValue($this->Name->CurrentValue); // Set master key
				$GLOBALS["activity"]->Hostel->setSessionValue($this->Hostel->CurrentValue); // Set master key
				$GLOBALS["activity"]->Floor->setSessionValue($this->Floor->CurrentValue); // Set master key
				$GLOBALS["activity"]->Room_No->setSessionValue($this->RoomNo->CurrentValue); // Set master key
				if (!isset($GLOBALS["activity_grid"]))
					$GLOBALS["activity_grid"] = new activity_grid(); // Get detail page object
				$Security->loadCurrentUserLevel($this->ProjectID . "activity"); // Load user level of detail table
				$addRow = $GLOBALS["activity_grid"]->gridInsert();
				$Security->loadCurrentUserLevel($this->ProjectID . $this->TableName); // Restore user level of master table
				if (!$addRow) {
					$GLOBALS["activity"]->HotelID->setSessionValue(""); // Clear master key if insert failed
					$GLOBALS["activity"]->RollNo->setSessionValue(""); // Clear master key if insert failed
					$GLOBALS["activity"]->Name->setSessionValue(""); // Clear master key if insert failed
					$GLOBALS["activity"]->Hostel->setSessionValue(""); // Clear master key if insert failed
					$GLOBALS["activity"]->Floor->setSessionValue(""); // Clear master key if insert failed
					$GLOBALS["activity"]->Room_No->setSessionValue(""); // Clear master key if insert failed
				}
			}
		}

		// Commit/Rollback transaction
		if ($this->getCurrentDetailTable() != "") {
			if ($addRow) {
				$conn->commitTrans(); // Commit transaction
			} else {
				$conn->rollbackTrans(); // Rollback transaction
			}
		}
		if ($addRow) {

			// Call Row Inserted event
			$rs = ($rsold) ? $rsold->fields : NULL;
			$this->Row_Inserted($rs, $rsnew);
		}

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

	// 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("activity", $detailTblVar)) {
				if (!isset($GLOBALS["activity_grid"]))
					$GLOBALS["activity_grid"] = new activity_grid();
				if ($GLOBALS["activity_grid"]->DetailAdd) {
					if ($this->CopyRecord)
						$GLOBALS["activity_grid"]->CurrentMode = "copy";
					else
						$GLOBALS["activity_grid"]->CurrentMode = "add";
					$GLOBALS["activity_grid"]->CurrentAction = "gridadd";

					// Save current master table to detail table
					$GLOBALS["activity_grid"]->setCurrentMasterTable($this->TableVar);
					$GLOBALS["activity_grid"]->setStartRecordNumber(1);
					$GLOBALS["activity_grid"]->HotelID->IsDetailKey = TRUE;
					$GLOBALS["activity_grid"]->HotelID->CurrentValue = $this->HostelID->CurrentValue;
					$GLOBALS["activity_grid"]->HotelID->setSessionValue($GLOBALS["activity_grid"]->HotelID->CurrentValue);
					$GLOBALS["activity_grid"]->RollNo->IsDetailKey = TRUE;
					$GLOBALS["activity_grid"]->RollNo->CurrentValue = $this->RollNo->CurrentValue;
					$GLOBALS["activity_grid"]->RollNo->setSessionValue($GLOBALS["activity_grid"]->RollNo->CurrentValue);
					$GLOBALS["activity_grid"]->Name->IsDetailKey = TRUE;
					$GLOBALS["activity_grid"]->Name->CurrentValue = $this->Name->CurrentValue;
					$GLOBALS["activity_grid"]->Name->setSessionValue($GLOBALS["activity_grid"]->Name->CurrentValue);
					$GLOBALS["activity_grid"]->Hostel->IsDetailKey = TRUE;
					$GLOBALS["activity_grid"]->Hostel->CurrentValue = $this->Hostel->CurrentValue;
					$GLOBALS["activity_grid"]->Hostel->setSessionValue($GLOBALS["activity_grid"]->Hostel->CurrentValue);
					$GLOBALS["activity_grid"]->Floor->IsDetailKey = TRUE;
					$GLOBALS["activity_grid"]->Floor->CurrentValue = $this->Floor->CurrentValue;
					$GLOBALS["activity_grid"]->Floor->setSessionValue($GLOBALS["activity_grid"]->Floor->CurrentValue);
					$GLOBALS["activity_grid"]->Room_No->IsDetailKey = TRUE;
					$GLOBALS["activity_grid"]->Room_No->CurrentValue = $this->RoomNo->CurrentValue;
					$GLOBALS["activity_grid"]->Room_No->setSessionValue($GLOBALS["activity_grid"]->Room_No->CurrentValue);
					$GLOBALS["activity_grid"]->Indiscipline_activity->setSessionValue(""); // Clear session key
				}
			}
		}
	}

	// Set up Breadcrumb
	protected function setupBreadcrumb()
	{
		global $Breadcrumb, $Language;
		$Breadcrumb = new Breadcrumb();
		$url = substr(CurrentUrl(), strrpos(CurrentUrl(), "/")+1);
		$Breadcrumb->add("list", $this->TableVar, $this->addMasterUrl("admissionlist.php"), "", $this->TableVar, TRUE);
		$pageId = ($this->isCopy()) ? "Copy" : "Add";
		$Breadcrumb->add("add", $pageId, $url);
	}

	// Setup lookup options
	public function setupLookupOptions($fld)
	{
		if ($fld->Lookup !== NULL && $fld->Lookup->Options === NULL) {

			// Get default connection and filter
			$conn = $this->getConnection();
			$lookupFilter = "";

			// No need to check any more
			$fld->Lookup->Options = [];

			// Set up lookup SQL and connection
			switch ($fld->FieldVar) {
				case "x_Hostel":
					$conn = Conn("");
					break;
				case "x_Floor":
					$conn = Conn("");
					break;
				case "x_RoomNo":
					$conn = Conn("");
					break;
				case "x_Academic":
					$conn = Conn("");
					$lookupFilter = function() {
						return "`Status`=1";
					};
					$lookupFilter = $lookupFilter->bindTo($this);
					break;
				case "x_Status":
					$conn = Conn("");
					break;
				default:
					$lookupFilter = "";
					break;
			}

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

			// Set up lookup cache
			if ($fld->UseLookupCache && $sql != "" && count($fld->Lookup->Options) == 0) {
				$totalCnt = $this->getRecordCount($sql, $conn);
				if ($totalCnt > $fld->LookupCacheCount) // Total count > cache count, do not cache
					return;
				$rs = $conn->execute($sql);
				$ar = [];
				while ($rs && !$rs->EOF) {
					$row = &$rs->fields;

					// Format the field values
					switch ($fld->FieldVar) {
						case "x_Hostel":
							break;
						case "x_Floor":
							break;
						case "x_RoomNo":
							$row[1] = FormatNumber($row[1], 0, -2, -2, -2);
							$row['df'] = $row[1];
							break;
						case "x_Academic":
							break;
					}
					$ar[strval($row[0])] = $row;
					$rs->moveNext();
				}
				if ($rs)
					$rs->close();
				$fld->Lookup->Options = $ar;
			}
		}
	}

	// Page Load event
	function Page_Load() {

		//echo "Page Load";
	}

	// Page Unload event
	function Page_Unload() {

		//echo "Page Unload";
	}

	// Page Redirecting event
	function Page_Redirecting(&$url) {

		// Example:
		//$url = "your URL";

	}

	// Message Showing event
	// $type = ''|'success'|'failure'|'warning'
	function Message_Showing(&$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
	function Page_Render() {

		//echo "Page Render";
	}

	// Page Data Rendering event
	function Page_DataRendering(&$header) {

		// Example:
		//$header = "your header";

	}

	// Page Data Rendered event
	function Page_DataRendered(&$footer) {

		// Example:
		//$footer = "your footer";

	}

	// Form Custom Validate event
	function Form_CustomValidate(&$customError) {

		// Return error message in CustomError
		return TRUE;
	}
} // End class
?>