My Captcha is not changing, always appear the same word, unless clicking on Reload Captcha button. Why testLimit is not working properly?
Controller.php
public $attempts = 5; // allowed 5 attempts
public $counter;
public function actions()
{
return array(
'captcha'=>array(
'class'=>'CCaptchaAction',
'backColor'=>0xf5f5f5,
'testLimit'=>1,
);
}
private function captchaRequired()
{
return Yii::app()->session->itemAt('captchaRequired') >= $this->attempts;
}
public function actionLogin()
{
if (!Yii::app()->user->isGuest) $this->redirect(array('users/update'));
$model = $this->captchaRequired()? new LoginForm('captchaRequired') : new LoginForm;
// collect user input data
if(isset($_POST['LoginForm']))
{
$model->attributes=$_POST['LoginForm'];
// validate user input and redirect to the previous page if valid
if($model->validate() && $model->login()) {
$this->redirect(array('users/update'));
} else {
$this->counter = Yii::app()->session->itemAt('captchaRequired') + 1;
Yii::app()->session->add('captchaRequired',$this->counter);
}
}
// display the login form
$this->render('login',array('model'=>$model));
}
View.php
<?php if($model->scenario == 'captchaRequired'): ?>
<br>
<legend><?php echo CHtml::activeLabelEx($model,'verifyCode'); ?></legend>
<div class="control-group">
<div class="controls">
<?php $this->widget('CCaptcha'); ?>
<?php echo CHtml::activeTextField($model,'verifyCode'); ?>
</div>
</div>
<?php endif; ?>
testLimit is the amount of captcha submission, that user can try before generated hash will be changed. Used for avoid typo mistakes.
Verify code stores in session (http://www.yiiframework.com/doc/api/1.1/CCaptchaAction#getVerifyCode-detail), thus be default code can be changed only one of two ways: submit form with testLimit times with incorrect code, or manual update by user.
So you can extends CCaptchaAction class to achieve what you want, f.g. force set $regenerate variable to true.
Is simple solution, use JScript. This script will be reload image captha.
$(document).ready(function () {
setTimeout(function () {
$("img#reviews-verifycode-image").click();
}, 100);
});
Related
I am trying to insert a row to the db using codeigniter.
Model-post.php
class Post extends CI_Model{
function get_posts($num=20, $start=0){
$this->db->select()->from('posts')->where('active',1)->order_by('date_added','desc')->limit($num,$start);
$query=$this->db->get();
return $query->result_array();
}
function get_post($postid){
$this->db->select()->from('posts')->where(array('active' => 1, 'postID'=>$postid))->order_by('date_added','desc');
$query=$this->db->get();
return $query->first_row('array');
}
function insert_post($data){
$this->db->insert('posts',$data);
return $this->db->return_id();
}
Controller-posts.php
class Posts extends CI_Controller{
function __construct(){
parent::__construct();
$this->load->model('post');
}
function index(){
$data['posts'] = $this->post->get_posts();
$this->load->view('post_index', $data);
}
function post($postid){
$data['post']=$this->post->get_post($postid);
$this->load->view('post',$data);
}
function new_post(){
if($_POST){
$data =array(
'title'=>$_POST['title'],
'post'=>$_POST['post'],
'active'=>1
);
$this->post->insert_post($data);
redirect(base_url());
}
else{
$this->load->view('new_post');
}
}
View-new_post.php
<form action="<?php base_url(); ?>posts/new_post" method="action">
<p>Title: <input type="text" name="title"></p>
<p>Description: <input type="textarea" name="post"></p>
<input type="submit" value="Add post">
</form>
Index view-post_index.php
foreach ($posts as $post) { ?>
<div id-="container">
<div><h3><?php echo $post['title']; ?> </h3>
<?php echo $post['post']; ?>
</div>
</div>
<?php
}
The index page shows all the posts from db. On clicking the title it takes to post.php view to show the respective data. This part is fine.
While trying to add a new post in new_post.php it is not reflecting in the db nor showing any error. Also I used redirect_url to redirect to the index page after inserting. So it shows the same available posts. On clicking the title it keeps on adding posts/post to the url repeatedly. Clicking the title once after redirecting the url shows
http://localhost/Codeigniter/posts/posts/post/1
Again on clicking the title it adds
http://localhost/Codeigniter/posts/posts/post/post/1
Can anyone help me? Thanks!
There are numerous issues across the entire application. These are what I found:
Views
Two problems in your new_post view.
You are not echoing out your base_url . You need to replace your form's action attribute.
the method attribute should either have post or get. In this case it should be post
Change it like this:
From this:
<form action="<?php base_url(); ?>posts/new_post" method="action">
To this:
<form action="<?= base_url(); ?>posts/new_post" method="post">
alternatively you can do this:
<form action="<?php echo base_url(); ?>posts/new_post" method="post">
Controller
In your posts controller, your new_post() function should be like this:
function new_post() {
if ($this->input->post()) {
$data = array(
'title' => $this->input->post('title'),
'post' => $this->input->post('post'),
'active' => 1
);
$id = $this->post->insert_post($data);// this is the id return by your model.. dont know what you wann do with it
// maybe some conditionals checking if the $id is valid
redirect(base_url());
} else {
$this->load->view('new_post');
}
}
Model
function insert_post() should not have $this->db->return_id();, instead it should be $this->db->insert_id();
in your model
function insert_post($newpost){
$this->db->insert('posts',$newpost);
// check if the record was added
if ( $this->db->affected_rows() == '1' ) {
// return new id
return $this->db->insert_id();}
else {return FALSE;}
}
any user input must be validated. if you are using Codeigniter then use its form validation and use its input library like:
$this->input->post('title')
an example for blog posts are in the tutorial https://ellislab.com/codeIgniter/user-guide/tutorial/create_news_items.html
otherwise in your controller -- check if the new post id did not come back from the model -- if it did not come back then just go to an error method within the same controller so you don't lose the php error messages.
if ( ! $postid = $this->post->insert_post($newpost); ){
// passing the insert array so it can be examined for errors
$this->showInsertError($newpost) ; }
else {
// success now do something else ;
}
In my web application the work flow demands that I should call one controller function from another function
Should I do add extra code or some configuration to proceed ? Right now This is how I implemented .But When I click "save" button nothing is happening values are just getting empty from the form .
My code .I want to create an object of model "BookVegetable" inside "ProducerOfferController" .
My code inside producerOffer controller
public function actionCreate()
{
//$book_vegetable=new BookVegetable;
$model=new BookVegetable;
if(isset($_POST['BookVegetable']))
{
$model->attributes=$_POST['BookVegetable'];
$model->booked_by = Yii::app()->user->id;
$model->save();
if ($model->hasErrors() === false)
{
$this->redirect(Yii::app()->user->returnUrl);
}
}
else
{
Yii::app()->user->setReturnUrl($_GET['returnUrl']);
}
$this->render('book',array('model'=>$model,));
}
My code for from view
<div style='padding-left:50px'>
<?php $form=$this->beginWidget('bootstrap.widgets.TbActiveForm',array('id'=>'non-ajax_form','enableAjaxValidation'=>false,)); ?>
<p class="help-block">Fields with <span class="required">*</span> are required.</p>
<?php echo $form->errorSummary($model); ?>
<?php echo "<br>" ?>
<?php echo CHtml::textField("booked_quantity",$model->booked_quantity); ?>
My scenario
public function actionBookvegetable($id){
$BookVegetable=new BookVegetable;
$model=$this->loadModel($id);
if(isset($_POST['ProducerOffer'],$_POST['BookVegetable']))
{
$model->attributes=$_POST['ProducerOffer'];
$BookVegetable->attributes=$_POST['BookVegetable'];
$BookVegetable->booked_by=Yii::app()->user->id;
$BookVegetable->producer_offer_id=$model->id;
$model->save();
$BookVegetable->save();
if (($model->hasErrors() === false)||($BookVegetable->hasErrors()=== false))
{
$this->redirect(Yii::app()->user->returnUrl);
}
}
else
{
Yii::app()->user->setReturnUrl($_GET['returnUrl']);
}
$this->render('book',array('model'=>$model,'BookVegetable'=>$BookVegetable));
}
<div class="form-actions">
<?php $this->widget('bootstrap.widgets.TbButton', array('buttonType'=>'submit', 'type'=>'primary', 'label'=> 'Save',)); ?>
How should I resolve this ? Is it essential to add anything extra to use one controller action inside another controller
The url before saving and its the same after I press save also
http://localhost/xxx/producerOffer/bookvegetable/20?returnUrl=%xxx%2FproducerOffer%2Fmanage
One way to do this in Yii2
Background
In SiteController action index method get the records of all objects from another model called voyzes.
In SiteController
Include the other model ex. Voyzes
Now in the SiteController action index method, implement the code to access the model/SQL/NoSQL or anything and set it in a array and return it to the view. For ex.
Now in the index view you should have your data from another model.
According to your information provided.. when you go here,
http://xxx.yyy.zzz/xxxx/producerOffer/create
Actually it should show you the form of book and when you click the save button there and go to returnUrl.
$this->redirect(Yii::app()->user->returnUrl);
I suggest you to write the following as,
$model->save();
$BookVegetable->save();
if (($model->hasErrors() === false)||($BookVegetable->hasErrors()=== false))
{
$this->redirect(Yii::app()->user->returnUrl);
}
To
if($model->save() && $BookVegetable->save())
$this->redirect('yourAction'); //if params needed, $this->redirect(array('yourAction', 'id' => $model->id));
When you go here, http://xxx.yyy.zzz/xxxx/producerOffer/bookvegetable
What ever the code you have written under ActionBookvegetable will trigger.
To make sure your values submitted properly please change this code
$model->save();
if ($model->hasErrors() === false)
{
$this->redirect(Yii::app()->user->returnUrl);
}
To
if($model->save())
$this->redirect('yourAction');
else
print_r(getErrors());
This will print any errors thats preventing from saving the model. let me know after you try this.
In my work , I have a lot of logic around the "loadModel" routine in controllers to make sure the user logged in has access to the particular model. I found this to work from another controller when I need to access the model, without moving or re-copying the loadmodel routine:
$caseviewController = Yii::app()->createController('Caseview');
//use this method from caseview controller to securley load case view model
$caseview = $caseviewController[0]->loadModel($caseviewid);
Hi I am attempting to upload a file and write it to the database using YII, but nothing is happening at all, Its neither saving the file nor name saving to DB.
My View...
<div class="row">
<div class="span4"><?php echo $form->labelEx($model,'slider_image'); ?></div>
<div class="span5"><?php echo $form->fileField($model,'slider_image'); ?></div>
<div class="span3"><?php echo $form->error($model,'slider_image'); ?></div>
</div>
My Model for validation...
public function rules()
{
// NOTE: you should only define rules for those attributes that
// will receive user inputs.
return array(
//more rules
array('slider_image', 'file', 'types'=>'jpg, gif, png', 'allowEmpty'=>true),
//more rules
);
}
Controller:
public function actionEdit()
{
$id = Yii::app()->getRequest()->getQuery('id');
$model = CustomPage::model()->findByPk($id);
if (!($model instanceof CustomPage))
{
Yii::app()->user->setFlash('error',"Invalid Custom Page");
$this->redirect($this->createUrl("custompage/index"));
}
if(isset($_POST['CustomPage']))
{
$model->attributes = $_POST['CustomPage'];
if (CUploadedFile::getInstance($model,'slider_image')) {
$model->slider_image=CUploadedFile::getInstance($model,'slider_image');
}
if ($model->validate())
{
if ($model->deleteMe)
{
$model->delete();
Yii::app()->user->setFlash('info',"Custom page has been deleted");
$this->redirect($this->createUrl("custompage/index"));
}
else {
$model->request_url = _xls_seo_url($model->title);
if (!$model->save())
Yii::app()->user->setFlash('error',print_r($model->getErrors(),true));
else
{
if (CUploadedFile::getInstance($model,'slider_image')) {
$model->slider_image->saveAs(Yii::app()->baseUrl.'images/'.$model->slider_image);
}
Yii::app()->user->setFlash('success',
Yii::t('admin','Custom page updated on {time}.',array('{time}'=>date("d F, Y h:i:sa"))));
$this->beforeAction('edit'); //In case we renamed one and we want to update menu
}
}
}
}
$this->render('edit',array('model'=>$model));
}
I attempted to die; after if (CUploadedFile::getInstance($model,'slider_image')) and nothing is happening, so it seems its not recognising it at all.
Thank you.
I think you're missing a minor directive in your view
Check to confirm that your form tag has the attribute "enctype"
i.e. <form action="" method="post" enctype="multipart/form-data">...</form>
TO set this in CActiveForm, do:
<?php $form = $this->widget('CActiveForm', array(
'htmlOptions'=>array('enctype'=>'multipart/form-data')
));?>
I have a form set up in a controller that both loads the form and its previously populated contents from a database and processes the form as needed. The problem is $this->form_validation->run() never evaluates to FALSE, even if rules are not met.
Controller:
public function edit_version($node, $lang)
{
// load form validation class
$this->load->library('form_validation');
// set validation rules
$this->form_validation->set_rules("title|Title|required");
// run validation
if ($this->form_validation->run() !== FALSE)
{
// save input to database
die("validation successful");
}
else
{
// either validation was not passed or no data to validate
// load page edition view and display databse contents
// load page model
$this->load->model("page_model");
// get the page from database
$data["page"] = $this->page_model->get_page($node, $lang);
// load views
$this->load->view("admin/header.php", array("title" => "Edit page no.: $node, $lang version - Admin"));
$this->load->view("admin/pages/edit_page.php", $data);
$this->load->view("admin/footer.php");
}
}
Model:
class Page_model extends CI_Model
{
public function get_page($node, $lang)
{
// load the page
return $this->db->get_where("pages", array("node" => $node, "lang" => $lang))->row();
}
public function save_version($page)
{
$this->db->where("node", $page["node"]);
$this->db->where("lang", $page["lang"]);
$this->db->update("pages", $page);
}
public function search($query)
{
return $this->db->get_where("pages", $query)->result();
}
}
View:
<h2>Edit page</h2>
<?php
// load form helper
$this->load->helper("form");
// open a form
echo form_open("admin/page/{$page->node}/edit/{$page->lang}");
// print validation errors
echo validation_errors();
// title and content fields
echo form_label("Title: ", "title");
echo form_input("title", set_value("title", $page->title));
// aesthetic line break
echo "<br>";
echo form_label("Content: ", "content") . "<br>";
echo form_textarea("content", set_value("content", $page->content));
// save button and close form
echo form_submit("submit", "Save page");
echo form_close();
Thanks in advance.
syntax for setting rule is
$this->form_validation->set_rules('field_name', 'Label', 'rule1|rule2|rule3');
by considering rules your set rule line will be
$this->form_validation->set_rules('title','Title', 'required");
I'm not a CodeIgniter seasoned dev but from documentation is the proper syntax not the following?
$this->form_validation->set_rules("title","Title","required");
As per this link:
http://ellislab.com/codeigniter/user-guide/libraries/form_validation.html#validationrules
Use
$this->form_validation->set_rules("title","Title","required");
instead of this
$this->form_validation->set_rules('title','Title','required');
I have tested this. It works like a Charm.
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