PHP code example of sylvainjule / categories

1. Go to this page and download the library: Download sylvainjule/categories library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

sylvainjule / categories example snippets


// site/config/config.php
'sylvainjule.categories.watch' => [
    'template' => 'fieldname',
    'template' => ['fieldname1', 'fieldname2'],
    'site'     => 'fieldname', # can also be used with the site.yml blueprint
]

// site/config/config.php
'sylvainjule.categories.watch' => [
    'blog'     => 'categories',
    'projects' => ['clients', 'techniques'],
]

'sylvainjule.categories.watch' => []

'sylvainjule.categories.hook' => true,

// select field
$categories = $page->parent()->categories()->toCategories(); // our structure field
$category   = $page->category(); // a select field value referencing structureItem.uuid
$category   = $categories->findBy('uuid', $category); // we convert this UUID into the associated Structure Object

// multiselect field
$categories         = $page->parent()->categories()->toCategories(); // our structure field
$selectedArray      = $page->categories()->split(); // a multiselect field value referencing structureItem.uuid
$selectedCategories = $categories->filter(function($category) use($selectedArray) {
  return in_array($category->uuid()->value(), $selectedArray);
}); // we convert this array of UUIDs into a filtered Structure

...

'page.update:after' => function($newPage, $oldPage) {
    // get the array of changes to apply
    // $changes = [
    //     'en' => [
    //         'fieldname1' => $data,
    //         'fieldname2' => $data,
    //     ],
    //     'de' => [
    //         'fieldname1' => $data,
    //         'fieldname2' => $data,
    //     ],
    //     ...
    // ]
    $changes = $categories->getChangesArray($this, $newPage, $oldPage);

    // logic to merge into your own hook / save to make sure content is saved in all languages
    $currentLanguage = $this->language();
    $currentCode     = $currentLanguage->code();
    $otherLanguages  = $this->languages()->not($currentLanguage);

    if(array_key_exists($currentCode, $changes)) {
        $newPage = $newPage->save($changes[$currentCode], $currentCode);
    }
    foreach($otherLanguages as $lang) {
        if(array_key_exists($lang->code(), $changes)) {
            $newPage = $newPage->save($changes[$lang->code()], $lang->code());
        }
    }
},