Learner One Learner One - 6 months ago 17
PHP Question

$many_many relation in summary fields

I have two classes with a

$many_many
and
$belongs_many_many
relation between them. I tried to define
$summary_fields
in the class that contains the
$many_many
to display the relation between the classes but that column ('Column2.Column2') displays blank results. How do I set
$summary_fields
to display this data correctly?

Here is my code

class Table1 extends DataObject {

private static $db = array(
'Column1' => 'Varchar(32)'
);

private static $many_many = array (
'Column2' => 'Table2'
);

private static $summary_fields = array (
'Column1' => 'Column 1',
'Column2.Column2' => 'Column 2'
);
}

class Table2 extends DataObject {

private static $db = array(
'Column2' => 'Varchar(32)'
);

private static $belongs_many_many = array (
'Column1' => 'Table1'
);
}

Answer

The issue is a $many_many relationship or a $has_many relationship can be linked to multiple objects. We cannot put a $many_many or $has_many into $summary_fields as a single row in the GridField does not know how to display more than one item.

For example, say we have Columns.Title where Columns is a $many_many relationship on the current object. If we have three Columns objects linked to the current object, the system doesn't know to display the Title of the three columns.

What we can do is create a function to return a string displaying the data that we want to display.

class Table1 extends DataObject {

    private static $db = array(
        'Title' => 'Varchar(32)'
    );

    private static $many_many = array(
        'Columns' => 'Table2'
    );

    private static $field_labels = array(
        'ColumnsString' => 'Column'
    );

    private static $summary_fields = array(
        'Title',
        'ColumnsString'
    );

    public function ColumnsString() {
        $returnString = '';
        foreach ($this->Columns() as $column) {
            $returnString .= $column->Title . ' ';
        }
        return $returnString;
    }
}

class Table2 extends DataObject {

    private static $db = array(
        'Title' => 'Varchar(32)'
    );

    private static $belongs_many_many = array(
        'Columns' => 'Table1'
    );
}