Custom table names in CakePHP - php

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'));

Related

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

Missing Helper error in cakephp blog tutorial

Im just starting out with php and cakePhp in general. I encountered the following error while trying to implement the blog tutorial. I have followed the steps in the tutorial till here http://book.cakephp.org/2.0/en/getting-started.html#creating-post-views
Screenshots of the error msgs are here-
[1]: http://i.imgur.com/xLvz3.png "top"
[2]: http://i.imgur.com/cJHPK.png "bottom"
Model/Post.php
<?php
class Post extends AppModel {}
Controller/PostsController.php
<?php
class PostsController extends AppController {
public $helpers = array(’Html’, ’Form’);
public function index() {
$this->set(’posts’, $this->Post->find(’all’));
}
public function view($id = null) {
$this->Post->id = $id;
$this->set(’post’, $this->Post->read());
}}
Posts/index.ctp
<h1>Blog posts</h1>
<table>
<tr>
<th>Id</th>
<th>Title</th>
<th>Created</th>
</tr>
<!-- Here is where we loop through our $posts array, printing out post info -->
<?php foreach ($posts as $post): ?>
<tr>
<td><?php echo $post['Post']['id']; ?></td>
<td>
<?php echo $this->Html->link($post['Post']['title'],
array('controller' => 'posts', 'action' => 'view', $post['Post']['id'])); ?>
</td>
<td><?php echo $post['Post']['created']; ?></td>
</tr>
<?php endforeach; ?>
<?php unset($post); ?>
Replace " ’ " by a simple quote " ' ".
so you must declare helpers as :
public $helpers = array('Html', 'Form');
the same change for find method param :
$this->set('posts', $this->Post->find('all'));
at last
$this->set('post', $this->Post->read());
Anas

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