Coder Social home page Coder Social logo

unclecheese / silverstripe-display-logic Goto Github PK

View Code? Open in Web Editor NEW
73.0 16.0 70.0 486 KB

The Display Logic module allows you to add conditions for displaying or hiding certain form fields based on client-side behavior.

License: BSD 3-Clause "New" or "Revised" License

PHP 60.53% JavaScript 24.10% Scheme 5.17% Gherkin 9.67% SCSS 0.54%

silverstripe-display-logic's Introduction

Display Logic Module for SilverStripe 4

Description

The Display Logic module allows you to add conditions for displaying or hiding certain form fields based on client-side behavior.

Example usage

<?php
$products->displayIf("HasProducts")->isChecked();

$sizes->hideUnless("ProductType")->isEqualTo("t-shirt")
      ->andIf("Price")->isGreaterThan(10);
      
$payment->hideIf("Price")->isEqualTo(0);

$shipping->displayIf("ProductType")->isEqualTo("furniture")
           ->andIf()
              ->group()
                ->orIf("RushShipping")->isChecked()
                ->orIf("ShippingAddress")->isNotEmpty()
              ->end();

Available comparison functions

- isEqualTo
- isNotEqualTo
- isGreaterThan
- isLessThan
- contains
- startsWith
- endsWith
- isEmpty
- isNotEmpty
- isBetween
- isChecked
- isNotChecked()
- hasCheckedOption
- hasCheckedAtLeast
- hasCheckedLessThan

Available display conditions

- displayIf()
- displayUnless()
- hideIf()
- hideUnless()

Kitchen sink example

<?php
  public function getCMSFields() {
		$fields = parent::getCMSFields();
		$fields->addFieldsToTab("Root.Test", array(
			TextField::create("Name","Name of event"),
			TextField::create("VenueSize","Size of venue"),
			$refreshments = CheckboxField::create("Refreshments","This is a large venue. Are there refreshments?"),							
			$vendors = CheckboxSetField::create("Vendors","Vendors", Member::get()->map()),				
			$tent = TextField::create("TentSize","You're going to need a tent. What size is it?"),

			OptionSetField::create("LinkType", "", array('internal' => 'Link to an internal page', 'external' => 'Link to an external page')),
			$internal = DropdownField::create("InternalLinkID", "Choose a page", SiteTree::get()->map()->toArray())->setEmptyString("-- choose --"),
			$external = TextField::create("ExternalLink", "Link to external page"),
			$label = TextField::create("LinkLabel", "Label for link"),

			$useEmbed = CheckboxField::create("UseEmbedCode","I have embed code"),
			$embed = TextareaField::create("EmbedCode","Enter the embed code.")
			
		));						
		
		$refreshments->displayIf("VenueSize")->isGreaterThan(100);
		$vendors->displayIf("Refreshments")->isChecked();
		$tent->displayIf("Vendors")->hasCheckedAtLeast(3);


		$internal->displayIf("LinkType")->isEqualTo("internal");				
		$external->displayIf("LinkType")->isEqualTo("external");
		$label->displayIf("LinkType")->isEqualTo("internal")->orIf("LinkType")->isEqualTo("external");
		
		$useEmbed->displayIf("LinkType")->isEqualTo("external");
		$embed->displayIf("UseEmbedCode")->isChecked()
					->orIf()
						->group()
							->orIf("ExternalLink")->contains("youtube.com")
							->orIf("ExternalLink")->contains("vimeo.com")
						->end();


		return $fields;
	}

Kitchen sink example, with chaining

<?php

