CakePHP - problem with merging add and edit - php

I am trying to "merge" add and edit function so to speak, into one "save" function, which will, whether $id of the model is provided, update or add a new instance of the model. By starting to code this, I realised that this idea brings more complications than built in CakePHP add and edit methods, thing is, my mentor insists that I merge this so I shall try it, even if i personally think this is not the best approach.
ItemTypesController.php
class ItemTypesController extends AppController {
public function save($id = null) {
if($this->request->is(array('post', 'put'))){
$this->ItemType->set($this->request->data);
//if i put an exit() funct here, it exits on this spot
if($this->ItemType->validates()){
if(!$id){
$this->ItemType->create();
if ($this->ItemType->save($this->request->data)) {
$this->Flash->success(__('The item type has been saved.'));
return $this->redirect(array('action' => 'index'));
} else {
$this->Flash->error(__('The item type could not be saved. Please, try again.'));
}
}
else{
if ($this->ItemType->save($this->request->data)) {
$this->Flash->success(__('The item type has been saved.'));
return $this->redirect(array('action' => 'index'));
} else {
$this->Flash->error(__('The item type could not be saved. Please, try again.'));
}
}
} else {
$this->Flash->warning($this->ItemType->validationErrors, array(
'key' => 'negative'
));
}
} else {
$options = array('conditions' => array('ItemType.' . $this->ItemType->primaryKey => $id));
$this->request->data = $this->ItemType->find('first', $options);
}
$this->set('classes', $this->ItemType->classes);
}
}
So basically the function will enter if block if $id is not provided, which is the case if i enter a link for a new ItemType. And it works fine for create, but, when I try to update it it always requires that any field must be changed, because of "isUnique" rule, i set that rule to be only for create, but CakePHP prolly thinks of its create function, albeit here is used my save() funct and it probably thinks it needs to enter that rule for my funct.
ItemType.php
class ItemType extends AppModel {
public $classes = array(
'product' => 'Proizvod',
'kit' => 'Kit (bundle)'
);
public $validate = array(
'code' => array(
'required' => array(
'rule' => 'notBlank',
'message' => 'A code is required'
),
'alphanum' => array(
'rule' => 'alphanumeric',
'message' => 'A code must be an alphanumeric value'
),
'unique' => array(
'rule' => 'isUnique',
'message' => 'This code already exists!',
'required' => 'create'
),
'between' => array(
'rule' => array('lengthBetween', 3, 7),
'message' => 'Code must be between 3 and 7 characters long'
)
),
'name' => array(
'required' => array(
'rule' => 'notBlank',
'message' => 'A name is required'
),
'unique' => array(
'rule' => 'isUnique',
'message' => 'This name already exists!',
'required' => 'create'
),
'between' => array(
'rule' => array('lengthBetween', 3, 30),
'message' => 'Name must be between 3 and 30 characters long'
)
),
'class' => array(
'valid' => array(
'rule' => array('inList', array('product', 'material', 'kit', 'semi_product', 'service_product', 'service_supplier','consumable','inventory','goods','other')),
'message' => 'Please enter a valid class',
'allowEmpty' => false
)
),
'tangible' => array(
'bool' => array(
'rule' => 'boolean',
'message' => 'Incorrect value for the checkbox'
)
),
'active' => array(
'bool' => array(
'rule' => 'boolean',
'message' => 'Incorrect value for the checkbox'
)
)
);
public $hasMany = array(
'Item' => array(
'className' => 'Item',
'foreignKey' => 'item_type_id',
'dependent' => false,
'conditions' => '',
'fields' => '',
'order' => '',
'limit' => '',
'offset' => '',
'exclusive' => '',
'finderQuery' => '',
'counterQuery' => ''
)
);
}
This is the view from which I am entering a new one or updating one:
index.ctp
<div class="itemTypes index">
<h2><?php echo __('Item Types'); ?></h2>
<table cellpadding="0" cellspacing="0">
<thead>
<tr>
<th><?php echo $this->Paginator->sort('id'); ?></th>
<th><?php echo $this->Paginator->sort('code'); ?></th>
<th><?php echo $this->Paginator->sort('name'); ?></th>
<th><?php echo $this->Paginator->sort('class'); ?></th>
<th><?php echo $this->Paginator->sort('tangible'); ?></th>
<th><?php echo $this->Paginator->sort('active'); ?></th>
<th><?php echo $this->Paginator->sort('created'); ?></th>
<th><?php echo $this->Paginator->sort('modified'); ?></th>
<th class="actions"><?php echo __('Actions'); ?></th>
</tr>
</thead>
<tbody>
<?php foreach ($itemTypes as $itemType): ?>
<tr>
<td><?php echo h($itemType['ItemType']['id']); ?> </td>
<td><?php echo h($itemType['ItemType']['code']); ?> </td>
<td><?php echo h($itemType['ItemType']['name']); ?> </td>
<td><?php echo h($itemType['ItemType']['class']); ?> </td>
<td><?php if($itemType['ItemType']['tangible']) echo "Yes"; else echo "No" ?></td>
<td><?php if($itemType['ItemType']['active']) echo "Yes"; else echo "No" ?></td>
<td><?php echo h($itemType['ItemType']['created']); ?> </td>
<td><?php echo h($itemType['ItemType']['modified']); ?> </td>
<td class="actions">
<?php echo $this->Html->link(__('View'), array('action' => 'view', $itemType['ItemType']['id'])); ?>
<?php echo $this->Html->link(__('Edit'), array('action' => 'save', $itemType['ItemType']['id'])); ?>
<?php echo $this->Form->postLink(__('Delete'), array('action' => 'delete', $itemType['ItemType']['id']), array('confirm' => __('Are you sure you want to delete # %s?', $itemType['ItemType']['id']))); ?>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<p>
<?php
echo $this->Paginator->counter(array(
'format' => __('Page {:page} of {:pages}, showing {:current} records out of {:count} total, starting on record {:start}, ending on {:end}')
));
?> </p>
<div class="paging">
<?php
echo $this->Paginator->prev('< ' . __('previous'), array(), null, array('class' => 'prev disabled'));
echo $this->Paginator->numbers(array('separator' => ''));
echo $this->Paginator->next(__('next') . ' >', array(), null, array('class' => 'next disabled'));
?>
</div>
</div>
<div class="actions">
<h3><?php echo __('Actions'); ?></h3>
<ul><li><?php echo $this->Html->link(__('New Item Type'), array('action' => 'save')); ?>
</li>
</ul>
</div>
save.ctp
<div class="itemTypes form">
<?php echo $this->Form->create('ItemType'); ?>
<fieldset>
<legend><?php echo __('Add Item Type'); ?></legend>
<?php
echo $this->Form->input('code');
echo $this->Form->input('name');
echo $this->Form->input('class', array('options' => $classes));
echo $this->Form->input('tangible');
echo $this->Form->input('active');
?>
</fieldset>
<?php echo $this->Form->end(__('Submit')); ?>
</div>
<div class="actions"><h3><?php echo __('Actions'); ?></h3><ul><li><?php echo $this->Html->link(__('List Item Types'), array('action' => 'index')); ?></li></ul></div>

