Search code examples
phpoopsilverstripe

Filter dataobject by page id SilvertStripe3


I have a page type "class Test extends Page" and it has many 'TestBlocks' => 'TestBlock', then the CMS users enter new data to the fields on CMS back-end and what I need is to get these values from "class TestBlock extends DataObject" and to create a form with them. Basically that data becomes question, but I'm not sure how to get it inside my Test controller the right way. When i try the get method for dataobect it returns all values from all pages from the pagetype instead that particular page code below:

class Test_Controller extends Page_Controller
{
private static $allowed_actions = array(
    'TestForm',

);

public function TestForm()
{

    $players = MultiQuestion::get();
    echo $players->QuestionText;
    $array = [];
    foreach ($players as $player) {
        $array[] = TextField::create($player->QuestionText)->setFieldHolderTemplate('Field_Holder');
    }

    $fieldGroup1 = CompositeField::create(
        $array

    )->setName('FieldGroup1');

    $fields = FieldList::create($fieldGroup1);
    $actions = FieldList::create(
        FormAction::create('submit', 'Get Results')->addExtraClass('get_results')
    );
    $form = Form::create($this, __function__, $fields, $actions);

    return $form;
}
}

Solution

  • You can use $testBlocks = $this->TestBlocks() assuming that you have the relationships set up correctly.

    TestBlock.php

    class TestBlock extends DataObject {
      static $has_one = array(
        'Test' => 'Test'
      );
    }
    

    Test.php

    class Test extends Page {
      static $has_many = array(
        'TestBlocks' => 'TestBlock'
      );
    }
    
    class Test_Controller extends Page_Controller {
    
      public function TestForm() {
        $testBlocks = $this->TestBlocks();
        //other code
      }
    }