Notice: Undefined index - doctrine

I have this error message when I submit form.
Notice: Undefined index: title in
C:\xampp\htdocs\ameyaw\module\BusinessGhana\src\Service\AutosManager.php
on line 38
Notice: Undefined index: description in
C:\xampp\htdocs\ameyaw\module\BusinessGhana\src\Service\AutosManager.php
on line 39
Notice: Undefined index: featured in
C:\xampp\htdocs\ameyaw\module\BusinessGhana\src\Service\AutosManager.php
on line 58
Message:
An exception occurred while executing 'INSERT INTO auto (title,
description, featured, date_created) VALUES (?, ?, ?, ?)' with params
[null, null, null, "2017-06-15 05:04:44"]:
SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'title'
cannot be null
this is my form and fieldset
use Zend\Form\Fieldset;
use Doctrine\Common\Persistence\ObjectManager;
use DoctrineModule\Persistence\ObjectManagerAwareInterface;
use BusinessGhana\Entity\Autos;
class AddFieldset extends Fieldset
{
protected $objectManager;
public function init()
{
$this->add([
'type' => 'text',
'name' => 'title',
'attributes' => [
'id' => 'autoTitle'
],
'options' => [
'label' => 'Title',
'display_empty_item' => true,
'empty_item_label' => 'Maximum of 60 characters',
],
]);
$this->add([
'type' => 'textarea',
'name' => 'description',
'attributes' => [
'id' => 'autoDescription'
],
'options' => [
'label' => 'Description',
'display_empty_item' => true,
'empty_item_label' => 'description',
],
]);
$this->add([
'type' => 'radio',
'name' => 'featured',
'attributes' => [
'id' => 'autoFeatured'
],
'options' => array(
'label' => 'Featured',
'value_options' => array(
array('value' => '0',
'label' => 'No',
'selected' => true,
'label_attributes' => array(
'class' => 'col-sm-2 btn btn-default',
),
),
array(
'value' => '1',
'label' => 'Yes',
'label_attributes' => array(
'class' => 'col-sm-2 btn btn-danger',
),
),
),
'column-size' => 'sm-12',
'label_attributes' => array(
'class' => 'col-sm-2',
),
),
]);
}
}
use Zend\Form\Form;
//use Zend\InputFilter\InputFilter;
class AddForm extends Form
{
public function init()
{
$this->add([
'name' => 'dependentForm',
'type' => AddFieldset::class,
]);
$this->add([
'type' => 'submit',
'name' => 'submit',
'attributes' => [
'value' => 'Submit',
],
]);
}
}
This is my controller action
public function addAction()
{
// Create the form.
$form = new PostForm();
if ($this->getRequest()->isPost()) {
// Get POST data.
$data = $this->params()->fromPost();
// Fill form with data.
$form->setData($data);
if ($form->isValid()) {
// Get validated form data.
$data = $form->getData();
$this->AutosManager->addNewAutos($data);
return $this->redirect()->toRoute('retrieve');
}
}
return new ViewModel([
'form' => $form
]);
}
I know hydration can solve this problem but I don't know how to use it yet.
thanks for any help.
this is my autosManager
class AutosManager
{
/**
* Entity manager.
* #var Doctrine\ORM\EntityManager;
*/
private $entityManager;
/**
* Constructor.
*/
public function __construct($entityManager)
{
$this->entityManager = $entityManager;
}
public function addNewAutos($data)
{
$autos = new Autos();
$autos->setTitle($data['title']);
$autos->setDescription($data['description']);
$autos->setFeatured($data['featured']);
$currentDate = date('Y-m-d H:i:s');
$autos->setDateCreated($currentDate);
$this->entityManager->persist($autos);
$this->entityManager->flush();
}
}
i can retrieve data from database.
This is where i render my forms:
$form = $this->form;
$fieldset = $form->get('dependentForm');
$title = $fieldset->get('title');
$title->setAttribute('class', 'form-control');
$title->setAttribute('placeholder', 'Maximum of 60 characters');
$title->setAttribute('id', 'autoTitle');
$description = $fieldset->get('description');
$description->setAttribute('class', 'form-control');
$description->setAttribute('placeholder', 'Description here...');
$description->setAttribute('id', 'autoDescription');
$featured = $fieldset->get('featured');
$featured->setAttribute('id', 'autoRadio');
$form->get('submit')->setAttributes(['class'=>'btn btn-primary']);
$form->prepare();
echo $this->form()->openTag($form);
?>
<fieldset>
<div class="form-group">
<?= $this->formLabel($title) ?>
<?= $this->formElement($title) ?>
<?= $this->formElementErrors()->render($title,['class'=>'help-block'])?>
</div>
<div class="form-group">
<?= $this->formLabel($description) ?>
<?= $this->formElement($description) ?>
<?=$this->formElementErrors()->render($description,
['class'=>'help-block'])?>
</div>
<div class="form-group">
<?= $this->formLabel($featured) ?>
<?= $this->formElement($featured) ?>
<?= $this->formElementErrors()->render($featured,
['class' =>'help-block']) ?>
</div>
</div></div><div class="row">
<div class="col-md-4">
</fieldset>
<?= $this->formElement($form->get('submit')); ?>

