how to save array data in database in cakephp3? - cakephp

Hi I'm new in cakephp and i want to save some array data in database
here is my code
$user = $this->Users->newEntity();
if ($this->request->is('post')) {
$user = $this->Users->patchEntity($user, $this->request->data);
$userdata=[
'firstname'=>$user['firstname'],
'lastname'=>$user['lastname'],
'nationcod'=>$user['nationcod'],
'usrename'=>$user['username'],
'password'=>$user['username']
];
$this->Users->save($userdata);
but when I test it this error occurred:
Call to a member function errors() on array.
I just wanna change user posted data and save it in the users table.

You have assigned $user with $this->Users->newEntity();. And afterwords you are using $user['firstname']. There won't be anything in it as it is an entity not array. From your question I guess that you want to keep user's username as their password. So all you have to do is this.
$user=$this->Users->newEntity();
if($this->request->is('post')){
$this->request->data['password']=$this->request->data['username'];
$user=$this->Users->patchEntity($user,$this->request->data);
$this->Users->save($user);
}

Related

CakePhp save changes only in middle table

Here is the problem what I have
I have 3 tables m:n
Users -> addresses_users -> Addresses
During adding new user I am selecting from dropdown X Addresses and after I click save I have to save new user data (new user in Users table), make mapping in addresses_user table and Addresses table shouldnt be changed, cos I have already those addresses in DB.
So, if i use code like this
input in ctp with
name="addresses[]"
In controller
if ($this->request->is('post')) {
$user = $this->Users->patchEntity($user, $this->request->
if ($this->Users->save($user)) {
$this->Flash->success(__('The user has been saved.'));
return $this->redirect(['controller' => 'users', 'action' => 'view/' . $user->id]);
} else {
$this->Flash->error(__('The user could not be saved. Please, try again.'));
}
}
Cakephph makes mapping automatically and want to save new user, mapping and information about addresses.
Is there way to make this automatically with cakephp that he saves new user and make mapping or I should use another input name (that cakephp doesnt make patch with addresses) and after save make foreach with all addresses_id and save values direct to addresses_users table?
Or there is better ideas?

Add a user in Cakephp

There is a problem when I write an add() function for UsersController.
public function add() {
if ($this->request->is('post')) {
$this->request->data['User']['book_id'] = $this->Book('id');
if ($this->User->saveAssociated($this->request->data)){
$this->request->data['User']['book_id'] = "ff";
$this->Session->setFlash(__('Save User'));
return $this->redirect(array('action' => 'index'));
}
$this->Session->setFlash(__('User Error.'));
}
}
If I add a User I want to save the book ID in my User book_id.
Anyone know how to deal with this problem? Thanks!
When you're adding a new user, does he get to select a book from a drop down(in the form)? If so, $this->request->data['User']['book_id'] will already contain the Book id.
There's no need to explicitly write $this->request->data['User']['book_id'] = $this->Book('id'); like you have done.
The way I see it, the add.ctp view file should contain a select box containing a list of all books which the user can select. On selecting one of those and submitting the form, $this->request->data['User']['book_id'] will automatically store the book_id, without having to write anything in the controller.
Please specify the add.ctp form fields so that I can assist you better.
Thanks!

Drupal 7 - show logged in user full name and email id

I know that I can fetch the logged in user's name as
<?php
global $user;
print $user->name;
?>
However, I want to know how to show logged in user's full name (first and last name) and email id. Any help?
You could use print_r($user) to look at the $user object. But i dont think global $user includes profile fields, so you might have to load the user object again like so:
global $user;
$account = user_load($user->uid);
print_r($account);
And the email field is usually:
$user->mail;
If you are still using drupal 7. you can get the user profile like this:
global $user;
$account = user_load($user->uid);
$user_email = $account->field_profile_email[LANGUAGE_NONE][0]["email"];
$user_first_name = $account->field_first_names[LANGUAGE_NONE][0]["value"];
$user_last_name = $account->field_surname[LANGUAGE_NONE][0]["value"];
$user_full_name = "$user_first_name $user_last_name";

Trying to write a simple Joomla plugin

Please help, this is my first plugin I'm writing and I'm completely lost. I'm trying to write and update information in a table in a joomla database using my custom giveBadge() function. The functions receives two different variables, the first variable is the $userID and the second one is the digit 300 which I pass at the bottom of the class using giveBadge(300). At the same comparing the $userID in the Joomla database to ensure that the number 300 is given to the current user logged in the Joomla site.
Thanks in advance.
<?php
defined('JPATH_BASE') or die;
class plgUserBadge extends JPlugin
{
public function onUserLogin () {
$user =& JFactory::getUser();
$userID =& user->userID;
return $userID;
}
public function giveBadge ($userID, &$badgeID) {
// Get a db connection.
$db = JFactory::getDbo();
// Create a new query object.
$query = $db->getQuery(true);
// Fields to update.
$fields = array(
'profile_value=\'Updating custom message for user 1001.\'',
'ordering=2');
// Conditions for which records should be updated.
$conditions = array(
'user_id='.$userID,
'profile_key=\'custom.message\'');
$query->update($db->quoteName('#__user_badges'))->set($fields)->where($conditions);
$db->setQuery($query);
try {
$result = $db->query();
} catch (Exception $e) {
// Catch the error.
}es = array(1001, $db->quote('custom.message'), $db->quote('Inserting a record using insert()'), 1);
}
}
giveBadge(300); //attaches to $badgeID
?>
Here is not going well with your code:
You can drop the assign by reference in all your code (&) - you really don't need it, in 99% of the cases.
Use an IDE (for example Eclipse with PDT). At the top of your code you have & user->userID; Any IDE will spot your error and also other things in your code.
Study existing plugins to understand how they work. Here is also the documentation on plugins.
The method onUserLogin() will automatically be called by Joomla when the specific event is triggered (when your plugin is activated). Check with a die("My plugin was called") to see if your plugin is really called
inside onUserLogin() you do all your business logic. You are not supposed to return something, just return true. Right now your method does absolutely nothing. But you can call $this->giveBadge() to move the logic to another method.

CakePHP: Retrieve specific table field in controller

I am new to Cake and tried to find the best solution to retrieve a specific field belonging to an $id:
This is my view function in my Post controller
function view($id = null) {
if (!$id) {
$this->Session->setFlash(__('Invalid post', true));
$this->redirect(array('action' => 'index'));
}
$this->set('post', $this->Post->read(null, $id));
}
In the post table, there is a user_id foreign key. I need to retrieve this specific field belonging to this Post $id.
I read about functions as find('All), read() or just drop an unconventional session in the view through:
$session->write('example') = $post['Post']['user_id];
What is the best way to do this, my preference is to retrieve the field in the controller. Thanks!
CakePHP has a field function which should do just that.
$this->Post->id = $id;
$user_id = $this->Post->field('user_id');
For more information on using field, see: http://book.cakephp.org/2.0/en/models/retrieving-your-data.html#model-field
A second option is to use the find function and returning only a few fields if you do not want the entire Post object. Also shown below is using a condition instead of setting the current Post.
$this->Post->find('first', array(
'conditions'=>array('id'=>$id),
'fields'=>array('user_id')
));
More information on find is available at: http://book.cakephp.org/2.0/en/models/retrieving-your-data.html
$this->Post->id = $id;
$this->Session->write('example',$this->Post->field('user_id'));
In CakePHP 3, you can use $this->Model->get() to get the Entity, and then reference the required field directly.
$fieldValue = $this->ModelName->get($id)->fieldName;
Try this one, since I don't know which field(s) you need I provide an example field array set using Magic Find Types:
$fields = ['title', 'body', 'created'];
$record = $this->Post->findById($id, $fields);
or multiple records
$recordSet = $this->Post->findAllByTitle('The title', $fields);
*Note the the second example doesn't make a lot of sense unless there are multiple titles with the name 'The title' in the the posts.title column.

Resources