Errors on submit in a popup box? - yii

How to show the validation errors in a form in a pop dialogue box?Instead of showing it in the top of the form as a separate div, i want to show those errors in a popup dialogue box so that user clicks okay and dismiss the box.How to do this in yii?

Register your own javascript function name to the afterValidate, which is one of the options in clientOptions property in CActiveForm form class.
Your form declaration should have
'clientOptions' => array(
'validateOnSubmit' => true,
'afterValidate' => 'js:myFunc',
),
And Your form will appear like bellow
<?php
$form = $this->beginWidget('CActiveForm', array(
'id' => 'a-form',
'enableClientValidation' => true,
'enableAjaxValidation' => true,
'errorMessageCssClass' => 'required',
'clientOptions' => array(
'validateOnSubmit' => true,
'afterValidate' => 'js:myFunc',
),
));
?>
------Your form fields------------
------Your form fields------------
------Your form fields------------
<?php $this->endWidget(); ?>
Now, Your myFunc code:
<script type="text/javascript" charset="utf-8">
function myFunc(form, data, hasError)
{
if (hasError)
{
var errors='';
$.each(data, function(obj)
{
errors+=data[obj][0]+"\n";
});
alert(errors);
// Do what ever you want
return true;
}
}
</script>

If you enable client side validation, then you will get error message under textbox, dropdown. There is no in-built option for poping up error message.
still if you need popup error message display, then you have to do with jquery. Then add in Yii forum to help others as well :-)
Refer this link (Yii forum) for details about client side validation

You can build the HTML view yourself with a custom CFormModel and use getError() method in a modal popup.
See : http://www.yiiframework.com/doc/api/1.1/CModel#getError-detail
and : http://www.yiiframework.com/doc/api/1.1/CFormModel

Related

Cakephp 3 Authentication plugin, login URL did not match

