2

Currently I'm trying to change the 'Assigned To' user for a lead to the current user whenever a user enters the lead details screen.

I have the following code:

function checkPermission(Vtiger_Request $request) {

    $moduleName = $request->getModule();
    $recordId = $request->get('record');

    $recordModel = Vtiger_Record_Model::getInstanceById($recordId, $moduleName);

    $recordModel->set('assigned_user_id',$current_user->id);

    $recordModel->save();

    ...

    return true;
}

The problem is, instead of saving the current record with a new assigned user, vTiger duplicates this record into a new record and saves it with the current user as a new assigned user.

Working on vTiger v6.2.0

Need A Hand
  • 577
  • 1
  • 6
  • 17
  • I had the same problem, the save command is creating the duplicate entry. But I don't know how to access the already created entity. Would love to see an answer to this too, I actually ended up updating the database manually `global $adb; [...] $adb->pquery("UPDATE [...]`. But not very nice! – Preexo Aug 10 '15 at 03:29

3 Answers3

4

You need to set mode is edit to recordModel before save

$recordModel->set('mode','edit');
Andrew Sun
  • 4,101
  • 6
  • 36
  • 53
Haidang Nguyen
  • 171
  • 3
  • 11
0

Try something like this:

            $recordModel= Vtiger_Record_Model::getInstanceById($recordId,$moduleName);
            $recordModel->set(my_fields, my_new_value);
            $recordModel->set(my_fields2, my_new_value2);
            $recordModel->set('mode', 'edit');
            $recordModel->save();
0

Tray with event Handler;

create a file: /modules/yourmodulename/handlers/RecordUpdater.php then put the code below in your file RecordUpdater.php :

require_once 'include/events/VTEventHandler.inc';

class yourmodulename_RecordUpdater_Handler extends VTEventHandler {

    function handleEvent($eventName, $data) {
        global $adb;
        $currentUserModel = Users_Record_Model::getCurrentUserModel();
        $module           = $data->getModuleName();

        if ($eventName === 'vtiger.entity.beforesave' AND $module === "yourmodulename") {

                require_once 'modules/yourmodulename/yourmodulename.php';

                $currentUserId = $currentUserModel->getId();

                $data->set('assigned_user_id', $currentUserId);
                }

        }
}

finally don't forget to insert in vtiger_eventhandlers table:

INSERT INTO `vtigercrm`.`vtiger_eventhandlers` (
`eventhandler_id` ,
`event_name` ,
`handler_path` ,
`handler_class` ,
`cond` ,
`is_active` ,
`dependent_on`
)
VALUES (
NULL , 'vtiger.entity.beforesave', 'modules/yourmodulename/handlers/RecordUpdater.php', 'yourmodulename_RecordUpdater_Handler', NULL , '1', '[]'
);

then increment vtiger_eventhandlers_seq with 1

that's it :)

I hope, that helps you

legoscia
  • 39,593
  • 22
  • 116
  • 167
Laila
  • 1