How to reduce form code duplication in CakePHP - cakephp

I have a form in CakePHP with a few dozen fields in it. From all the examples I have seen, there is duplicate form code for an add view and an edit view.
Is there any tricks to keep the duplication out? What is best method in CakePHP for this?

What I do, is to put all form fields in an element, and then insert the element in the add.ctp and edit.ctp
Don't forget to add the hidden field with the id in the edit.ctp
This way all visible elements are in one file, easier to maintain.
View/MyModel/add.ctp
echo $this->Form->create('MyModel');
echo $this->element('my_form');
echo $this->Form->end();
View/MyModel/edit.ctp
echo $this->Form->create('MyModel');
echo $this->Form->input('id');
echo $this->element('my_form');
echo $this->Form->end();
View/Elements/my_form.ctp
// your form inputs
// whatever they are

You should NOT merge those views, because add/edit are different actions and deserve separate view files. As your application grows you will realize that its good to have separate views to reduce complexity of if else conditions.
If you still want to avoid the separate files, Use
function add() {
.....
$this->render('edit')
}

I've done this before, but reverted back to having separate views, mainly for my own sanity.
It's easy enough to do. The edit requires an input for the record id. This is usually hidden. Any default form values for the add form will have to be contained in conditionals so that the stored values are not overwritten with defaults when you are editing a record
On the controller side of things, you'll need a conditional statement to decide whether to act as an add or edit depending on whether the $this->data['MyModel']['id'] is set.
I think that covers it - if I think of anything else I'll add it in.
My work pattern tends to be to build the edit view, then copy and paste to create the basis for the add view.

this code will check if you have admin_form.ctp or form.ctp which will make it use the same code for add / edit
https://github.com/infinitas/infinitas/blob/dev/app_controller.php#L389
1.3 submits the forms automatically to where the are from so when you go to /edit/1 it will post to there, and /add will post to add.
that is all you need to do. if you have a edit that is vastly different to the add, then you just create the 2 files. when you want them the same, just make the one.

in your app controller
public function render($view = null, $layout = null) {
$viewPaths = App::path('View', $this->plugin);
$rootPath = $viewPaths[0] . DS . $this->viewPath . DS;
$requested = $rootPath . $view . '.ctp';
if (in_array($this->request->action, array('admin_edit', 'admin_add', 'edit', 'add'))) {
$viewPath = $rootPath . $this->request->action . '.ctp';
if (!file_exists($requested) && !file_exists($viewPath)) {
if (strpos($this->request->action, 'admin_') === false) {
$view = 'form';
} else {
$view = 'admin_form';
}
}
}
return parent::render($view, $layout);
}
and in your view you can always check whether its edit or add
if ($this->request->params['action'] == 'admin_edit') {
//do something
}
if ($this->request->params['action'] == 'admin_add') {
//do something
}

in edit.ctp
if($this->data[ModelName]['id']) {
$this->Form->input('id');
}
// create rest of the fields
in Controller::add()
$this->autoRender=false; // at the start of function
$this->render('edit.ctp'); // at the point where you actually want to render
no need to create add.ctp

Related

Difference in accessing variables in views

