I have controller, 'products', with the actions 'add' and 'edit'.
I made开发者_StackOverflow社区 the view 'add.ctp' which has a long form. Was wondering if I can use that same view for generating display 'edit'. What would I need to put in the controller, under edit() {}, to make it output to 'add.ctp' instead of 'edit.ctp'?
Thanks.
You could use:
$this->render('add');
at the end of your controller's edit function, but I wouldn't recommend it.
A better solution would be to do a small refactor to put the contents of your add.ctp into an element (e.g. app/views/elements/productForm.ctp), and then use that element from both the add.ctp and edit.ctp views.
<?php echo $this->element('productForm'); ?>
This gives you the flexibility to wrap the form with action specific elements, and do any setup that might be specific to that action. For example, under the product form you might have a different set of actions, such as "View Product" that doesn't make sense in add mode but does in edit mode.
@kaklon made a very good point, you should put a little bit of logic into the productForm element to make sure edit mode behaves correctly:
if ($this->action == 'edit') {
echo $this->Form->input('id');
}
Pseudocoder wrote a very good article on this: http://www.pseudocoder.com/archives/category/cakephp/page:4
He has since improved this even more by using routes to eliminate the add action altogether I think. You may be interested in his compilation of CakePHP tips & hacks: http://www.pseudocoder.com/free-cakephp-book/
yes you can, This is one way to do it... https://github.com/infinitas/infinitas/blob/dev/app_controller.php#L374
that allows you to use one file when there is only one available, or add/edit when you need different stuff
You are looking for elements. The view is not 100% identical, because the edit form needs to contain the id of the product you want to edit, while the add form does not have an id..
精彩评论