I want to use the Authentication plugin for CakePHP 3.8 and I'm having problems that are not in documentation.
After follow Getting Started (https://book.cakephp.org/authentication/1/en/index.html) I have one question.
Originally $fields were specified to change username and password relation in real database, same that Auth component, and login URL is where login form si loaded.
First, in getting started or any part of documentation doesn't says about a login view (form), so, like old Auth Component I created this to Users/login.ctp
<div class="users form">
<?= $this->Flash->render('auth') ?>
<?= $this->Form->create() ?>
<fieldset>
<legend><?= __('Please enter your email and password') ?></legend>
<?= $this->Form->input('email') ?>
<?= $this->Form->input('password') ?>
</fieldset>
<?= $this->Form->button(__('Login')); ?>
<?= $this->Form->end() ?>
</div>
My code in Application.php includes this (with its respective uses and implements):
public function getAuthenticationService(ServerRequestInterface $request, ResponseInterface $response)
{
$service = new AuthenticationService();
$fields = [
'username' => 'email',
'password' => 'password'
];
// Load identifiers
$service->loadIdentifier('Authentication.Password', compact('fields'));
// Load the authenticators, you want session first
$service->loadAuthenticator('Authentication.Session');
$service->loadAuthenticator('Authentication.Form', [
'fields' => $fields,
'loginUrl' => '/users/login'
]);
return $service;
}
But when I try to login, I have this error, after var_dump in login.ctp I get this:
object(Authentication\Authenticator\Result)[124]
protected '_status' => string 'FAILURE_OTHER' (length=13)
protected '_data' => null
protected '_errors' =>
array (size=1)
0 => string 'Login URL `http://localhost/users/login` did not match `/users/login`.' (length=70)
If I comment 'loginUrl' => '/users/login' line, then login works fine.
Additional notes:
- I've tested with hashed and textplane passwords, same results.
- I've added $this->Authentication->allowUnauthenticated(['view', 'index', 'login', 'add']); in beforeFilter to access login.
- It's a clean cakephp 3.8 install, only database is the same for tests.
- I've added Crud only with cake console.
I would like to learn more about that loginURL, I should include some uses in UsersController? What causes this error?
Thank you
The error messages is currently a little misleading, as it doesn't show you the possible base directory, which is the actual issue that you are experiencing. I've proposed a fix for that, which may make into the next release.
When your application lives in a subdirectory, you need to make sure that your login URL configuration takes that into account, that is by either passing the URL including the base directory, which you could do either manually:
'loginUrl' => '/myapp/users/login'
or by using the router:
'loginUrl' => \Cake\Routing\Router::url('/users/login')
'loginUrl' => \Cake\Routing\Router::url([
'plugin' => null,
'prefix' => null,
'controller' => 'Users',
'action' => 'login'
])
Another option would be to use the routes based URL checker, which can be configured via the form authenticators urlChecker option, then you can define the login URL using URL arrays, without having to use the router:
'urlChecker' => 'Authentication.CakeRouter',
'loginUrl' => [
'plugin' => null,
'prefix' => null,
'controller' => 'Users',
'action' => 'login'
]
See also:
Authentication Cookbook > Authenticators > Form
Authentication Cookbook > URL Checkers

Remove OK button from kartik-v custom dialog

I tried to create a custom dialog using yii2-dialog, one of the kartik-v widgets. I want to create this dialog with a single button: Statistics so, using the documentation provided in the demo, I wrote the code below.
The problem is that the dialog I get has two buttons instead of one and I CAN NOT get rid of the OK button.
My questions are: is there any way to create a custom dialog using yii2-dialog with a single button? and if possible, how can I achieve this?
use kartik\dialog\Dialog;
use yii\web\JsExpression;
echo Dialog::widget([
'libName' => 'krajeeDialogCust',
'overrideYiiConfirm' => false,
'options' => [
'size' => Dialog::SIZE_LARGE,
'type' => Dialog::TYPE_SUCCESS,
'title' => 'My Dialog',
'message' => 'This is an entirely customized bootstrap dialog from scratch.',
'buttons' => [
[
'id' => 'cust-btn-1',
'label' => 'Statistics',
'action' => new JsExpression("function(dialog) {
dialog.setTitle('Title 1');
dialog.setMessage('This is a custom message for button number 1');
}")
],
]
]
]);
// button for testing the custom krajee dialog box
echo '<button type="button" id="btn-custom" class="btn btn-success">Custom Dialog</button>';
// javascript for triggering the dialogs
$js = <<< JS
$("#btn-custom").on("click", function() {
krajeeDialogCust.dialog(
"Welcome to a customized Krajee Dialog! Click the close icon on the top right to exit.",
function(result) {
// do something
}
);
});
JS;
// register your javascript
$this->registerJs($js);
And this is what I'm getting:
You need to use dialogDefaults option, according to the docs the configuration options to be setup as defaults for the bootstrap dialog (applicable when useNative is false). and the default value for useNative is false until you explicitly set to true.
Update your Dialog definition to below and override the buttons property in the dialogDefault option as the plugin sets the ok and cancel buttons by default.
echo Dialog::widget ( [
'libName' => 'krajeeDialogCust' ,
'overrideYiiConfirm' => false ,
'dialogDefaults' => [
Dialog::DIALOG_OTHER => [
'buttons' => ''
]
] ,

Yii - Ajax Get based on drop down selection

I am trying to display the price based on the selection of product from a drop down.
View contains:
<?php $form=$this->beginWidget('bootstrap.widgets.TbActiveForm', array(
'id'=>'plan-form',
'enableAjaxValidation'=>true,
)); ?>
<?php echo $form->dropDownListRow($model, 'plan_id',
$planList, array('id'=>'planid', 'prompt'=>'Select Plan',
'ajax' => array('type'=>'GET',
'url'=> Yii::app()->createUrl('mbr/plan/ajaxGetPrice'),
'update'=>'#price'))); ?>
<div id="price">0.00</div>
<?php $this->endWidget(); ?>
Action:
public function actionAjaxGetPrice()
{
Yii::log("Within AjaxGetPrice");
if (Yii::app()->request->isAjaxRequest)
Yii::log("ajax request");
else
Yii::log("regular request");
//$plan=Plan::model()->findByPk((int) $_GET['plan_id']);
//Yii::log(serializ($plan));
// echo $plan->price;
echo "10";
Yii::app()->end();
}
It is not updating the price. Its not calling the action at all. I looked at the suggestions found in Yiiframework and here and tried those and still no luck.
when I add this to the view
<?php
echo CHtml::ajaxLink(
"Get Price",
Yii::app()->createUrl('mbr/plan/ajaxgetprice'),
array( // ajaxOptions
'type' => 'GET',
'update' => '#price'),
array( //htmlOptions
'href' => Yii::app()->createUrl('mbr/plan/ajaxgetprice')
)
);
?>
I get the response when I click on the link, but it renders a separate page with value "10". I have URLFormat = Path.
What am I doing wrong? Any pointers?
You can also try this as shown
<?php echo CHtml::dropDownList('categories','',
$category,
array('ajax'=>array('type'=>'POST','url'=>CController::createUrl('yourController/GetId'),'update' =>'#data'))
);?>
yourController action
public function actionGetId(){
echo 10;
}
And the div
<div id="data">0.00</div>
I'm not really sure how to do this the Yii way but the following javascript should be useful.
$("#yourdropdownidhere").change(function(){
$.ajax({
url: 'your url here', //(dynamically generated by product item)
type: "get",
success: ajaxSuccessHandler
});
});
function ajaxSuccessHandler(obj) {
$('#price').html(obj);
}
I also suggest sending a JSON object as the response for AJAX requests, so it will have an actual structure. A great blog post on this to check out would be Fully ajax website with Yii
I had the same problem and solved it on the controller that renders the view. If you are using renderPartial assure that the processOutput() option is set to TRUE, otherwise Yii will not attach any Javascript.
If you use render instead of renderPartial it also works.

CCaptcha displaying no image yii

I have a user registration form, in which I am trying to display a Captcha image by using Yii widget CCaptcha, however my image link appears broken,
Controller file:
public function actions()
{
return array(
// captcha action renders the CAPTCHA image displayed on the contact page
'captcha'=>array(
'class'=>'CCaptchaAction',
'backColor'=>0xFFFFFF,
),
);
}
Model File:
public function rules()
{
return array( array('verifyCode','captcha','allowEmpty'=>!CCaptcha::checkRequirements(),'on'=>'insert'),
);
}
And view file:
<?php if(CCaptcha::checkRequirements()): ?>
<div class="row">
<?php echo $form->labelEx($model,'verifyCode'); ?>
<div>
<?php $this->widget('CCaptcha'); ?>
<?php echo $form->textField($model,'verifyCode'); ?>
</div>
<div class="hint">Please enter the letters as shown.
<br/>Letters are not case-sensitive.</div>
<?php echo $form->error($model,'verifyCode'); ?>
</div>
<?php endif; ?>
As a answer provided somewhere I also tried giving the access rules in my controller file as
public function accessRules()
{
return array(
array('allow',
'actions' => array('captcha'),
'users' => array('*'),
),
);
}
But nothing seems to be working.
The problem was with the controller file,it should have been,
public function accessRules()
{
return array(
array('allow',
'actions'=>array('create', 'captcha'),
'users'=>array('*'),
),
}
whereas I had mentioned the action for captcha at the end, which I figured out is not allowed in Yii. All the allow actions for * should be together.
Yii captcha will create a png image. A possible explanation for the broken image link would be a missing GD extension or imagick extension, which can be identified by the presence of the following text in your error.log:
call to undefined function imagecreatetruecolor
For details and fix see "call to undefined function imagecreatetruecolor" error in PHP & pChart

yii Tipsy tooltip css does not work while using in ajax popup?

I am using Tipsy tooltip
in a popup which loads on ajax call. In such case the tooltip css does not work. The widget load the css file but does not work.
Here is my code :
<a id="north-west" href="#" original-title="Click on this">Click me</a>
<?php
$this->widget('application.extensions.tipsy.Tipsy', array(
'trigger' => 'hover',
'items' => array(
array('id' => '#north-west', 'gravity' => 'sw'),
),
));
?>
Usually when you load via ajax you would use 'renderPartial' instead of 'render'. There is one catch though: If you have javascript in it you need to make sure the processOutput parameter is set to TRUE. Basically the call would be:
$this->renderPartial('view', array(<data>), FALSE, TRUE);
Yii would then make sure the javascript is also returned, it normally does not do that with a partial. This is only required for ajax calls where the renderPartial is the only output you do, not for calls to it during a regular request.