Use the user.module API to create user in Drupal 7 - php

I am trying to use user_save() in Drupal 7 to add new accounts to the system.
The function is defined as user_save($account, $edit = array(), $category = 'account').
According to the documentation, the variable $account is a user object. How do I put together a user object that the function can process?

Here is a comment that may help you out a little regarding the user object: User Object. Another way to see what the user object holds is to do:
<?php
global $user;
print_r($user);
?>
Here is a very basic example of creating a new user with user_save():
<?php
$edit = array(
'name' => 'New User',
'pass' => 'password',
'mail' => 'myemail#example.com',
'status' => 1,
'language' => 'en',
'init' => 'myemail#example.com',
'roles' => array(2 => 'authenticated user'),
);
user_save(NULL, $edit);
?>

Related

How to edit a session after it's created

I'm using Phalcon PHP and I want to add another item to my session after it's created. I have this :
private function _registerSession($user, $account) {
$this->session->set('auth', array(
'user_id' => $user->id,
'username' => $user->name
)); }
In another controller I want to edit this session for example :
$auth = $this->session->get('auth');
$auth->add('account_id', '10');
And this session will content the 3 variables as :
$this->session->set('auth', array(
'user_id' => $user->id,
'username' => $user->name,
'account_id' => 10
)); }
But I don't know how I can dot that.
Yo need to do it in following manner:-
$auth = $this->session->get('auth'); // get auth array from Session
$auth['account_id']= '10'; // add new index value pair to it
$this->session->set('auth',$auth); // reassign it to auth index of Session
This should work:
$auth = $this->session->get("auth");
$this->session->set("auth", array_merge($auth, array('account_id'=>'10')));
i think you can use like this :-
$auth = $this->session->get('auth');
$auth['account_id']= 10;
$this->session->set('auth',$auth);
private function _registerSession($user, $account) {
$this->session->set_userdata('auth', array(
'user_id' => $user->id,
'username' => $user->name
)); }
// You should use the following code to set one more parameter in sesssion:
$this->session->set_userdata('auth', array(
'user_id' => $this->session_userdata('user_id'),
'username' => $this->session_userdata('username'),
'account_id' => 10
));
Phalcon's session code is simply a wrapper around $_SESSION. The simplest solution is to avoid using Phalcon functions:
$_SESSION['auth']->add('account_id',10);

Changing display logic for a field in sugarcrm