Function save is not coded well, because id of the model was never set, so it did not knew whether it was updating or not.
public function save($id = null) {
if($this->request->is(array('post', 'put'))){
if($id){
$this->request->data['ItemType']['id'] = $id;
}
$this->ItemType->set($this->request->data);
if($this->ItemType->validates()){
if(!$id){
$this->ItemType->create();
}
if ($this->ItemType->save($this->request->data)) {
$this->Flash->success(__('The item type has been saved.'));
return $this->redirect(array('action' => 'index'));
} else {
$this->Flash->error(__('The item type could not be saved. Please, try again.'));
}
} else {
$this->Flash->warning($this->ItemType->validationErrors, array(
'key' => 'negative'
));
}
} else {
$options = array('conditions' => array('ItemType.' . $this->ItemType->primaryKey => $id));
$this->request->data = $this->ItemType->find('first', $options);
}
$this->set('classes', $this->ItemType->classes);}
Now, this is how function should look.

Related

how to validate two form in cakephp

i am new in cakephp.
in View i have 2 form(login and Registration) in both form have email id then how to validate that both from same value in cake php please help and if you have example then please sent that type of information.
First of all define validate function in model
public $validate = array(
'username' => array(
'nonEmpty' => array('rule' => array('notEmpty'),
'message' => 'A username is required',
'allowEmpty' => false),),
'password' => array(
'required' => array(
'rule' => array('notEmpty'),
'message' => 'A password is required' ),
'min_length' => array(
'rule' => array('minLength', '6'),
'message' => 'Password must have a mimimum of 6 characters')),
'password_confirm' => array(
'required' => array(
'rule' => array('notEmpty'),
'message' => 'Please confirm your password' ), ),
'email' => array(
'required' => array(
'rule' => array('email', true),
'message' => 'Please provide a valid email address.' ),
),
);
Then in controller use
function register() {
if( isset($this->data) )
{
$this->User->create();
if($this->User->save($this->data))
{
$this->Session->setFlash( 'Thank you for registering!' );
}else
{
$this->Session->setFlash('An error occurred, try again!');
}
}
}
function login(){
if ($this->request->is('post')) {
$this->User->set($this->request->data);
if ($this->User->validates()) {
echo "This is valid!";
} else {
echo "This is invalid";
$errors = $this->User->validationErrors;
}
}
}
Registration ctp
<div class="users form">
<?php echo $this->Form->create('User');?>
<fieldset>
<legend><?php echo __('Add User'); ?></legend>
<?php echo $this->Form->input('username');
echo $this->Form->input('email');
echo $this->Form->input('password');
echo $this->Form->input('password_confirm', array('label' => 'Confirm Password *', 'maxLength' => 255, 'title' => 'Confirm password', 'type'=>'password'));
echo $this->Form->submit('Add User', array('class' => 'form-submit', 'title' => 'Click here to add the user') ); ?>
</fieldset>
<?php echo $this->Form->end(); ?>
</div>
login.ctp
<div class="users form">
<?php echo $this->Form->create('User');?>
<fieldset>
<legend><?php echo __('Add User'); ?></legend>
<?php echo $this->Form->input('email');
echo $this->Form->input('password');
echo $this->Form->submit('Login'); ?>
</fieldset>
<?php echo $this->Form->end(); ?>
</div>

