4

I am stuck on saving entry with a category field. The error message I get is about not being able to create/update the entry in the relations table.

$accomodationTypecategory = ['title'=>'Hotel']

$entry = new EntryModel();
$entry->sectionId = 3;
$entry->typeId = 3;
$entry->authorId = 1;
$entry->enabled = true;
$entry->setContent(
    $entry->getContent()->setAttributes([
        'title' => 'Test Entry', 
        'body' => "Testing", 
        'address'=>"101 Silver Avenue",
        'phone'=>'0209900292092',
        'websiteAddress'=>'www.example.com',
        'towns'=>'Newy', 
        'accommodationType'=>$accomodationTypecategory
    ]);

craft()->entries->saveEntry($entry);

Any help will be appreciated.

1 Answer 1

6

To set a related category (or any other kind of element) you will want to pass an array of categoryIds (elementIds) — even if, as in this case, there is only one category or element. You can either set the ID as a static value if it's predefined or dynamically look it up based on the title, slug or any other unique element attribute.

$criteria = craft()->elements->getCriteria(ElementType::Category);
$criteria->title = 'Hotel';
$accomodationTypeCategory = craft()->elements->findElements($criteria);

$entry = new EntryModel();
$entry->sectionId = 3;
$entry->typeId = 3;
$entry->authorId = 1;
$entry->enabled = true;
$entry->getContent()->setAttributes(array(
    'title'             => 'Test Entry', 
    'body'              => 'Testing', 
    'address'           => '101 Silver Avenue',
    'phone'             => '0209900292092',
    'websiteAddress'    => 'www.example.com',
    'towns'             => 'Newy', 
    'accommodationType' => array(
        $accomodationTypeCategory[0]->id
    )
);
craft()->entries->saveEntry($entry);
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.