In your function addNewAutos($data) : your $data variable don't have title, description and featured fields. So php consider these as null, and your $this->entityManager->flush() will try to write null values in database, but you have a constraint that at least title must not be null.
So check your $data array contains the title, description and featured fields before to initiate your Auto object...

Related

CakePHP 3 : default validation not working

I am working in CakePHP 3.2. I have users table and register action in UsersController.
I'm trying to add a new record but default validation is not working.
This is my 'UsersTable.php`
<?php
namespace App\Model\Table;
use App\Model\Entity\User;
use Cake\ORM\Query;
use Cake\ORM\RulesChecker;
use Cake\ORM\Table;
use Cake\Auth\DefaultPasswordHasher;
use Cake\Validation\Validator;
class UsersTable extends Table
{
/**
* Initialize method
*
* #param array $config The configuration for the Table.
* #return void
*/
public function initialize(array $config)
{
parent::initialize($config);
$this->table('users');
$this->displayField('name');
$this->primaryKey('id');
$this->addBehavior('Timestamp');
$this->hasMany('UserAddresses', [
'foreignKey' => 'user_id'
]);
}
/**
* Default validation rules.
*
* #param \Cake\Validation\Validator $validator Validator instance.
* #return \Cake\Validation\Validator
*/
public function validationDefault(Validator $validator)
{
$validator
->uuid('id')
->allowEmpty('id', 'create');
$validator
->notEmpty('name');
$validator
->email('email')
->notEmpty('email');
$validator
->add('mobile', [
'minLength' => [
'rule' => ['minLength', 10],
'message' => 'Mobile number must be of 10 characters long',
],
'maxLength' => [
'rule' => ['maxLength', 10],
'message' => 'Mobile number must be of 10 characters long',
]
])
->numeric('mobile')
->notEmpty('mobile');
$validator
->notEmpty('password');
$validator
->add('newPassword', [
'compare' => [
'rule' => ['compareWith', 'confirmNewPassword'],
]
])
->notEmpty('newPassword');
$validator
->add('confirmNewPassword', [
'compare' => [
'rule' => ['compareWith', 'newPassword'],
'message' => 'Password does not match'
]
])
->notEmpty('confirmNewPassword');
return $validator;
}
/**
* Returns a rules checker object that will be used for validating
* application integrity.
*
* #param \Cake\ORM\RulesChecker $rules The rules object to be modified.
* #return \Cake\ORM\RulesChecker
*/
public function buildRules(RulesChecker $rules)
{
$rules->add($rules->isUnique(['email']));
return $rules;
}
public function validationPassword(Validator $validator)
{
$validator
->add('old_password', 'custom', [
'rule' => function($value, $context){
$user = $this->get($context['data']['id']);
if ($user) {
if((new DefaultPasswordHasher)->check($value, $user->password)) {
return true;
}
}
return false;
},
'message' => 'The old password does not match the current password!',
])
->notEmpty('old_password');
$validator
->add('password1', [
'length' => [
'rule' => ['minLength', 6],
'message' => 'The Password have to be at least 6 characters!',
]
])
->add('password1', [
'match' => [
'rule' => ['compareWith', 'password2'],
'message' => 'The passwords does not match!',
]
])
->notEmpty('password1');
$validator
->add('password2', [
'length' => [
'rule' => ['minLength', 6],
'message' => 'The Password have to be at least 6 characters!',
]
])
->add('password2', [
'match' => [
'rule' => ['compareWith', 'password1'],
'message' => 'The passwords does not match!',
]
])
->notEmpty('password2');
return $validator;
}
}
register() method
public function register()
{
// if already logged in, redirect to referer action to prevent new registration
if (!empty($this->Auth->user('id'))) {
return $this->redirect($this->referer());
}
$user = $this->Users->newEntity();
if ($this->request->is('post')) {
// check user exists or not
$userExists = $this->Users->find('all', [
'conditions' => [
'OR' => [
'email' => $this->request->data['email'],
'mobile' => $this->request->data['mobile'],
]
]
]);
if ($userExists->count() > 0) {
$userExists = $userExists->first();
$this->Flash->success(__('It seems you are already registered. Please login using your email or mobile and passowrd'));
return $this->redirect(['controller' => 'Users', 'action' => 'login']);
}
$hash = hash('sha256',date('YmdHis').time());
$user->tmp_hash = $hash;
$user->verified = 0;
$user = $this->Users->patchEntity($user, $this->request->data);
if ($u = $this->Users->save($user)) {
// send verification email
if ($this->sendEmail($user->id, $user->email, $hash, 'register')) {
$this->Flash->registerSuccess(__('Thank you. You need to verify email. Not received verification email ?'), [
'params' => [
'userId' => $user->id
],
['escape' => false]
]);
return $this->redirect(['action' => 'login']);
} else {
$this->Flash->error(__('The user could not be saved. Please, try again.'));
return $this->redirect(['action' => 'login']);
}
}
}
$this->set(compact('user'));
$this->set('_serialize', ['user']);
}
register.ctp view
<?= $this->Form->create(null, ['url' => ['controller' => 'Users', 'action' => 'register'], 'class' => 'regForm']) ?>
<div class="form-group">
<label>Name <?= $this->Form->error('name') ?></label>
<?= $this->Form->input('name', ['class' => 'form-control', 'label' => false, 'placeholder' => 'Enter Your Name', 'title' => 'Please Enter your full name']) ?>
</div>
<div class="form-group">
<label>Email address</label>
<?= $this->Form->input('email', ['label' => false, 'class' => 'form-control', 'placeholder' => 'Enter Email', 'title' => 'Please enter valid email']) ?>
</div>
<div class="form-group">
<label>Mobile</label>
<?= $this->Form->input('mobile', ['label' => false, 'class' => 'form-control', 'placeholder' => 'Mobile Number', 'title' => 'Please enter valid mobile no to receive notifications']) ?>
</div>
<div class="form-group">
<label>Password</label>
<?= $this->Form->input('password', ['label' => false, 'class' => 'form-control', 'placeholder' => 'Password', 'title' => 'Please enter password']) ?>
</div>
<?= $this->Form->button('<i class="fa fa-user"></i> Create and account', ['type' => 'submit', 'class' => 'btn btn-primary', 'escape' => false]) ?>
<?= $this->Form->end() ?>
</div>
When I try to submit form without filling anything, it simply refreshes the form without showing validation error.
In your register.ctp file
$this->Form->create(null, ['url' => ['controller' => 'Users', 'action' => 'register'], 'class' => 'regForm']);
Replace it with
$this->Form->create($user, ['url' => ['controller' => 'Users', 'action' => 'register'], 'class' => 'regForm']);
As per concept of CakePHP v3 you have to pass entity in Form Creation method so it will display form validation error in view.