Zend\View\Renderer\PhpRenderer::render: Unable to render template

Unable to render file error in zf2.
I am working on a project for matrimonial site, in which I need to search data according to matched requirement but get an error.
Here is my code:
//SearchController.php in Project/src/Project/Controller
public function processAction()
{
if (!$this->request->isPost()) {
return $this->redirect()->toRoute(NULL ,
array( 'controller' => 'search',
'action' => 'index'
));
}
$post = $this->request->getPost();
$dbAdapter=$this->getServiceLocator()->get('Zend\Db\Adapter\Adapter');
$form = new SearchForm($dbAdapter);
//$inputFilter = new RegisterFilter();
//$form->setInputFilter($inputFilter);
$form->setData($post);
if (!$form->isValid()) {
$model = new ViewModel(array(
'error' => true,
'form' => $form,
));
$model->setTemplate('project/search/index');
return $model;
}
$ageto = $this->getRequest()->getPost('ageto');
$agefrom = $this->getRequest()->getPost('agefrom');
$heightfrom = $this->getRequest()->getPost('heightfrom');
$heightto = $this->getRequest()->getPost('heightto');
$educationid = $this->getRequest()->getPost('educationid');
$cityid = $this->getRequest()->getPost('cityid');
$complexionid = $this->getRequest()->getPost('complexionid');
$religioncode = $this->getRequest()->getPost('religioncode');
$sql="SELECT * FROM projects WHERE YEAR(CURDATE())-YEAR(dob) BETWEEN ".$agefrom. " AND ".$ageto;
$sql.=" and heightcode BETWEEN ". $heightfrom." AND ". $heightto." and religioncode = ".$religioncode;
$sm = $this->getServiceLocator();
$dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
$statement = $dbAdapter->query($sql);
$result = $statement->execute();
$num=count($result);
if($num==0)
{
echo "No Matches Found";
}
else
{
$result = $statement->execute();
$selectData = array();
foreach ($result as $res) {
$selectData=$res;
}
return $selectData;
}
return $this->redirect()->toRoute(NULL , array(
'controller' => 'search',
'action' => 'confirm'
));
}
public function confirmAction()
{
$viewModel = new ViewModel();
return $viewModel;
}
index.phtml in Project/view/project/search
<html>
<head><link rel="stylesheet" href="/css/demo.css" type="text/css" ></head>
<section class="search">
<p> Welcome! </p>
<h2>Search Form</h2>
<?php if ($this->error): ?>
<p class="error">
There were one or more issues with your submission.
Please correct them as
indicated below.
</p>
<?php endif ?>
<?php
$form = $this->form;
$form->prepare();
$form->setAttribute('action', $this->url(NULL,array('controller'=>'Search', 'action' =>'process')));
$form->setAttribute('method', 'post');
$form->setAttribute('enctype','multipart/form-data');
echo $this->form()->openTag($form);
?>
<body>
<div align="left">
<table align="left" cellpadding="6">
<tr><th>Age:</th>
<td><?php
echo $this->formElement($form->get('agefrom'));
?>
<b>to </b>
<?php echo $this->formElement($form->get('ageto'));
?></td></tr>
<tr><th>Height:</th>
<td><?php
echo $this->formElement($form->get('heightfrom'));
?>
<b>to</b>
<?php echo $this->formElement($form->get('heightto'));
?></td></tr>
<tr><th>Education:</th>
<td><?php
echo $this->formElement($form->get('educationid'));
echo $this->formElementErrors($form->get('educationid'));?></td></tr>
<tr><th>City:</th>
<td><?php
echo $this->formElement($form->get('cityid'));
echo $this->formElementErrors($form->get('cityid'));?></td></tr>
<th>Complexion:</th>
<td><?php
echo $this->formElement($form->get('complexionid'));
echo $this->formElementErrors($form->get('complexionid'));?></td></tr>
<tr><th>Religion:</th>
<td><?php
echo $this->formElement($form->get('religioncode'));
echo $this->formElementErrors($form->get('religioncode'));?></td></tr>
<tr>
<td><?php
echo $this->formElement($form->get('submit'));
echo $this->formElementErrors($form->get('submit'));
?></td></tr>
<?php echo $this->form()->closeTag() ?>
</table>
</section>
</div>
But after clicking on submit I'm getting the renderer error:
Zend\View\Renderer\PhpRenderer::render: Unable to render template "project/search/process"; resolver could not resolve to a file
Module.config.php
<?php
return array(
'controllers' => array(
'invokables' => array(
'Project\Controller\Index' =>
'Project\Controller\IndexController',
'Project\Controller\Register' =>
'Project\Controller\RegisterController',
'Project\Controller\Login' =>
'Project\Controller\LoginController',
'Project\Controller\Search' =>
'Project\Controller\SearchController',
),
),
'router' => array(
'routes' => array(
'project' => array(
'type' => 'Literal',
'options' => array(
'route' => '/project',
'defaults' => array(
'__NAMESPACE__' => 'Project\Controller',
'controller' => 'Index',
'action' => 'index',
),
),
'may_terminate' => true,
'child_routes' => array(
// specific routes.
'default' => array(
'type' => 'Segment',
'options' => array(
'route' =>
'/[:controller[/:action]]',
'constraints' => array(
'controller' =>
'[a-zA-Z][a-zA-Z0-9_-]*',
'action' =>
'[a-zA-Z][a-zA-Z0-9_-]*',
),
'defaults' => array(
),
),
),
),
),
),
),
'view_manager' => array(
'template_path_stack' => array(
'project' => __DIR__ . '/../view',
),
'strategies' => array(
'ViewJsonStrategy',
),
),
);
Do you create file Project/view/project/search/process.phtml?