use UncleCheese\DisplayLogic\Forms\Wrapper;
//...
  public function getCMSFields() {
        $f = parent::getCMSFields();
        $f->addFieldsToTab("Root.Test", array(
            TextField::create("Name","Name of event"),
            TextField::create("VenueSize","Size of venue"),
            CheckboxField::create("Refreshments","This is a large venue. Are there refreshments?")
                ->displayIf("VenueSize")->isGreaterThan(100)->end(),
            CheckboxSetField::create("Vendors","Vendors", Member::get()->map())
                ->displayIf("Refreshments")->isChecked()->end(),
            TextField::create("TentSize","You're going to need a tent. What size is it?")
                ->displayIf("Vendors")->hasCheckedAtLeast(3)->end(),
            CheckboxField::create('HasUpload', 'Has an upload'),
            
            Wrapper::create(
            	UploadField::create('FileUpload', 'Upload a file'),
            	LiteralField::create('test', '<strong>Keep the file small!</strong>')
            )->displayIf('HasUpload')->isChecked()->end(),

            OptionSetField::create("LinkType", "", array('internal' => 'Link to an internal page', 'external' => 'Link to an external page')),
            DropdownField::create("InternalLinkID", "Choose a page", SiteTree::get()->map()->toArray())->setEmptyString("-- choose --")
                ->displayIf("LinkType")->isEqualTo("internal")
                ->end(),
            TextField::create("ExternalLink", "Link to external page")
                ->displayIf("LinkType")->isEqualTo("external")
                ->end(),
            Wrapper::create(
            	ReadonlyField::create('URL','Base URL','http://example.com')
            )->displayIf('LinkType')->isEqualTo('internal')->end(),
            TextField::create("LinkLabel", "Label for link")
                ->displayIf("LinkType")->isChecked()->end(),
            CheckboxField::create("UseEmbedCode","I have embed code")
                ->displayIf("LinkType")->isEqualTo("external")              
                ->end(),
            TextareaField::create("EmbedCode","Enter the embed code.")
                ->displayIf("UseEmbedCode")->isChecked()
                    ->orIf()
                        ->group()
                            ->orIf("ExternalLink")->contains("youtube.com")
                            ->orIf("ExternalLink")->contains("vimeo.com")
                        ->end()
        ));                     

		return $f;
	}

Dealing with non-standard form fields

Sometimes you will want to wrap display logic around a form field that does not use the standard FormField template, such as GridField or LiteralField. For these cases, you can wrap the form field in UncleCheese\DisplayLogic\Forms\Wrapper.

$fields->addFieldToTab("Root.Main", Wrapper::create(
		LiteralField::create("foo","<h2>Hello</h2>")
	)
	->displayIf("Title")->isEmpty()->end()
);

What's the difference between displayIf() and hideUnless()?

Not much. hideUnless() will take a CSS class that hides it by default before the script loads, to eliminate any flash of form fields before the script has loaded. In general, use displayIf() when the common case is for the field to be hidden, and hideUnless() when the common case is for the field to be shown. The same logic applies to hideIf() and displayUnless().

silverstripe-display-logic's People

Contributors

chrispenny avatar christopherdarling avatar colintucker avatar firesphere avatar gavro avatar jason-zz avatar leapfrognz avatar mattybalaam avatar michalkleiner avatar nightjar avatar phillprice avatar sageworksstudio avatar sheadawson avatar silbinarywolf avatar tyrannosaurusjames avatar unclecheese avatar undefinedoffset avatar wilr avatar xini avatar zauberfisch avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

silverstripe-display-logic's Issues

Display Logic not work with LiteralField

Like in topic.
Display logic not hide/show etc... with LiteralField

LiteralField::create("ExampleLiteral", "Example text")
->displayIf("OtherField")->isEqualTo('SomeText')
->end(),

Sorry for my bad English

Option for use with dropDownField value?

I'm having trouble figuring out how to use the display logic based on the value of a drop down field. I can make it work with optionSetField, e.g.

OptionSetField::create("BlockType", "Block Type", array("MyBlock" => "My Block")); $myOtherField = TextareaField::create('Text')->hideUnless('BlockType')->isEqualTo('MyBlock');

But this does not work with dropDownField:

DropDownField::create("BlockType", "Block Type", array("MyBlock" => "My Block")); $myOtherField = TextareaField::create('Text')->hideUnless('BlockType')->isEqualTo('MyBlock')

I do have 'BlockType' defined in my $db array:

private static $db = array ( 'BlockType' => 'Varchar(255)' );