I've two controllers one is "Upload" which deals with images uploads and other is "Page" whid deals with the creation of pages of CMS now if in my "Upload" controller I load both the models i.e 'image_m' which deals with image upload and "page_m" which deals with the pages creation I've highlighted the relevant code my problem is if I access the variables in the view
$this->data['images'] = $this->image_m->get(); sent by this I can access in foreach loop as "$images->image_title, $images->image_path" etc
But the variable sent by this line ***$this->data['get_with_images'] = $this->page_m->get_no_parents();*** as $get_with_images->page_name, $get_with_images->page_id etc produces given error
A PHP Error was encountered
Severity: Notice
Message: Trying to get property of non-object
Filename: upload/index.php
Line Number: 20
what is the difference between these two access levels one for $image & other for $get_with_images because I can only access its values as $get_with_images
class Upload extends Admin_Controller {
public function __construct() {
parent::__construct();
***$this->load->model('image_m');
$this->load->model('page_m');***
}
public function index($id = NULL) {
//var_dump($this->data['images'] = $this->image_m->get_with_images());
//$this->data['images'] = $this->image_m->get_with_images();
***$this->data['images'] = $this->image_m->get();***
$this->data['subview'] = 'admin/upload/index';
if ($id) {
$this->data['image'] = $this->image_m->get($id);
count($this->data['image']) || $this->data['errors'][] = 'Page Could not be found';
}
$id == NULL || $this->data['image'] = $this->image_m->get($id);
/*this calls the page_m model function to load all the pages from pages table*/
***$this->data['get_with_images'] = $this->page_m->get_no_parents();***
You are not posting all your code so its hard to tell but is it because you used $this-> in the controller, but you haven't done the same thing in the view?
In this case i would recommend not using $this-> because its not necessary. Also its much better to check for errors etc when you call the model so do something like
if ( ! $data['images'] = $this->image_m->get($id) ) {
// Failure -- show an appropriate view for not getting any images
// am showing $data in case you have other values that are getting passed
$this->load->view( 'sadview', $data ); }
else {
// Success -- show a view to display images
$this->load->view( 'awesomeview', $data ); }
so we are saying if nothing came back - the ! is a negative - then show the failure view. Else $data['images'] came back, and it will be passed to the view. note i have not had to use $this-> for anything and it won't be needed in the view.
Would also suggest using separate methods - have one method to show all images and a separate method like returnimage($id) to show an image based on a specific validated $id.
====== Edit
You can access as many models as you want and pass that data to the View. You have a different issue - the problem is that you are waiting until the View to find out - and then it makes it more difficult to figure out what is wrong.
Look at this page and make sure you understand the differences between query results
http://ellislab.com/codeigniter/user-guide/database/results.html
When you have problems like this the first thing to do is make a simple view, and echo out directly from the model method that is giving you problems. Its probably something very simple but you are having to look through so much code that its difficult to discover.
The next thing is that for every method you write, you need to ask yourself 'what if it doesn't return anything?' and then deal with those conditions as part of your code. Always validate any input coming in to your methods (even links) and always have fallbacks for any method connecting to a database.
On your view do a var_dump($get_with_images) The error being given is that you are trying to use/access $get_with_images as an object but it is not an object.
or better yet on your controller do a
echo '<pre>';
var_dump($this->page_m->get_no_parents());
exit();
maybe your model is not returning anything or is returning something but the data is not an object , maybe an array of object that you still need to loop through in some cases.

View link if depended on user rights

I am working with CakePhp 2.x. I have three Columns:
User | Course | UserCourseRole
Each user can edit multiple courses and one course can be edited by multiple users. So far so good.
If a user wants to see an index of all the courses i want to show a 'edit'-link only next to the courses which he can in fact edit.
How can i realize this? I figured i would have to set some sort of extra field inside the CourseController and check for this field inside the view. Is this the right way to go?
My current Code is
CourseController.php
...
public function index() {
$courses = $this->Course->find('all', array('recursive' => 2));
$this->set('courses', $courses);
}
...
Courses/index.ctp
<!-- File: /app/View/Courses/index.ctp -->
...
<?php foreach ($courses as $course):?>
...
<?php
echo $this->Html->link('edit', array('action' => 'edit', $course['Course']['id']));
?>
...
In beforeRender() or beforeFilter() set $this->Auth->user() as a variable to the view, for example as userData.
$this->set('userData', $this->Auth->user());
Implement a (auth)helper that uses that variable (you can make it configurable as a helper setting) and do your checks like:
if ($this->Auth->hasRole($course['Course']['role']) { /* ... */ }
if ($this->Auth->isLoggedIn() { /* ... */ }
if ($this->Auth->isMe($course['Course']['user_id']) { /* ... */ }
Implement the hasRole() method according to whatever your specific requirements are.
Doing this as helper as a bunch of advantages, it is easy to reuse, overload and adapt to whatever your checks are and you don't use a component in a view plus that you should avoid calling statics and singletons a lot in your app. Also it is pretty easy to read and understand what the code does.
I think the good idea is set some variable or constans after logged (if user has privileges) and uses if statement for check.
if($allow === true) {
echo $html->link('Edit',...
}
or use AuthComponent::user() in Views.
This idea it's not good if we can many kind of admins (admin, moderator, reviewier, etc.)
Maybe someone will have a better solution

how to add hidden value from registeration from in db field in cakephp

I have one registration form. I want to pass hidden value in that form. I have created one field in database 'lang'. In registration form I did like this: echo $form->hidden('lang', array('value' => '1')); But its not saving the value in db. Sorry I have no experience in cakephp, so please if anybody help me in this with all processes. Thanks
You should not just pass hidden stuff through the form just for the heck of it.
If you can, add those values prior to actually saving.
See http://www.dereuromark.de/2010/06/23/working-with-forms/ for details
Basically, you do:
if ($this->request->is('post') || $this->request->is('put')) {
$this->Post->create();
// add the content before passing it on to the model
$this->request->data['Post']['lang'] = '1';
if ($this->Post->save($this->request->data)) {
...
}
}

Styling/Theming Drupal 7 Content Type Record

I developed a Content type of "Car Sales" with following fields:
Manufacturer
Model
Make
Fuel Type
Transmission (Manual/Automatic)
Color
Registered? (Yes/No)
Mileage
Engine Power
Condition (New/Reconditioned/Used)
Price
Pictures (Multiple uploads)
I have developed View of this Content Type to display list of cars. Now I want to develop a screen/view for individual Car Sale Record like this:
Apart from arranging fields, please note that I want to embed a Picture Gallery in between. Can this be achieved through Drupal 7 Admin UI or do I need to create custom CSS and template files? If I need to edit certain template files/css, what are those? I'm using Zen Sub Theme.
I would accomplish this by creating a page, and then creating a node template to accompany it. Start by creating a new node, and then record the NID for the name of the template.
Then, in your template, create a new file, and name it in the following manner: node--[node id].tpl.php
Then, in that file, paste in the following helper function (or you can put it in template.php if you're going to use it elsewhere in your site):
/**
* Gets the resulting output of a view as an array of rows,
* each containing the rendered fields of the view
*/
function views_get_rendered_fields($name, $display_id = NULL) {
$args = func_get_args();
array_shift($args); // remove $name
if (count($args)) {
array_shift($args); // remove $display_id
}
$view = views_get_view($name);
if (is_object($view)) {
if (is_array($args)) {
$view->set_arguments($args);
}
if (is_string($display_id)) {
$view->set_display($display_id);
}
else {
$view->init_display();
}
$view->pre_execute();
$view->execute();
$view->render();
//dd($view->style_plugin);
return $view->style_plugin->rendered_fields;
} else {
return array();
}
}
Then add the following code to your template:
<?php
$cars = views_get_rendered_fields('view name', 'default', [...any arguments to be passed to the view]);
foreach ($cars as $car): ?>
<div>Put your mockup in here. It might be helpful to run <?php die('<pre>'.print_r($car, 1).'</pre>'); ?> to see what the $car array looks like.</div>
<?php endforeach;
?>
Just change the placeholders in the code to whatever you want the markup to be, and you should be set!
As I mentioned above, it's always helpful to do <?php die('<pre>'.print_r($car,1).'</pre>'); ?> to have a visual representation of what the array looks like printed.
I use views_get_rendered_fields all the time in my code because it allows me to completely customize the output of the view.
As a Reminder: Always clear your caches every time you create a new template.
Best of luck!

Need to make full names in cakePHP

If I have a person model with first_name and last_name, how do I create and display a full_name? I would like to display it at the top of my Edit and View views (i.e. "Edit Frank Luke") and other places. Simply dropping echoes to first_name and last_name isn't DRY.
I'm sorry if this is a very simple question, but nothing has yet worked.
Thank you,
Frank Luke
Edit for clarity: Okay, I have a function on the person model.
function full_name() {
return $this->Person->first_name . ' ' . $this->Person->last_name;
}
In the view, I call
echo $person['Person']['full_name']
This gives me a notice that I have an undefined index. What is the proper way to call the function from the view? Do I have to do it in the controller or elsewhere?
If what you are wanting is just to display a full name, and never need to do any database actions (comparisons, lookups), I think you should just concatenate your fields in the view.
This would be more aligned with the MVC design pattern. In your example you just want to view information in your database in a different way.
Since the action of concatenating is simple you probably don't save much code by placing it in a separate function. I think its easiest to do just in the view file.
If you want to do more fancy things ( ie Change the caps, return a link to the user ) I would recommend creating an element which you call with the Users data.
The arrays set by the save() method only return fields in the datbase, they do not call model functions. To properly use the function above (located in your model), you will need to add the following:
to the controller, in the $action method:
$this->set( 'fullname', $this->Person->full_name();
// must have $this-Person->id set, or redefine the method to include $person_id
in the view,
echo $fullname;
Basically, you need to use the controller to gather the data from the model, and assign it to the controller. It's the same process as you have before, where you assign the returned data from the find() call to the variable in the view, except youre getting the data from a different source.
There are multiple ways of doing this. One way is to use the afterFind-function in a model-class.
See: http://book.cakephp.org/view/681/afterFind.
BUT, this function does not handle nested data very well, instead, it doesn't handles it al all!
Therefore I use the afterfind-function in the app_model that walks through the resultset
function afterFind($results, $primary=false){
$name = isset($this->alias) ? $this->alias : $this->name;
// see if the model wants to attach attributes
if (method_exists($this, '_attachAttributes')){
// check if array is not multidimensional by checking the key 'id'
if (isset($results['id'])) {
$results = $this->_attachAttributes($results);
} else {
// we want each row to have an array of required attributes
for ($i = 0; $i < sizeof($results); $i++) {
// check if this is a model, or if it is an array of models
if (isset($results[$i][$name]) ){
// this is the model we want, see if it's a single or array
if (isset($results[$i][$name][0]) ){
// run on every model
for ($j = 0; $j < sizeof($results[$i][$name]); $j++) {
$results[$i][$name][$j] = $this->_attachAttributes($results[$i][$name][$j]);
}
} else {
$results[$i][$name] = $this->_attachAttributes($results[$i][$name]);
}
} else {
if (isset($results[$i]['id'])) {
$results[$i] = $this->_attachAttributes($results[$i]);
}
}
}
}
}
return $results;
}
And then I add a _attachAttributes-function in the model-class, for e.g. in your Person.php
function _attachAttributes($data) {
if (isset($data['first_name']) && isset($data['last_name'])) {
$data['full_name'] = sprintf("%s %s %s", $data['first_name'], $data['last_name']);
}
return $data;
}
This method can handle nested modelData, for e.g. Person hasMany Posts then this method can also attachAttributes inside the Post-model.
This method also keeps in mind that the linked models with other names than the className are fixed, because of the use of the alias and not only the name (which is the className).
You must use afterFind callback for it.
You would probably need to take the two fields that are returned from your database and concatenate them into one string variable that can then be displayed.
http://old.nabble.com/Problems-with-CONCAT-function-td22640199.html
http://teknoid.wordpress.com/2008/09/29/dealing-with-calculated-fields-in-cakephps-find/
Read the first one to find out how to use the 'fields' key i.e. find( 'all', array( 'fields' => array( )) to pass a CONCAT to the CakePHP query builder.
The second link shows you how to merge the numeric indexes that get returned when you use custom fields back into the appropriate location in the returned results.
This should of course be placed in a model function and called from there.

Resources