jareddreyer
9/13/2017 - 10:33 PM

Silverstripe

Useful Silverstripe tips

<?php
//add specific class but not extended classes to allowed children

class Page extends SiteTree {
  private static $allowed_children = array("*Page,", "BlogHolder");
}
<?php

//simple array list in silverstripe using PHP6 array syntax.

public function myfruit() {
	$fruit = new ArrayList([
		new ArrayData(['fruit' => 'foo']), 
		new ArrayData(['fruit' => 'bar']),
	]);
	
	return $fruit;
}
<?php

/**
 *  Checks if class exsists
 * 
 */
 
 public function getVacancies () {

		if($Page = SiteTree::get()->Filter('ClassName', 'SkillVacancies')->First()->URLSegment) {
			
			return $Page;
		}

		return false;
	}
<?php
	/** 
	 * gets parent ID
	 * gets all children based on parent ID
	 * 
	 * @return obj
	 **/

class Page_Controller extends Page_Controller {

	public function init() {
		parent::init();
	}


	public function Articles(){
		$newsLandingPageID = ClasssPage::get()->first();


		$newsItems = Page::get()->filter(array('ParentID' => $newsLandingPageID->{'ID'} ) );
		$newsItems = $newsItems->sort('Created DESC');
		$list = PaginatedList::create($newsItems, $this->getRequest());
		$list->setPageLength(15);
		
		return $list;
	}
	
<?php
//still work in progress
use SilverStripe\Control\Controller;

class CopyDMSAssets extends BuildTask {
 
    protected $title = "Copy DMS Assets"; 
    protected $description = "Copys DMS Assets from _dmsasset folder to whats specificed in config.yml"; 
    protected $enabled = true;
 
    public function run($request) {
        
        //get all document dataobjects        
        $document = DMSDocument::get();
        
        $DMSAssetsPath = Config::inst()->get('DMS', 'folder_name');

        //check if config.yml has been updated, otherwise you don't know new folder path for DMS Assets
        if($DMSAssetsPath == "assets/_dmsassets") {
          echo  "Config.yml has not been updated first, please update to new DMSAssets folder and try again.".PHP_EOL;
          
          return;
        } 

       //check if config.yml new directory for DMS is created
        if(file_exists(BASE_PATH . DIRECTORY_SEPARATOR . $DMSAssetsPath) !== TRUE) {
            
            if(mkdir(BASE_PATH . $DMSAssetsPath ) === FALSE) {
                echo "Was a problem creating folder " . $DMSAssetsPath;

                return;
            }

        }

        if(file_exists(BASE_PATH . DIRECTORY_SEPARATOR . $DMSAssetsPath. DIRECTORY_SEPARATOR . "0") !== TRUE) {
            
            
            if(mkdir(BASE_PATH . DIRECTORY_SEPARATOR . $DMSAssetsPath . DIRECTORY_SEPARATOR . "0") === FALSE) {
                echo "Was a problem creating folder " . $DMSAssetsPath . "/0";

                return;
            }
        }

        
        //start requesting to move everything
        foreach ($document as $key => $value) {
            $this->SaveDMSAssets($value->Link, $value->Filename, $DMSAssetsPath);
        }
    }

    /**
    *   Save DMS files to new directory
    *   
    *   Takes file and copies it to new DMS assets folder,
    *   based on config.yml setting <folder_name>
    *
    *   @var $url <string> - URL to grab file
    *   @var $filename <string> - file name to save in new DMS assets dir
    *   @var $DMSAssetsPath <string> - folder
    */
    public function SaveDMSAssets ($url, $filename, $DMSAssetsPath) {

        //save into new folder e.g. /assets/dmsassets/0/document.pdf
        file_put_contents(
            BASE_PATH . $DMSAssetsPath . DIRECTORY_SEPARATOR. "0" .DIRECTORY_SEPARATOR . $filename, 
            file_get_contents(SS_PRIMARY_DOMAIN. DIRECTORY_SEPARATOR . $url)
        ); 

        echo  "Saved...." . $filename . " in ". BASE_PATH. $DMSAssetsPath. PHP_EOL;

        return;
    }
    
}
<?php 

class PublishDMSAssetSizes extends BuildTask
{
    protected $title = 'Publish DMS Asset Sizes';
    protected $description = 'Publishes the file size for all DMS documents.';