CakePHP 3 : Retrieving data from database using Ajax

I am working on a CakePHP 3 project which is having a Apply Coupon form.
I want to apply the coupon using Ajax.
The view of coupon form is
<?= $this->Form->create(null, [
'url' => ['controller' => 'Coupons', 'action' => 'checkCoupon'],
'name' => 'checkCoupon'
]) ?>
<?= $this->Form->input('coupon_code', [
'type' => 'text',
'placeholder' => 'Apply Coupon Code',
'label' => false
]) ?>
<?= $this->Form->submit('Apply Coupon') ?>
and the checkCoupon action in CouponsController is
public function checkCoupon()
{
$this->request->onlyAllow('ajax'); // No direct access via browser URL
if ($this->request->is('post')) {
$couponCode = $this->request->data['coupon_code'];
$couponCheck = $this->Coupons->find('all', [
'conditions' => [
'coupon_code' => $couponCode
]
]);
if ($couponCheck->count() === 1) {
$coupon = $couponCheck->first();
$valid_till = $coupon->valid_till;
$dt = new Time($valid_till);
$date = $dt->format('Y-m-d');
if ($date >= date('Y-m-d')) {
echo 'Coupon is Valid. Discount of '.$coupon->value.'has been applied';
} else {
echo 'Coupon is Expired';
}
} else {
echo 'This is not a valid coupon code';
}
}
}
I want the $coupon->value and $coupon->id to be retrieved and added to the checkout link as
<?= $this->Html->link(__('Confirm Checkout'), ['controller' => 'ServiceRequests', 'action' => 'confirmCheckout', $service->id, $primaryAddressId, $serviceArea->id, $coupon->id], ['class' => 'btn btn-block btn-success']) ?>
The Apply Coupon form is in checkout action of RequestsController
Also the form is working well. I have checked it by removing the onlyAllow('ajax') line and printing values in check_coupon.ctp view.
How could I do it using Ajax ?
Edit 2 : checkout.ctp
<div class="form-info coupon">
<?= $this->Form->create(null, [
'url' => ['controller' => 'Coupons', 'action' => 'ajax_checkCoupon'],
'name' => 'checkCoupon',
'id' => 'checkCoupon'
]) ?>
<?= $this->Form->input('coupon_code', [
'type' => 'text',
'placeholder' => 'Apply Coupon Code',
'label' => false
]) ?>
<label class="hvr-sweep-to-right">
<?= $this->Form->submit('Apply Coupon', ['id' => 'applyCoupon']) ?>
</label>
<label id="couponUpdate"></label>
<label id="loading" style="display:none;">Loading...</label>
<?php
$data = $this->Html->script('#checkCoupon')->serializeForm(['isForm' => true, 'inline' => true]);
$this->Html->script('#checkCoupon')->event(
'submit',
$this->Html->script(
[
'controller' => 'Coupons',
'action' => 'ajax_checkCoupon'
],
[
'update' => '#couponUpdate',
'data' => $data,
'async' => true,
'dataExpression' => true,
'before' => "$('#loading').fadeIn();$('#applyCoupon').attr('disabled','disabled');",
'complete' => "$('#loading').fadeOut();$('#applyCoupon').removeAttr('disabled');"
]
)
);
?>
</div>
Error : Call to a member function serializeForm() on string on line 18 in checkout.ctp

