Opencart Multi Store login with same store customer not others - authentication

I am using opencart Multi store , as per my code we are having up to 10 stores , every store we have customers , the customers who is registered with particular store he can able to login to that store only, if he tries to login with any other store which he not registered there must be a error message like you are not registered with this store or else something else...
as per my code if customer login with other store which not registered he is redirecting to his store only but not login, it should not redirect and he should get error message...
Below is my controller :
<?php
class ControllerAccountLogin extends Controller {
private $error = array();
public function index() {
//echo 44; exit;
$this->load->model('account/customer');
// Login override for admin users
if (!empty($this->request->get['token'])) {
$this->event->trigger('pre.customer.login');
$this->customer->logout();
$this->cart->clear();
unset($this->session->data['wishlist']);
unset($this->session->data['payment_address']);
unset($this->session->data['payment_method']);
unset($this->session->data['payment_methods']);
unset($this->session->data['shipping_address']);
unset($this->session->data['shipping_method']);
unset($this->session->data['shipping_methods']);
unset($this->session->data['comment']);
unset($this->session->data['order_id']);
unset($this->session->data['coupon']);
unset($this->session->data['reward']);
unset($this->session->data['voucher']);
unset($this->session->data['vouchers']);
$customer_info = $this->model_account_customer->getCustomerByToken($this->request->get['token']);
if ($customer_info && $this->customer->login($customer_info['email'], '', true)) {
// Default Addresses
$this->load->model('account/address');
if ($this->config->get('config_tax_customer') == 'payment') {
$this->session->data['payment_address'] = $this->model_account_address->getAddress($this->customer->getAddressId());
}
if ($this->config->get('config_tax_customer') == 'shipping') {
$this->session->data['shipping_address'] = $this->model_account_address->getAddress($this->customer->getAddressId());
}
$this->event->trigger('post.customer.login');
$this->response->redirect($this->url->link('account/account', '', 'SSL'));
}
}
if ($this->customer->isLogged()) {
$this->response->redirect($this->url->link('account/account', '', 'SSL'));
}
$this->load->language('account/login');
$this->document->setTitle($this->language->get('heading_title'));
if (($this->request->server['REQUEST_METHOD'] == 'POST') && $this->validate()) {
//echo $this->config->get('config_store_id'); exit;
if ($this->config->get('config_store_id')) {
// echo 'sravz';
// echo $this->customer->getStoreId(); exit;
if ($this->customer->getStoreId() != 0) {
if ($this->customer->getStoreId() != $this->config->get('config_store_id')) {
$this->load->model('setting/store');
// $store_info = $this->model_setting_store->getStore($this->customer->getStoreId());
$query = $this->db->query("SELECT * FROM " . DB_PREFIX . "store where store_id=".$this->customer->getStoreId()."");
$store_info = $query->row;
$this->response->redirect($store_info['url']);
}
}
}
unset($this->session->data['guest']);
// Default Shipping Address
$this->load->model('account/address');
if ($this->config->get('config_tax_customer') == 'payment') {
$this->session->data['payment_address'] = $this->model_account_address->getAddress($this->customer->getAddressId());
}
if ($this->config->get('config_tax_customer') == 'shipping') {
$this->session->data['shipping_address'] = $this->model_account_address->getAddress($this->customer->getAddressId());
}
// Add to activity log
$this->load->model('account/activity');
$activity_data = array(
'customer_id' => $this->customer->getId(),
'name' => $this->customer->getFirstName() . ' ' . $this->customer->getLastName()
);
$this->model_account_activity->addActivity('login', $activity_data);
// Added strpos check to pass McAfee PCI compliance test (http://forum.opencart.com/viewtopic.php?f=10&t=12043&p=151494#p151295)
if (isset($this->request->post['redirect']) && (strpos($this->request->post['redirect'], $this->config->get('config_url')) !== false || strpos($this->request->post['redirect'], $this->config->get('config_ssl')) !== false)) {
$this->response->redirect(str_replace('&', '&', $this->request->post['redirect']));
} else {
$this->response->redirect($this->url->link('account/account', '', 'SSL'));
}
}
$data['breadcrumbs'] = array();
$data['breadcrumbs'][] = array(
'text' => $this->language->get('text_home'),
'href' => $this->url->link('common/home')
);
$data['breadcrumbs'][] = array(
'text' => $this->language->get('text_account'),
'href' => $this->url->link('account/account', '', 'SSL')
);
$data['breadcrumbs'][] = array(
'text' => $this->language->get('text_login'),
'href' => $this->url->link('account/login', '', 'SSL')
);
$data['heading_title'] = $this->language->get('heading_title');
$data['text_new_customer'] = $this->language->get('text_new_customer');
$data['text_register'] = $this->language->get('text_register');
$data['text_register_account'] = $this->language->get('text_register_account');
$data['text_returning_customer'] = $this->language->get('text_returning_customer');
$data['text_i_am_returning_customer'] = $this->language->get('text_i_am_returning_customer');
$data['text_forgotten'] = $this->language->get('text_forgotten');
$data['entry_email'] = $this->language->get('entry_email');
$data['entry_password'] = $this->language->get('entry_password');
$data['button_continue'] = $this->language->get('button_continue');
$data['button_login'] = $this->language->get('button_login');
if (isset($this->error['warning'])) {
$data['error_warning'] = $this->error['warning'];
} else {
$data['error_warning'] = '';
}
$data['action'] = $this->url->link('account/login', '', 'SSL');
$data['register'] = $this->url->link('account/register', '', 'SSL');
$data['forgotten'] = $this->url->link('account/forgotten', '', 'SSL');
// Added strpos check to pass McAfee PCI compliance test (http://forum.opencart.com/viewtopic.php?f=10&t=12043&p=151494#p151295)
if (isset($this->request->post['redirect']) && (strpos($this->request->post['redirect'], $this->config->get('config_url')) !== false || strpos($this->request->post['redirect'], $this->config->get('config_ssl')) !== false)) {
$data['redirect'] = $this->request->post['redirect'];
} elseif (isset($this->session->data['redirect'])) {
$data['redirect'] = $this->session->data['redirect'];
unset($this->session->data['redirect']);
} else {
$data['redirect'] = '';
}
if (isset($this->session->data['success'])) {
$data['success'] = $this->session->data['success'];
unset($this->session->data['success']);
} else {
$data['success'] = '';
}
if (isset($this->request->post['email'])) {
$data['email'] = $this->request->post['email'];
} else {
$data['email'] = '';
}
if (isset($this->request->post['password'])) {
$data['password'] = $this->request->post['password'];
} else {
$data['password'] = '';
}
$data['column_left'] = $this->load->controller('common/column_left');
$data['column_right'] = $this->load->controller('common/column_right');
$data['content_top'] = $this->load->controller('common/content_top');
$data['content_bottom'] = $this->load->controller('common/content_bottom');
$data['footer'] = $this->load->controller('common/footer');
$data['header'] = $this->load->controller('common/header');
$data['account'] = $this->load->controller('module/account');
if (file_exists(DIR_TEMPLATE . $this->config->get('config_template') . '/template/account/login.tpl')) {
$this->response->setOutput($this->load->view($this->config->get('config_template') . '/template/account/login.tpl', $data));
} else {
$this->response->setOutput($this->load->view('default/template/account/login.tpl', $data));
}
}
protected function validate() {
//echo $this->request->post['email'];exit;
$this->event->trigger('pre.customer.login');
// Check how many login attempts have been made.
$login_info = $this->model_account_customer->getLoginAttempts($this->request->post['email']);
if ($login_info && ($login_info['total'] >= $this->config->get('config_login_attempts')) && strtotime('-1 hour') < strtotime($login_info['date_modified'])) {
$this->error['warning'] = $this->language->get('error_attempts');
}
// Check if customer has been approved.
$customer_info = $this->model_account_customer->getCustomerByEmail($this->request->post['email']);
//print_r($customer_info);exit;
if ($customer_info && !$customer_info['approved']) {
$this->error['warning'] = $this->language->get('error_approved');
}
//print_r( $this->error); exit;
if (!$this->error) {
if (!$this->customer->login($this->request->post['email'], $this->request->post['password'])) {
//echo 44; exit;
// $this->error['warning'] = $this->language->get('error_login');
// $this->model_account_customer->addLoginAttempt($this->request->post['email']);
} else {
$this->model_account_customer->deleteLoginAttempts($this->request->post['email']);
$this->event->trigger('post.customer.login');
}
}
return !$this->error;
}
}
Below is my View :
<?php echo $header; ?>
<div class="container">
<ul class="breadcrumb">
<?php foreach ($breadcrumbs as $breadcrumb) { ?>
<li><?php echo $breadcrumb['text']; ?></li>
<?php } ?>
</ul>
<?php if ($success) { ?>
<div class="alert alert-success"><i class="fa fa-check-circle"></i> <?php echo $success; ?></div>
<?php } ?>
<?php if ($error_warning) { ?>
<div class="alert alert-danger"><i class="fa fa-exclamation-circle"></i> <?php echo $error_warning; ?></div>
<?php } ?>
<div class="row"><?php echo $column_left; ?>
<?php if ($column_left && $column_right) { ?>
<?php $class = 'col-sm-6 no-pad'; ?>
<?php } elseif ($column_left || $column_right) { ?>
<?php $class = 'col-sm-9'; ?>
<?php } else { ?>
<?php $class = 'col-sm-12'; ?>
<?php } ?>
<div id="content" class="<?php echo $class; ?>"><?php echo $content_top; ?>
<div class="panel panel-primary">
<div class="top">
<div class="panel-heading title-heading search-head"><?php echo $heading_title; ?></div>
</div>
<div class="panel-body">
<div class="row">
<!-- <h2></h2>-->
<div class="col-sm-6">
<b style="margin-bottom: 2px; display: block;"><?php echo $text_new_customer; ?></b>
<div class="well left">
<!-- <p><strong><?php echo $text_register; ?></strong></p>-->
<p><?php echo $text_register_account; ?></p>
<!-- <?php echo "Go to Shopping"; ?> --></div>
</div>
<div class="col-sm-6">
<b style="margin-bottom: 2px; display: block;"><?php echo $text_returning_customer; ?></b>
<div class="well">
<!-- <h2><?php echo $text_returning_customer; ?></h2>-->
<p><?php echo $text_i_am_returning_customer; ?></p>
<form action="<?php echo $action; ?>" method="post" enctype="multipart/form-data">
<div class="form-group">
<label class="control-label" for="input-email"> <strong> <?php echo $entry_email; ?></strong></label>
<input type="text" name="email" value="<?php echo $email; ?>" placeholder="<?php echo $entry_email; ?>" id="input-email" class="form-control" />
</div>
<div class="form-group">
<label class="control-label" for="input-password"> <strong> <?php echo $entry_password; ?></strong></label></strong>
<input type="password" name="password" value="<?php echo $password; ?>" placeholder="<?php echo $entry_password; ?>" id="input-password" class="form-control" />
<?php echo $text_forgotten; ?></div>
<input type="submit" value="<?php echo $button_login; ?>" class="btn btn-primary" />
<?php if ($redirect) { ?>
<input type="hidden" name="redirect" value="<?php echo $redirect; ?>" />
<?php } ?>
</form>
</div>
</div>
</div>
</div>
<?php echo $content_bottom; ?></div></div>
<div class="clearfix hidden-sm hidden-md hidden-lg"></div>
<?php echo $column_right; ?>
<div class="hidden-sm hidden-md hidden-lg"><div class="container"><?php echo $account; ?></div></div>
</div>
</div>
<?php echo $footer; ?>

