Announcement

Collapse
No announcement yet.

Problem with array_merge function in a Hook

Collapse
X
 
  • Filter
  • Time
  • Show
Clear All
new posts

  • Problem with array_merge function in a Hook

    Hello. I have 3 fields in my Account entity. owners, accountants and managers. They are all multiple links to User entity. I use Account's beforeSave and afterSave hooks. In general, I need to have a linked Team entity(the Team can be only one) for every Account. Owners, accountants or managers may change sometimes and I want to save all these users to Team.users every time after saving Account entity. I wrote this code:
    PHP Code:
    <?php
    namespace Espo\Custom\Hooks\Account;

    use 
    Espo\ORM\Entity;

    class 
    Teams extends \Espo\Core\Hooks\Base
    {

    public function 
    beforeSave(Entity $entity, array $options = [])
    {
    //creating new Team if Account is new
    if ($entity->isNew()) {
    $nameOfAccount $entity->get('name');
    $team $this->getEntityManager()->createEntity('Team', [
    'name' => 'Some name'
    ]);
    $this->getEntityManager()->saveEntity($team);
    //link Team to Account.teams
    $teamId $team->get('id');
    $teamsIds = [$teamId];
    $entity->set('teamsIds'$teamsIds);
    }


    }

    public function 
    afterSave(Entity $entity, array $options = [])
    {
    //finding the Team
    $team $this->getEntityManager()
    ->
    getRepository('Account')
    ->
    getRelation($entity'teams')
    ->
    findOne();
    //getting ids of users
    $idsOfOwners $entity->get('ownersIds');
    $idsOfAccountants $entity->get('accountantsIds');
    $idsOfManagers $entity->get('managersIds');
    //merge them in one array
    $allIds array_merge($idsOfOwners$idsOfAccountants$idsOfManagers);
    //setting all ids to Team.users
    $team->set('usersIds'$allIds);
    $nameOfAccount $entity->get('name');
    $team->set('name'$nameOfAccount);
    $this->getEntityManager()->saveEntity($team);
    }

    }
    This code works fine when I creating new Account. It creates new team and set all users in Team.users as I want. But if I changing some user it doesn't change Team.users. There is a warning in a log file WARNING: E_WARNING: array_merge(): Expected parameter 1 to be an array, null given {"code":2,"message":"array_merge(): Expected parameter 1 to be an array, null given". If I replacing array_merge with, for example, only $idsOfAccountants it works great every time I change Accountant user. What am I doing wrong? Why it can pass null instead of the array of Ids?

  • #2
    Check $idsOfOwners, $idsOfAccountants, $idsOfManagers are arrays ( using var_dump) and check model maybe by using Postman to eliminate a mistake in a variables names.

    Comment

    Working...
    X