PHP one form to post to two tables while getting the id of the first table posted to

I am using Cakephp2.0
I have a table for all my images and a table for features.
I have a form that takes the following inputs:
name of feature
text and multiple images with image name.
I need to insert the feature name and text into the feature table, grab id just created, and insert it along with all the image info from the form. I am not sure how to make the controller do that.
controller:
public function add() {
if ($this->request->is('post')) {
$this->Feature->create();
if ($this->Feature->saveAll($this->request->data)) {
$this->Session->setFlash(__('Your Feature has been saved.'));
return $this->redirect(array('controller' => 'dashbords', 'action' => 'index'));
}
$this->Session->setFlash(__('Unable to add your Feature.'));
}
}
form:
<?php
echo $this->Form->create('Feature', array(
'class' => 'form-horizontal',
'role' => 'form',
'type' => 'file',
'inputDefaults' => array(
'format' => array('before', 'label', 'between', 'input', 'error', 'after'),
'div' => array('class' => 'form-group'),
'class' => array('form-control'),
'label' => array('class' => 'col-lg-2 control-label'),
'between' => '<div class="col-lg-6">',
'after' => '</div>',
'error' => array('attributes' => array('wrap' => 'span', 'class' => 'help-inline')),
))); ?>
<?php
echo '<fieldset>';
echo '<legend>Add Features</legend>';
echo '<div class="row"><div class="col-md-4">';
echo $this->Form->input('Feature.name', array('class' => 'feature'));
echo '</div>';
echo '<div class="col-md-8">';
echo '';
echo '</div></div>';
echo '</fieldset>';
//----------------------- Image Block -----------------------------//
// group main image //
echo '<fieldset>';
echo '<div class="row"><div class="col-md-4">';
echo '<legend>Main Image</legend>';
echo $this->Form->input(
'upload', array(
'type' => 'file',
'class' =>'main_image'));
echo $this->Form->input('Image.name', array(
'class' => 'main_image'));
echo $this->Form->input('placement_id', array(
'type' => 'hidden',
'value' => '1',
'class' => 'main_image'));
echo '</div>';
// bottom left image //
echo '<div class="col-md-4">';
echo '<legend>Bottom Left</legend>';
// group image 2//
echo $this->Form->input(
'upload', array(
'type' => 'file',
'class' =>'bl'));
echo $this->Form->input('Image.name', array(
'class' => 'bl'));
echo $this->Form->input('placement_id', array(
'type' => 'hidden',
'value' => '2',
'class' => 'bl'));
echo '</div>';
// bottom right //
echo '<div class="col-md-4">';
echo '<legend>Bottom Right</legend>';
echo $this->Form->input(
'upload', array(
'type' => 'file',
'class' =>'br'));
echo $this->Form->input('Image.name', array(
'class' => 'br'));
echo $this->Form->input('placement_id', array(
'type' => 'hidden',
'value' => '3',
'class' => 'br'));
echo '</div></div>';
echo '</fieldset>';
//----------------------- Gallery Block -----------------------------//
// group 1
echo '<fieldset>';
echo '<legend>Gallery</legend>';
echo '<div class="row"><div class="col-md-4">';
echo $this->Form->input(
'upload', array(
'type' => 'file',
'class' =>'gallery1'));
echo $this->Form->input('Image.name', array(
'class' => 'gallery1'));
echo $this->Form->input('placement_id', array(
'type' => 'hidden',
'value' => '4',
'class' => 'gallery1'));
echo '</div>';
echo '<div class="col-md-4">';
// group image 2//
echo $this->Form->input(
'upload', array(
'type' => 'file',
'class' =>'gallery2'));
echo $this->Form->input('Image.name', array('class'=>'gallery2'));
echo $this->Form->input('placement_id', array(
'type' => 'hidden',
'value' => '4',
'class', 'gallery2'));
echo '</div>';
echo '<div class="col-md-4">';
// group image 3 //
echo $this->Form->input(
'upload', array(
'type' => 'file',
'class' => 'gallery3'));
echo $this->Form->input('Image.name', array('class'=> 'gallery3'));
echo $this->Form->input('placement_id', array(
'type' => 'hidden',
'value' => '4',
'class', 'gallery3'));
echo '</div></div>';
// Feature Text //
echo '</fieldset>';
echo '<div class="row"><div class="col-md-12"><fieldset>';
echo '<legend>Content</legend>';
echo $this->Form->textarea('Feature.content', array('rows' => '10', 'cols' => '75'));
echo '</fieldset></div></div>';
?>
</fieldset>
<div class="row">
<div class="col-md-2 col-md-offset-10">
<?php echo $this->Form->end('Save Content'); ?>
</div>
</div>
Modles:
Featuer:
class Feature extends AppModel{
public $useTable = "features";
public $displayField = "name";
public $hasMany = array(
'Image'=>array('classname' => 'Image', 'foreignkey' => 'image_id'),
);
}
Update:
Per #SverriM.Olsen I have done some more research. I have concluded a few things like how to upload multiple images. Which then lead me to the fact I did dont know how to allow for a name to use as the image alt tag, so I removed that and in my controller add function I looped through the array and grabbed the file name minus the extension. I have read about set and saveAssociated. Where I am at now it how to join the newly created array of names and add then to the image table with the images from the form. here is an updated controller:
public function add() {
//get array of images loop throug
$file = $this->request->data['Image']['image'];
// get file name and extract name - extention
$name = array();
foreach($file as $key=>$value){
foreach($value as $k=>$v){
if($k == 'name'){
$file = $v;
$info = pathinfo($file);
$file_name = basename($file,'.'.$info['extension']);
$this->set(
'Image', array(
'name'=> $name[] = $file_name));
}
}
}
if ($this->request->is('post')) {
$this->Feature->create();
if ($this->Feature->saveAssociated($this->request->data)) {
$this->Session->setFlash(__('Your Feature has been saved.'));
return $this->redirect(array('controller' => 'dashbords', 'action' => 'index'));
}
$this->Session->setFlash(__('Unable to add your Feature.'));
debug($this->Feature->validationErrors);
}
}
and an updated form (add.ctp)
<?php
echo $this->Form->create('Feature', array(
'class' => 'form-horizontal',
'role' => 'form',
'type' => 'file',
'inputDefaults' => array(
'format' => array('before', 'label', 'between', 'input', 'error', 'after'),
'div' => array('class' => 'form-group'),
'class' => array('form-control'),
'label' => array('class' => 'col-lg-2 control-label'),
'between' => '<div class="col-lg-6">',
'after' => '</div>',
'error' => array('attributes' => array('wrap' => 'span', 'class' => 'help-inline')),
))); ?>
<?php
echo '<fieldset>';
echo '<legend>Add Features</legend>';
echo '<div class="row"><div class="col-md-4">';
echo $this->Form->input('name');
echo $this->Form->textarea('content', array('rows' => '5', 'cols' => '55'));
echo '<br/><br/>';
echo '<div class="col-md-8">';
echo '';
echo '</div></div>';
echo '</fieldset>';
//----------------------- Image Block -----------------------------//
// group main image //
echo '<fieldset>';
echo '<div class="row"><div class="col-md-4">';
echo '<legend>Main Image</legend>';
echo '<p>Uploade multiple image for each lug set at once.</p>';
echo $this->Form->input(
'Image.image.', array(
'type' => 'file',
'multiple' => 'multiple',
'class' =>'main_image'));
echo $this->Form->input('Image.name', array(
'type' => 'hidden',
'class' => 'main_image'));
echo $this->Form->input('placement_id', array(
'type' => 'hidden',
'value' => '1',
'class' => 'main_image'));
echo '</div>';
// bottom left image //
echo '<div class="col-md-4">';
echo '<legend>Bottom Left</legend>';
// group image 2//
echo $this->Form->input(
'Image.image.', array(
'type' => 'file.',
'multiple' => 'multiple',
'class' =>'bl'));
echo $this->Form->input('Image.name', array(
'class' => 'bl'));
echo $this->Form->input('placement_id', array(
'type' => 'hidden',
'value' => '2',
'class' => 'bl'));
echo '</div>';
// bottom right //
echo '<div class="col-md-4">';
echo '<legend>Bottom Right</legend>';
echo $this->Form->input(
'Image.image.', array(
'type' => 'file',
'class' =>'br'));
echo $this->Form->input('Image.name', array(
'class' => 'br'));
echo $this->Form->input('placement_id', array(
'type' => 'hidden',
'value' => '3',
'class' => 'br'));
echo '</div></div>';
echo '</fieldset>';
//----------------------- Gallery Block -----------------------------//
// group 1
echo '<fieldset>';
echo '<legend>Gallery</legend>';
echo '<div class="row"><div class="col-md-4">';
echo $this->Form->input(
'Image.image.', array(
'type' => 'file',
'class' =>'gallery1'));
echo $this->Form->input('Image.name', array(
'class' => 'gallery1'));
echo $this->Form->input('placement_id', array(
'type' => 'hidden',
'value' => '4',
'class' => 'gallery1'));
echo '</div>';
echo '<div class="col-md-4">';
// group image 2//
echo $this->Form->input(
'Image.image.', array(
'type' => 'file.',
'class' =>'gallery2'));
echo $this->Form->input('Image.name', array('class'=>'gallery2'));
echo $this->Form->input('placement_id', array(
'type' => 'hidden',
'value' => '4',
'class', 'gallery2'));
echo '</div>';
echo '<div class="col-md-4">';
// group image 3 //
echo $this->Form->input(
'Image.image.', array(
'type' => 'file.',
'class' => 'gallery3'));
echo $this->Form->input('placement_id', array(
'type' => 'hidden',
'value' => '4',
'class', 'gallery3'));
echo '</div></div>';
?>
</fieldset>
<div class="row">
<div class="col-md-2 col-md-offset-10">
<?php echo $this->Form->end('Save Content'); ?>
</div>
</div>
Any help or pointer to places that will help is great. I will try some more googling.
Thank you in advance.

