Recaptcha with CodeIgniter - codeigniter

I am trying to implement recaptcha my form in CodeIgniter (without using the recaptcha library). This works fine, however as in my form, I am displaying each fields errors individually, I want to display recaptcha error next to its place in the form, can someone help me how can i do it?
The code from my controller:
$this->form_validation->set_rules('name', 'Name', 'trim|required|min_length[3]|max_length[25]');
$this->form_validation->set_rules('email', 'Email address', 'trim|required|valid_email');
//With above set_rules i'm able to display each fields errors next to it,
//How can i display following recaptcha error next to it.
if (!$resp->is_valid)
{
//reCAPTCHA was entered incorrectly
die (
"The reCAPTCHA wasn entered incorrectly." .
"(reCAPTCHA said: " . $resp->error . ")
");
}
else
{
//Successful verification
die('Success!');
}
Thanks for any help.

If you aren't running the recaptcha field through the form validation library you won't be able to use the form_error() function, but you can easily send the error to your view as a variable:
if ($this->form_validation->run())
{
if ( ! $resp->is_valid)
{
$data['recaptcha_error'] = "reCAPTCHA said: ".$resp->error;
}
else
{
// Process form
}
}
$this->load->view('my_view', $data);
Then in your view (wherever/however you want):
<?php if (isset($recaptcha_error)): ?>
<label class="error">
<?php echo $recaptcha_error; ?>
</label>
<?php endif; ?>

Related

Codeigniter Flash Data After Submitting Form?

I have a question regarding form validation with Codeigniter and Flash Data. My form is located deep inside a URL string so I figured the best way to display error message on the page is with CI flash data. I'm having a difficult time figuring out how to actually display the error message. I'm not sure where I'm going wrong. Where am I going wrong? Thanks everyone.
public function form_validate_cars()
{
$this->load->library('form_validation');
$this->form_validation->set_rules("value", "<b>Value</b>", "trim|required|is_numeric|xss_clean");
$this->form_validation->set_rules("exterior_color", "<b>Exterior Color</b>", "trim|required|xss_clean");
$this->form_validation->set_rules("interior_color", "<b>Interior Color</b>", "trim|required|xss_clean");
$this->form_validation->set_rules("mileage","<b>Mileage</b>","trim|required|is_numeric|xss_clean");
if ($this->form_validation->run() == FALSE)
{
// if person does not fill in correct info, they get resubmitted back to the form.
// redirect('site/item/2332');
// echo 'Hello World!';
$msg = "Please fill out proper data";
$this->session->set_flashdata('test', $msg);
// echo 'Please fill out needed ifnormation!';
}
else
{
$this->load->model('model_data');
$this->model_data->add_new_value();
redirect('/site/thanks');
}
}
My View
echo form_open('site/form_validate_cars');
print_r($this->session->flashdata('test'));
echo validation_errors();
my form continues below .......
Right after $this->session->set_flashdata('test', $msg); make redirect to desired url.
in view
if ($this->session->flashdata('result') != ''):
echo $this->session->flashdata('result');
endif;
better way without session
public function form_validate_cars()
{
$this->load->library('form_validation');
$this->form_validation->set_rules("value", "<b>Value</b>", "trim|required|is_numeric|xss_clean");
$this->form_validation->set_rules("exterior_color", "<b>Exterior Color</b>", "trim|required|xss_clean");
$this->form_validation->set_rules("interior_color", "<b>Interior Color</b>", "trim|required|xss_clean");
$this->form_validation->set_rules("mileage","<b>Mileage</b>","trim|required|is_numeric|xss_clean");
if ($this->form_validation->run() == FALSE)
{
// if person does not fill in correct info, they get resubmitted back to the form.
// redirect('site/item/2332');
// echo 'Hello World!';
$data['error'] = "Please fill out proper data";
$this->load->view('desired_view', $data);
} else {
$this->load->model('model_data');
$this->model_data->add_new_value();
redirect('/site/thanks');
}
}
and in view
echo (isset($error)) ? $error : "";
After you assigned the flashdata, redirect back to the form with redirect(). This will then pick up the flashdata, make sure to check if it's filled though.

Yii ClientSide Validation on Render Partial not Working

I have a Yii form which calls a render partial from another model (team has_many team_members). I want to call via ajax a partial view to add members in team/_form. All works (call, show, save) except for ajax validations (server and client side). If i submit form, member's model isn't validating, even in client side, it's not validating the required fields.
Any clue?
//_form
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'team-form',
'enableAjaxValidation'=>true,
'enableClientValidation'=>true,
'clientOptions'=>array(
'validateOnSubmit'=>true,
'validateOnChange'=>true
),
'htmlOptions' => array('enctype' => 'multipart/form-data'),
)); ?>
//Controller
public function actionMember($index)
{
$model = new TeamMember();
$this->renderPartial('_member',array(
'model'=> $model, 'index'=> $index
)
,false,true
);
}
public function actionCreate()
{
$model=new Team;
$members = array();
if(isset($_POST['Team']))
{
$model->attributes=$_POST['Team'];
if(!empty($_POST['TeamMember'])){
foreach($_POST['TeamMember'] as $team_member)
{
$mem = new TeamMember();
$mem->setAttribute($team_member);
if($mem->validate(array('name'))) $members[]=$mem;
}
}
$this->redirect(array('team/create','id'=>$model->id,'#'=>'submit-message'));
}
$members[]=new TeamMember;
$this->performAjaxMemberValidation($members);
$this->render('create',array(
'model'=>$model,'members'=>$members
));
}
//_member
<div class="row-member<?php echo $index; ?>">
<h3>Member <?php echo $index+1; ?></h3>
<div class="row">
<?php echo CHtml::activeLabel($model, "[$index]name",array('class'=>'member')); ?>
<?php echo CHtml::activeTextField($model, "[$index]name",array('class'=>'member')); ?>
<?php echo CHtml::error($model, "[$index]name");?>
</div>
</div>
ProcessOutput was set to true. No dice.
Switch renderPartial() to render(). No dice.
If you will look at the CActiveForm::run:
$cs->registerCoreScript('yiiactiveform');
//...
$cs->registerScript(__CLASS__.'#'.$id,"jQuery('#$id').yiiactiveform($options);");
Then you will understand that you validation will not work, because you render partial and not the whole page. And these scripts show up at the bottom of the page. So you should solve this by execute these scripts.
After you partial is rendered, try to get activeform script which should be stored at the scipts array:
$this->renderPartial('_member',array('model'=> $model, 'index'=> $index));
$script = Yii::app()->clientScript->scripts[CClientScript::POS_READY]['CActiveForm#team-form'];
after, send it with rendered html to page:
echo "<script type='text/javascript'>$script</script>"
Also remember before you will append recieved html on the page you should include jquery.yiiactiveform.js, if you not already did it(by render another form, or registerCoreScript('yiiactiveform')), on the page from calling ajax request. Otherwise javascript error will raised.
Hope this will help.
Edit:
Sorry I'm not understood that you are render part of form and not the whole. But you validation will not work exactly with the same issue. Because jQuery('#$id').yiiactiveform($options); script was not created for the field.
The actual problem is that the ActiveForm saves its attributes to be validated in the "settings" data attribute. I see you are already using indexes so what you need to add the new elements to this settings object in order for the validation to work. After the ajax response this is what must be done:
//Get the settings object from the form
var settings = $("#form").data('settings');
//Get all the newly inserted elements via jquery
$("[name^='YourModel']", data).each(function(k, v) {
//base attribute skeleton
var base = {
model : 'YourModel',
enableAjaxValidation : true,
errorCssClass : 'error',
status : 1,
hideErrorMessage : false,
};
var newRow = $.extend({
id : $(v).attr('id'),
inputID : $(v).attr('id'),
errorID : $(v).attr('id') + '_em_',
name : $(v).attr('name'),
}, base);
//push it to the settings.attribute object
settings.attributes.push(newRow);
});
//update the form
$("#form").data('settings', settings);
```
This way the ActiveForm will be aware of the new fields and will validate them.
Well, setting processOutput to true in renderPartial (in order to make client validation works on newly added fields) will not help in this case since it will only work for CActiveForm form and you don't have any form in your _member view (only input fields).
A simple way to deal with this kind of problem could be to use only ajax validation, and use CActiveForm::validateTabular() in your controller to validate your team members.

codeigniter form helper wiredness

I have some of wiredness going on in some code I am writing. I have a regular form to update a user account. The fields are populated with data from the database. after changing that needs to be changed, I can't submit the form. when I click on the button, it behaves like disabled submit with javascript but I didn't. On the otherhand if I use javascript and stop it from submitting and console log to see if a click is happening, it appears the button is being clicked but just nothing. below is my code in my view for the form.
form_open('members/users/update_curr_user');
$data5 = array('name'=>'username','id'=>'username','value'=>$uservar['username']);
echo 'Username :'.form_input($data5);
$data6 = array('name'=>'email','id'=>'email','value'=>$uservar['email']);
echo 'Email Address :'.form_input($data6);
$phone1 = array('name'=>'phone','id'=>'phone','value'=>$uservar['phone']);
echo 'Your phone number formatted like so: 0802-331-5544'.form_input($phone1);
switch ($uservar['active']):
case 0:
$data7 = array(
'name'=>'status',
'id'=> 'status',
'value' =>'Deactivated'
);
echo 'Status : Active or Deactivated'.form_input($data7);
break;
case 1:
$data8 = array(
'name' =>'status',
'id' =>'status',
'value'=>'active'
);
echo 'Status :Active or Deactivated'.form_input($data8);
break;
endswitch;
$group1 = array('name'=>'group','id'=>'group','value'=>$uservar['group']);
echo 'Group :'.form_dropdown('group',$groups).'<br />';
echo '<br /><br />';
//$data9 = 'id="updateuser"';
//echo form_submit('submit','Update User',$data9);
?>
<input name="submit" id="updateuser" type="submit" value="Update User" />
<?php echo form_close();?>
Because of how unsure I was of what was going on I manually created a button still the same. Other forms on the page are working ok. If it's of any consequence, I am using phil sturgeon's template library, ion_auth and firephp.
You're not actually writing out the form tag. You need to put an echo up there. Do this:
echo form_open('members/users/update_curr_user');
Your submit button should now work.

Zend Framework fancybox confirmation dialog with ajax and posted values

I created a confirmation page for deleting an item. This works perfectly.
Now I want to appear the confirmation page in fancybox, still passing all the variables and delete the data or close the dialog.
It's important that the process still works as it does now (delete->confirmationpage->redirect/deletion) so that users with javascript disabled can perform these actions without a problem.
Now have I been reading about zend framework,ajax, json and more, but the more I read, the less I understand.
So in a nutshell, my question:
I want to pass a variable to the fancybox and if 'yes' perform the delete action or on 'no' close the dialog. This within the zend framework and jquery.
Any advice or tips are greatly appreciated!
You need to use content switching in your ajax which will then render your action appropriately, for example:
function confirmDeleteAction() {
if($this->_request->isXmlHttpRequest()) {
//This is ajax so we want to disable the layout
$this->_helper->layout->disableLayout();
//Think about whether you want to use a different view here using: viewRenderer('yourview')
}
//The normal code can go here
}
function deleteAction() {
//You probably don't want to show anything here, just do the delete logic and redirect therefore you don't need to worry where it's coming from
}
And in your fancybox, have a view that has a form and two buttons, the form should point to your delete action with the id of whatever your deleting as a get param. Set some javascript up that says something like (and this is mootools code, but you can convert it easily):
$('confirmButton').addEvent('click', function(e) {
e.preventDefault();
this.getParent('form').submit();
}
$('cancelButton').addEvent('click', function(e) {
e.preventDefault();
$('fancyBox').destroy(); //I'm not sure it has an id of fancyBox, never used it
}
Came across the question today and figured I could give it a fresh look. For Zend Framework the solution is really simple:
This is how the action looks:
public function deleteAction()
{
$this->_helper->layout()->disableLayout();
$this->view->news = $this->newsService->GetNews($this->_getParam('id'));
if($this->getRequest()->isPost())
{
if($this->getRequest()->getPost('delete') == 'Yes')
{
$this->newsService->DeleteNews($this->_getParam('id'), $this->view->user->username, $this->view->translate('deleted: ').'<strong>'.$this->view->pages[0]['title'].'</strong>');
$this->_helper->flashMessenger(array('message' => $this->view->translate('The page is deleted'), 'status' => 'success'));
$this->_helper->redirectToIndex();
}
elseif($this->getRequest()->getPost('delete') == 'No')
{
$this->_helper->flashMessenger(array('message' => $this->view->translate('The page is <u>not</u> deleted'), 'status' => 'notice'));
$this->_helper->redirectToIndex();
}
}
}
The delete.phtml
<div>
<h2><?php echo $this->translate('Delete news'); ?></h2>
<?php
foreach($this->news as $news)
{
?>
<p>
<?php echo $this->translate('You are now deleting <strong>\'').$news['title'].$this->translate('\'</strong>. Are you sure about this?'); ?>
</p>
<p>
<?php echo $this->translate('<strong>Note! </strong>This action is inreversable, even for us!'); ?>
</p>
<form action="<?php echo $this->baseUrl(false).'/news/index/delete/'.$news['id']; ?>" method="post">
<?php
}
?>
<input class="submit deleteYes" type="submit" name="delete" value="<?php echo $this->translate('Yes'); ?>" />
<input class="submit deleteNo" type="submit" name="delete" value="<?php echo $this->translate('No'); ?>" />
</form>
And this is how the link to delete a file looks (within a foreach loop with my database results)
<a class="deleteConfirmation" href="<?php echo $this->baseUrl(false).'/news/index/delete/'.$news->id; ?>">delete</a>
This works like you would expect; when you click on delete the user goes to the delete confirmation page and redirects the user back to the index after the form is submitted. But I wanted the confirmation in a dialog (in my case I use fancybox). To achieve this, add the following jquery to your index:
$('.deleteConfirmation').fancybox({
// Normal fancybox parameters
ajax : {
type : "POST"
}
});

Codeigniter: How to redirect properly with form validation

I understand how to do it w/ a plain form w/o existing values, but let's say I have a view that I can call via http://domain.com/account/settings. let's say I have two fields, username, password and city, which are all pulled from the DB (except for password of course). So, if a user tries to submit the form and fails validation for whatever reason, where should I "redirect" them to? Right now, I have it showing the same view but the problem is, it pulls the info from the DB again. Should I be creating two different views?
The second view would essentially show the information they tried to enter along w/ the error message.
You do not need two separate views. Check out Form Helper's functions set_value(), set_select(), set_checkbox() and set_radio(). These re-populate form after its submission and validation. So in your case, you should specify the fields this way:
<input type="text"
name="username"
value="<?php echo set_value('username', $user['username']); ?>" />
<input type="text"
name="city"
value="<?php echo set_value('city', $user['city']); ?>" />
By default, the input will have $user['city'] value. But after failed validation it will be re-populated with previously entered values (including incorrect ones).
Just remember that all fields you want to re-populate need to be passed through form_validation library:
$this->form_validation->set_rules('username', 'Username', 'required');
$this->form_validation->set_rules('city', 'City', '');
On the same controller you could have something like this:
if ($this->form_validation->run('create_comment') === TRUE)
{
$this->comments_model->name = $this->input->post('name', TRUE);
$this->comments_model->email = $this->input->post('email', TRUE);
$this->comments_model->website = $this->input->post('website', TRUE);
$this->comments_model->comment = $this->input->post('comment', TRUE);
$this->comments_model->create_comment();
redirect(current_url());
}
$this->load->view('your_view');
That's all there is to it.
The idea is to have it redirect to itself or wherever you want, when the validation returns 'true' so that we kind of refresh the page, hence, update the page.
If the validation returns 'false' then you won't have to do anything.
Redirect to the same form.
And in your view give error information to the visitor.
There are two ways you can do this.
Use this error in your view. This will show validation error info.
echo validation_errors('<p class="error">','</p>');
Or you can use flashdata()
In your controller
...
...
$this->session->set_flashdata('msg', 'All fields are required. or other useful info here. Please try again!');
redirect('yourcontroller');
And in your view, you need to show it.
<?php
if ($this->session->flashdata('msg')){ //change!
echo "<div class='message'>";
echo $this->session->flashdata('msg');
echo "</div>";
}
?>
Had the same problem and discovered that a redirection makes you lose the data that would have been provided by form_error(...) or validation_errors(), except you store such data in a session or in an array being passed into the loaded view.
The point to note is that you should redirect only if the data you want passed around is in session, else you should just load a view. The latter ensures that you have your validation errors intact when you reach the loaded view.
Just load same view if form validation failed
controller
$userData=array(
'username'=NULL,
'password'=NULL
);
#set form validation rules
$this->form_validation->set_rules('username', 'Username', 'required');
$this->form_validation->set_rules('password', 'Password', 'required');
#get all posted data ,this helps you in two ways,
# 1. Get all form data and can be use here server side
# 2. repopulating the form data by passing to view page
$userData=$this->input->post(NULL, TRUE);
#check form validation result
if ($this->form_validation->run() == TRUE) {
//do the operation
redirect(URL);
}else{
$this->load->view($view, $userData);
}
View page
<form method=post action='URL'>
<input type='text' name='username'value='<?php echo $username?>'/>
<?php echo (form_error('username')) ? form_error('username', "<div style='color:red'>", "</div>") : ""; ?>
<input type='text' name='password' value='<?php echo $password?>'/>
<?php echo (form_error('username')) ? form_error('username', "<div style='color:red'>", "</div>") : ""; ?>
<input type='submit' value='submit'/>
</form>
This code display form errors and repopulate the form

Resources