How to add Account name to a contact in Dynamics 365

410 views Asked by At

I am using Alexa-php-toolkit for Dynamics 365 https://github.com/AlexaCRM/php-crm-toolkit, using this I can successfully create new contact but I can't add an account name with the contact, when I try I get this error:

Notice: Property accountid of the contact entity cannot be set in ../vendor/alexacrm/php-crm-toolkit/src/Entity.php on line 263.

Here is my script.

<?php
//URL: https://github.com/AlexaCRM/php-crm-toolkit
/**
 * Use init.php if you didn't install the package via Composer
 */
use AlexaCRM\CRMToolkit\Client as OrganizationService;
use AlexaCRM\CRMToolkit\Settings;
require_once '../vendor/autoload.php';
require_once '../vendor/alexacrm/php-crm-toolkit/init.php';
require_once 'config.php';
require_once 'includes/db.php';
$db         = new DB();
$options    = getAuth();
$serviceSettings = new Settings( $options );
$service = new OrganizationService( $serviceSettings );
$accountId = 'a2536507-018d-e711-8115-c4346bac0a5f';
// create a new contact
$contact = $service->entity( 'contact' );
$contact->accountid = $accountId;
$contact->firstname = 'Test';
$contact->lastname = 'Contact12'; 
$contact->jobtitle = 'Business Analyst';
$contact->mobilephone = '1002345679';
$contact->fax = '9902345679';
$contact->emailaddress1 = '[email protected]';
$contact->address1_line1 = '119 Cambridge'; 
$contact->address1_line2 = 'Apt 22';
$contact->address1_city = 'Houston';
$contact->address1_stateorprovince = 'TX';
$contact->address1_postalcode = '77009';
$contact->address1_country = 'US';
$contactId = $contact->create();
echo $contactId; 
?>
1

There are 1 answers

0
jcjr On BEST ANSWER

There is this line of your code in a question:

$contact->accountid = $accountId;

First, the parent account on a contact is saved in the parentcustomerid field that is a special lookup field that can store link to both account or contact entity. The fields accountid and parentcontactid help to handle this in background, but are not generaly available. You need to work with parentcustomerid field.

Second, another problem when working with lookups (foreign keys) is you need to pass entity type (table name).

The correct code might look like this:

$accountRef = $client->entity( 'account' );
$accountRef->ID = $accountId;
$contact->parentcustomerid = $accountRef;

or

$contact->parentcustomerid = new EntityReference( 'account', $accountId );

Those examples are taken from the issue list, adjusted, but not tested. I hope it is working example, not functionality request.