Cakephp using two models - cakephp

In my CakePHP forms_controller I have:
var $uses=array('Form','Field');
// ...
$this->set('retrived',$this->Field->find("all",array('conditions'=>array('Field.formname'=>$formname,))));
and in the view:
<?php foreach ($retrived as $r): ?>
<?php echo $r['Field']['fieldname']; ?><br>
<?php endforeach; ?>
I'm not getting the answer for it
Actually my table fields wil be like:
fieldname
formname
type
value
More details from my forms_controller:
function views()
{
if (!empty($this->params['form']))
{
$this->set('fieldctr',$this->params['form']['formfieldctr']);
$fieldctr=$this->params['form']['formfieldctr'];
if(!empty($this->params['form']['formnameelements']))
{
$this->set('formname',$this->params['form']['formnameelements']);//formname
$this->Form->saveField('name',$this->params['form']['formnameelements']);
}
else
{
$this->set('formname','MyForm');//formname
$this->Form->saveField('name','MyForm');
}
$this->Form->saveField('body',$this->params['form']['formelements']);//inserts into database
$ret = $this->Form->query("Select id from forms order by id DESC LIMIT 1");
$newid=$ret[0]['forms']['id'];echo $newid;
$upd=$this->Form->query("update forms set ctr=$fieldctr where id= $newid");
$formname=$this->params['form']['formnameelements'];
$n="$formname";
$array = $this->params['form']['formfieldnameelements'];
$comma_separated = explode(",", $array);
for($i=0;$i<$fieldctr;$i++)
{
echo $comma_separated[$i];
echo " ";
$n="$comma_separated[$i]";
//insert the fields of each form to the table fields
$this->data['Field']['fieldname'] = $comma_separated[$i];
$this->data['Field']['formname'] = $formname;
$this->Field->saveAll($this->data);
}
The above method is where I'm inserting the formname in my forms table.
And inserting that formname with their fieldsname in the fields table:
function formupdate()
{
$this->set('fieldctr',$this->params['form']['formfieldctr']);
$fieldctr=$this->params['form']['formfieldctr'];
$this->set('formname',$this->params['form']['formnameelements']);//formname
$formname=$this->params['form']['formnameelements'];
$ret = $this->Field->query("SELECT fieldname FROM fields WHERE fields.formname = "."'$formname'"."order by id ASC");
for($q=0;$q<$fieldctr;$q++)
{
$fieldname[$q]=$ret[$q]['fields']['fieldname'];
}
$this->set('retrived',$this->Field->find("all",array('conditions'=>array('Field.formname'=>$formname))));
$array = $this->params['form']['formfieldvalueelements'];
$comma_separated = explode(",", $array);
for($i=0;$i<$fieldctr;$i++)
{
echo $comma_separated[$i];
echo " ";
$n="$comma_separated[$i]";
echo $fieldname[$i];
$this->Field->updateAll(array('Field.value' => "'$comma_separated[$i]'"),array('Field.fieldname' => $fieldname[$i],'Field.formname'=>$formname));
}
$this->set('retrived',$this->Field->find("all",array('conditions'=>array('Field.formname'=>$formname,))));
} // end of function formupdate
In the above formupdate method I'm inserting the values of the corresponding values of that fields in the fields table... All the values are inserted correctly - but in my formupdate.ctp view:
Nothing is displayed in my view... eventhough the content is there in the table..
Please resolve my problem

By the names of your models, I think it's safe to conclude that you're trying to ouput some HTML. Since the question isn't really complete (where is the code?), we can't tell what's wrong with it.
A wild guess would be that something is being stripped there or ignored by your browser.

Aruna,
Please post the code you're using! It's possible that the error is something small, but without knowing what you're doing, it's impossible to help more than dr. Lecter did.
When you say that the fields table is updated correctly, do you mean that you can safely invoke the Model::save() method? Are you then calling Model::read() or Model::find() in the controller, then using the returned values from that to set a variable that can be accessed in the view?

Related

How to Unserialize this data in wordpress

CURRENT ISSUE: I am making one plugin for listing users with there user role in WP_LIST_TABLE table.
This is my query
$this->items = $wpdb->get_results($wpdb->prepare("SELECT {$wpdb->users}.*, {$wpdb->usermeta}.meta_value as roles FROM {$wpdb->users}
LEFT JOIN {$wpdb->usermeta} ON {$wpdb->users}.ID = {$wpdb- >usermeta}.user_id
WHERE {$wpdb->usermeta}.meta_key = '{$wpdb->get_blog_prefix()}capabilities'
ORDER BY {$wpdb->users}.display_name", $per_page, $paged), ARRAY_A);
It display out like This
[roles] => a:1:{s:13:"administrator";b:1;}
How to Unserialize this data. and I want to display the First name too using this query please help me
Finally this helps me.
$input = unserialize($item['roles']);
$result = array();
foreach($input as $key => $value){
$result[] = $key;
}
$userRole = implode(",", $result);
return $userRole;
Try below code:
foreach($this->items as $value){
echo $value->COLUMN_NAME ."<br>";
}
Please change the COLUMN_NAME to whichever column you want to display. If there's a column named e_name, then write "$value->e_name".
Its tried and tested. It works for me. Let me know if it works for you!

Eloquent - groupBy and sum() of hasManyThrough relationship

I have 3 models Job, Diary, Resource.
Jobs has relation with Diary and Diary has relation with Resource.
I wanted to get all Resource associated with a Job and did this using
public function labourers()
{
return $this->hasManyThrough(Resource::class, Diary::class, 'job_id');
}
On my Job class.
Now I want to group the results by User who's user_id is a column in Resource and then show the total hours.
This is the closest I can get.
$job = Job::where('job_number', 3007)->first();
$labour = $job->labourers()->get();
$results = $labour->groupBy('user_id');
echo $results;
foreach($results as $result)
{
$hours = $result->sum('hours');
echo $result[0]->user_id." - ";
echo $hours.". ";
}
This gets me the user_id and the sum of the hours but I am unable to access the user name through the relationship set up on the resource model
public function user()
{
return $this->belongsTo(User::class);
}
with
$result->user->name;
This produces
Property [user] does not exist on this collection instance.
How can I return a collection which allows me to access the users name and the sum of the hours.
The reason you're not able to access the user like that is because (in this case) groupBy is a method on the collection that returns another collection.
Firstly, eager load the user relationship on so that your code is a bit more efficient:
$labour = $job->labourers()->with('user')->get();
Secondly, since you have a collection you can use first() instead of [0]:
$result->first()->user_id
Lastly, you would have to access the user in the same way you're accessing the user_id:
$result->first()->user
So, you would end up with something like:
$job = Job::where('job_number', 3007)->first();
$labourers = $job->labourers()->with('user')->get();
$results = $labourers->groupBy('user_id');
foreach($results as $result)
{
echo $result->first()->user->name . ' - ' . $result->sum('hours') . '.';
}
You can try this
$job = Job::where('job_number', 3007)->with(['labourers' => function($query){
$query->select('id','user_id', DB::raw('sum(hours) as hours'))->groupBy('user_id');
}, labourers.user])->first();
$results = $job->labourers;
foreach($results as $result){
print_r($result->user);
print_r($result->hours);
}

CakePhp foreach saving only last value in array

I have a problem, right now Im using this foreach loop on CakePhp on which I want to add all the values which are still not on the table for the respecting user. To give a little more context, the user has a menu. And the admin can select which one to add for the user to use. On the next code I receive a array with the menus which will be added as so:
//This is what comes on the ['UserMenuAccessibility'] array:
Array ( [menu_accessibility_id2] => 2 [menu_accessibility_id3] => 3 [menu_accessibility_id4] => 4 [menu_accessibility_id5] => 5 [menu_accessibility_id8] => 8 )
I get the ids of the menus which want to be added to the table for the user to use. And I use the next code to add the menus to the table if they are not there still:
//I check if the array has something cause it can come with no ids.
if (!(isset($this->request->data['UserMenuAccessibility']))) {
$this->request->data['UserMenuAccessibility'] = array();
}
$UserMenuAccessibility = $this->request->data['UserMenuAccessibility'];
foreach ($UserMenuAccessibility as $key => $value) {
$conditions = array(
'UserMenuAccessibility.menu_accessibility_id' => $value,
'UserMenuAccessibility.users_id' => $id
);
if ($this->User->UserMenuAccessibility->hasAny($conditions)) {
} else {
$valuemenu['UserMenuAccessibility']['users_id'] = $id;
$valuemenu['UserMenuAccessibility']['menu_accessibility_id'] = $value;
if ($this->User->UserMenuAccessibility->save($valuemenu)) {
} else {
$this->Session->setFlash(__('The user could not be saved. Please, try again.'));
}
}
}
For some reason the array is only saving the last new id which is not on the table and not the rest. For example if I have menu 1 and 2 and add 3 and 4 only 4 gets added to the table. For some reason I cant add all the missing menu ids to the table. Any ideas why this is happening?
Thanks for the help on advance.
It looks like your code will save each item, but each call to save() is overwriting the last entry added as $this->User->UserMenuAccessibility->id is set after the first save and will be used for subsequent saves. Try calling $this->User->UserMenuAccessibility->create() before each save to ensure that the model data is reset and ready to accept new data:-
$valuemenu['UserMenuAccessibility']['users_id'] = $id;
$valuemenu['UserMenuAccessibility']['menu_accessibility_id'] = $value;
$this->User->UserMenuAccessibility->create();
if ($this->User->UserMenuAccessibility->save($valuemenu)) {
}
In cakephp 2.0 $this->Model->create() create work fine. But if you are using cakephp version 3 or greater then 3. Then follow the below code
$saveData['itemId'] = 1;
$saveData['qty'] = 2;
$saveData['type'] = '0';
$saveData['status'] = 'active';
$saveData = $this->Model->newEntity($saveData);
$this->Model->save($materialmismatch);
In normal case we use patchEntity
$this->Model->patchEntity($saveData, $this->request->data);
It will only save last values of array so you have to use newEntity() with data
In cakephp3, patchEntity() is normally used. However, when using it for inserting-new/updating entries in a foreach loop, I too saw that it only saves the last element of the array.
What worked for me was using patchEntities(), which as explained in the patchEntity() doc, is used for patching multiple entities at once.
So simplifying and going by the original code sample to handle multiple entities, it could be:
$userMenuAccessibilityObject = TableRegistry::get('UserMenuAccessibility');
foreach ($UserMenuAccessibility as $key => $value) {
$userMenuAccessibility = $userMenuAccessibilityObject->get($value);//get original individual entity if exists
$userMenuAccessibilities[] = $userMenuAccessibility;
$dataToPatch = [
'menu_accessibility_id' => $value,
'users_id' => $id
]//store corresponding entity data in array for patching after foreach
$userMenuAccessibilitiesData[] = $dataToPatch;
}
$userMenuAccessibilities = $userMenuAccessibilityObject->patchEntities($userMenuAccessibilities, $userMenuAccessibilities);
if ($userMenuAccessibilityObject->saveMany($requisitions)) {
} else {
$this->Session->setFlash(__('The users could not be saved. Please, try again.'));
}
Note: I haven't made it handle if entity doesn't exist, create a new one and resume. That can be done with a simple if condition.

How to show data from this joint table with MVC principle of codeigniter.?

I saw this answer from a post that is intended to post database data from specific set_id with its following questions and answers. I find it hard to convert it that it has to be separated into models-controllers-views principle of codeigniter. I need some help here
It has 3 tables and came up with this code:
<?php
$this->db->select('s.id as set, s.name as name, q.id as qid, q.question as qu, a.id as aid, a.answer as an, a.points as p')
->from('sets s')
->join('questions q', 'q.set_id = s.id')
->join('answers a', 's.set_id = s.id')
->where('s.id', 'SET ID');
$questions = $this->db->get();
$set = array('questions' => array());
foreach($questions as $s){
$set['id'] = $s->set;
$set['name'] = $s->name;
$set['questions'][$s->qid]['id'] = $q->qid;
$set['questions'][$s->qid]['question'] = $q->qu;
if(!isset($set['questions'][$s->qid]['answers']))
$set['questions'][$s->qid]['answers'] = array();
$set['questions'][$s->qid]['answers'][] = array(
'id' => $q->aid,
'answer' => $q->an',
'points' => $q->p
);
}
echo '<h2>'.$set['name'].'</h2>';
foreach($set['questions'] as $q){
echo '<div class="question">';
echo '<h3>'.$q['question'].'</h3>';
echo '<div class="answers">';
foreach($q['answers'] as $a){
echo '<label for="a'.$a['id'].'">'.$a['answer'].'<input type="checkbox value="'.$a['id'].'" name="q'.$q['id'].'" /></label><br />';
}
echo '</div>';
echo '</div>';
}
MVC pattern is simple once you get used to it . The model component basically handles the database query. you can write simple functions for different query and put them under model class . The Controller basically pulls the model data and puts forward to the View component.
Inside the controller you will define logics how and where to put the data into different View classes . The following link is a good place to check out .
http://kyokasuigetsu25.wordpress.com/2012/01/06/codeigniter-beginner-tutorial-3-playing-with-the-database/
In this instruction there is a problem
$set = $questions->result_array();

CakePHP: Is it possible to insert record with pre-defined primary key value?

I have a CakePHP model - User - that has ties to an external corporate system. I store some data on those systems and other data locally. In my User::beforeSave() method, I'm trying to set an ID, send the data (with that custom ID) to my corporate systems and then, if it inserts successfully there, return true so that Cake will insert the new user record with that same ID so that I can link them later.
I can't find a way to make this happen. Is there a way to insert a CakePHP record with a user-specified primary key value? I'm using UUIDs so there's (effectively) no opportunity for overlap.
$this->data['User']['id'] = String::uuid()
try {
$user_proxy = new CoreServicesUserProxy();
$corp_user = $user_proxy->CreateUser (
array (
'user' => array (
'UserName' => 'myusername',
'EmailAddress' => $this->data['User']['email'],
'SecurityId' => $this->data['User']['id']
)
)
);
}
catch ( Exception $e ) {
// error handling stuff
return false;
}
I realise you have already been given some hints, but here is some code which might help.
Why not add an external_user_id field to your users table?
<?php
class User extends AppModel {
function beforeSave() {
$ds = ConnectionManager::getDataSource('core_services');
$externalUser = $ds->createUser($this->data);
if (!$externalUser) {
return false;
}
$this->data['User']['external_id'] = $externalUser['id'];
return true;
}
function afterFind($results, $primary) {
// handle different types of find here ('all' vs 'first' vs through relation)
foreach ($results as &$result) {
$result = $this->_mergeExternalUser($result);
}
}
function _mergeExternalUser($user) {
$ds = ConnectionManager::getDataSource('core_services');
$externalUser = $ds->retrieveUser($result['external_id']);
return am($externalUser, $user);
}
}
?>
There is a way - but typically you would add another column to the Users table instead and let CakePHP do it's thing with the primary key. See this Bakery article to know how it's done. Since it is more than a year later, this is for reference mostly. As far as I understand it, this should function well with CakePHP 1.2 as well.

Resources