Can you advise the correct way of doing this for dropDownFields? Many thanks.

Display event fires on any checkbox.

                CheckboxSetField::create("Fruits", "Fruit list")
                    ->setSource([
                        '1' => 'Apple',
                        '2' => 'Banana',
                        '3' => 'Orange',
                    ]),

                TextareaField::create("CommentAboutFruit", "Enter comment")
                    ->displayIf('Fruits')
                    ->hasCheckedOption(2)
                    ->end(),

CommentAboutFruit is shown on page load.
Ticking the Apple hides the comment box (would expect it to do nothing). Unticking apple displays the comment box. The same can be said for each object in the list. Seems to be firing on all events regardless of what they are.

This is on the SS 3.1.x stable release, using the latest stable display-logic codebase.

Remove custom field templates

Because this module writes its own form field templates, it can break when a theme uses the same template.

Here's how a formfield extension can update attributes:

    public function onBeforeRender() {
        if($masters = $this->DisplayLogicMasters()){
            $this->owner->setAttribute("data-display-logic-masters", $masters);
        }
    }

Edit: Just noticed that this updates the Field, rather than the holder, where it is currently set.

and for the logic itself...I think the criteria could be somehow encoded into JSON, and included via Requirements. This bit requires a bit more effort, although it would mean no more eval, and devs could potentially avoid using jQuery.

Getting display_logic working with other fields

Could include a wrapper form field to wrap fields that aren compatible with DL. Simply extend CompositeField:

<?php
class DisplayLogicWrapper extends CompositeField {
}

and a template:

<$Tag class="field WrapperField $extraClass <% if ColumnCount %>multicolumn<% end_if %>" <% if DisplayLogic %>data-display-logic-masters="$DisplayLogicMasters"<% end_if %>>

    <% if $Tag == 'fieldset' && $Legend %>
        <legend>$Legend</legend>
    <% end_if %>

    <% loop FieldList %>
        <% if ColumnCount %>
            <div class="column-{$ColumnCount} $FirstLast">
                $FieldHolder
            </div>
        <% else %>
            $FieldHolder
        <% end_if %>
    <% end_loop %>

    <% if Description %><span class="description">$Description</span><% end_if %>

    <% if DisplayLogic %>
        <div class="display-logic-eval">$DisplayLogic</div>
    <% end_if %>

</$Tag>

Fairly simple. Just copied code from CompositeField and added your special tags.
Works for me when wrapping a Gridfield anyway.

PHP-Error at /dev/build

Installing display-logic ends up with the PHP-Error:
Warning: Invalid argument supplied for foreach() in /var/www/vhosts/fs-net.de/httpdocs/framework/core/manifest/ConfigManifest.php on line 655

I also deleted manually the silverstripe-cache, but this didn't help.
Running SS 3.1.2

Setup step missing?

The DisplayLogic method that sets up the Requirements and returns the script for the logic criteria doesn't appear to be called anywhere when I'm using this simple implementation:

$field->displayIf("OtherField")->isChecked();

Am I missing something here?

Non compatible with Rhym/silverstripe-color-field

On SS3, v1.5 doesn't seem to be compatible with Rhym/silverstripe-color-field. The Display-Logic wrapper seems to see the field as a set of two identical named fields and stops with an user error.

Need nested conditionals example

Hey Cheese,

Can we please get an example of how we would display a field if either of two sets of conditionals are true?

E.g.

Fields A, B, C, D

Field D should show if
A = 1 AND B = 2
-or-
A = 2 AND C = 2

