public function run() { $id = Yii::app()->request->getParam('id'); $type = Yii::app()->request->getParam('type'); $userId = Yii::app()->request->getParam('userId'); $hub = Yii::app()->request->getParam('hub'); $startTime = Yii::app()->request->getParam('startTime'); $endTime = Yii::app()->request->getParam('endTime'); $room = Yii::app()->request->getParam('room'); $data = array('type' => $type, 'userId' => $userId, 'hubId' => $hub, 'startTime' => $startTime, 'endTime' => $endTime, 'conferenceroomId' => $room); $proxy = new BReservation(); $dc = new BConference(); $dp = new BHub(); if (Yii::app()->request->isAjaxRequest) { $result = $proxy->updateReservation($data, $id); echo CJSON::encode($result); } else { $result = $proxy->getReservationInfo($id); $hub = $dp->getHubList($start, 10); $room = $dc->getRoomList($start, 10); if ($result['code'] == 200) { $this->controller->render('edit', array('data' => $result['data'], 'hub' => $hub['data'], 'room' => $room['data'])); } else { throw new CHttpException($result['code'], $result['message']); } } }
public function run() { $params = array(); $criteria = new CDbCriteria(); // $criteria->select = array('id,username,fullname,phone,address,status'); $criteria->select = '*'; if (isset($this->team_lear_id) and $this->team_lear_id != '') { $criteria->addCondition('team_lear_id=' . $this->team_lear_id); } $criteria->params = $params; $total = ATrainingTeam::model()->count($criteria); $offset = $this->limit * ($this->page - 1); $criteria->limit = $this->limit; $criteria->offset = $offset; $data = ATrainingTeam::model()->findAll($criteria); $listTrainee = array(); if (!empty($data)) { foreach ($data as $item) { $listTrainee[] = CJSON::decode(CJSON::encode($item->pls_user)); } } $data = $listTrainee; $pages = new CPagination($total); $pages->pageSize = $this->limit; $pages->applyLimit($criteria); $this->render($this->view, array('data' => $data, 'pages' => $pages)); }
/** * Encodes the data as a JSON string to be used in JavaScript code. * * @static * * @param mixed $data * @param bool $forceObject force all arrays to objects * * @return mixed */ public static function encodeJson($data, $forceObject = false) { if (self::$json === null) { self::$json = new CJSON(); } return self::$json->encode($data, array(), $forceObject); }
/** * Output ajax response. If any error was added, 'result' is false, otherwise true. * * @return void */ public function send() { $json = new CJSON(); if ($this->_result) { echo $json->encode(array('result' => true, 'data' => $this->_data)); } else { echo $json->encode(array('result' => false, 'errors' => $this->_errors)); } }
/** * Display editor */ public function run() { // Resolve name and id list($name, $id) = $this->resolveNameID(); // Get assets dir $baseDir = dirname(__FILE__); $assets = Yii::app()->getAssetManager()->publish($baseDir . DIRECTORY_SEPARATOR . 'ueditor1_2_5'); // Publish required assets $cs = Yii::app()->getClientScript(); $jsFile = $this->debug ? 'editor_all.js' : 'editor_all_min.js'; $cs->registerScriptFile($assets . '/' . $jsFile); $cs->registerScriptFile($assets . '/editor_config.js'); $this->htmlOptions['id'] = $id; if (!array_key_exists('style', $this->htmlOptions)) { $this->htmlOptions['style'] = "width:{$this->width};"; } if ($this->toolbars) { $this->editorOptions['toolbars'][] = $this->toolbars; } $options = CJSON::encode(array_merge(array('theme' => $this->theme, 'lang' => $this->language, 'UEDITOR_HOME_URL' => "{$assets}/", 'initialFrameWidth' => $this->width, 'initialFrameHeight' => $this->height), $this->editorOptions)); $js = <<<EOP UE.getEditor('{$id}',{$options}); EOP; // Register js code $cs->registerScript('Yii.' . get_class($this) . '#' . $id, $js, CClientScript::POS_READY); // Do we have a model if ($this->hasModel()) { $html = CHtml::activeTextArea($this->model, $this->attribute, $this->htmlOptions); } else { $html = CHtml::textArea($name, $this->value, $this->htmlOptions); } echo $html; }
/** * Creates a new model. * If creation is successful, the browser will be redirected to the 'view' page. */ public function actionSend() { $model = new Reports(); // Uncomment the following line if AJAX validation is needed $this->performAjaxValidation($model); if (isset($_POST['Reports'])) { $model->attributes = $_POST['Reports']; $jsonError = CActiveForm::validate($model); if (strlen($jsonError) > 2) { echo $jsonError; } else { if (isset($_GET['enablesave']) && $_GET['enablesave'] == 1) { if ($model->save()) { echo CJSON::encode(array('type' => 5, 'get' => Yii::app()->controller->createUrl('send', array('type' => 'success')))); } else { print_r($model->getErrors()); } } } Yii::app()->end(); } else { $this->dialogDetail = true; $this->dialogGroundUrl = Yii::app()->createUrl('site/index'); $this->dialogWidth = 500; $this->pageTitle = Phrase::trans(12014, 1); $this->pageDescription = ''; $this->pageMeta = ''; $this->render('front_send', array('model' => $model)); } }
protected function makeBuilderPredefinedEmailTemplate($name, $unserializedData, $subject = null, $modelClassName = null, $language = null, $type = null, $isDraft = 0, $textContent = null, $htmlContent = null) { $emailTemplate = new EmailTemplate(); $emailTemplate->type = $type; //EmailTemplate::TYPE_WORKFLOW; $emailTemplate->builtType = EmailTemplate::BUILT_TYPE_BUILDER_TEMPLATE; $emailTemplate->isDraft = $isDraft; $emailTemplate->modelClassName = $modelClassName; $emailTemplate->name = $name; if (empty($subject)) { $subject = $name; } $emailTemplate->subject = $subject; if (!isset($language)) { $language = Yii::app()->languageHelper->getForCurrentUser(); } $emailTemplate->language = $language; $emailTemplate->htmlContent = $htmlContent; $emailTemplate->textContent = $textContent; $emailTemplate->serializedData = CJSON::encode($unserializedData); $emailTemplate->addPermissions(Group::getByName(Group::EVERYONE_GROUP_NAME), Permission::READ_WRITE_CHANGE_PERMISSIONS_CHANGE_OWNER); $saved = $emailTemplate->save(false); if (!$saved) { throw new FailedToSaveModelException(); } $emailTemplate = EmailTemplate::getById($emailTemplate->id); ReadPermissionsOptimizationUtil::securableItemGivenPermissionsForGroup($emailTemplate, Group::getByName(Group::EVERYONE_GROUP_NAME)); $saved = $emailTemplate->save(false); assert('$saved'); }
/** * Suggests models based on the current user input. */ public function run() { if (isset($_GET['term']) && ($keyword = trim($_GET['term'])) !== '') { $suggest = $this->getModel()->{$this->methodName}($keyword, $this->limit, $_GET); echo CJSON::encode($suggest); } }
/** * Returns a List of all notifications for an user */ public function actionIndex() { // the id from the last entry loaded $lastEntryId = (int) Yii::app()->request->getParam('from'); // create database query $criteria = new CDbCriteria(); if ($lastEntryId > 0) { // start from last entry id loaded $criteria->condition = 'id<:lastEntryId'; $criteria->params = array(':lastEntryId' => $lastEntryId); } $criteria->order = 'seen ASC, created_at DESC'; $criteria->limit = 6; // safe query $notifications = Notification::model()->findAllByAttributes(array('user_id' => Yii::app()->user->id), $criteria); // variable for notification list $output = ""; foreach ($notifications as $notification) { // format and save all entries $output .= $notification->getOut(); // get the id from the last entry $lastEntryId = $notification->id; } // build json array $json = array(); $json['output'] = $output; $json['lastEntryId'] = $lastEntryId; $json['counter'] = count($notifications); // return json echo CJSON::encode($json); // compete action Yii::app()->end(); }
public function init() { //Yii::app()->setTheme('adm'); $cs = Yii::app()->getClientScript(); $cs->registerScriptFile(Yii::app()->theme->baseUrl . '/js/global.js'); $cs->registerScriptFile(Yii::app()->theme->baseUrl . '/js/jquery-ui.min.js'); $cs->registerScriptFile(Yii::app()->theme->baseUrl . '/js/jquery.alerts.js'); //$cs->registerScriptFile(Yii::app()->theme->baseUrl.'/js/jquery.confirm.js'); //$cs->registerScriptFile(Yii::app()->theme->baseUrl.'/js/jquery.blockui.js'); $cs->registerScriptFile(Yii::app()->theme->baseUrl . '/js/jquery-ui-1.8.2.custom.min.js'); //$cs->registerScriptFile(Yii::app()->theme->baseUrl.'/js/bsystemgroup.js'); $cs->registerCssFile(Yii::app()->theme->baseUrl . '/css/jquery.alerts.css'); Yii::app()->clientScript->registerScript('global', ' yii = { urls: { base: ' . CJSON::encode(Yii::app()->theme->baseUrl) . ' } }; ', CClientScript::POS_HEAD); if (Yii::app()->user->id) { $user = new ASystemUser(); $userInfo = $user->getSystemUserById(Yii::app()->user->id); //var_dump($userInfo->cp_code);exit(); $this->group_id = $userInfo->group_id; $this->username = $userInfo->username; Yii::app()->session['group_id'] = $this->group_id; Yii::app()->session['username'] = $this->username; } //$xmlPath = realpath($path = Yii::app()->basePath.'/../'.Yii::app()->params['config_folder'].'/'); // $xmlFile = Yii::app()->params['config_file_name']; // $this->config = new LoadConfigXML($xmlPath,$xmlFile); Yii::$classMap = array_merge(Yii::$classMap, array('CaptchaExtendedAction' => Yii::getPathOfAlias('ext.captchaExtended') . DIRECTORY_SEPARATOR . 'CaptchaExtendedAction.php', 'CaptchaExtendedValidator' => Yii::getPathOfAlias('ext.captchaExtended') . DIRECTORY_SEPARATOR . 'CaptchaExtendedValidator.php')); }
public function run() { $galleryItemType = $this->albumItemType; $item_id = Yii::app()->request->getParam('gitem_id'); $model = $galleryItemType::model()->findByPk($item_id); if (!$model) { throw new CHttpException(404); } $target_id = $model->target_id; if (!Yii::app()->user->checkAccess('album_deleteGItem', array('item' => $model))) { throw new CHttpException(403); } $afterDeleteHandler = function ($event) { $originalPath = $event->sender->path; $filesPathes = Yii::app()->getModule('album')->getAbsolutePathes($originalPath); foreach ($filesPathes as $path) { if (file_exists($path)) { unlink($path); } } }; $model->attachEventHandler('onAfterDelete', $afterDeleteHandler); if (!$model->delete()) { throw new CException('Item #' . $item_id . ' deletion failed'); } if (Yii::app()->request->isAjaxRequest) { echo CJSON::encode(array('success' => true, 'html' => Yii::t('album.messages', 'Элемент был удален успешно'))); Yii::app()->end(); } $this->redirect(array($this->getModule()->rootRoute, 'target_id' => $target_id)); }
public function actionIndex() { // Return all Diseases $response = array(); $response['PhotoPath'] = Yii::app()->params['siteDomain'] . Yii::app()->params['imagePath']; $response['Entries'] = array(); $response['Photos'] = array(); $response['PhotoLinker'] = array(); $tubers = Tuber::model()->findAll(); if ($tubers != null) { // Have something to return.. // Get images for each entry. foreach ($tubers as $tuber) { // Get all images for current tuber entry. $images = $tuber->images; if ($images != null) { foreach ($images as $image) { $response['PhotoLinker'][] = array('Id' => $image->Id, 'EntryId' => $image->TuberId, 'PhotoId' => $image->PhotoId); $response['Photos'][] = array("Id" => $image->photo->Id, "ImageName" => $image->photo->Name, "EntryId" => $tuber->Id); } } $response['Entries'][] = $tuber; } } $this->sendResponse(200, CJSON::encode($response)); }
public function actionUpdate($id) { if (null === ($model = User::model()->findByPk($id))) { throw new CHttpException(404); } $data = CJSON::decode(file_get_contents('php://input')); $model->fname = $data['fname']; $model->lname = $data['lname']; $model->email = $data['email']; $model->username = $data['username']; $model->role = $data['role']; $model->newPassword = $data['password']; if ($model->newPassword) { $model->password = $model->newPassword; } if (!$model->save()) { $errors = array(); foreach ($model->getErrors() as $e) { $errors = array_merge($errors, $e); } $this->sendResponse(500, implode("<br />", $errors)); } $model = User::model()->noPassword()->findByPk($model->id); $this->sendResponse(200, CJSON::encode($model)); }
/** * Добавление / редактирование комментариев */ public function actionSave_comment() { if (Yii::app()->user->isGuest) { $this->redirect($this->createAbsoluteUrl('base')); } // Редактирование или добавление новой if (isset($_GET['idComment'])) { $model = Comments::model()->findByPk($_GET['idComment']); } else { $model = new Comments(); } if (isset($_POST['idArticle']) && isset($_POST['text']) && isset($_POST['idAuthor'])) { $model->idArticle = $_POST['idArticle']; $model->text = $_POST['text']; $model->idUser = empty($this->_user) ? Users::getIdUserForAdmin() : $this->_user['idUser']; $model->typeUser = $model->idUser == $_POST['idAuthor'] ? 'author' : (empty($this->_user) ? 'admin' : 'user'); if ($model->save()) { if (Yii::app()->request->isAjaxRequest) { $criteria = new CDbCriteria(); $criteria->with = array('idUser0'); $criteria->condition = 'idArticle = :idArticle AND deleted = 0 AND public = 1'; $criteria->params = array(':idArticle' => $_POST['idArticle']); $comments = Comments::model()->findAll($criteria); $commentsDataProvider = new CArrayDataProvider($comments, array('keyField' => 'idComment', 'pagination' => array('pageSize' => 50))); $listComments = $this->renderPartial('_list_comments', array('dataProvider' => $commentsDataProvider), true); echo CJSON::encode(array('listComments' => $listComments)); exit; } } } }
public function actionAnyFileData($id = null, $model = 'Partner', $filename = 'image', $realname = false) { $result = array(); $id = (int) $id; $model = $model::model()->findByPk($id); if (!$model) { echo '[]'; Yii::app()->end(); throw new CHttpException(404, Yii::t('site', 'Page not found')); } $uploadPath = $model->getFileFolder(); if ($model->{$filename}) { $obj['id'] = $model->id; //get the filename in array if ($realname) { $obj['name'] = $model->{$realname}; } else { $obj['name'] = $model->{$filename}; } if (file_exists($uploadPath . $model->{$filename})) { $obj['size'] = filesize($uploadPath . $model->{$filename}); //get the flesize in array } else { $obj['size'] = '0'; } $result[] = $obj; // copy it to another array } header('Content-Type: application/json'); echo CJSON::encode($result); Yii::app()->end(); }
public function actionIndex() { global $API_CODE; if (!empty($_REQUEST['s'])) { $s = trim($_REQUEST['s']); $data = get_all_data(true, true, false, true); $result_array = array(); foreach ($data as $_data) { if (strpos(@$_data['user'], $s) !== false || strpos($_data['post_content'], $s) !== false || strpos($_data['reply_content'], $s) !== false || strpos($_data['b_username'], $s) !== false) { $result_array[] = $_data; } } if (defined('API_MODE')) { $json_array = array('messages' => $result_array, 'nums' => count($result_array)); die(function_exists('json_encode') ? json_encode($json_array) : CJSON::encode($json_array)); } $nums = count($result_array); $this->render('search_result', array('data' => $result_array, 'nums' => $nums)); } elseif (defined('API_MODE')) { $error_array = array('error_code' => '400', 'error' => $API_CODE['400'], 'error_detail' => t('NO_SEARCH_PARAM')); die(function_exists('json_encode') ? json_encode($error_array) : CJSON::encode($error_array)); } else { header("Location:index.php"); } }
public function authenticate() { Yii::log(__METHOD__, "info"); $this->errorCode = self::ERROR_USERNAME_INVALID; $model = Yii::app()->user->um->loadUser($this->username); Yii::log(__METHOD__ . ' ' . CrugeTranslator::t('logger', 'Returned User') . ":\n" . CJSON::encode($model), "info"); $this->_userinstance = null; if ($model != null) { if (CrugeUtil::checkhash($this->password, $model->password)) { $this->_userinstance = $model; $this->errorCode = self::ERROR_NONE; } else { if (CrugeUtil::config()->debug == true) { // ayuda a instalar, quiza el usuario olvide quitar la encriptacion de claves // y reciba error de ERROR_PASSWORD_INVALID, es porque esta actuando el Hash // y el usuario recien creado trae una clave no encritpada if (CrugeUtil::config()->useEncryptedPassword == true) { echo Yii::app()->user->ui->setupAlert(CrugeTranslator::t('logon', 'Maybe your password doesn\'t match because you have set up \'useEncryptedPassword = true\' when you were installing Cruge, try \'false\' instead')); } } $this->errorCode = self::ERROR_PASSWORD_INVALID; } } else { // username o email error $this->errorCode = self::ERROR_USERNAME_INVALID; } Yii::log(__CLASS__ . "\nauthenticate returns:\n" . $this->errorCode . "\n boolean result is:" . ($this->errorCode == self::ERROR_NONE), "info"); return $this->errorCode == self::ERROR_NONE; }
public function actionCreate() { $basic = new basic(); if (isset($_POST['title']) & isset($_POST['content']) & isset($_POST['phone'])) { $node = new stdClass(); $node->title = $_POST['title']; $node->body['und'][0]['value'] = $_POST['content']; $node->field_phone['und'][0]['value'] = $_POST['phone']; $node->uid = 1; $node->type = 'yijianfank'; $node->language = 'zh-hans'; $node->status = 1; //(1 or 0): published or not $node->promote = 0; //(1 or 0): promoted to front page $node->comment = 0; // 0 = comments disabled, 1 = read only, 2 = read/write $node = node_submit($node); // Prepare node for saving //print_r($node); node_save($node); $basic->error_code = 0; //$basic->error_msg="no input parameters"; } else { $basic->error_code = 1; $basic->error_msg = "no input parameters"; } $jsonObj = CJSON::encode($basic); echo $jsonObj; }
private function add() { $post = $this->request->getPost('Setting'); if (empty($post)) { $this->response(404, '参数缺失'); } else { $exists = Setting::model()->findByAttributes(['section' => $post['section'], 'name' => $post['name']]); if (empty($exists)) { $model = new Setting(); $model->attributes = ['section' => $post['section'], 'name' => $post['name'], 'value' => CJSON::encode(explode(',', $post['value']))]; if ($model->save()) { $this->response(200, '添加成功'); } else { $this->response(500, '添加失败'); } } else { $exists->value = CJSON::encode(explode(',', $post['value'])); if ($exists->save()) { $this->response(200, '修改成功'); } else { $this->response(500, '修改失败'); } } } }
private function _sendResponse($raw = false, $dataType = false) { $status = $this->_statusCode; if ($dataType === false) { $contentType = $this->_contentType; } else { $contentType = $dataType; } // set the status $status_header = 'HTTP/1.1 ' . $status . ' ' . $this->_statusText; @header($status_header); // and the content type @header('Content-type: ' . $contentType); $response = $this->data; if ($raw) { echo $response; } else { //jsonp handling $json = CJSON::encode($response); if (isset($_GET['callback'])) { echo $_GET['callback'] . ' ('; echo $json; echo ');'; } else { echo $json; } } }
/** * Creates a new model. * If creation is successful, the browser will be redirected to the 'view' page. */ public function actionCreate() { if ($this->CanAccess('create')) { $model = new Language(); // Uncomment the following line if AJAX validation is needed // $this->performAjaxValidation($model); if (isset($_POST['Language'])) { $model->attributes = $_POST['Language']; if ($model->CanUpdate() && $model->save()) { // if AJAX request , we should not redirect the browser if (!Yii::app()->request->isAjaxRequest) { $this->redirect(array('view', 'id' => $model->id)); } else { echo CJSON::encode(array('error' => '', 'id' => $model->id)); die; } } } if (!Yii::app()->request->isAjaxRequest) { $this->render('create', array('model' => $model, 'ajaxRendering' => false)); } else { $this->renderPartial('create', array('model' => $model, 'ajaxRendering' => true)); } } else { throw new CHttpException(405, Yii::t('app', 'You do not have permissions to access this page.')); } }
/** * Duplicated from the admin controller to give a user list * * (there's also a method on the UserController that could be used, so would be worth consolidating) */ public function actionUserFind() { $res = array(); if (\Yii::app()->request->isAjaxRequest && !empty($_REQUEST['search'])) { $criteria = new \CDbCriteria(); $criteria->compare("LOWER(username)", strtolower($_REQUEST['search']), true, 'OR'); $criteria->compare("LOWER(first_name)", strtolower($_REQUEST['search']), true, 'OR'); $criteria->compare("LOWER(last_name)", strtolower($_REQUEST['search']), true, 'OR'); $words = explode(" ", $_REQUEST['search']); if (count($words) > 1) { // possibly slightly verbose approach to checking first and last name combinations // for searches $first_criteria = new \CDbCriteria(); $first_criteria->compare("LOWER(first_name)", strtolower($words[0]), true); $first_criteria->compare("LOWER(last_name)", strtolower(implode(" ", array_slice($words, 1, count($words) - 1))), true); $last_criteria = new \CDbCriteria(); $last_criteria->compare("LOWER(first_name)", strtolower($words[count($words) - 1]), true); $last_criteria->compare("LOWER(last_name)", strtolower(implode(" ", array_slice($words, 0, count($words) - 2))), true); $first_criteria->mergeWith($last_criteria, 'OR'); $criteria->mergeWith($first_criteria, 'OR'); } foreach (\User::model()->findAll($criteria) as $user) { $res[] = array('id' => $user->id, 'label' => $user->getFullNameAndTitle(), 'value' => $user->getFullName(), 'username' => $user->username); } } echo \CJSON::encode($res); }
public function run() { // Создать модель и указать ей, что используется сценарий регистрации $model = new RegistrationForm(); // if it is ajax validation request if (isset($_POST['ajax']) && $_POST['ajax'] === 'RegistrationForm') { //echo CActiveForm::validate($model); $error = CActiveForm::validate($model); if ($error != '[]') { echo $error; } Yii::app()->end(); } // Если пришли данные для сохранения if (isset($_POST['RegistrationForm'])) { // Безопасное присваивание значений атрибутам $model->attributes = $_POST['RegistrationForm']; // Проверка данных if ($model->validate() && $model->signUp()) { echo CJSON::encode(array('status' => 'success')); Yii::app()->end(); } else { $error = CActiveForm::validate($model); if ($error != '[]') { echo $error; } Yii::app()->end(); } } // вивести форму //$this->controller->redirect(Yii::app()->user->returnUrl); //$this->renderPartial('registration', array('model'=>$model)); }
/** * Register required script files * @param $id */ public function registerClientScript($id) { Yii::app()->bootstrap->registerAssetCss('redactor.css'); Yii::app()->bootstrap->registerAssetJs('redactor.min.js'); $options = CJSON::encode(CMap::mergeArray($this->editorOptions, array('lang' => $this->lang))); Yii::app()->bootstrap->registerRedactor('#' . $id, $options); }
public function authenticate() { Yii::log(__METHOD__, "info"); $this->errorCode = self::ERROR_USERNAME_INVALID; $model = Yii::app()->user->um->loadUser($this->username); Yii::log(__METHOD__ . " usuario retornado es:\n" . CJSON::encode($model), "info"); $this->_userinstance = null; if ($model != null) { if ($model->password == $this->_getPwd()) { $this->_userinstance = $model; $this->errorCode = self::ERROR_NONE; } else { if (CrugeUtil::config()->debug == true) { // ayuda a instalar, quiza el usuario olvide quitar la encriptacion de claves // y reciba error de ERROR_PASSWORD_INVALID, es porque esta actuando el MD5 // y el usuario recien creado trae una clave no encritpada if (CrugeUtil::config()->useEncryptedPassword == true) { echo Yii::app()->user->ui->setupAlert("Quiza su clave no coincide porque ha configurado 'useEncryptedPassword = true' estando en la fase de instalacion, pruebe deshabilitandolo"); } } $this->errorCode = self::ERROR_PASSWORD_INVALID; } } else { // username o email error $this->errorCode = self::ERROR_USERNAME_INVALID; } Yii::log(__CLASS__ . "\nauthenticate returns:\n" . $this->errorCode . "\n boolean result is:" . ($this->errorCode == self::ERROR_NONE), "info"); return $this->errorCode == self::ERROR_NONE; }
public function actionAjaxObtenerCliente() { $idCliente = $_POST['idCliente']; $clientes = Cliente::model()->obtenerClientexId($idCliente); header('Content-Type: application/json; charset="UTF-8"'); echo CJSON::encode(array('output' => $clientes[0])); }
/** * Creates a new model. * If creation is successful, the browser will be redirected to the 'view' page. */ public function actionCreate($cat_id = null) { if (Yii::app()->user->checkAccess($this->id . '.' . $this->action->id)) { $model = new PaymentType(); // Uncomment the following line if AJAX validation is needed // $this->performAjaxValidation($model); if (isset($_POST['PaymentType'])) { $model->attributes = $_POST['PaymentType']; $model->category_id = $cat_id; if ($model->save()) { if (Yii::app()->request->isAjaxRequest) { echo CJSON::encode(array('status' => 'success', 'div' => 'Payment Type successfully added.')); exit; } else { // Yii::app()->user->setFlash('success', 'Payment Type added successfully!'); $this->redirect(Yii::app()->user->returnUrl); } } } // $model->category_id = $cat_id; if (Yii::app()->request->isAjaxRequest) { echo CJSON::encode(array('status' => 'failure', 'div' => $this->renderPartial('_form', array('model' => $model), true, true))); exit; } else { $this->render('create', array('model' => $model, 'cat_name' => Category::model()->findByPk($cat_id)->getFullCategory())); } } else { $this->accessDenied(); } }
public function run($code) { if (Yii::app()->request->isAjaxRequest) { $user = User::model()->findByAttributes(array('id' => Yii::app()->user->id)); $result = Coding::isValidCode($code); $hasused = Coding::hasUsedCode($code); if ($result['code'] == 200 && $user->status >= 3 && !$hasused) { $code = Code::model()->findByAttributes(array('code' => $code)); $code->times--; $code->save(); $codeused = new CodeUsed(); $codeused->codeId = $code->id; $codeused->userId = Yii::app()->user->id; $codeused->createTime = date('YmdHis'); $codeused->save(); $user->status = 4; $user->save(); $ccode = new CCode(); $result = $ccode->getproduct($code->code); echo CJSON::encode(array('code' => 200, 'mes' => 'success', 'data' => $result['data'])); } else { echo CJSON::encode(array('code' => 500, 'mes' => 'fail')); } } }
public function init() { $quotesAssetsUrl = $this->module->assetsUrl; if (isset($_POST)) { $startHidden = false; } if ($this->startHidden) { if ($this->startHidden) { Yii::app()->clientScript->registerScript('startQuotesHidden', "\$('#quotes-form').hide();", CClientScript::POS_READY); } // Set up the new create form: Yii::app()->clientScript->registerScriptFile($quotesAssetsUrl . '/js/inlineQuotes.js', CClientScript::POS_HEAD); Yii::app()->clientScript->registerScriptFile($quotesAssetsUrl . '/js/LineItems.js', CClientScript::POS_HEAD); Yii::app()->clientScript->registerCssFiles('InlineQuotesCss', array($quotesAssetsUrl . '/css/inlineQuotes.css', $quotesAssetsUrl . '/css/lineItemsMain.css', $quotesAssetsUrl . '/css/lineItemsWrite.css'), false); Yii::app()->clientScript->registerCoreScript('jquery.ui'); $this->contact = X2Model::model('Contacts')->findByPk($this->contactId); //$this->contact = Contacts::model()->findByPk($this->contactId); $iqConfig = array('contact' => $this->contact instanceof Contacts ? CHtml::encode($this->contact->name) : '', 'account' => $this->account, 'sendingQuote' => false, 'lockedMessage' => Yii::t('quotes', 'This quote is locked. Are you sure you want to update this quote?'), 'deniedMessage' => Yii::t('quotes', 'This quote is locked.'), 'lockedDialogTitle' => Yii::t('quotes', 'Locked'), 'failMessage' => Yii::t('quotes', 'Could not save quote.'), 'reloadAction' => CHtml::normalizeUrl(array('/quotes/quotes/viewInline', 'recordId' => $this->recordId, 'recordType' => CHtml::encode($this->modelName))), 'createAction' => CHtml::normalizeUrl(array('/quotes/quotes/create', 'quick' => 1, 'recordId' => $this->recordId, 'recordType' => $this->modelName)), 'updateAction' => CHtml::normalizeUrl(array('/quotes/quotes/update', 'quick' => 1))); Yii::app()->clientScript->registerScript('quickquote-vars', ' ;(function () { if(typeof x2 == "undefined"){ x2 = {}; } var iqConfig = ' . CJSON::encode($iqConfig) . '; if(typeof x2.inlineQuotes=="undefined") { x2.inlineQuotes = iqConfig; } else { $.extend(x2.inlineQuotes,iqConfig); } }) ();', CClientScript::POS_HEAD); } parent::init(); }
public function actionAjaxAdd() { if (Yii::app()->request->isAjaxRequest && Yii::app()->user->checkAccess('blockip_admin')) { $postValue = CHtml::encode(strip_tags(Yii::app()->request->getParam('value'))); $pk = CHtml::encode(strip_tags(Yii::app()->request->getParam('pk'))); if ($postValue) { $blockIpModel = BlockIp::model()->find('ip = :ip', array(':ip' => $postValue)); if ($blockIpModel) { # IP уже есть $msg = 'already_exists'; } else { $blockIpModel = new BlockIp(); $blockIpModel->ip = $postValue; $blockIpModel->ip_long = ip2long($postValue); $blockIpModel->date_created = new CDbExpression('NOW()'); if ($blockIpModel->save()) { $msg = 'ok'; } else { $msg = 'save_error'; } } } else { $msg = 'no_value'; } echo CJSON::encode(array('msg' => $msg, 'value' => $postValue, 'pk' => $pk)); Yii::app()->end(); } }