CakePHP 2.0 search database error - php

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.

Related

Symfony 1 - How to make a link from a foreach

I am really new to Symfony 1. I know it's old and that support has ended for this version. But one of the projects at the company where I do my internship still runs on symfony 1.4.
I have a foreach loop;
<?php foreach ($configuration->getFormFields($form, 'show') as $fieldset => $fields): ?>
<?php //include_partial('service/form_fieldset', array('service' => $service, 'form' => $form, 'fields' => $fields, 'fieldset' => $fieldset)) ?>
<table id="sf_fieldset_<?php echo preg_replace('/[^a-z0-9_]/', '_', strtolower($fieldset)) ?>" cellspacing="0" cellpadding="0" class="sf_admin_st">
<tr>
<th>Property</th>
<th>Value</th>
</tr>
<?php
$i = 0;
foreach ($fields as $name => $field):
?>
<?php $i++;
$class = ($i % 2 == 0) ? 'even' : 'odd';
?>
<?php $attributes = $field->getConfig('attributes', array()); ?>
<?php if ($field->isPartial()): ?>
<?php include_partial('service/' . $name, array('service' => $service, 'form' => $form, 'attributes' => $attributes instanceof sfOutputEscaper ? $attributes->getRawValue() : $attributes)) ?>
<?php elseif ($field->isComponent()): ?>
<?php include_component('service', $name, array('service' => $service, 'form' => $form, 'attributes' => $attributes instanceof sfOutputEscaper ? $attributes->getRawValue() : $attributes)) ?>
<?php else: ?>
<tr class="<?php echo $class ?>">
<td><?php echo $field->getConfig('label') ? $field->getConfig('label') : $field->getName() ?>:</td>
<td><?php echo $form->getObject()->get($name) ? $form->getObject()->get($name) : "-" ?></td>
<?php endif; ?>
</tr>
<?php endif; ?>
<?php endforeach; ?>
</table>
<?php endforeach; ?>
the above mentioned code output table below;
My question is, how can I make a field in the table a link to that specific description. I want the Parent Service value in the table to become a link to that specific value.
I have thought of an if, like this;
<?php if ($field->getConfig('label') == "parent_service_description"): ?>
<td><?php echo $form->getObject()->get($name) ? $form->getObject()->get($name) : "-" ?></td>
<?php else: ?>
<td><?php echo $form->getObject()->get($name) ? $form->getObject()->get($name) : "-" ?></td>
<?php endif; ?>
But my knowledge still lacks a lot to figure this out. I'll really appreciate some help, please?
If you got a route to the details page I would try something like this using url_for and a given $parentId:
<?php if ($field->getConfig('label') == "parent_service_description"): ?>
<td>
<a href="<?php echo url_for('#show_details?id=' . $parentId) ?>">
<?php echo $form->getObject()->get($name) ? $form->getObject()->get($name) : "-" ?>
</a>
</td>
You should use.
echo link_to ($name, "action/module?id=". $sf_params->get("id") . "&params2=2") )
the reason behind is its readability and simplicity.

Codeigniter & Datamapper: Form Saving is behaving strange

I have a weird problem with Codeigniter and Datamapper,
I am making an CMS system and I am trying to edit an article from the Database using Datamapper. When I click to edit the article I get the message 'You have succesfully saved the article ' without clicking on the SAVE button, also all the data becomes empty and leaves 0. When I enter the data and click on SAVE it saves it but again when I try edit it again it goes back to 0 ... Can someone help out please
Here is my edit function in the controller
public function edit($id = NULL)
{
// Get articles by ID
$articles = new Article_model();
$article = $articles->where('id', $id)->get();
if ($id)
{
$id == NULL || $article;
count($article) || $error = 'Page not found ';
}
else
{
$article = $this->article_model->get_new();
}
$article->title = $this->input->post('title');
$article->text = $this->input->post('text');
if ($article->save())
{
echo 'You have succesfully saved the article';
}
else
{
echo 'Sorry something went terribly worng';
}
$data = array(
'admin_content' => 'admin/article/edit',
'article' => $article,
);
$this->parser->parse('admin/template_admin', $data);
}
and here is my view
<?php if ($this->tank_auth->is_logged_in()): ?>
<div class="container">
<div class="row">
<div class="col-md-9">
<h3><?php echo empty($article->id) ? 'Add an article' : 'Edit a Page ' . $article->title ;?></h3>
<?php echo form_open(); ?>
<table class="table">
<tr>
<td>Publication Date</td>
<td><?php echo form_input('pubdate', set_value('pubdate', $article->pubdate), 'class="datepicker"'); ?></td>
</tr>
<tr>
<td>Title</td>
<td><?php echo form_input('title', set_value('title', $article->title)); ?></td>
</tr>
<tr>
<td>Body</td>
<td><?php echo form_textarea('text', set_value('text' , $article->text), 'class="tinymce"'); ?></td>
</tr>
<tr>
<td></td>
<td><?php echo form_submit('submit', 'Save', 'class="btn btn-primary"'); ?></td>
</tr>
</table>
<?php echo form_close(); ?>
</div>
</div>
</div>
<?php else: redirect('/auth/login'); ?>
<?php endif; ?>
that's not weird at all...every time that controller is loaded it's going to execute the save() method of the article class.
you should probably include some form validation and only save the article if the form was submitted and validation passes.

Cakephp Pass array of checkboxes to another controller

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

cakephp Indirect modification of overloaded property PaginatorHelper

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!

Codeigniter - How to validate dynamic INPUT array?

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.

Categories