Editing and Deleting in Codeigniter

I created a table with search functionality that displays information from my database. I have made so on the last 2 columns of each row has an edit and delete link. The problem is that the when I click edit it won't direct me to the form I created and linked it to, As for the delete link it won't delete at all. I am going to include the code for the view, if you need me to show anymore code just ask and I'll do so.
<table align="center">
<tr>
<th>Voter #</th>
<th>First Name</th>
<th>Last Name</th>
<th>Middle</th>
<th>Home #</th>
<th>Street</th>
<th>Apt</th>
<th>Zip</th>
<th>DOB</th>
<th>District</th>
<th>Edit</th>
<th>Delete</th>
</tr>
<?php
foreach($query as $voter){
$voter_id = $voter['voterNum'];
?>
<tr align="center">
<td><?php echo $voter['voterNum'] ?></td>
<td><?php echo $voter['firstName'] ?></td>
<td><?php echo $voter['lastName'] ?></td>
<td><?php echo $voter['midInitial'] ?></td>
<td><?php echo $voter['homeNum'] ?></td>
<td><?php echo $voter['street'] ?></td>
<td><?php echo $voter['apt'] ?></td>
<td><?php echo $voter['zip'] ?></td>
<td><?php echo $voter['dob'] ?></td>
<td><?php echo $voter['district'] ?></td>
<td>Edit</td>
<td><?php echo anchor('reg/delete_voter'.$voter_id, 'Delete',
array('onClick' => "return confirm('Are you sure you want to delete?')"));
?>
</td>
</tr>
<?php
}
?>
</table>
UPDATE
Controller
public function search(){
$search_term = array(
'firstName' => $this->input->post('firstName'),
'lastName' => $this->input->post('lastName'),
'street' => $this->input->post('street'),
'dob' => $this->input->post('dob')
);
$data['query'] = $this->reg_model->search_voters($search_term);
$this->load->view("reg_header");
$this->load->view("reg_nav");
$this->load->view("reg_search", $data);
}
function edit_voter($voter_id) {
$voter = $this->reg_model->get_voter($voter_id);
$this->data['title'] = 'Edit Voter';
$this->load->library("form_validation");
$this->form_validation->set_rules("firstName", "First Name", "required");
$this->form_validation->set_rules("lastName", "Last Name", "required");
$this->form_validation->set_rules("homeNum", "Home Number", "required");
$this->form_validation->set_rules("street", "Street", "required");
$this->form_validation->set_rules("zip", "Zip Code", "required");
$this->form_validation->set_rules("dob", "Date of Birth", 'trim|required|valid_date[d/m/y,/]');
$this->form_validation->set_rules("district", "District", "required");
if (isset($_POST) && !empty($_POST))
{
$data = array(
'firstName' => $this->input->post('firstName'),
'lastName' => $this->input->post('lastName'),
'midInitial' => $this->input->post('midInitial'),
'homeNum' => $this->input->post('homeNum'),
'street' => $this->input->post('street'),
'apt' => $this->input->post('apt'),
'zip' => $this->input->post('zip'),
'dob' => $this->input->post('dob'),
'district' => $this->input->post('district')
);
if ($this->form_validation->run() === true)
{
$this->reg_model->update_voter($voter_id, $data);
$this->session->set_flashdata('message', "<p>voter updated successfully.</p>");
redirect(base_url().'reg/search/'.$voter_id);
}
}
$this->data['message'] = (validation_errors() ? validation_errors() : $this->session->flashdata('message'));
$this->data['voter'] = $voter;
$this->data['firstName'] = array(
'name' => 'firstName',
'id' => 'firstName',
'type' => 'text',
'value' => $this->form_validation->set_value('firstName', $voter['firstName'])
);
$this->data['lastName'] = array(
'name' => 'lastName',
'id' => 'lastName',
'type' => 'text',
'value' => $this->form_validation->set_value('lastName', $voter['lastName'])
);
$this->data['midInitial'] = array(
'name' => 'midInitial',
'id' => 'midInitial',
'type' => 'text',
'value' => $this->form_validation->set_value('midInitial', $voter['firstName'])
);
$this->data['homeNum'] = array(
'name' => 'homeNum',
'id' => 'homeNum',
'type' => 'text',
'value' => $this->form_validation->set_value('homeNum', $voter['homeNum'])
);
$this->data['street'] = array(
'name' => 'street',
'id' => 'street',
'type' => 'text',
'value' => $this->form_validation->set_value('street', $voter['street'])
);
$this->data['apt'] = array(
'name' => 'apt',
'id' => 'apt',
'type' => 'text',
'value' => $this->form_validation->set_value('apt', $voter['apt'])
);
$this->data['zip'] = array(
'name' => 'zip',
'id' => 'zip',
'type' => 'text',
'value' => $this->form_validation->set_value('zip', $voter['zip'])
);
$this->data['dob'] = array(
'name' => 'dob',
'id' => 'dob',
'type' => 'text',
'value' => $this->form_validation->set_value('dob', $voter['dob'])
);
$this->data['district'] = array(
'name' => 'district',
'id' => 'district',
'type' => 'text',
'value' => $this->form_validation->set_value('district', $voter['district'])
);
$this->load->view('edit_voter_form', $this->data);
}
function delete_voter($voter_id) {
$this->reg_model->del_voter($voter_id);
$this->session->set_flashdata('message', '<p>Product were successfully deleted!</p>');
redirect(base_url('reg/search'));
}
Why mix base_url() and anchor()? Just use anchor().
<td><?php echo anchor("reg/edit_voter/{$voter_id}", 'Edit') ?></td>
<td><?php echo anchor('reg/delete_voter/'.$voter_id, 'Delete',
array('onClick' => "return confirm('Are you sure you want to delete?')"));
?>
</td>
I think your delete link is missing a trailing slash.

