Cakephp 3 Not Recognizing Custom Validation Rule Method and Validation Messages Not Showing - forms

First issue is I have the following validators and public function in my table
UsersTable.php
$validator
->scalar('name')
->maxLength('name', 45)
->requirePresence('name', 'create')
->notEmptyString('name', 'You must enter a name for the user.');
$validator
->add('name', 'custom', array('rule' => 'checkExistingUser', 'message' => 'This user already appears to be in the system.', 'on' => 'create'));
public function checkExistingUser($value,$context)
{
return $this->find('all', ['conditions' => ['Users.name' => $context['data']['name'], 'Users.user_type_id' => $context['data']['user_type_id']]])->count() < 1 ;
}
When I save the form below I receive the message "Method checkExistingUser does not exist". Why doesn't it recognize the method when it's clearly defined in the table model? Am I missing something?
add.ctp
<?php echo $this->Form->create($user);?>
<fieldset>
<legend><?php echo __('Add User'); ?></legend>
<?php
echo $this->Form->control('name', ['type' => 'text']);
echo $this->Form->control('user_type_id');
echo $this->Form->control('owner', array('type' => 'text', 'label' => "Owner Name"));
echo $this->Form->control('owner_contact', array('type' => 'text', 'label' => "Owner Contact (phone, email etc)"));
echo $this->Form->control('description', ['type' => 'textarea']);
echo $this->Form->control('ia_exception', array('type' => 'text', 'label' => "IA Exception Number"));
echo $this->Form->control('is_manual', array('type' => 'checkbox', 'label' => "Password Updated Manually"));
echo $this->Form->control('Environment', ['type' => 'select', 'multiple' => 'true', 'label' => 'Environment(s)']);
?>
</fieldset>
<div class="buttons">
<?php
echo $this->Form->button('Save', ['type'=> 'submit', 'name' => 'submit']);
echo $this->Form->button('Cancel', ['type' => 'button', 'name'=>'cancel', 'onClick' => 'history.go(-1);return true;']);
echo $this->Form->end();
?>
</div>
UsersController.php
function add() {
$user = $this->Users->newEntity();
if ($this->request->is('post')) {
$user = $this->Users->patchEntity($user, $this->request->data);
if ($this->Users->save($user)) {
$this->Flash->set('The user has been saved');
return $this->redirect(array('action' => 'index'));
} else {
$this->Flash->set('The user could not be saved. Please, try again.');
}
}
$userTypes = $this->Users->UserTypes->find('list');
$changeSteps = $this->Users->ChangeSteps->find('list');
$environments = $this->Users->Environments->find('list');
$this->set(compact('user','userTypes', 'changeSteps', 'environments'));
}
Second issue is when I try to submit my form to check that the validator is working correctly for an empty name field I don't receive the message 'You must enter a name for the user'. Instead I receive a message stating 'This field is required'. Why is it not showing my message from notEmptyString? And where is 'This field is required' coming from?

For the first issue, I had to add a provider in my validator.
I changed
$validator
->add('name', 'custom', array('rule' => 'checkExistingUser', 'message' => 'This user already appears to be in the system.', 'on' => 'create'));
To this
$validator
->add('name', 'custom', ['rule' => 'checkExistingUser', 'provider' => 'table', 'message' => 'This user already appears to be in the system.', 'on' => 'create']);

