Magento 2 ; Unable to pass custom params into the Save Button Of a UI Form - magento2

I want to pass a value/params via the save button of my ui adminform.
i tried this:
public function getButtonData()
{
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$request = $objectManager->get('Magento\Framework\App\RequestInterface');
$id = $request->getParam('id');
return
[
'label' => __('Save'),
'class' => 'save primary',
'on_click' => '',
'sort_order' => 80,
'data_attribute' => [
'mage-init' => [
'Magento_Ui/js/form/button-adapter' => [
'actions' => [
[
'targetName' => 'thechateau_magenest_bookable_save',
'actionName' => 'save',
'params' => [
true,
['multidome_id' =>$id],
]
]
]
]
],
]
];
}
I can indeed see the values in the save button of the phtml page.
<button id="save" title="Save" type="button" class="action- scalable save primary" data-mage-init="{"Magento_Ui\/js\/form\/button-adapter":{"actions":[{"targetName":"thechateau_magenest_bookable_save","actionName":"save","params":[true,{"multidome_id":"1"}]}]}}" data-ui-id="save-button" >
<span>Save</span>
</button>
however when i try to retreive these values it comes up null.
$request = $this->_objectManager->create('Magento\Framework\App\RequestInterface');
$multiDome = $request->getParam('multidome_id');
I also tried to add it as part of the URL of the save button but it does not even show up on this:
public function getSaveUrl()
{
return $this->getUrl('*/*/save',['param'=>'value']);
}

Related

How to run controller action as ajax in yii2

I have created a grid called 'Status' in yii2-advanced application.
I have added a custom button in backend/views/status/index.php that is working and calling respective controller action.
My customization is as follows :
[ 'class' => 'yii\grid\ActionColumn',
'template' => '{view} {update} {delete} {status/custom}',
'buttons' => [
'status/custom' => function ($url)
{
return Html::a( 'Custom', $url,
[
'title' => 'Custom',
'data-pjax' => '0',
]
);
},
],
],
Now I want that the controller action will be call using ajax without page redirect or load.
How to call actionCustom() using ajax on click Custom button?
Resolve it by using modal.
use yii\bootstrap\Modal;
use johnitvn\ajaxcrud\CrudAsset;
Html::a('Custom', ['custom'], ['role'=>'modal-remote', 'title'=>'Custom']);
In the bottom of the page..
<?php Modal::begin([
"id"=>"ajaxCrudModal",
"footer"=>"",// always need it for jquery plugin
])?>
<?php Modal::end(); ?>
In Controller
use \yii\web\Response;
In the action of controller
$request = Yii::$app->request;
if($request->isAjax){
/*
* Process for ajax request
*/
Yii::$app->response->format = Response::FORMAT_JSON;
if($request->isGet){
return [
'title'=> "Title",
'content'=>$this->renderAjax('
'model' => $yourModel
]),
'footer'=> Html::button('Close',['class'=>'btn btn-default pull-left','data-dismiss'=>"modal"]).
Html::button('Save',['class'=>'btn btn-primary','type'=>"submit"])
];
}else if($model->load($request->post()) && $model->save()){
return [
'forceReload'=>'#crud-datatable-pjax',
'title'=> "Title",
'content'=>'<span class="text-success">Textspan>',
'footer'=> Html::button('Close',['class'=>'btn btn-default pull-left','data-dismiss'=>"modal"]).
Html::a('Create new',['create', 'id'=>$id],['class'=>'btn btn-primary','role'=>'modal-remote'])
];
}else{
...
}else{
...
}

yii2: Undefined variable: model

