How to call confirm dialog on button Yii2 Action column? - yii2-advanced-app

I am using Kartik/grid. I have this button in action column.How can I have a confirm dialog on clicking it, like in delete ?
[
'class' => 'kartik\grid\ActionColumn',
'template'=>'{statement}',
'controller'=>'statement',
'buttons' => [
'pay' => function($url,$model) {
if($model->sum_balance<>0) {
return Html::a('Statement', $url, ['class'=>'pay btn btn-primary','data-pjax' => '0']);
} else {
return null;
}
},
]
],

hii Kritika555,
'buttons' => [
'pay' => function($url,$model) {
if($model->sum_balance<>0) {
return Html::a('Statement', $url, ['onClick' => 'return confirm("You'r confirmation message?")', 'class'=>'pay btn btn-primary','data-pjax' => '0']);
} else {
return null;
}
},
]

Although Mohan's answer is correct, in Yii2 there is a much more simpler way of making a confirm popup for your buttons or links. Just add data-confirm="Your question here" as a property to any button or a link you want to trigger a confirm box.
'buttons' => [
'pay' => function($url,$model) {
if($model->sum_balance<>0) {
return Html::a('Statement', $url, ['data-confirm'=>"Your confirmation message?", 'class'=>'pay btn btn-primary','data-pjax' => '0']);
} else {
return null;
}
},
]

Related

Yii2 redirecting postman request to a different route in the api rest

I am accessing a route by the postman in an api made in Yii2, but the code that I insert in the action that corresponds to that route is not working. Follow the request print:
postman-request-print
The request return was not meant to be the one in the image, because the code I put in the 'create' action was this:
<?php
namespace app\modules\api\controllers;
use Yii;
use app\modules\pesquisa_mercado\models\PontoDaPesquisa;
class PesquisaPontoController extends \yii\rest\ActiveController
{
public $modelClass = 'app\modules\pesquisa_mercado\models\PesquisaPonto';
public function behaviors()
{
$behaviors = parent::behaviors();
return $behaviors + [
[
'class' => \yii\filters\auth\HttpBearerAuth::className(),
'except' => ['options'],
],
'verbs' => [
'class' => \app\modules\api\behaviors\Verbcheck::className(),
'actions' => [
'index' => ['GET'],
'create' => ['POST'],
'update' => ['PUT'],
'view' => ['GET'],
'delete' => ['DELETE'],
'finalizar-pesquisa' => ['POST'],
],
],
];
}
public function actions()
{
$actions = parent::actions();
unset($actions['update']);
return $actions;
}
public function actionCreate()
{
die("Test"); // test inserted here
}
}
That is, the return was to be 'Test'. For some reason I don't know, the route is being redirected to another place.
I also discovered that the request goes through the getLinks () method present in the PesquisaPonto model:
<?php
namespace app\modules\pesquisa_mercado\models;
class PesquisaPonto extends \yii\db\ActiveRecord implements \yii\web\Linkable
{
/**
* #inheritdoc
*/
public static function tableName()
{
return '{{%pesquisa_ponto}}';
}
/**
* #inheritdoc
*/
public function getLinks() // the requisition also passes through here!
{
return [
Link::REL_SELF => Url::to(['pesquisa-ponto/view', 'id' => $this->id], true),
'index' => Url::to(['pesquisa-ponto'], true)
];
}
}
Also follow the configuration of urlManager:
'urlManager' => [
'class' => 'yii\web\UrlManager',
'enablePrettyUrl' => true,
'showScriptName' => true,
'rules' => [
// Pontos de Pesquisa
// api/pesquisa-ponto
[
'class' => 'yii\rest\UrlRule',
'controller' => [
'api/pesquisa-ponto'
],
'pluralize' => false,
],
],
]
I still haven't found the reason why Yii2 is redirecting the route and not allowing the postman to access the 'create' action...
The actions() method in yii\rest\ActiveController looks like this
public function actions()
{
return [
// ...
'create' => [
'class' => 'yii\rest\CreateAction',
'modelClass' => $this->modelClass,
'checkAccess' => [$this, 'checkAccess'],
'scenario' => $this->createScenario,
],
// ...
];
}
In your implementation of actions() method you are only removing the configuration for update action but the configuration for create action is left untouched. That means that the action is run from the yii\rest\CreateAction not the actionCreate() method of the controller.
To run the action from the PesquisaPontoController::actionCreate() you have to unset the configuration for the create action as well.
public function actions()
{
$actions = parent::actions();
unset($actions['update'], $actions['create']);
return $actions;
}

How get user data with Yii2 bearer authentication?

I need to get the user data to use for the access control. I bearer authentication works fine, the user session is disabled.
public static function findIdentityByAccessToken ($token, $type = null) {
$user = static::findOne(['access_token' => $token, 'status' => self::STATUS_ACTIVE]);
if ( $user ) {
if ( $user->isAccessTokenValid() ) {
$user->last_request = time();
$user->save(false);
return $user;
}
}
return null;
}
The Yii::$app->user->id and Yii::$app->user->getId() return null because the session is disabled.
I need to use it in:
$behaviors['access'] = ['class' => AccessControl::class,
'only' => ['view'],
'rules' => [
[
'actions' => ['view'],
'allow' => false,
'roles' => User::isUserAdmin(Yii::$app->user->getId()),
],
[
'actions' => ['view'],
'allow' => true,
'roles' => User::isUserManager(Yii::$app->user->getId()),
],
],
];
I tried to save the user data or the token in public static variable in the user class, but the variable always null.

Magento 2 Plugins / Interceptors accessing and modifying $this object

I have a plugin that i want to modify functionality of a method within specific class in Magento 2 however am not quite sure on how to access the original object and return the modified data.
Original Method
protected function _initTotals()
{
$source = $this->getSource();
$this->_totals = [];
$this->_totals['subtotal'] = new \Magento\Framework\DataObject(
['code' => 'subtotal', 'value' => $source->getSubtotal(), 'label' => __('Subtotal')]
);
/**
* Add shipping
*/
if (!$source->getIsVirtual() && ((double)$source->getShippingAmount() || $source->getShippingDescription())) {
$this->_totals['shipping'] = new \Magento\Framework\DataObject(
[
'code' => 'shipping',
'field' => 'shipping_amount',
'value' => $this->getSource()->getShippingAmount(),
'label' => __('Shipping & Handling'),
]
);
}
/**
* Add discount
*/
if ((double)$this->getSource()->getDiscountAmount()) {
if ($this->getSource()->getDiscountDescription()) {
$discountLabel = __('Discount (%1)', $source->getDiscountDescription());
} else {
$discountLabel = __('Discount');
}
$this->_totals['discount'] = new \Magento\Framework\DataObject(
[
'code' => 'discount',
'field' => 'discount_amount',
'value' => $source->getDiscountAmount(),
'label' => $discountLabel,
]
);
}
$this->_totals['grand_total'] = new \Magento\Framework\DataObject(
[
'code' => 'grand_total',
'field' => 'grand_total',
'strong' => true,
'value' => $source->getGrandTotal(),
'label' => __('Grand Total'),
]
);
/**
* Base grandtotal
*/
if ($this->getOrder()->isCurrencyDifferent()) {
$this->_totals['base_grandtotal'] = new \Magento\Framework\DataObject(
[
'code' => 'base_grandtotal',
'value' => $this->getOrder()->formatBasePrice($source->getBaseGrandTotal()),
'label' => __('Grand Total to be Charged'),
'is_formated' => true,
]
);
}
return $this;
}
This i have set to have a plugin to modify functionality of method above with di.xml:
<type name="Magento\Sales\Block\Order\Totals">
<plugin disabled="false" name="Harrigo_EverDiscountLabel_Plugin_Magento_Sales_Block_Order_Totals" sortOrder="10" type="Harrigo\EverDiscountLabel\Plugin\Magento\Sales\Block\Order\Totals"/>
</type>
Plugin
class Totals
{
public function after_initTotals(
\Magento\Sales\Block\Order\Totals $subject,
$result
) {
if ((double)$subject->getSource()->getDiscountAmount() != 0 OR $subject->getSource()->getDiscountDescription() != null) {
if ($subject->getSource()->getDiscountDescription()) {
$discountLabel = __('Offer (%1)', $source->getDiscountDescription());
} else {
$discountLabel = __('Offer');
}
$subject->_totals['discount'] = new \Magento\Framework\DataObject(
[
'code' => 'discount',
'field' => 'discount_amount',
'value' => $source->getDiscountAmount(),
'label' => $discountLabel,
]
);
}
return $subject;
}
}
Have used $subject instead of $this within the plugin, this does not work for me however. How do I access the $this object within the plugin to add / overwrite $this->_totals['discount'] and return the updated $this object from within the plugin. I have it working fine with a standard preference but would rather use a plugin if possible.
I think you should check this before implementing above code.
http://devdocs.magento.com/guides/v2.0/extension-dev-guide/plugins.html
As per devdocs for Magento2 protected functions can not be intercepted so We can not use plugins for that.
May be that is causing issue in your case.
Hope this helps!

How to update data using session in codeigniter

This my code in codeigniter but it doesn't update in database, I'm beginner ni codeigniter, how could I fix this error, or what is wrong in my code?
THis is my Controller:
function edit() {
$role = $this->session->userdata('role');
$this->form_validation->set_rules('firstname', 'firstname', 'required|xss_clean');
$this->form_validation->set_rules('lastname', 'lastname', 'required|xss_clean');
if ($this->form_validation->run() == FALSE) {
//set page data
$data['title'] = 'Update Profile';
if($role!=''){
$data['admin'] = $this->M_user->get($this->session->userdata('user_id'));
}else{
$data['admin'] = $this->M_administrator->getAdmin($this->session->userdata('id_admin'));
}
$data['sitename'] = $this->M_website->getName();
$data['content'] = 'admin/myaccount/edit';
//parse template
$this->parser->parse('admin/template', $data);
} else {
if($role!=''){
if ($this->M_user->updateStatus($_POST['user_id'])) {
//SAVE ADMIN ACTION LOG
//save_admin_action(array('module' => Constant::AM_ACCOUNT, 'action' => Constant::AL_EDIT, 'title' => $this->form_validation['username'], 'object_id' => $id));
//redirect page
$this->session->set_flashdata('saved', TRUE);
redirect('admin/myaccount');
}
}else{
if ($this->M_administrator->updateStatus($_POST['id_admin'])) {
//SAVE ADMIN ACTION LOG
//save_admin_action(array('module' => Constant::AM_ACCOUNT, 'action' => Constant::AL_EDIT, 'title' => $this->form_validation['username'], 'object_id' => $id));
//redirect page
$this->session->set_flashdata('saved', TRUE);
redirect('admin/myaccount');
}
}
}
}
This is my model administrator:
function updateStatus($post, $id){
$data = array(
'firstname' => $post['firstname'],
'lastname' => $post['lastname']
);
$this->db->where('id_admin', $id);
if($this->db->update('admin', $data)){
return TRUE;
}else{
return FALSE;
}
}
user Model:
function updateStatus($post, $id){
$data = array(
'firstname' => $post['firstname'],
'lastname' => $post['lastname']
);
$this->db->where('user_id', $id);
if($this->db->update('user', $data)){
return TRUE;
}else{
return FALSE;
}
}
pass firstname and last name to your updatestatus model function if you are not getting that value in model so you are not able to change
print your query using $this->db->last_query(); to get query output and post your query here
Change your where clause to
$this->db->where('id_admin', $post);

How to differentiate oauth social media plugin in YII2

I have a website which using twitter, facebook or google to login to system.
I use oAuth and here is my code.
config
'authClientCollection' => [
'class' => 'yii\authclient\Collection',
'clients' => [
'facebook' => [
'class' => 'yii\authclient\clients\Facebook',
'clientId' => 'asdsad',
'clientSecret' => 'xzxas',
],
'twitter' => [
'class' => 'yii\authclient\clients\Twitter',
'consumerKey' => 'sadsd',
'consumerSecret' => 'dasdasd',
],
],
],
controller
public function actions()
{
return [
'error' => [
'class' => 'yii\web\ErrorAction',
],
'captcha' => [
'class' => 'yii\captcha\CaptchaAction',
'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,
],
'auth' => [
'class' => 'yii\authclient\AuthAction',
'successCallback' => [$this, 'oAuthSuccess'],
],
];
}
public function oAuthSuccess($client) {
// get user data from client
$userAttributes = $client->getUserAttributes();
echo '<pre>';
print_r($userAttributes);
die;
The question is how do i know that which one of social media the user use to log to system?
To differentiate your oauth client you can put some instance condition as:--
public function oAuthSuccess($client) {
$reponse = $client->getUserAttributes();
$session = Yii::$app->session;
$token = $client->accessToken->params['access_token'];
$session->set('token' ,$token);
$id = ArrayHelper::getValue($reponse , 'id');
$session->set('auth_id', $id);
//Facebook Oauth
if($client instanceof \yii\authclient\clients\Facebook){
//Do Facebook Login
}
//Google Oauth
elseif($client instanceof \yii\authclient\clients\GoogleOAuth){
//Do Google Login Condition
}
}
public function oAuthSuccess($client) {
// get user data from client
$userAttributes = $client->getUserAttributes();
if($client->getName() == 'twitter'){
........
}else if($client->getName() == 'facebook'){
.........
}