Be careful with custom methods for validation during patching, because Cake expects string to be returned, otherwise it will rendere default meassage.
So for example, if we use a custom validation function during patching
// in a Controller
$this->Users->patchEntity($user, $data, ['validate' => 'custom');
Same applies for closures.
// in UserTable.php
public function validationCustom(Validator $validator) {
$validator = $this->validationDefault($validator);
$validator
->minLength('password',8,'At least 8 digits');
$validator->add('password',
'strength_light',[
'rule' => 'passwordCheck',
'provider' => 'table',
'message' => 'At least a number and a capital letter'
]
);
return $validator;
}
public function passwordCheck ($value = "") {
return preg_match("/^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[#?!#$%^&*-]).{8,}/",$value);
}
This will return default message and not the custom one ("At least..") because we set a callable not-cakephp function as rule for custom validation, so the message should be returned by the called function:
public function passwordCheck ($value = "") {
if (!preg_match("/^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[#?!#$%^&*-]).{8,}/",$value))
return "At least a number and a capital letter";
}

Related

Form Data Not Being Sent From View To Controller

So I'm trying to send a few pieces of data from a form in cake's form builder but for some reason none of the data being submitted is showing up when I print out $this->data or $this->request->data
I've tried creating the form myself and using cake's Form Builder and I need to send this data via POST. The data shows up if I send it as a GET parameter.
view.ctp
echo $this->Form->create(null, array('action' => 'downloadbgc', 'type' => 'get'));
echo $this->Form->input('userId', ['type' => 'text' , 'id' => 'userId', 'name' => 'userId', 'value' => $user->id]);
echo $this->Form->input('product_id', ['type' => 'hidden' , 'id' => 'product_id', 'name' => 'product_id', 'value' => $user->product_id]);
echo $this->Form->submit('Download PDF', array('class' => 'btn btn-icon btn-primary', 'title' => 'Download'));
echo $this->Form->end();
controller.php
...
public function downloadbgc() {
$this->autoRender = false;
print_r("Data: ");
print_r($this->data); die();
}
}
...
When printing this out I get Data: Array() instead of Array('userId' => X, 'product_id' => Y) And I'm positive that these values aren't null since they print to the console.
Use the FormHelper's create() in a correct way:
echo $this->Form->create(false, ['url' => 'downloadbgc']);
echo $this->Form->input('userId', ['type' => 'text' , 'id' => 'userId', 'name' => 'userId', 'value' => 123]);
echo $this->Form->input('product_id', ['type' => 'hidden' , 'id' => 'product_id', 'name' => 'product_id', 'value' => 4456]);
echo $this->Form->submit('Download PDF', array('class' => 'btn btn-icon btn-primary', 'title' => 'Download'));
echo $this->Form->end();
Like the Docs point out the create() method can take the Model as first parameter or false, if you want to access the data without Model. Also use the url option as action is deprecated
In your Controller you can then use $this->request->data to access your data.

$this->getRequest()->getPost() return empty array in magento back end form submission

I am creating a magento custom admin module and a form. I want update this form but not updating. In Controller, under SaveAction() I print $this->getRequest()->getPost() and get empty array. please help me. Below code for form declination..
protected function _prepareForm() {
$form = new Varien_Data_Form(array(
'id' => 'edit_form1',
'action' => $this->getUrl('*/*/save', array('id' => $this->getRequest()->getParam('id'))),
'method' => 'post',
'enctype' => 'multipart/form-data'
)
);
$form->setUseContainer(true);
$this->setForm($form);
return parent::_prepareForm();
}
And Create a from filed set like
protected function _prepareForm() {
$form = new Varien_Data_Form();
$this->setForm($form);
$fieldset = $form->addFieldset('qbanner_form', array('legend' => Mage::helper('qbanner')->__('Art information')));
$fieldset->addField('name', 'text', array(
'label' => Mage::helper('catalog')->__('Product'),
'required' => false,
'name' => 'name',
));
$fieldset->addField('artist_name', 'text', array(
'label' => Mage::helper('catalog')->__('Artist Name'),
// 'name' => 'artist_name',
'value' => Mage::helper('catalog')->__('Art Name value'),
));
$fieldset->addField('bca_status', 'select', array(
'label' => Mage::helper('catalog')->__('Art status'),
'name' => 'bca_status',
'values' =>$this->_getAttributeOptions('bca_status'),
));
$fieldset->addField('reason', 'editor', array(
'name' => 'reason',
'label' => Mage::helper('catalog')->__('Reason'),
'title' => Mage::helper('catalog')->__('Reason'),
'style' => 'width:440px; height:300px;',
'wysiwyg' => true,
'required' => false,
));
$fieldset->addField('thumbnail', 'text', array(
'label' => Mage::helper('catalog')->__('Art status'),
'name' => 'thumbnail',
//'values' =>$this->_getAttributeOptions('thumbnail'),
//'renderer' => 'Qaz_Qbanner_Block_Adminhtml_Qbanner_Grid_Renderer_Image'
));
if (Mage::getSingleton('adminhtml/session')->getQbannerData()) {
$form->setValues(Mage::getSingleton('adminhtml/session')->getQbannerData());
Mage::getSingleton('adminhtml/session')->setQbannerData(null);
} elseif (Mage::registry('qbanner_data')) {
$form->setValues(Mage::registry('qbanner_data')->getData());
}
return parent::_prepareForm();
}
protected function _getAttributeOptions($attribute_code)
{
$attribute = Mage::getModel('eav/config')->getAttribute('catalog_product', $attribute_code);
$options = array();
foreach( $attribute->getSource()->getAllOptions(true, true) as $option ) {
$options[$option['value']] = $option['label'];
}
return $options;
}
Here my
SaveAction()
public function saveAction() {
echo print_r( $this->getRequest()->getPost());
}
I have tied verious post. Any ideas?
Common error for all. You just need to add form key to your form.
Just add this line below your form declaration.
<input type="hidden" name="form_key" value="<?php echo Mage::getSingleton('core/session')->getFormKey(); ?>" />
Like this
<form action="<?php echo Mage::helper("adminhtml")->getUrl("demo/adminhtml_demo/demo");?>" method="post" id="custom-payment-form" enctype="multipart/form-data">
<input type="hidden" name="form_key" value="<?php echo Mage::getSingleton('core/session')->getFormKey(); ?>" />
Add this. Now you can get parameters by $this->getRequest()->getPost().
you can get variable of post and get method in magento with $this->getRequest()->getParams(); getParams() method But if you want to get exactly some variable data then use getParam('id');
/magento/catalog/product/view/id/406/category/14
$this->getRequest()->getParam('id') // 406
$this->getRequest()->getParams(); //get all get and post variables

