modifying Form->input() data in cakePHP - php

A database table for Event model has following fields:
user_id, name, title
in the Event add view the user is asked to insert the name, hours and minutes as following:
echo $this->Form->input('hours');
echo $this->Form->input('minutes');
echo $this->Form->input('name');
Now the name would be obviously stored as it should, but the problem occurs when I want to concacinate the hours and minutes inserted by user and store them into the DBs "title" field.
Any suggestions for how to achieve this?

use the model's beforeSave function to add any fields you like. In this case a title is being injected
in Event.php
public function beforeSave($options=array()){
parent::beforeSave($options);
$this->data['Event']['title'] = $this->data['Event']['hours'].$this->data['Event']['minutes'];
//do other stuff
return true;
}

Related

Unable to do laravel relationships using laravel 5.5

I am facing issue regarding storing ids and display their values from two different table i have 1 table business_master and other table is page_master i have combine business_name column with page_url column which are available on page_master table if i add my business and page first time its successfully combine these two values as one business can have many pages and if i only add page 2nd time i am unable to see business_url with page_url column.
My Page Model:
class PageList extends Model
{
protected $table = 'page_master';
protected $fillable = ['business_id', 'page_url', 'page_name'];
public function business()
{
return $this->hasOne('App\Business','business_id');
}
}
and in my view:
<td>{{optional($value->business)->business_url}}.spikesales.io/{{$value->page_url}}</td>
This is my first time out if i add business_url and page_url
hussain.spikesales.io/house
and then if i add only page the out put is something like that
.spikesales.io/hello
one business can have many page it should attach business_ url also but i am unable to find solution:
Any help will be highly appreciated!
public function pageListHere()
{
$list = PageList::all();
return view('page-list',compact('list'));
}
You have to change your controller code like this:
$list = PageList::select('*');
$list->with(
array('business'=>function($query){
$query->select('*');
}));
$pageList = $list->get();
return view('page-list',compact('pageList'));
The varialbe $pageList will be having all the rows of that table along with related Business table rows.

cant save multiple tables in cakephp

I am learning cakephp and have made quite a bit already. The only reason I am asking this question is that the docs in cakePHP could be wrong.
I cant see from the docs or past stackoverflow posts on this issue why the (child)Teacher table doesnt save the user_id from the id table in the (parent)User table.
I get no error but the user_id is 0 in the Teacher table so it isnt picking it up from the User table.
I have a one-one relationship on the 2 models.
I am just testing saving over 2 models where I have a User and teacher. I simply enter data in a form and create a new User and also a new teacher with the user_id being a foreign key in the teacher table.
I am loathe to ask this question as there is a lot of material on this but I just cant see my issue after following the docs in cakePHP.
http://book.cakephp.org/2.0/en/models/saving-your-data.html
public function addteacher() {
if ($this->request->is('post')) {
$this->User->create();
}
if (!empty($this->request->data)) {
// We can save the User data:
// it should be in $this->request->data['User']
$user = $this->User->save($this->request->data);
// If the user was saved, Now we add this information to the data
// and save the Profile.
if (!empty($user)) {
// The ID of the newly created user has been set
// as $this->User->id.
$this->request->data['teacher']['user_id'] = $this->User->id; //here is the problem
// Because our User hasOne Profile, we can access
// the Profile model through the User model:
if ($this->User->Teacher->save($this->request->data))
{
$this->Session->setFlash(__('Your post has been saved.'));
return $this->redirect(array('action' => 'login'));
}
}
}
}
<?php
echo $this->Form->create('User');
echo $this->Form->input('User.username');
echo $this->Form->input('User.password');
echo $this->Form->input('Teacher.firstname'); //text
echo $this->Form->input('Teacher.surname');
echo $this->Form->input('Teacher.address'); //text
echo $this->Form->input('Teacher.suburb');
echo $this->Form->input('Teacher.phone');
echo $this->Form->end('Save Post');
?>
$this->request->data['teacher']['user_id'] = $this->User->id;
should be
$this->request->data['Teacher']['user_id'] = $this->User->id;.
Capital "T". Model names are always CamelCased.
That said there is no need for 2 saves. You can just use
$this->User->saveAll($this->request->data);.
It will save both the User record and Teacher record adding proper foreign key value for the Teacher record (assuming you have setup proper association between User and Teacher model).

How to use grocery set_relation function to display content from two different tables in different columns