To give back an error message to the customer you must check that the customer is part of the Customer Group assigned to that store. Use this at the start of the validate() method in catalog/controller/account/login.php:
$customer_info = $this->model_account_customer->getCustomerByEmail($this->request->post['email']);
$customerGroupId = isset($customer_info['customer_group_id']) ? $customer_info['customer_group_id'] : -1;
$allowedCustomerGroups = $this->config->get('config_customer_group_display');
if(!is_array($allowedCustomerGroups) || !in_array($customerGroupId, $allowedCustomerGroups)) {
$this->error['warning'] = $this->language->get('error_login');
return false;
}
Remember that this will not take care if your customer logs in into the right store and then goes to another store.
If you want to log customer out when they change store use this code and paste after the $data variable declaration in catalog/controller/common/header.php at around line 90:
if ($this->customer->isLogged() && ($this->config->get('config_store_id') != $this->customer->getStoreId())) {
$this->url->link('account/logout', '', true);
$this->customer->logout();
}
Then
You will have to add this method in the system/library/cart/customer.php file:
public function getStoreId() {
return $this->store_id;
}
Hope this helps :)

Related

Prestashop after submit return page html

Hello I develop a module under Prestashop 1.6 and I am blocked on the submission of a form.
I add in my module a form with the hook "DisplayAdminOrderContentShip" which retrieves a tpl hook_button.tpl which displays my form (button)
relance
here is my tpl:
<div class="panel panel-default">
<div class="panel-heading">
<p>Export commande mecalux</p>
</div>
<div class="panel-body">
<p>Permet de relancer l'export vers Mecalux de la commande</p>
<form method="POST" action="#">
<button type="submit" value="1" id="exportordersubmit" name="exportordersubmit" class="btn btn-default pull-right">
<i class="process-icon-refresh"></i> {l s='Relancer l\'export' mod='exportorders'}
</button>
</form>
</div>
Here is my function:
public function hookDisplayAdminOrderContentShip($params)
{
$order = new Order(Tools::getValue('id_order'));
$status = (int)Configuration::get('EXPORTORDERS_STATUS_TRANSFERED_TO_WMS');
$statusError = (int)Configuration::get('EXPORTORDERS_STATUS_CMD_ERROR');
if (Tools::isSubmit('exportordersubmit')) {
if (isset($order) && (int)$order->valid == 1) {
if ($order->current_state != $status && $order->current_state != $statusError) {
return;
}
if (!$order->valid) {
return;
}
$customer = $order->getCustomer();
$deliveryAddress = new Address($order->id_address_delivery);
$id_country_delivery = $deliveryAddress->getCountryAndState($order->id_address_delivery);
$iso = new Country();
$userXml = [
'id_client' => $customer->id,
'email' => $customer->email,
'livraison' => $deliveryAddress,
'country_code_delivery' => $iso->getIsoById($id_country_delivery['id_country'])
];
$dateOrder = new DateTime($order->date_add);
$orderXml = [
'id' => $order->id,
'sorCode' => $order->reference,
'payment' => $order->payment,
'date' => $dateOrder->format('Y-m-d\TH:i:s') . 'Z',
];
$result = $this->fileXml($userXml, $orderXml, $order->getProducts());
if ((int)$result === 1) {
$order->setCurrentState($statusError, (int)$this->context->employee->id ? (int)$this->context->employee->id : 0);
$html = [
'message' => $this->displayError('Erreur de transmission au WMS'),
];
} else {
if ((int)$order->current_state !== (int)$status) {
$order->setCurrentState($status, (int)$this->context->employee->id ? (int)$this->context->employee->id : 0);
$order->wms_transfered = 1;
$order->save();
$html = [
'message' => $this->displayConfirmation('Transmise au WMS'),
];
}
}
}
}
$this->context->smarty->assign(
array(
'alert' => $html
)
);
return ($this->display(__FILE__, 'views/templates/hook/hook_button.tpl'));
}
and when I click here is the result of my page:
html
normally it should return an alert in the order detail page (admin) I do not see where my problem comes from have any idea?
Thank you for your help.
fetch