I thought this should work (and PHP doesn't complain), but the JS only outputs the first part of the conditional (if A = 1 AND B = 2).

->displayIf('ApplicationType')->isEqualTo('Individual')
->andIf("NZResidentIndividual")->isEqualTo("No")
  ->group()->orIf()
    ->group()
      ->andIf("ApplicationType")->isEqualTo("Joint")
      ->andIf("NZResidentJoint")->isEqualTo("No")
->end()

Hides Multiple Column-Dropdown

Hi,

when adding a GridField with mulitpleClass-component assigned the classes-dropdown is hidden...
when I edit a record of the gridfield and come back from object-editing mode,.. it is visible...

any advice?

Doesn't work on framework 3.4.0

Hi @unclecheese ,

When I use the module for cms and framework 3.3.1 it is perfectly fine. However, for version 3.4.0, displayLogic doesn't work with same code.

Just a note. Thanks for the module.

Doesn't work with OptionsetField in ss3.2.1

I see some updates for the OptionsetField about 20 days ago, but in ss3.2.1 (released 2 days ago) it's not working with OptionsetField yet. If I change the field type to dropdown or other it's working.

FieldGroup problems

When display logic is installed, FieldGroup isn't working anymore as it should.

schermafbeelding 2014-01-28 om 09 33 17

As you can see by the template source comments, the template(s) that are being used are coming from displaylogic:
schermafbeelding 2014-01-28 om 09 33 37

Display Logic and CMS doesn't display link options

I have both Display Logic and Bootstrap forms on a website where currently Display Forms has to be on version 1.0.8 for the Display Logic to work with Bootstrap forms but I have noticed that on any version of Display Logic the link options on CMS doesn't show up.

image

displayLogicCriteria returning null so onBeforeRender not including assets

Hi! Love this mod (and all your mods UncleCheese, let me add another thank you to what's hopefully a long list of grateful SS devs). Just did an install via composer of master into a relatively clean 3.1.8 and found displaylogic js and css not being included. Some poking around shows $this->displayLogicCriteria is returning null when checked in onBeforeRender, so the assets are not being added via Requirements::. I'm not sure if I'm doing something wrong, but my code was a pretty bare bones use of $field->displayIf('OtherFieldName')->equalTo('value'). Definitely wasn't a flush issue.

A switch back to tag 1.0.8 and everything was fine. I'd debug further but I'm on a tight deadline today. As always I suppose. If I get the chance later in the week I'll dig around further. Cheers.

Doesn't seem to work with the DatetimeField

I tried using ->displayIf("CheckboxField")->isChecked(); on my Datetime field and it doesn't seem to work. It will hide the field but when I do hit the checkbox it doesn't appear. Here is my code:

public function getCMSFields() { $fields = FieldList::create(TabSet::create('Root')); $defautTokenExpire = $this->addToCurrentDate(array('3')); $fields->addFieldsToTab("Root.Main", array( ReadonlyField::create("OwnerID.Name","Token Owner"), TextField::create("Token","Token"), DropdownField::create('StatusID','Status',ApiAccountStatus::get()->map('ID','Name'),2), CheckboxField::create("Expires","Does this token expire?"), $expiresOnField = DatetimeField::create('ExpiresOn', 'Expires on',$defautTokenExpire), $autoRenewField = CheckboxField::create("AutoRenew","Auto renew?") )); //$expiresOnField->displayIf("Expires")->isChecked(); $expiresOnField->setConfig('datavalueformat', 'yyyy-MM-dd HH:mm:ss'); // global setting $expiresOnField->getDateField()->setConfig('showcalendar', 1); // field-specific setting $expiresOnField->setAttribute('placeholder', 'Click to select a date'); $expiresOnField->setTimeField(TimePickerField::create('ExpiresOn[time]')); $autoRenewField->displayIf("Expires")->isChecked(); return $fields; }

Doesn't react to scripted chzn dropdown reset

DisplayLogic doesn't seem to react to the dependent chosen-select field when the field is reset by script.

Suppose you have eg a TextField which is shown if the previous field (DropdownField) is set to Apple. When you reset the dropdownfield (which uses jquery 'chosen-select' body) using $('select').val('').trigger("liszt:updated"); the displaylogic field doesn't update thus staying visible.

Temporary solution

$('select').val('').trigger("liszt:updated");
$('.display-logic-display').hide(); // Hide the field manually. DisplayLogic can show() it again

Suggested new comparison isNotChecked

I've encountered the need for an "isNotChecked" comparison a couple of times when displaying/hiding a field based on checkbox A being checked AND checkbox B being not checked.

Example:

$field->displayIf('A')->isChecked()->andIf('B')->isNotChecked()->end();

I haven't found a solution to this with the current comparisons. My suggestion is therefor to add an isNotChecked() comparison.

UploadField doesn't work with DataObjects

Not sure if it's supposed to or not, but UploadField doesn't work if using ClassName extends DataObject instead of extends Page.

SS: 3.1.15
DL: dev-master

[User Error] collateDataFields() I noticed that a field called 'SlideImage' appears twice in your form: '(unknown form)'. One is a 'UploadField' and the other is a 'UploadField'

Display logic doesn't seem to work on UploadFields.

$uploadField = UploadField::create('Image', 'Image')
->setAllowedFileCategories('image')
->setAllowedMaxFileNumber(1)
->setFolderName('Uploads/images');

    $uploadField->hideUnless('ImageType')->isEqualTo('Single');
    $fields->push($uploadField);

Errors on multiple checks to a field

I have a front end form that is used to add a job, the job can be contract or perm and i want two rate boxes to appear if contract or salary boxes if perm.
I have a drop down field

         DropdownField::create("JobTypeID","Job Type")
              ->setSource(DataList::create("JobType")->map('ID','Name'))
              ->setEmptyString('(Select one)'),

and then the two fields i'd like hidden until the correct JobType is picked.

  TextField::create("RateFrom","Rate From")
      ->prependText("&pound;")
      ->appendText(".00")
      ->displayIf("JobTypeID")->isEqualTo(2)
      ->end(),

 TextField::create("RateTo","Rate To")
      ->prependText("&pound;")
      ->appendText(".00")
      ->displayIf("JobTypeID")->isEqualTo(2)
      ->end(),

The error i'm getting when i have both is

    $("#JobTypeID").evaluateEqualTo(2) is not a function

If i just put the code on one it works fine.

Is this a bug or am i doing it wrong?

Cheers

Mick

Bug: $script .= "(";

Hi Aaron!

I think this is a bug: (Line 203) $script .= "(";
DisplayLogicCriteria.php

    public function toScript() {
        $script .= "(";
        $first = true;
        foreach($this->getCriteria() as $c) {
            $script .= $first ? "" :  " {$this->getLogicalOperator()} ";
            $script .= $c->toScript();
            $first = false;
        }   
        $script .= ")";
        return $script;
    }

Regards,
Jose A.

Silverstripe 4 support

Some work has been done in this pull request + thread to update to Silverstripe 4, but there were still some issues to resolve and the pull request was eventually closed.

#78

Dynamically setting the "required" flag

Could we have a feature to make fields dynamically required, based on state of other fields?
I would for example want to enable a TextField depending on whether currently selected dropdown item (its label, not value) contains a phrase. When the text field gets enabled, it also has to be filled in, so it should be made "required".

Form templates overwrite those from theme

A bit of an odd one, but because this module loads it's form templates in the root templates directory (instead of templates/forms) if I choose to over right OptionsetField (or even a template of a field that extends OptionsetField) these templates also have to be placed inside the root templates director inside my theme (otherwise Silverstripe ignores my tempaltes and uses the ones from display_logic instead.

I guess this may be an issue in Silverstripe, but shouldn't the form templates in this module be in "templates/forms" rather than just "templates", as this is how they are located in framework?

I am getting this issue in Silverstripe 3.3

Display Logic does not work with Blocks

Hey @unclecheese ,

I am using blocks to manage content and some of the blocks has display logic.

If I edit each block at a time then display logic works but when I want to edit multi block, display logic does not work as expected. Is it a problem regarding version or something that these 2 modules conflict?

Thank you

UploadField now requires a DisplayLogicWrapper?

In 1.0.8 it used to be possible to use display conditions directly on an UploadField. However, this seemed to break completely in 1.1.0, and in the latest master only seems possible when using a DisplayLogicWrapper around the UploadField.

Just wanted to check if this was the desired behaviour? As took me a while to work out why it has stopped working, and would be good to have an UploadField example in the docs. :)

Display Logic with two GridField

I've got a problem with Display Logic module when I use it with two GridField. I want to see the second GridField when the first is not empty, but doesn't work. Is this possible whit Display Logic module? This is the code:

$listToBeSearched = DoMezzo::get();
$autoCompleteField = new GridFieldAddExistingAutocompleter('toolbar-header-right');
$autoCompleteField->setSearchList($listToBeSearched);
$autoCompleteField->setSearchFields(array('Telaio', 'Targa'));
$autoCompleteField->setResultsFormat('$Telaio - $Targa');
$gridFieldConfig = GridFieldConfig::create()->addComponents(
        new GridFieldButtonRow('toolbar-header-right'),
        new GridFieldToolbarHeader(),
        new GridFieldDataColumns(),
        new GridFieldDeleteAction(true),
        new GridFieldDetailForm(),
        $autoCompleteField      
);
$gridFieldConfig->removeComponentsByType('GridFieldAddNewButton');
$gridFieldConfig->addComponent(new GridFieldSortableRows('PosizioneTemplateMezzi'));
$mezzi = $this->SortedMezzi();
$gridfieldMezzi = new GridField('Mezzi', 'Mezzi', $mezzi, $gridFieldConfig);
$fields->addFieldToTab(
        'Root.MezziOperatori',
        DisplayLogicWrapper::create($gridfieldMezzi)
);


$listToBeSearched = DoOperatore::get();
$autoCompleteField = new GridFieldAddExistingAutocompleter('toolbar-header-right');
$autoCompleteField->setSearchList($listToBeSearched);
$autoCompleteField->setSearchFields(array('Cognome', 'Nome'));
$autoCompleteField->setResultsFormat('$Cognome - $Nome');
$gridFieldConfig = GridFieldConfig::create()->addComponents(
        new GridFieldButtonRow('toolbar-header-right'),
        new GridFieldToolbarHeader(),
        new GridFieldDataColumns(),
        new GridFieldDeleteAction(true),
        new GridFieldDetailForm(),
        $autoCompleteField      
);
$gridFieldConfig->removeComponentsByType('GridFieldAddNewButton');
$gridFieldConfig->addComponent(new GridFieldSortableRows('PosizioneTemplateOperatori'));
$operatori = $this->SortedOperatori();
$gridfieldOperatori = new GridField('Operatori', 'Operatori', $operatori, $gridFieldConfig);
$fields->addFieldToTab(
        'Root.MezziOperatori',
        DisplayLogicWrapper::create($gridfieldOperatori)->displayIf('Mezzi')->isNotEmpty()->end()
);

Fatal error: Object::add_extension() - Extension "FormField" is not a subclass of Extension in C:\wamp\www\framework\core\Object.php on line 467

Hi Aaron!

There is a problem with the latest version 3.1 from github:
https://github.com/silverstripe/silverstripe-cms/tree/3.1
https://github.com/silverstripe/sapphire/tree/3.1

http://127.0.0.1/dev/build?flush=all

Fatal error: Object::add_extension() - Extension "FormField" is not a subclass of Extension in C:\wamp\www\framework\core\Object.php on line 467

$('div.display-logic').getFieldName() broken with SilverStripe >=3.2

In SilverStripe it was usual that FormFields had the ID set to the name of the FormField. With SilverStripe 3.2 FormFields now have a 'namespaced' ID.

<div class="field text" id="FirstName"> becomes <div class="field text" id="FormClass_FormName_FirstName_Holder">

but the name of the input remains the same (<input name="FirstName">).
because of this, display_logic is no longer able to find the input.


I have hot-fixed the problem for myself now overwriting getFieldName with this in my projects javascript file:

$('form div.display-logic, form div.display-logic-master').entwine({
    getFieldName: function () {
        return this.attr('id').replace(new RegExp('^' + this.closest('form').attr('id') + '_(.*)_Holder$'), '$1');
    }
});

Doesn't it work with TabSet and HeaderField?

HeaderField ignores it in total, and TabSet only vanishes and never appears again. Also tried both fields with the wrapper, but also doesn't work. Have a regular TextField as a control instance and that works perfectly.

Using SilverStripe v3.2.1 and DisplayLogic v1.3.1. Thanks.

FormField templates in Includes folder

Hi,
unfortunatly it looks like js and css files will never be loaded because function DisplayLogic was never fired, because the right templates were not used or couldnt be found. Moving CheckboxField_holder.ss, CompositeField_holder.ss, FormField_holder.ss one folder up from Includes to the modules template folder fixes this isssue for me.

Running on ss 3.1.1

Friendly regards
bumbus

Gridfield Components?

I've been trying to use this with a grid field, scaffolded by ModelAdmin but then moved to the main tab with...

$grid = $fields->dataFieldByName('RelationShipName')
$fields->removeByName('RelationShipName');
$fields->insertAfter($grid,'Name');

..which works fine.
But then when I'm applying the display condition it isn't working...

$fields->dataFieldByName('RelationShipName')
->displayIf('Type')
->isEqualTo('A');

...I've got this working for other fields that are in the db array and "simple" (like Text, Int).

Is this a known issue - or maybe I'm doing it wrong?

Catchable fatal error: Argument 1 passed to DisplayLogicCriteria::addCriterion() must be an instance of DisplayLogicCriterion, instance of DisplayLogicCriteria given, called in C:\wamp\www\display-logic\code\DisplayLogicCriteria.php on line 190 and define

This code, similar to your example, does not work with the latest version of SilverStripe 3.1 (github):

 $textColor->displayIf("typebackground")->isEqualTo('standard')
        ->orIf()
        ->group()
            ->orIf("typebackground")->isEqualTo('header')
            ->orIf("typebackground")->isEqualTo('imageres')
        ->end();

Catchable fatal error: Argument 1 passed to DisplayLogicCriteria::addCriterion() must be an instance of DisplayLogicCriterion, instance of DisplayLogicCriteria given, called in C:\wamp\www\display-logic\code\DisplayLogicCriteria.php on line 190 and defined in C:\wamp\www\display-logic\code\DisplayLogicCriteria.php on line 147

Thanks,
Regards,
Jose A.

Nothing happens

Followed, even copy-pasted your example. Classes are added but nothing happens

Ss3.1 no js or CSS errors detected

Rename composer vendor prefix

Hello! First of all, thanks for getting on board with Composer with us, and registering your module on Packagist! We rely on early adopters like you to push adoption, and are thrilled to see such an enthusiastic uptake of Composer :)

We've noticed that you're using the "silverstripe" vendor prefix, which should only be used for modules maintained by the SilverStripe Ltd. organization (details). We'd like to ask you to change your vendor prefix accordingly by changing the name key in your composer.json. Usually using your github name is a good idea. The fact that this repo is a SilverStripe module is already contained in the "type": "silverstripe-module" metadata.

In order to ensure existing links to the module continue to work, please add a "replace" key to your composer.json:

"replace": {"<old-name>": "*"}

If you have created branches and releases containing a composer.json file,
it is recommended that you push the change there as well (and create new releases).
Once the name change is committed, force update the module on Packagist.

Thanks
Ingo Schommer, SilverStripe Core Developer

Display logic does not appear to work inside a widget

Tested in SS 3.1Beta

If I include these lines in a widget Display Logic does not appear to work:

        $fields->merge(
            new FieldList(
        CheckboxField::create("ThoughtLinkBoo", _t('ThoughtWidget.ThoughtLinkBoo', "Would you like to define which page is shown and linked to?")),
        $thoughtLink = DropdownField::create("ThoughtLinkID", _t('ThoughtWidget.ThoughtLinkID', "Select a page to to"), SiteTree::get()->map())
            )
        );

        $thoughtLink->displayIf("ThoughtLinkBoo")->isChecked();

But if I make a CheckboxField for ThoughtLinkBoo in the page class the widget is used on, this will then trigger the showing of $thoughtLink

checkboxfield layout wonky

In the CMS above my gridfield, I have a checkboxfield:

Before display-logic installed:
before-display-logic-installed

After display-logic installed:
after-display-logic-installed

Future compatibility

Hey @unclecheese,

Just tried installing SS 3.3 (dev) and noticed this happens:

  - Removing unclecheese/display-logic (1.3.1)
  - Installing unclecheese/display-logic (1.2.1)

Given that future minor releases of SS should be backwards compatible can I suggest that you set a minimum minor version requirement instead of a specific one? ^3.2 means >= 3.2.0 and < 4.0.0, so that could be a good option.

I can see why you might want to restrict people from installing this module with new versions of SilverStripe until you've tested with them, but if it means people can still install the module but are given an older version then it's probably counter-productive :)