    /**
     * {@inheritDoc}
     */
    public function run($request)
    {
        //check if we running from cli or web
        $lbr = php_sapi_name() === 'cli' ? "\n" : "<br />\n";

        $documents = DMSDocument::get();

        //loop all DMS documents, and republish
        foreach ($documents as $document) {
                 
            $fileSize = $document->AbsoluteSize;
            
            if ($fileSize != null) {
                echo "Publishing page '{$document->Title}'" . $lbr;
                $document->write();
            } else {
                echo "document '{$document->Title}' will not be published" . $lbr;
            }
        }
    }
}
<?php

//get fields from config.yml
$array = Config::inst()->get('MyConfig', 'States');

foreach ($array as $key => $value) echo "$key: $value<br>";
<?php

function sendForm($data, $form) {
	
	//Custom validation
	if ($data['FieldName'] == 0) { //Some logical test
	
		//Add error message to field
		$form->addErrorMessage('FieldName','Something went wrong!','required');
		//Set form data from submitted values
		Session::set("FormInfo.".$form->FormName().".data", $data);
		//Return back to form
		return $this->redirectBack();
		
	}
<?php

class CustomValidator extends RequiredFields {
    public function php($data) {

    	$RequiredFields  = array(
		 		'Organisation',
				'Name',
				'ContactName',
				'ContactTitle',
				'ContactEmail',
				'Website',
				'LogoID',
				'Member',
				'TAC',	
		);

		$this->appendRequiredFields(RequiredFields::create($RequiredFields));


        if($data['Member'] == 'No') {

	 		$this->addRequiredField('OrgAddress');
	        $this->addRequiredField('OrgPhone');
	        $this->addRequiredField('BusinessSize');
	        $this->addRequiredField('Region');
	        $this->addRequiredField('PrimarySector');
	        $this->addRequiredField('OpSector');
        }

        return parent::php($data);
    }
}

//get form object field 
$form->dataFieldByName('FirstName')->Value()
<?php
/**
* 
* exclude new page from showing in menus
* 
*/

private static $defaults = array('ShowInMenus' => 0);

?>
  <?php
  /**
   * Checks if dataobject is empty
   * 
   * @note: If any sorting is done on the dataobject before the exists() call 
   * is made, then the object will be converted to an array and exists() can 
   * only be called on objects.
   */
  public function dataObject()
  {
    //get dataObject
    $result = Class::get(); 
    
    //if result is empty return null
    return ($result->exists()) ? $result : $result null; 
  }
  
/**
 * debugging tools in silverstripe
 * 
 * 
 */
 public function debug () {
    //get debug output of object/variable
    debug::dump($variableName);   
    
    //get SQL dump of called query
    echo $class->sql();
 }

/**
 * set 2 fields as 1 output for a dropdown field
 * 
 */
 //data object
 class ListCountry extends DataObject
 {
    static $db = array(
  		'Title' => 'Varchar',
  		'Code' => 'Varchar'
  	);

  	public function getCountryAndCode () {
  		return $this->Title . ' ('. $this->Code . ')';
  	}
}
 
 //page controller
  $fields->addFieldToTab("Root.VAP", 
    new DropdownField('CountryID', 'Country', ListCountry::get()->map("ID", "CountryAndCode", "Please select"))
  );
<?php
/**
* Check if current logged in user belongs to administrators group
*
*/
public function userGroupCheck() {
    if(Member::currentUser()){
             if(Member::currentUser()->inGroup('Administrators')) return true;   
    }
}
<?php
/**
 * insert new field to fieldlist 
 * 
 */
$fields = new FieldList(<fields here>);
$fields->push(<new field>);

/**
 * 
 * use parent scope methods in template form render
 * 
 */
 
 return $form->customise(array('templateMethodCall' => $this->parentMethodName()));