public function init() { $model = Options::model()->findByPk(1); $this->site_name = $model->site_name; $this->email = $model->email; $this->top_news_count = $model->top_news_count; $this->short_description_symbols = $model->short_description_symbols; }
/** * Updates a particular model. * If update is successful, the browser will be redirected to the 'show' page. */ public function actionWeboptions() { if (isset($_POST['options_posted'])) { User::updateOptionTemplate(User::optionsWebTemplate(), 0, 0); $this->redirect(Yii::app()->request->baseUrl); } else { $this->render('weboptions', array('weboptions' => Options::model()->findAll('companyId=0 AND userId=0', array()))); } }
private function optionsArrayToString() { $criteria = new CDbCriteria(); $criteria->compare('companyId', $this->id); $criteria->compare('userId', 0); $options = Options::model()->findAll($criteria); $returnString = ''; foreach ($options as $n => $option) { $returnString .= $option->name . '=' . $option->datavalue . ";"; } return $returnString; }
/** * Manages all models. */ public function actionIndex() { $model = Options::model()->findByPk(1); // Uncomment the following line if AJAX validation is needed // $this->performAjaxValidation($model); if (isset($_POST['Options'])) { $model->attributes = $_POST['Options']; if ($model->save()) { Yii::app()->user->setFlash('success', Yii::t('main', 'Данные успешно сохранены!')); $this->refresh(); } else { Yii::app()->user->setFlash('error', Yii::t('main', 'Ошибка!')); } $this->refresh(); } $this->render('index', array('model' => $model)); }
/** * getElementsAndDynamicAttributes * @param array $componentData * @access public * @return array */ public function getElementsAndDynamicAttributes($componentData = []) { $elements = []; $attributeArray = []; $dynamicDataAttributes = []; //$getFormCondition = 't.formId=:formId'; //$getFormParams = array(':formId' => 1); $getForm = EvaluationElements::model()->findAll(); //$elements['title'] = "Components Form"; $elements['showErrorSummary'] = true; $elements['showErrors'] = true; $elements['errorSummaryHeader'] = Yii::app()->params['headerErrorSummary']; $elements['errorSummaryFooter'] = Yii::app()->params['footerErrorSummary']; $elements['activeForm']['id'] = "EvalForm"; $elements['activeForm']['enableClientValidation'] = true; $elements['activeForm']['clientOptions'] = ['validateOnSubmit' => true]; //$elements['activeForm']['enableAjaxValidation'] = false; $elements['activeForm']['class'] = 'CActiveForm'; //print_r($getForm); die(); $evalElements = $getForm; $dataArray['getForm'] = $elements; $inputType = 'text'; //$dynamicDataAttributes['frameworkId'] = 'frameworkId'; //$rules[] = ['frameworkId', 'required']; $designData = FrameworkContext::model()->findAll(['condition' => 'userId=:userId', 'params' => [':userId' => Yii::app()->user->id]]); $designItems = []; // process the dropdown data into an array foreach ($designData as $params) { $designItems[$params->frameworkId] = $params->name; } $elements['elements'] = EvaluationHeader::getElements(); // add the dropdown items to the element //$elements['elements']['frameworkId']['items'] = $designItems; $elements['elements']['evaContext']['type'] = 'form'; //$elements['elements']['evaluationName']['layout'] = '{label} {input} {hint} {error}'; $rules = []; $labels = []; foreach ($evalElements as $element) { //set the model attribute array $attributeId = $element->inputName . "_" . $element->evalElementsId; $dynamicDataAttributes[$attributeId] = ''; $validation = $element->required ? 'required' : 'safe'; $rules[] = [$attributeId, $validation]; if ($element->inputName == 'componentNo') { $rules[] = [$attributeId, 'numerical']; } $highlightClass = ""; if (isset($attributeArray[$element->evalElementsId])) { $highlightClass = "attributeHighlight"; } $labels[$attributeId] = $element->label; // add the elements to the CForm array $elements['elements']['evaContext']['elements'][$attributeId] = ['label' => $element->label, 'required' => $element->required, 'type' => $element->inputType, 'class' => $highlightClass, 'title' => UtilModel::urlToLink($element->elementMetaData), 'data-field' => $element->evalElementsId]; // Add an image icon that will be displayed on the ui to show more info $button = CHtml::image('', '', ['id' => 'moreInfoButton' . $element->evalElementsId, 'style' => 'cursor:pointer', 'class' => 'ui-icon ui-icon-info', 'title' => 'More Information', 'onClick' => '$("#moreInfoDialog").html($("#popupData' . $element->evalElementsId . '").html());$("#moreInfoDialog").dialog("open")']); // Add the image icon and information to the layout/ui // if (!empty($element->moreInfo) && !empty($element->url) && !empty($element->description)) { // $elements['elements']['evaContext']['elements'][$attributeId]['layout'] = '{label}<div class="componentImagePopup">' . $button . // '</div>{hint} {input}' . '<div id="popupData' . $element->evalElementsId . '" style="display:none">' . $element->moreInfo . '</div>' . // '<div class="componentDataPopup">' . $element->description . // ' <br/> <a href=' . $element->url . ' target=_blank>' . $element->url . '</a></div> {error}'; // } // add the values to the form if (!empty($componentData[$attributeId])) { $elements['elements']['evaContext']['elements'][$attributeId]['value'] = $componentData[$attributeId]['value']; } // add the component name element value if (!empty($componentData['evaluationName'])) { $elements['elements']['evaContext']['elements']['evaluationName']['value'] = $componentData['evaluationName']; } // add the frameworkId element value if (!empty($componentData['frameworkId'])) { $elements['elements']['evaContext']['elements']['frameworkId']['value'] = $componentData['frameworkId']; } //add the dropdown parameters if ($element->inputType == 'dropdownlist') { $items = CHtml::listData(Options::model()->findAll(['condition' => 'elementId=:elementId', 'params' => [':elementId' => $element->evalElementsId]]), 'optionId', 'label'); // add the dropdown items to the element $elements['elements']['evaContext']['elements'][$attributeId]['items'] = $items; $elements['elements']['evaContext']['elements'][$attributeId]['prompt'] = 'Choose one'; } if ($element->inputName == 'currentCost' || $element->inputName == 'budgetLimit') { $elements['elements']['evaContext']['elements'][$attributeId]['class'] = 'update-able'; } } $elements['buttons'] = ['newEvaluation' => ['type' => 'submit', 'label' => 'Create evaluation context']]; $returnArray = ['elements' => $elements, 'dynamicDataAttributes' => $dynamicDataAttributes, 'labels' => $labels, 'rules' => $rules]; return $returnArray; }
/** * Displays the requested report * */ public function actionReport() { //throw(new Exception('just die')); if ((isset($_POST['ShowReport']) || isset($_POST['DownloadPDF']) || isset($_POST['DownloadExcel'])) && isset($_POST['reportId'])) { $this->_model = Report::model()->findbyPk($_POST['reportId']); if ($this->_model === null) { throw new CHttpException(404, 'The requested page does not exist.'); } //delete all the old report parameter values ReportUserLastUsedParams::model()->dbConnection->createCommand('DELETE FROM ReportUserLastUsedParams WHERE reportId=' . $this->_model->id . ' AND userId=' . Yii::app()->user->id)->execute(); //build the Sql sats $aliases = array(); $replacements = array(); $repParams = $this->_model->reportparameters; $parameterValues = array(); $graphicFilename = ""; $title = ""; if (isset($repParams) && count($repParams) > 0) { foreach ($repParams as $n => $repParam) { //get the new parameter values if ($repParam->dataType == 'HIDDEN_NO_SHOW_HEAD' || $repParam->dataType == 'HIDDEN_SHOW_HEAD') { if (strlen($repParam->phpSecondaryInfo) > 0) { eval($repParam->phpSecondaryInfo); } else { $defaultValue = $repParam->defaultValue; if ($repParam->isDefaultPhp) { eval($defaultValue); } } $parameterValues[$n] = $defaultValue; } else { if (isset($_POST[$n])) { if ($repParam->dataType == 'DATE') { $parameterValues[$n] = User::parseDate($_POST[$n]); } else { $parameterValues[$n] = $_POST[$n]; } if (strlen($title) == 0) { $title = $_POST[$n]; } $negateGraphicValues = false; if ($repParam->name == 'Negate values for graphics') { $negateGraphicValues = (int) $_POST[$n]; } //save the parameter values $saveLast = new ReportUserLastUsedParams(); $saveLast->reportId = $this->_model->id; $saveLast->userId = Yii::app()->user->id; $saveLast->paramId = $n; $saveLast->LastUsedValue = $parameterValues[$n]; $saveLast->save(); } } //get the aliases if (strlen($repParam->alias) > 0) { $aliases[] = $repParam->alias; if ($repParam->dataType == 'HIDDEN_NO_SHOW_HEAD' || $repParam->dataType == 'HIDDEN_SHOW_HEAD') { $defaultValue = $repParam->defaultValue; if ($repParam->isDefaultPhp) { eval($defaultValue); } $replacements[] = $defaultValue; } else { if ($repParam->dataType == 'DATE') { $replacements[] = User::parseDate($_POST[$n]); } else { $replacements[] = $_POST[$n]; } } if ($repParam->alias == '{ShowGraph}' && strlen($_POST[$n]) > 0) { $graphicFilename = $_POST[$n]; } } } } $sqlSelect = str_replace($aliases, $replacements, $this->_model->selectSql); // var_dump($aliases); // var_dump($replacements); //echo $sqlSelect.'<br><br>'; // echo $sqlSelect; die(); //execute the Sql sats //Yii::log($sqlSelect, CLogger::LEVEL_INFO, 'system.web.CController'); $command = Report::model()->dbConnection->createCommand($sqlSelect); try { $reader = $command->query(); //foreach($reader as $row)print_r($row); //die(); } catch (Exception $e) { echo '<h2>Died on Sql execution</h2>' . $sqlSelect; throw $e; } $imageFileNames = array(); $imageFilePaths = array(); if (strlen($graphicFilename) > 0) { $images = $this->readXmlGraphicFile($graphicFilename, false, $reader, $title, $negateGraphicValues, $imageFileNames); $imageFileNames = $images[1]; $imageFilePaths = $images[0]; //must do this again because the reader can only go forwards $reader = $command->query(); } //update last used report for printout $printoutview = ""; if (isset($_POST['printoutview'])) { $printoutview = $_POST['printoutview']; } $option = Options::model()->find('name=\'isReportForPrintout\' AND companyId=0 AND userId=' . Yii::app()->user->id); $option->datavalue = $printoutview == 1 ? 'true' : 'false'; $option->save(); Yii::app()->user->setState('isReportForPrintout', $printoutview); //update last used black and white $option = Options::model()->find('name=\'isReportBlackAndWhite\' AND companyId=0 AND userId=' . Yii::app()->user->id); $option->datavalue = false; $option->datavalue = isset($_POST['blackandwhite']) && $_POST['blackandwhite'] == 1 ? 'true' : 'false'; $option->save(); Yii::app()->user->setState('isReportBlackAndWhite', isset($_POST['blackandwhite']) && $_POST['blackandwhite'] == 1 ? 1 : 0); if (isset($_POST['blackandwhite']) && $_POST['blackandwhite'] == 1) { Yii::app()->user->setState('reportCssFile', $this->_model->cssBwFileName); } else { Yii::app()->user->setState('reportCssFile', $this->_model->cssColorFileName); } //get the number and date formats $cLoc = CLocale::getInstance('en'); $numberFormatter = $cLoc->getNumberFormatter(); $dateFormatter = $cLoc->getDateFormatter(); // echo "<pre>"; // var_dump($dateFormatter); // echo "</pre>"; // die(); $numberFormat = User::getNumberFormat(); $pdf_name = ""; $cron_job = FALSE; // if from cron job if (isset($_POST['cron'])) { $pdf_name = "reports/lazy8report_" . date('Y-m-d_H.i.s'); $cron_job = TRUE; } if (isset($_POST['DownloadExcel'])) { Yii::import('application.controllers.excel.*'); require_once "exportExcel.php"; new exportExcel($this->_model, $reader, $pdf_name, $numberFormatter, $dateFormatter, $numberFormat, $printoutview, $parameterValues); die; } else { if (isset($_POST['DownloadPDF'])) { // var_dump($numberFormat); // die(); Yii::import('application.controllers.tcpdf.*'); require_once "lazy8tcpdf.php"; new lazy8tcpdf($this->_model, $reader, $pdf_name, $cron_job, $numberFormatter, $dateFormatter, $numberFormat, $printoutview, $parameterValues, $imageFileNames, isset($_POST['blackandwhite']) && $_POST['blackandwhite'] == 1 ? 1 : 0, strpos(Yii::app()->user->getState('reportCssFile'), "wide") === false); // if cron job was run then email user with the pdf attatchment if (isset($_POST['cron'])) { $accountID = $_POST['accountID']; $sql = "SELECT Account.code AS accountcode, Account.name AS accountname, Account.email AS email, Account.balance_threshold AS threshold, Account.days AS days\n\t\t\t\t\t\t\t\tFROM Account\n\t\t\t\t\t\t\t\tWHERE Account.code = '{$accountID}'"; $account = Yii::app()->db->createCommand($sql)->queryAll(); $to = $account['email']; $subject = 'Weekly Report'; $headers = "From: Accounting@thaiconnections.org \r\n"; $headers .= "Reply-To: no-reply@thaiconnections.org\r\n"; $headers .= "MIME-Version: 1.0\r\n"; $headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n"; $message = '<html><body>'; $message .= '<p>Hello,</p>'; $message .= '<p>This a automated notification from Thaiconnections Accounting website that your weekly report for: <strong>' . $account['accountname'] . ' </strong>is ready to be downloaded. Please click the link to view your report.<p>'; $message .= '<phttp://accounting.thaiconnections.org/' . $pdf_name . '.pdf<p>'; $message .= '<p>Kindest Regards,<br>'; $message .= 'Thaiconnections Accounting</p>'; $message .= '</body></html>'; if (mail($to, $subject, $message, $headers)) { echo "Email sent...<br>"; } else { echo "Mail did not send. Error occurred"; } } } else { //show the report $this->render('report', array('model' => $this->_model, 'reader' => $reader, 'numberFormatter' => $numberFormatter, 'dateFormatter' => $dateFormatter, 'numberFormat' => $numberFormat, 'printoutview' => $printoutview, 'parameterValues' => $parameterValues, 'imageFileNames' => $imageFilePaths)); } } } else { //show the report parameter selection page. $noActivityLogSelectionString = ""; if (!Yii::app()->user->getState('allowChangeLog')) { $noActivityLogSelectionString = " AND name<>'Activity log'"; } $allRepModels = Report::model()->findAll(array('select' => 'id,name', 'order' => 'sortOrder', 'condition' => '(companyId=' . Yii::app()->user->getState('selectedCompanyId') . ' OR companyId=0)' . $noActivityLogSelectionString)); $reports = CHtml::listData($allRepModels, 'id', 'name'); foreach ($reports as $n => $reportsTrans) { $reports[$n] = Yii::t('lazy8', $reportsTrans); } if (isset($_POST['reportId']) && $_POST['reportId']) { $model = Report::model()->findbyPk($_POST['reportId']); //update last used report $option = Options::model()->find('name=\'lastPrintedReportId\' AND companyId=0 AND userId=' . Yii::app()->user->id); $option->datavalue = $_POST['reportId']; $option->save(); Yii::app()->user->setState('lastPrintedReportId', $_POST['reportId']); } else { //always try to select any report $selectReport = Yii::app()->user->getState('lastPrintedReportId'); $model = Report::model()->findbyPk($selectReport); if (isset($model)) { $_POST['reportId'] = $selectReport; } elseif (isset($allRepModels) && count($allRepModels) > 0) { $_POST['reportId'] = $allRepModels[0]->id; $model = $allRepModels[0]; } } //preselect the values to what was done before... $repParams = $model->reportparameters; if (isset($repParams) && count($repParams) > 0) { foreach ($repParams as $n => $repParam) { if ($repParam->dataType == 'FREE_TEXT' || $repParam->dataType == 'DROP_DOWN' || $repParam->dataType == 'DATE' || $repParam->dataType == 'BOOLEAN') { $lastChosen = ReportUserLastUsedParams::model()->find('reportId=' . $model->id . ' AND userId=' . Yii::app()->user->id . ' AND paramId=' . $n); if (isset($lastChosen)) { $defaultValue = $lastChosen->LastUsedValue; } else { $defaultValue = $repParam->defaultValue; if ($repParam->isDefaultPhp) { eval($defaultValue); } } if ($repParam->dataType == 'DATE') { $_POST[$n] = User::getDateFormatted($defaultValue); } else { $_POST[$n] = $defaultValue; } } } } $_POST['blackandwhite'] = Yii::app()->user->getState('isReportBlackAndWhite') ? 1 : 0; $_POST['printoutview'] = Yii::app()->user->getState('isReportForPrintout') ? 1 : 0; $this->render('reportparams', array('reports' => $reports, 'model' => $model)); } }
public static function setOption($name, $val) { if ($name) { $param = Options::model()->findByAttributes(['key' => $name]); if ($param) { $param->value = $val; $param->update(); return true; } else { $param = new Options(); $param->key = $name; $param->value = $val; $param->save(); return true; } } else { return false; } }
/** * Returns the data model based on the primary key given in the GET variable. * If the data model is not found, an HTTP exception will be raised. * @param integer $id the ID of the model to be loaded * @return Options the loaded model * @throws CHttpException */ public function loadModel($id) { $model = Options::model()->findByPk($id); if ($model === null) { throw new CHttpException(404, 'The requested page does not exist.'); } return $model; }
} else { $(like).val(0); } console.log($(like).val()); } </script> </tbody> </table> </div><!-- form --> </div> </div> <div class="row"> <div class="col-lg-12"> <?php $option = Options::model()->findAll(array('limit' => 1)); $url; if (yii::app()->user->isUser()) { if ($option[0]->id > 3) { $url = createUrl('options/optionView', array('id' => $option[0]->id)); } else { $url = createUrl('options/optionView', array('id' => $option[0]->id)); } } elseif (yii::app()->user->isFranchiseAdmin()) { if ($option[0]->id > 3) { $url = createUrl('options/optionsView', array('options_num' => $option[0]->id, 'custom' => 1)); } else { $url = createUrl('options/optionsView', array('options_num' => $option[0]->id)); } } else { $url = createUrl('customer/list');
public function actionDownloadPdf($id) { $cusUser = Customer::model()->findByPk($id); if (!$cusUser) { throw new CHttpException(403, 'Customer not exists'); } $franchise_admin = User::model()->find(" franchise = " . $cusUser->franchise . " and role_id=3"); $pdf_content = PdfContentFranchise::model()->findByAttributes(array('cus_id' => $id, 'isactive' => 1, 'type' => 2)); if (!$pdf_content) { $pdf_content = PdfContent::model()->findByAttributes(array('type' => 2)); } $params = array(); $offers = Options::model()->findByPk($cusUser->option_id); if (!$offers) { $offers = CustomOptionsId::model()->findByPk($cusUser->option_id); } $params['options'][] = $offers; $params['lunchMenu'] = $cusUser->lunches; $params['breakfasts'] = $cusUser->breakfasts; $params['indusFoods'] = $cusUser->indusFoods; $params['sundries'] = $cusUser->sundries; $params['sandwiches'] = $cusUser->sandwiches; $params['hotfood'] = $cusUser->hotFoods; $params['magicSpoolsAns'] = $cusUser->magicSpoolsAns; $selProd = SelProducts::model()->findAll(array("condition" => "cus_id =" . $id, "order" => "product_id asc")); $params['selproducts'] = array(); foreach ($selProd as $selp) { $product = Product::model()->findByPk($selp->product_id); $params['selproducts'][] = array_merge($product->attributes, $selp->attributes); } $this->layout = '//decorators/empty'; $html2pdf = Yii::app()->ePdf->HTML2PDF(); ///////////////////////////////////// menu container started $container = array(); foreach ($params as $param) { foreach ($param as $p) { $container[] = $p; } } $div_array = array_chunk($container, 200); $showTitle = 1; foreach ($div_array as $array) { $html2pdf->WriteHTML($this->renderPartial('//decorators/pdf_no_h_f', array('params' => $array, 'cusUser' => $cusUser, 'showTitle' => $showTitle, 'franchise_admin' => $franchise_admin, 'pdf_content' => $pdf_content), true)); $showTitle = 0; } if (Yii::app()->session['User_mail']) { $html2pdf->Output(dirname(__FILE__) . '/../../pdf/test_xxxx.pdf', 'F'); $message = "\n You Will find an pdf attachment in this mail which contain detail of all the menues and items selected \n by you.\n "; $subject = "\n Customer Solutions Iform Pdf Form\n "; $mail_to = array(); if ($franchise_admin->email) { $mail_to[] = $franchise_admin->email; } // if ($cusUser->email) // $mail_to[] = $cusUser->email; if ($cusUser->attendee0->email) { $mail_to[] = $cusUser->attendee0->email; } $this->mail_attachment('Jasper Franchise.pdf', 'FILEPATH', $mail_to, '*****@*****.**', 'Jaspers', '*****@*****.**', $subject, $message); } else { $html2pdf->Output('jasper_franchise.pdf', 'D'); } unset(Yii::app()->session['User_mail']); Yii::app()->session['email_sent'] = $cusUser->id; $this->redirect(array('site/index')); }
/** * actionGetInputTypeOpts * * @access public * @return void */ public function actionGetInputTypeOpts() { $optArray = array(); if (!empty($_GET['subFormId'])) { $subFormId = $_GET['subFormId']; $options = Options::model()->findAll(array("condition" => "componentId = {$subFormId}", 'select' => 'optionId, label')); if (!empty($options)) { foreach ($options as $opt) { $optArray[] = $opt->getAttributes(); } } } echo json_encode(array("aaData" => $optArray)); return; }
public function actionOptionsEditView() { $customer = Customer::model()->findByPk(getCurCusId()); if (isset($_POST['option'])) { $cus = Customer::Model()->findByPk(getCurCusId()); $cus->option_id = $_POST['option']; $cus->save(); $this->redirect(array('site/index')); } if (isset($_GET['options_num'])) { $value = intval(isset($_GET['options_num']) ? $_GET['options_num'] : "0"); $model = Options::model()->findByPk($value); if ($model === NULL || empty($model)) { $model = array('offer_msg' => "Sorry, Selected offer is not available"); } } else { $model = array('offer_msg' => "Please choose Offers"); } $criteria = new CDbCriteria(); $criteria->compare('franchise', Yii::app()->user->franchise); $customers = Customer::model()->findAll($criteria); $customerlist = CHtml::listData($customers, 'id', 'name'); $this->render("optioneditviews", array('model' => $model, 'customers' => $customerlist, 'id' => $customer->option_id)); }
public static function updateOptionTemplate($options, $id, $companyId, $updateAdminOptions = true) { $webapp = Yii::app()->user; foreach ($options as $key => $option) { if (($updateAdminOptions || $option[5] == 'false') && $option[3] == 'false') { $foundOption = Options::model()->find('name=:name AND userId=:id AND companyId=:compid', array(':name' => $key, ':id' => $id, ':compid' => $companyId)); if ($foundOption === null) { $createOption = new Options(); $createOption->name = $key; $createOption->userId = $id; $createOption->companyId = $companyId; $foundOption = $createOption; } switch ($option[0]) { case 'STRING': case 'DROP_DOWN_LIST': case 'INTEGER': case 'FLOAT': case 'DATE': $foundOption->datavalue = $_POST['option_' . $foundOption->name]; break; case 'BOOLEAN': $foundOption->datavalue = isset($_POST['option_' . $foundOption->name]) && $_POST['option_' . $foundOption->name] == 1 ? 'true' : 'false'; break; } if ($foundOption->name == 'NonStandardNumberDecimalFormat' || $foundOption->name == 'NonStandardNumberDecimalFormat') { if (Yii::app()->user->getState('allowAdmin')) { $foundOption->save(); } } else { $foundOption->save(); } if ($id == $webapp->id || $id == 0) { $webapp->setState($key, User::convertOptionToObject($foundOption->datavalue, $option)); } } } }
/** * Updates a particular model. * If update is successful, the browser will be redirected to the 'show' page. */ public function actionUpdate() { $model = $this->loadCompany(); if (isset($_POST['Company'])) { $modelBeforeChange = $model->toString(); $model->attributes = $_POST['Company']; if ($model->save()) { User::updateOptionTemplate(User::optionsCompanyTemplate(), 0, $model->id); $stringModel = $model->toString(); if ($modelBeforeChange != $stringModel) { ChangeLog::addLog('UPDATE', 'Company', 'BEFORE<br />' . $modelBeforeChange . '<br />AFTER<br />' . $stringModel); } $this->redirect(array('admin', 'id' => $model->id)); } } User::setOptionStatesAndControlTable(false, false, Yii::app()->user, User::optionsCompanyTemplate(), $model->id, 0); $criteria = new CDbCriteria(); $criteria->compare('companyId', $model->id); $criteria->compare('userId', 0); $options = Options::model()->findAll($criteria); $this->render('update', array('model' => $model, 'options' => $options)); }
/** * Updates a particular model. * If update is successful, the browser will be redirected to the 'show' page. */ public function actionUpdate() { $model = $this->loadUser(); if (isset($_POST['User'])) { $oldPassword = $model->password; $modelBeforeChange = $model->toString(); $model->attributes = $_POST['User']; //salt must contain something if (!isset($model->salt) || strlen($model->salt) == 0) { $model->salt = hash('sha1', uniqid(rand(), true)); //since the salt has changed, We must have a new password. Force it if it is not changed if (strlen($model->password) == 0 && strlen($model->confirmPassword == 0)) { //this forces the entry of a new password unset($oldPassword); } } //only check the password if they have entered something. Blank password is ignored. if (strlen($model->password) == 0 && strlen($model->confirmPassword == 0)) { $model->password = $oldPassword; $model->confirmPassword = $oldPassword; } else { $model->password = hash('sha1', $model->password . $model->salt); $model->confirmPassword = hash('sha1', $model->confirmPassword . $model->salt); } if ($model->save()) { if (Yii::app()->user->getState('allowAdmin')) { //remove all companies for this user User::model()->dbConnection->createCommand("DELETE FROM CompanyUser WHERE userId={$model->id}")->execute(); $companies = array(); if (isset($_POST['companies'])) { $companies = $_POST['companies']; } //must remove all options for unchosen companies. $beforeCompanies = $model->companies; foreach ($beforeCompanies as $beforeComp) { $foundCompany = false; foreach ($companies as $comp) { if ($comp == $beforeComp->id) { $foundCompany = true; break; } } if (!$foundCompany) { //company no longer selected. Delete all options User::model()->dbConnection->createCommand("INSERT INTO CompanyUser (userId, companyId) VALUES ({$model->id},{$beforeComp->id})")->execute(); } } $foundCurrentCompany = false; $foundSelectedCompany = false; //re-add the selected companies foreach ($companies as $comp) { User::model()->dbConnection->createCommand("INSERT INTO CompanyUser (userId, companyId) VALUES ({$model->id},{$comp})")->execute(); if ($model->selectedCompanyId == $comp) { $foundCurrentCompany = true; } if ($_POST['companyForOptionsBeforeChange'] == $comp) { $foundSelectedCompany = true; } } if (!$foundCurrentCompany) { //they have remove the currently selected company. We must remove it as being selected $model->selectedCompanyId = 0; $model->selectedPeriodId = 0; $model->confirmPassword = $model->password; $model->save(); if (Yii::app()->user->id == $_GET['id']) { $model->setStates(); } } } //do the options $this->setOptionsByTemplate(false); //user options first User::updateOptionTemplate(User::optionsUserTemplate(), $model->id, 0, Yii::app()->user->getState('allowAdmin')); //company options, only if admin if (!isset($_POST['save']) && Yii::app()->user->getState('allowAdmin')) { //we must set all companies to the template chosen foreach ($companies as $comp) { User::updateOptionTemplate(User::optionsCompanyUserTemplate(), $model->id, $comp); } } elseif (isset($foundSelectedCompany) && $foundSelectedCompany && Yii::app()->user->getState('allowAdmin')) { //no template chosen. Just update the visible options for the selected company $model->updateOptionTemplate($model->optionsCompanyUserTemplate(), $model->id, $_POST['companyForOptionsBeforeChange']); } $stringModel = $model->toString(); if ($modelBeforeChange != $stringModel) { ChangeLog::addLog('UPDATE', 'Account', 'BEFORE<br />' . $modelBeforeChange . '<br />AFTER<br />' . $stringModel); } //we need to reload this user to get all the updates in the companies. $this->_model = User::model()->findbyPk(isset($id) && $id !== null ? $id : $_GET['id']); $model = $this->_model; // $this->redirect(array('update','id'=>$model->id)); } else { unset($this->_model->password); unset($this->_model->confirmPassword); } } else { unset($this->_model->password); unset($this->_model->confirmPassword); //make sure the options are all created $this->_model->setStates(); } $companyForOptions = null; $companyList = null; $options = null; $allCompanies = null; $selectedCompanies = null; if (Yii::app()->user->getState('allowAdmin') == 1 || Yii::app()->user->getState('allowAdmin') == 1) { $companiesUsers = $model->companies; $companyForOptions = null; if (isset($companiesUsers) && isset($companiesUsers[0])) { $companyForOptions = $companiesUsers[0]->id; } if (isset($_POST['companyForOptions'])) { $companyForOptions = $_POST['companyForOptions']; } $options = Options::model()->findAll('companyId=:comp AND userId=:id', array(':comp' => $companyForOptions, ':id' => $model->id)); $companyList = CHtml::listData($companiesUsers, 'id', 'name'); $usersModel = User::model()->findbyPk($_GET['id']); //put all the user companies in an array $companiesUsers = $usersModel->companies; $selectedCompanies = array(); if (isset($companiesUsers)) { foreach ($companiesUsers as $companyUser) { $selectedCompanies[] = $companyUser->id; } } $allCompanies = Company::model()->findAll(); } $model->password = ""; $model->confirmPassword = ""; $this->render('update', array('model' => $model, 'companyForOptions' => $companyForOptions, 'companies' => $companyList, 'weboptions' => $options, 'allCompanies' => $allCompanies, 'selectedCompanies' => $selectedCompanies)); }
/** * @param $fieldId * @param $dForm * @return string */ private function generateGridElements($fieldId, &$dForm) { //$model = new DynamicFormDetails('insert', 'frameworkFieldData'); // get grid fields $gridFieldsCriteria = new CDbCriteria(); $gridFieldsCriteria->condition = 'parentId=' . $fieldId; $gridFieldsCriteria->order = '`order` ASC'; $gridFieldsNames = []; $labels = []; $properties = []; $rules = []; $inputs = ''; if ($dForm->getScenario() == 'insert') { $gridFields = FrameworkFields::model()->findAll($gridFieldsCriteria); $inputs .= '<tr class="copy' . $fieldId . '">'; foreach ($gridFields as $field) { //$el = new CFormInputElement() $attribute = $field->inputName . '_' . $field->id; $dForm->setpropertyName($attribute); // continue; //$model->setAttribute($attribute, $field->inputName); // $dForm->_dynamicLabels[$attribute] = isset($field->label) ? // $field->label : $dForm->generateAttributeLabel($field->inputName); $labels[$attribute] = isset($field->label) ? $field->label : $dForm->generateAttributeLabel($field->inputName); $validation = $field->required ? 'required' : 'safe'; $rules[] = [$attribute, $validation]; $i = 0; //print_r($dForm); die; $inputs .= '<td>'; switch ($field->inputType) { case 'text': $inputs .= CHtml::activeTextField($dForm, "[{$i}]{$attribute}"); $inputs .= CHtml::error($dForm, "[{$i}]{$attribute}"); break; case 'dropdownlist': $options = []; if ($field->multiple) { $options['multiple'] = true; } $inputs .= CHtml::activeDropDownList($dForm, "[{$i}]{$attribute}", Options::model()->getContextFieldOptions($field->id), $options); $inputs .= CHtml::error($dForm, "[{$i}]{$attribute}"); break; } $inputs .= '</td>'; //$elements['elements'][] = '</td>'; } $inputs .= '<td></td></tr>'; } else { // get id's of fields that belong to the grid //$gridFieldsCriteria->select = 'id'; $childFields = ModelToArray::convertModelToArray(FrameworkFields::model()->with('data')->findAll($gridFieldsCriteria)); // ['frameworkFields' => 'id, inputName, label, inputType, required, multiple']); //print_r($childFields); die; $gridFieldsIds = array_map(function ($item) { return $item['id']; }, $childFields); // get grid data $fieldDataCriteria = new CDbCriteria(); $fieldDataCriteria->condition = 'frameworkId=' . Yii::app()->session['surDesign']['id']; $fieldDataCriteria->addInCondition('frameworkFieldId', $gridFieldsIds); $gridFields = FrameworkFieldData::model()->findAll($fieldDataCriteria); if (empty($gridFields)) { $dForm->setScenario('insert'); //print_r($dForm); die; return self::generateGridElements($fieldId, $dForm); } $dFormGrid = []; foreach ($childFields as $child) { $elementId = $child['inputName'] . '_' . $child['id']; $gridFieldsNames[$child['id']] = $elementId; $gridParams[$elementId]['id'] = $child['id']; $labels[$elementId] = $child['label']; $gridParams[$elementId]['inputType'] = $child['inputType']; $gridParams[$elementId]['required'] = $child['required']; $gridParams[$elementId]['multiple'] = $child['multiple']; } //$dFormGrid[$k] = new DForm(); foreach ($childFields as $child) { if (isset($child['data'][0])) { foreach ($child['data'] as $key => $data) { if (!isset($dFormGrid[$key])) { $dFormGrid[$key] = new DForm(); } $elementId = $child['inputName'] . '_' . $child['id']; foreach ($gridFieldsNames as $gridElement) { if (empty($dFormGrid[$key]->attributes[$gridElement])) { //echo "new $key $gridElement \n"; //print_r($dFormGrid[$key]); // $dFormGrid[$key]->setPropertyName($gridElement); } //var_dump($dFormGrid[$key]->$gridElement); } $dFormGrid[$key]->{$elementId} = $data['value']; if (DForm::isJson($data['value'])) { $dFormGrid[$key]->{$elementId} = json_decode($data['value']); } } } } $copyClass = ''; foreach ($dFormGrid as $key => $gridItems) { $inputs .= '<tr class="copy' . $fieldId . ' ' . $copyClass . '">'; foreach ($gridItems->attributeNames() as $attr) { //var_dump($gridItems[$attr]); die; $inputs .= '<td>'; switch ($gridParams[$attr]['inputType']) { case 'text': $inputs .= CHtml::activeTextField($gridItems, "[{$key}]{$attr}"); $inputs .= CHtml::error($gridItems, "[{$key}]{$attr}"); break; case 'dropdownlist': $options = []; if ($gridParams[$attr]['multiple']) { $options['multiple'] = true; } $inputs .= CHtml::activeDropDownList($gridItems, "[{$key}]{$attr}", Options::model()->getContextFieldOptions($gridParams[$attr]['id']), $options); $inputs .= CHtml::error($gridItems, "[{$key}]{$attr}"); break; } $inputs .= '</td>'; } $inputs .= '<td><a class="remove ui-icon ui-icon-trash" href="#"' . ' onclick="$(this).parent().parent().remove(); return false">remove</a></td></tr>'; $copyClass = 'copy1'; } //echo $inputs; die; } //var_dump($data, $cols); die('lklk'); //die; $dForm->setRules($rules); $dForm->setAttributeLabels($labels); //print_r(array_values($labels)); $tableHeader = '<th>' . implode('</th><th>', array_values($labels)); $table = '<table class="jgTabular"><thead><tr>' . $tableHeader . '<th></th></tr></thead>'; $table .= '<tbody>' . $inputs . '</tbody>'; $table .= '</table>'; $table .= CHtml::htmlButton('<span class="ui-icon ui-icon-plusthick"></span>Add new row', ['id' => 'copyLink-' . $fieldId, 'rel' => '.copy' . $fieldId]); // if($fieldId == 37) { // print_r($table); //die('pop'); // } return $table; }
public static function getComponentData($componentsOnly = false) { $componentListArray = []; $formDetailsArray = []; // get list of surveillance designs $componentList = ComponentHead::model()->with("compDetails")->findAll(['condition' => 'frameworkId=:frameworkId', 'params' => [':frameworkId' => Yii::app()->session['surDesign']['id']]]); $formDetails = SurFormDetails::model()->findAll(['condition' => 'showOnComponentList=:showOnList', 'params' => [':showOnList' => true]]); $selectOptions = CHtml::listData(Options::model()->findAll(['condition' => 'componentId IS NOT NULL']), 'optionId', 'label'); //print_r($selectOptions); die; // format dataTable data $count = 0; foreach ($componentList as $com) { $componentListArray[$count] = ['componentId' => $com->componentId, 'frameworkId' => $com->frameworkId, 'name' => $com->componentName, 'targetSpecies' => '', 'targetSector' => '', 'dataColPoint' => '', 'diseaseType' => '', 'sampleType' => '', 'studyType' => '']; foreach ($formDetails as $formInput) { $formDetailsArray[$formInput->inputName] = $formInput->label; foreach ($com->compDetails as $data) { //$subDetails[$data->inputName] = $data->value; if ($formInput->subFormId == $data->subFormId) { $componentListArray[$count][$formInput->inputName] = $data->value; if ($formInput->inputType == "dropdownlist" && isset($selectOptions[$data->value])) { $componentListArray[$count][$formInput->inputName] = $selectOptions[$data->value]; } } } } $count++; } return $componentsOnly ? $componentListArray : ['componentListArray' => $componentListArray, 'formDetailsArray' => $formDetailsArray]; }
public function getRecruitmentNextProcess($data) { $status = $data->status; $model = Options::model(); $raw = $model->with('options')->findByAttributes(array('id' => $status)); $next_opt = $raw->getRelated('options'); $this->renderPartial('_carousel_form', array('data' => $data, 'next_option' => $next_opt, 'model' => TalentStatus::model())); return ''; //这里是为了防止出现默认的空格,如果不返回 }
/** * actionDeleteOption * * @access public * @return void */ public function actionDeleteOption($id) { Yii::log("actionDeleteOption OptionsController called", "trace", self::LOG_CAT); $record = Options::model()->findByPk($id)->delete(); if (!$record) { Yii::log("Error deleting Option: " . $id, "warning", self::LOG_CAT); echo Yii::t("translation", "A problem occurred when deleting the Option "); } else { echo Yii::t("translation", "The Option has been successfully deleted"); } }
/** * Executes any command triggered on the admin page. */ protected function processAdminCommand() { //print_r($_POST);die(); if (isset($_POST['Save'])) { //check that ALL translations are in this translation.. $sources = SourceMessage::model()->findAll(); foreach ($sources as $source) { $existstest = Message::model()->find(array('condition' => 'language=\'' . $_POST['langcode'] . '\' AND id=' . $source->id)); if ($existstest === null) { $trans = new Message(); $trans->id = $source->id; $trans->translation = '-dirty-' . $source->message; $trans->language = $model->language; $trans->save(); } else { if (isset($_POST['Message'][$source->id])) { } } } //do the actual reading of data from the form $messages = Message::model()->findAll(array('condition' => 'language=\'' . $_POST['langcode'] . '\'')); foreach ($messages as $message) { if (isset($_POST['Message'][$message->id])) { $message->attributes = $_POST['Message'][$message->id]; $message->save(); } //delete no longer used posts. if (!isset($message->source)) { $message->delete(); } } } elseif (isset($_POST['Delete'])) { SourceMessage::model()->dbConnection->createCommand("DELETE FROM Message WHERE language='" . $_POST['langcode'] . "'")->execute(); $foundOption = Options::model()->find('name=:name AND userId=:id AND companyId=:compid', array(':name' => "Language.Version." . $_POST['langcode'], ':id' => 0, ':compid' => 0)); if ($foundOption !== null) { $foundOption->delete(); } unset($_POST['langcode']); } elseif (isset($_POST['Export'])) { $dom = new DomDocument(); $dom->encoding = 'utf-8'; $root = $dom->createElement("lazy8webportlang"); $root->setAttribute("version", "1.00"); $language = $dom->createElement("language"); $language->setAttribute("langcode", $_POST['langcode']); $exportLang = Message::model()->with('source')->findAll(array('condition' => "language='" . $_POST['langcode'] . "'", 'together' => true, 'order' => "message")); foreach ($exportLang as $export) { if (isset($export->source)) { $message = $dom->createElement("message"); $message->setAttribute("category", $export->source->category); $message->setAttribute("key", html_entity_decode($export->source->message)); $this->appendTextNode($dom, $message, "translation", $export->translation); $language->appendChild($message); } } $root->appendChild($language); $dom->appendChild($root); $dom->formatOutput = true; $thefile = $dom->saveXML(); // set headers header("Pragma: no-cache"); header("Expires: 0"); header("Content-Description: File Transfer"); header("Content-Type: text/xml"); header("Content-Disposition: attachment; filename=\"lazy8webExport.Language." . $_POST['langcode'] . "." . date('Y-m-d_H.i.s') . ".xml\""); header("Content-Transfer-Encoding: binary"); header("Content-Length: " . strlen($thefile)); //flush(); print $thefile; return; //we may not send any more to the screen or it will mess up the file we just sent! } elseif (isset($_POST['langcode'])) { $this->editinglanguage = $_POST['langcode']; } }
public function actionOptions() { $options = Options::model()->findAll(array('order' => 'opt_type')); $this->render('options', array('options' => $options)); }