Unexpected field 'g-recaptcha-response' in POST data on CakePHP 3 - cakephp

I have created a site using CakePHP 3. I have static page which has contact us form something like this:
inside contactus.ctp:
<?=$this->Form->create(); ?>
<?=$this->Form->hidden('form_type',['value' => 'contact']) ?>
<?=$this->Form->input('name',[
'label' => false,
'placeholder' => 'Your Full Name',
'required' => true
]); ?>
<?=$this->Form->input('email',[
'label' => false,
'placeholder' => 'Your Email',
'type' => 'email',
'require' => true
]); ?>
<?=$this->Form->textarea('message',[
'placeholder' => 'Your message...'
]) ?>
<?= $this->Recaptcha->display()?>
<button>Submit Query!</button>
<?=$this->Form->end(); ?>
Using the following link I created Recaptcha:
https://github.com/agiletechvn/Recaptcha
Just beside the Submit button I have Recaptcha.
In the pageController I have the submit check happening:
if($this->request->is(['post']) && $this->request->data('form_type') == 'contact'){
$name = $this->request->data('name');
$email = $this->request->data('email');
$message = $this->request->data('message');
if(!$name){
$this->Flash->set('Please enter a name' . $name,['element' => 'error']);
} elseif (!$email || filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
$this->Flash->set('The email you entered is invalid',['element' => 'error']);
} elseif(!$message){
$this->Flash->set('Message cannot be blank',['element' => 'error']);
} else {
if($this->Recaptcha->verify()) {
$emailObj = new Email();
$emailObj
->from(['contactus#mydomain.com' => 'Developer'])
->replyTo([$email => $name])
->to(['contactus#contactus.com'])
->template('pages/contactus')
->viewVars([
'quickAction' => [
'description' => 'Contact form',
'action' => "from: $name"
],
'name' => 'contactus#mydomain.com',
'senderName' => $name,
'email' => $email,
'message' => $message
])
->subject('Contact email from ' . $name)
->send();
$this->Flash->set('Your message has been sent', ['element' => 'success']);
}
$this->Flash->error(__('Please pass Google Recaptcha first'));
}
If I click submit button I get:
Unexpected field 'g-recaptcha-response' in POST data
I moved the reCaptcha code outside the form. Everything works correctly but the captcha but is sitting outside some random location like this:
How do I solve this issue?

This message can show if you are using CakePHP Security Component, and this component does not recognize one of your form fields. You should unlock this field using:
$this->Form->unlockField('g-recaptcha-response');
More info: CakePHP 3.x Security Component

Related

SELECT in cake php

In this form I can't see name of select, this dropdown don't work, my code is:
In the controller I have:
public function admin_cambiar_centro() {
$this->Session->write(
'Auth.User.centro_id',
$this->request->data('CambioCentro.centro_id')
);
$this->redirect($this->referer());
}
In the view:
<?= $this->Form->create('CambioCentro', array(
'url' => array(
'controller'=> 'Users',
'action' => 'cambiar_centro'
)
)) ?>
<?= $this->Form->select('centro_id',
Hash::combine(AuthComponent::User('Centro'), '{n}.id', '{n}.nombre'),
array(
'empty' => false,
'value' => AuthComponent::User('centro_id'),
'style' => 'margin-top: 7px;',
'onchange' => 'this.form.submit()',
)); ?>
<?=$this->Form->end()?>
and this does not deploy I would be very grateful if you could help me
It looks like your form url is not correct. Try to add admin => true to the form's url.
<?=$this->Form->create('CambioCentro', array('url' =>
array('controller'
=> 'Users', 'action' => 'cambiar_centro', 'admin' => true)))?>
Another potential problem is that you are writing to the session and redirecting on every request, so you may create a redirect loop, and also on get request the session variable gets overwritten.
Check the request type in the action:
public function admin_cambiar_centro() {
if($this->request->is('post')) {
$this->Session->write('Auth.User.centro_id',
$this->request->data('CambioCentro.centro_id'));
return $this->redirect($this->referer());
}
}

how can i make two form input are related cakephp

I would like to make this in my add.ctp.
when user choose the department, on the file form field, only shows the file with the same department that they choose
in my add.ctp
<div class="form-group">
<?php echo $this->Form->input('department', array('class' => 'form-control', 'placeholder' => 'Department', 'options' => array(
'Administrator' => 'Administrator',
'Multimedia' => 'Multimedia',
'Treasurer' => 'Treasurer',
'Marketing' => 'Marketing',
),
'empty' => '(Choose Department)',));?>
</div>
<div class="form-group">
<?php echo $this->Form->input('fail_id', array('class' => 'form-control', 'label' => 'File','placeholder' => 'File Id', 'empty' => '(Choose File)'));?>
</div>
in my controller
public function add() {
if ($this->request->is('post')) {
$this->Borrow->create();
$this->request->data['Borrow']['user_id']= $this->Auth->user('id');
if ($this->Borrow->save($this->request->data)) {
$this->Session->setFlash(__('The borrow has been saved.'), 'default', array('class' => 'alert alert-success'));
return $this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The borrow could not be saved. Please, try again.'), 'default', array('class' => 'alert alert-danger'));
}
}
$users = $this->Borrow->User->find('list');
$fails = $this->Borrow->Fail->find('list');
$fails = $this->Borrow->Fail->find('list');
$this->set(compact('users', 'fails', 'fails'));
}
thanks for the kindness help.
You have to use ajax post. after user select a department you should send an ajax post with the value of department and get the related files and update second combobox.

Form Dropdown Not Registering in Codeigniter

I have created a registration form that has a dropdown field, but I am unable to get it to link into the database to register the selection. I have form validation turned on, but it keeps saying that no value has been selected.
My other inputs work, as they're user entered. However, the values in this dropdown do not register as any value. Any assistance would be appreciated.
Thanks!
View
<div class = "form-group">
<?php echo form_label('Mobile Carrier'); ?><br/><!--Form Label-->
<?php
$data = array(
'None' => 'None',
'att' => 'AT&T',
'verizon' => 'Verizon',
'sprint' => 'Sprint',
'tmobile' => 'T-Mobile'
);
?>
<?php echo form_dropdown('Mobile Carrier', $data, 'None'); ?>
Controller
public function register(){
$this->form_validation->set_rules('mobile_carrier', 'Mobile Carrier', 'required'); }
User Model
public function create_user(){
$data = array(
'first_name' => $this->input->post('first_name'),
'last_name' => $this->input->post('last_name'),
'email' => $this->input->post('email'),
'phone_number' => $this->input->post('phone_number'),
'mobile_carrier' => $this->input->post('mobile_carrier'),
'username' => $this->input->post('username'),
'password' => $encrypted_pass
);
$insert_data = $this->db->insert('users', $data);
return $insert_data;
}
you are assigning the wrong name attribute when creating the dropdown list:
<?php echo form_dropdown('Mobile Carrier', $data, 'None'); ?>
the name attribute must match your $this->input->post('mobile_carrier') in your model. so the correct use would be:
<?php echo form_dropdown('mobile_carrier', $data, 'None'); ?>
more information: https://www.codeigniter.com/userguide3/helpers/form_helper.html, scroll to form_dropdown([$name = ''[, $options = array()[, $selected = array()[, $extra = '']]]])

cakephp form validation success class/message

I'm using cakePHP with its default model validation. On error cake add the class "error" to my container div. Great! But what about if everything is entered correctly but one form element? I would like the inputs that are correct to receive the class "success" (and maybe a message or icon telling my user how awesome they are).
Here is my form create code:
echo $this->Form->create('User',
array(
'class' => 'form-horizontal',
'inputDefaults' =>
array(
'format' => array('before', 'label', 'between', 'input', 'error', 'after'),
'div' => array('class' => 'control-group'),
'label' => array('class' => 'control-label'),
'between' => 'div class="controls">',
'after' => '/div>',
'error' => array('attributes' => array('wrap' => 'span', 'class' => 'help-inline')),
)
)
);
What I ended up doing was copy /lib/Cake/View/HelperFormHelper.php to /app/View/Helper/FormHelper.php. I then modified /app/View/Helper/FormHelper.php around line 1028 (on my copy, it's the end of the 'input' function) so that it looks like this:
1028:
if ($this->_introspectModel($modelKey, 'validates', $fieldKey)) {
$divOptions = $this->addClass($divOptions, 'required');
}
if($this->request->is('post')) {
if(!$this->isFieldError($modelKey.'.'.$fieldKey)) {
// This is the important line.
$divOptions = $this->addClass($divOptions, 'success');
}
}
if (!isset($divOptions['tag'])) {
$divOptions['tag'] = 'div';
}
}//end input function
Don't know if it's the cleanest way, but it would work.
I would add the following lines to my View, checking if the request is a POST. All the fields with the class 'control-group' would adopt the new style.
if($this->request->is('post')){
echo '<style type="text/css">div.control-group { background-color:#000; }</style>';
}
As you don't wan't to show the new style in the fields that use class 'error', just put !important after the style rules at the CSS file revoking the change.
Example 'style.css':
error {
background-color: none !important;
}

Matching data from a drop down menu in add.cpt to view.ctp

Title seems a bit odd as I am trying to find way's to explain my dilema in layman's terms.
What I am trying to achieve is is from what I can gather, fairly simple but.. I just can't seem to place my finger on it.
I have a drop down selection menu which users can select a country of residence which resides in a helper - example below:
class CountryListHelper extends FormHelper {
var $helpers = array('Form');
function select($fieldname) {
$list = $this->Form->input($fieldname , array(
'type' => 'select', 'label' => 'Country of Residence', 'options' => array(
'' => 'Please select a country',
'AF' => 'Afganistan',
'AL' => 'Albania',
'DZ' => 'Algeria',
.................
),
'error' => 'Please select a country'));
return $this->output($list);
}
}
in the add.ctp:
<?php echo $this->CountryList->select('country');?>
Pretty simple stuff - on save it writes the acronym to the country field.
My issue is.. When pulling the data to view.ctp, how would I go about displaying the full country name as apposed to the acronym saved in the database without having to write the entire list down in view.ctp and matching the acronym to Country name there..
<dt<?php if ($i % 2 == 0) echo $class;?>><?php __('Country of Residence'); ?></dt>
<dd<?php if ($i++ % 2 == 0) echo $class;?>>
<?php echo $user['User']['country']; ?>
</dd>
Any and all help is very much appreciated!
Add a new function to the helper that returns the full name of the country.
class CountryListHelper extends FormHelper {
var $helpers = array('Form');
var $countryList = array(
'AF' => 'Afganistan',
'AL' => 'Albania',
'DZ' => 'Algeria',
.................
);
function select($fieldname) {
$list = $this->Form->input($fieldname , array(
'type' => 'select', 'label' => 'Country of Residence',
'options' => $this->countryList,
'empty' => 'Please select a country',
'error' => 'Please select a country'));
return $this->output($list);
}
function fullName( $abbr ) {
return $this->countryList[ $abbr ];
// + error checking
}
}

Resources