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.
Related
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 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...
I'm really new to Yii and as a starter, I want to know how to get the value from the textbox when the button is pressed.
<?php CHtml::textField($name,$value,array('submit'=>'')); ?>
<?php echo CHtml::submitButton('Greet!',array(
'submit' => 'message/goodbye')); ?>
Keep your view some thing like
<?php
$form = $this->beginWidget('CActiveForm', array(
'id' => 'aForm',
'htmlOptions' => array('onsubmit'=>"return false;"),
));
?>
<?php echo CHtml::textField('name', 'value'); ?>
<?php echo CHtml::submitButton('Greet!', array('onclick' => 'getValue()'));?>
<?php $this->endWidget(); ?>
And the Action Script for the onclick event is
<script type="text/javascript">
function getValue()
{
$text=$("#aForm").find('input[name="name"]').val();
alert($text);
//$formData=$("#aForm").serialize();
}
</script>
UNDERSTANDING THE BASIC CONCEPT
You have to remember that Yii is an MVC framework ( Model, View Controller ) and the best practice is to keep the entire structure like so. The best way to learn it is from the awesome forum that they have.
Hence, to define a scenario where you would like to save a data/textbox from the form, you would be following the following workflow :
A BASIC WORKFLOW
Assuming that you don't want to save the data in the Database. :
I would be assuming that a basic knowledge of the how the framework works is known. You can check out the guide and the other tutorials if not.
This is a basic workflow in which the data would be taken from the form and validated in the model.
Create a model file in your protected/models folder
Example : Lets name this file as FormData.php
<?php
class FormData extends CFormModel{
public $name;
public $email;
public function rules()
{
return array(
array('name , email','required'), // This rule would make it compulsory for the data to be added.
array('email','email'), // This will check if the email matches the email criteria.
);
}
public function attributeLabels()
{
return array(
'name' => 'Enter your name',
'email' => 'Enter your email',
);
}
}
?>
2. After this , in your protected/FormController.php
Add this :
<?php
class Formdata extends CController{
public function actionCoolForm()
{
$model = new FormData();
if(isset($_POST['FormData'])){
$model->attributes = $_POST['FormData'];
if($model->validate()){
// Do whatever you want to do here.
}
}
$this->render('someview',array('model'=>$model));
}
}
?>
3. Now to add the form in your page is easy :
<?php echo CHtml::form('formdata/coolform','post'); ?>
<?php
echo CHtml::activeTextField($model,'name');
echo CHtml::activeTextField($model,'email');
?>
<?php echo CHtml::endForm(); ?>
Now to add it in the database
The best and the easiest method of adding it in the database is to use the Gii.
But the code is nearly identical, except that the model extends CModel.
I hope that I was able to help.
We have a actionSearchType in our User Controller as follows:
public function actionSearchType()
{
if (Yii::app()->user->isGuest == true)
$this->render('login');
else
$this->render('search_type');
}
Our actionLogin in our User Controller is as follows:
public function actionLogin()
{
$model= new Users();
// if it is ajax validation request
if(isset($_POST['ajax']))
{
echo CActiveForm::validate($model);
Yii::app()->end();
}
$this->redirect(Yii::app()->user->returnUrl);
}
}
// display the login form
$this->render('login',array('model'=>$model));
}
The goal is to ensure that only authenticated users can execute the options on the search type view. When I run this page, I receive an error stating Undefined variable: model.
A snippet of the login view is as follows:
<div class="form">
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'login-form',
'enableClientValidation'=>true,
'clientOptions'=>array(
'validateOnSubmit'=>true,
),
)); ?>
<p class="note">Fields with <span class="required">*</span> are required.</p>
<div class="row">
<?php echo $form->labelEx($model,'username'); ?>
<?php echo $form->textField($model,'username'); ?>
<?php echo $form->error($model,'username'); ?>
</div>
What steps must be taken to remedy the above error and properly check to ensure we have an authenticated user?
update
I changed actionSearchType to render the Login Widget per below:
public function actionSearchType()
{
if (Yii::app()->user->isGuest)
$this->widget('ext.LoginWidget');
else
$this->render('search_type');
}
This indeed resolved the error initially seen. A new problem is that there's no styling of the login widget when it renders. Should I echo my tags with appropriate stylesheet classes, or is there a bit more elegant way of doing that?
public function actionSearchType() {
if (Yii::app()->user->isGuest)
$this->redirect('/user/login');
$this->render('search_type');
}
Notes:
to do something when user is guest, simply use if(Yii::app()->user->isGuest) { statement }
to do something when user is logged in, simply use if(!Yii::app()->user->isGuest) { statement }
in the second code, public function actionLogin(), I think you have 2 more closing curly brackets than needed. Anyway, the login action should look like this:
public function actionLogin() {
$formModel = new Login_Form; // Login_Form.php should be in models folder
if (isset($_POST['Login_Form'])) {
$formModel->attributes = $_POST['Login_Form'];
if ($formModel->validate() && $formModel->login()) {
$this->redirect('/'); // replace / with stuff like Yii::app()->user->returnUrl
}
}
$this->render('login', array(
'formModel'=>$formModel,
));
}
Instead of rendering the view redirect to the user login page / action so you don't have to recreate it.
$this->redirect('login');
Somewhere in search_type you are referencing the variable $model which you do not hand over to the render() function. You need to define that variable otherwise the view will create an Exception.
I don't know which Model/Class your search_type view is expecting but you will need to initialize it before you hand it over to the view like this:
$this->render('search_type',array(
'model' => $model,
));
Here a good read about this topic: Understanding the view rendering flow
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();
?>