Convert model data before AJAX response in CakePHP 2 - php

I fetch some user data for a view via AJAX:
public function adminFetchUserDXData($id) {
$this->ajax_response(array('data'=>$this->UserDXEntry->find('all', array(
'conditions' => array('user_id' => $id)
))));
}
I use CakePHP 2 and want to convert a timestamp field from several fetched entries to a formatted date before sending it.
How can I do it?

Related

Laravel save an array of data in individual rows

How can I save an array of data into individual rows in Laravel ?
Here's how my UI looks like
once i click the save button in the controller Store function gets the data
public function store(Request $request, $venue, CustomProduct $customProduct)
{
dd($request->Availability);
}
This is how the data looks like
I'm wondering how can i save this to my database ?
This is how my database table looks like
Please suggest me a way that i can save this to my table
Use this example:
$days = ["monday","thursday","wednesday","tuesday","friday","saturday","sunday"];
forach($request->Availability as $key => $value){
CustomProductAvalibility::create([
'day_id' => array_search($key), // array_search($key) returns day id
'starts_at' => $value["start"],
'ends_at' => $value["end"],
'custom_product_id' => '...' // your custom product id
]);
}

Laravel creating API return with help of JSON field in MySQL

I have a requirement wherein I will be creating a JSON response. This will be active only for a day. So simply to avoid the creating JSON response I can store it in the MySQL Database. The issue is I am able to create JSON response, Save it in MySQL JSON field. However, I am not able to return a response directly via MySQL field.
//getting the value's from db
$news = DB::table('news')->where('news_item_name', $news_id)->first();
// checking if the news json values are still active(Cron job will delete expired news articles)
if (isset($news->news_expiry)) {
//this part is not working
return response()->json($news->news_content);
}
//if no news exits create new JSON and save it in the database.
$array = [];
$array[0]['title'] = "some news";
$array[0]['link'] = "http://www.example.com/";
$array[0]['source'] = "example.com ";
$array[0]['description'] = "some news description";
$array[0]['thumbnail']="http://www.example.com/images/sample.png";
//insert fresh news json with an expiry time.
DB::table('news')->insert(
['news_item_name' => $news_id, 'news_content' => json_encode($array), 'news_expiry' => some_expiry_time]
);
return response()->json($array);
If this only the case you can use this:
//insert of news json with an expiry time.
$saved = DB::table('news')->insert([
'news_item_name' => $news_id,
'news_content' => json_encode($array), 'news_expiry' => some_expiry_time
]);
return response()->json($saved->news_content);
But if it possible to change to Elequent and use Laravel getter and setter in model you can do that:
to set a value before inserting
public function setNewsContentAttribute($value)
{
$this->attributes['news_content'] = json_encode($value);
}
to fetch the value
public function getNewsContentAttribute()
{
return json_decode($this->news_content);
}
check laravel docs for elequent

Adding new record but time field should use current time

I am using Cakephp 3.0.2. I would like to add a new record. A complete record $this->request->data would look something like this;
'date_taken' => [
'month' => '01',
'day' => '05',
'year' => '2015',
'hour' => '02',
'minute' => '51'
],
'moves_per_minute' => '80',
'person_id' => '1'
However, I want to HTTP Post $this->request->data such that it looks like this;
'moves_per_minute' => '80',
'person_id' => '1'
The dates_taken data should be updated automatically by using the current time.
I defined the column dates_taken as DATETIME type and default as CURRENT_TIME_STAMP. When I do a HTTP Post and send $this->request->data over leaving date_taken empty, the new row cannot be added.
This is how my controller code looks like;
$newRecord = $this->newRecords->newEntity();
if ($this->request->is('post')) {
$newRecord = $this->newRecords->patchEntity($newRecord, $this->request->data);
if ($this->newRecords->save($newRecord))
{
//success
Debugger::dump("Save success");
}
else
{
$this->response->statusCode(400); //bad request
Debugger::dump("Save failure");
}
}
How should a correct controller look like?
Add the columns 'created' and 'modified' to your database table (both DATETIME), then inside the model for the table add this line:
class ArticlesTable extends Table
{
public function initialize(array $config)
{
$this->addBehavior('Timestamp');
// Timestamp is the correct, even though the field is a datetime
}
}
After you add new records, the datetime stored in the created field will be the exact time of creation and the modified field will be the last time you modify the record. Cake will do this by default every time you access this record through the entity.
More information can be found via the Timestamp documentation here: http://book.cakephp.org/3.0/en/orm/behaviors/timestamp.html
You could also save the current time by using the Time library and manually setting it in the entity before saving:
$time = Time::now();
$newRecord->date_taken = $time;
$this->newRecords->save($newRecord);
Again assuming the date_taken field is a datetime object in your table. I'd recommend letting the database set it for you rather than this method, though.

update json file dynamically whenever mysql is updated

i am going to create a live score board using php and mysql. But i want to create a json file which update automatically whenever i update my table on database. i mean new scores added in tables should be added in my json file. Really confused. sorry for not having any program. hope for some solutions. Thank you. i have some code which i have used to insert in database.
$data = array(
'name' => $name,
'score' => $score,
'comment' => $comment
);
$result=$this->db->insert('score', $data);
Do not quite understand what you want, I developed this code, see if it is what you need.
https://gist.github.com/juniorb2ss/7431040
Example:
public function __construct()
{
$this->load->helper('json');
}
public function index()
{
$data = array(
'name' => $name,
'score' => $score,
'comment' => $comment
);
save($data);
$result = $this->db->insert('score', $data);
}
File is created in folder application/cache/score.cache. Content is all scores the application.
You can enter a new score or update, the file will be updated.
Example cache content:
{"teste":{"name":"teste","score":"32","comment":"score comment"}}
The most direct solution would be to dump the whole of your score table as a JSON object on each insert. The problem with this approach is that if you have a large amount of data, on each insert you'll be selecting a lot of data.
function SelectScores()
{
$query = $this->db->query('SELECT * FROM score');
return $query->result();
}
You can then json_encode this result and save as file.

pass array from controller to view in codeigniter

Model:
Grabs data from mySQL with the value: array['10','5','2'] and puts it in the session data
Controller:
Puts that session data into an array to pass to the view:
$fubar = array(
'ex1' => $this->session->userdata('ex1')
);
$this->load->view('view', $fubar);
View:
echo $ex1;
The view will spit out the array: array['10','5','2']
How do I parse that array to get the individual values (10, 5, or 2)?
For example, echo $ex1['1']; will spit out the first 1 characters: ar but I want it to return the value 5
I think perhaps I may not be storing the array properly in mySQL, but I'm not sure.
$fubar['ex1'] = $this->session->userdata('ex1');
$this->load->view('view', $fubar);
Now Try
$ex1[0];
$ex1[1];

Categories