Show all model validation errors on top of the page in cakePHP

I am new to CakePHP. When I am using Model Field Validations then it is showing error message infront of each required form field. I want to show it in a div at the top of the form. How I can implement it. Thanks in advance.
Here is my Code:
Model:
<?php
class User extends AppModel {
public $validate = array(
'username' => array(
'required' => array(
'rule' => array('notEmpty'),
'message' => 'A username is required'
),
array(
'rule' => array('minLength', 8),
'message' => 'Username must be at least 6 characters long'
)
),
'password' => array(
'required' => array(
'rule' => array('notEmpty'),
'message' => 'A password is required'
)
),
'city' => array(
'required' => array(
'rule' => array('notEmpty'),
'message' => 'A City is required'
)
),
'state' => array(
'required' => array(
'rule' => array('notEmpty'),
'message' => 'A State is required'
)
),
'role' => array(
'valid' => array(
'rule' => array('inList', array('admin', 'author')),
'message' => 'Please enter a valid role',
'allowEmpty' => false
)
)
);
}
UsersController.php
public function add() {
$this->set('states_options', $this->State->find('list', array('fields' =>array('id','name') )));
$this->set('cities_options', array());
if ($this->request->is('post')) {
$this->User->set($this->request->data);
if($this->User->validates())
{
$this->User->create();
if ($this->User->save($this->request->data)) {
$this->Session->setFlash(__('The user has been saved'));
$this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The user could not be saved. Please, try again.'));
}
}
else {
$errors = $this->User->validationErrors;
$this->set('ValidateAjay',$errors);
//pr($errors);die;
}
}
}
User View:
<!--<script src="http://code.jquery.com/jquery-1.7.2.js"></script>-->
<script>
$(document).ready(function(){
$('#UserState').change(function(){
var stateid=$(this).val();
$.ajax({
type: "POST",
url: "checkcity",
data:'stateid='+stateid+'&part=checkcity',
success: function(data) {
$("#city_div").html(data);
}
});
});
});
</script>
<div class="users form">
<?php
if(!empty($ValidateAjay)){
pr($ValidateAjay);
}
echo $this->Form->create('User'); ?>
<fieldset>
<legend><?php echo __('Add User'); ?></legend>
<?php
echo $this->Form->input('username');
echo $this->Form->input('password');
echo $this->Form->input('state', array('options' => $states_options , 'empty' => 'Select State' ));
?>
<div id="city_div">
<?php
echo $this->Form->input('city', array('options' => $cities_options, 'empty' => 'Select City' ));
?>
</div>
<?php
echo $this->Form->input('role', array(
'options' => array('admin' => 'Admin', 'author' => 'Author')
));
?>
</fieldset>
<?php echo $this->Form->end(__('Submit')); ?>
</div>
You can get all validation errors from the $this->validationErrors variable on the view. Then feel free to iterate through them and display as you like. They will be organized by model, like so:
array(
'User' => array(
'username' => 'This field cannot be empty.',
'password' => 'This field cannot be empty.'
)
);
Then you can iterate through them on the view and display them as such. This example displays them as an unordered list:
$errors = '';
foreach ($this->validationErrors['User'] as $validationError) {
$errors .= $this->Html->tag('li', $validationError);
}
echo $this->Html->tag('ul', $errors);
Lastly, you can hide the form helper's automatic error messages by hiding them with CSS or setting the FormHelper defaults to not show them.
CSS
.input.error {
display: none;
}
or
in the view
$this->Form->inputDefaults(array(
'error' => false
));
jeremyharris example makes a lot of sense, however if you don't want to manually set loop for every form field, you can try this:
$errors = '';
foreach($this->validationErrors as $assoc) {
foreach ($assoc as $k => $v) {
$errors .= $this->Html->tag('li', $v);
}
}
echo $this->Html->tag('ul', $errors);
So if your validation returns multiple errors, the output will looks like this:
- A username is required
- A password is required
Though this is a very old post, I'd like to answer my solution here as well.
To get Errors of Model Validations, just use the $model->getErrors();. This will return an array of errors with field key.
Example
$errors = $user->getErrors();

Categories