CakePHP declaring variables

Hey guys trying to declare a variable in CakePHP in the Fields Controller. This variable will display the template id from the template table, but the view is saying the variable is undefined even though we delared it in the controller. Temaplates has many fields and fields belongs to templates.
Here is the Fields Controller:
<?php
class FieldsController extends AppController{
public $uses = array('Template');
function add(){
$this->set('title_for_layout', 'Please Enter Your Invoice Headings');
$this->set('stylesheet_used', 'style');
$this->set('image_used', 'eBOXLogo.jpg');
$this->Session->setFlash("Please create your required fields.");
$templates = $this->Template->find('list');
//$current_template = $this->request->data['Field']['template_id'];
// right way to do it, but Template is undefined, and says undefined var
//$template = $this->request->data['Field']['template_id'];
// makes sense with the find, no errors, but still doesnt print in form, says undefined var
//$current_template = $this->request->data($template['Field']['template_id']);
if($this->request->is('post'))
{
$this->Field->create();
if ($this->Field->save($this->request->data))
{
if($this->request->data['submit'] == "type_1")
{
$this->Session->setFlash('The field has been saved');
$this->redirect( array('controller' => 'fields','action' => 'add'));
}
if($this->request->data['submit'] == "type_2")
{
$this->Session->setFlash('The template has been saved');
$this->redirect( array('controller' => 'templates','action' => 'index'));
}
}
else
{
$this->Session->setFlash('The field could not be saved. Please, try again.');
}
}
}
}
And here is our add view which adds fields:
<?php
echo $this->Form->create('Field', array('action'=>'add'));
echo $this->Form->create('Field', array('action'=>'add'));
echo $this->Form->input('name', array('label'=>'Name: '));
echo $this->Form->input('description', array('label'=>'Description: '));
//echo $this->Form->input('template_id',array('label'=>'Template ID: ', 'type' => 'select', 'options' => $templates));
echo $this->Form->input('template_id',array('label'=>'Template ID: ', 'type' => 'text', 'default'=> $templates));
//echo $this->Form->input('templates_id', array('label'=>'Template ID: ', 'type' => 'text', 'default' => $current_template['templates_id']));//this would be the conventional fk fieldname
echo $this->Form->button('Continue adding fields', array('name' => 'submit', 'value' => 'type_1'));
echo $this->Form->button('Finish adding fields', array('name' => 'submit', 'value' => 'type_2'));
echo $this->Form->end();
?>
You should try the following code:
<?php
class FieldsController extends AppController{
public $uses = array('Template', 'Field');
function add(){
$this->set('title_for_layout', 'Please Enter Your Invoice Headings');
$this->set('stylesheet_used', 'style');
$this->set('image_used', 'eBOXLogo.jpg');
$this->Session->setFlash("Please create your required fields.");
$templates = $this->Template->find('list', array('fields' => array('Template.id, Template.template_name' );
$this->set('templates', $templates);
//$current_template = $this->request->data['Field']['template_id'];
// right way to do it, but Template is undefined, and says undefined var
//comment: You should check the request data with in if condition
//$template = $this->request->data['Field']['template_id'];
// makes sense with the find, no errors, but still doesnt print in form, says undefined var
//$current_template = $this->request->data($template['Field']['template_id']);
if($this->request->is('post'))
{
$this->Field->create();
if ($this->Field->save($this->request->data))
{
if($this->request->data['submit'] == "type_1")
{
$this->Session->setFlash('The field has been saved');
$this->redirect( array('controller' => 'fields','action' => 'add'));
}
if($this->request->data['submit'] == "type_2")
{
$this->Session->setFlash('The template has been saved');
$this->redirect( array('controller' => 'templates','action' => 'index'));
}
}
else
{
$this->Session->setFlash('The field could not be saved. Please, try again.');
}
}
}
}
You view should looks like:
<?php
echo $this->Form->create('Field', array('action'=>'add'));
echo $this->Form->input('name', array('label'=>'Name: '));
echo $this->Form->input('description', array('label'=>'Description: '));
echo $this->Form->input('template_id',array('label'=>'Template ID: ', 'options' => $templates));
//echo $this->Form->input('template_id',array('label'=>'Template ID: ', 'type' => 'text', 'default'=> $templates));
//echo $this->Form->input('templates_id', array('label'=>'Template ID: ', 'type' => 'text', 'default' => $current_template['templates_id']));//this would be the conventional fk fieldname
echo $this->Form->button('Continue adding fields', array('name' => 'submit', 'value' => 'type_1'));
echo $this->Form->button('Finish adding fields', array('name' => 'submit', 'value' => 'type_2'));
echo $this->Form->end();
?>
Kindly check and verify if it is working for you or not.
You are missing $this->set('templates', $templates); after doing the find() for templates in your controller.

CakePHP 2.1 Contact Form in Element Won't Send

I have two contact forms in my CakePHP application -- one with its own Controller, Model, and View, and another one in an element that can be accessed as a "quick" contact form from the footer of every page on the site.
The code for both forms is the same. The element is intended to access the Controller and Model that the other form uses. However, the element is not submitting the data or sending the email, while the regular page works just fine.
Here is the MVC Code for the regular form that IS working:
<!-- Model: Model/Contact.php -->
<?php
class Contact extends AppModel {
var $name = 'Contacts';
public $useTable = false; // Not using the database, of course.
var $validate = array(
'name' => array(
'rule' => '/.+/',
'allowEmpty' => false,
'required' => true,
),
'email' => array(
'allowEmpty' => false,
'required' => true,
)
);
function schema() {
return array (
'name' => array('type' => 'string', 'length' => 60, 'class' => 'contact input'),
'email' => array('type' => 'string', 'length' => 60, 'class' => 'contact input'),
'message' => array('type' => 'text', 'length' => 2000, 'class' => 'contact input'),
);
}
}
?>
<!-- Controller: Controller/ContactsController.php -->
class ContactsController extends AppController
{
var $name = 'Contacts';
/* var $uses = 'Contact'; */
var $helpers = array('Html', 'Form', 'Js');
var $components = array('Email', 'Session');
public function index() {
if(isset($this->data['Contact'])) {
$userEmail = $this->data['Contact']['email'];
$userMessage = $this->data['Contact']['message'];
$email = new CakeEmail();
$email->from(array($userEmail));
$email->to('email#example.com');
$email->subject('Website Contact Form Submission');
$email->send($userMessage);
if ($email->send($userMessage)) {
$this->Session->setFlash('Thank you for contacting us');
}
else {
$this->Session->setFlash('Mail Not Sent');
}
}
}
public function contact() {
if(isset($this->data['Contact'])) {
$userEmail = $this->data['Contact']['email'];
$userMessage = $this->data['Contact']['message'];
$email = new CakeEmail();
$email->from(array($userEmail));
$email->to('email#example.com');
$email->subject('Website Contact Form Submission');
$email->send($userMessage);
if ($email->send($userMessage)) {
$this->Session->setFlash('Thank you for contacting us');
// $this->redirect(array('controller' => 'pages', 'action' => 'index'));
}
else {
$this->Session->setFlash('Mail Not Sent');
}
}
}
}
?>
<!-- View: Views/Contacts/index.ctp -->
<?
$main = 'contact';
$title = 'quick contact';
?>
<div style="border-bottom: solid 1px #ccc;">
<h1 style="position:relative; float:left;"><?php echo $main; ?></h1>
<h2 style="position:relative;float:left;margin-top:15px; color: #869c38"> • <?php echo $title;?></h2>
<br><br>
</div>
<div class="clear"><br></div>
<div id="interior-page">
<?php
echo $this->Form->create('Contact');
echo $this->Form->input('name', array('default' => 'name (required)', 'onfocus' => 'clearDefault(this)'));
echo $this->Form->input('email', array('default' => 'email (required)', 'onfocus' => 'clearDefault(this)'));
echo $this->Form->input('message', array('default' => 'message', 'onfocus' => 'clearDefault(this)'));
echo $this->Form->submit();
echo $this->Form->end();
?>
</div>
And here is the view for the quick contact form that is NOT working, located in an element displayed in the footer of the default layout:
<?php
echo $this->Form->create('Contact');
echo $this->Form->input('name', array('default' => 'name (required)', 'onfocus' => 'clearDefault(this)'));
echo $this->Form->input('email', array('default' => 'email (required)', 'onfocus' => 'clearDefault(this)'));
echo $this->Form->input('message', array('default' => 'message', 'onfocus' => 'clearDefault(this)'));
echo $this->Form->submit();
echo $this->Form->end();
?>
I tried different ways of changing the form action, but I couldn't figure that out.
Usually, cake "automagically" creates the action of the form based on where you call it from E.g. if called from the view Views/Contacts/index.ctp, it will set the action to /contacts/index. In case of an element, Cake can't really guess what you're trying to do, so you need to set the action manually:
$this->Form->create('Contact', array('action' => 'index'));
Or set the full URL alternatively:
$this->Form->create('Contact', array('url' => '/contacts/index'));
Make sure you're including the Contact model for use on every page you need to create that form. In your case, since it's in your layout, that likely means you should put it in your AppController, so every page has access to it.
You also need to specify where the form should submit to:
echo $this->Form->create('Contact', array(
'url' => array('controller'=>'contacts', 'action'=>'contact')
)
);
Off-note - You can combine the last 2 lines:
echo $this->Form->end('Submit');
This creates the submit button with text "Submit" and also closes the form.
Thanks for this! It helped me a lot.
Just a quick thing, you're sending the email twice.
Once here:
$email->send($userMessage);
And again here:
if ($email->send($userMessage))
The first instance ($email->send($userMessage)) isn't necessary.
Cheers

How do I take over a value sent by a "null form" redirecting to another controller?

This is my form:
echo $this->Form->create(null, array('url' => '/offices/addOffice'));
echo $this->Form->input('id', array('type' => 'hidden',
'value' => $this->data['Agency']['id']));
echo $this->Form->end(__('Add Office', true));
Now in the addOffice function I would like to get the value sent from this form.
What I did is:
function addOffice($id = null){
$this->set(compact('id'));
}
but it doesn't send the $id to the view. What am I doing wrong?
I'm not sure what you're asking, because if you want to "get the value sent from this form", then "send the $id to the view" doesn't have anything to do with it.
If you want to retrieve the the data from the form, you shouldn't put null as the model's name. Use the relevant model, which I assume is "Office" in this case.
echo $this->Form->create('Office', array('url' => '/offices/addOffice'));
echo $this->Form->input('id', array('type' => 'hidden',
'value' => $this->data['Agency']['id']));
Now the id can be retrieved from $this->data[ 'Office' ][ 'id' ] in the controller.
If the question is how you can set the id in the first place using the function parameter, you have to use the $id parameter you've set in the controller:
echo $this->Form->input('id', array('type' => 'hidden',
'value' => $id));