I am not being able to run validation on an array of input fields. When I submit the form, it is submitted OK (data is saved correctly), but without validation (no errors, no messages).
Any idea what I'm doing wrong?
My view:
<?php echo form_open('save', array('id' => 'form')); ?>
<?php foreach ($cars as $row): ?>
<table>
<tr>
<td>
<h2>
<?php echo $row->cars_name; ?>
</h2>
</td>
<th>
Number
</th>
<td>
<?php echo form_input("car[$row->cars_id][cars_number]", $row->cars_number); ?>
</td>
</tr>
<tr>
<td>
</td>
<th>
Registry
</th>
<td>
<?php echo form_input("car[$row->cars_id][cars_number_reg]", $row->cars_number_reg); ?>
</td>
</tr>
</table>
<?php endforeach; ?>
<?php echo form_close(); ?>
My config/form_validation.php:
'test/save' => array(
array(
'field' => 'car[]', // also tried car[][], but no go
'label' => 'Field',
'rules' => 'alpha|htmlspecialchars|trim'
),
),
My controller:
function save()
{
if ($this->form_validation->run() == FALSE) {
$json['success'] = '0';
$json['message'] = validation_errors();
echo json_encode($json);
} else {
$car = $this->input->post('car');
foreach ($car as $k => $v) {
$data['cars_number'] = $v['cars_number'];
$data['cars_number_reg'] = $v['cars_number_reg'];
$cars_id = $k;
$this->emergency_model->save($data, $cars_id);
}
$json['success'] = '1';
echo json_encode($json);
}
}
I suggest using a callback validation function like in this tutorial
in this tutorial
From the user guide form_validation
You must use the "exact" name for validation rules.
In your case validation rules should be generated in foreach, same as your view.
$validation_rules = array();
foreach($cars as $row){
$validation_rules[] = array( 'field'=>'car['.$row->cars_id.'][cars_number]',
'Field',
'rules' => 'alpha|htmlspecialchars|trim'
);
}
$this->form_validation->set_rules($validation_rules);
(note:this code was not tested)
I think you have to do this in controller instead of config.
Related
I want to echo database value for the drop down in edit mode. but in edit page it doesn't show the previously selected drop down value. now i want to echo database values to the drop down. how can i do it. My view controller and model are below. Please any one can help me.
View
<!--//Address-->
<tr><td><?php echo '<label for="heading" class="col-sm-0 control-label">Address </label>';?></td>
<td class="col-lg-10">
<?php
$data = array(
'name' => 'address',
'value' => $post->address,
'class' => 'form-control',
'style' => 'width:140%',
'placeholder' => 'Address of Your Site'
);
echo form_input($data);
echo '<br>';
?>
</td>
</tr>
<!--//Address-->
<?php foreach ($single as $post):?>
$attributes = 'class = "form-control" id = "client" style="width:140%; height:35px;"';
$buildings = array('-SELECT-'=>'-SELECT-', 'House'=>'House', 'Building Complex'=>'Building Complex', 'Commercial Building'=>'Commercial Building', 'Hotel'=>'Hotel','Hospital'=>'Hospital' );
echo form_dropdown('building', $buildings, $post->building,set_value('building'), $attributes);
?>
Controller
function edit_single(){
$id = $this->uri->segment(3);
//load project details according to relevent id
$data['single'] = $this->project_registration_details->show_pro_id($id);
$this->load->view('client/project_registration_edit_view',$data);
}
Model
function show_pro_id($id){
$this->db->select('*');
$this->db->from('project_registration');
$this->db->join('client', 'client.client_id = project_registration.reg_client_id');
$this->db->where('project_registration.id',$id);
$query = $this->db->get();
$result = $query->result();
return $result;
}
Use
set_value('building',$post->building)
in your selected part of form_dropdown function.
Try..
echo form_dropdown('building', $buildings,set_value('building',$post->building), $attributes);
Updated Answer
<?php foreach($single as $post) { ?>
<select name="building" class = "form-control" id = "client" style="width:140%; height:35px;">
<?php
$buildings = array('-SELECT-'=>'-SELECT-', 'House'=>'House', 'Building Complex'=>'Building Complex', 'Commercial Building'=>'Commercial Building', 'Hotel'=>'Hotel','Hospital'=>'Hospital' );
foreach($buildings as $key => $building) { ?>
<option value="<?php echo $key; ?>" <?php echo set_select('building', $post->building); ?>><?php echo $building; ?></option>
<?php } ?>
</select>
<?php } ?>
What I'm trying to do is give users a way to checkout multiple products from the inventory.
My products index page (lists all available products to be checked out) looks like this:
<?php echo $this->Form->create('multi');?>
<?php foreach ($products as $product): ?>
<tr class="hovertable">
//All the fields go here
<td style="cursor: default">
<?php echo $this->Html->link($this->Html->image('tr/Checkouts_Add.png') . " " . __('Checkout'), array('controller' => 'Checkouts','action' => 'add', $product['Product']['id']), array('escape' => false, 'class' => 'button')); ?>
<?php echo $this->Html->link($this->Html->image('tr/Edit.png'), array('action' => 'edit', $product['Product']['id']), array('escape' => false)); ?>
<?php echo $this->Form->postLink($this->Html->image('tr/Delete.png'), array('action' => 'delete', $product['Product']['id']), array('escape' => false), __('Are you sure you want to delete # %s?', $product['Product']['id'])); ?>
<?php echo $this->Form->input('Product.id.'.$product['Product']['id'] ,
array('label' => false,
'type' => 'checkbox',
'id'=>'listing_'.$product['Product']['id'])); ?>
</td>
</tr>
<?php endforeach; ?>
<?php echo $this->Form->submit(__('Submit'));?>
Then in my checkouts controller I've added a new function to checkout multiple items, I'd like this form to be populated by the checked products
public function multi($count = 1) {
if($this->request->is('post')) {
foreach($this->request->data['Checkout'] as $data) {
//Do not forget this line. you need to create new model for saving each time.
if ($this->request->isPost()) {
$this->Checkout->create();
$this->Checkout->save($data);
} else {
$this->request->data['Checkout']['product_id'] = $productId;
}
}
$this->redirect(array('action' => 'index'));
}
$products = $this->Checkout->Product->find('list');
$users = $this->Checkout->User->find('list');
$this->set(compact('products', 'users'));
$this->set('count', $count);
}
As you see I've tried to add hat I thought might work but the Submit button from the products index page does nothing. Any help would be greatly appreciated!
i just check several times and at least i understand one of the reason of your failure is inside of your foreach you have some error or warning as i don't know about the value of your product array i check this code and it worked well for me :
<?php $products=array('0'=>'11','1'=>'22','2'=>'333');
echo $this->Form->create('User');?>
<?php foreach ($products as $product): ?>
<tr class="hovertable">
//All the fields go here
<td style="cursor: default">
<?php echo $this->Form->input('Product.id.'.$product,
array('label' => false,
'type' => 'checkbox',
'id'=>'listing_'.$product)); ?>
</td>
</tr>
<?php
endforeach;
echo $this->Form->end(__('Submit'));
if you have no error or warning i suggest to you check without
$this->Form->postLink
Hi Im trying to create a function that searches my Uploads model and displays the information that is in the that table.
Notice (8): Undefined variable: uploads [APP/View/Uploads/search.ctp, line 28]
Warning (2): Invalid argument supplied for foreach() [APP/View/Uploads/search.ctp, line 28]
Before I am even allowed to search I get this error,
This is my search.ctp
<?php $uploads = $this->requestAction('uploads/search');
?>
<div id="search">
<?php echo $this->Form->create('Upload',array('action'=>'search'));?>
<fieldset>
<legend><?php __('Upload Search');?></legend>
<?php
echo $this->Form->input('searchupload', array('label' => false, 'class'=>'searchinput'));
$options = array(
'label' => '',
'value' => 'Search',
'class' => 'searchbutton'
);
echo $this->Form->end($options);
?>
</fieldset>
</div>
<div id="contentbox">
<table>
<?php foreach($uploads as $upload) : ?>
<tr>
<td><?php echo $upload['Upload']['name'] ?></td>
<td><?php echo $upload['Upload']['eventname'] ?></td>
</tr>
<?php endforeach; ?>
</table>
</div>
and this is the function in the uploads controller:
function search() {
if (!empty($this->data)) {
$searchstr = $this->data['Upload']['search'];
$this->set('searchstring', $this->data['Upload']['search']);
$conditions = array(
'conditions' => array(
'or' => array(
"Upload.name LIKE" => "%$searchstr%",
"Upload.eventname LIKE" => "%$searchstr%"
)
)
);
$this->set('uploads', $this->Upload->find('all', $conditions));
}
}
Any help would be greatly appreciated!
Thanks in advance
<?php if(!empty($uploads)) : ?>
<?php foreach($uploads as $upload) : ?>
<tr>
<td><?php echo $upload['Upload']['name'] ?></td>
<td><?php echo $upload['Upload']['eventname'] ?></td>
</tr>
<?php endforeach; ?>
<?php else : ?>
<div>
No search matches found
</div>
<?php endif; ?>
This ensures that if an empty set is found then the no search match found is thrown into the webpage
Why are you running the uploads/search twice from the same view?
Try removing this from your view:
<?php $uploads = $this->requestAction('uploads/search'); ?>
It calls the same action you are rendering with search.ctp.
UPDATE:
If you are getting the Undefined Variable notice (that you will not see when in production and debug is set to 0 by the way), all you need to do is set the uploads variable to null in the controller (not the view). Before you run the search do: $this->set('uploads', array()); in the controller so the variable will be defined in the view. You do not want to clutter the view with logic.
i have the following search form
<?php
echo $this->Form->create('Order', array('action' => 'search','type'=>'get'));?>
<?php echo $this->Form->input('SearchTerm',array('label' => 'Find:')); ?>
<?php $options=array('full_name'=>'By Name','code'=>'By Code','phone'=>'By Phone','email'=>'By Mail'); ?>
<?php echo $this->Form->input('options', array('type'=>'select', 'label'=>'Search:', 'options'=>$options)); ?>
<?php echo $this->Form->end('search'); ?>
<?php if($rs!=0){?>
<?php if($rs!=null) { ?>
results found : <?php print $results; //print_r ($result['Order']['full_name']); ?>
<h1 class="ico_mug">Results Matching Term: <?php print '"'.$term.'"' ;?></h1>
<table id="table">
<tr>
<th>Client Name</th>
<th>Order Code</th>
<th>Phone</th>
<th>Received Order</th>
<th>Working On Order </th>
<th>Order Ready </th>
</tr>
<!-- Here is where we loop through our $posts array, printing out post info -->
<?php foreach ($rs as $order): ?>
<tr>
<td>
<?php echo $this->Html->link($order['Order']['full_name'],
array('controller' => 'orders', 'action' => 'view', $order['Order']['id'])); ?>
</td>
<td><?php echo $order['Order']['code']; ?></td>
<td><?php echo $order['Order']['phone']; ?></td>
<td><?php echo $this->OrderStatus->getStatusString($order['Order']['receive_state']); ?></td>
<td><?php echo $this->OrderStatus->getStatusString($order['Order']['working_state']); ?></td>
<td><?php echo $this->OrderStatus->getStatusString($order['Order']['ready_state']); ?></td>
<td> <?php //echo $this->Html->link($this->Html->image("cancel.jpg"), array('action' => 'index'), array('escape' => false));?><?php echo $this->Html->link($this->Html->image("edit.jpg"), array('action' => 'edit',$order['Order']['id']), array('escape' => false));/*echo $this->Html->link('Edit', array('action' => 'edit', $order['Order']['id']));*/?></td>
</tr>
<?php endforeach; ?>
<tr ><?php //echo $this->Paginator->numbers(array('first' => 'First page')); ?></tr>
<?php
$urlParams = $this->params['url'];
unset($urlParams['url']);
$optionss=array('url' => array('?' => http_build_query($urlParams)));
//$this->Paginator->options($optionss);
$this->Paginator->settings['paramType'] = 'querystring';
?>
<tr ><?php //echo" << ".$this->Paginator->counter(
// 'Page {:page} of {:pages}');
?></tr>
</table>
<?php }else echo"no results found"; ?>
<?php } //endif?>
and this is my controller action
function search($options=null){
$this->set('results',"");
$this->set('term',"");
$this->set('rs',0);
if ((isset($_GET["SearchTerm"]))||(isset($_GET["options"])) ) {
$SearchTerm=$_GET["SearchTerm"];
$options=$_GET["options"];
if (!$options || !$SearchTerm) {
$this->Session->setFlash('Please enter something to search for');
}
else {
$SearchArray = array($options." LIKE " => "%".$SearchTerm."%");
$this->paginate = array('conditions' => $SearchArray,'limit'=>2,'convertKeys' => array($options, $SearchTerm));
$data=$this->paginate('Order');
$this->set('rs', $data);
$this->set('term',$SearchTerm);
}
}
as you can see i am using Get parameters options and SearchTerm. I want theese two to stay in the pagination links. I have tried various fixes that i've found on stackoverflow and on other site, (like ex:
$urlParams = $this->params['url'];
unset($urlParams['url']);
$optionss=array('url' => array('?' => http_build_query($urlParams)));
yet i still get the following error message :
Indirect modification of overloaded property
PaginatorHelper::$settings has no effect
[APP\View\orders\search.ctp, line 75
why is that? and what about a solution to this ? ( even if i use the wxample from the cookbook
$this->Paginator->settings['paramType'] = 'querystring';
i still get the same error :S can you please help/explain ?
If I understand your code correctly, you should be able to replace:
<?php
$urlParams = $this->params['url'];
unset($urlParams['url']);
$optionss=array('url' => array('?' => http_build_query($urlParams)));
//$this->Paginator->options($optionss);
$this->Paginator->settings['paramType'] = 'querystring';
?>
with
<?php $this->Paginator->options(array('url' => $this->passedArgs)); ?>
Form Fields In Pagination
If you are actually trying to put the form elements into the pagination, you will need to alter your code slightly. You will need to build named parameters for each item in the search options. Then, in the action of the controller, you will need to check for both the request->data and the params['named'] versions of the search to make sure you use them in both cases. I would also clean up the code so it is a little more readable.
First, you need to use the cake methods for getting the data. It will make sure that it cleans the requests for you etc. In addition, you will need to account for the search term and filter options being passed as both a named variable and submitted in a form. So you need to update your controller as follows:
function search($options=null){
$this->set('results',""); // where is this used ??
$this->set('rs', 0);
$this->set('SearchTerm', '');
$this->set('FilterBy', '');
$this->set('options', array('full_name'=>'By Name','code'=>'By Code','phone'=>'By Phone','email'=>'By Mail'));
if ($SearchTerm = $this->request->data['Order']['SearchTerm']) or $SearchTerm = $this->params['named']['SearchTerm']) {
if ($FilterBy = $this->request->data['Order']['FilterBy'] or $FilterBy = $this->params['named']['FilterBy'])) {
$this->paginate = array(
'conditions' => array($FilterBy." LIKE " => "%".$SearchTerm."%"),
'limit' => 2,
'convertKeys' => array($FilterBy, $SearchTerm)
);
$this->set('rs', $this->paginate('Order'));
$this->set('SearchTerm', $SearchTerm);
$this->set('FilterBy', $FilterBy);
} else {
$this->Session->setFlash('Please enter something to search for');
}
} else {
$this->Session->setFlash('Please enter something to search for');
}
}
Next, we focus on the view. Remove move this:
$options=array('full_name'=>'By Name','code'=>'By Code','phone'=>'By Phone','email'=>'By Mail');
It shouldn't be in the view. It belongs in the controller (which is where it is now).
Next, cleanup the form:
<?php
echo $this->Form->create('Order', array('action' => 'search','type'=>'get'));
echo $this->Form->input('SearchTerm',array('label' => 'Find:'));
echo $this->Form->input('FilterBy', array('type'=>'select', 'label'=>'Search:', 'options'=>$options));
echo $this->Form->end('search');
?>
*Note that I changed the options name to FilterBy so it is easier to find in the controller. Also there are other things that could be cleaned up in the view. However, I will only address the things that correspond to the question.
Now you need to replace this code:
<tr ><?php //echo $this->Paginator->numbers(array('first' => 'First page')); ?></tr>
<?php
$urlParams = $this->params['url'];
unset($urlParams['url']);
$optionss=array('url' => array('?' => http_build_query($urlParams)));
//$this->Paginator->options($optionss);
$this->Paginator->settings['paramType'] = 'querystring';
?>
<tr ><?php //echo" << ".$this->Paginator->counter(
// 'Page {:page} of {:pages}');
?></tr>
</table>
With this code:
</table>
<p>
<?php
$this->Paginator->options(array('url' => array_merge(array('SearchString' => $SearchString, 'FilterBy' => $FilterBy), $this->passedArgs)));
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'=>'disabled'));?>
| <?php echo $this->Paginator->numbers();?>
| <?php echo $this->Paginator->next(__('next') . ' >>', array(), null, array('class' => 'disabled'));?>
</div>
You an format it differently of course to fit your needs. But the code should work as expected with the search term and filter option applied to pagination.
Good luck and Happy Coding!
I am building a portfolio website using CakePHP and have named my model 'Portfolio' and my controller 'PortfolioController' however cake decides to look for a table called portfolios instead of just portfolio! How can I fix this as I don't want to call my table portfolios!
Also when dealing with the foreach loop in the views where it has statements like
<?php foreach ($posts as $post): ?> how would I deal with the plural issue with my portfolio?
Thanks
EDIT Here is the index.ctp file where I have the plural issue:
<p><?php echo $this->Html->link("Add Post", array('action' => 'add')); ?></p>
<table>
<tr>
<th>Id</th>
<th>Title</th>
<th>Action</th>
<th>Created</th>
</tr>
<!-- Here's where we loop through our $posts array, printing out post info -->
<?php foreach ($posts as $post): ?>
<tr>
<td><?php echo $post['Portfolio']['id']; ?></td>
<td>
<?php echo $this->Html->link($post['Portfolio']['title'], array('action' => 'view', $post['Portfolio']['id']));?>
</td>
<td>
<?php echo $this->Html->link(
'Delete',
array('action' => 'delete', $post['Portfolio']['id']),
null,
'Are you sure?'
)?>
<?php echo $this->Html->link('Edit', array('action' => 'edit', $post['Portfolio']['id']));?>
</td>
<td><?php echo $post['Portfolio']['created']; ?></td>
</tr>
<?php endforeach; ?>
</table>
EDIT Here is the controller:
<?php
class PortfolioController extends AppController
{
var $helpers = array ('Html','Form');
var $name = 'Portfolio';
function index()
{
$this->set('portfolio', $this->Portfolio->find('all'));
}
function view($id = null)
{
$this->Portfolio->id = $id;
$this->set('portfolio', $this->Portfolio->read());
}
function add()
{
if (!empty($this->data))
{
if ($this->Portfolio->save($this->data))
{
$this->Session->setFlash('Your post has been saved.');
$this->redirect(array('action' => 'index'));
}
}
}
function delete($id)
{
if ($this->Portfolio->delete($id))
{
$this->Session->setFlash('The post with id: ' . $id . ' has been deleted.');
$this->redirect(array('action' => 'index'));
}
}
function edit($id = null)
{
$this->Portfolio->id = $id;
if (empty($this->data))
{
$this->data = $this->Portfolio->read();
}
else
{
if ($this->Portfolio->save($this->data))
{
$this->Session->setFlash('Your post has been updated.');
$this->redirect(array('action' => 'index'));
}
}
}
}
?>
Class Portfolio extends App_Model{
public $useTable = 'portfolio';
}
in you model you can set the $useTable variable to be whatever you need.
in views you pass variable values from controllers with set method
$this->set('portfolio',$array_of_data);
so the first parameter can be anything you like.
in the index action.
$this->set('portfolio', $this->Portfolio->find('all'));
see the code here? that's what I meant.
you are setting $portfolio variable for your view. so you must change all your $posts variables into $portfolio variables.
<p><?php echo $this->Html->link("Add Post", array('action' => 'add')); ?></p>
<table>
<tr>
<th>Id</th>
<th>Title</th>
<th>Action</th>
<th>Created</th>
</tr>
<!-- Here's where we loop through our $posts array, printing out post info -->
<?php foreach ($portfolio as $portfolio_item): ?>
<tr>
<td><?php echo $portfolio_item['Portfolio']['id']; ?></td>
<td>
<?php echo $this->Html->link($portfolio_item['Portfolio']['title'], array('action' => 'view', $portfolio_item['Portfolio']['id']));?>
</td>
<td>
<?php echo $this->Html->link(
'Delete',
array('action' => 'delete', $portfolio_item['Portfolio']['id']),
null,
'Are you sure?'
)?>
<?php echo $this->Html->link('Edit', array('action' => 'edit', $portfolio_item['Portfolio']['id']));?>
</td>
<td><?php echo $portfolio_item['Portfolio']['created']; ?></td>
</tr>
<?php endforeach; ?>
</table>
or change portfolio in set method to posts like this.
$this->set('posts', $this->Portfolio->find('all'));