I have to tables with these schema:
users(id, name, email)
user_details (id, user_id, physical_address, otherinfo)
I would like to display all contents of both tables in one grid using grocery crud
when i try to use set relation on the first table as shown: Note: I have reducted the part that does the rendering of the view;
$crud = new grocery_CRUD();
$crud->set_table('users');
$crud->set_relation('id', 'user_details', '{physical_address} + {otherinfo}');
the values of the id field as well as the referenced table don't appear in the grid, so it does not seem to work when using primary keys.
So I decided to start with the contents of the second table like so:
$crud = new grocery_CRUD();
$crud->set_table('user_details');
$crud->set_relation('user_id', 'users', '{name} + {email}');
This works, but the problem is that the values appear in one column in the grid. I would like to know how i can separate them to different columns and make them editable in separate input fields.
my way kinda ridiculous,
if i were really need the field to be separated, i might use callback_column then use active records to return the value using $row->user_id, and callback each record
just like:
return $this->some_model->get_name($row->user_id); for name field
and
return $this->some_model->get_name($row->user_id); for email field
but, as i tested with some dummy records, it can't be sorted, (i dont know if anyone could)
There is no direct way to show multiple columns but i found an work around for this problem.
here is how
set name column as follows.
$crud->columns('name','email'); // define all required columns
$crud->callback_column(unique_field_name('user_id'),array($this,'callback_set_user_name'));
function unique_field_name($field_name)
{
return 's'.substr(md5($field_name),0,8);
}
public function callback_set_user_name($value, $row)
{
$row->full_name = $row->s447d3092; // before getting to know s447d3092 key return json_encode($row); you will key pair with {name} + {email} ex: {"s447d3092":"shiva + shiv#gmail.com"}
return explode("+",$value)[0]; // here you will have only name
}
$crud->callback_column('email',array($this,'callback_set_email'));
public function callback_set_email($value, $row)
{
return explode("+",$row->full_name)[1];
}
I am 100% sure this will help you

yii: validate multiple models

I have a Competition model, that has many Entry models.
[edit] Schema looks (roughly) like this:
Competition:
id INT(11)
name VARCHAR(50)
date DATETIME
Entry:
id INT(11)
competition_id INT(11)
user_id INT(11)
answer VARCHAR(50)
isWinner INT(1)
In my pickWinner view, I have a form that loops through all related entries - offering the isWinner field to allow the user to pick an entry as the winner. Saving the related model etc is pretty standard and that all works fine.
I'm trying to validate the form so that at least one of the Entry models has isWinner set to true (the user has to pick at least one winner).
I obviously can't apply the validation rule to the Entry model - as each model only knows about itself and not the values of the other models.
Only one Entry model should be set as the winner - how do I add a validation rule to Competition, so that it can detect that one of its child Entry models has isWinner set to true?
One way to achieve this would be to add a relation to the Competition model to detect if it has a winner, something like;
public function relations()
{
return array(
...
'winners' => array(self::STAT, 'Entry', 'competition_id', 'condition'=>'`t`.`isWinner` = true'),
...
);
}
Then the following should return the number of winners for the given competition:
$competition = Competition::model()->findByPk($id);
$winners = $competition->winners;
Not tested, so you may need to alter a little.
EDIT
Ok, to get this info before you save you could do something like the following: if for example in your pickWinner view you have a field for each model and it's submitting back as an array, for example like $_POST[Entry][$model->id]['isWinner'] for each model, can you not simply cycle through those making sure one is set to true? e.g:
$winners = 0;
foreach(array_keys($_POST[Entry]) as $key)
{
if($_POST[Entry][$key]['isWinner']=='true')
$winners++;
}
if($winners==0)
{
echo "You selected no winners.";
} else if($winners>1) {
echo "You selected too many winners.";
} else if($winners==1) {
echo "Woot, 1 winner!";
}
Again, this depends on how your pickWinner form is laid out.

CakePHP adding a comment to Photo

I have a problem with adding comments to photos on my website. In comments table I have:
id, user_id, photo_id, content, created, modified, erased.
In view I create:
echo $this->Form->create('Comment');
echo $this->Form->input('title');
echo $this->Form->input('content');
echo $this->Form->input($this->Session->read('User.id'), array('type'=>'hidden'));
echo $this->Form->input($photo['Photo']['id'], array('type'=>'hidden'));
echo $this->Form->end('Add comment');
I don't know if it is correct way. How cake will know that 2 hidden values are user_id and photo_id ?
Thx for advices.
You will have to populate User ID in the controller when the data is submitted (so users cannot post as other users). You can fetch the user ID with $this->Auth->user('id'); (providing you are using the built in Auth component). As for photo ID, you obviously have this somewhere as you're loading the photo, you just need to pass this data into $this->request->data before you save.
A simple CakePHP 2 approach would be like so:
public function viewPhoto($photoId) { //$photoId comes from your routes or something
if($this->request->is('post')) {
$this->request->data['Comment']['user_id'] = $this->Auth->user('id');
$this->request->data['Comment']['photo_id'] = $photoId;
$this->Photo->Comment->save($this->request->data);
}
}
This structure be slightly different for you, depending on your controller/model setup.

Categories