Yii2 Dynamic Form

I'm using wbraganca's dynamicform samples codes for mine own project. My code with its corresponding errors are as follows.
Under the view folder
_form.php
<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
use yii\helpers\ArrayHelper;
use frontend\models\Items;
use frontend\models\Employees;
use frontend\models\Departments;
use dosamigos\datepicker\DatePicker;
use wbraganca\dynamicform\DynamicFormWidget;
/* #var $this yii\web\View */
/* #var $model backend\models\Borrow */
/* #var $form yii\widgets\ActiveForm */
$js = '
jQuery(".dynamicform_wrapper").on("afterInsert", function(e, item) {
jQuery(".dynamicform_wrapper .panel-title-address").each(function(index) {
jQuery(this).html("Items: " + (index + 1))
});
});
jQuery(".dynamicform_wrapper").on("afterDelete", function(e) {
jQuery(".dynamicform_wrapper .panel-title-address").each(function(index) {
jQuery(this).html("Items: " + (index + 1))
});
});
';
$this->registerJs($js);?>
<div class="borrow-form">
<?php $form = ActiveForm::begin(['id'=>'dynamic-form']); ?>
<div class="row">
<div class="col-xs-4">
<?= $form->field($model,'dept_id')->dropDownList(
ArrayHelper::map(Departments::find()->all(),'id','dept_name'),
['prompt'=>'select departments'])
?>
</div>
<div class="col-xs-4">
<?=$form->field($model, 'return_date')->widget(
DatePicker::className(), [
'inline' => false,
'clientOptions' => [
'autoclose' => true,
'format' => 'yyyy-mm-dd'
]
]);?>
</div>
</div>
<div class="padding-v-md">
<div class="line line-dashed"></div>
</div>
<!-- beginning of dynamic form -->
<?php DynamicFormWidget::begin([
'widgetContainer' => 'dynamicform_wrapper', // required: only alphanumeric characters plus "_" [A-Za-z0-9_]
'widgetBody' => '.container-items', // required: css class selector
'widgetItem' => '.item', // required: css class
'limit' => 10, // the maximum times, an element can be added (default 999)
'min' => 1, // 0 or 1 (default 1)
'insertButton' => '.add-item', // css class
'deleteButton' => '.remove-item', // css class
'model' => $modelsAddress[0],
'formId' => 'dynamic-form',
'formFields' => [
'items_id',
'unit',
'request',
'allowed',
],
]); ?>
<div class="panel panel-default">
<div class="panel-heading">
<h4><i class="glyphicon glyphicon-envelope"></i> Items
</h4>
</div>
<div class="panel-body">
<div class="container-items"><!-- widgetBody -->
<?php foreach ($modelsAddress as $i => $modelAddress): ?>
<div class="item panel panel-default"><!-- widgetItem -->
<div class="panel-heading">
<h3 class="panel-title pull-left">Items</h3>
<div class="pull-right">
<button type="button" class="add-item btn btn-success btn-xs"><i class="glyphicon glyphicon-plus"></i></button>
<button type="button" class="remove-item btn btn-danger btn-xs"><i class="glyphicon glyphicon-minus"></i></button>
</div>
<div class="clearfix"></div>
</div>
<div class="panel-body">
<?php
// necessary for update action.
if (! $modelAddress->isNewRecord) {
echo Html::activeHiddenInput($modelAddress, "[{$i}]id");
}
?>
<div class="row">
<div class="col-xs-4">
<?= $form->field($modelAddress, "[{$i}]items_id")->dropDownList(
ArrayHelper::map(Items::find()->all(),'id','item_name'),
['prompt'=>'select items']) ?>
</div>
<div class="col-xs-2">
<?= $form->field($modelAddress, "[{$i}]unit")->textInput(['maxlength' => true]) ?>
</div>
<div class="col-xs-2">
<?= $form->field($modelAddress, "[{$i}]request")->textInput(['maxlength' => true]) ?>
</div>
<div class="col-xs-2">
<?= $form->field($modelAddress, "[{$i}]allowed")->textInput(['maxlength' => true]) ?>
</div>
<div class="col-xs-2">
<?= $form->field($modelAddress, "[{$i}]unit_price")->textInput(['maxlength' => true]) ?>
</div>
</div><!-- .row -->
</div>
</div>
<?php endforeach; ?>
</div>
</div>
</div><!-- .panel -->
<?php DynamicFormWidget::end(); ?>
<!-- end dynamic form-->
<div class="row">
<div class="col-xs-5">
<?= $form->field($model,'emp_id')->dropDownList(
ArrayHelper::map(Employees::find()->all(),'id','emp_name'),
['prompt'=>'select employees'])
?>
<?= $form->field($model,'head_id')->dropDownList(
ArrayHelper::map(Employees::find()->all(),'id','emp_name'),
['prompt'=>'select dept heads'])
?>
<?= $form->field($model,'man_id')->dropDownList(
ArrayHelper::map(Employees::find()->all(),'id','emp_name'),
['prompt'=>'select stoke managers'])
?>
<?= $form->field($model,'keeper_id')->dropDownList(
ArrayHelper::map(Employees::find()->all(),'id','emp_name'),
['prompt'=>'select stoke keepers'])
?>
</div>
<div class="col-xs-5">
<?=$form->field($model, 'emp_date')->widget(
DatePicker::className(), [
'inline' => false,
'clientOptions' => [
'autoclose' => true,
'format' => 'yyyy-mm-dd'
]
]);?>
<?=$form->field($model, 'head_date')->widget(
DatePicker::className(), [
'inline' => false,
'clientOptions' => [
'autoclose' => true,
'format' => 'yyyy-mm-dd'
]
]);?>
<?=$form->field($model, 'man_date')->widget(
DatePicker::className(), [
'inline' => false,
'clientOptions' => [
'autoclose' => true,
'format' => 'yyyy-mm-dd'
]
]);?>
<?=$form->field($model, 'keeper_date')->widget(
DatePicker::className(), [
'inline' => false,
'clientOptions' => [
'autoclose' => true,
'format' => 'yyyy-mm-dd'
]
]);?>
</div>
</div>
<div class="form-group">
<?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
</div>
<?php ActiveForm::end(); ?>
The create action under the controller
public function actionCreate()
{
$model = new Borrow();
$modelsAddress = [new Borrow];
if ($model->load(Yii::$app->request->post())) {
$modelsAddress = Model::createMultiple(Borrow::classname());
Model::loadMultiple($modelsAddress, Yii::$app->request->post());
// validate all models
$valid = $model->validate();
$valid = Model::validateMultiple($modelsAddress) && $valid;
if ($valid) {
$transaction = \Yii::$app->db->beginTransaction();
try {
if ($flag = $model->save(false)) {
foreach ($modelsAddress as $modelAddress) {
$modelAddress->id = $model->id;
if (! ($flag = $modelAddress->save(false))) {
$transaction->rollBack();
break;
}
}
}
if ($flag) {
$transaction->commit();
return $this->redirect(['view', 'id' => $model->id]);
}
} catch (Exception $e) {
$transaction->rollBack();
}
}
}
return $this->render('create', [
'model' => $model,
'modelsAddress' => (empty($modelsAddress)) ? [new Address] : $modelsAddress
]);
}
The Model Class under the Model Folder
<?php
namespace frontend\models;
use Yii;
use yii\helpers\ArrayHelper;
class Model extends \yii\base\Model
{
/**
* Creates and populates a set of models.
*
* #param string $modelClass
* #param array $multipleModels
* #return array
*/
public static function createMultiple($modelClass, $multipleModels = [])
{
$model = new $modelClass;
$formName = $model->formName();
$post = Yii::$app->request->post($formName);
$models = [];
if (! empty($multipleModels)) {
$keys = array_keys(ArrayHelper::map($multipleModels, 'id', 'id'));
$multipleModels = array_combine($keys, $multipleModels);
}
if ($post && is_array($post)) {
foreach ($post as $i => $borrow) {
if (isset($borrow['id']) && !empty($borrow['id']) && isset($multipleModels[$borrow['id']])) {
$models[] = $multipleModels[$borrow['id']];
} else {
$models[] = new $modelClass;
}
}
}
unset($model, $formName, $post);
return $models;
}
}
It gives the following error when I run my code:
PHP Fatal Error – yii\base\ErrorException Class 'frontend\controllers\Model' not found as shown below.
It looks like you have not namespaced frontend\models\Model in the controller.
Add there at the beginning:
use frontend\models\Model;

