Using elements for repeatable forms?

Following the CakePHP docs, I use elements for forms that are the same in Add and Edit. So a user_form.ctp element that I include in Add.ctp and Edit.ctp. This helps avoid copy pasting between forms. For me this is common sense, especially after dealing with a legacy CakePHP 1.3 app that had the same code on different forms, I then had to copy paste. A new developer did the same, they have much more CakePHP experience than me, but again, I see form code copy pasted between .ctp files. As you can imagine this creates bugs when you forget to copy paste code!

Am I missing something here? Elements are ideal right for repeatable form fields, avoiding you copy pasting? The developer is telling me I’m wrong.

If I undertstand the question, you’re saying if you use an element (https://book.cakephp.org/3.0/en/views.html#elements) with common form elements inside them inside a template? e.g. you have a form asking the user’s first and last name in one element, then another two elements for say home address and another for place of employment, if the user has indicated they are employed.

I don’t know if there’s a technical reason you couldn’t use blocks of elements (possibly a performance reason, especially with older versions of Cake) to assemble a form out of re-usable elements. It’s an interesting idea, just never seen it done before.

@hakim

I have used an element with common form controls in many projects, however, typically with address fields or file upload functionality.

A common practice where I work is that we combine the add/edit functionality in the same action. If the ID param is passed, we do a get/find, else we build a new entity for example. Overall, this cuts down on unnecessary code duplication and complication on maintenance/updates.

1 Like

You are correct, your new dev is incorrect :slight_smile:

It comes down to the “dry” principle (Don’t repeat yourself). Using an element between add and edit is, in my opinion, the right way of doing it. The even better way is not to write any code at all and use a combination of the Crud and Crud-View plugins.

Remember, the best code is the code that you don’t have to write yourself!

2 Likes