I have just realized that my captcha doesn't display the images, is like if it was broke. I'm sure that before it works well, but I don't know what happened.
So, the first thing that I did was to change the model, view and controller edited for my for the original created using Yii, but now it dosen't work either...
Now I have the following controller (the originals created by Yii):
<?php
class SiteController extends Controller
{
/**
* Declares class-based actions.
*/
public function actions()
{
return array(
// captcha action renders the CAPTCHA image displayed on the contact page
'captcha'=>array(
'class'=>'CCaptchaAction',
'backColor'=>0xFFFFFF,
),
// page action renders "static" pages stored under 'protected/views/site/pages'
// They can be accessed via: index.php?r=site/page&view=FileName
'page'=>array(
'class'=>'CViewAction',
),
);
}
...
The model:
<?php
/**
* ContactForm class.
* ContactForm is the data structure for keeping
* contact form data. It is used by the 'contact' action of 'SiteController'.
*/
class ContactForm2 extends CFormModel
{
public $name;
public $email;
public $subject;
public $body;
public $verifyCode;
/**
* Declares the validation rules.
*/
public function rules()
{
return array(
// name, email, subject and body are required
array('name, email, subject, body', 'required'),
// email has to be a valid email address
array('email', 'email'),
// verifyCode needs to be entered correctly
array('verifyCode', 'captcha', 'allowEmpty'=>!CCaptcha::checkRequirements()),
);
}
...
and the view:
...
<?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 they are shown in the image above.
<br/>Letters are not case-sensitive.</div>
<?php echo $form->error($model,'verifyCode'); ?>
</div>
<?php endif; ?>
...
I think that my problem may be like the reported in the following link, so I also used the follow accessRules()
public function rules()
{
return array(
array('allow',
'actions' => array('captcha'),
'users' => array('*'),
),
);
}
and
public function rules()
{
return array(
array('allow',
'actions'=>array('create', 'captcha'),
'users'=>array('*'),
)
);
}
But both gave me errors:
"ContactForm2 tiene una regla de validación inválida. La regla se debe especificar attributos para ser validados y el nombre de su validador."
Please, someone could help me? Why is happening this? I read a lot about this topic, but I didn't find the solution...
Related
I'm trying to login with POST and Auth however unsuccessfully returning FALSE the function "$ this-> Auth-> identify ()" within my UsersController
Here are my settings from AppController to view
AppController
public function initialize() {
parent::initialize();
$this->loadComponent('Flash');
$this->loadComponent('Auth');
$this->loadComponent('Cookie');
}
function beforeFilter(Event $event) {
$this->Auth->allow('add');
$this->Auth->config('authorize','Controller',true);
$this->Auth->config('authenticate', ['Form' => ['fields' => ['username' => 'username', 'password' => 'password']]]);
$this->Auth->config('logoutRedirect', 'Homes/index',true);
$this->Auth->config('loginRedirect', 'Homes/index',true);
$this->Auth->config('loginAction', 'Users/login',true);
$this->Auth->config('loginError', 'Usuário e/ou senha incorreto(s)',true);
$this->Auth->config('authError', 'Você precisa fazer login para acessar esta página',true);
$this->Auth->config('userModel', 'Users',true);
}
UsersController
public function login() {
if ($this->request->is('post')) {
/* Here return FALSE */
if ($this->Auth->identify()) {
$this->Session->setFlash(__('Welcome, ' . $this->Auth->user('username')));
} else {
$this->Auth->flash('Login errado');
}
}
}
login.ctp
<?= $this->Form->create(); ?>
<?php // $this->Form->create('Users'); ?>
<fieldset>
<legend><?= __('Login') ?></legend>
<?php
echo $this->Form->input('username');
echo $this->Form->input('password');
?>
</fieldset>
<?= $this->Form->button(__('Login')) ?>
<?= $this->Form->end() ?>
table mysql
username and password varchar 200
Two things - 1, depending on how strict your database is, you might have to make sure the username is saved exactly as you typed it. I've had an issue before where I created a username with camelcase like JohnDoe. Typing 'johndoe' worked for me until I upgraded to MySQL Enterprise, which was incredibly picky and demanded that I type JohnDoe instead.
2 - It looks like your input names match with the fields in your database, but double check that you're saving the password correctly when you set up the account. I'm going to assume you followed the CakePHP 3 tutorial and your password is being saved and hashed through the entity:
protected function _setPassword($password)
{
return (new DefaultPasswordHasher)->hash($password);
}
// inside the tutorial on the cake site
Following the instructions in the Cake tutorial should work for you, and be sure to follow suit with $this->Auth->setUser($user); afterwards once it returns true.
I have this code Im trying to save the content and the title from a form I made..It has an id that autoincrement the id number adds in the database but the title and the content isn't/cant be save in the database. Can you please check my code if I've done something wrong? or what I'm lacking at.
Here is my model ContentForm.php
<?php
class ContentForm extends CActiveRecord{
public $content;
public $title;
public function tableName(){
return 'tbl_content';
}
public function attributeLabels()
{
return array(
'contentid' => 'contentid',
'content' => 'content',
'title' => 'title',
// 'email' => 'Email',
// 'usrtype' => 'Usrtype',
);
}
Here is my view content.php
<div>
<p>User: <a href="viewuserpost">
<?php
echo Yii::app()->session['nameuser'];
?>
</a>
</p>
</div>
<h1>Content</h1>
<?php
$form=$this->beginWidget('CActiveForm', array(
'id'=>'contact-form',
'enableClientValidation'=>true,
'clientOptions'=>array(
'validateOnSubmit'=>true,
),
));
?>
Title:
<div class="row">
<?php
echo $form->textfield($model,'title');
?>
</div>
</br>
Body:
<div class="row">
<?php
echo $form->textArea($model,'content',array('rows'=>16,'cols'=>110));
?>
</div>
<div class="row buttons">
<?php
echo CHtml::submitButton($model->isNewRecord? 'Create':'Save');
?>
</div>
<?php $this->endWidget(); ?>
and here is my content action in my sitecontroller.php
public function actionContent(){
$model=new ContentForm;
if(isset($_POST['ContentForm'])) {
$model->attributes=$_POST['ContentForm'];
if($model->save())
$this->redirect(array('content','contentid'=>$model->contentid));
$this->redirect(array('content','title'=>$model->title));
$this->redirect(array('content','content'=>$model->content));
}
$this->render('content',array('model'=>$model));
}
Please help.
Remove
public $content;
public $title;
from your class.
Yii uses PHP magic methods. And when you add attributes to your class, PHP doesn't call them but references to your explicitly written attributes.
Moreover, you should add some validation, if you use $model->attributes=$_POST['ContentForm'];. Another variant is to use unsecure $model->setAttributes($_POST[ContentForm], false) where false tells Yii to set all attributes, not only that are considered safe.
Note, that attributes is not real Model attribute, this is virtual attribute accessed through magic methods.
Also, you don't need three redirects. This is HTTP redirect to other page. This time, you just should just specify route to model view action and its parameter that is id, for example. Like this $this->redirect(array('content/view','id'=>$model->contentid));.
Of course, simplest way for you is to create new model and controller with actions using Gii.
you may missed rules , add this in your model ContentForm.php
public function rules()
{
return array(
array('content,title', 'safe'),
);
}
For more about model validation
http://www.yiiframework.com/wiki/56/reference-model-rules-validation/
I have an email field in my model registration form and other fields like name, country, age.
and I have to do an ajax validation onChange event only for email field .
I was set my view to enable ajax validation.
my problem is the ajax validation applied for all field not only for email, I need to do this action only for one field onChange event.
this my view
$form=$this->beginWidget('bootstrap.widgets.TbActiveForm', array(
'id'=>'Login-Form',
'enableClientValidation'=>true,
'enableAjaxValidation'=>true,
'clientOptions'=>array(
'validateOnSubmit'=>true,
),
));
echo $form->errorSummary($loginForm);
echo $form->textFieldRow($loginForm, 'email');
echo $form->textFieldRow($loginForm, 'name');
echo $form->textFieldRow($loginForm, 'age');
echo $form->textFieldRow($loginForm, 'country');
and this is my model
public function rules()
{
return array(
array('email, country, name', 'required'),
array('email', 'checkEmail')
);
}
// custom function to check email
public function checkEmail($attribute, $params)
{
$this->addError($attribute,strtr('email exsit before',$params));
}
how can enable ajax validation only for email and the other filed (country, name, age) on client side without ajax validation.
Please help I send a lot of time to do that.
Thanks
Set the form clientOption on change like this:
$form=$this->beginWidget('bootstrap.widgets.TbActiveForm', array(
'id'=>'Login-Form',
'enableClientValidation'=>true,
'enableAjaxValidation'=>true,
'clientOptions'=>array(
'validateOnSubmit'=>true,
'validateOnChange'=>true,
So that on change it can trigger the validation
This can be done by setting the 4th parameter to false on validate trigger.
<?php echo $form->error($model,'email', array(), false); ?>
In your model set this
public function rules()
{
return array(
array('email, country, name', 'required'),
array('email', 'unique'), //check if email already exist
array('email', 'email'),
);
}
in your controller
<?php
class SiteController extends CController {
.... // Other functions
public function actionLogin(){ // Your corresponding action
$model= new LoginForm(); // Your actual model name
$_POST['ajax'] === 'Login-form' make sure that login form is the same as your form name in view
if (isset($_POST['ajax']) && $_POST['ajax'] === 'Login-form') {
echo CActiveForm::validate($model,);
Yii::app()->end();
}
... // Remaining action logic
in your view
$form=$this->beginWidget('bootstrap.widgets.TbActiveForm', array(
'id'=>'Login-Form',
'enableClientValidation'=>false,
'enableAjaxValidation'=>true,
'clientOptions'=>array(
'validateOnSubmit'=>false,
'validateOnChange'=>false,
'validateOnType' => true,
To perform validation via ajax you first need to call a helper function in your controller in addition to you enabling the enableAjaxValidation in your form view
In your Controller ( I am assuming the SiteController since this a login form )
<?php
class SiteController extends CController {
.... // Other functions
public function actionLogin(){ // Your corresponding action
$model= new LoginForm(); // Your actual model name
if (isset($_POST['ajax']) && $_POST['ajax'] === 'login-form') {
echo CActiveForm::validate($model,array('email'));
Yii::app()->end();
}
... // Remaining action logic
see Validate and enableAjaxValidation api docs for full details how this works
I just wondering how it is possible to copy exact code of Yii Framework demo-blog-contact , downloaded from Yii website to other yii application with same version library and it don't show captcha.
When i go to controller/action page ,it show broken link instead of captcha and when i open broken link image in new page it show another broken link.
I saw this link for common problem of CCaptcha and i checked gd library is up and running and i have function actions() with content of exact same as the link said and i don't define any access control filter in the application.
I saw this link and i don't have permission problem and this link and i don't ajax it.
I did exact same as this link said but no success. any help to show these captcha would be appreciated.
Controller :
public function actions()
{
return array(
'captcha'=>array(
'class'=>'CCaptchaAction',
'backColor'=>0xFFFFFF,
),
'page'=>array(
'class'=>'CViewAction',
),
);
}
public function accessRules()
{
return array(
array('allow',
'actions'=>array('create', 'captcha'),
'users'=>array('*'),
));
}
Model :
<?php
class ContactsM extends CFormModel {
public $name;
public $email;
public $subject;
public $body;
public $verifyCode;
/**
* Declares the validation rules.
*/
public function rules()
{
return array(
// name, email, subject and body are required
array('name, email, subject, body', 'required'),
// email has to be a valid email address
array('email', 'email'),
// verifyCode needs to be entered correctly
array('verifyCode', 'captcha', 'allowEmpty'=>!CCaptcha::checkRequirements()),
);
}
public function attributeLabels()
{
return array(
'verifyCode'=>'Verification Code',
);
}
}
View :
<?php $form=$this->beginWidget('CActiveForm'); ?>
<?php echo $form->errorSummary($model); ?>
<?php if(extension_loaded('gd')): ?>
<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 they are shown in the image above.
<br/>Letters are not case-sensitive.</div>
</div>
<?php endif; ?>
<div class="row submit">
<?php echo CHtml::submitButton('Submit'); ?>
</div>
<?php $this->endWidget(); ?>
As i understand from your comment You should Extend your Controller class from CController.
I want to share the fact i have understand :
My problem was :
I used inheritances and father class have some issue , the son class extend it but it do not show any error and i was thinking it works fine but in fact it didn't , i understand it till i used some of father function which in this case was CCaptcha.
I am only trying to create a non-AJAX registration form.
When I submit through a CForm, PHP says error() is being called on a non-object. I checked the source file where the error occurred and (using var_dump(get_class($parent->getActiveFormWidget()));) found that getActiveFormWidget() returns a CFormInputElement, which does not have error() defined.
I thought this had to do with CForm::activeForm, but it defaulted to CActiveForm.
I did try 'enableAjaxValidation'=>false.
What am I not understanding? I suspect I misinterpreted something along the way.
CFormInputElement::renderError():
public function renderError()
{
$parent=$this->getParent();
// $parent->getActiveFormWidget() returns object that does not define error()
return $parent->getActiveFormWidget()->error($parent->getModel(), $this->name, $this->errorOptions, $this->enableAjaxValidation, $this->enableClientValidation);
}
Model:
class RegisterFormModel extends CFormModel {
public $email;
public $password;
public $password_confirm;
public function rules()
{
return array(
array('email, password, password_confirm', 'required'),
array('password','compare','compareAttribute'=>'password_confirm'),
array('password, password_confirm','length','min'=>'6','max'=>'20'),
array('email', 'email'),
array('email', 'length', 'max'=>256)
);
}
public function attributeLabels()
{
return array(
'email'=>'Email',
'password'=>'Password',
'password_confirm'=>'Confirm Password',
);
}
}
View:
<div class="form">
<?php echo $form; ?>
</div><!-- form -->
Controller Action:
class RegisterAction extends CAction
{
public function run()
{
$register_model = new RegisterFormModel;
$controller = $this->getController();
$form = new CForm(array(
'title'=>'Register',
'enableAjaxValidation'=>false,
'elements'=>array(
'email'=>array(
'type'=>'text',
'maxlength'=>256,
),
'password'=>array(
'type'=>'password',
'minlength'=>6,
'maxlength'=>32,
),
'password_confirm'=>array(
'type'=>'password',
'minlength'=>6,
'maxlength'=>32,
),
),
'buttons'=>array(
'register'=>array(
'type'=>'submit',
'label'=>'Register',
),
),
), $register_model);
if($form->submitted('register', true) && $form->validate())
{
// ...
}
else
{
$controller->render('register', array('model'=>$register_model, 'form'=>$form));
}
}
}
Well, I have never seen using CForm as you show us.
I recommend you to use the active form widget,
http://www.yiiframework.com/wiki/195/implementing-a-registration-process-using-the-yii-user-management-module/
and you need to define all those fields in your CFormModel. This way you will be able to provide proper validation for them.
I know that the answer is really late :)
But for the sake of anyone else who may have a similar error.
<?php
// change from: echo $form;
echo $form->render();
?>
I was rendering the elements separately so this is how I did it:
<?php
// without the renderBegin() and renderEnd() it may give the no object error
echo $form->renderBegin();
echo $form->renderElements();
echo $form->renderEnd();
?>