Yii 2.0 hidden field value not modifiable using javascript

In my model I have a hidden field.I am modifying its value using javascript (jQuery).But when I submit the form to model, it still contains its initial value instead of values modified via javascript.I have checked whether javascript is modifying the values, and is confirmed that values are being modified.But when form is submitted it is sending initial values.
Code is given below
<?php
/*Model -- wrong_answers is my hidden field*/
namespace app\models;
use yii;
use yii\db;
use yii\base\Model;
use yii\web\UploadedFile;
class QuestionModel extends Model
{
public $quiz_id = null;
public $question = '';
public $choices = '';
public $explanation ="";
public $hints = array();
public $correct_answer = "";
public $wrong_answers = '{}';//when populating from already entered data use {"a":"as"} format instead of {'a':'as'}
public $wrong_answer = "";
public function rules()
{
return [
[['quiz_id'], 'safe'] ,
[['question'], 'required'] ,
[['correct_answer'], 'required'] ,
[['wrong_answers'], 'safe'] ,
[['wrong_answer'], 'safe'] ,
[['explanation'],'required']
];
}
public function get_quiz($quiz_id) {
$ret = array();
$command = Yii::$app->db->createCommand("CALL get_quiz(:qz_id)");
$command->bindParam(":qz_id", $this->quiz_id);
$result = $command->queryAll();
if(sizeof($result) > 0) {
$ret = $result[0] ;
}
return $ret;
}
public function save_question() {
$ret = false;
//echo "quiz- id is ".$this->quiz_id;
$quiz_details = $this->get_quiz($this->quiz_id);
if(sizeof($quiz_details)) {
$quiz_data = $quiz_details['quiz_data'];
$quiz_data = json_decode($quiz_data);
$choices = [];
echo $this->wrong_answers;
exit;
$wrong_answers_array = json_decode($this->wrong_answers);
if($this->wrong_answer)
array_push($wrong_answers_array, $this->wrong_answer);
print_r($wrong_answers_array);
exit;
foreach($wrong_answers_array as $wr_ans) {
array_push($choices,array('choice'=>$wr_ans));
}
$question_data = array('question'=>$this->question,'explanation'=>$this->explanation,'choices'=>$choices);
$ret = false;
}
return $ret;
}
public function getHint($key) {
return $this->hints[$key];
}
}
Controller - actionAdd_question is the action
<?php
namespace app\controllers;
use Yii;
use yii\filters\AccessControl;
use yii\web\Controller;
use yii\filters\VerbFilter;
use app\models\QuizModel;
use app\models\QuestionModel;
use yii\web\UploadedFile;
global $username;
class QuizController extends Controller
{
public function behaviors()
{
return [
'access' => [
'class' => AccessControl::className(),
'only' => ['logout'],
'rules' => [
[
'actions' => ['logout'],
'allow' => true,
'roles' => ['#'],
],
],
],
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'logout' => ['post'],
],
],
];
}
public function actions()
{
return [
'error' => [
'class' => 'yii\web\ErrorAction',
],
'captcha' => [
'class' => 'yii\captcha\CaptchaAction',
'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,
],
];
}
public function actionEntry()
{
}
public function actionView_all() {
$request = Yii::$app->request;
$layout_params=array(
'username'=>'admin',
'sidebar_menu1_class' =>'active',
'sidebar_menu12_class' =>'active',
'dash_title' => 'Courses',
'dash_sub_title'=>'View all'
);
$message = '';
$data = array();
$layout_params['scripts'] = array("view-all-modules.js");
/*$model = new ViewAllCompaniesModel();
$pagination_data = $model->getTotalCompanies();
$layout_params['js_variables'] = array(
'totalCompanyPages'=>$pagination_data['total_page_count'],
'csrfToken' => "'".$request->csrfToken."'" ,
'csrfTokenName' => "'".$request->csrfParam."'"
);
*/
return $this->render('view-all-modules', [
'layout_params'=>$layout_params,
'message' =>$message,
'data' =>$data
]);
}
public function actionAdd() {
$layout_params=array(
'username'=>'admin',
'sidebar_menu1_class' =>'active',
'sidebar_menu12_class' =>'active',
'dash_title' => 'Quiz',
'dash_sub_title'=>'Add new quiz'
);
$message = array();
$request = Yii::$app->request;
$proceed = true;
$parent_course_id = null;
$req_params = $_POST;
$layout_params['scripts'] = array("add-quiz.js");
$model = new QuizModel();
if(!$model->quiz_id) {
if ($model->load($request->post()) && $model->validate()) {
$params = $request->post();
$model->save_quiz();
$message['title'] = 'Wow !';
$message['body'] = 'Successfully added quiz '.$model->quiz_title;
} else {
}
} else {
}
return $this->render('add-quiz', ['model' => $model,
'layout_params'=>$layout_params,
'message' =>$message
]);
//return $this->render('add-company',$data);
}
public function actionSave() {
//print_r($_POST);
}
public function actionAdd_question() {
print_r($_POST);
$layout_params=array(
'username'=>'admin',
'sidebar_menu1_class' =>'active',
'sidebar_menu12_class' =>'active',
'dash_title' => 'Quiz',
'dash_sub_title'=>'Add question'
);
$request = Yii::$app->request;
$message = array();
$layout_params['scripts'] = array("add-question.js");
$model = new QuestionModel();
if($request->get('q_id')) {
$model->quiz_id = $request->get('q_id');
if ($model->load($request->post()) && $model->validate()) {
$model->save_question();
} else {
echo "yo yo";
}
return $this->render('add-question', ['model' => $model,
'layout_params'=>$layout_params,
'message' =>$message
]);
} else {
}
}
public function actionIndex()
{
$data = array(
'layout_params'=>array(
'username'=>'admin',
'sidebar_menu11_class' =>'active'
)
);//
}
public function actionLogout()
{
Yii::$app->user->logout();
return $this->goHome();
}
}
View
/*Assigning the parameters to be accessible by layouts*/
foreach($layout_params as $layout_param => $value) {
$this->params[$layout_param] = $value;
}
?>
<div class="form-group">
</div>
<div class="col-md-12">
<div class="box box-primary">
<div class="box-header">
<h3 class="box-title">Add Question</h3>
</div><!-- /.box-header -->
<!-- form start -->
<?php $form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']]); ?>
<input type = 'hidden' id = 'test' name = 'test' />
<div class="box-body">
<?php if(isset($message)&&sizeof($message)): ?>
<div class="form-group">
<div class="callout callout-info alert-dismissible">
<h4><?php if(isset($message['title']))echo $message['title'];?></h4>
<p>
<?php if(isset($message['body']))echo $message['body'];?>
</p>
</div>
</div>
<?php endif;?>
<div class="form-group">
<?= $form->field($model, 'question')->textInput(array('class'=>'form-control')); ?>
</div>
<div class="form-group">
<?= $form->field($model, 'correct_answer')->textInput(array("class"=>"form-control",'id'=>'correct_answer')); ?>
<?= Html::activeHiddenInput($model, 'wrong_answers',array('id'=>'wrong_answers')) ;?>
<?= Html::activeHiddenInput($model, 'quiz_id',array('id'=>'quiz_id')) ;?>
</div>
<div class="form-group">
<?= $form->field($model, 'wrong_answer')->textInput(array("class"=>"form-control ",'id'=>'wrong_answer')); ?>
<button id = 'add-answer' type = "button">Add Another</button>
<?= Html::activeHiddenInput($model, 'wrong_answers',array('id'=>'wrong_answers')) ;?>
<?= Html::activeHiddenInput($model, 'quiz_id',array('id'=>'quiz_id')) ;?>
</div>
<div class="form-group" id ='wrong-group'>
<h3>Wrong Answers</h3>
<!-- The following dummy html is used for generating html inside javascript -->
<ul class="edit-list-dummy" id ="edit-list-dummy">
<li> <button class="btn btn-danger" id = 'dummy-wrong-ans-delete' onClick = "deleteWrongAnswer(this.name)" type ="button">Delete</button> <span id ='dummy-wrong-answer'>Hello I am a wrong answer here</span>
</ul>
<ul class="edit-list" id = 'wrong-answers'>
</ul>
</div>
<div class="form-group">
<?= $form->field($model, 'explanation')->textArea(array("class"=>"form-control",'id'=>'explanation')); ?>
</div>
</div><!-- /.box-body --> <div class="box-footer">
<?= Html::submitButton('Save Question', ['class' => 'btn btn-primary','onclick'=>'this.preventDefault']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
</div>
Javascript -#wrong_answers is my hidden input id
var wrongAnswers = {};//{1:answer1,2:answer2...};
var randCount = 0;//radom count for setting as wrongAnswers attribute
//initialise wrong answers json from database
$(document).ready(function() {
console.log($('#wrong_answers').val());
wrongAnswers = jQuery.parseJSON($('#wrong_answers').val());
console.log(wrongAnswers);
$('#add-answer').click(function() {
var wrongAns = $('#wrong_answer').val().trim();
if(wrongAns) {
wrongAnswers[randCount] = wrongAns;
randCount++;
generateWrongAnswers();
$('#wrong_answer').val("");
// alert($('#wrong_answers').val());
}
});
generateWrongAnswers();
});
function generateWrongAnswers() {
$('#wrong-group').hide();
var html = '';
for(var wrongIdx in wrongAnswers) {
//console.log("w is ".wrongAnsIdx);
$('#dummy-wrong-answer').html(wrongAnswers[wrongIdx]);
$('#dummy-wrong-ans-delete').attr('name',wrongIdx);
html += $('#edit-list-dummy').html();
}
if(html) {
$('#wrong-group').show();
$('#wrong-answers').html(html);
}
var jsonData = JSON.stringify(wrongAnswers);
$('#wrong_answers').val(jsonData);
// $('#test').val(jsonData);
//$('#correct_answer').val("Mallu");
// alert($('#wrong_answers').val());
}
function deleteWrongAnswer(idx) {
delete wrongAnswers[idx];
generateWrongAnswers() ;
}
Finall solved it. The issue is that, I accidentally included two hidden input fields with same id.Removed one and solved

yii modal dialog login

I've been looking all over the internet and I can't seem to find the solution to just a simple login via header. I tried all sorts of way. The problem I have right now just reloads every time i hit login. It's only when I go to ?r=site/login it'll let me login. Is there some kind of controller for headers!??! Not sure what is wrong anymore.
Right now i have this in my header:
<?php $this->beginWidget(
'bootstrap.widgets.TbModal',
array('id' => 'login')
); ?>
<?php
$model=new LoginForm;
$this->renderPartial('//site/login', array('model'=>$model));
?>
<?php $this->endWidget(); ?>
//stuff here
<?php $this->widget(
'bootstrap.widgets.TbButton',
array(
'label' => 'Signin',
'type' => 'warning',
'htmlOptions' => array(
'data-toggle' => 'modal',
'data-target' => '#login',
),
)
);
?>
And then in site/login:
<div class="spacing">
<div class="form">
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'login-form',
'enableClientValidation'=>true,
'clientOptions'=>array(
'validateOnSubmit'=>true,
),
)); ?>
<div class="form" id="login-form">
<div class="login-container">
<div class="login-header">
<h1 title="login">Sign In</h1>
</div>
<div class="login-form">
<div class="input-position">
<?php echo $form->labelEx($model,'Email',array('class'=>'span3','style'=>'text-align:left')); ?>
<?php echo $form->textField($model,'email', array('class'=>'span3')); ?>
<?php echo $form->error($model,'email'); ?>
</div>
<div class="input-position">
<?php echo $form->labelEx($model,'password',array('class'=>'span3','style'=>'text-align:left')); ?>
<?php echo $form->passwordField($model,'password',array('class'=>'span3',)); ?>
<?php echo $form->error($model,'password'); ?>
</div>
<div class="input-position ">
<div class="rememberMe">
<?php echo $form->checkBox($model,'rememberMe'); ?>
<?php echo $form->label($model,'rememberMe'); ?>
<?php echo $form->error($model,'rememberMe'); ?>
</div>
</div>
<div class="row buttons">
<?php echo CHtml::submitButton('Login'); ?>
</div>
<?php $this->endWidget(); ?>
</div>
</div>
</div>
</div>
</div>
controller
public function actionLogin()
{
$model=new LoginForm;
// if it is ajax validation request
if(isset($_POST['ajax']) && $_POST['ajax']==='login-form')
{
echo CActiveForm::validate($model);
Yii::app()->end();
}
// collect user input data
if(isset($_POST['LoginForm']))
{
$model->attributes=$_POST['LoginForm'];
// validate user input and redirect to the previous page if valid
if($model->validate() && $model->login())
$this->redirect(Yii::app()->user->returnUrl);
}
// display the login form
$this->render('login',array('model'=>$model));
}
As per my understanding, please keep your login script inside some loop like this to escape it from reloading every time.
if(Yii::app()->user->isGuest and (Yii::app()->controller->id=='site' and Yii::app()->controller->action->id = 'login')){
$this->beginWidget('bootstrap.widgets.TbModal', array('id' => 'login'));
---
$this->endWidget();
}else{
// keep some log out or other script here.
}
Here is the login what i have implemented on Modal login style:
Component/Header:
<?php
Yii::import('zii.widgets.CPortlet');
class Header extends CPortlet
{
protected function renderContent()
{
$this->render('Header');
}
}
Components/view/Header.php
<?php if(Yii::app()->user->isGuest){?>
<?php echo TbHtml::link('<i class="sign-in"></i>Sign in', '#', array(
'data-toggle' => 'modal',
'data-target' => '#loginModal',
));?>
<?php } else{ echo 'Hi!'.$user; } ?>
In View/Layout/Main.php
<?php
$model = new LoginForm;
$this->widget('bootstrap.widgets.TbModal', array(
'id' => 'loginModal',
'header' => '<h3 id="loginModal">Sign In</h3>',
'content'=> $this->renderPartial('userlogin',array('model'=>$model),true),
'remote' => $this->createUrl('site/userlogin'),
'onShow'=>'function(){$("#login-form")[0].reset(); }',
'show'=>false,)); ?>
View/Site/Userlogin.php
<?php $form = $this->beginWidget('bootstrap.widgets.TbActiveForm', array(
'id'=>'login-form',
//'helpType'=>'help-none',
'action'=>Yii::app()->createUrl('userlogin'),
//'enableAjaxValidation' => false,
'enableClientValidation'=>true,
'clientOptions' => array(
'validateOnSubmit' => true,
'validateOnChange'=>false,
'afterValidate' => 'js:function(form, data, hasError) {
if (!hasError){
str = $("#login-form").serialize() + "&ajax=login-form";
$.ajax({
type: "POST",
url: "' . Yii::app()->createUrl('site/userlogin') . '",
data: str,
dataType: "json",
beforeSend : function() {
$("#login").attr("disabled",true);
},
success: function(data, status) {
if(data.authenticated)
{
window.location = data.redirectUrl;
}
else
{
$.each(data, function(key, value) {
var div = "#"+key+"_em_";
$(div).text(value);
$(div).show();
});
$("#login").attr("disabled",false);
}
},
});
return false;
}
}',
),
));?>
<?php echo $form->textFieldControlGroup($model,'username',array('span'=>5,'maxlength'=>255,'required'=>true)); ?>
<?php echo $form->passwordFieldControlGroup($model,'password',array('span'=>5,'maxlength'=>255,'required'=>true)); ?>
<?php echo TbHtml::submitbutton('Sign In',array('class'=>'btn btn-primary')); ?>
<?php $this->endWidget(); ?>
This will Authenticate via Ajax
SiteController:
$model=new LoginForm;
// if it is ajax validation request
if(isset($_POST['ajax']) && $_POST['ajax']==='login-form')
{
$errors = CActiveForm::validate($model);
if ($errors != '[]')
{
echo $errors;
Yii::app()->end();
}
}
if(isset($_POST['LoginForm']))
{
$model->attributes=$_POST['LoginForm'];
// validate user input and redirect to the previous page if valid
if ($model->validate() && $model->login()) {
if (isset($_POST['ajax']) && $_POST['ajax'] === 'login-form') {
$user_id = Yii::app()->user->id;
$arr = array();
$record = Users::model()->findByPk($user_id);
if ($record) {
echo CJSON::encode(array( 'authenticated' => true,
'redirectUrl' => CController::createUrl('users/trainerprofile'),
"id" => $record->id,));
Yii::app()->end();
}
}

yii modal box form validation

I am using yii framework for my website. I have a signup form in modal box. If i submit the form without fill the validation errors should show within the modal box without refresh. But now it redirects to some other page. How can i show the validation errors within the modal box in the same page?
This is the code that i have used for sign up view
<?php
$model=new SignupForm;
$form=$this->beginWidget('CActiveForm', array(
'id'=>'signup-form',
'enableAjaxValidation'=>true,
'action'=>'site/signup'
));
?>
<?php echo $form->errorSummary($model); ?>
<?php echo $form->textField($model,'name',array('value'=>'Enter Your Name', 'onclick'=>'javascript:this.value=""', 'onblur'=> 'this.value = ( this.value == "" ) ? "Enter Your Name" : this.value;')); ?><br />
<?php echo $form->textField($model,'email',array('value'=>'Enter Your Email ID', 'onclick'=>'javascript:this.value=""', 'onblur'=> 'this.value = ( this.value == "" ) ? "Enter Your Email ID" : this.value;')); ?><br />
<?php echo $form->textField($model,'phone',array('value'=>'Telephone', 'onclick'=>'javascript:this.value=""', 'onblur'=> 'this.value = ( this.value == "" ) ? "Telephone" : this.value;')); ?><br />
<!--<input type="text" value="username" onClick="this.value=''"/><br/>
<input type="password" value="Password" onClick="this.value=''"/> -->
<div class="d-login"><?php echo CHtml::submitButton('Submit'); ?>
<?php /*?><input type="image" alt="Login" title="Login" src="<?php echo Yii::app()->request->baseUrl; ?>/images/signup.png"/><?php */?>
</div>
<?php $this->endWidget(); ?>
The code in controller:
public function actionSignup()
{
$model=new SignupForm;
// if it is ajax validation request
if(isset($_POST['ajax']) && $_POST['ajax']==='signup-form')
{
$model->attributes=$_POST['SignupForm'];
echo CActiveForm::validate($model);
Yii::app()->end();
}
// collect input data
if(isset($_POST['SignupForm']))
{
$model->attributes=$_POST['SignupForm'];
$name=$model->name;
$email=$model->email;
$phone=$model->phone;
$newsletter = new Newsletter();
if($model->validate())
{
//insert data
$newsletter->varName = $name;
$newsletter->varEmail = $email;
$newsletter->varPhone = $phone;
if($newsletter->save()) {
$url = Yii::app()->getBaseUrl();
Yii::app()->getRequest()->redirect($url);
}
}
}
$this->render('signup',array('model'=>$model));
}
You have to use ajax and renderPartial if you want to validate a model inside a dialog modal box. below is an untested code.(From this link )
in your views/signup.php
<div class="form">
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'signup-form',
'enableAjaxValidation'=>false,
));
?>
<?php echo $form->errorSummary($model); ?>
<?php echo $form->textField($model,'name',array('value'=>'Enter Your Name', 'onclick'=>'javascript:this.value=""', 'onblur'=> 'this.value = ( this.value == "" ) ? "Enter Your Name" : this.value;')); ?><br />
<?php echo $form->textField($model,'email',array('value'=>'Enter Your Email ID', 'onclick'=>'javascript:this.value=""', 'onblur'=> 'this.value = ( this.value == "" ) ? "Enter Your Email ID" : this.value;')); ?><br />
<?php echo $form->textField($model,'phone',array('value'=>'Telephone', 'onclick'=>'javascript:this.value=""', 'onblur'=> 'this.value = ( this.value == "" ) ? "Telephone" : this.value;')); ?><br />
<div class="d-login">
<?php echo CHtml::submitButton('Submit'); ?>
</div>
<?php $this->endWidget(); ?>
</div>
In your controller
public function actionSignup()
{
$model=new SignupForm;
if(isset($_POST['SignupForm']))
{
$model->attributes=$_POST['SignupForm'];
$name=$model->name;
$email=$model->email;
$phone=$model->phone;
$newsletter = new Newsletter();
if($model->save())
{
//insert data
$newsletter->varName = $name;
$newsletter->varEmail = $email;
$newsletter->varPhone = $phone;
if($newsletter->save())
{
if (Yii::app()->request->isAjaxRequest)
{
echo CJSON::encode(array(
'status'=>'success',
));
exit;
}
else
{
$url = Yii::app()->getBaseUrl();
Yii::app()->getRequest()->redirect($url);
}
}
}
if (Yii::app()->request->isAjaxRequest)
{
echo CJSON::encode(array(
'status'=>'failure',
'div'=>$this->renderPartial('signup', array('model'=>$model), true)));
exit;
}
else
$this->render('signup',array('model'=>$model,));
}
And finally in your view file where you want to display the signup modal box
<?php echo CHtml::link('Signup', "", // the link for open the dialog modal
array(
'style'=>'cursor: pointer; text-decoration: underline;',
'onclick'=>"{doSignup(); $('#dialogSignup').dialog('open');}"));?>
<?php
$this->beginWidget('zii.widgets.jui.CJuiDialog', array( // the dialog
'id'=>'dialogSignup',
'options'=>array(
'title'=>'Signup',
'autoOpen'=>false,
'modal'=>true,
'width'=>550,
'height'=>470,
),
));?>
<div class="divForForm"></div>
<?php $this->endWidget();?>
<script type="text/javascript">
function doSignup()
{
<?php echo CHtml::ajax(array(
'url'=>array('site/signup'),
'data'=> "js:$(this).serialize()",
'type'=>'post',
'dataType'=>'json',
'success'=>"function(data)
{
if (data.status == 'failure')
{
$('#dialogSignup div.divForForm').html(data.div);
$('#dialogSignup div.divForForm form').submit(doSignup);
}
else
{
window.location.href =".Yii::app()->getBaseUrl().";
}
} ",
))?>;
return false;
}
</script>
You should define the validation rules in signup model.. Or paste your sign up model here..