Yii Refresh Grid On DropDown change

In YII views folder i have test module and admin.php file to manage contents are below and i render form here where i put the code of form and dropdown in it , i want that grid refresh value of status change in dropdown
Suppose i select "Approved" than Grid show the data where status is approved
<?php
Yii::app()->clientScript->registerScript('dropdown', "
$('.dropdown-form form').submit(function(){
$('#testimonial-grid').yiiGridView('update', {
data: $(this).serialize()
});
return false;
});
");
?>
<h1>Manage Testimonials</h1>
<div class="dropdown-form">
<?php $this->renderPartial('_dropdownform',array(
'model'=>$model,
)); ?>
</div><!-- search-form -->
<?php $this->widget('zii.widgets.grid.CGridView', array(
'id'=>'testimonial-grid',
'dataProvider'=>$model->search(),
'filter'=>$model,
'columns'=>array(
'id',
'created_by',
'test_name',
'test_email',
'comments',
'created_at',
/*
'status',
'approved_on',
'approved_by',
*/
array(
'class'=>'CButtonColumn',
),
),
)); ?>
Form below is _dropdownform , it contain a form and dropdown from this dropdown i am choosing the value of status
<div class="wide form">
<?php
$form = $this->beginWidget('CActiveForm', array(
'action' => Yii::app()->createUrl($this->route),
'method' => 'get',
));
?>
<div class="row">
<?php
echo CHtml::dropDownList('status', '', array(0 => 'New', 1 => 'Approved', 2 => 'Declined'), array(
'prompt' => 'Select Status',
'ajax' => array(
'type' => 'POST',
'url' => Yii::app()->createUrl('testimonial/loadthedata'),
//or $this->createUrl('loadcities') if '$this' extends CController
'update' => '#testimonial-grid', //or 'success' => 'function(data){...handle the data in the way you want...}',
'data' => array('status' => 'js:this.value'),
)));
?>
</div>
<div class="row buttons">
<?php //echo CHtml::submitButton('Search'); ?>
</div>
<?php $this->endWidget(); ?>
</div><!-- search-form -->
AND THE CODE IN MY CONTROLLER OR URL GIVEN IN DROPDOWN TO FETCH DATA IS FOLLOWING ACTION BUT I DONT KNOW HOW TO FETCH DATA FROM THIS FUNCTION AND PASS TO GRID VIEW
public function actionloadthedata() {
if (isset($_POST['status'])) {
$status = $_POST['status'];
if($status==0){
$status='New';
}
if($status==1){
$status='Approved';
}
if($status==2){
$status='Declined';
}
Testimonial::model()->findByAttributes(array('status'=>$status));
}
}
You can use CGridView property filterCssClass to link the grid filter, for example
$this->widget('CGridView', array(
'id' => 'my-list',
'filterCssClass' => '#filterFormId .filter',
And there is filter form
<?php $form = $this->beginWidget('CActiveForm', array(
'id' => 'filter-fomr-id',
)); ?>
<div class="filter clearfix">
<?php echo $form->dropDownList($model, 'name', [0=>'all', '1'=>'some else']); ?>
</div>
Replace #filterFormId .filter on jquery selector specific to you form. In other words, set id attribute for filter form, then use "#THISID .row".
In your gridview file, make sure you have this code:
Yii::app()->clientScript->registerScript('search', "
$('.search-button').click(function(){
$('.search-form').toggle();
return false;
});
$('.search-form form').submit(function(){
$('#ad-grid').yiiGridView('update', {
data: $(this).serialize()
});
return false;
});
");
then in the CGridView definition:
$this->widget('zii.widgets.grid.CGridView', array(
'id'=>'testimonial-grid',
'dataProvider'=>$model->search(),
'filter'=>$model,
'columns'=>array(
...
array(
'name'=>'Status',
'filter'=>CHtml::dropDownList('YourModel[status]', $model->status, array(0 => 'New', 1 => 'Approved', 2 => 'Declined'), array('empty' => '--all--') ),
'value'=>'( $data->status == 0) ? "New": ( $data->status == 1) ? "Approved" : "Declined"',
'htmlOptions' => array(
'style' => 'width: 40px; text-align: center;',
),
),
...
array(
'class'=>'CButtonColumn',
),
),
));
// CGridView
In order to save if/else in the 'value' section, you can implement a method in your model that returns the string associated to the integer.
It works great, just with the default Yii admin.php view, which you can edit as much as you need.
Update
Added support for empty status, does not filter query results
Thanks #Alex for your help but i am successful to make filterdropdown for grid , code is following but will you please tell me that i want that grid show only values where status=New , how i can do when page load grid show values where status is New
but first i paste the working code of dropdown filter for grid
Here is my admin.php file
<?php
$this->breadcrumbs = array(
'Testimonials' => array('index'),
'Manage',
);
$this->menu = array(
array('label' => 'List Testimonial', 'url' => array('index')),
array('label' => 'Create Testimonial', 'url' => array('create')),
);
?>
<h1>Manage Testimonials</h1>
<!-----------drop down form------------->
<?php
Yii::app()->clientScript->registerScript('dropdownfilter', "
$('.dropdown-form form #staticid').change(function(){
$.fn.yiiGridView.update('testimonial-grid', {
data: $(this).serialize()
});
return false;
});
");
?>
<div class="dropdown-form">
<?php
$this->renderPartial('_dropdownfilter', array(
'model' => $model,
));
?>
</div><!-- search-form -->
<?php
$this->widget('zii.widgets.grid.CGridView', array(
'id' => 'testimonial-grid',
'dataProvider' => $model->search(),
// 'filter' => $model,
'columns' => array(
'id',
'created_by',
'test_name',
'test_email',
'comments',
'created_at',
'status',
array(
'class' => 'CButtonColumn',
),
),
));
?>
Here is my render partial form where i place the static drop dow
<div class="wide form">
<?php
$form = $this->beginWidget('CActiveForm', array(
'action' => Yii::app()->createUrl($this->route),
'method' => 'get',
));
?>
<div class="row">
<?php
echo CHtml::dropDownList('staticid', '', array('0' => 'New', '1' => 'Approved', '2' => 'Declined'), array(
// 'onChange' => 'this.form.submit()',
'ajax' => array(
'type' => 'POST', //request type
)));
?>
</div>
<?php $this->endWidget(); ?>
And Here is code of my adminaction in controller
public function actionAdmin() {
$model = new Testimonial('search');
$model->unsetAttributes(); // clear any default values
if (isset($_GET['staticid'])) {
$getStatus = $_GET['staticid'];
if ($getStatus == 0)
$status = 'New';
if ($getStatus == 1)
$status = 'Approved';
if ($getStatus == 2)
$status = 'Declined';
$model->status = $status;
}
if (isset($_GET['Testimonial']))
$model->attributes = $_GET['Testimonial'];
$this->render('admin', array(
'model' => $model,
));
}
Now i want that when i actionadmin triggered first time it show status=New values

CakePHP validation not working

Iam new in cakephp ,I need to validate a form.
This is the code:
Controller:
<?php
class TasksController extends AppController {
var $name = 'Tasks';
var $helpers = array('Html','Form','Session');
public function index(){
}
function add_task()
{
if(!empty($this->data)) {
//print_r($this->data);
$this->Task->set($this->data);
if ($this->Task->validates()) {
// it validated logic
//echo "ttt";
} else {
// didn't validate logic
echo $errors = $this->Task->validationErrors;
}
}
}
}
?>
Model:
<?php
class Task extends AppModel
{
public var $name = 'Task';
var $useDbConfig = 'travanco_erp';
public var $useTable = 'tbl_tasks'; // This model uses a database table 'exmp'
public var $validate = array(
'task_title_mm' => array(
'rule' => 'notEmpty',
'required' => true,
'message' => 'The title field is required'
),
'task_description_mm' => array(
'rule' => 'notEmpty',
'required' => true,
'message' => 'The description field is required'
),
'task_from_mm' => array(
'rule' => 'notEmpty',
'required' => true,
'message' => 'The from date field is required'
),
'task_to_mm' => array(
'rule' => 'notEmpty',
'required' => true,
'message' => 'The to date field is required'
)
);
}
?>
This is the view:
<div class="employeeForm" style="width:64%; padding:10px 30%;">
<?php echo $this->Form->create('test', array('class'=>'form'));?>
<fieldset style="width:36em; padding:0px 0px;">
<div style="width:475px; font-family:Arial, Helvetica, sans-serif; font-size:16px; color:#333333; font-weight:bold; margin-left:20px; margin-top:10px;">Add Task</div>
<br/>
<?php
/*echo $this->Form->input('task_ids_mm', array( 'div'=>'frm_filed_new',
'error' => array( 'wrap' => 'div',
'class' => 'formerror'
),
'label' => 'Task ID',
));*/
echo $this->Form->input('task_title_mm', array( 'div'=>'frm_filed_new',
'error' => array( 'wrap' => 'div',
'class' => 'formerror'
),
'label' => 'Title',
));
echo $this->Form->input('task_description_mm', array( 'type' => 'textarea',
'cols'=>60,
'rows' => 5,
'div'=>'frm_filed_new',
'error' => array( 'wrap' => 'div',
'class' => 'formerror'
),
'label' => 'Description',
));
echo $this->Form->input('task_from_mm', array( 'div'=>'frm_filed_new','id'=>'task_from_mm','value'=>'',
'error' => array( 'wrap' => 'div',
'class' => 'formerror'
),
'label' => 'From',
));
echo $this->Form->input('task_to_mm', array( 'div'=>'frm_filed_new','id'=>'task_to_mm','value'=>'',
'error' => array( 'wrap' => 'div',
'class' => 'formerror'
),
'label' => 'To',
));
?>
<br/>
<?php echo $this->Form->button('Submit', array('type'=>'submit','escape'=>true)); ?>
</fieldset>
<?php echo $this->Form->end(); ?>
</div>
The validation not working.
What is the error in my code?
How can i solve this?
EDIT:
It is the mistake of misconfiguration of databse.php file.Now its corrected .And the print_r($errors) displays the errors.But that not displayed in the view page , i mean near the textboxes.
This is that error array:
Array ( [task_title_mm] => Array ( [0] => The title field is required ) [task_description_mm] => Array ( [0] => The description field is required ) [task_from_mm] => Array ( [0] => The from date field is required ) [task_to_mm] => Array ( [0] => The to date field is required ) )
How can i put it in near the text box?
CakePHP is designed to automatically validate model and display validation errors. Auto validation runs on model save. In your case:
$this->Task->save($this->request->data);
above will trigger validation. There is no need to run: $this->Task->validates() - If you do so, you also have to take care of displaying validation error by your own. So I think you simply should try:
<?php
class TasksController extends AppController {
var $name = 'Tasks';
var $helpers = array('Html','Form','Session');
function add_task()
{
if ($this->request->is('post')) {
// If the form data can be validated and saved...
if ($this->Task->save($this->request->data)) {
//saved and validated
}
}
}
}
?>
one thing i noticed in your code that you are writing in your model
public var $validate=array();
instead try
public $validate= array() or var $validate=array();
Validation should work after words.
Thanks :)
Try this:
if ($this->Task->validates()) {
// it validated logic
//echo "ttt";
} else {
$this->validateErrors($this->Task);
$this->render();
}

Validation Errors not showing

I am trying to validate a user when they register to my application. Nothing is getting set to validationErrors, which is strange can anyone help me out?
Here is my MembersController
<?php
class MembersController extends AppController {
var $name = 'Members';
var $components = array('RequestHandler','Uploader.Uploader');
function beforeFilter() {
parent::beforeFilter();
$this->layout = 'area';
$this->Auth->allow('register');
$this->Auth->loginRedirect = array('controller' => 'members', 'action' => 'dashboard');
$this->Uploader->uploadDir = 'files/avatars/';
$this->Uploader->maxFileSize = '2M';
}
function login() {}
function logout() {
$this->redirect($this->Auth->logout());
}
function register() {
if ($this->data) {
if ($this->data['Member']['psword'] == $this->Auth->password($this->data['Member']['psword_confirm'])) {
$this->Member->create();
if ($this->Member->save($this->data)) {
$this->Auth->login($this->data);
$this->redirect(array('action' => 'dashboard'));
} else {
$this->Session->setFlash(__('Account could not be created', true));
$this->redirect(array('action' => 'login'));
pr($this->Member->invalidFields());
}
}
}
}
}
?>
Member Model
<?php
class Member extends AppModel {
var $name = 'Member';
var $actsAs = array('Searchable');
var $validate = array(
'first_name' => array(
'rule' => 'alphaNumeric',
'required' => true,
'allowEmpty' => false,
'message' => 'Please enter your first name'
),
'last_name' => array(
'rule' => 'alphaNumeric',
'required' => true,
'allowEmpty' => false,
'message' => "Please enter your last name"
),
'email_address' => array(
'loginRule-1' => array(
'rule' => 'email',
'message' => 'please enter a valid email address',
'last' => true
),
'loginRule-2' => array(
'rule' => 'isUnique',
'message' => 'It looks like that email has been used before'
)
),
'psword' => array(
'rule' => array('minLength',8),
'required' => true,
'allowEmpty' => false,
'message' => 'Please enter a password with a minimum lenght of 8 characters.'
)
);
var $hasOne = array('Avatar');
var $hasMany = array(
'Favourite' => array(
'className' => 'Favourite',
'foreignKey' => 'member_id',
'dependent' => false
),
'Friend' => array(
'className' => 'Friend',
'foreignKey' => 'member_id',
'dependent' => false
),
'Guestbook' => array(
'className' => 'Guestbook',
'foreignKey' => 'member_id',
'dependent' => false
),
'Accommodation'
);
var $hasAndBelongsToMany = array('Interest' => array(
'fields' => array('id','interest')
)
);
function beforeSave($options = array()) {
parent::beforeSave();
if (isset($this->data[$this->alias]['interests']) && !empty($this->data[$this->alias]['interests'])) {
$tagIds = $this->Interest->saveMemberInterests($this->data[$this->alias]['interests']);
unset($this->data[$this->alias]['interests']);
$this->data[$this->Interest->alias][$this->Interest->alias] = $tagIds;
}
$this->data['Member']['first_name'] = Inflector::humanize($this->data['Member']['first_name']);
$this->data['Member']['last_name'] = Inflector::humanize($this->data['Member']['last_name']);
return true;
}
}
?>
login.ctp
<div id="login-form" class="round">
<h2>Sign In</h2>
<?php echo $form->create('Member', array('action' => 'login')); ?>
<?php echo $form->input('email_address',array('class' => 'login-text',
'label' => array('class' => 'login-label')
));?>
<?php echo $form->input('psword' ,array('class' => 'login-text',
'label' => array('class' => 'login-label','text' => 'Password')
))?>
<?php echo $form->end('Sign In');?>
</div>
<div id="signup-form" class="round">
<h2>Don't have an account yet?</h2>
<?php echo $form->create('Member', array('action' => 'register')); ?>
<?php echo $form->input('first_name',array('class' => 'login-text',
'label' => array('class' => 'login-label')
));?>
<?php echo $form->input('last_name',array('class' => 'login-text',
'label' => array('class' => 'login-label')
));?>
<?php echo $form->input('email_address',array('class' => 'login-text',
'label' => array('class' => 'login-label')
));?>
<?php echo $form->input('psword' ,array('class' => 'login-text',
'label' => array('class' => 'login-label','text' => 'Password')
))?>
<?php echo $form->input('psword_confirm' ,array('class' => 'login-text',
'label' => array('class' => 'login-label','text' => 'Confirm'),
'div' => array('style' => ''),
'type' => 'password'
))?>
<?php echo $form->end('Sign In');?>
</div>
I believe your problem is here:
$this->redirect(array('action' => 'login'));
pr($this->Member->invalidFields());
The validation errors are designed to show on the form, underneath the appropriate field. However, instead of continuing and trying to display the form, you are redirecting the user to a different page.
If you remove the two lines above, it should show the validation errors beneath their fields on the form when the validation fails.

Resources