I am just starting Yii2 framework.
I want to create a dropdown list which is 1 to 10 and a submit button
Once select the option and click the button should go to next page to show the number I choose.
In my view file : index.php
use yii\widgets\ActiveForm;
<?php $form = ActiveForm::begin(); ?>
<?= $form->field($model, 'QTY')->dropDownList(range(1, 10)) ?>
<?= Html::submitButton('Buy', ['class' => 'btn btn-primary']) ?>
<?php ActiveForm::end(); ?>
Then when I go to the page it gave me 'Undefined variable: model' at dropdown list there.
What should I do to make it correct?
And what is the different between Html and CHtml?
Thanks.
this code is form.php not index.php.
because we can see, there are active form.
your model is undefined maybe you write the wrong code
this is example of controller index.php
public function actionIndex()
{
$searchModel = new PersediaanBarangSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
Html and Chtml is the same
in Yii1=CHtml
in Yii2=Html
This is ment to be pagination? If yes use default functionality of the grid view.
This goes to controller:
$query = Post::find()->where(['status' => 1]);
$provider = new ActiveDataProvider([
'query' => $query,
'pagination' => [
'pageSize' => 10,
],
'sort' => [
'defaultOrder' => [
'created_at' => SORT_DESC,
'title' => SORT_ASC,
]
],
]);
return $this->render('path_to_view',['dataProvider'=>$provider]);
Read more
This goes to view:
GridView::widget([
'dataProvider' => $dataProvider,
'columns' => [
'id',
'name',
'created_at:datetime',
// ...
],
]);
Read more
Actually you model is not loaded, Please check below example.
public function actionIndex($id = Null)
{
$data=array();
$data['model'] = !empty($id) ? \app\models\YourModel::findOne($id) : new \app\models\YourModel();
return $this->render('index', $data);
}

Yii2 Modal Dialog on Gridview update button not load the update form

With reference to How to implement Yii2 Modal Dialog on Gridview view and update button?. I did my code below, but it popups a window with no update form. could anyone please let me know the correct code? (i use Kartik Gridview)
This is the code for column:
['class' => '\kartik\grid\ActionColumn',
'template'=>'{update}{delete}{view}',//{view}'//{view}{delete}',
'headerOptions' => ['width' => '20%', 'class' => 'activity- update-link',],
'contentOptions' => ['class' => 'padding-left-5px'],
'buttons' => [
'update' => function ($url, $model, $key) {
return Html::a('<span class="glyphicon glyphicon-pencil"></span>','/projects/update?id='.$key.'', [
'class' => 'activity-update-link',
'title' => Yii::t('yii', 'Project Update'),
'data-toggle' => 'modal',
'data-target' => '#activity-modal',
'data-id' => $key,
'data-pjax' => '0',
]);
},
],
],
This is JS code:
<?php $this->registerJs(
'
function init_click_handlers(){
$(".activity-update-link").click(function(e) {
var fID = $(this).closest("tr").data("key");
$.get(
"update",
{
id: fID
},
function (data)
{
$("#activity-modal").find(".modal-body").html(data);
$(".modal-body").html(data);
$("#activity-modal").modal("show");
}
);
});
}
init_click_handlers(); //first run
$("#project_pjax_id").on("pjax:success", function() {
init_click_handlers(); //reactivate links in grid after pjax update
});
');
?>
<?php
Modal::begin([
'id' => 'activity-modal',
'header' => '<h4 class="modal-title">Update Project Testing</h4>',
'size'=>'modal-lg',
'footer' => '<a href="#" class="btn btn-primary" data-
dismiss="modal">Close</a>',
]); ?>
<div class='well'></div>
<?php Modal::end(); ?>
Thanks all for watching my question. I solved my issue by adding modal into main.js file of the assets folder using class instead of ID.

Way to redirect login page if user not login

I want to redirect user to login page if he is not logged on page. But i have actionLogin in my registrationController
So when I use in my common/main:
'as beforeRequest' => [ //if guest user access site so, redirect to login page.
'class' => 'yii\filters\AccessControl',
'rules' => [
[
'actions' => ['login', 'error'],
'allow' => true,
],
[
'allow' => true,
'roles' => ['#'],
],
],
],
It always redirect me to index.php?r=site%2Flogin
Is it possible to change main login redirect to index.php?r=registration%2Flogin?
If it possible where I should overwrite code or change something..
'user' => [ 'loginUrl' => ['registration/login'], ],
resolve problem but when I want to go to registration/index to signup user it redirect me to registration/login.
Is it possible to rule out this url from being enforced? I Want to make index.php?r=registration the only available path.
And here is my facebook login; I want to enable this too
public function oAuthSuccess($client) {
// get user data from client
$userAttributes = $client->getUserAttributes();
$user = User::find()->where(['Email' => $userAttributes['email']])->one();
if (!$user) {
$newuser = New SignupForm();
$newuser->oAuthSuccess($client);
$user = User::find()->where(['Email' => $userAttributes['email']])->one();
if ($newuser->validate() && Yii::$app->getUser()->login($user)) {
Yii::$app->session->setFlash('success', Yii::t('app', 'Udało się poprawnie zalogować. Prosimy dokonać zmian w ustawianiach profilu.'));
return $this->redirect('index.php?r=content/news');
}
}
Yii::$app->user->login($user);
}
In your app/config/web.php (for basic template) or
app/frontend/config/main.php (for advance template) - reference
return [
// ...
'components' => [
// ...
'user' => [
'identityClass' => 'common\models\UserIdentity',
'enableAutoLogin' => true,
'loginUrl'=>['registration/login']
],
// ...
and in your controller for eg RegistrationController.php
// ...
class RegistrationController extends Controller
{
public function behaviors()
{
return [
'access' => [
'class' => AccessControl::className(),
'rules' => [
[
'actions' => ['login', 'signup'], // those action only which guest (?) user can access
'allow' => true,
'roles' => ['?'],
],
[
'actions' => ['home', 'update'], // those action only which authorized (#) user can access
'allow' => true,
'roles' => ['#'],
],
],
],
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'logout' => ['post'],
],
],
];
}
// ...
The simple way is using index.php from backend web or public directory
<?php
// comment out the following two lines when deployed to production
defined('YII_DEBUG') or define('YII_DEBUG', true);
defined('YII_ENV') or define('YII_ENV', 'dev');
require __DIR__ . '/../../vendor/autoload.php';
require __DIR__ . '/../../vendor/yiisoft/yii2/Yii.php';
$config = require __DIR__ . '/../../config/web.php';
$config["controllerNamespace"]='app\controllers\backend';
(new yii\web\Application($config))->run();
if(Yii::$app->user->isGuest){
$request_headers = apache_request_headers();
$srv=$request_headers['Host'];
header("Location: https://".$srv);
die();
}

How to populate Yii2 Autocomplete with AJAX call

I am trying to switch to Yii2 from Yii 1.1. This was source attribute of TextAreaJuiAutoComplete widget
'source'=>"js:function(request, response) {
$.getJSON('".$url"', {
term: extractLast(request.term)
}, response);
}",
This is not working in Yii2 with yii\jui\AutoComplete anymore. Can anyone give me a hint what is the cause? Underlying JavaScript objects should be the same.
If I put following code it works, but I want to use ajax calls instead.
'source' => [ "c++", "java", "php", "coldfusion", "javascript", "asp", "ruby" ],
Try this:
use yii\web\JsExpression;
.....
.....
'source'=>new JsExpression("function(request, response) {
$.getJSON('".$url."', {
term: request.term
}, response);
}"),
Try this:
AutoComplete::widget([
'name'=>'myacfield',
'clientOptions' => [
'source' => Url::to(['autocomplete']),
'minLength'=>'2',
],
'options'=>[
'class' => 'form-control'
]
]);
But your AutoComplete action must return a one dimensional array like
...
$rs = Yii::$app->db->createCommand($sql)->queryAll();
$row_set = [];
foreach ($rs as $row)
{
$row_set[] = $row['name']; //build an array
}
echo json_encode($row_set); //format the array into json data
Examle with like.
Controller:
public function actionSearch($term)
{
\Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
$rs = Cure::find()->where(['like', 'name_uz', $term])->all();
if($rs !=null){
$row_set = [];
foreach ($rs as $row)
{
$row_set[] = $row->name_uz; //build an array
}
return $row_set;
}else{
false;
}
}
In view:
<? use yii\jui\AutoComplete;?>
<?= AutoComplete::widget([
'model' => $model,
'attribute' => 'country',
'options' => ['class' => 'form-control'],
'clientOptions' => [
'source' => Url::to(['cure/search']),
'minLength'=>'2',
],
]); ?>