What is the best way to enter hidden field data in CakePHP? - php

I am using CakePHP and want to pass the author's name (stored in a session) to an article that is being saved to the database. Is a hidden field the only way to do this or is there a better way?

If you already have it in the session, I would not spend the extra code/time to add it to a hidden field. I would update the method to add the session variable to the $this->data so it will add it when you save the record. So the method in the controller would look something like:
function add() {
if($this->data) {
$this->data['Article']['author'] = $this->Session->read('User.name');
$this->Article->create();
if ($this->Article->save($this->data)) {
...
}
This way you are not dealing with all the extra work and you can still achieve the results you are looking for.

There are other ways, but a hidden field is as convenient as any other and probably the most transparent (i.e. most detectable by other developers who may pick up the code later). You could also insert the value into the $this->data structure before save and be sure that your model knows what to do with it.

Related

Several forms logic, Laravel

I'm still learning Laravel, as what I'm trying to accomplish at the moment is the following logic:
-An User submits a form-> The form input is saved into DB, and is 'sent' to another User who can then validate it->I save into the DB if the state is validated or not, and inform the User who sent the form.
I know this is not too hard, but I'm doing it as I learn Laravel, so I'm coming up with a few 'problems'.
First of all, I do have quite a lot of forms, and I did get the Post logic working. At the moment I'm not working with the Database yet, so I tested the Forms with SESSION, to make sure the data was being saved.
So my first question is: is it best practice in this case to keep all form logic into one Controller? Like the following(this is working with two different forms) (session is there only for testing purposes)
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class PostController extends Controller
{
public function geralSuggest(Request $request)
{
$name = $request->input('obs');
return redirect('sugestoes');
}
public function GD(Request $request)
{
session_start();
$name = $request->input('nome');
$cc = $request->input('cartao');
$array = array ($name, $cc);
$_SESSION["testPostSection"] = $array;
return redirect('declaracaogd');
}
}
Secondly, I have some forms where the user can add inputs. Lets say one input is for the name, and the user has a button that when he clicks he adds another name input, so he can input many names at once. This is done by Javascript on my side. What I'm wondering is how will I save this inputs, since I 'don't know' how many "names" the user will be submitting. I was thinking a for or foreach loop, where I would check with "isset", but I'm not sure if it will work. I will be testing this when I get to it regardless, and I'm sure I'll figure it out, but if you know a good logic for this and could point me in the right path, it would be appreciated.
Lastly, about my general logic, for User validation, from what I read on Laravel documentation, I think Events will be what makes the trigger to 'warn' the second User that he needs to validate a form, is that correct?
I'm sorry if I'm asking "too much at once" or if these are very basic questions. I just wanted to make sure that I'm going in the right direction.
Thanks a ton in advance!
Im not sure if I understand your system 100% correctly. But it seems you are trying to make a human validation program? So 1 users submits data and another users validates this data. In this case I would do this in 2 seperate controllers. Laravels explenation on controllers states: "Controllers can group related request handling logic into a single class." Providing data or validating data are 2 different things. But this isnt a strict rule.
For the second question. Laravel has an all() method. $input = $request->all(); will give you an array will all request data. After that you could loop over the array and insert it into a db or the storage method you want.
Edit: another way to handle this if you could have multiple names could be:
// View
<input type="text" name="names[]">
<input type="text" name="names[]">
// Controller
$request->names; // This is an array of values
Source: https://laracasts.com/discuss/channels/laravel/get-the-values-of-dynamically-generated-inputs
And events are indeed the way to go if you want to send a message. so you could fire an event as soon as the data is submitted. And one of the listeners would send a email or something like that

is it possible to return database data like withinput and use it with {{old()}} laravel?

I have articles database table and need same form for both saving new article and updating old one. So I have made a forms folder and created my form, then I included it in both places i needed, but in article edit I need to see all article which i am editing info (title, article content, etc.) and that info is saved in database. It would be the best if i could use {{old()}} and see article info from database (because when i save article, if there are any errors, i want not to loose all post inputs data, so i use {{old()}} there) Sorry, my english is not really good and it's really hard for me to formulate... So my questions sounds: Is it possible to return database data from controller like withInput() and use it with {{old()}}? Thank you! Ask if i said something not understandable.
The answer is yes, the function old() accepts a second parameter, a value if the old value is not defined. In this case, you use the value of the database
Example
{{ old('username', $user->username) }}
Although the answer below should work, I believe that the best way to solve it is binding the model on your form (use the Form::model, instead of the Form:open).
This way, when you use old('some_field'), it will get the some_field field that the Model refers to.
You can have more information here: https://laravelcollective.com/docs/5.2/html#form-model-binding

Yii - Massive Assignment of a private field

TL;DR - How do I massively assign private fields in Yii?
Any Yii experts on StackOverflow? The YiiFramework forums didn't really help me out.
I've got a private field hired in my CActiveRecord model that is dependent on another relation jobCount. Basically, if there is at least one valid job (stored in another table) associated with that member, they are consider hired.
Conventionally, I would set hired in the afterFind method, but that would mean loading the relation every time. For the sake of saving database queries, I would only like to load the relation if hired is needed. So I set hired to private, and can load the relation and set it once getHired() is called.
So far so good...
The problem arises once I incorporate the hired field in my CGridView. I'd like to be able to use the column filters, with a simple dropdown filtering on Yes or No. Upon filling out your filters, CGridView passes back a GET request, which you would set to a cleared model using massive assignment...
$model->attributes = $_GET['ModelName'];
Obviously I would like hired to get set as well, despite it being a private field. (I handle the searching for CGridView, don't worry about that.) I've made it a safe field in my model, but it doesn't get set.
setHired() function doesn't get called
setAttribute() function doesn't get called
setAttributes() function doesn't get called
What's the correct way to do this? Clearly, I could just add an extra line in my controller action...
if (isset($_GET['ModelName']['hired']))
$model->setHired($_GET['ModelName']['hired']);
...but I would really rather learn how to allow private fields to be massively assigned.
I realize that this is rather convoluted. If you see some way that I could streamline this hired bit, I'd appreciate that. Still, I would like to learn if there's a way to do this.
I suppose, you need just to add your attribute to the list of attributes.
public function attributeNames()
{
$names = parent::attributeNames();
$names[] = 'hired';
return $names;
}

CakePHP model->save(): save all but some excluded fields

I want to save all but some excluded fields. I know that I can do it this way
$this->Blah->save($this->data,false,$fieldList)
Where $fieldList contains all the data fields of the table but these I don't want to get saved. I have some tables that have maaany data fields, and I don't want to write the whole list from scratch in every single controller action (yes, the fields that should not be saved differ from action to action). Additionally, it looky messy and confusing. Is cakePHP providing something ready-to-use for this case? If not, I guess, I'd have to implement it by myself by adding a $fieldList property to every controller and doing something like this (ugly-hacked-together-solution):
$tmp = $fieldList;
unset(array_search('fieldtoexclude', $tmp));
$this->Blah->save($this->data,false,$tmp);
Best Regards
function blacklist($blackList = array()) {
return array_diff(array_keys($this->schema()), $blackList);
}
shoud work
Take a look at:
http://www.dereuromark.de/2010/09/21/saving-model-data-and-security/
for details
If the field list changes from action to action, then you're looking for an automagic function that can read your mind. Cake doesn't provide that!
Somewhere you have to say which fields are to be excluded and doing so longhand in a clear way will make your code much more maintainable.
If it is only one controller, define the list as a class variable, or alternatively subclass the save action on the model.

Allowing the creation of custom forms and storing the data

I'm building a site and need to allow users to be able to create custom forms. The part I'm having trouble with is how to store the data from these forms. Since they are user created fields, there will be no corresponding field in the database. What would be the best way of going about this? I assume modifying the table is the incorrect way of doing so. Would putting all the data into an array, serializing it, and then storing it in a field be a good way?
Would putting all the data into an array, serializing it, and then storing it in a field be a good way?
While that would store the data, it would not make the individual elements queryable. It's an astoundingly bad long-term idea.
Take a look at the entity-attribute-value model. You should be able to represent the fields in a form and even the data filled in to the form using EAV backed up by some rigid foreign key checks.
Now, EAV isn't perfect. It can be tough to create certain queries against it because of MySQL's limitations, but that's nothing a bit of external code can't fix. It'll still be ten times better than serialized data.
maybe you can serialize the values of the complete form and storing it in a blob to the database.
Maybe you can provide a solid Form builder framework (or modify an existing solution) where every user created field controlled by you like this:
//input elements named by a custom namespace:
`<input type="text" name="mycustomelement[user_defined_name]" />`
and there you go: when user submits the form, you can catch all 'mycustomelement' element then you can serialize it to store in a db.
I would store a table userforms {id, user, index, fieldname, fieldtype} and then userformresponses {id, userformid, fieldname, response}

Categories