Expand display-logic to include these features:

Hi Aaron!

Could you expand display-logic to include these features?

$products->AssignValue("XXXX")->If("Order")->isChanged();
$products->AssignFieldValue("FieldName")->If("FieldName")->isChanged();
$products->AssignExpression('FieldName1+"22"+FieldName2')->If("FieldName")->isChanged();
// Sum of all fields starting with 'FieldName' if any of these fields is modified
$products->AssignSum('FieldName_')->If("FieldName_")->isChanged();
$products->ErrorIf("The product code is greater than 20.")->isGreaterThan(20);

Thanks for this great module.
Regards,
Jose A.

DisplayLogic v1.2.1 seems not to work with UploadField

I have a couple of fields (eg. DropDown, TextField, etc.) and they all work with DisplayLogic, except UploadField. Here ist my code:

UploadField::create('Visual', _t('Dict.VISUAL', 'Visual'))
->displayIf('Type')->isEqualTo('image')->end()
->setFolderName('MainTeasers')

Anything wrong with it? Thanks in advance.

Optionsets no longer work

Looks like something in #54 has broken Optionsets, they can't be a master and can't be used as part of logic. I haven't yet been able to isolate the issue specifically but the simple solution could be to just a modified OptionsetField_Holder.ss to the templates/forms folder that uses HolderID instead of $Name on the outer div.