I have the following situation: Contacts without a first or last name, in fact, they only have a email address.
I can work with these contacts fine, but when I use the listview anywhere (for instance to show all contacts from a company) there now is no way to click through to the contact (normally you would click on the name).
I'm looking for a way to solve this, for instance by showing a clickable text like 'name not known', but can't figure out how to do this. I've been looking at the manual and in the files in the modules directory and the sugarfields dir, but can't quite figure it out.
The closest I got was in /sugarcrm/modules/Contacts/metadata/listviewdefs.php
where this piece of code resides:
$listViewDefs['Contacts'] = array(
'NAME' => array(
'width' => '20%',
'label' => 'LBL_LIST_NAME',
'link' => true,
'contextMenu' => array('objectType' => 'sugarPerson',
'metaData' => array('contact_id' => '{$ID}',
'module' => 'Contacts',
'return_action' => 'ListView',
'contact_name' => '{$FULL_NAME}',
'parent_id' => '{$ACCOUNT_ID}',
'parent_name' => '{$ACCOUNT_NAME}',
'return_module' => 'Contacts',
'return_action' => 'ListView',
'parent_type' => 'Account',
'notes_parent_type' => 'Account')
),
'orderBy' => 'name',
'default' => true,
'related_fields' => array('first_name', 'last_name', 'salutation', 'account_name', 'account_id'),
),
Somewhere there has to be a function that joins the first and lastname together...
Edit: I found a solution:
The actual concatenation function is in /sugarcrm/include/SugarObjects/templates/person/person.php and is called _create_proper_name_field()
I can modify the output for my specific case by adding something like this to the end of the function:
if (empty(trim($full_name))){
$full_name = 'Name unknown';
}
However, I would rather have a upgrade safe solution, so that will be the next challenge.
Don't edit the core because the next upgrade will break your SugarCRM instance. Use logic hooks to be upgrade safe:
create a file 'logic_hooks.php' in /custom/modules/Contacts/
In that file, add the followin code:
<?php
$hook_array['before_save'][] = Array(1,'logic_fill_name','custom/modules/Contacts/logic_hooks/logics.php','ContactLogics','logic_fill_name');
After you have done this. create the file 'logics.php' in /custom/modules/Contacts/logic_hooks.
In the logics.php file, add something like:
<?php
require_once 'include/SugarQuery/SugarQuery.php';
/**
* Class ContactLogics
*/
class ContactLogics {
/**
* #param $bean
* #param $event
* #param $arguments
*/
public function logic_fill_name($bean, $event, $arguments) {
if (empty(trim($bean->first_name)) && empty(trim($bean->last_name))){
$bean->last_name = 'Name unknown';
}
}
}
Now some explanation. When you edited a recordview and pressed the save button, the logic hook 'before_save' will be triggered. This code will change the full name to 'Name unknown' when the full name is empty. When the 'before_save' is executed, the actual save will take place.

Zf2 Form dependent on userId

I want to create a dropdown unique to the users, and found a way to do that, but its not ok with the client.
here is what i`ve done:
public function __construct($name = null, EntityManager $em = null, $userId = null)
{
parent::__construct($name);
$this->setAttribute('method', 'post');
[...]
$this->add(array(
'name' => 'religionId',
'type' => 'DoctrineModule\Form\Element\ObjectSelect',
'options' => array(
'object_manager' => $this->getEntityManager(),
'target_class' => 'Religions\Entity\Religions',
'property' => 'name',
'disable_inarray_validator' => true,
'by_reference' => false,
'is_method' => true,
'find_method' => array(
'name' => 'findBy',
'params' => array(
'criteria' => array('reUserId' => $userId),
'orderBy' => array('name' => 'ASC'),
),
),
),
'attributes' => array(
'multiple' => false,
'required' => false,
)
));
}
This worked, as i was sending the variable reuserId when initializing the form, using $this->identity()
The client wants to inject the user entity and select from there....
Searched stackoverflow and google, but was not able to find anything...any help please? thanks!
To 'inject' anything in ZF2 you will need to use the ServiceManager and create service factories.
It is therefore important to ensure that you are always creating the form via the ServiceManager.
In a controller for instance:
$form = $this->getServiceLocator()->get('MyModule\Form\FooForm');
Then you would need to 'inject' the user buy creating a factory class or closure.
Module.php
public function getFormElementConfig() {
return array(
'factories' => array(
'MyModule\Form\FooForm' => function($fem) {
$serviceManager = $fem->getServiceLocator();
$entityManager = $serviceManager->get('objectmanager'); // Doctrine object manager
// Load the user
// Example is the zfcUser authentication service, however replace
// this with whatever you use to maintain the users id
$user = $serviceManager->get('zfcuser_auth_service')->getIdentity();
// Inject the user entity into the form constructor
$form = new FooForm($user);
return $form;
},
),
);
}
With that said I think you might need to think about the form dependencies. It seems to me that you do not depend on the user entity - but rather the user's id should be used in a database query that reduces the list of 'Religions'.
You could execute this query and then pass the result (The religion collection) to the form in the same way my example shows how to for the user entity - This would then mean you could use a 'normal' Zend\Form\Element\Select rather than the ObjectSelect - meaning no need to inject the ObjectManager etc.

Troubleshooting dynamic dropdowns in SugarCRM 6.5

I had asked a question here a while back about setting up database populated dropdowns for SugarCRM. I received a really good answer and, after more php studies and a dev instance running, I decided to give it a shot. The instructions I followed can be found here. After I run the repair and rebuild, I would expect to see the custom field in my Fields list under the module in studio, but have not been able to find it. The module is named Makers (a1_makers as a database table). For good orders sake, there were no errors when I repaired/rebuilt after saving the files. Per the instructions, I first created a php file with a custom function to query the database (custom/Extension/application/Ext/Utils/getMakers.php):
<?php
function getMakers() {
static $makers = null;
if (!$makers){
global $db;
$query = "SELECT id, name FROM a1_maker";
$result = $db->query($query, false);
$accounts = array();
$accounts[''] = '';
while (($row = $db->fetchByAssoc($result)) !=null) {
$accounts[$row['id']] = $row['name'];
}
}
return $makers;
}
?>
Then, I set 'function' field in Vardefs to point to the function (custom/Extension/modules/Maker/Ext/Vardefs/makers_template.php):
<?php
$dictionary['Maker']['fields']['list_of_makers'] = array (
'name' => 'list_of_makers',
'vname' => 'LBL_MKRLST'
'function' => 'getMakers',
'type' => 'enum',
'len' => '100',
'comment' => 'List of makers populated from the database',
);
?>
Unfortunately, there are no errors and the repair/rebuild runs fine. I am just unable to see the custom field when I go into studio. Can anyone please help point out what I may be doing wrong?
I would recommend checking existence of newly created field 'list_of_makers' in cache/modules/Maker/Makervardefs.php file. If new field definition exists in that file, try add 'studio' => 'visible' to custom/Extension/modules/Maker/Ext/Vardefs/makers_template.php to get something like this:
<?php
$dictionary['Maker']['fields']['list_of_makers'] = array (
'name' => 'list_of_makers',
'vname' => 'LBL_MKRLST'
'function' => 'getMakers',
'type' => 'enum',
'studio' => 'visible'
'len' => '100',
'comment' => 'List of makers populated from the database',
);
Try to edit your custom/modules/Maker/metadata/editviewdefs.php manually and insert field definition by hand in proper place if everything above won't work.
$dictionary['Maker']['fields']['list_of_makers'] = array (
'name' => 'list_of_makers',
'vname' => 'LBL_MKRLST'
'function' => 'getMakers',
'type' => 'enum',
'studio' => 'visible'
'len' => '100',
'comment' => 'List of makers populated from the database',
'studio' => array(
'listview' => true,
'detailview' => true,
'editview' => true
),
);

Cakephp testing login

I want to test login function if it works propperly and only lets valid and active users in.
My user fixture contains:
array(
'password' => '*emptyPasswordHash*', // empty password
'username' => 'Lorem',
'balance' => 0,
'currency' => 'USD',
'id' => 1,
'user_group_id' => 3, //Customer
'active' => 1,
'hash' => 'LoremHash'
),
My test function looks like this:
function testLogin() {
//test valid login
$result = $this->testAction('/users/login', array(
'data' => array(
'User' => array(
'username' => 'Lorem',
'pass' => '',
'remember' => true
)),
'method' => 'post',
'return' => 'view'
));
debug($result);
}
The login form has 3 inputs: username, password and remember
I have set $this->Auth->autoRedirect = false; in the UsersController::beforeFilter and I am doing some cookie setting stuff
when I debug($this->data); in UsersController::login() it shows the exact same data when testing and when logging normaly. But while testing the login fails and I get $this->Auth->loginError message instead of a login.
How do I test login action propperly?
if you use cakes Auth component and dont hack it up you dont need to...
https://github.com/cakephp/cakephp/blob/master/cake/tests/cases/libs/controller/components/auth.test.php#L545
and if you really want to, look at how the pro's do it :)
Did you also set your custom function, like described in The CakePHP manual:
Normally, the AuthComponent will
attempt to verify that the login
credentials you've entered are
accurate by comparing them to what's
been stored in your user model.
However, there are times where you
might want to do some additional work
in determining proper credentials. By
setting this variable to one of
several different values, you can do
different things.

Categories