[User Error] collateDataFields() I noticed that a field called 'B' appears twice.

Hi ya,

Have come across this, its the standard check that SS does on forms looking for fields with the same name. I'm using the display-logic to show different forms depending on what a dropdown value is. All the forms populate mostly the same database fields in the call log which is where the system is now complaining that i have duplicate fields. Anyway round this? Your gonna say no aren't you :o)

Mick.

   DropdownField::create("CardTitle", "Radio Cards", array('Loc' => 'Loc Stat', 
       'Task' => 'Task Rep', 'Cas' => 'Casualty Report'))
        ->setEmptyString('(Select one)')
        ->displayIf("Type")->isEqualTo("Radio Cards")
        ->end(),




     ////////LOC STAT//////////////////////////
    TextField::create('GridRef','A: Grid')
         ->displayIf("CardTitle")->isEqualTo("Loc")
        ->end(),
    TextField::create('B','B: Description')
         ->displayIf("CardTitle")->isEqualTo("Loc")
        ->end(),
    TextField::create('C','C: Direction of Travel')
         ->displayIf("CardTitle")->isEqualTo("Loc")
        ->end(),

////////Task STAT//////////////////////////
    TextField::create('A','A: Area/Route')
         ->displayIf("CardTitle")->isEqualTo("Task")
        ->end(),
    TextField::create('B','B: % Complete')
         ->displayIf("CardTitle")->isEqualTo("Task")
        ->end(),
    TextField::create('C','C: Est. Time to Completion')
         ->displayIf("CardTitle")->isEqualTo("Task")
        ->end(),            

Not working with Bootstrap Front-end forms

I know there are issues posted for this already but I am using silverstripe bootstrap forms and I cannot get display-logic working with them. It will work in the CMS no problem though.

I have included the DisplayLogicWrapper and while it wraps the field correctly and hides it, once I apply logic it doesn't show.

Is there a possible way around this?

Edit: Found out that using Display-Logic 1.0.8 works with Bootstrap forms. Any version higher will not work,

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.