repo
stringlengths
7
63
file_url
stringlengths
81
284
file_path
stringlengths
5
200
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 15:02:33
2026-01-05 05:24:06
truncated
bool
2 classes
crisu83/php-conversion
https://github.com/crisu83/php-conversion/blob/0dff0e374a49070b436188dced52226bbc4cbe3c/src/Crisu83/Conversion/Quantity/Acceleration/Acceleration.php
src/Crisu83/Conversion/Quantity/Acceleration/Acceleration.php
<?php /* * This file is part of Conversion. * * (c) 2013 Christoffer Niska * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Crisu83\Conversion\Quantity\Acceleration; use Crisu83\Conversion\Quantity\Quantity; /** * Class Acceleration * @package Crisu83\Conversion\Quantity\Acceleration */ class Acceleration extends Quantity { /** * @var string native unit name */ protected static $native = Unit::METRE_PER_SECOND_SQUARED; /** * @var array conversion map (unit => native unit) */ protected static $conversionMap = array( Unit::METRE_PER_SECOND_SQUARED => 1, ); }
php
Apache-2.0
0dff0e374a49070b436188dced52226bbc4cbe3c
2026-01-05T05:22:45.144188Z
false
crisu83/php-conversion
https://github.com/crisu83/php-conversion/blob/0dff0e374a49070b436188dced52226bbc4cbe3c/src/Crisu83/Conversion/Quantity/Acceleration/Unit.php
src/Crisu83/Conversion/Quantity/Acceleration/Unit.php
<?php /* * This file is part of Conversion. * * (c) 2013 Christoffer Niska * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Crisu83\Conversion\Quantity\Acceleration; use \Crisu83\Conversion\Quantity\Unit as BaseUnit; /** * Class Unit * @package Crisu83\Conversion\Quantity\Acceleration */ class Unit extends BaseUnit { // todo: add more units const METRE_PER_SECOND_SQUARED = 'm/s^2'; }
php
Apache-2.0
0dff0e374a49070b436188dced52226bbc4cbe3c
2026-01-05T05:22:45.144188Z
false
crisu83/php-conversion
https://github.com/crisu83/php-conversion/blob/0dff0e374a49070b436188dced52226bbc4cbe3c/src/Crisu83/Conversion/Quantity/Voltage/Unit.php
src/Crisu83/Conversion/Quantity/Voltage/Unit.php
<?php /* * This file is part of Conversion. * * (c) 2013 Christoffer Niska * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Crisu83\Conversion\Quantity\Voltage; use \Crisu83\Conversion\Quantity\Unit as BaseUnit; /** * Class Unit * @package Crisu83\Conversion\Quantity\Voltage */ class Unit extends BaseUnit { const VOLT = 'V'; const KILOVOLT = 'KV'; }
php
Apache-2.0
0dff0e374a49070b436188dced52226bbc4cbe3c
2026-01-05T05:22:45.144188Z
false
crisu83/php-conversion
https://github.com/crisu83/php-conversion/blob/0dff0e374a49070b436188dced52226bbc4cbe3c/src/Crisu83/Conversion/Quantity/Voltage/Voltage.php
src/Crisu83/Conversion/Quantity/Voltage/Voltage.php
<?php /* * This file is part of Conversion. * * (c) 2013 Christoffer Niska * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Crisu83\Conversion\Quantity\Voltage; use Crisu83\Conversion\Quantity\Quantity; /** * Class Voltage * @package Crisu83\Conversion\Quantity\Voltage */ class Voltage extends Quantity { /** * @var string native unit name */ protected static $native = Unit::VOLT; /** * @var array conversion map (unit => native unit) */ protected static $conversionMap = array( Unit::VOLT => 1, Unit::KILOVOLT => 1000, ); }
php
Apache-2.0
0dff0e374a49070b436188dced52226bbc4cbe3c
2026-01-05T05:22:45.144188Z
false
crisu83/php-conversion
https://github.com/crisu83/php-conversion/blob/0dff0e374a49070b436188dced52226bbc4cbe3c/src/Crisu83/Conversion/Quantity/Temperature/Unit.php
src/Crisu83/Conversion/Quantity/Temperature/Unit.php
<?php /* * This file is part of Conversion. * * (c) 2013 Christoffer Niska * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Crisu83\Conversion\Quantity\Temperature; use \Crisu83\Conversion\Quantity\Unit as BaseUnit; /** * Class Unit * @package Crisu83\Conversion\Quantity\Temperature */ class Unit extends BaseUnit { const CELSIUS = 'C'; const FAHRENHEIT = 'F'; const KELVIN = 'K'; }
php
Apache-2.0
0dff0e374a49070b436188dced52226bbc4cbe3c
2026-01-05T05:22:45.144188Z
false
crisu83/php-conversion
https://github.com/crisu83/php-conversion/blob/0dff0e374a49070b436188dced52226bbc4cbe3c/src/Crisu83/Conversion/Quantity/Temperature/Temperature.php
src/Crisu83/Conversion/Quantity/Temperature/Temperature.php
<?php /* * This file is part of Conversion. * * (c) 2013 Christoffer Niska * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Crisu83\Conversion\Quantity\Temperature; use Crisu83\Conversion\Quantity\Quantity; /** * Class Temperature * @package Crisu83\Conversion\Quantity\Temperature */ class Temperature extends Quantity { /** * @var string native unit name */ protected static $native = Unit::KELVIN; /** * @var array conversion map (unit => native unit) */ protected static $conversionMap = array( Unit::CELSIUS => 273.15, Unit::FAHRENHEIT => 255.372, Unit::KELVIN => 1, ); }
php
Apache-2.0
0dff0e374a49070b436188dced52226bbc4cbe3c
2026-01-05T05:22:45.144188Z
false
crisu83/php-conversion
https://github.com/crisu83/php-conversion/blob/0dff0e374a49070b436188dced52226bbc4cbe3c/src/Crisu83/Conversion/Quantity/Velocity/Velocity.php
src/Crisu83/Conversion/Quantity/Velocity/Velocity.php
<?php /* * This file is part of Conversion. * * (c) 2013 Christoffer Niska * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Crisu83\Conversion\Quantity\Velocity; use Crisu83\Conversion\Quantity\Quantity; /** * Class Velocity * @package Crisu83\Conversion\Quantity\Velocity */ class Velocity extends Quantity { /** * @var string native unit name */ protected static $native = Unit::METRE_PER_SECOND; /** * @var array conversion map (unit => native unit) */ protected static $conversionMap = array( Unit::METRE_PER_SECOND => 1, ); }
php
Apache-2.0
0dff0e374a49070b436188dced52226bbc4cbe3c
2026-01-05T05:22:45.144188Z
false
crisu83/php-conversion
https://github.com/crisu83/php-conversion/blob/0dff0e374a49070b436188dced52226bbc4cbe3c/src/Crisu83/Conversion/Quantity/Velocity/Unit.php
src/Crisu83/Conversion/Quantity/Velocity/Unit.php
<?php /* * This file is part of Conversion. * * (c) 2013 Christoffer Niska * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Crisu83\Conversion\Quantity\Velocity; use \Crisu83\Conversion\Quantity\Unit as BaseUnit; /** * Class Unit * @package Crisu83\Conversion\Quantity\Velocity */ class Unit extends BaseUnit { const METRE_PER_SECOND = 'm/s'; }
php
Apache-2.0
0dff0e374a49070b436188dced52226bbc4cbe3c
2026-01-05T05:22:45.144188Z
false
crisu83/php-conversion
https://github.com/crisu83/php-conversion/blob/0dff0e374a49070b436188dced52226bbc4cbe3c/src/Crisu83/Conversion/Quantity/Time/Time.php
src/Crisu83/Conversion/Quantity/Time/Time.php
<?php /* * This file is part of Conversion. * * (c) 2013 Christoffer Niska * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Crisu83\Conversion\Quantity\Time; use Crisu83\Conversion\Quantity\Quantity; /** * Class Time * @package Crisu83\Conversion\Quantity\Time */ class Time extends Quantity { /** * @var string native unit name */ protected static $native = Unit::SECOND; /** * @var array conversion map (unit => native unit) */ protected static $conversionMap = array( Unit::NANOSECOND => 1e-9, Unit::MICROSECOND => 1e-6, Unit::MILLISECOND => 0.001, Unit::SECOND => 1, Unit::MINUTE => 60, Unit::HOUR => 3600, Unit::DAY => 86400, Unit::WEEK => 604800, Unit::MONTH => 2.62974e6, Unit::YEAR => 3.15569e7, Unit::DECADE => 3.15569e8, Unit::CENTURY => 3.15569e9, Unit::MILLENIUM => 3.1556926e10 ); }
php
Apache-2.0
0dff0e374a49070b436188dced52226bbc4cbe3c
2026-01-05T05:22:45.144188Z
false
crisu83/php-conversion
https://github.com/crisu83/php-conversion/blob/0dff0e374a49070b436188dced52226bbc4cbe3c/src/Crisu83/Conversion/Quantity/Time/Unit.php
src/Crisu83/Conversion/Quantity/Time/Unit.php
<?php /* * This file is part of Conversion. * * (c) 2013 Christoffer Niska * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Crisu83\Conversion\Quantity\Time; use \Crisu83\Conversion\Quantity\Unit as BaseUnit; /** * Class Unit * @package Crisu83\Conversion\Quantity\Time */ class Unit extends BaseUnit { const NANOSECOND = 'ns'; const MICROSECOND = 'us'; const MILLISECOND = 'ms'; const SECOND = 's'; const MINUTE = 'min'; const HOUR = 'hr'; const DAY = 'd'; const WEEK = 'wk'; const MONTH = 'mo'; const YEAR = 'a'; const DECADE = 'decade'; const CENTURY = 'century'; const MILLENIUM = 'ka'; }
php
Apache-2.0
0dff0e374a49070b436188dced52226bbc4cbe3c
2026-01-05T05:22:45.144188Z
false
crisu83/php-conversion
https://github.com/crisu83/php-conversion/blob/0dff0e374a49070b436188dced52226bbc4cbe3c/src/Crisu83/Conversion/Quantity/ApparentPower/Unit.php
src/Crisu83/Conversion/Quantity/ApparentPower/Unit.php
<?php /* * This file is part of Conversion. * * (c) 2013 Christoffer Niska * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Crisu83\Conversion\Quantity\ApparentPower; use Crisu83\Conversion\Quantity\Unit as BaseUnit; /** * Class Unit * @package Crisu83\Conversion\Quantity\ApparentPower */ class Unit extends BaseUnit { const VOLT_AMPERE = 'VA'; const KILOVOLT_AMPERE = 'kVA'; }
php
Apache-2.0
0dff0e374a49070b436188dced52226bbc4cbe3c
2026-01-05T05:22:45.144188Z
false
crisu83/php-conversion
https://github.com/crisu83/php-conversion/blob/0dff0e374a49070b436188dced52226bbc4cbe3c/src/Crisu83/Conversion/Quantity/ApparentPower/ApparentPower.php
src/Crisu83/Conversion/Quantity/ApparentPower/ApparentPower.php
<?php /* * This file is part of Conversion. * * (c) 2013 Christoffer Niska * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Crisu83\Conversion\Quantity\ApparentPower; use Crisu83\Conversion\Quantity\Quantity; /** * Class ApparentPower * @package Crisu83\Conversion\Quantity\ApparentPower */ class ApparentPower extends Quantity { /** * @var string native unit name */ protected static $native = Unit::VOLT_AMPERE; /** * @var array conversion map (unit => native unit) */ protected static $conversionMap = array( Unit::VOLT_AMPERE => 1, Unit::KILOVOLT_AMPERE => 1000, ); }
php
Apache-2.0
0dff0e374a49070b436188dced52226bbc4cbe3c
2026-01-05T05:22:45.144188Z
false
crisu83/php-conversion
https://github.com/crisu83/php-conversion/blob/0dff0e374a49070b436188dced52226bbc4cbe3c/src/Crisu83/Conversion/Quantity/Frequency/Frequency.php
src/Crisu83/Conversion/Quantity/Frequency/Frequency.php
<?php /* * This file is part of Conversion. * * (c) 2013 Christoffer Niska * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Crisu83\Conversion\Quantity\Frequency; use Crisu83\Conversion\Quantity\Quantity; /** * Class Frequency * @package Crisu83\Conversion\Quantity\Frequency */ class Frequency extends Quantity { /** * @var string native unit name */ protected static $native = Unit::HERTZ; /** * @var array conversion map (unit => native unit) */ protected static $conversionMap = array( Unit::HERTZ => 1, Unit::KILOHERTZ => 1000, Unit::MEGAHERTZ => 1000000, Unit::GIGAHERTZ => 1000000000, Unit::RPS => 1, Unit::RPM => 0.016666667, Unit::RPH => 0.000277778, ); }
php
Apache-2.0
0dff0e374a49070b436188dced52226bbc4cbe3c
2026-01-05T05:22:45.144188Z
false
crisu83/php-conversion
https://github.com/crisu83/php-conversion/blob/0dff0e374a49070b436188dced52226bbc4cbe3c/src/Crisu83/Conversion/Quantity/Frequency/Unit.php
src/Crisu83/Conversion/Quantity/Frequency/Unit.php
<?php /* * This file is part of Conversion. * * (c) 2013 Christoffer Niska * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Crisu83\Conversion\Quantity\Frequency; use \Crisu83\Conversion\Quantity\Unit as BaseUnit; /** * Class Unit * @package Crisu83\Conversion\Quantity\Frequency */ class Unit extends BaseUnit { const HERTZ = 'Hz'; const KILOHERTZ = 'KHz'; const MEGAHERTZ = 'MHz'; const GIGAHERTZ = 'GHz'; const RPS = 'RPS'; // Revolutions per second const RPM = 'RPM'; // Revolutions per minute const RPH = 'RPH'; // Revolutions per hour }
php
Apache-2.0
0dff0e374a49070b436188dced52226bbc4cbe3c
2026-01-05T05:22:45.144188Z
false
crisu83/php-conversion
https://github.com/crisu83/php-conversion/blob/0dff0e374a49070b436188dced52226bbc4cbe3c/src/Crisu83/Conversion/Quantity/Volume/Unit.php
src/Crisu83/Conversion/Quantity/Volume/Unit.php
<?php /* * This file is part of Conversion. * * (c) 2013 Christoffer Niska * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Crisu83\Conversion\Quantity\Volume; use \Crisu83\Conversion\Quantity\Unit as BaseUnit; /** * Class Unit * @package Crisu83\Conversion\Quantity\Volume */ class Unit extends BaseUnit { // Metric system const MILLILITRE = 'mL'; const LITRE = 'L'; const CUBIC_MILLIMETRE = 'mm^3'; const CUBIC_CENTIMETRE = 'cm^3'; const CUBIC_METRE = 'm^3'; // Imperial system const GALLON = 'gal'; const QUART = 'qt'; const PINT = 'pt'; const CUP = 'c'; const OUNCE = 'oz'; const TABLESPOON = 'tbsp'; const TEASPOON = 'tsp'; // US system const US_GALLON = 'us gal'; const US_QUART = 'us qt'; const US_PINT = 'us pt'; const US_CUP = 'us c'; const US_OUNCE = 'us oz'; const US_TABLESPOON = 'us tbsp'; const US_TEASPOON = 'us tsp'; // Other units const CUBIC_INCH = 'in^3'; const CUBIC_FOOT = 'ft^3'; }
php
Apache-2.0
0dff0e374a49070b436188dced52226bbc4cbe3c
2026-01-05T05:22:45.144188Z
false
crisu83/php-conversion
https://github.com/crisu83/php-conversion/blob/0dff0e374a49070b436188dced52226bbc4cbe3c/src/Crisu83/Conversion/Quantity/Volume/Volume.php
src/Crisu83/Conversion/Quantity/Volume/Volume.php
<?php /* * This file is part of Conversion. * * (c) 2013 Christoffer Niska * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Crisu83\Conversion\Quantity\Volume; use Crisu83\Conversion\Quantity\Quantity; /** * Class Volume * * @package Crisu83\Conversion\Quantity\Volume */ class Volume extends Quantity { /** * @var string native unit name */ protected static $native = Unit::CUBIC_METRE; /** * @var array conversion map (unit => native unit) */ protected static $conversionMap = array( Unit::MILLILITRE => 1e-6, Unit::CUBIC_MILLIMETRE => 1e-9, Unit::CUBIC_CENTIMETRE => 1e-6, Unit::LITRE => 0.001, Unit::CUBIC_METRE => 1, Unit::GALLON => 0.00454609, Unit::QUART => 0.00113652, Unit::PINT => 0.000568261, Unit::CUP => 0.000284131, Unit::OUNCE => 2.8413e-5, Unit::TABLESPOON => 1.7758e-5, Unit::TEASPOON => 5.9194e-6, Unit::US_GALLON => 0.00378541, Unit::US_QUART => 0.000946353, Unit::US_PINT => 0.000473176, Unit::US_CUP => 0.000236588, Unit::US_OUNCE => 2.9574e-5, Unit::US_TABLESPOON => 1.4787e-5, Unit::US_TEASPOON => 4.9289e-6, Unit::CUBIC_INCH => 1.6387e-5, Unit::CUBIC_FOOT => 0.0283168, ); }
php
Apache-2.0
0dff0e374a49070b436188dced52226bbc4cbe3c
2026-01-05T05:22:45.144188Z
false
crisu83/php-conversion
https://github.com/crisu83/php-conversion/blob/0dff0e374a49070b436188dced52226bbc4cbe3c/src/Crisu83/Conversion/Quantity/LuminousIntensity/Unit.php
src/Crisu83/Conversion/Quantity/LuminousIntensity/Unit.php
<?php /* * This file is part of Conversion. * * (c) 2013 Christoffer Niska * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Crisu83\Conversion\Quantity\LuminousIntensity; use \Crisu83\Conversion\Quantity\Unit as BaseUnit; /** * Class Unit * @package Crisu83\Conversion\Quantity\LuminousIntensity */ class Unit extends BaseUnit { // todo: add more units const CANDELA = 'cd'; }
php
Apache-2.0
0dff0e374a49070b436188dced52226bbc4cbe3c
2026-01-05T05:22:45.144188Z
false
crisu83/php-conversion
https://github.com/crisu83/php-conversion/blob/0dff0e374a49070b436188dced52226bbc4cbe3c/src/Crisu83/Conversion/Quantity/LuminousIntensity/LuminousIntensity.php
src/Crisu83/Conversion/Quantity/LuminousIntensity/LuminousIntensity.php
<?php /* * This file is part of Conversion. * * (c) 2013 Christoffer Niska * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Crisu83\Conversion\Quantity\LuminousIntensity; use Crisu83\Conversion\Quantity\Quantity; /** * Class LuminousIntensity * @package Crisu83\Conversion\Quantity\LuminousIntensity */ class LuminousIntensity extends Quantity { /** * @var string native unit name */ protected static $native = Unit::CANDELA; /** * @var array conversion map (unit => native unit) */ protected static $conversionMap = array( Unit::CANDELA => 1, ); }
php
Apache-2.0
0dff0e374a49070b436188dced52226bbc4cbe3c
2026-01-05T05:22:45.144188Z
false
crisu83/php-conversion
https://github.com/crisu83/php-conversion/blob/0dff0e374a49070b436188dced52226bbc4cbe3c/src/Crisu83/Conversion/Quantity/Area/Unit.php
src/Crisu83/Conversion/Quantity/Area/Unit.php
<?php /* * This file is part of Conversion. * * (c) 2013 Christoffer Niska * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Crisu83\Conversion\Quantity\Area; use \Crisu83\Conversion\Quantity\Unit as BaseUnit; /** * Class Unit * @package Crisu83\Conversion\Quantity\Area */ class Unit extends BaseUnit { // Metric system const SQUARE_METRE = 'm^2'; const HECTARE = 'ha'; const SQUARE_KILOMETRE = 'km^2'; // Imperial system const SQUARE_INCH = 'in^2'; const SQUARE_FEET = 'ft^2'; const SQUARE_YARD = 'yd^2'; const ACRE = 'ac'; const SQUARE_MILE = 'mi^2'; }
php
Apache-2.0
0dff0e374a49070b436188dced52226bbc4cbe3c
2026-01-05T05:22:45.144188Z
false
crisu83/php-conversion
https://github.com/crisu83/php-conversion/blob/0dff0e374a49070b436188dced52226bbc4cbe3c/src/Crisu83/Conversion/Quantity/Area/Area.php
src/Crisu83/Conversion/Quantity/Area/Area.php
<?php /* * This file is part of Conversion. * * (c) 2013 Christoffer Niska * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Crisu83\Conversion\Quantity\Area; use Crisu83\Conversion\Quantity\Quantity; /** * Class Area * @package Crisu83\Conversion\Quantity\Area */ class Area extends Quantity { /** * @var string native unit name */ protected static $native = Unit::SQUARE_METRE; /** * @var array conversion map (unit => native unit) */ protected static $conversionMap = array( Unit::SQUARE_METRE => 1, Unit::HECTARE => 10000, Unit::SQUARE_KILOMETRE => 1000000, Unit::SQUARE_INCH => 0.00064516, Unit::SQUARE_FEET => 0.09290304, Unit::SQUARE_YARD => 0.83612736, Unit::ACRE => 4046.8564224, Unit::SQUARE_MILE => 2589988.110336, ); }
php
Apache-2.0
0dff0e374a49070b436188dced52226bbc4cbe3c
2026-01-05T05:22:45.144188Z
false
crisu83/php-conversion
https://github.com/crisu83/php-conversion/blob/0dff0e374a49070b436188dced52226bbc4cbe3c/src/Crisu83/Conversion/Quantity/FuelConsumption/Unit.php
src/Crisu83/Conversion/Quantity/FuelConsumption/Unit.php
<?php /* * This file is part of Conversion. * * (c) 2013 Christoffer Niska * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Crisu83\Conversion\Quantity\FuelConsumption; use \Crisu83\Conversion\Quantity\Unit as BaseUnit; /** * Class Unit * @package Crisu83\Conversion\Quantity\FuelConsumption */ class Unit extends BaseUnit { // Metric units const KILOMETRES_PER_LITRE = 'km/L'; const LITRE_PER_100_KILOMETRES = 'L/100 km'; // Imperial units const MILES_PER_GALLON = 'mpg'; // US units const US_MILES_PER_GALLON = 'us mpg'; }
php
Apache-2.0
0dff0e374a49070b436188dced52226bbc4cbe3c
2026-01-05T05:22:45.144188Z
false
crisu83/php-conversion
https://github.com/crisu83/php-conversion/blob/0dff0e374a49070b436188dced52226bbc4cbe3c/src/Crisu83/Conversion/Quantity/FuelConsumption/FuelConsumption.php
src/Crisu83/Conversion/Quantity/FuelConsumption/FuelConsumption.php
<?php /* * This file is part of Conversion. * * (c) 2013 Christoffer Niska * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Crisu83\Conversion\Quantity\FuelConsumption; use Crisu83\Conversion\Quantity\Quantity; /** * Class FuelConsumption * @package Crisu83\Conversion\Quantity\FuelConsumption */ class FuelConsumption extends Quantity { /** * @var string native unit name */ protected static $native = Unit::KILOMETRES_PER_LITRE; /** * @var array conversion map (unit => native unit) */ protected static $conversionMap = array( Unit::KILOMETRES_PER_LITRE => 1, Unit::LITRE_PER_100_KILOMETRES => 100, Unit::MILES_PER_GALLON => 0.354006, Unit::US_MILES_PER_GALLON => 0.425144, ); }
php
Apache-2.0
0dff0e374a49070b436188dced52226bbc4cbe3c
2026-01-05T05:22:45.144188Z
false
crisu83/php-conversion
https://github.com/crisu83/php-conversion/blob/0dff0e374a49070b436188dced52226bbc4cbe3c/src/Crisu83/Conversion/Quantity/Speed/Unit.php
src/Crisu83/Conversion/Quantity/Speed/Unit.php
<?php /* * This file is part of Conversion. * * (c) 2013 Christoffer Niska * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Crisu83\Conversion\Quantity\Speed; use \Crisu83\Conversion\Quantity\Unit as BaseUnit; /** * Class Unit * @package Crisu83\Conversion\Quantity\Speed */ class Unit extends BaseUnit { // Metric units const METRE_PER_SECOND = 'm/s'; const KILOMETRES_PER_HOUR = 'km/h'; // Imperial units const FEET_PER_SECOND = 'ft/s'; const MILES_PER_HOUR = 'mph'; // Other units const KNOT = 'kn'; }
php
Apache-2.0
0dff0e374a49070b436188dced52226bbc4cbe3c
2026-01-05T05:22:45.144188Z
false
crisu83/php-conversion
https://github.com/crisu83/php-conversion/blob/0dff0e374a49070b436188dced52226bbc4cbe3c/src/Crisu83/Conversion/Quantity/Speed/Speed.php
src/Crisu83/Conversion/Quantity/Speed/Speed.php
<?php /* * This file is part of Conversion. * * (c) 2013 Christoffer Niska * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Crisu83\Conversion\Quantity\Speed; use Crisu83\Conversion\Quantity\Quantity; /** * Class Speed * @package Crisu83\Conversion\Quantity\Speed */ class Speed extends Quantity { /** * @var string native unit name */ protected static $native = Unit::METRE_PER_SECOND; /** * @var array conversion map (unit => native unit) */ protected static $conversionMap = array( Unit::METRE_PER_SECOND => 1, Unit::KILOMETRES_PER_HOUR => 0.277778, Unit::FEET_PER_SECOND => 0.3048, Unit::MILES_PER_HOUR => 0.44704, Unit::KNOT => 0.514444, ); }
php
Apache-2.0
0dff0e374a49070b436188dced52226bbc4cbe3c
2026-01-05T05:22:45.144188Z
false
crisu83/php-conversion
https://github.com/crisu83/php-conversion/blob/0dff0e374a49070b436188dced52226bbc4cbe3c/src/Crisu83/Conversion/Quantity/DigitalInformation/DigitalInformation.php
src/Crisu83/Conversion/Quantity/DigitalInformation/DigitalInformation.php
<?php /* * This file is part of Conversion. * * (c) 2013 Christoffer Niska * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Crisu83\Conversion\Quantity\DigitalInformation; use Crisu83\Conversion\Quantity\Quantity; /** * Class DigitalInformation * @package Crisu83\Conversion\Quantity\DigitalInformation */ class DigitalInformation extends Quantity { /** * @var string native unit name */ protected static $native = Unit::KILOBYTE; /** * @var array conversion map (unit => native unit) */ protected static $conversionMap = array( Unit::BIT => 0.00012207, Unit::BYTE => 0.000976563, Unit::KILOBIT => 0.125, Unit::KILOBYTE => 1, Unit::MEGABIT => 128, Unit::MEGABYTE => 1024, Unit::GIGABIT => 131072, Unit::GIGABYTE => 1.049e+6, Unit::TERABIT => 1.342e+8, Unit::TERABYTE => 1.074e+9, Unit::PETABIT => 1.374e+11, Unit::PETABYTE => 1.1e+12, Unit::EXABIT => '1152921504606846976', Unit::EXABYTE => '9223372036854775808', Unit::ZETTABIT => '1180591620717411303424', Unit::ZETTABYTE => '9444732965739290427392', Unit::YOTTABIT => '1208925819614629174706176', Unit::YOTTABYTE => '9671406556917033397649408', ); }
php
Apache-2.0
0dff0e374a49070b436188dced52226bbc4cbe3c
2026-01-05T05:22:45.144188Z
false
crisu83/php-conversion
https://github.com/crisu83/php-conversion/blob/0dff0e374a49070b436188dced52226bbc4cbe3c/src/Crisu83/Conversion/Quantity/DigitalInformation/Unit.php
src/Crisu83/Conversion/Quantity/DigitalInformation/Unit.php
<?php /* * This file is part of Conversion. * * (c) 2013 Christoffer Niska * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Crisu83\Conversion\Quantity\DigitalInformation; use \Crisu83\Conversion\Quantity\Unit as BaseUnit; /** * Class Unit * @package Crisu83\Conversion\Quantity\DigitalInformation */ class Unit extends BaseUnit { const BIT = 'b'; const BYTE = 'B'; const KILOBIT = 'kb'; const KILOBYTE = 'kB'; const MEGABIT = 'Mb'; const MEGABYTE = 'MB'; const GIGABIT = 'Gb'; const GIGABYTE = 'GB'; const TERABIT = 'Tb'; const TERABYTE = 'TB'; const PETABIT = 'Pb'; const PETABYTE = 'PB'; const EXABIT = 'Eb'; const EXABYTE = 'EB'; const ZETTABIT = 'Zb'; const ZETTABYTE = 'ZB'; const YOTTABIT = 'Yb'; const YOTTABYTE = 'YB'; }
php
Apache-2.0
0dff0e374a49070b436188dced52226bbc4cbe3c
2026-01-05T05:22:45.144188Z
false
crisu83/php-conversion
https://github.com/crisu83/php-conversion/blob/0dff0e374a49070b436188dced52226bbc4cbe3c/tests/_bootstrap.php
tests/_bootstrap.php
<?php require(dirname(__DIR__) . '/vendor/autoload.php');
php
Apache-2.0
0dff0e374a49070b436188dced52226bbc4cbe3c
2026-01-05T05:22:45.144188Z
false
crisu83/php-conversion
https://github.com/crisu83/php-conversion/blob/0dff0e374a49070b436188dced52226bbc4cbe3c/tests/_helpers/CodeHelper.php
tests/_helpers/CodeHelper.php
<?php namespace Codeception\Module; // here you can define custom functions for CodeGuy class CodeHelper extends \Codeception\Module { }
php
Apache-2.0
0dff0e374a49070b436188dced52226bbc4cbe3c
2026-01-05T05:22:45.144188Z
false
crisu83/php-conversion
https://github.com/crisu83/php-conversion/blob/0dff0e374a49070b436188dced52226bbc4cbe3c/tests/unit/LengthTest.php
tests/unit/LengthTest.php
<?php use Codeception\Util\Stub; use Crisu83\Conversion\Quantity\Length\Length; class LengthTest extends \Codeception\TestCase\Test { /** * @var \CodeGuy */ protected $codeGuy; public function testAdd() { $length = new Length(1, 'm'); $this->assertEquals('1.00 m', $length->out()); $this->assertEquals('2.00 m', $length->add(1)->out()); $this->assertEquals('2.30 m', $length->add(1, 'ft')->out()); } public function testSub() { $length = new Length(5, 'ft'); $this->assertEquals('5.00 ft', $length->out()); $this->assertEquals('4.00 ft', $length->sub(1)->out()); $this->assertEquals('0.72 ft', $length->sub(1, 'm')->out()); } public function testTo() { $length = new Length(100, 'm'); $this->assertEquals('100,000.00 mm', $length->to('mm')->out()); $this->assertEquals('10,000.00 cm', $length->to('cm')->out()); $this->assertEquals('0.10 km', $length->to('km')->out()); $this->assertEquals('3,937.01 in', $length->to('in')->out()); $this->assertEquals('328.08 ft', $length->to('ft')->out()); $this->assertEquals('109.36 yd', $length->to('yd')->out()); $this->assertEquals('0.06 mi', $length->to('mi')->out()); $this->assertEquals('0.05 nmi', $length->to('nmi')->out()); } public function testFormat() { $length = new Length(1234.56789, 'm'); $this->assertEquals('1,234.57', $length->format()); $this->assertEquals('1.234,568', $length->format(3, ',', '.')); $this->assertEquals('1234.6', $length->format(1, '.', '')); } public function testUnknownRate() { $this->setExpectedException('Exception'); $length = new Length(1, 'foo'); $this->assertEquals(1, $length->to('bar')); } public function testGetUnit() { $length = new Length(1234.56789, 'm'); $this->assertEquals('m', $length->getUnit()); } public function testToString() { $length = new Length(1234.56789, 'm'); $this->assertEquals('1,234.57 m', $length->__toString()); } }
php
Apache-2.0
0dff0e374a49070b436188dced52226bbc4cbe3c
2026-01-05T05:22:45.144188Z
false
crisu83/php-conversion
https://github.com/crisu83/php-conversion/blob/0dff0e374a49070b436188dced52226bbc4cbe3c/tests/unit/CurrencyTest.php
tests/unit/CurrencyTest.php
<?php use Crisu83\Conversion\Currency\Currency; use Crisu83\Conversion\Currency\CurrencyData; class CurrencyTest extends \Codeception\TestCase\Test { /** * @return CurrencyData */ private function getCurrencyData() { $currencyData = new CurrencyData(); $currencyData->addCurrency('USD', 1); $currencyData->addCurrency('CAD', 5); $currencyData->addCurrency('DKK', 7.5); $currencyData->addCurrency('SEK', 9.1489); $currencyData->addCurrency('AUD', 1.4175); $currencyData->setNative('EUR'); return $currencyData; } public function testCurrencyCanConvertCurrency() { $currency = new Currency(1, 'EUR', $this->getCurrencyData()); $this->assertEquals('1.00', $currency->to('USD')->format()); } public function testCurrencyCanConvertToEuro() { $currency = new Currency(100, 'CAD', $this->getCurrencyData()); $this->assertEquals('500.00', $currency->to('EUR')->format()); } public function testCurrencyCanConvertToDkk() { $currency = new Currency(100, 'DKK', $this->getCurrencyData()); $this->assertEquals('750.00', $currency->to('EUR')->format()); } public function testCurrencyCanConvertToSek() { $currency = new Currency(100, 'EUR', $this->getCurrencyData()); $this->assertEquals('10.93', $currency->to('SEK')->format()); } public function testCurrencyCanConvertFromUsdToCad() { $currency = new Currency(1, 'USD', $this->getCurrencyData()); $this->assertEquals('0.20', $currency->to('CAD')->format()); } public function testCurrencyCanAddAndSubSameCurrency() { $currency = new Currency(1, 'EUR', $this->getCurrencyData()); $currency->add(5); // 6 eur $currency->sub(2); // 4 eur $this->assertEquals('4.00', $currency->to('EUR')->format()); } public function testCurrencyCanAddAndSubDifferentCurriencies() { $currency = new Currency(1, 'USD', $this->getCurrencyData()); $currency->add(1, 'DKK'); $this->assertEquals('8.50 EUR', $currency->to('EUR')->__toString()); $this->assertEquals('8.50 EUR', $currency->toNativeUnit()); } public function testCurrencyCanAddAndSubDifferentCurriencies_2() { $currency = new Currency(100, 'EUR', $this->getCurrencyData()); $currency->add(1, 'SEK'); $currency->sub(10, 'DKK'); $currency->sub(11.25, 'AUD'); $this->assertEquals('12.84', $currency->to('AUD')->format()); $this->assertEquals('AUD', $currency->getUnit()); } public function testCurrencyUnknownCurrency() { $this->setExpectedException('Exception'); $currency = new Currency(100, 'EUR', $this->getCurrencyData()); $this->assertEquals(125.00, $currency->to('FOO')->getUnit()); } }
php
Apache-2.0
0dff0e374a49070b436188dced52226bbc4cbe3c
2026-01-05T05:22:45.144188Z
false
crisu83/php-conversion
https://github.com/crisu83/php-conversion/blob/0dff0e374a49070b436188dced52226bbc4cbe3c/tests/unit/NumberBaseTest.php
tests/unit/NumberBaseTest.php
<?php use Crisu83\Conversion\NumberBase\NumberBase; class NumberBaseTest extends \Codeception\TestCase\Test { public function testNumberParsing() { $number = new NumberBase("0xff", NumberBase::HEXADECIMAL); $this->assertEquals('0xff', $number->__toString()); $number = new NumberBase("b1001", NumberBase::BINARY); $this->assertEquals('b1001', $number->__toString()); $number = new NumberBase(16, NumberBase::DECIMAL); $this->assertEquals(16, $number->__toString()); } public function testNumberFormatDetection() { $number = new NumberBase("0xff"); $this->assertEquals(NumberBase::HEXADECIMAL, $number->getUnit()); $number = new NumberBase("b1010"); $this->assertEquals(NumberBase::BINARY, $number->getUnit()); $number = new NumberBase("o7"); $this->assertEquals(NumberBase::OCTAL, $number->getUnit()); $number = new NumberBase("77"); $this->assertEquals(NumberBase::DECIMAL, $number->getUnit()); } public function testNumberBaseConvertDecimalToHex() { $numberBase = new NumberBase(16, NumberBase::DECIMAL); $this->assertEquals('0x10', $numberBase->to(NumberBase::HEXADECIMAL)->format()); } public function testNumberBaseConvertDecimalToBinary() { $numberBase = new NumberBase(15, NumberBase::DECIMAL); $this->assertEquals('b1111', $numberBase->to(NumberBase::BINARY)->format()); } public function testNumberBaseConvertDecimalToOctal() { $numberBase = new NumberBase(15, NumberBase::DECIMAL); $this->assertEquals('o17', $numberBase->to(NumberBase::OCTAL)->format()); } public function testNumberBaseConvertHexToDecimal() { $numberBase = new NumberBase("0x10", NumberBase::HEXADECIMAL); $this->assertEquals('16', $numberBase->to(NumberBase::DECIMAL)->format()); } public function testNumberBaseConvertHexToBinary() { $numberBase = new NumberBase("0x10", NumberBase::HEXADECIMAL); $this->assertEquals('b10000', $numberBase->to(NumberBase::BINARY)->format()); } public function testNumberBaseConvertHexToOctal() { $numberBase = new NumberBase("0x10", NumberBase::HEXADECIMAL); $this->assertEquals('o20', $numberBase->to(NumberBase::OCTAL)->format()); } }
php
Apache-2.0
0dff0e374a49070b436188dced52226bbc4cbe3c
2026-01-05T05:22:45.144188Z
false
crisu83/php-conversion
https://github.com/crisu83/php-conversion/blob/0dff0e374a49070b436188dced52226bbc4cbe3c/tests/unit/SizeTest.php
tests/unit/SizeTest.php
<?php use Crisu83\Conversion\Size\HatSize\HatSize; use Crisu83\Conversion\Size\HatSize\System as HatsizeSystem; class SizeTest extends \Codeception\TestCase\Test { /** * @var \CodeGuy */ protected $codeGuy; public function testHatsizes() { $hatSize = new HatSize(40, HatsizeSystem::CENTIMETRE); $this->assertEquals('4', $hatSize->to(HatsizeSystem::AMERICAN)->format()); $this->assertEquals('4 7/8', $hatSize->to(HatsizeSystem::BRITISH)->format()); $this->assertEquals('15.748', $hatSize->to(HatsizeSystem::INCH)->format()); } public function testHatsizeUnknown() { $this->setExpectedException('Exception'); $hatSize = new HatSize(40, 'foo'); $this->assertEquals('4 US', $hatSize->to('bar')->format()); } public function testHatsizesToString() { $hatSize = new HatSize(40, HatsizeSystem::CENTIMETRE); $this->assertEquals( sprintf('%s %s', $hatSize->to(HatsizeSystem::AMERICAN)->format(), $hatSize->getSystem()), $hatSize->to(HatsizeSystem::AMERICAN)->__toString() ); } }
php
Apache-2.0
0dff0e374a49070b436188dced52226bbc4cbe3c
2026-01-05T05:22:45.144188Z
false
crisu83/php-conversion
https://github.com/crisu83/php-conversion/blob/0dff0e374a49070b436188dced52226bbc4cbe3c/tests/unit/_bootstrap.php
tests/unit/_bootstrap.php
<?php // Here you can initialize variables that will for your tests
php
Apache-2.0
0dff0e374a49070b436188dced52226bbc4cbe3c
2026-01-05T05:22:45.144188Z
false
crisu83/php-conversion
https://github.com/crisu83/php-conversion/blob/0dff0e374a49070b436188dced52226bbc4cbe3c/tests/unit/CodeGuy.php
tests/unit/CodeGuy.php
<?php //[STAMP] cdc51f4755cb5eca31196f8801ce85fe // This class was automatically generated by build task // You should not change it manually as it will be overwritten on next build // @codingStandardsIgnoreFile use Codeception\Module\CodeHelper; /** * Inherited Methods * @method void wantToTest($text) * @method void wantTo($text) * @method void execute($callable) * @method void expectTo($prediction) * @method void expect($prediction) * @method void amGoingTo($argumentation) * @method void am($role) * @method void lookForwardTo($achieveValue) * @method void comment($description) * @method void haveFriend($name, $actorClass = null) * * @SuppressWarnings(PHPMD) */ class CodeGuy extends \Codeception\Actor { }
php
Apache-2.0
0dff0e374a49070b436188dced52226bbc4cbe3c
2026-01-05T05:22:45.144188Z
false
crisu83/php-conversion
https://github.com/crisu83/php-conversion/blob/0dff0e374a49070b436188dced52226bbc4cbe3c/tests/unit/DigitalInformationTest.php
tests/unit/DigitalInformationTest.php
<?php use Crisu83\Conversion\Quantity\DigitalInformation\DigitalInformation; use Crisu83\Conversion\Quantity\DigitalInformation\Unit; class DigitalInformationTest extends \Codeception\TestCase\Test { public function testSimple() { $di = new DigitalInformation(1024, Unit::BYTE); $this->assertEquals('1,024.00 B', $di->out()); $this->assertEquals('1.00 kB', $di->to(Unit::KILOBYTE)->out()); $di = new DigitalInformation(1, 'ZB'); $this->assertEquals('1.00 ZB', $di->out()); $this->assertEquals('1,024.00 EB', $di->to(Unit::EXABYTE)->out()); } }
php
Apache-2.0
0dff0e374a49070b436188dced52226bbc4cbe3c
2026-01-05T05:22:45.144188Z
false
crisu83/php-conversion
https://github.com/crisu83/php-conversion/blob/0dff0e374a49070b436188dced52226bbc4cbe3c/example/index.php
example/index.php
<?php ini_set('display_errors', 1); error_reporting(E_ALL ^ E_NOTICE); use Crisu83\Conversion\Quantity\DigitalInformation\DigitalInformation; use Crisu83\Conversion\Quantity\Length\Length; use Crisu83\Conversion\NumberBase\NumberBase; use Crisu83\Conversion\Size\HatSize\HatSize; use Crisu83\Conversion\Size\ShoeSize\ChildShoeSize; use Crisu83\Conversion\Quantity\Length\Unit as LengthUnit; use Crisu83\Conversion\Quantity\DigitalInformation\Unit as DIUnit; use Crisu83\Conversion\Size\HatSize\System as HatSizeSystem; use Crisu83\Conversion\Size\ShoeSize\System as ShoeSizeSystem; require(dirname(__DIR__) . '/vendor/autoload.php'); $length = new Length(1, LengthUnit::METRE); echo $length . '<br>'; echo $length->add(1, LengthUnit::FOOT) . '<br>'; echo $length->add(5)->sub(2, LengthUnit::FOOT) . '<br>'; echo $length->to(LengthUnit::YARD) . '<br>'; echo '<br>'; $di = new DigitalInformation(1000, DIUnit::MEGABYTE); echo $di . '<br>'; echo $di->to(DIUnit::BIT)->out(2, '.', '') . '<br>'; echo $di->to(DIUnit::GIGABIT) . '<br>'; echo $di->to(DIUnit::TERABYTE)->out(10) . '<br>'; echo '<br>'; $number = new NumberBase("0xff", NumberBase::HEXADECIMAL); echo $number .'<br>'; echo $number->to(NumberBase::DECIMAL).'<br>'; echo $number->to(NumberBase::OCTAL).'<br>'; echo $number->to(NumberBase::BINARY).'<br>'; $hatSize = new HatSize(40, HatSizeSystem::CENTIMETRE); echo $hatSize . '<br>'; echo $hatSize->to(HatSizeSystem::AMERICAN) . '<br>'; echo $hatSize->to(HatSizeSystem::BRITISH) . '<br>'; echo $hatSize->to(HatSizeSystem::INCH) . '<br>'; echo '<br>'; $shoeSize = new ChildShoeSize(20, ShoeSizeSystem::EUROPEAN); echo $shoeSize . '<br>'; echo $shoeSize->to(ShoeSizeSystem::AMERICAN) . '<br>'; echo $shoeSize->to(ShoeSizeSystem::BRITISH) . '<br>'; echo $shoeSize->to(ShoeSizeSystem::INCH) . '<br>';
php
Apache-2.0
0dff0e374a49070b436188dced52226bbc4cbe3c
2026-01-05T05:22:45.144188Z
false
silverstripe/silverstripe-userforms
https://github.com/silverstripe/silverstripe-userforms/blob/e33fff165d33a077ec4b20c2eef2ef8bca25d15a/tests/Model/Recipient/UserFormRecipientItemRequestTest.php
tests/Model/Recipient/UserFormRecipientItemRequestTest.php
<?php namespace SilverStripe\UserForms\Tests\Model\Recipient; use SilverStripe\Dev\SapphireTest; use SilverStripe\ORM\PolymorphicHasManyList; use SilverStripe\UserForms\Model\Recipient\EmailRecipient; use SilverStripe\UserForms\Model\Recipient\UserFormRecipientItemRequest; use SilverStripe\UserForms\Model\UserDefinedForm; class UserFormRecipientItemRequestTest extends SapphireTest { public function testShowInReportsAffectsPreview() { // classes where showInReports() returns false $namespace = 'SilverStripe\UserForms\Model\EditableFormField'; $falseClasses = ['EditableFieldGroup', 'EditableFieldGroupEnd', 'EditableFormStep']; // some classes where showInReports() returns true (inherits from EditableFormField) $trueClasses = ['EditableTextField', 'EditableEmailField', 'EditableDateField']; $form = new UserDefinedForm(); $form->write(); /** @var PolymorphicHasManyList $fields */ $fields = $form->Fields(); foreach (array_merge($falseClasses, $trueClasses) as $class) { $fqcn = "$namespace\\$class"; $obj = new $fqcn(); $obj->Name = 'My' . $class; $obj->write(); $fields->add($obj); } $recipient = new EmailRecipient(); $recipient->EmailAddress = 'to@example.com'; $recipient->EmailFrom = 'from@example.com'; $recipient->EmailTemplate = 'email/SubmittedFormEmail'; $recipient->Form = $form; $recipient->write(); $recipient->setComponent('Form', $form); $request = new UserFormRecipientItemRequest(null, null, $recipient, null, ''); $html = $request->preview()->getValue(); foreach ($falseClasses as $class) { $this->assertStringNotContainsString('My' . $class, $html); } foreach ($trueClasses as $class) { $this->assertStringContainsString('My' . $class, $html); } } }
php
BSD-3-Clause
e33fff165d33a077ec4b20c2eef2ef8bca25d15a
2026-01-05T05:22:58.009669Z
false
silverstripe/silverstripe-userforms
https://github.com/silverstripe/silverstripe-userforms/blob/e33fff165d33a077ec4b20c2eef2ef8bca25d15a/tests/Extension/UserFormBlockStub.php
tests/Extension/UserFormBlockStub.php
<?php namespace SilverStripe\UserForms\Tests\Extension; use SilverStripe\Dev\TestOnly; use SilverStripe\ORM\DataObject; use SilverStripe\UserForms\UserForm; /** * A stand in for e.g. dnadesigned/silverstripe-elemental-userforms */ class UserFormBlockStub extends DataObject implements TestOnly { use UserForm; }
php
BSD-3-Clause
e33fff165d33a077ec4b20c2eef2ef8bca25d15a
2026-01-05T05:22:58.009669Z
false
silverstripe/silverstripe-userforms
https://github.com/silverstripe/silverstripe-userforms/blob/e33fff165d33a077ec4b20c2eef2ef8bca25d15a/tests/Extension/UserFormFieldEditorExtensionTest.php
tests/Extension/UserFormFieldEditorExtensionTest.php
<?php namespace SilverStripe\UserForms\Tests\Extension; use SilverStripe\Dev\SapphireTest; use SilverStripe\UserForms\Model\EditableFormField\EditableEmailField; use SilverStripe\UserForms\Model\UserDefinedForm; use SilverStripe\Versioned\Versioned; class UserFormFieldEditorExtensionTest extends SapphireTest { protected static $fixture_file = 'UserFormFieldEditorExtensionTest.yml'; protected static $extra_dataobjects = [ UserFormBlockStub::class, ]; protected function setUp(): void { parent::setUp(); $page = $this->objFromFixture(UserDefinedForm::class, 'page'); $block = $this->objFromFixture(UserFormBlockStub::class, 'block'); $page->publishRecursive(); $block->publishRecursive(); } public function testOrphanRemovalDoesNotAffectOtherClassesWithTheSameID() { $page = $this->objFromFixture(UserDefinedForm::class, 'page'); $block = $this->objFromFixture(UserFormBlockStub::class, 'block'); // assert setup $this->assertSame($page->ID, $block->ID); $this->assertCount(2, $page->Fields(), 'Draft UserForm page starts with 2 fields'); $this->assertCount(3, $block->Fields(), 'Draft UserForm block starts with 3 fields'); // ensure setup has affected live mode too $origReadingMode = Versioned::get_reading_mode(); Versioned::withVersionedMode(function () { Versioned::set_reading_mode(Versioned::LIVE); $initialLivePage = UserDefinedForm::get()->First(); $initialLiveBlock = UserFormBlockStub::get()->First(); $this->assertSame($initialLivePage->ID, $initialLiveBlock->ID); $this->assertCount(2, $initialLivePage->Fields(), 'Live UserForm page starst with 2 fields'); $this->assertCount(3, $initialLiveBlock->Fields(), 'Live UserForm block starst with 3 fields'); }); // execute change $newField = new EditableEmailField(); $newField->update([ 'Name' => 'basic_email_name', 'Title' => 'Page Email Field' ]); $page->Fields()->add($newField); $page->publishRecursive(); // assert effect of change /** @var UserDefinedForm $checkPage */ $checkPage = UserDefinedForm::get()->First(); $checkBlock = UserFormBlockStub::get()->First(); $this->assertCount(3, $checkPage->Fields(), 'Field has been added to draft user form page'); $this->assertCount( 3, $checkBlock->Fields(), 'Draft userform block with same ID is not affected' ); // ensure this is true for live mode too Versioned::withVersionedMode(function () { Versioned::set_reading_mode(Versioned::LIVE); $checkLivePage = UserDefinedForm::get()->First(); $checkLiveBlock = UserFormBlockStub::get()->First(); $this->assertCount( 3, $checkLivePage->Fields(), 'Field has been added to live user form page' ); $this->assertCount( 3, $checkLiveBlock->Fields(), 'Live userform block with same ID is not affected' ); }); } }
php
BSD-3-Clause
e33fff165d33a077ec4b20c2eef2ef8bca25d15a
2026-01-05T05:22:58.009669Z
false
silverstripe/silverstripe-userforms
https://github.com/silverstripe/silverstripe-userforms/blob/e33fff165d33a077ec4b20c2eef2ef8bca25d15a/tests/behat/src/FeatureContext.php
tests/behat/src/FeatureContext.php
<?php namespace SilverStripe\UserForms\Tests\Behat\Context; use SilverStripe\BehatExtension\Context\SilverStripeContext; class FeatureContext extends SilverStripeContext { /** * The preview email button is a hyperlink with target="_blank" * Behat won't view the newly opened tab * * @When /^I preview the email$/ */ public function iPreviewTheEmail() { $js = <<<JS document.querySelectorAll('a.btn').forEach(link => { if (link.innerHTML.trim() == 'Preview email') { document.location.href = link.href; } }); JS; $result = $this->getSession()->getDriver()->executeScript($js); sleep(5); } }
php
BSD-3-Clause
e33fff165d33a077ec4b20c2eef2ef8bca25d15a
2026-01-05T05:22:58.009669Z
false
silverstripe/silverstripe-userforms
https://github.com/silverstripe/silverstripe-userforms/blob/e33fff165d33a077ec4b20c2eef2ef8bca25d15a/tests/behat/src/FixtureContext.php
tests/behat/src/FixtureContext.php
<?php namespace SilverStripe\UserForms\Tests\Behat\Context; use SilverStripe\BehatExtension\Context\FixtureContext as BaseFixtureContext; use SilverStripe\ORM\DataObject; use SilverStripe\UserForms\Model\EditableCustomRule; use SilverStripe\UserForms\Model\EditableFormField\EditableFormStep; use SilverStripe\UserForms\Model\EditableFormField\EditableTextField; use SilverStripe\UserForms\Model\UserDefinedForm; use SilverStripe\Versioned\Versioned; /** * Context used to create fixtures in the SilverStripe ORM. */ class FixtureContext extends BaseFixtureContext { /** * Example: Given a userform with a hidden form step "My userform" * * @Given /^a userform with a hidden form step "([^"]+)"$/ * @param string $udfTitle */ public function stepCreateUserFormWithHiddenFormStep(string $udfTitle): void { /** @var UserDefinedForm|Versioned $udf */ /** @var EditableTextField $tf01 */ /** @var EditableFormStep $fs02 */ $udf = $this->getFixtureFactory()->createObject(UserDefinedForm::class, $udfTitle); $this->createEditableFormField(EditableFormStep::class, 'EditableFormStep_01', $udf); $tf01 = $this->createEditableFormField(EditableTextField::class, 'EditableTextField_01', $udf); $fs02 = $this->createEditableFormField(EditableFormStep::class, 'EditableFormStep_02', $udf); $this->createEditableFormField(EditableTextField::class, 'EditableTextField_02', $udf); $fs02->ShowOnLoad = 0; $fs02->write(); $this->createCustomRule('cr1', $fs02, $tf01); $this->createEditableFormField(EditableFormStep::class, 'EditableFormStep_03', $udf); $this->createEditableFormField(EditableTextField::class, 'EditableTextField_03', $udf); $this->createEditableFormField(EditableFormStep::class, 'EditableFormStep_04', $udf); $tf04 = $this->createEditableFormField(EditableTextField::class, 'EditableTextField_04', $udf); $fs05 = $this->createEditableFormField(EditableFormStep::class, 'EditableFormStep_05', $udf); $this->createEditableFormField(EditableTextField::class, 'EditableTextField_05', $udf); $fs05->ShowOnLoad = 0; $fs05->write(); $this->createCustomRule('cr2', $fs05, $tf04); $fs06 = $this->createEditableFormField(EditableFormStep::class, 'EditableFormStep_06', $udf); $this->createEditableFormField(EditableTextField::class, 'EditableTextField_06', $udf); $fs06->ShowOnLoad = 0; $fs06->write(); $this->createCustomRule('cr3', $fs06, $tf04); $this->createEditableFormField(EditableFormStep::class, 'EditableFormStep_07', $udf); $this->createEditableFormField(EditableTextField::class, 'EditableTextField_07', $udf); $udf->publishRecursive(); } private function createEditableFormField(string $class, string $id, UserDefinedForm $udf): DataObject { $field = $this->getFixtureFactory()->createObject($class, $id); $field->Title = $id; $field->Parent = $udf; $field->write(); return $field; } private function createCustomRule(string $id, EditableFormStep $fs, EditableTextField $tf): EditableCustomRule { /** @var EditableCustomRule $rule */ $rule = $this->getFixtureFactory()->createObject(EditableCustomRule::class, $id); $rule->Parent = $fs; $rule->ConditionField = $tf; $rule->Display = 'Show'; $rule->ConditionOption = 'IsNotBlank'; $rule->write(); return $rule; } }
php
BSD-3-Clause
e33fff165d33a077ec4b20c2eef2ef8bca25d15a
2026-01-05T05:22:58.009669Z
false
silverstripe/silverstripe-userforms
https://github.com/silverstripe/silverstripe-userforms/blob/e33fff165d33a077ec4b20c2eef2ef8bca25d15a/tests/php/Model/EditableFormFieldTest.php
tests/php/Model/EditableFormFieldTest.php
<?php namespace SilverStripe\UserForms\Tests\Model; use SilverStripe\Core\Config\Config; use SilverStripe\Dev\FunctionalTest; use SilverStripe\Forms\DropdownField; use SilverStripe\Forms\OptionsetField; use SilverStripe\UserForms\Model\EditableFormField; use SilverStripe\UserForms\Model\EditableFormField\EditableCheckbox; use SilverStripe\UserForms\Model\EditableFormField\EditableDropdown; use SilverStripe\UserForms\Model\EditableFormField\EditableFileField; use SilverStripe\UserForms\Model\EditableFormField\EditableLiteralField; use SilverStripe\UserForms\Model\EditableFormField\EditableOption; use SilverStripe\UserForms\Model\EditableFormField\EditableRadioField; use SilverStripe\UserForms\Model\EditableFormField\EditableTextField; use SilverStripe\UserForms\Model\EditableCustomRule; use PHPUnit\Framework\Attributes\DataProvider; /** * @package userforms */ class EditableFormFieldTest extends FunctionalTest { protected static $fixture_file = 'EditableFormFieldTest.yml'; public function testFormFieldPermissions() { $text = $this->objFromFixture(EditableTextField::class, 'basic-text'); $this->logInWithPermission('ADMIN'); $this->assertTrue($text->canCreate()); $this->assertTrue($text->canView()); $this->assertTrue($text->canEdit()); $this->assertTrue($text->canDelete()); $text->setReadonly(true); $this->assertTrue($text->canView()); $this->assertFalse($text->canEdit()); $this->assertFalse($text->canDelete()); $text->setReadonly(false); $this->assertTrue($text->canView()); $this->assertTrue($text->canEdit()); $this->assertTrue($text->canDelete()); $this->logOut(); $this->logInWithPermission('SITETREE_VIEW_ALL'); $this->assertFalse($text->canCreate()); $text->setReadonly(false); $this->assertTrue($text->canView()); $this->assertFalse($text->canEdit()); $this->assertFalse($text->canDelete()); $text->setReadonly(true); $this->assertTrue($text->canView()); $this->assertFalse($text->canEdit()); $this->assertFalse($text->canDelete()); } public function testEditableOptionEmptyValue() { $option = $this->objFromFixture(EditableOption::class, 'option-1'); $option->Value = ''; // Disallow empty values EditableOption::set_allow_empty_values(false); $this->assertEquals($option->Title, $option->Value); $option->Value = 'test'; $this->assertEquals('test', $option->Value); // Allow empty values EditableOption::set_allow_empty_values(true); $option->Value = ''; $this->assertEquals('', $option->Value); } public function testEditableDropdownField() { $dropdown = $this->objFromFixture(EditableDropdown::class, 'basic-dropdown'); $field = $dropdown->getFormField(); $this->assertThat($field, $this->isInstanceOf(DropdownField::class)); $values = $field->getSource(); $this->assertEquals(['Option 1' => 'Option 1', 'Option 2' => 'Option 2'], $values); } public function testEditableRadioField() { $radio = $this->objFromFixture(EditableRadioField::class, 'radio-field'); $field = $radio->getFormField(); $this->assertThat($field, $this->isInstanceOf(OptionsetField::class)); $values = $field->getSource(); $this->assertEquals(['Option 5' => 'Option 5', 'Option 6' => 'Option 6'], $values); } public function testMultipleOptionDuplication() { $dropdown = $this->objFromFixture(EditableDropdown::class, 'basic-dropdown'); $clone = $dropdown->duplicate(); $this->assertEquals( $dropdown->Options()->Count(), $clone->Options()->Count(), "The duplicate should have contain same number of options" ); foreach ($clone->Options() as $option) { $original = $dropdown->Options()->find('Title', $option->Title); $this->assertEquals($original->Sort, $option->Sort); } } public function testFileField() { $fileField = $this->objFromFixture(EditableFileField::class, 'file-field'); $formField = $fileField->getFormField(); $this->assertContains('jpg', $formField->getValidator()->getAllowedExtensions()); $this->assertNotContains('notallowedextension', $formField->getValidator()->getAllowedExtensions()); } public function testFileFieldAllowedExtensionsBlacklist() { Config::modify()->merge(EditableFileField::class, 'allowed_extensions_blacklist', ['jpg']); $fileField = $this->objFromFixture(EditableFileField::class, 'file-field'); $formField = $fileField->getFormField(); $this->assertNotContains('jpg', $formField->getValidator()->getAllowedExtensions()); } /** * Test that if folder is not set or folder was removed, * then getFormField() saves file in protected folder */ public function testCreateProtectedFolder() { $fileField1 = $this->objFromFixture(EditableFileField::class, 'file-field-without-folder'); $fileField2 = $this->objFromFixture(EditableFileField::class, 'file-field-with-folder'); $fileField1->createProtectedFolder(); $formField1 = $fileField1->getFormField(); $formField2 = $fileField2->getFormField(); $canViewParent1 = $fileField1->Folder()->Parent()->Parent()->CanViewType; $canViewParent2 = $fileField2->Folder()->Parent()->CanViewType; $this->assertEquals('OnlyTheseUsers', $canViewParent1); $this->assertEquals('Inherit', $canViewParent2); $this->assertTrue( (bool) preg_match( sprintf( '/^Form-submissions\/page-%d\/upload-field-%d/', $fileField1->ParentID, $fileField1->ID ), $formField1->folderName, ) ); $this->assertEquals('folder1/folder1-1/', $formField2->folderName); } /** * Verify that folder is related to a field exist */ public function testGetFolderExists() { $fileField1 = $this->objFromFixture(EditableFileField::class, 'file-field-without-folder'); $fileField2 = $this->objFromFixture(EditableFileField::class, 'file-field-with-folder'); $this->assertFalse($fileField1->getFolderExists()); $this->assertTrue($fileField2->getFolderExists()); } /** * Verify that unique names are automatically generated for each formfield */ public function testUniqueName() { $textfield1 = new EditableTextField(); $this->assertEmpty($textfield1->Name); // Write values $textfield1->write(); $textfield2 = new EditableTextField(); $textfield2->write(); $checkboxField = new EditableCheckbox(); $checkboxField->write(); // Test values are in the expected format $this->assertMatchesRegularExpression('/^EditableTextField_.+/', $textfield1->Name); $this->assertMatchesRegularExpression('/^EditableTextField_.+/', $textfield2->Name); $this->assertMatchesRegularExpression('/^EditableCheckbox_.+/', $checkboxField->Name); $this->assertNotEquals($textfield1->Name, $textfield2->Name); } public function testLengthRange() { /** @var EditableTextField $textField */ $textField = $this->objFromFixture(EditableTextField::class, 'basic-text'); // Empty range /** @var TextField $formField */ $textField->MinLength = 0; $textField->MaxLength = 0; $attributes = $textField->getFormField()->getAttributes(); $this->assertFalse(isset($attributes['maxLength'])); $this->assertFalse(isset($attributes['data-rule-minlength'])); $this->assertFalse(isset($attributes['data-rule-maxlength'])); // Test valid range $textField->MinLength = 10; $textField->MaxLength = 20; $attributes = $textField->getFormField()->getAttributes(); $this->assertEquals(20, $attributes['maxLength']); $this->assertEquals(20, $attributes['size']); $this->assertEquals(10, $attributes['data-rule-minlength']); $this->assertEquals(20, $attributes['data-rule-maxlength']); // textarea $textField->Rows = 3; $attributes = $textField->getFormField()->getAttributes(); $this->assertEquals(20, $attributes['maxlength']); $this->assertEquals(10, $attributes['data-rule-minlength']); $this->assertEquals(20, $attributes['data-rule-maxlength']); } public function testFormatDisplayRules() { $field = $this->objFromFixture(EditableTextField::class, 'irdNumberField'); $displayRules = $field->formatDisplayRules(); $this->assertNotNull($displayRules); $this->assertCount(1, $displayRules['operations']); // Field is initially visible, so the "view" method should be to hide it $this->assertSame('addClass("hide")', $displayRules['view']); // The opposite method should be to return it to its original state, i.e. show it again $this->assertSame('removeClass("hide")', $displayRules['opposite']); } public function testGetIcon() { $field = new EditableTextField; $this->assertStringContainsString('/images/editabletextfield.png', $field->getIcon()); } public static function displayedProvider() { $one = ['basic_text_name' => 'foobar']; $two = array_merge($one, ['basic_text_name_2' => 'foobar']); return [ 'no display rule AND' => ['alwaysVisible', [], true], 'no display rule OR' => ['alwaysVisibleOr', [], true], 'no display rule hidden AND' => ['neverVisible', [], false], 'no display rule hidden OR' => ['neverVisibleOr', [], false], '1 unmet display rule AND' => ['singleDisplayRule', [], false], '1 met display rule AND' => ['singleDisplayRule', $one, true], '1 unmet display rule OR' => ['singleDisplayRuleOr', [], false], '1 met display rule OR' => ['singleDisplayRuleOr', $one, true], '1 unmet hide rule AND' => ['singleHiddingRule', [], true], '1 met hide rule AND' => ['singleHiddingRule', $one, false], '1 unmet hide rule OR' => ['singleHiddingRuleOr', [], true], '1 met hide rule OR' => ['singleHiddingRuleOr', $one, false], 'multi display rule AND none met' => ['multiDisplayRule', [], false], 'multi display rule AND partially met' => ['multiDisplayRule', $one, false], 'multi display rule AND all met' => ['multiDisplayRule', $two, true], 'multi display rule OR none met' => ['multiDisplayRuleOr', [], false], 'multi display rule OR partially met' => ['multiDisplayRuleOr', $one, true], 'multi display rule OR all met' => ['multiDisplayRuleOr', $two, true], 'multi hide rule AND none met' => ['multiHiddingRule', [], true], 'multi hide rule AND partially met' => ['multiHiddingRule', $one, true], 'multi hide rule AND all met' => ['multiHiddingRule', $two, false], 'multi hide rule OR none met' => ['multiHiddingRuleOr', [], true], 'multi hide rule OR partially met' => ['multiHiddingRuleOr', $one, false], 'multi hide rule OR all met' => ['multiHiddingRuleOr', $two, false], ]; } /** * @param $fieldName * @param $data * @param $expected */ #[DataProvider('displayedProvider')] public function testIsDisplayed($fieldName, $data, $expected) { /** @var EditableFormField $field */ $field = $this->objFromFixture(EditableTextField::class, $fieldName); $this->assertEquals($expected, $field->isDisplayed($data)); } public function testChangingDataFieldTypeToDatalessRemovesRequiredSetting() { $requiredTextField = $this->objFromFixture(EditableTextField::class, 'required-text'); $fieldId = $requiredTextField->ID; $this->assertTrue((bool)$requiredTextField->Required); $literalField = $requiredTextField->newClassInstance(EditableLiteralField::class); $this->assertTrue((bool)$literalField->Required); $literalField->write(); $this->assertFalse((bool)$literalField->Required); $updatedField = EditableFormField::get()->byId($fieldId); $this->assertFalse((bool)$updatedField->Required); } public function testRecursionProtection() { $radioOne = EditableRadioField::create(); $radioOneID = $radioOne->write(); $optionOneOne = EditableOption::create(); $optionOneOne->Value = 'yes'; $optionOneOne->ParentID = $radioOneID; $optionOneTwo = EditableOption::create(); $optionOneTwo->Value = 'no'; $optionOneTwo->ParentID = $radioOneID; $radioTwo = EditableRadioField::create(); $radioTwoID = $radioTwo->write(); $optionTwoOne = EditableOption::create(); $optionTwoOne->Value = 'yes'; $optionTwoOne->ParentID = $radioOneID; $optionTwoTwo = EditableOption::create(); $optionTwoTwo->Value = 'no'; $optionTwoTwo->ParentID = $radioTwoID; $conditionOne = EditableCustomRule::create(); $conditionOne->ParentID = $radioOneID; $conditionOne->ConditionFieldID = $radioTwoID; $conditionOne->ConditionOption = 'HasValue'; $conditionOne->FieldValue = 'yes'; $conditionOne->write(); $radioOne->DisplayRules()->add($conditionOne); $conditionTwo = EditableCustomRule::create(); $conditionTwo->ParentID = $radioTwoID; $conditionTwo->ConditionFieldID = $radioOneID; $conditionTwo->ConditionOption = 'IsNotBlank'; $conditionTwo->write(); $radioTwo->DisplayRules()->add($conditionTwo); $testField = new class extends EditableFormField { public function countIsDisplayedRecursionProtection(int $fieldID) { return count(array_filter(static::$isDisplayedRecursionProtection, function ($id) use ($fieldID) { return $id === $fieldID; })); } }; $this->assertSame(0, $testField->countIsDisplayedRecursionProtection($radioOneID)); $radioOne->isDisplayed([]); $this->assertSame(100, $testField->countIsDisplayedRecursionProtection($radioOneID)); } }
php
BSD-3-Clause
e33fff165d33a077ec4b20c2eef2ef8bca25d15a
2026-01-05T05:22:58.009669Z
false
silverstripe/silverstripe-userforms
https://github.com/silverstripe/silverstripe-userforms/blob/e33fff165d33a077ec4b20c2eef2ef8bca25d15a/tests/php/Model/SubmittedFileFieldTest.php
tests/php/Model/SubmittedFileFieldTest.php
<?php namespace SilverStripe\UserForms\Tests\Model; use SilverStripe\Assets\Dev\TestAssetStore; use SilverStripe\Assets\File; use SilverStripe\Assets\Storage\AssetStore; use SilverStripe\Control\Director; use SilverStripe\Core\Injector\Injector; use SilverStripe\Dev\SapphireTest; use SilverStripe\UserForms\Model\Submission\SubmittedFileField; use SilverStripe\UserForms\Model\Submission\SubmittedForm; use SilverStripe\Versioned\Versioned; class SubmittedFileFieldTest extends SapphireTest { protected $file; protected $submittedForm; protected $submittedFile; protected function setUp(): void { parent::setUp(); TestAssetStore::activate('SubmittedFileFieldTest'); $this->file = File::create(); $this->file->setFromString('ABC', 'test-SubmittedFileFieldTest.txt'); $this->file->write(); $this->submittedForm = SubmittedForm::create(); $this->submittedForm->write(); $this->submittedFile = SubmittedFileField::create(); $this->submittedFile->UploadedFileID = $this->file->ID; $this->submittedFile->Name = 'File'; $this->submittedFile->ParentID = $this->submittedForm->ID; $this->submittedFile->write(); } protected function tearDown(): void { TestAssetStore::reset(); parent::tearDown(); } public function testDeletingSubmissionRemovesFile() { $this->assertStringContainsString('test-SubmittedFileFieldTest', $this->submittedFile->getFileName(), 'Submitted file is linked'); $this->submittedForm->delete(); $fileId = $this->file->ID; $draftVersion = Versioned::withVersionedMode(function () use ($fileId) { Versioned::set_stage(Versioned::DRAFT); return File::get()->byID($fileId); }); $this->assertNull($draftVersion, 'Draft file has been deleted'); $liveVersion = Versioned::withVersionedMode(function () use ($fileId) { Versioned::set_stage(Versioned::LIVE); return File::get()->byID($fileId); }); $this->assertNull($liveVersion, 'Live file has been deleted'); } public function testGetFormattedValue() { // Set an explicit base URL so we get a reliable value for the test Director::config()->set('alternate_base_url', 'http://mysite.com'); $fileName = $this->submittedFile->getFileName(); $link = 'http://mysite.com/assets/3c01bdbb26/test-SubmittedFileFieldTest.txt'; $this->file->CanViewType = 'OnlyTheseUsers'; $this->file->write(); // Userforms submission filled in by non-logged in user being emailed to recipient $this->logOut(); $this->assertEquals( sprintf( '%s - <a href="%s" target="_blank">%s</a> - <em>%s</em>', $fileName, $link, 'Download File', 'You must be logged in to view this file' ), $this->submittedFile->getFormattedValue()->value ); $this->logOut(); // Logged in CMS user without permissions to view file in the CMS $this->logInWithPermission('CMS_ACCESS_CMSMain'); $this->assertEquals( sprintf( '<span class="icon font-icon-lock" aria-hidden="true"></span> %s - <em>%s</em>', $fileName, 'You don&#039;t have the right permissions to download this file' ), $this->submittedFile->getFormattedValue()->value ); $this->logOut(); // Logged in CMS user with permissions to view file in the CMS $this->loginWithPermission('ADMIN'); $this->assertEquals( sprintf( '%s - <a href="%s" target="_blank">%s</a>', $fileName, $link, 'Download File' ), $this->submittedFile->getFormattedValue()->value ); } }
php
BSD-3-Clause
e33fff165d33a077ec4b20c2eef2ef8bca25d15a
2026-01-05T05:22:58.009669Z
false
silverstripe/silverstripe-userforms
https://github.com/silverstripe/silverstripe-userforms/blob/e33fff165d33a077ec4b20c2eef2ef8bca25d15a/tests/php/Model/EditableCustomRuleTest.php
tests/php/Model/EditableCustomRuleTest.php
<?php namespace SilverStripe\UserForms\Tests\Model; use SilverStripe\Dev\SapphireTest; use SilverStripe\UserForms\Model\EditableCustomRule; use PHPUnit\Framework\Attributes\DataProvider; /** * Class EditableCustomRulesTest */ class EditableCustomRuleTest extends SapphireTest { protected static $fixture_file = 'EditableCustomRuleTest.yml'; public function testBuildExpression() { /** @var EditableCustomRule $rule1 */ $rule1 = $this->objFromFixture(EditableCustomRule::class, 'rule1'); $result1 = $rule1->buildExpression(); //Dropdowns expect change event $this->assertEquals('change', $result1['event']); $this->assertNotEmpty($result1['operation']); //Check for equals sign $this->assertStringContainsString('==', $result1['operation']); /** @var EditableCustomRule $rule2 */ $rule2 = $this->objFromFixture(EditableCustomRule::class, 'rule2'); $result2 = $rule2->buildExpression(); //TextField expect change event $this->assertEquals('keyup', $result2['event']); $this->assertNotEmpty($result2['operation']); //Check for greater than sign $this->assertStringContainsString('>', $result2['operation']); } /** * Test that methods are returned for manipulating the presence of the "hide" CSS class depending * on whether the field should be hidden or shown */ public function testToggleDisplayText() { /** @var EditableCustomRule $rule1 */ $rule1 = $this->objFromFixture(EditableCustomRule::class, 'rule1'); $this->assertSame('addClass("hide")', $rule1->toggleDisplayText('show')); $this->assertSame('removeClass("hide")', $rule1->toggleDisplayText('hide')); $this->assertSame('removeClass("hide")', $rule1->toggleDisplayText('show', true)); $this->assertSame('addClass("hide")', $rule1->toggleDisplayText('hide', true)); } public function testToggleDisplayEvent() { /** @var EditableCustomRule $rule1 */ $rule1 = $this->objFromFixture(EditableCustomRule::class, 'rule1'); $this->assertSame('userform.field.hide', $rule1->toggleDisplayEvent('show')); $this->assertSame('userform.field.show', $rule1->toggleDisplayEvent('hide')); $this->assertSame('userform.field.show', $rule1->toggleDisplayEvent('show', true)); $this->assertSame('userform.field.hide', $rule1->toggleDisplayEvent('hide', true)); } public static function dataProviderValidateAgainstFormData() { return [ 'IsNotBlank with blank value' => ['IsNotBlank', '', '', false], 'IsNotBlank with nopn-blank value' => ['IsNotBlank', '', 'something', true], 'IsBlank with blank value' => ['IsBlank', '', '', true], 'IsBlank with nopn-blank value' => ['IsBlank', '', 'something', false], 'HasValue with blank value' => ['HasValue', 'NZ', '', false], 'HasValue with correct value' => ['HasValue', 'NZ', 'NZ', true], 'HasValue with incorrect value' => ['HasValue', 'NZ', 'UK', false], 'ValueNot with blank value' => ['ValueNot', 'NZ', '', true], 'ValueNot with targeted value' => ['ValueNot', 'NZ', 'NZ', false], 'ValueNot with non-targeted value' => ['ValueNot', 'NZ', 'UK', true], 'ValueLessThan with value below target' => ['ValueLessThan', '0', '-0.00001', true], 'ValueLessThan with value equal to target' => ['ValueLessThan', '0', '0', false], 'ValueLessThan with value greater to target' => ['ValueLessThan', '0', '0.0001', false], 'ValueLessThanEqual with value below target' => ['ValueLessThanEqual', '0', '-0.00001', true], 'ValueLessThanEqual with value equal to target' => ['ValueLessThanEqual', '0', '0', true], 'ValueLessThanEqual with value greater to target' => ['ValueLessThanEqual', '0', '0.0001', false], 'ValueGreaterThan with value below target' => ['ValueGreaterThan', '0', '-0.00001', false], 'ValueGreaterThan with value equal to target' => ['ValueGreaterThan', '0', '0', false], 'ValueGreaterThan with value greater to target' => ['ValueGreaterThan', '0', '0.0001', true], 'ValueGreaterThanEqual with value below target' => ['ValueGreaterThanEqual', '0', '-0.00001', false], 'ValueGreaterThanEqual with value equal to target' => ['ValueGreaterThanEqual', '0', '0', true], 'ValueGreaterThanEqual with value greater to target' => ['ValueGreaterThanEqual', '0', '0.0001', true], ]; } /** * Test that methods are returned for manipulating the presence of the "hide" CSS class depending * on whether the field should be hidden or shown */ #[DataProvider('dataProviderValidateAgainstFormData')] public function testValidateAgainstFormData($condition, $targetValue, $value, $expected) { $rule1 = $this->objFromFixture(EditableCustomRule::class, 'rule1'); $rule1->ConditionOption = $condition; $rule1->FieldValue = $targetValue; $this->assertFalse( $rule1->validateAgainstFormData([]), 'Unset value always returns false no matter the rule' ); $this->assertEquals( $expected, $rule1->validateAgainstFormData(['CountrySelection' => $value]) ); } public function testValidateAgainstFormDataWithNonSenseRule() { $this->expectException(\LogicException::class); $rule1 = $this->objFromFixture(EditableCustomRule::class, 'rule1'); $rule1->ConditionOption = 'NonSenseRule'; $rule1->validateAgainstFormData(['CountrySelection' => 'booya']); } }
php
BSD-3-Clause
e33fff165d33a077ec4b20c2eef2ef8bca25d15a
2026-01-05T05:22:58.009669Z
false
silverstripe/silverstripe-userforms
https://github.com/silverstripe/silverstripe-userforms/blob/e33fff165d33a077ec4b20c2eef2ef8bca25d15a/tests/php/Model/UserDefinedFormTest.php
tests/php/Model/UserDefinedFormTest.php
<?php namespace SilverStripe\UserForms\Tests\Model; use SilverStripe\Control\Controller; use SilverStripe\Control\Email\Email; use SilverStripe\Core\Convert; use SilverStripe\Dev\FunctionalTest; use SilverStripe\Forms\DropdownField; use SilverStripe\Forms\FieldList; use SilverStripe\Forms\Form; use SilverStripe\Forms\GridField\GridField; use SilverStripe\Forms\GridField\GridFieldDataColumns; use SilverStripe\ORM\DB; use SilverStripe\UserForms\Extension\UserFormFieldEditorExtension; use SilverStripe\UserForms\Extension\UserFormValidator; use SilverStripe\UserForms\Model\EditableCustomRule; use SilverStripe\UserForms\Model\EditableFormField; use SilverStripe\UserForms\Model\EditableFormField\EditableDropdown; use SilverStripe\UserForms\Model\EditableFormField\EditableEmailField; use SilverStripe\UserForms\Model\EditableFormField\EditableFieldGroup; use SilverStripe\UserForms\Model\EditableFormField\EditableFieldGroupEnd; use SilverStripe\UserForms\Model\Recipient\EmailRecipient; use SilverStripe\UserForms\Model\UserDefinedForm; use SilverStripe\Versioned\Versioned; /** * @package userforms */ class UserDefinedFormTest extends FunctionalTest { protected $usesTransactions = false; protected static $fixture_file = '../UserFormsTest.yml'; protected static $required_extensions = [ UserDefinedForm::class => [UserFormFieldEditorExtension::class], ]; protected function setUp(): void { parent::setUp(); Email::config()->set('admin_email', 'no-reply@example.com'); } public function testRollbackToVersion() { $this->markTestSkipped( 'UserDefinedForm::rollback() has not been implemented completely' ); $this->logInWithPermission('ADMIN'); /** @var UserDefinedForm|Versioned $form */ $form = $this->objFromFixture(UserDefinedForm::class, 'basic-form-page'); $form->SubmitButtonText = 'Button Text'; $form->write(); $form->publishRecursive(); $origVersion = $form->Version; $form->SubmitButtonText = 'Updated Button Text'; $form->write(); $form->publishRecursive(); // check published site $updated = Versioned::get_one_by_stage(UserDefinedForm::class, 'Stage', "\"UserDefinedForm\".\"ID\" = $form->ID"); $this->assertEquals($updated->SubmitButtonText, 'Updated Button Text'); $form->rollbackRecursive($origVersion); $orignal = Versioned::get_one_by_stage(UserDefinedForm::class, 'Stage', "\"UserDefinedForm\".\"ID\" = $form->ID"); $this->assertEquals($orignal->SubmitButtonText, 'Button Text'); } public function testGetCMSFields() { $this->logInWithPermission('ADMIN'); $form = $this->objFromFixture(UserDefinedForm::class, 'basic-form-page'); $fields = $form->getCMSFields(); $this->assertNotNull($fields->dataFieldByName('Fields')); $this->assertNotNull($fields->dataFieldByName('EmailRecipients')); $this->assertNotNull($fields->dataFieldByName('Submissions')); $this->assertNotNull($fields->dataFieldByName('OnCompleteMessage')); } public function testGetCMSFieldsShowInSummary() { $this->logInWithPermission('ADMIN'); $form = $this->objFromFixture(UserDefinedForm::class, 'summary-rules-form'); $fields = $form->getCMSFields(); $this->assertInstanceOf(GridField::class, $fields->dataFieldByName('Submissions')); $submissionsgrid = $fields->dataFieldByName('Submissions'); $gridFieldDataColumns = $submissionsgrid->getConfig()->getComponentByType(GridFieldDataColumns::class); $summaryFields = $gridFieldDataColumns->getDisplayFields($submissionsgrid); $this->assertContains('SummaryShow', array_keys($summaryFields ?? []), 'Summary field not showing displayed field'); $this->assertNotContains('SummaryHide', array_keys($summaryFields ?? []), 'Summary field showing displayed field'); } public function testEmailRecipientPopup() { $this->logInWithPermission('ADMIN'); $form = $this->objFromFixture(UserDefinedForm::class, 'basic-form-page'); $popup = new EmailRecipient(); $popup->FormID = $form->ID; $popup->FormClass = UserDefinedForm::class; $popup->EmailAddress = 'test@example.com'; $fields = $popup->getCMSFields(); $this->assertNotNull($fields->dataFieldByName('EmailSubject')); $this->assertNotNull($fields->dataFieldByName('EmailFrom')); $this->assertNotNull($fields->dataFieldByName('EmailAddress')); $this->assertNotNull($fields->dataFieldByName('HideFormData')); $this->assertNotNull($fields->dataFieldByName('SendPlain')); $this->assertNotNull($fields->dataFieldByName('EmailBody')); // add an email field, it should now add a or from X address picker $email = $this->objFromFixture(EditableEmailField::class, 'email-field'); $form->Fields()->add($email); $popup->write(); $fields = $popup->getCMSFields(); $this->assertThat($fields->dataFieldByName('SendEmailToFieldID'), $this->isInstanceOf(DropdownField::class)); // if the front end has checkboxes or dropdown they can select from that can also be used to send things $dropdown = $this->objFromFixture(EditableDropdown::class, 'department-dropdown'); $form->Fields()->add($dropdown); $fields = $popup->getCMSFields(); $this->assertTrue($fields->dataFieldByName('SendEmailToFieldID') !== null); $popup->delete(); } public function testGetEmailBodyContent() { $recipient = new EmailRecipient(); $recipient->EmailAddress = 'test@example.com'; $emailBody = 'not html'; $emailBodyHtml = '<p>html</p>'; $recipient->EmailBody = $emailBody; $recipient->EmailBodyHtml = $emailBodyHtml; $recipient->write(); $this->assertEquals($recipient->SendPlain, 0); $this->assertEquals($recipient->getEmailBodyContent(), $emailBodyHtml); $recipient->SendPlain = 1; $recipient->write(); $this->assertEquals($recipient->getEmailBodyContent(), $emailBody); $recipient->delete(); } public function testGetEmailTemplateDropdownValues() { $page = $this->objFromFixture(UserDefinedForm::class, 'basic-form-page'); $recipient = new EmailRecipient(); $recipient->FormID = $page->ID; $recipient->FormClass = UserDefinedForm::class; $result = $recipient->getEmailTemplateDropdownValues(); // Installation path can be as a project when testing in Travis, so check partial match $foundKey = false; foreach (array_keys($result ?? []) as $key) { if (strpos($key ?? '', 'email' . DIRECTORY_SEPARATOR . 'SubmittedFormEmail') !== false) { $foundKey = true; } } $this->assertTrue($foundKey); $this->assertTrue(in_array('SubmittedFormEmail', array_values($result ?? []))); } public function testEmailTemplateExists() { $page = $this->objFromFixture(UserDefinedForm::class, 'basic-form-page'); $recipient = new EmailRecipient(); $recipient->FormID = $page->ID; $recipient->FormClass = UserDefinedForm::class; $recipient->EmailAddress = 'test@example.com'; // Set the default template $recipient->EmailTemplate = current(array_keys($recipient->getEmailTemplateDropdownValues() ?? [])); $recipient->write(); // The default template exists $this->assertTrue($recipient->emailTemplateExists()); // A made up template doesn't exists $this->assertFalse($recipient->emailTemplateExists('MyTemplateThatsNotThere')); $recipient->delete(); } public function testCanEditAndDeleteRecipient() { $form = $this->objFromFixture(UserDefinedForm::class, 'basic-form-page'); $this->logInWithPermission('ADMIN'); foreach ($form->EmailRecipients() as $recipient) { $this->assertTrue($recipient->canEdit()); $this->assertTrue($recipient->canDelete()); } $this->logOut(); $this->logInWithPermission('SITETREE_VIEW_ALL'); foreach ($form->EmailRecipients() as $recipient) { $this->assertFalse($recipient->canEdit()); $this->assertFalse($recipient->canDelete()); } } public function testPublishing() { $this->logInWithPermission('ADMIN'); $form = $this->objFromFixture(UserDefinedForm::class, 'basic-form-page'); $form->write(); $form->publishRecursive(); $live = Versioned::get_one_by_stage(UserDefinedForm::class, 'Live', "\"UserDefinedForm_Live\".\"ID\" = $form->ID"); $this->assertNotNull($live); $this->assertEquals(2, $live->Fields()->Count()); // one page and one field $dropdown = $this->objFromFixture(EditableDropdown::class, 'basic-dropdown'); $form->Fields()->add($dropdown); $stage = Versioned::get_one_by_stage(UserDefinedForm::class, 'Stage', "\"UserDefinedForm\".\"ID\" = $form->ID"); $this->assertEquals(3, $stage->Fields()->Count()); // should not have published the dropdown $liveDropdown = Versioned::get_one_by_stage(EditableFormField::class, 'Live', "\"EditableFormField_Live\".\"ID\" = $dropdown->ID"); $this->assertNull($liveDropdown); // when publishing it should have added it $form->publishRecursive(); $live = Versioned::get_one_by_stage(UserDefinedForm::class, 'Live', "\"UserDefinedForm_Live\".\"ID\" = $form->ID"); $this->assertEquals(3, $live->Fields()->Count()); // edit the title $text = $form->Fields()->limit(1, 1)->First(); $text->Title = 'Edited title'; $text->write(); $liveText = Versioned::get_one_by_stage(EditableFormField::class, 'Live', "\"EditableFormField_Live\".\"ID\" = $text->ID"); $this->assertFalse($liveText->Title == $text->Title); $form->publishRecursive(); $liveText = Versioned::get_one_by_stage(EditableFormField::class, 'Live', "\"EditableFormField_Live\".\"ID\" = $text->ID"); $this->assertTrue($liveText->Title == $text->Title); // Add a display rule to the dropdown $displayRule = new EditableCustomRule(); $displayRule->ParentID = $dropdown->ID; $displayRule->ConditionFieldID = $text->ID; $displayRule->write(); $ruleID = $displayRule->ID; // Not live $liveRule = Versioned::get_one_by_stage(EditableCustomRule::class, 'Live', "\"EditableCustomRule_Live\".\"ID\" = $ruleID"); $this->assertEmpty($liveRule); // Publish form, it's now live $form->publishRecursive(); $liveRule = Versioned::get_one_by_stage(EditableCustomRule::class, 'Live', "\"EditableCustomRule_Live\".\"ID\" = $ruleID"); $this->assertNotEmpty($liveRule); // Remove rule $displayRule->delete(); // Live rule still exists $liveRule = Versioned::get_one_by_stage(EditableCustomRule::class, 'Live', "\"EditableCustomRule_Live\".\"ID\" = $ruleID"); $this->assertNotEmpty($liveRule); // Publish form, it should remove this rule $form->publishRecursive(); $liveRule = Versioned::get_one_by_stage(EditableCustomRule::class, 'Live', "\"EditableCustomRule_Live\".\"ID\" = $ruleID"); $this->assertEmpty($liveRule); } public function testUnpublishing() { $this->logInWithPermission('ADMIN'); $form = $this->objFromFixture(UserDefinedForm::class, 'basic-form-page'); $form->write(); $this->assertEquals(0, DB::query("SELECT COUNT(*) FROM \"EditableFormField_Live\"")->value()); $form->publishRecursive(); // assert that it exists and has a field $live = Versioned::get_one_by_stage(UserDefinedForm::class, 'Live', "\"UserDefinedForm_Live\".\"ID\" = $form->ID", false); $this->assertTrue(isset($live)); $this->assertEquals(2, DB::query("SELECT COUNT(*) FROM \"EditableFormField_Live\"")->value()); // unpublish $form->doUnpublish(); $this->assertNull(Versioned::get_one_by_stage(UserDefinedForm::class, 'Live', "\"UserDefinedForm_Live\".\"ID\" = $form->ID", false)); $this->assertEquals(0, DB::query("SELECT COUNT(*) FROM \"EditableFormField_Live\"")->value()); } public function testDoRevertToLive() { $this->logInWithPermission('ADMIN'); $form = $this->objFromFixture(UserDefinedForm::class, 'basic-form-page'); $field = $form->Fields()->First(); $field->Title = 'Title'; $field->write(); $form->publishRecursive(); $field->Title = 'Edited title'; $field->write(); // check that the published version is not updated $live = Versioned::get_one_by_stage(EditableFormField::class, 'Live', "\"EditableFormField_Live\".\"ID\" = $field->ID"); $this->assertInstanceOf(EditableFormField::class, $live); $this->assertEquals('Title', $live->Title); // revert back to the live data $form->doRevertToLive(); $form->flushCache(); $check = Versioned::get_one_by_stage(EditableFormField::class, 'Stage', "\"EditableFormField\".\"ID\" = $field->ID"); $this->assertEquals('Title', $check->Title); } public function testDuplicatingForm() { $this->logInWithPermission('ADMIN'); $form = $this->objFromFixture(UserDefinedForm::class, 'basic-form-page'); $duplicate = $form->duplicate(); $this->assertEquals($form->Fields()->Count(), $duplicate->Fields()->Count()); // can't compare object since the dates/ids change $this->assertEquals($form->Fields()->First()->Title, $duplicate->Fields()->First()->Title); // Test duplicate with group $form2 = $this->objFromFixture(UserDefinedForm::class, 'page-with-group'); $form2Validator = new UserFormValidator(); $form2Validator->setForm(new Form(new Controller(), Form::class, new FieldList(), new FieldList())); $this->assertTrue($form2Validator->php($form2->toMap()), json_encode($form2Validator->getResult()->getMessages())); // Check field groups exist $form2GroupStart = $form2->Fields()->filter('ClassName', EditableFieldGroup::class)->first(); $form2GroupEnd = $form2->Fields()->filter('ClassName', EditableFieldGroupEnd::class)->first(); $this->assertEquals($form2GroupEnd->ID, $form2GroupStart->EndID); // Duplicate this $form3 = $form2->duplicate(); $form3Validator = new UserFormValidator(); $form3Validator->setForm(new Form(new Controller(), Form::class, new FieldList(), new FieldList())); $this->assertTrue($form3Validator->php($form3->toMap()), json_encode($form3Validator->getResult()->getMessages())); // Check field groups exist $form3GroupStart = $form3->Fields()->filter('ClassName', EditableFieldGroup::class)->first(); $form3GroupEnd = $form3->Fields()->filter('ClassName', EditableFieldGroupEnd::class)->first(); $this->assertEquals($form3GroupEnd->ID, $form3GroupStart->EndID); $this->assertNotEquals($form2GroupEnd->ID, $form3GroupStart->EndID); } public function testDuplicateFormDuplicatesRecursively() { $this->logInWithPermission('ADMIN'); /** @var UserDefinedForm $form */ $form = $this->objFromFixture(UserDefinedForm::class, 'form-with-multioptions'); $this->assertGreaterThanOrEqual(1, $form->Fields()->count(), 'Fixtured page has a field'); $this->assertCount( 2, $form->Fields()->Last()->Options(), 'Fixtured multiple option field has two options' ); $newForm = $form->duplicate(); $this->assertEquals( $form->Fields()->count(), $newForm->Fields()->count(), 'Duplicated page has same number of fields' ); $this->assertEquals( $form->Fields()->Last()->Options()->count(), $newForm->Fields()->Last()->Options()->count(), 'Duplicated dropdown field from duplicated form has duplicated options' ); } public function testFormOptions() { $this->logInWithPermission('ADMIN'); $form = $this->objFromFixture(UserDefinedForm::class, 'basic-form-page'); $fields = $form->getFormOptions(); $submit = $fields->fieldByName('SubmitButtonText'); $reset = $fields->fieldByName('ShowClearButton'); $this->assertEquals($submit->Title(), 'Text on submit button:'); $this->assertEquals($reset->Title(), 'Show Clear Form Button'); } public function testEmailRecipientFilters() { /** @var UserDefinedForm $form */ $form = $this->objFromFixture(UserDefinedForm::class, 'filtered-form-page'); // Check unfiltered recipients $result0 = $form ->EmailRecipients() ->sort('EmailAddress') ->column('EmailAddress'); $this->assertEquals( [ 'filtered1@example.com', 'filtered2@example.com', 'unfiltered@example.com' ], $result0 ); // check filters based on given data $result1 = $form->FilteredEmailRecipients( [ 'your-name' => 'Value', 'address' => '', 'street' => 'Anything', 'city' => 'Matches Not Equals', 'colours' => ['Red'] // matches 2 ], null ) ->sort('EmailAddress') ->column('EmailAddress'); $this->assertEquals( [ 'filtered2@example.com', 'unfiltered@example.com' ], $result1 ); // Check all positive matches $result2 = $form->FilteredEmailRecipients( [ 'your-name' => '', 'address' => 'Anything', 'street' => 'Matches Equals', 'city' => 'Anything', 'colours' => ['Red', 'Blue'] // matches 2 ], null ) ->sort('EmailAddress') ->column('EmailAddress'); $this->assertEquals( [ 'filtered1@example.com', 'filtered2@example.com', 'unfiltered@example.com' ], $result2 ); $result3 = $form->FilteredEmailRecipients( [ 'your-name' => 'Should be blank but is not', 'address' => 'Anything', 'street' => 'Matches Equals', 'city' => 'Anything', 'colours' => ['Blue'] ], null )->column('EmailAddress'); $this->assertEquals( [ 'unfiltered@example.com' ], $result3 ); $result4 = $form->FilteredEmailRecipients( [ 'your-name' => '', 'address' => 'Anything', 'street' => 'Wrong value for this field', 'city' => '', 'colours' => ['Blue', 'Green'] ], null )->column('EmailAddress'); $this->assertEquals( ['unfiltered@example.com'], $result4 ); } public function testIndex() { // Test that the $UserDefinedForm is stripped out $page = $this->objFromFixture(UserDefinedForm::class, 'basic-form-page'); $page->copyVersionToStage(Versioned::DRAFT, Versioned::LIVE); $result = $this->get($page->Link()); $body = Convert::nl2os($result->getBody(), ''); // strip out newlines $this->assertFalse($result->isError()); $this->assertStringContainsString('<p>Here is my form</p><form', $body); $this->assertStringContainsString('</form><p>Thank you for filling it out</p>', $body); $this->assertStringNotContainsString('<p>$UserDefinedForm</p>', $body); $this->assertStringNotContainsString('<p></p>', $body); $this->assertStringNotContainsString('</p><p>Thank you for filling it out</p>', $body); } public function testEmailAddressValidation() { $this->logInWithPermission('ADMIN'); // test invalid email addresses fail validation $recipient = $this->objFromFixture( EmailRecipient::class, 'invalid-recipient-list' ); $result = $recipient->validate(); $this->assertFalse($result->isValid()); $this->assertNotEmpty($result->getMessages()); $this->assertStringContainsString('filtered.example.com', $result->getMessages()[0]['message']); $this->assertStringNotContainsString('filtered2@example.com', $result->getMessages()[0]['message']); // test valid email addresses pass validation $recipient = $this->objFromFixture( EmailRecipient::class, 'valid-recipient-list' ); $result = $recipient->validate(); $this->assertTrue($result->isValid()); $this->assertEmpty($result->getMessages()); } }
php
BSD-3-Clause
e33fff165d33a077ec4b20c2eef2ef8bca25d15a
2026-01-05T05:22:58.009669Z
false
silverstripe/silverstripe-userforms
https://github.com/silverstripe/silverstripe-userforms/blob/e33fff165d33a077ec4b20c2eef2ef8bca25d15a/tests/php/Model/Recipient/EmailRecipientTest.php
tests/php/Model/Recipient/EmailRecipientTest.php
<?php namespace SilverStripe\UserForms\Tests\Model\Recipient; use SilverStripe\CMS\Model\SiteTree; use SilverStripe\Dev\SapphireTest; use SilverStripe\UserForms\Model\Recipient\EmailRecipient; use SilverStripe\UserForms\Model\UserDefinedForm; class EmailRecipientTest extends SapphireTest { protected static $fixture_file = 'EmailRecipientTest.yml'; public function testShortcodesAreRenderedInEmailPreviewContent() { $page = $this->objFromFixture(SiteTree::class, 'about_us'); $recipient = EmailRecipient::create(); $recipient->SendPlain = false; $recipient->EmailBodyHtml = '<p>Some email content. About us: [sitetree_link,id=' . $page->ID . '].</p>'; $result = $recipient->getEmailBodyContent(); $this->assertStringContainsString('/about-us', $result); $recipient->SendPlain = true; $recipient->EmailBody = 'Some email content. About us: [sitetree_link,id=' . $page->ID . '].'; $result = $recipient->getEmailBodyContent(); $this->assertStringContainsString('/about-us', $result); } public function testEmptyRecipientFailsValidation() { $this->expectException(\SilverStripe\Core\Validation\ValidationException::class); $this->expectExceptionMessage('"Send email to" address or field is required'); $recipient = new EmailRecipient(); $recipient->EmailFrom = 'test@example.com'; $recipient->write(); } public function testEmailAddressesTrimmed() { $recipient = new EmailRecipient(); $recipient->EmailAddress = 'test1@example.com '; $recipient->EmailFrom = 'test2@example.com '; $recipient->EmailReplyTo = 'test3@example.com '; $recipient->write(); $this->assertSame('test1@example.com', $recipient->EmailAddress); $this->assertSame('test2@example.com', $recipient->EmailFrom); $this->assertSame('test3@example.com', $recipient->EmailReplyTo); } public function testGetEmailTemplateDropdownValues() { $form = new UserDefinedForm(); $form->write(); $recipient = new EmailRecipient(); $recipient->FormID = $form->ID; $recipient->FormClass = UserDefinedForm::class; $ds = DIRECTORY_SEPARATOR; $expected = [ "email{$ds}SubmittedFormEmail" => 'SubmittedFormEmail', "email{$ds}SubmittedFormEmailPlain" => 'SubmittedFormEmailPlain' ]; $this->assertSame($expected, $recipient->getEmailTemplateDropdownValues()); } }
php
BSD-3-Clause
e33fff165d33a077ec4b20c2eef2ef8bca25d15a
2026-01-05T05:22:58.009669Z
false
silverstripe/silverstripe-userforms
https://github.com/silverstripe/silverstripe-userforms/blob/e33fff165d33a077ec4b20c2eef2ef8bca25d15a/tests/php/Model/Recipient/EmailRecipientConditionTest.php
tests/php/Model/Recipient/EmailRecipientConditionTest.php
<?php namespace SilverStripe\UserForms\Tests\Model\Recipient; use SilverStripe\Dev\SapphireTest; use SilverStripe\UserForms\Model\Recipient\EmailRecipientCondition; /** * Class EditableCustomRulesTest */ class EmailRecipientConditionTest extends SapphireTest { protected static $fixture_file = 'EmailRecipientConditionTest.yml'; /** * Various matching tests */ public function testMatches() { $fixtureClass = EmailRecipientCondition::class; //Test Blank $blankObj = $this->objFromFixture($fixtureClass, 'blankTest'); $this->assertTrue($blankObj->matches(['Name' => null])); $this->assertFalse($blankObj->matches(['Name' => 'Jane'])); //Test IsNotBlank $blankObj = $this->objFromFixture($fixtureClass, 'isNotBlankTest'); $this->assertTrue($blankObj->matches(['Name' => 'Jane'])); $this->assertFalse($blankObj->matches(['Name' => null])); //Test ValueLessthan $blankObj = $this->objFromFixture($fixtureClass, 'valueLessThanTest'); $this->assertTrue($blankObj->matches(['Age' => 17])); $this->assertFalse($blankObj->matches(['Age' => 19])); //Test ValueLessThanEquals $blankObj = $this->objFromFixture($fixtureClass, 'valueLessThanEqualTest'); $this->assertTrue($blankObj->matches(['Age' => 18])); $this->assertFalse($blankObj->matches(['Age' => 19])); //Test ValueGreaterThan $blankObj = $this->objFromFixture($fixtureClass, 'valueGreaterThanTest'); $this->assertTrue($blankObj->matches(['Age' => 19])); $this->assertFalse($blankObj->matches(['Age' => 17])); //Test ValueGreaterThanEquals $blankObj = $this->objFromFixture($fixtureClass, 'valueGreaterThanEqualTest'); $this->assertTrue($blankObj->matches(['Age' => 18])); $this->assertFalse($blankObj->matches(['Age' => 17])); //Test Equals $blankObj = $this->objFromFixture($fixtureClass, 'equalsTest'); $this->assertTrue($blankObj->matches(['Age' => 18])); $this->assertFalse($blankObj->matches(['Age' => 17])); //Test NotEquals $blankObj = $this->objFromFixture($fixtureClass, 'notEqualsTest'); $this->assertTrue($blankObj->matches(['Age' => 17])); $this->assertFalse($blankObj->matches(['Age' => 18])); } }
php
BSD-3-Clause
e33fff165d33a077ec4b20c2eef2ef8bca25d15a
2026-01-05T05:22:58.009669Z
false
silverstripe/silverstripe-userforms
https://github.com/silverstripe/silverstripe-userforms/blob/e33fff165d33a077ec4b20c2eef2ef8bca25d15a/tests/php/Model/EditableFormField/EditableDropdownTest.php
tests/php/Model/EditableFormField/EditableDropdownTest.php
<?php namespace SilverStripe\UserForms\Tests\Model\EditableFormField; use SilverStripe\UserForms\Model\EditableFormField\EditableDropdown; use SilverStripe\Dev\SapphireTest; /** * Tests the {@see EditableDropdown} class */ class EditableDropdownTest extends SapphireTest { protected static $fixture_file = '../EditableFormFieldTest.yml'; /** * Tests that the field sets the empty string if set */ public function testFormField() { if (!$dropdown = EditableDropdown::get()->filter('UseEmptyString', true)->first()) { $dropdown = $this->objFromFixture(EditableDropdown::class, 'basic-dropdown'); $dropdown->UseEmptyString = true; $dropdown->EmptyString = 'My Default Empty String'; $dropdown->write(); } $field = $dropdown->getFormField(); $this->assertEquals($field->getEmptyString(), 'My Default Empty String'); $alternateDropdown = $this->objFromFixture(EditableDropdown::class, 'department-dropdown'); $formField = $alternateDropdown->getFormField(); $this->assertFalse($formField->getHasEmptyDefault()); $alternateDropdown->UseEmptyString = true; $alternateDropdown->write(); $this->assertEquals($formField->getEmptyString(), ''); } public function testAllowEmptyTitle() { /** @var EditableDropdown $field */ $field = EditableDropdown::create(); $field->Name = 'EditableFormField_123456'; $this->assertEmpty($field->getFormField()->Title()); } public function testDuplicate() { /** @var EditableDropdown $dropdown */ $dropdown = $this->objFromFixture(EditableDropdown::class, 'basic-dropdown'); $this->assertCount(2, $dropdown->Options()); $duplicatedDropdown = $dropdown->duplicate(); $this->assertSame($dropdown->Options()->count(), $duplicatedDropdown->Options()->count()); } }
php
BSD-3-Clause
e33fff165d33a077ec4b20c2eef2ef8bca25d15a
2026-01-05T05:22:58.009669Z
false
silverstripe/silverstripe-userforms
https://github.com/silverstripe/silverstripe-userforms/blob/e33fff165d33a077ec4b20c2eef2ef8bca25d15a/tests/php/Model/EditableFormField/EditableFileFieldTest.php
tests/php/Model/EditableFormField/EditableFileFieldTest.php
<?php namespace SilverStripe\UserForms\Tests\Model\EditableFormField; use SilverStripe\Assets\Folder; use SilverStripe\Dev\SapphireTest; use SilverStripe\Core\Validation\ValidationException; use SilverStripe\UserForms\Model\EditableFormField\EditableFileField; /** * @package userforms */ class EditableFileFieldTest extends SapphireTest { protected static $fixture_file = '../EditableFormFieldTest.yml'; /** * @var */ private $php_max_file_size; /** * Hold the server default max file size upload limit for later */ protected function setUp(): void { parent::setUp(); $editableFileField = singleton(EditableFileField::class); $this->php_max_file_size = $editableFileField::get_php_max_file_size(); } /** * Test that the field validator has the server default as the max file size upload */ public function testDefaultMaxFileSize() { $fileField = $this->objFromFixture(EditableFileField::class, 'file-field'); $formField = $fileField->getFormField(); $this->assertEquals($this->php_max_file_size, $formField->getValidator()->getAllowedMaxFileSize()); } /** * Test that validation prevents the provided upload size limit to be less than or equal to the max php size */ public function testValidateFileSizeFieldValue() { $fileField = $this->objFromFixture(EditableFileField::class, 'file-field'); $this->expectException(ValidationException::class); $fileField->MaxFileSizeMB = $this->php_max_file_size * 2; $fileField->write(); } /** * Test the field validator has the updated allowed max file size */ public function testUpdatedMaxFileSize() { $fileField = $this->objFromFixture(EditableFileField::class, 'file-field'); $fileField->MaxFileSizeMB = .25; $fileField->write(); $formField = $fileField->getFormField(); $this->assertEquals($formField->getValidator()->getAllowedMaxFileSize(), 262144); } public function testAllowEmptyTitle() { /** @var EditableFileField $field */ $field = EditableFileField::create(); $field->Name = 'EditableFormField_123456'; $this->assertEmpty($field->getFormField()->Title()); } public function testOnBeforeWrite() { $this->logOut(); /** @var EditableFileField $fileField */ $fileField = $this->objFromFixture(EditableFileField::class, 'file-field'); $defaultFolder = Folder::find('Form-submissions'); $this->assertNotEmpty($defaultFolder, 'Default Folder was created along with the EditableFileField'); $this->assertFalse($defaultFolder->canView(), 'Default Folder default to being restricted'); $this->assertFalse((bool) $fileField->FolderConfirmed, 'EditableFileField are not Folder Confirmed initially'); $this->assertEquals( $defaultFolder->ID, $fileField->FolderID, 'EditableFileField default to default form submission folder' ); $fileField->FolderID = Folder::find_or_make('boom')->ID; $fileField->write(); $this->assertTrue( (bool) $fileField->FolderConfirmed, 'EditableFileField are Folder Confirmed once you assigned them a folder' ); $secondField = EditableFileField::create(); $secondField->ParentID = $fileField->ParentID; $secondField->write(); $this->assertEquals( $fileField->FolderID, $secondField->FolderID, 'Second EditableFileField defaults to first field FolderID' ); } }
php
BSD-3-Clause
e33fff165d33a077ec4b20c2eef2ef8bca25d15a
2026-01-05T05:22:58.009669Z
false
silverstripe/silverstripe-userforms
https://github.com/silverstripe/silverstripe-userforms/blob/e33fff165d33a077ec4b20c2eef2ef8bca25d15a/tests/php/Model/EditableFormField/EditableRadioFieldTest.php
tests/php/Model/EditableFormField/EditableRadioFieldTest.php
<?php namespace SilverStripe\UserForms\Tests\Model\EditableFormField; use SilverStripe\Dev\SapphireTest; use SilverStripe\UserForms\FormField\UserFormsOptionSetField; use SilverStripe\UserForms\Model\EditableFormField\EditableRadioField; class EditableRadioFieldTest extends SapphireTest { protected static $fixture_file = '../EditableFormFieldTest.yml'; /** * Tests that this element is rendered with a custom template */ public function testRenderedWithCustomTemplate() { $radio = $this->objFromFixture(EditableRadioField::class, 'radio-field'); $this->assertSame( UserFormsOptionSetField::class, $radio->getFormField()->getTemplate() ); } public function testAllowEmptyTitle() { /** @var EditableRadioField $field */ $field = EditableRadioField::create(); $field->Name = 'EditableFormField_123456'; $this->assertEmpty($field->getFormField()->Title()); } }
php
BSD-3-Clause
e33fff165d33a077ec4b20c2eef2ef8bca25d15a
2026-01-05T05:22:58.009669Z
false
silverstripe/silverstripe-userforms
https://github.com/silverstripe/silverstripe-userforms/blob/e33fff165d33a077ec4b20c2eef2ef8bca25d15a/tests/php/Model/EditableFormField/EditableFieldGroupTest.php
tests/php/Model/EditableFormField/EditableFieldGroupTest.php
<?php namespace SilverStripe\UserForms\Tests\Model\EditableFormField; use SilverStripe\Dev\SapphireTest; use SilverStripe\UserForms\Model\EditableFormField\EditableFieldGroup; class EditableFieldGroupTest extends SapphireTest { public function testAllowEmptyTitle() { /** @var EditableFieldGroup $field */ $field = EditableFieldGroup::create(); $field->Name = 'EditableFormField_123456'; $this->assertEmpty($field->getFormField()->Title()); } }
php
BSD-3-Clause
e33fff165d33a077ec4b20c2eef2ef8bca25d15a
2026-01-05T05:22:58.009669Z
false
silverstripe/silverstripe-userforms
https://github.com/silverstripe/silverstripe-userforms/blob/e33fff165d33a077ec4b20c2eef2ef8bca25d15a/tests/php/Model/EditableFormField/EditableCheckboxTest.php
tests/php/Model/EditableFormField/EditableCheckboxTest.php
<?php namespace SilverStripe\UserForms\Tests\Model\EditableFormField; use SilverStripe\Dev\SapphireTest; use SilverStripe\UserForms\Model\EditableFormField\EditableCheckbox; class EditableCheckboxTest extends SapphireTest { public function testAllowEmptyTitle() { /** @var EditableCheckbox $field */ $field = EditableCheckbox::create(); $field->Name = 'EditableFormField_123456'; $this->assertEmpty($field->getFormField()->Title()); } }
php
BSD-3-Clause
e33fff165d33a077ec4b20c2eef2ef8bca25d15a
2026-01-05T05:22:58.009669Z
false
silverstripe/silverstripe-userforms
https://github.com/silverstripe/silverstripe-userforms/blob/e33fff165d33a077ec4b20c2eef2ef8bca25d15a/tests/php/Model/EditableFormField/EditableFormHeadingTest.php
tests/php/Model/EditableFormField/EditableFormHeadingTest.php
<?php namespace SilverStripe\UserForms\Tests\Model\EditableFormField; use SilverStripe\Dev\SapphireTest; use SilverStripe\UserForms\Model\EditableFormField\EditableFormHeading; class EditableFormHeadingTest extends SapphireTest { public function testAllowEmptyTitle() { /** @var EditableFormHeading $field */ $field = EditableFormHeading::create(); $field->Name = 'EditableFormField_123456'; $this->assertEmpty($field->getFormField()->Title()); } }
php
BSD-3-Clause
e33fff165d33a077ec4b20c2eef2ef8bca25d15a
2026-01-05T05:22:58.009669Z
false
silverstripe/silverstripe-userforms
https://github.com/silverstripe/silverstripe-userforms/blob/e33fff165d33a077ec4b20c2eef2ef8bca25d15a/tests/php/Model/EditableFormField/EditableEmailFieldTest.php
tests/php/Model/EditableFormField/EditableEmailFieldTest.php
<?php namespace SilverStripe\UserForms\Tests\Model\EditableFormField; use SilverStripe\Dev\SapphireTest; use SilverStripe\UserForms\Model\EditableFormField\EditableEmailField; class EditableEmailFieldTest extends SapphireTest { public function testAllowEmptyTitle() { /** @var EditableEmailField $field */ $field = EditableEmailField::create(); $field->Name = 'EditableFormField_123456'; $this->assertEmpty($field->getFormField()->Title()); } }
php
BSD-3-Clause
e33fff165d33a077ec4b20c2eef2ef8bca25d15a
2026-01-05T05:22:58.009669Z
false
silverstripe/silverstripe-userforms
https://github.com/silverstripe/silverstripe-userforms/blob/e33fff165d33a077ec4b20c2eef2ef8bca25d15a/tests/php/Model/EditableFormField/EditableFormStepTest.php
tests/php/Model/EditableFormField/EditableFormStepTest.php
<?php namespace SilverStripe\UserForms\Tests\Model\EditableFormField; use SilverStripe\Dev\SapphireTest; use SilverStripe\UserForms\Model\EditableFormField\EditableFormStep; class EditableFormStepTest extends SapphireTest { public function testAllowEmptyTitle() { /** @var EditableFormStep $field */ $field = EditableFormStep::create(); $field->Name = 'EditableFormField_123456'; $this->assertEmpty($field->getFormField()->Title()); } }
php
BSD-3-Clause
e33fff165d33a077ec4b20c2eef2ef8bca25d15a
2026-01-05T05:22:58.009669Z
false
silverstripe/silverstripe-userforms
https://github.com/silverstripe/silverstripe-userforms/blob/e33fff165d33a077ec4b20c2eef2ef8bca25d15a/tests/php/Model/EditableFormField/EditableTextFieldTest.php
tests/php/Model/EditableFormField/EditableTextFieldTest.php
<?php namespace SilverStripe\UserForms\Tests\Model\EditableFormField; use SilverStripe\Core\Config\Config; use SilverStripe\Dev\SapphireTest; use SilverStripe\Forms\DropdownField; use SilverStripe\UserForms\Model\EditableFormField\EditableTextField; class EditableTextFieldTest extends SapphireTest { public function testGetCmsFields() { Config::modify()->set(EditableTextField::class, 'autocomplete_options', ['foo' => 'foo']); $field = new EditableTextField; $result = $field->getCMSFields(); $autocompleteField = $result->fieldByName('Root.Main.Autocomplete'); $this->assertInstanceOf(DropdownField::class, $autocompleteField); $this->assertEquals(['foo' => 'foo'], $autocompleteField->getSource()); } public function testAllowEmptyTitle() { /** @var EditableTextField $field */ $field = EditableTextField::create(); $field->Name = 'EditableFormField_123456'; $field->Rows = 1; $this->assertEmpty($field->getFormField()->Title()); $field->Rows = 3; $this->assertEmpty($field->getFormField()->Title()); } }
php
BSD-3-Clause
e33fff165d33a077ec4b20c2eef2ef8bca25d15a
2026-01-05T05:22:58.009669Z
false
silverstripe/silverstripe-userforms
https://github.com/silverstripe/silverstripe-userforms/blob/e33fff165d33a077ec4b20c2eef2ef8bca25d15a/tests/php/Model/EditableFormField/EditableDateFieldTest.php
tests/php/Model/EditableFormField/EditableDateFieldTest.php
<?php namespace SilverStripe\UserForms\Tests\Model\EditableFormField; use SilverStripe\Dev\SapphireTest; use SilverStripe\UserForms\Model\EditableFormField\EditableDateField; class EditableDateFieldTest extends SapphireTest { public function testAllowEmptyTitle() { /** @var EditableDateField $field */ $field = EditableDateField::create(); $field->Name = 'EditableFormField_123456'; $this->assertEmpty($field->getFormField()->Title()); } }
php
BSD-3-Clause
e33fff165d33a077ec4b20c2eef2ef8bca25d15a
2026-01-05T05:22:58.009669Z
false
silverstripe/silverstripe-userforms
https://github.com/silverstripe/silverstripe-userforms/blob/e33fff165d33a077ec4b20c2eef2ef8bca25d15a/tests/php/Model/EditableFormField/EditableNumericFieldTest.php
tests/php/Model/EditableFormField/EditableNumericFieldTest.php
<?php namespace SilverStripe\UserForms\Tests\Model\EditableFormField; use SilverStripe\Dev\SapphireTest; use SilverStripe\UserForms\Model\EditableFormField\EditableNumericField; class EditableNumericFieldTest extends SapphireTest { public function testAllowEmptyTitle() { /** @var EditableNumericField $field */ $field = EditableNumericField::create(); $field->Name = 'EditableFormField_123456'; $this->assertEmpty($field->getFormField()->Title()); } public function testValidateAddsErrorWhenMinValueIsGreaterThanMaxValue() { /** @var EditableNumericField $field */ $field = EditableNumericField::create(); $field->MinValue = 10; $field->MaxValue = 5; $result = $field->validate(); $this->assertFalse($result->isValid(), 'Validation should fail when min is greater than max'); $this->assertStringContainsString('Minimum length should be less than the maximum length', json_encode($result->__serialize())); } public function testValidate() { /** @var EditableNumericField $field */ $field = EditableNumericField::create(); $field->MinValue = 5; $field->MaxValue = 10; $result = $field->validate(); $this->assertTrue($result->isValid()); } }
php
BSD-3-Clause
e33fff165d33a077ec4b20c2eef2ef8bca25d15a
2026-01-05T05:22:58.009669Z
false
silverstripe/silverstripe-userforms
https://github.com/silverstripe/silverstripe-userforms/blob/e33fff165d33a077ec4b20c2eef2ef8bca25d15a/tests/php/Model/EditableFormField/EditableCountryDropdownFieldTest.php
tests/php/Model/EditableFormField/EditableCountryDropdownFieldTest.php
<?php namespace SilverStripe\UserForms\Tests\Model\EditableFormField; use SilverStripe\Dev\SapphireTest; use SilverStripe\Forms\DropdownField; use SilverStripe\UserForms\Model\EditableFormField\EditableCountryDropdownField; class EditableCountryDropdownFieldTest extends SapphireTest { public function testGetIcon() { $field = new EditableCountryDropdownField; $this->assertStringContainsString('/images/editabledropdown.png', $field->getIcon()); } public function testAllowEmptyTitle() { /** @var EditableCountryDropdownField $field */ $field = EditableCountryDropdownField::create(); $field->Name = 'EditableFormField_123456'; $this->assertEmpty($field->getFormField()->Title()); } public function testCMSFieldsContainsDefaultValue() { /** @var EditableCountryDropdownField $field */ $field = EditableCountryDropdownField::create(); $cmsFields = $field->getCMSFields(); $defaultField = $cmsFields->dataFieldByName('Default'); $this->assertNotNull($defaultField); $this->assertInstanceOf(DropdownField::class, $defaultField); } public function testDefaultValue() { /** @var EditableCountryDropdownField $field */ $field = EditableCountryDropdownField::create(); $field->Default = 'nz'; $this->assertEquals($field->getFormField()->getValue(), 'nz'); } public function testEmptyDefaultValue() { /** @var EditableCountryDropdownField $field */ $field = EditableCountryDropdownField::create(); /** @var DropdownField $formField */ $formField = $field->getFormField(); $this->assertFalse($formField->getHasEmptyDefault()); $this->assertEmpty($formField->getEmptyString()); $field->UseEmptyString = true; $field->EmptyString = '--- empty ---'; /** @var DropdownField $formField */ $formField = $field->getFormField(); $this->assertTrue($formField->getHasEmptyDefault()); $this->assertEquals($formField->getEmptyString(), $field->EmptyString); } }
php
BSD-3-Clause
e33fff165d33a077ec4b20c2eef2ef8bca25d15a
2026-01-05T05:22:58.009669Z
false
silverstripe/silverstripe-userforms
https://github.com/silverstripe/silverstripe-userforms/blob/e33fff165d33a077ec4b20c2eef2ef8bca25d15a/tests/php/Model/EditableFormField/EditableCheckboxGroupFieldTest.php
tests/php/Model/EditableFormField/EditableCheckboxGroupFieldTest.php
<?php namespace SilverStripe\UserForms\Tests\Model\EditableFormField; use SilverStripe\Dev\SapphireTest; use SilverStripe\UserForms\FormField\UserFormsCheckboxSetField; use SilverStripe\UserForms\Model\EditableFormField\EditableCheckboxGroupField; class EditableCheckboxGroupFieldTest extends SapphireTest { protected static $fixture_file = '../EditableFormFieldTest.yml'; /** * Tests that this element is rendered with a custom template */ public function testRenderedWithCustomTemplate() { $checkboxGroup = $this->objFromFixture(EditableCheckboxGroupField::class, 'checkbox-group'); $this->assertSame(UserFormsCheckboxSetField::class, $checkboxGroup->getFormField()->getTemplate()); } public function testAllowEmptyTitle() { /** @var EditableCheckboxGroupField $field */ $field = EditableCheckboxGroupField::create(); $field->Name = 'EditableFormField_123456'; $this->assertEmpty($field->getFormField()->Title()); } }
php
BSD-3-Clause
e33fff165d33a077ec4b20c2eef2ef8bca25d15a
2026-01-05T05:22:58.009669Z
false
silverstripe/silverstripe-userforms
https://github.com/silverstripe/silverstripe-userforms/blob/e33fff165d33a077ec4b20c2eef2ef8bca25d15a/tests/php/Model/EditableFormField/EditableMemberListFieldTest.php
tests/php/Model/EditableFormField/EditableMemberListFieldTest.php
<?php namespace SilverStripe\UserForms\Tests\Model\EditableFormField; use SilverStripe\Dev\SapphireTest; use SilverStripe\Security\Group; use SilverStripe\UserForms\Model\EditableFormField\EditableMemberListField; class EditableMemberListFieldTest extends SapphireTest { protected static $fixture_file = 'EditableMemberListFieldTest.yml'; public function testAllowEmptyTitle() { /** @var EditableMemberListField $field */ $field = EditableMemberListField::create(); $field->GroupID = $this->idFromFixture(Group::class, 'a_group'); $field->Name = 'EditableFormField_123456'; $this->assertEmpty($field->getFormField()->Title()); } }
php
BSD-3-Clause
e33fff165d33a077ec4b20c2eef2ef8bca25d15a
2026-01-05T05:22:58.009669Z
false
silverstripe/silverstripe-userforms
https://github.com/silverstripe/silverstripe-userforms/blob/e33fff165d33a077ec4b20c2eef2ef8bca25d15a/tests/php/Model/EditableFormField/EditableLiteralFieldTest.php
tests/php/Model/EditableFormField/EditableLiteralFieldTest.php
<?php namespace SilverStripe\UserForms\Tests\Model\EditableFormField; use SilverStripe\Core\Config\Config; use SilverStripe\Dev\SapphireTest; use SilverStripe\Forms\CompositeField; use SilverStripe\Forms\HTMLEditor\HTMLEditorConfig; use SilverStripe\Forms\HTMLEditor\HTMLEditorField; use SilverStripe\Forms\LiteralField; use SilverStripe\UserForms\Model\EditableFormField\EditableLiteralField; /** * Tests the {@see EditableLiteralField} class */ class EditableLiteralFieldTest extends SapphireTest { protected function setUp(): void { parent::setUp(); $cmsConfig = HTMLEditorConfig::get('cms'); HTMLEditorConfig::set_active($cmsConfig); } /** * Tests the sanitisation of HTML content */ public function testSanitisation() { $rawContent = '<h1>Welcome</h1><script>alert("Hello!");</script><p>Giant Robots!</p>'; $safeContent = '<h1>Welcome</h1><p>Giant Robots!</p>'; $field = new EditableLiteralField(); // Test with sanitisation enabled Config::modify()->set(HTMLEditorField::class, 'sanitise_server_side', true); $field->setContent($rawContent); $this->assertEquals($safeContent, $field->getContent()); // Test with sanitisation disabled Config::modify()->remove(HTMLEditorField::class, 'sanitise_server_side'); $field->setContent($rawContent); $this->assertEquals($rawContent, $field->getContent()); } public function testHideLabel() { $field = new EditableLiteralField([ 'Title' => 'Test label' ]); $this->assertStringContainsString('Test label', $field->getFormField()->FieldHolder()); $this->assertEquals('Test label', $field->getFormField()->Title()); $field->HideLabel = true; $this->assertStringNotContainsString('Test label', $field->getFormField()->FieldHolder()); $this->assertEmpty($field->getFormField()->Title()); } public function testLiteralFieldHasUpdateFormFieldMethodCalled() { $field = $this->getMockBuilder(EditableLiteralField::class) ->onlyMethods(array('doUpdateFormField')) ->getMock(); $field->expects($this->once())->method('doUpdateFormField'); $field->getFormField(); } /** * LiteralFields do not allow field names, etc. Instead, the field is contained within a composite field. This * test ensures that this structure is correct. */ public function testLiteralFieldIsContainedWithinCompositeField() { $field = new EditableLiteralField; $formField = $field->getFormField(); $this->assertInstanceOf( CompositeField::class, $formField, 'Literal field is contained within a composite field' ); $this->assertInstanceOf( LiteralField::class, $formField->FieldList()->first(), 'Actual literal field exists in composite field children' ); } }
php
BSD-3-Clause
e33fff165d33a077ec4b20c2eef2ef8bca25d15a
2026-01-05T05:22:58.009669Z
false
silverstripe/silverstripe-userforms
https://github.com/silverstripe/silverstripe-userforms/blob/e33fff165d33a077ec4b20c2eef2ef8bca25d15a/tests/php/Extension/UserFormFileExtensionTest.php
tests/php/Extension/UserFormFileExtensionTest.php
<?php namespace SilverStripe\UserForms\Tests\Extension; use SilverStripe\Assets\File; use SilverStripe\Dev\SapphireTest; use SilverStripe\UserForms\Model\Submission\SubmittedFileField; use SilverStripe\UserForms\Extension\UserFormFileExtension; class UserFormFileExtensionTest extends SapphireTest { protected $usesDatabase = true; public function testUpdateIsUserFormUploadFalse() { $file = File::create(); $file->write(); $this->assertNull($file->UserFormUpload); $value = true; $file->invokeWithExtensions('updateTrackedFormUpload', $value); $this->assertFalse($value); // refresh DataObject to get latest DB changes $file = File::get()->byID($file->ID); $this->assertEquals(UserFormFileExtension::USER_FORM_UPLOAD_FALSE, $file->UserFormUpload); } public function testUpdateIsUserFormUploadTrue() { $file = File::create(); $file->write(); $this->assertNull($file->UserFormUpload); $submittedFileField = SubmittedFileField::create(); $submittedFileField->UploadedFileID = $file->ID; $submittedFileField->write(); $value = false; $file->invokeWithExtensions('updateTrackedFormUpload', $value); $this->assertTrue($value); // refresh DataObject to get latest DB changes $file = File::get()->byID($file->ID); $this->assertEquals(UserFormFileExtension::USER_FORM_UPLOAD_TRUE, $file->UserFormUpload); } }
php
BSD-3-Clause
e33fff165d33a077ec4b20c2eef2ef8bca25d15a
2026-01-05T05:22:58.009669Z
false
silverstripe/silverstripe-userforms
https://github.com/silverstripe/silverstripe-userforms/blob/e33fff165d33a077ec4b20c2eef2ef8bca25d15a/tests/php/FormField/UserFormsCheckboxSetFieldTest.php
tests/php/FormField/UserFormsCheckboxSetFieldTest.php
<?php namespace SilverStripe\UserForms\Tests\FormField; use SilverStripe\Dev\SapphireTest; use SilverStripe\UserForms\FormField\UserFormsCheckboxSetField; use SilverStripe\UserForms\Model\EditableFormField\EditableCheckboxGroupField; class UserFormsCheckboxSetFieldTest extends SapphireTest { protected static $fixture_file = '../UserFormsTest.yml'; public function testValidate() { $field = new UserFormsCheckboxSetField('Field', 'My field', ['One' => 'One', 'Two' => 'Two']); // String values $field->setValue('One'); $this->assertTrue($field->validate()->isValid()); $field->setValue('One,Two'); $this->assertTrue($field->validate()->isValid()); $field->setValue('Three,Four'); $this->assertFalse($field->validate()->isValid()); // Array values $field->setValue(array('One')); $this->assertTrue($field->validate()->isValid()); $field->setValue(array('One', 'Two')); $this->assertTrue($field->validate()->isValid()); // Invalid $field->setValue('Three'); $this->assertFalse($field->validate()->isValid()); $field->setValue(array('Three', 'Four')); $this->assertFalse($field->validate()->isValid()); } public function testCustomErrorMessageValidationAttributesHTML() { /** @var EditableCheckboxGroupField $editableCheckboxGroupField */ $editableCheckboxGroupField = $this->objFromFixture(EditableCheckboxGroupField::class, 'checkbox-group'); $editableCheckboxGroupField->Required = true; $editableCheckboxGroupField->CustomErrorMessage = 'My custom error message with \'single\' and "double" quotes'; $userFormsCheckboxSetField = $editableCheckboxGroupField->getFormField(); $html = $userFormsCheckboxSetField->renderWith(UserFormsCheckboxSetField::class)->getValue(); $attributesHTML = 'data-rule-required="true" data-msg-required="My custom error message with &amp;#039;single&amp;#039; and &amp;quot;double&amp;quot; quotes"'; $this->assertTrue(strpos($html ?? '', $attributesHTML ?? '') > 0); } }
php
BSD-3-Clause
e33fff165d33a077ec4b20c2eef2ef8bca25d15a
2026-01-05T05:22:58.009669Z
false
silverstripe/silverstripe-userforms
https://github.com/silverstripe/silverstripe-userforms/blob/e33fff165d33a077ec4b20c2eef2ef8bca25d15a/tests/php/FormField/UserFormsOptionSetFieldTest.php
tests/php/FormField/UserFormsOptionSetFieldTest.php
<?php namespace SilverStripe\UserForms\Tests\FormField; use SilverStripe\Dev\SapphireTest; use SilverStripe\UserForms\FormField\UserFormsOptionSetField; use SilverStripe\UserForms\Model\EditableFormField\EditableRadioField; class UserFormsOptionSetFieldTest extends SapphireTest { protected static $fixture_file = '../UserFormsTest.yml'; public function testCustomErrorMessageValidationAttributesHTML() { /** @var UserFormsOptionSetField $userFormsOptionSetField */ $radio = $this->objFromFixture(EditableRadioField::class, 'radio-field'); $radio->Required = true; $radio->CustomErrorMessage = 'My custom error message with \'single\' and "double" quotes'; $userFormsOptionSetField = $radio->getFormField(); $html = $userFormsOptionSetField->setTemplate(UserFormsOptionSetField::class)->Field()->getValue(); $attributesHTML = 'data-rule-required="true" data-msg-required="My custom error message with &amp;#039;single&amp;#039; and &amp;quot;double&amp;quot; quotes"'; $this->assertTrue(strpos($html ?? '', $attributesHTML ?? '') > 0); } }
php
BSD-3-Clause
e33fff165d33a077ec4b20c2eef2ef8bca25d15a
2026-01-05T05:22:58.009669Z
false
silverstripe/silverstripe-userforms
https://github.com/silverstripe/silverstripe-userforms/blob/e33fff165d33a077ec4b20c2eef2ef8bca25d15a/tests/php/Form/GridFieldAddClassesButtonTest.php
tests/php/Form/GridFieldAddClassesButtonTest.php
<?php namespace SilverStripe\UserForms\Tests\Form; use SilverStripe\CMS\Controllers\CMSMain; use SilverStripe\Control\HTTPRequest; use SilverStripe\Control\Session; use SilverStripe\Core\Injector\Injector; use SilverStripe\Dev\SapphireTest; use SilverStripe\Forms\GridField\GridField; use SilverStripe\ORM\DataList; use SilverStripe\UserForms\Form\GridFieldAddClassesButton; use SilverStripe\UserForms\Model\EditableFormField; use SilverStripe\UserForms\Model\EditableFormField\EditableDateField; use SilverStripe\UserForms\Model\EditableFormField\EditableTextField; use SilverStripe\UserForms\Model\UserDefinedForm; use Symbiote\GridFieldExtensions\GridFieldEditableColumns; class GridFieldAddClassesButtonTest extends SapphireTest { protected $usesDatabase = true; public function testHandleAddUpdatesModifiedFormData() { $this->logInWithPermission('SITETREE_EDIT_ALL'); $udf = UserDefinedForm::create(['Title' => 'MyUDF']); $udfID = $udf->write(); // Set the current controller to CMSMain to satisfy EditableFormField::getCanCreateContext() /** @var CMSMain $controller */ $controller = Injector::inst()->get(CMSMain::class); $request = new HTTPRequest('GET', '/'); $request->setSession(new Session([])); $controller->setRequest($request); $controller->setCurrentRecordID($udf->ID); $controller->pushCurrent(); $list = new DataList(EditableFormField::class); $field = EditableTextField::create([ 'ParentClass' => UserDefinedForm::class, 'ParentID' => $udfID, 'Title' => 'MyTitle', ]); $fieldID = $field->write(); $list->add($field); $gridField = new GridField('MyName', 'MyTitle', $list); $button = new GridFieldAddClassesButton([EditableTextField::class]); $request = new HTTPRequest('POST', 'url', [], [ 'Fields' => [ GridFieldEditableColumns::POST_KEY => [ $fieldID => [ 'ClassName' => EditableDateField::class, 'Title' => 'UpdatedTitle' ] ] ] ]); $gridField->setRequest($request); $button->handleAdd($gridField); $field = EditableFormField::get()->byID($fieldID); $this->assertSame(EditableDateField::class, $field->ClassName); $this->assertSame('UpdatedTitle', $field->Title); } }
php
BSD-3-Clause
e33fff165d33a077ec4b20c2eef2ef8bca25d15a
2026-01-05T05:22:58.009669Z
false
silverstripe/silverstripe-userforms
https://github.com/silverstripe/silverstripe-userforms/blob/e33fff165d33a077ec4b20c2eef2ef8bca25d15a/tests/php/Form/UserFormsRequiredFieldsValidatorTest.php
tests/php/Form/UserFormsRequiredFieldsValidatorTest.php
<?php namespace SilverStripe\UserForms\Tests\Form; use SilverStripe\CMS\Controllers\ModelAsController; use SilverStripe\Dev\Debug; use SilverStripe\Dev\SapphireTest; use SilverStripe\UserForms\Form\UserFormsRequiredFieldsValidator; use SilverStripe\UserForms\Model\UserDefinedForm; use SilverStripe\UserForms\Form\UserForm; use PHPUnit\Framework\Attributes\DataProvider; class UserFormsRequiredFieldsValidatorTest extends SapphireTest { protected static $fixture_file = '../UserFormsTest.yml'; private function getValidatorFromPage($page) { $controller = ModelAsController::controller_for($page); $form = new UserForm($controller); return $form->getValidator(); } public function testUsesUserFormsRequiredFormFieldsValidator() { $page = $this->objFromFixture(UserDefinedForm::class, 'required-custom-rules-form'); $this->assertEquals(3, $page->Fields()->count()); $validator = $this->getValidatorFromPage($page); $this->assertNotNull($validator); $this->assertInstanceOf(UserFormsRequiredFieldsValidator::class, $validator, 'Uses UserFormsRequiredFieldsValidator validator'); } public static function dataProviderValidationOfConditionalRequiredFields() { return [ 'Passes when non-conditional required field has a value' => [ [ 'required-text-field-2' => 'some text', 'radio-option-2' => 'N', 'conditional-required-text' => '' ], true ], 'Fails when conditional required is displayed but not completed' => [ [ 'required-text-field-2' => 'some text', 'radio-option-2' => 'Y', 'conditional-required-text' => '' ], false ], 'Passes when conditional required field has a value' => [ [ 'required-text-field-2' => 'some text', 'radio-option-2' => 'Y', 'conditional-required-text' => 'some more text' ], true ] ]; } /** * @param $data * @param $expected */ #[DataProvider('dataProviderValidationOfConditionalRequiredFields')] public function testValidationOfConditionalRequiredFields($data, $expected) { $page = $this->objFromFixture(UserDefinedForm::class, 'required-custom-rules-form'); $validator = $this->getValidatorFromPage($page); $this->assertNotNull($validator); $this->assertFalse( $validator->php([]), 'Fails when non-conditional required field is empty' ); $this->assertEquals($expected, $validator->php($data)); } public static function dataProviderValidationOfNestedConditionalRequiredFields() { return [ 'Fails when non-conditional required field is empty' => [[], false], 'Passes when non-conditional required field has a value' => [ [ 'required-text-field-3' => 'some text', 'radio-option-3' => 'N', 'conditional-required-text-2' => '', 'conditional-required-text-3' => '' ], true ], 'Fails when conditional required is displayed but not completed' => [ [ 'required-text-field-3' => 'some text', 'radio-option-3' => 'Y', 'conditional-required-text-2' => '', 'conditional-required-text-3' => '' ], false ], 'Passes when non-conditional required field has a value' => [ [ 'required-text-field-3' => 'some text', 'radio-option-3' => 'Y', 'conditional-required-text-2' => 'this text', 'conditional-required-text-3' => '' ], true ], 'Fails when nested conditional required is displayed but not completed' => [ [ 'required-text-field-3' => 'some text', 'radio-option-3' => 'Y', 'conditional-required-text-2' => 'Show more', 'conditional-required-text-3' => '' ], false ], 'Passes when nested conditional required field has a value' => [ [ 'required-text-field-3' => 'some text', 'radio-option-3' => 'Y', 'conditional-required-text-2' => 'Show more', 'conditional-required-text-3' => 'more text' ], true ] ]; } /** * @param string $data * @param array $expected */ #[DataProvider('dataProviderValidationOfNestedConditionalRequiredFields')] public function testValidationOfNestedConditionalRequiredFields($data, $expected) { $page = $this->objFromFixture(UserDefinedForm::class, 'required-nested-custom-rules-form'); $this->assertEquals(4, $page->Fields()->count()); $validator = $this->getValidatorFromPage($page); $this->assertNotNull($validator); $this->assertEquals($expected, $validator->php($data)); } }
php
BSD-3-Clause
e33fff165d33a077ec4b20c2eef2ef8bca25d15a
2026-01-05T05:22:58.009669Z
false
silverstripe/silverstripe-userforms
https://github.com/silverstripe/silverstripe-userforms/blob/e33fff165d33a077ec4b20c2eef2ef8bca25d15a/tests/php/Form/UserFormTest.php
tests/php/Form/UserFormTest.php
<?php namespace SilverStripe\UserForms\Tests\Form; use SilverStripe\CMS\Controllers\ModelAsController; use SilverStripe\Dev\SapphireTest; use SilverStripe\UserForms\Model\UserDefinedForm; use SilverStripe\UserForms\Form\UserForm; class UserFormTest extends SapphireTest { protected static $fixture_file = '../UserFormsTest.yml'; /** * Tests that a form will not generate empty pages */ public function testEmptyPages() { $page = $this->objFromFixture(UserDefinedForm::class, 'empty-page'); $this->assertEquals(5, $page->Fields()->count()); $controller = ModelAsController::controller_for($page); $form = new UserForm($controller); $this->assertEquals(2, $form->getSteps()->count()); } }
php
BSD-3-Clause
e33fff165d33a077ec4b20c2eef2ef8bca25d15a
2026-01-05T05:22:58.009669Z
false
silverstripe/silverstripe-userforms
https://github.com/silverstripe/silverstripe-userforms/blob/e33fff165d33a077ec4b20c2eef2ef8bca25d15a/tests/php/Control/UserDefinedFormAdminTest.php
tests/php/Control/UserDefinedFormAdminTest.php
<?php namespace SilverStripe\UserForms\Tests\Control; use SilverStripe\Assets\Folder; use SilverStripe\Dev\FunctionalTest; use SilverStripe\Security\InheritedPermissions; use SilverStripe\UserForms\Control\UserDefinedFormAdmin; use SilverStripe\UserForms\Model\EditableFormField; use SilverStripe\UserForms\Model\EditableFormField\EditableFileField; use SilverStripe\UserForms\Model\EditableFormField\EditableTextField; /** * @package userforms */ class UserDefinedFormAdminTest extends FunctionalTest { protected static $fixture_file = '../UserFormsTest.yml'; protected function setUp(): void { parent::setUp(); $submissionFolder = Folder::find('Form-submissions'); if ($submissionFolder) { $submissionFolder->delete(); } foreach (Folder::get() as $folder) { $folder->publishSingle(); } } public function testConfirmfolderformInvalidRequest() { $this->logInWithPermission(['CMS_ACCESS_CMSMain']); $url = 'admin/user-forms/confirmfolderformschema?'; $fieldID = $this->idFromFixture(EditableFileField::class, 'file-field-1'); $response = $this->get($url); $this->assertEquals(400, $response->getStatusCode(), 'Request without ID parameter is invalid'); $response = $this->get($url . http_build_query(['ID' => -1])); $this->assertEquals(400, $response->getStatusCode(), 'Request with unknown ID and known UserFormID is invalid'); } public function testConfirmfolderformAccessControl() { $url = 'admin/user-forms/confirmfolderformschema?'; $fieldID = $this->idFromFixture(EditableFileField::class, 'file-field-1'); $restrictedFieldID = $this->idFromFixture(EditableFileField::class, 'file-field-2'); $this->logInWithPermission(['CMS_ACCESS_CMSMain']); $response = $this->get($url . http_build_query(['ID' => $fieldID])); $this->assertEquals(200, $response->getStatusCode(), 'CMS editors can access confirm folder form '); $response = $this->get($url . http_build_query(['ID' => $restrictedFieldID])); $this->assertEquals( 403, $response->getStatusCode(), 'CMS editors can\'t access confirm folder form for restricted form' ); $this->logInWithPermission('ADMIN'); $response = $this->get($url . http_build_query(['ID' => $restrictedFieldID])); $this->assertEquals( 200, $response->getStatusCode(), 'Admins can access confirm folder form for restricted form' ); } public function testConfirmfolderformFields() { $url = 'admin/user-forms/confirmfolderformschema?'; $fieldID = $this->idFromFixture(EditableFileField::class, 'file-field-1'); $folderID = $this->idFromFixture(Folder::class, 'unrestricted'); $this->logInWithPermission('ADMIN'); $response = $this->get( $url . http_build_query(['ID' => $fieldID]), null, ['X-FormSchema-Request' => 'auto,schema,state,errors'] ); $schemaData = json_decode($response->getBody() ?? '', true); $this->assertEquals('ConfirmFolderForm', $schemaData['schema']['name']); $this->assertField($schemaData, 'FolderOptions', ['component' => 'OptionsetField']); $this->assertField($schemaData, 'FolderID', ['component' => 'TreeDropdownField']); $this->assertField($schemaData, 'ID', ['schemaType' =>'Hidden']); $this->assertStateValue($schemaData, ['ID' => $fieldID, 'FolderID' => $folderID]); } public function testConfirmfolderformDefaultFolder() { $url = 'admin/user-forms/confirmfolderformschema?'; $fieldID = $this->idFromFixture(EditableFileField::class, 'file-field-2'); $this->logInWithPermission('ADMIN'); $response = $this->get( $url . http_build_query(['ID' => $fieldID]), null, ['X-FormSchema-Request' => 'auto,schema,state,errors'] ); $schemaData = json_decode($response->getBody() ?? '', true); $this->assertEquals('ConfirmFolderForm', $schemaData['schema']['name']); $this->assertField($schemaData, 'FolderOptions', ['component' => 'OptionsetField']); $this->assertField($schemaData, 'FolderID', ['component' => 'TreeDropdownField']); $this->assertField($schemaData, 'ID', ['schemaType' =>'Hidden']); $folder = Folder::find('Form-submissions'); $this->assertNotEmpty($folder, 'Default submission folder has been created'); $this->assertStateValue($schemaData, ['ID' => $fieldID, 'FolderID' => $folder->ID]); $this->logOut(); $this->assertFalse($folder->canView(), 'Default submission folder is protected'); } public function testConfirmfolderInvalidRequest() { $this->logInWithPermission(['CMS_ACCESS_CMSMain', 'CMS_ACCESS_AssetAdmin']); $url = 'admin/user-forms/ConfirmFolderForm'; $response = $this->post($url, ['ID' => -1]); $this->assertEquals(400, $response->getStatusCode(), 'Request without ID parameter is invalid'); } public function testConfirmfolderAccessControl() { $url = 'admin/user-forms/ConfirmFolderForm'; $fieldID = $this->idFromFixture(EditableFileField::class, 'file-field-1'); $restrictedFieldID = $this->idFromFixture(EditableFileField::class, 'file-field-2'); $this->logInWithPermission(['CMS_ACCESS_CMSMain']); $response = $this->post($url, ['ID' => $fieldID]); $this->assertEquals( 403, $response->getStatusCode(), 'Users without CMS_ACCESS_AssetAdmin can\'t confirm folder' ); $this->logInWithPermission(['CMS_ACCESS_CMSMain', 'CMS_ACCESS_AssetAdmin']); $response = $this->post($url, ['ID' => $fieldID]); $this->assertEquals(200, $response->getStatusCode(), 'CMS editors can access confirm folder form '); $response = $this->post($url, ['ID' => $restrictedFieldID]); $this->assertEquals( 403, $response->getStatusCode(), 'CMS editors can\'t confirm folder form for restricted form' ); $this->logInWithPermission('ADMIN'); $response = $this->post($url, ['ID' => $restrictedFieldID]); $this->assertEquals( 200, $response->getStatusCode(), 'Admins can confirm folder form for restricted form' ); } public function testConfirmfolderExistingFolder() { $this->logInWithPermission(['CMS_ACCESS_CMSMain', 'CMS_ACCESS_AssetAdmin']); $url = 'admin/user-forms/ConfirmFolderForm'; $fieldID = $this->idFromFixture(EditableFileField::class, 'file-field-1'); $folderID = $this->idFromFixture(Folder::class, 'restricted'); $response = $this->post($url, ['ID' => $fieldID, 'FolderOptions' => 'existing', 'FolderID' => $folderID]); $this->assertEquals(200, $response->getStatusCode(), 'Valid request to confirm an existing folder is successful'); $this->assertEquals( $folderID, EditableFileField::get()->byID($fieldID)->FolderID, 'FileField points to restricted folder' ); } public function testConfirmfolderInexistingFolder() { $this->logInWithPermission(['CMS_ACCESS_CMSMain', 'CMS_ACCESS_AssetAdmin']); $url = 'admin/user-forms/ConfirmFolderForm'; $fieldID = $this->idFromFixture(EditableFileField::class, 'file-field-1'); $response = $this->post($url, ['ID' => $fieldID, 'FolderOptions' => 'existing', 'FolderID' => -1]); $this->assertEquals(400, $response->getStatusCode(), 'Confirm a non-existant folder fails with 400'); } public function testConfirmfolderRootFolder() { $this->logInWithPermission(['CMS_ACCESS_CMSMain', 'CMS_ACCESS_AssetAdmin']); $url = 'admin/user-forms/ConfirmFolderForm'; $fieldID = $this->idFromFixture(EditableFileField::class, 'file-field-1'); $response = $this->post($url, ['ID' => $fieldID, 'FolderOptions' => 'existing', 'FolderID' => 0]); $this->assertEquals(200, $response->getStatusCode(), 'Valid request to confirm an root folder is successful'); $this->assertEquals(0, EditableFileField::get()->byID($fieldID)->FolderID, 'FileField points to root folder'); } public function testConfirmfolderNewFolder() { $this->logInWithPermission(['CMS_ACCESS_CMSMain', 'CMS_ACCESS_AssetAdmin']); $url = 'admin/user-forms/ConfirmFolderForm'; $fieldID = $this->idFromFixture(EditableFileField::class, 'file-field-1'); $response = $this->post($url, ['ID' => $fieldID, 'FolderOptions' => 'new']); $this->assertEquals(200, $response->getStatusCode(), 'Valid request to confirm folder by creating a new one is valid'); $folder = Folder::find('Form-submissions/Form-with-upload-field'); $this->assertNotEmpty($folder, 'New folder has been created based on the UserFormPage\'s title'); $this->logOut(); $this->assertFalse($folder->canView(), 'New folder is restricted'); } public function testConfirmfolderNewFolderWithSpecificName() { $this->logInWithPermission(['CMS_ACCESS_CMSMain', 'CMS_ACCESS_AssetAdmin']); $url = 'admin/user-forms/ConfirmFolderForm'; $fieldID = $this->idFromFixture(EditableFileField::class, 'file-field-1'); $response = $this->post( $url, ['ID' => $fieldID, 'FolderOptions' => 'new', 'CreateFolder' => 'My-Custom-Folder->\'Pow'] ); $this->assertEquals(200, $response->getStatusCode(), 'Valid request to confirm folder by creating a new one is valid'); $folder = Folder::find('Form-submissions/My-Custom-Folder-Pow'); $this->assertNotEmpty($folder, 'New folder has been created based the provided CreateFolder value'); $this->logOut(); $this->assertFalse($folder->canView(), 'New folder is restricted'); } public function testConfirmfolderWithFieldTypeConversion() { $this->logInWithPermission('ADMIN'); $url = 'admin/user-forms/ConfirmFolderForm?'; $fieldID = $this->idFromFixture(EditableTextField::class, 'become-file-upload'); $response = $this->post($url, ['ID' => $fieldID, 'FolderOptions' => 'new']); $this->assertEquals(200, $response->getStatusCode(), 'Valid request to confirm folder by creating a new one is valid'); $folder = Folder::find('Form-submissions/Form-editable-only-by-admin'); $this->assertNotEmpty($folder, 'New folder has been created based on the UserFormPage\'s title'); $this->logOut(); $this->assertFalse($folder->canView(), 'New folder is restricted'); $field = EditableFormField::get()->byID($fieldID); $this->assertEquals( EditableFileField::class, $field->ClassName, 'EditableTextField has been converted to EditableFileField' ); } public function testPreserveSubmissionFolderPermission() { $folder = Folder::find_or_make('Form-submissions'); $folder->CanViewType = InheritedPermissions::ANYONE; $folder->write(); $this->logInWithPermission(['CMS_ACCESS_CMSMain', 'CMS_ACCESS_AssetAdmin']); $url = 'admin/user-forms/ConfirmFolderForm?'; $fieldID = $this->idFromFixture(EditableFileField::class, 'file-field-1'); $this->post($url, ['ID' => $fieldID, 'FolderOptions' => 'new']); $folder = Folder::find('Form-submissions'); $this->assertEquals( InheritedPermissions::ANYONE, $folder->CanViewType, 'Submission folder permissions are preserved' ); } /** * Assert that a field with the provided attribute exists in $schema. * * @param array $schema * @param string $name * @param string $component * @param $value * @param string $message */ private function assertField(array $schema, string $name, array $attributes, $message = '') { $message = $message ?: sprintf('A %s field exists with %s', $name, var_export($attributes, true)); $fields = $schema['schema']['fields']; $state = $schema['state']['fields']; $this->assertNotEmpty($fields, $message); $foundField = false; foreach ($fields as $field) { if ($field['name'] === $name) { $foundField = true; foreach ($attributes as $attr => $expectedValue) { $this->assertEquals($expectedValue, $field[$attr]); } break; } } $this->assertTrue($foundField, $message); } private function assertStateValue(array $schema, $values) { $fields = $schema['state']['fields']; $this->assertNotEmpty($fields); $foundField = false; foreach ($fields as $field) { $key = $field['name']; if (isset($values[$key])) { $this->assertEquals($values[$key], $field['value'], sprintf('%s is %s', $key, $values[$key])); } } } public function testGetFolderPermissionAccessControl() { $this->logOut(); $url = 'admin/user-forms/getfoldergrouppermissions?'; $this->logInWithPermission(['CMS_ACCESS_CMSMain', 'CMS_ACCESS_AssetAdmin']); $adminOnlyFolder = Folder::find('admin-only'); $response = $this->get($url . http_build_query(['FolderID' => $adminOnlyFolder->ID])); $this->assertEquals( 403, $response->getStatusCode(), 'Access denied for getting permission of Folder user does not have read access on' ); $this->logInWithPermission('ADMIN'); $adminOnlyFolder = Folder::find('admin-only'); $response = $this->get($url . http_build_query(['FolderID' => $adminOnlyFolder->ID])); $this->assertEquals( 200, $response->getStatusCode(), 'Access denied for getting permission of Folder user does not have read access on' ); } public function testGetFolderPermissionNonExistentFolder() { $this->logInWithPermission(['CMS_ACCESS_CMSMain', 'CMS_ACCESS_AssetAdmin']); $url = 'admin/user-forms/getfoldergrouppermissions?'; $response = $this->get($url . http_build_query(['FolderID' => -1])); $this->assertEquals( 400, $response->getStatusCode(), 'Non existent folder should fail' ); } public function testGetFolderPermissionValidRequest() { $url = 'admin/user-forms/getfoldergrouppermissions?'; $this->logInWithPermission(['CMS_ACCESS_CMSMain', 'CMS_ACCESS_AssetAdmin']); $folder = Folder::find('unrestricted'); $response = $this->get($url . http_build_query(['FolderID' => $folder->ID])); $this->assertEquals( 200, $response->getStatusCode(), 'Valid request is successfull' ); $this->assertStringContainsString('Unrestricted access, uploads will be visible to anyone', $response->getBody()); $folder = Folder::find('restricted-folder'); $response = $this->get($url . http_build_query(['FolderID' => 0])); $this->assertEquals( 200, $response->getStatusCode(), 'Valid request for root folder is successful' ); $this->assertStringContainsString('Unrestricted access, uploads will be visible to anyone', $response->getBody()); $folder = Folder::find('restricted-folder'); $response = $this->get($url . http_build_query(['FolderID' => $folder->ID])); $this->assertEquals( 200, $response->getStatusCode(), 'Valid request for root folder is successful' ); $this->assertStringContainsString('Restricted access, uploads will be visible to logged-in users ', $response->getBody()); $this->logInWithPermission('ADMIN'); $adminOnlyFolder = Folder::find('admin-only'); $response = $this->get($url . http_build_query(['FolderID' => $adminOnlyFolder->ID])); $this->assertEquals( 200, $response->getStatusCode(), 'Valid request for folder restricted to group is successful' ); $this->assertStringContainsString('Restricted access, uploads will be visible to the following groups: Administrators', $response->getBody()); } public function testGetFormSubmissionFolder() { $submissionFolder = Folder::find('Form-submissions'); $this->assertEmpty($submissionFolder, 'Submission folder does not exists initially.'); // No parameters $submissionFolder = UserDefinedFormAdmin::getFormSubmissionFolder(); $this->assertNotEmpty($submissionFolder, 'Submission folder exists after getFormSubmissionFolder call'); $this->assertEquals('Form-submissions/', $submissionFolder->getFilename(), 'Submission folder got created under correct name'); $this->assertEquals(InheritedPermissions::ONLY_THESE_USERS, $submissionFolder->CanViewType, 'Submission folder has correct permissions'); $this->assertNotEmpty($submissionFolder->ViewerGroups()->find('Code', 'administrators'), 'Submission folder is limited to administrators'); // subfolder name $submissionSubFolder = UserDefinedFormAdmin::getFormSubmissionFolder('test-form'); $this->assertNotEmpty($submissionSubFolder, 'Submission subfolder has been created'); $this->assertEquals('Form-submissions/test-form/', $submissionSubFolder->getFilename(), 'Submission sub folder got created under correct name'); $this->assertEquals(InheritedPermissions::INHERIT, $submissionSubFolder->CanViewType, 'Submission sub folder inherit permission from parent'); // make sure parent folder permission don't get overridden $submissionFolder = Folder::find('Form-submissions'); $submissionFolder->CanViewType = InheritedPermissions::INHERIT; $submissionFolder->write(); $submissionSubFolder = UserDefinedFormAdmin::getFormSubmissionFolder('test-form-2'); $submissionFolder = Folder::find('Form-submissions'); $this->assertEquals(InheritedPermissions::INHERIT, $submissionFolder->CanViewType, 'Submission sub folder inherit permission from parent'); // Submission folder get recreated $submissionFolder->delete(); $submissionFolder = Folder::find('Form-submissions'); $this->assertEmpty($submissionFolder, 'Submission folder does has been deleted.'); $submissionSubFolder = UserDefinedFormAdmin::getFormSubmissionFolder('test-form-3'); $submissionFolder = Folder::find('Form-submissions'); $this->assertNotEmpty($submissionFolder, 'Submission folder got recreated'); $this->assertEquals('Form-submissions/', $submissionFolder->getFilename(), 'Submission folder got recreated under correct name'); $this->assertEquals(InheritedPermissions::ONLY_THESE_USERS, $submissionFolder->CanViewType, 'Submission folder has correct permissions'); $this->assertNotEmpty($submissionFolder->ViewerGroups()->find('Code', 'administrators'), 'Submission folder is limited to administrators'); } }
php
BSD-3-Clause
e33fff165d33a077ec4b20c2eef2ef8bca25d15a
2026-01-05T05:22:58.009669Z
false
silverstripe/silverstripe-userforms
https://github.com/silverstripe/silverstripe-userforms/blob/e33fff165d33a077ec4b20c2eef2ef8bca25d15a/tests/php/Control/UserDefinedFormControllerTest.php
tests/php/Control/UserDefinedFormControllerTest.php
<?php namespace SilverStripe\UserForms\Tests\Control; use ReflectionClass; use SilverStripe\Assets\Dev\TestAssetStore; use SilverStripe\Assets\File; use SilverStripe\Assets\Folder; use SilverStripe\Assets\Storage\AssetStore; use SilverStripe\Assets\Upload_Validator; use SilverStripe\Control\HTTPRequest; use SilverStripe\Control\HTTPResponse; use SilverStripe\Control\Session; use SilverStripe\Core\Config\Config; use SilverStripe\Core\Injector\Injector; use SilverStripe\Dev\CSSContentParser; use SilverStripe\Dev\FunctionalTest; use SilverStripe\Forms\FieldList; use SilverStripe\Forms\FormAction; use SilverStripe\ORM\DataObject; use SilverStripe\Security\InheritedPermissions; use SilverStripe\UserForms\Control\UserDefinedFormController; use SilverStripe\UserForms\Model\EditableFormField\EditableFileField; use SilverStripe\UserForms\Model\EditableFormField\EditableTextField; use SilverStripe\UserForms\Model\Recipient\EmailRecipient; use SilverStripe\UserForms\Model\Submission\SubmittedFormField; use SilverStripe\UserForms\Model\UserDefinedForm; use SilverStripe\UserForms\Tests\Control\fixtures\SizeStringTestableController; use SilverStripe\Versioned\Versioned; use SilverStripe\Model\ArrayData; use SilverStripe\View\SSViewer; use function filesize; use PHPUnit\Framework\Attributes\DataProvider; /** * @package userforms */ class UserDefinedFormControllerTest extends FunctionalTest { protected static $fixture_file = '../UserFormsTest.yml'; protected static $disable_themes = true; protected function setUp(): void { parent::setUp(); // Set backend and base url TestAssetStore::activate('AssetStoreTest'); $config = Config::modify(); $config->set(UserDefinedFormController::class, 'maximum_email_attachment_size', "1M"); $config->merge(SSViewer::class, 'themes', ['startup-theme', '$default']); } protected function tearDown(): void { TestAssetStore::reset(); parent::tearDown(); } public function testProcess() { $form = $this->setupFormFrontend(); $controller = new UserDefinedFormController($form); $this->autoFollowRedirection = false; $this->clearEmails(); // load the form $this->get($form->URLSegment); /** @var EditableTextField $field */ $field = $this->objFromFixture(EditableTextField::class, 'basic-text'); $data = [$field->Name => 'Basic Value <b>HTML</b>']; $response = $this->submitForm('UserForm_Form_' . $form->ID, null, $data); // should have a submitted form field now $submitted = DataObject::get(SubmittedFormField::class, "\"Name\" = 'basic_text_name'"); $this->assertListAllMatch( [ 'Name' => 'basic_text_name', 'Value' => 'Basic Value <b>HTML</b>', 'Title' => 'Basic Text Field' ], $submitted ); // check emails $this->assertEmailSent('test@example.com', 'no-reply@example.com', 'Email Subject'); $email = $this->findEmail('test@example.com', 'no-reply@example.com', 'Email Subject'); // assert that the email has the field title and the value html email $parser = new CSSContentParser($email['Content']); $title = $parser->getBySelector('strong'); $this->assertEquals('Basic Text Field', (string) $title[0], 'Email contains the field name'); // submitted html tags are escaped for the html value $value = 'class="readonly">My body html Basic Value &lt;b&gt;HTML&lt;/b&gt;</span>'; $this->assertTrue(strpos($email['Content'] ?? '', $value ?? '') !== false, 'Email contains the merge field value'); $value = $parser->getBySelector('dd'); $this->assertEquals('Basic Value <b>HTML</b>', (string) $value[0], 'Email contains the value'); // no html $this->assertEmailSent('nohtml@example.com', 'no-reply@example.com', 'Email Subject'); $nohtml = $this->findEmail('nohtml@example.com', 'no-reply@example.com', 'Email Subject'); $this->assertStringContainsString('* Basic Value <b>HTML</b>', $nohtml['Content'], 'Email contains no html'); // submitted html tags are not escaped because the email is being sent as text/plain $value = 'My body text Basic Value <b>HTML</b>'; $this->assertStringContainsString($value, $nohtml['Content'], 'Email contains the merge field value'); // no data $this->assertEmailSent('nodata@example.com', 'no-reply@example.com', 'Email Subject'); $nodata = $this->findEmail('nodata@example.com', 'no-reply@example.com', 'Email Subject'); $parser = new CSSContentParser($nodata['Content']); $list = $parser->getBySelector('dl'); $this->assertEmpty($list, 'Email contains no fields'); // check to see if the user was redirected (301) $this->assertEquals($response->getStatusCode(), 302); $location = $response->getHeader('Location'); $this->assertStringContainsString('finished', $location); $this->assertStringEndsWith('#uff', $location); // check that multiple email addresses are supported in to and from $this->assertEmailSent( 'test1@example.com, test2@example.com', 'test3@example.com, test4@example.com', 'Test Email' ); } public function testValidation() { $form = $this->setupFormFrontend('email-form'); // Post with no fields $this->get($form->URLSegment); /** @var HTTPResponse $response */ $response = $this->submitForm('UserForm_Form_' . $form->ID, null, []); $this->assertStringContainsString('This field is required', $response->getBody()); // Post with all fields, but invalid email $this->get($form->URLSegment); /** @var HTTPResponse $response */ $response = $this->submitForm('UserForm_Form_' . $form->ID, null, [ 'required-email' => 'invalid', 'required-text' => 'bob' ]); $this->assertStringContainsString('Invalid email address', $response->getBody()); // Post with only required $this->get($form->URLSegment); /** @var HTTPResponse $response */ $response = $this->submitForm('UserForm_Form_' . $form->ID, null, [ 'required-text' => 'bob' ]); $this->assertStringContainsString("Thanks, we've received your submission.", $response->getBody()); } public function testFinished() { $form = $this->setupFormFrontend(); // set formProcessed and SecurityID to replicate the form being filled out $this->session()->set('SecurityID', 1); $this->session()->set('FormProcessed', 1); $response = $this->get($form->URLSegment.'/finished'); $this->assertStringContainsString($form->OnCompleteMessage, $response->getBody()); } public function testAppendingFinished() { $form = $this->setupFormFrontend(); // replicate finished being added to the end of the form URL without the form being filled out $this->session()->set('SecurityID', 1); $this->session()->set('FormProcessed', null); $response = $this->get($form->URLSegment.'/finished'); $this->assertStringNotContainsString($form->OnCompleteMessage, $response->getBody()); } public function testForm() { $form = $this->objFromFixture(UserDefinedForm::class, 'basic-form-page'); $controller = new UserDefinedFormController($form); // test form $this->assertEquals($controller->Form()->getName(), 'Form_' . $form->ID, 'The form is referenced as Form'); $this->assertEquals($controller->Form()->Fields()->Count(), 1); // disabled SecurityID token fields $this->assertEquals($controller->Form()->Actions()->Count(), 1); $this->assertEquals(count($controller->Form()->getValidator()->getRequired() ?? []), 0); $requiredForm = $this->objFromFixture(UserDefinedForm::class, 'validation-form'); $controller = new UserDefinedFormController($requiredForm); $this->assertEquals($controller->Form()->Fields()->Count(), 1); // disabled SecurityID token fields $this->assertEquals($controller->Form()->Actions()->Count(), 1); $this->assertEquals(count($controller->Form()->getValidator()->getRequired() ?? []), 1); } public function testGetFormFields() { // generating the fieldset of fields $form = $this->objFromFixture(UserDefinedForm::class, 'basic-form-page'); $controller = new UserDefinedFormController($form); $formSteps = $controller->Form()->getFormFields(); $firstStep = $formSteps->first(); $this->assertEquals($formSteps->Count(), 1); $this->assertEquals($firstStep->getChildren()->Count(), 1); // custom error message on a form field $requiredForm = $this->objFromFixture(UserDefinedForm::class, 'validation-form'); $controller = new UserDefinedFormController($requiredForm); Config::modify()->set(UserDefinedForm::class, 'required_identifier', '*'); $formSteps = $controller->Form()->getFormFields(); $firstStep = $formSteps->first(); $firstField = $firstStep->getChildren()->first(); $this->assertEquals('Custom Error Message', $firstField->getCustomValidationMessage()); $this->assertEquals($firstField->Title(), 'Required Text Field <span class=\'required-identifier\'>*</span>'); // test custom right title $field = $form->Fields()->limit(1, 1)->First(); $field->RightTitle = 'Right Title'; $field->write(); $controller = new UserDefinedFormController($form); $formSteps = $controller->Form()->getFormFields(); $firstStep = $formSteps->first(); $this->assertEquals($firstStep->getChildren()->First()->RightTitle(), "Right Title"); // test empty form $emptyForm = $this->objFromFixture(UserDefinedForm::class, 'empty-form'); $controller = new UserDefinedFormController($emptyForm); $this->assertFalse($controller->Form()->getFormFields()->exists()); } public function testGetFormActions() { // generating the fieldset of actions $form = $this->objFromFixture(UserDefinedForm::class, 'basic-form-page'); $controller = new UserDefinedFormController($form); $actions = $controller->Form()->getFormActions(); // by default will have 1 submit button which links to process $expected = new FieldList(new FormAction('process', 'Submit')); $expected->setForm($controller->Form()); $this->assertEquals($actions, $expected); // the custom popup should have a reset button and a custom text $custom = $this->objFromFixture(UserDefinedForm::class, 'form-with-reset-and-custom-action'); $controller = new UserDefinedFormController($custom); $actions = $controller->Form()->getFormActions(); $expected = new FieldList(new FormAction('process', 'Custom Button')); $clearAction = new FormAction('clearForm', 'Clear'); $expected->push($clearAction->setAttribute('type', 'reset')); $expected->setForm($controller->Form()); $this->assertEquals($actions, $expected); } public function testRenderingIntoFormTemplate() { $form = $this->setupFormFrontend(); $this->logInWithPermission('ADMIN'); $form->Content = 'This is some content without a form nested between it'; $form->publishRecursive(); $controller = new UserDefinedFormController($form); // check to see if $Form is placed in the template $index = new ArrayData($controller->index()); $parser = new CSSContentParser($index->renderWith(__CLASS__)); $this->checkTemplateIsCorrect($parser, $form); } public function testRenderingIntoTemplateWithSubstringReplacement() { $form = $this->setupFormFrontend(); $controller = new UserDefinedFormController($form); // check to see if $Form is replaced to inside the content $index = new ArrayData($controller->index()); $parser = new CSSContentParser($index->renderWith(__CLASS__)); $this->checkTemplateIsCorrect($parser, $form); } public function testRenderingIntoTemplateWithDisabledInterpolation() { $form = $this->setupFormFrontend(); $controller = new UserDefinedFormController($form); $controller->config()->set('disable_form_content_shortcode', true); // check to see if $Form is replaced to inside the content $index = new ArrayData($controller->index()); $html = $index->renderWith(__CLASS__); $parser = new CSSContentParser($html); // Assert Content has been rendered with the shortcode in place $this->assertStringContainsString('<p>Here is my form</p><p>$UserDefinedForm</p><p>Thank you for filling it out</p>', $html); // And the form in the $From area $this->assertArrayHasKey(0, $parser->getBySelector('form#UserForm_Form_' . $form->ID)); // check for the input $this->assertArrayHasKey(0, $parser->getBySelector('input.text')); } /** * Publish a form for use on the frontend * * @param string $fixtureName * @return UserDefinedForm */ protected function setupFormFrontend($fixtureName = 'basic-form-page') { $form = $this->objFromFixture(UserDefinedForm::class, $fixtureName); $this->actWithPermission('ADMIN', function () use ($form) { $form->publishRecursive(); }); return $form; } public function checkTemplateIsCorrect($parser, $form) { $this->assertArrayHasKey(0, $parser->getBySelector('form#UserForm_Form_' . $form->ID)); // check for the input $this->assertArrayHasKey(0, $parser->getBySelector('input.text')); // check for the label and the text $label = $parser->getBySelector('label.left'); $this->assertArrayHasKey(0, $label); $this->assertEquals((string) $label[0][0], "Basic Text Field", "Label contains correct field name"); // check for the action $action = $parser->getBySelector('input.action'); $this->assertArrayHasKey(0, $action); $this->assertEquals((string) $action[0]['value'], "Submit", "Submit button has default text"); } public function testRecipientSubjectMergeFields() { $form = $this->setupFormFrontend(); $recipient = $this->objFromFixture(EmailRecipient::class, 'recipient-1'); $recipient->EmailSubject = 'Email Subject: $basic_text_name'; $recipient->write(); $this->autoFollowRedirection = false; $this->clearEmails(); // load the form $this->get($form->URLSegment); $field = $this->objFromFixture(EditableTextField::class, 'basic-text'); $response = $this->submitForm('UserForm_Form_' . $form->ID, null, [$field->Name => 'Basic Value']); // should have a submitted form field now $submitted = DataObject::get(SubmittedFormField::class, "\"Name\" = 'basic_text_name'"); $this->assertListAllMatch( [ 'Name' => 'basic_text_name', 'Value' => 'Basic Value', 'Title' => 'Basic Text Field' ], $submitted ); // check emails $this->assertEmailSent('test@example.com', 'no-reply@example.com', 'Email Subject: Basic Value'); } public function testImageThumbnailCreated() { Config::modify()->set(Upload_Validator::class, 'use_is_uploaded_file', false); $userForm = $this->setupFormFrontend('upload-form'); $controller = new UserDefinedFormController($userForm); $field = $this->objFromFixture(EditableFileField::class, 'file-field-1'); $path = realpath(__DIR__ . '/fixtures/testfile.jpg'); $data = [ $field->Name => [ 'name' => 'testfile.jpg', 'type' => 'image/jpeg', 'tmp_name' => $path, 'error' => 0, 'size' => filesize($path ?? ''), ] ]; $_FILES[$field->Name] = $data[$field->Name]; $controller->getRequest()->setSession(new Session([])); $controller->process($data, $controller->Form()); /** @var File $image */ // Getting File instead of Image so that we still delete the physical file in case it was // created with the wrong ClassName // Using StartsWith in-case of existing file so was created as testfile-v2.jpg $image = File::get()->filter(['Name:StartsWith' => 'testfile'])->last(); $this->assertNotNull($image); // Assert thumbnail variant created /** @var AssetStore $store */ $store = Injector::inst()->get(AssetStore::class); $this->assertTrue($store->exists($image->getFilename(), $image->getHash(), 'FitMaxWzM1MiwyNjRd')); } public function testRecipientAttachment() { Config::modify()->set(Upload_Validator::class, 'use_is_uploaded_file', false); $userForm = $this->setupFormFrontend('upload-form'); $controller = new UserDefinedFormController($userForm); $field = $this->objFromFixture(EditableFileField::class, 'file-field-1'); $path = realpath(__DIR__ . '/fixtures/testfile.jpg'); $data = [ $field->Name => [ 'name' => 'testfile.jpg', 'type' => 'image/jpeg', 'tmp_name' => $path, 'error' => 0, 'size' => filesize($path ?? ''), ] ]; $_FILES[$field->Name] = $data[$field->Name]; $controller->getRequest()->setSession(new Session([])); $controller->process($data, $controller->Form()); // check emails $this->assertEmailSent('test@example.com', 'no-reply@example.com', 'Email Subject'); $email = $this->findEmail('test@example.com', 'no-reply@example.com', 'Email Subject'); $this->assertNotEmpty($email['AttachedFiles'], 'Recipients receive attachment by default'); // no data $this->assertEmailSent('nodata@example.com', 'no-reply@example.com', 'Email Subject'); $nodata = $this->findEmail('nodata@example.com', 'no-reply@example.com', 'Email Subject'); $this->assertEmpty($nodata['AttachedFiles'], 'Recipients with HideFormData do not receive attachment'); } public function testMissingFolderCreated() { Config::modify()->set(Upload_Validator::class, 'use_is_uploaded_file', false); $userForm = $this->setupFormFrontend('upload-form-without-folder'); $controller = UserDefinedFormController::create($userForm); $field = $this->objFromFixture(EditableFileField::class, 'file-field-3'); $path = realpath(__DIR__ . '/fixtures/testfile.jpg'); $data = [ $field->Name => [ 'name' => 'testfile.jpg', 'type' => 'image/jpeg', 'tmp_name' => $path, 'error' => 0, 'size' => filesize($path ?? ''), ] ]; $_FILES[$field->Name] = $data[$field->Name]; $controller->getRequest()->setSession(new Session([])); $folderExistBefore = $field->getFolderExists(); $stageBefore = Versioned::get_stage(); $controller->process($data, $controller->Form()); $field = EditableFileField::get()->setUseCache(true)->byID($field->ID); $filter = [ 'ParentID' => $field->Folder()->ID, 'Name' => 'testfile.jpg', ]; $fileDraftCount = Versioned::get_by_stage(File::class, Versioned::DRAFT)->filter($filter)->count(); $fileLiveCount = Versioned::get_by_stage(File::class, Versioned::LIVE)->filter($filter)->count(); $folderExistAfter = $field->getFolderExists(); $this->assertFalse($folderExistBefore); $this->assertTrue($folderExistAfter); $this->assertEquals($stageBefore, Versioned::get_stage()); $this->assertEquals(1, $fileDraftCount); $this->assertEquals(0, $fileLiveCount); } public function testEmailAttachmentMaximumSizeCanBeConfigured() { $udfController = new UserDefinedFormController(); $config = Config::modify(); $config->set(UserDefinedFormController::class, 'maximum_email_attachment_size', '1M'); $this->assertSame(1 * 1024 * 1024, $udfController->getMaximumAllowedEmailAttachmentSize()); $config->set(UserDefinedFormController::class, 'maximum_email_attachment_size', '5M'); $this->assertSame(5 * 1024 * 1024, $udfController->getMaximumAllowedEmailAttachmentSize()); } public static function getParseByteSizeStringTestValues() { return [ ['9846', 9846], ['1048576', 1048576], ['1k', 1024], ['1K', 1024], ['4k', 4096], ['4K', 4096], ['1kb', 1024], ['1KB', 1024], ['4kB', 4096], ['4Kb', 4096], ['1m', 1048576], ['1M', 1048576], ['4mb', 4194304], ['4MB', 4194304], ['25mB', 26214400], ['25Mb', 26214400], ['1g', 1073741824], ['2GB', 2147483648], ]; } #[DataProvider('getParseByteSizeStringTestValues')] public function testParseByteSizeString($input, $expectedOutput) { $controller = new SizeStringTestableController(); // extends UserDefinedFormController $this->assertSame($expectedOutput, $controller->convertSizeStringToBytes($input)); } public static function getParseByteSizeStringTestBadValues() { return [ ['1234b'], ['9846B'], ['1kilobyte'], ['1 K'], ['Four kilobytes'], ['4Mbs'], ['12Gigs'], ]; } /** * @expectedException \InvalidArgumentException */ #[DataProvider('getParseByteSizeStringTestBadValues')] public function testParseByteSizeStringBadValuesThrowException($input) { $this->expectException('\InvalidArgumentException'); $controller = new SizeStringTestableController(); // extends UserDefinedFormController $controller->convertSizeStringToBytes($input); } public static function provideValidEmailsToArray() { return [ [ 'input' => [ null ], 'expected' => [], ], [ 'input' => [ ' , , ' ], 'expected' => [], ], [ 'input' => [ 'broken.email, broken@.email, broken2.@email' ], 'expected' => [], ], [ 'input' => [ ', broken@email, email@-email.com,correctemail@email.com,' ], 'expected' => [ 'correctemail@email.com' ], ], [ 'input' => [ 'correctemail1@email.com, correctemail2@email.com, correctemail3@email.com' ], 'expected' => [ 'correctemail1@email.com', 'correctemail2@email.com', 'correctemail3@email.com' ], ] ]; } /** * Test that provided email is valid */ #[DataProvider('provideValidEmailsToArray')] public function testValidEmailsToArray(array $input, array $expected) { $class = new ReflectionClass(UserDefinedFormController::class); $method = $class->getMethod('validEmailsToArray'); $controller = new UserDefinedFormController(); $this->assertEquals($expected, $method->invokeArgs($controller, $input)); } }
php
BSD-3-Clause
e33fff165d33a077ec4b20c2eef2ef8bca25d15a
2026-01-05T05:22:58.009669Z
false
silverstripe/silverstripe-userforms
https://github.com/silverstripe/silverstripe-userforms/blob/e33fff165d33a077ec4b20c2eef2ef8bca25d15a/tests/php/Control/fixtures/SizeStringTestableController.php
tests/php/Control/fixtures/SizeStringTestableController.php
<?php namespace SilverStripe\UserForms\Tests\Control\fixtures; use SilverStripe\Dev\TestOnly; use SilverStripe\UserForms\Control\UserDefinedFormController; class SizeStringTestableController extends UserDefinedFormController implements TestOnly { public function convertSizeStringToBytes($sizeString) { return $this->parseByteSizeString($sizeString); } }
php
BSD-3-Clause
e33fff165d33a077ec4b20c2eef2ef8bca25d15a
2026-01-05T05:22:58.009669Z
false
silverstripe/silverstripe-userforms
https://github.com/silverstripe/silverstripe-userforms/blob/e33fff165d33a077ec4b20c2eef2ef8bca25d15a/code/UserForm.php
code/UserForm.php
<?php namespace SilverStripe\UserForms; use Colymba\BulkManager\BulkManager; use SilverStripe\Forms\CheckboxField; use SilverStripe\Forms\CompositeField; use SilverStripe\Forms\FieldList; use SilverStripe\Forms\GridField\GridField; use SilverStripe\Forms\GridField\GridFieldButtonRow; use SilverStripe\Forms\GridField\GridFieldConfig; use SilverStripe\Forms\GridField\GridFieldDataColumns; use SilverStripe\Forms\GridField\GridFieldDeleteAction; use SilverStripe\Forms\GridField\GridFieldDetailForm; use SilverStripe\Forms\GridField\GridFieldEditButton; use SilverStripe\Forms\GridField\GridFieldExportButton; use SilverStripe\Forms\GridField\GridFieldPageCount; use SilverStripe\Forms\GridField\GridFieldPaginator; use SilverStripe\Forms\GridField\GridFieldPrintButton; use SilverStripe\Forms\GridField\GridFieldSortableHeader; use SilverStripe\Forms\GridField\GridFieldToolbarHeader; use SilverStripe\Forms\HTMLEditor\HTMLEditorField; use SilverStripe\Forms\LabelField; use SilverStripe\Forms\LiteralField; use SilverStripe\Forms\TextField; use SilverStripe\Forms\Validation\CompositeValidator; use SilverStripe\Model\List\ArrayList; use SilverStripe\ORM\DB; use SilverStripe\UserForms\Extension\UserFormFieldEditorExtension; use SilverStripe\UserForms\Extension\UserFormValidator; use SilverStripe\UserForms\Form\UserFormsGridFieldFilterHeader; use SilverStripe\UserForms\Model\Recipient\EmailRecipient; use SilverStripe\UserForms\Model\Submission\SubmittedForm; use SilverStripe\UserForms\Model\EditableFormField; use SilverStripe\View\Requirements; use SilverStripe\Core\Config\Configurable; /** * Defines the user defined functionality to be applied to any {@link DataObject} * * @mixin UserFormFieldEditorExtension */ trait UserForm { use Configurable; /** * Built in extensions required by this page. * * @config * @var array */ private static $extensions = [ UserFormFieldEditorExtension::class ]; /** * @var string Required Identifier */ private static $required_identifier = null; /** * @var string */ private static $email_template_directory = 'silverstripe/userforms:templates/email/'; /** * Should this module automatically upgrade on db build? * * @config * @var bool * @deprecated 6.1.0 Will be removed without equivalent functionality to replace it in a future major release. */ private static $upgrade_on_build = true; /** * Set this to true to disable automatic inclusion of CSS files * @config * @var bool */ private static $block_default_userforms_css = false; /** * Set this to true to disable automatic inclusion of JavaScript files * @config * @var bool */ private static $block_default_userforms_js = false; /** * @var array Fields on the user defined form page. */ private static $db = [ 'SubmitButtonText' => 'Varchar', 'ClearButtonText' => 'Varchar', 'OnCompleteMessage' => 'HTMLText', 'ShowClearButton' => 'Boolean', 'DisableSaveSubmissions' => 'Boolean', 'EnableLiveValidation' => 'Boolean', 'DisplayErrorMessagesAtTop' => 'Boolean', 'DisableAuthenicatedFinishAction' => 'Boolean', 'DisableCsrfSecurityToken' => 'Boolean' ]; /** * @var array Default values of variables when this page is created */ private static $defaults = [ 'Content' => '$UserDefinedForm', 'DisableSaveSubmissions' => 0, ]; /** * @var array */ private static $has_many = [ 'EmailRecipients' => EmailRecipient::class, 'Submissions' => SubmittedForm::class, ]; private static $cascade_deletes = [ 'EmailRecipients', ]; private static $cascade_duplicates = [ 'EmailRecipients', ]; /** * @var array * @config */ private static $casting = [ 'ErrorContainerID' => 'Text' ]; private static array $scaffold_cms_fields_settings = [ 'ignoreFields' => [ 'OnCompleteMessageLabel', 'OnCompleteMessage', 'DisableSaveSubmissions', ], 'ignoreRelations' => [ 'Submissions', ], ]; /** * Error container selector which matches the element for grouped messages * * @var string * @config */ private static $error_container_id = 'error-container'; /** * The configuration used to determine whether a confirmation message is to * appear when navigating away from a partially completed form. * * @var boolean * @config */ private static $enable_are_you_sure = true; /** * @var bool * @config */ private static $recipients_warning_enabled = false; private static $non_live_permissions = ['SITETREE_VIEW_ALL']; /** * @var array */ public function populateDefaults() { parent::populateDefaults(); $this->OnCompleteMessage = '<p>' . _t('SilverStripe\\UserForms\\Model\\UserDefinedForm.ONCOMPLETEMESSAGE', 'Thanks, we\'ve received your submission.') . '</p>'; } /** * @return FieldList */ public function getCMSFields() { Requirements::css('silverstripe/userforms:client/dist/styles/userforms-cms.css'); $this->beforeUpdateCMSFields(function (FieldList $fields) { $fields->findTab('Root.EmailRecipients') ?->setName('Recipients') ?->setTitle(_t('SilverStripe\\UserForms\\Model\\UserDefinedForm.RECIPIENTS', 'Recipients')); $fields->dataFieldByName('EmailRecipients')?->setTitle(''); // Configuration options $fields->findOrMakeTab('Root.FormOptions')->setTitle(_t('SilverStripe\\UserForms\\Model\\UserDefinedForm.CONFIGURATION', 'Configuration')); $fields->addFieldsToTab('Root.FormOptions', [ // text to show on complete CompositeField::create( $label = LabelField::create( 'OnCompleteMessageLabel', _t('SilverStripe\\UserForms\\Model\\UserDefinedForm.ONCOMPLETELABEL', 'Show on completion') ), $editor = HTMLEditorField::create( 'OnCompleteMessage', '', $this->OnCompleteMessage ) )->addExtraClass('field'), ...$this->getFormOptions()->toArray(), CheckboxField::create( 'DisableSaveSubmissions', _t('SilverStripe\\UserForms\\Model\\UserDefinedForm.SAVESUBMISSIONS', 'Disable Saving Submissions to Server') ) ]); $editor->setRows(3); $label->addExtraClass('left'); $submissions = $this->getSubmissionsGridField(); $fields->findOrMakeTab('Root.Submissions')->setTitle(_t('SilverStripe\\UserForms\\Model\\UserDefinedForm.SUBMISSIONS', 'Submissions')); $fields->addFieldToTab('Root.Submissions', $submissions); // Fix tab order - otherwise recipients comes too early due to being scaffolded $fields->findTab('Root')->changeTabOrder(['Main', 'FormOptions', 'Recipients', 'Submissions']); }); $fields = parent::getCMSFields(); if ($this->EmailRecipients()->Count() == 0 && static::config()->recipients_warning_enabled) { $fields->addFieldToTab('Root.Main', LiteralField::create( 'EmailRecipientsWarning', '<p class="alert alert-warning">' . _t( 'SilverStripe\\UserForms\\Model\\UserDefinedForm.NORECIPIENTS', 'Warning: You have not configured any recipients. Form submissions may be missed.' ) . '</p>' ), 'Title'); } return $fields; } public function getSubmissionsGridField() { // view the submissions // make sure a numeric not a empty string is checked against this int column for SQL server $parentID = (!empty($this->ID)) ? (int) $this->ID : 0; // get a list of all field names and values used for print and export CSV views of the GridField below. $columnSQL = <<<SQL SELECT DISTINCT "SubmittedFormField"."Name" as "Name", REPLACE(COALESCE("EditableFormField"."Title", "SubmittedFormField"."Title"), '.', ' ') as "Title", COALESCE("EditableFormField"."Sort", 999) AS "Sort" FROM "SubmittedFormField" LEFT JOIN "SubmittedForm" ON "SubmittedForm"."ID" = "SubmittedFormField"."ParentID" LEFT JOIN "EditableFormField" ON "EditableFormField"."Name" = "SubmittedFormField"."Name" WHERE "SubmittedForm"."ParentID" = '$parentID' AND "EditableFormField"."ParentID" = '$parentID' ORDER BY "Sort", "Title" SQL; $columns = DB::query($columnSQL)->map(); $config = GridFieldConfig::create(); $config->addComponent(new GridFieldToolbarHeader()); $config->addComponent(new GridFieldSortableHeader()); $config->addComponent($filter = new UserFormsGridFieldFilterHeader()); $config->addComponent(new GridFieldDataColumns()); $config->addComponent(new GridFieldEditButton()); $config->addComponent(new GridFieldDeleteAction()); $config->addComponent(new GridFieldPageCount('toolbar-header-right')); $config->addComponent(new GridFieldPaginator(25)); $config->addComponent(new GridFieldDetailForm(null, true, false)); $config->addComponent(new GridFieldButtonRow('after')); $config->addComponent($export = new GridFieldExportButton('buttons-after-left')); $config->addComponent($print = new GridFieldPrintButton('buttons-after-left')); // show user form items in the summary tab $summaryarray = SubmittedForm::singleton()->summaryFields(); foreach (EditableFormField::get()->filter(['ParentID' => $parentID, 'ShowInSummary' => 1]) as $eff) { $summaryarray[$eff->Name] = $eff->Title ?: $eff->Name; } $config->getComponentByType(GridFieldDataColumns::class)->setDisplayFields($summaryarray); /** * Support for {@link https://github.com/colymba/GridFieldBulkEditingTools} */ if (class_exists(BulkManager::class)) { $config->addComponent(new BulkManager); } // attach every column to the print view form $columns['Created'] = 'Created'; $columns['SubmittedBy.Email'] = 'Submitter'; $filter->setColumns($columns); // print configuration $print->setPrintHasHeader(true); $print->setPrintColumns($columns); // export configuration $export->setCsvHasHeader(true); $export->setExportColumns($columns); $submissions = GridField::create( 'Submissions', '', $this->Submissions()->sort('Created', 'DESC'), $config ); $this->extend('updateSubmissionsGridField', $submissions); return $submissions; } /** * Allow overriding the EmailRecipients on a {@link Extension} * so you can customise who receives an email. * Converts the RelationList to an ArrayList so that manipulation * of the original source data isn't possible. * * @return ArrayList<EmailRecipient> */ public function FilteredEmailRecipients($data = null, $form = null) { $recipients = ArrayList::create($this->EmailRecipients()->toArray()); // Filter by rules $recipients = $recipients->filterByCallback(function ($recipient) use ($data, $form) { /** @var EmailRecipient $recipient */ return $recipient->canSend($data, $form); }); $this->extend('updateFilteredEmailRecipients', $recipients, $data, $form); return $recipients; } /** * Custom options for the form. You can extend the built in options by * using {@link updateFormOptions()} * * @return FieldList */ public function getFormOptions() { $submit = ($this->SubmitButtonText) ? $this->SubmitButtonText : _t('SilverStripe\\UserForms\\Model\\UserDefinedForm.SUBMITBUTTON', 'Submit'); $clear = ($this->ClearButtonText) ? $this->ClearButtonText : _t('SilverStripe\\UserForms\\Model\\UserDefinedForm.CLEARBUTTON', 'Clear'); $options = FieldList::create( TextField::create('SubmitButtonText', _t('SilverStripe\\UserForms\\Model\\UserDefinedForm.TEXTONSUBMIT', 'Text on submit button:'), $submit), TextField::create('ClearButtonText', _t('SilverStripe\\UserForms\\Model\\UserDefinedForm.TEXTONCLEAR', 'Text on clear button:'), $clear), CheckboxField::create('ShowClearButton', _t('SilverStripe\\UserForms\\Model\\UserDefinedForm.SHOWCLEARFORM', 'Show Clear Form Button'), $this->ShowClearButton), CheckboxField::create('EnableLiveValidation', _t('SilverStripe\\UserForms\\Model\\UserDefinedForm.ENABLELIVEVALIDATION', 'Enable live validation')), CheckboxField::create('DisplayErrorMessagesAtTop', _t('SilverStripe\\UserForms\\Model\\UserDefinedForm.DISPLAYERRORMESSAGESATTOP', 'Display error messages above the form?')), CheckboxField::create('DisableCsrfSecurityToken', _t('SilverStripe\\UserForms\\Model\\UserDefinedForm.DISABLECSRFSECURITYTOKEN', 'Disable CSRF Token')), CheckboxField::create('DisableAuthenicatedFinishAction', _t('SilverStripe\\UserForms\\Model\\UserDefinedForm.DISABLEAUTHENICATEDFINISHACTION', 'Disable Authentication on finish action')) ); $this->extend('updateFormOptions', $options); return $options; } /** * Get the HTML id of the error container displayed above the form. * * @return string */ public function getErrorContainerID() { return $this->config()->get('error_container_id'); } public function getCMSCompositeValidator(): CompositeValidator { $validator = parent::getCMSCompositeValidator(); $validator->addValidator(UserFormValidator::create()); return $validator; } }
php
BSD-3-Clause
e33fff165d33a077ec4b20c2eef2ef8bca25d15a
2026-01-05T05:22:58.009669Z
false
silverstripe/silverstripe-userforms
https://github.com/silverstripe/silverstripe-userforms/blob/e33fff165d33a077ec4b20c2eef2ef8bca25d15a/code/Model/UserDefinedForm.php
code/Model/UserDefinedForm.php
<?php namespace SilverStripe\UserForms\Model; use Page; use SilverStripe\UserForms\UserForm; use SilverStripe\UserForms\Control\UserDefinedFormController; /** * @package userforms * @method SilverStripe\ORM\HasManyList<SilverStripe\UserForms\Model\Recipient\EmailRecipient> EmailRecipients() * @method SilverStripe\ORM\HasManyList<SilverStripe\UserForms\Model\Submission\SubmittedForm> Submissions() */ class UserDefinedForm extends Page { use UserForm; /** * @var string */ private static $cms_icon_class = 'font-icon-p-list'; private static $class_description = 'Adds a customizable form.'; /** * @var string */ private static $table_name = 'UserDefinedForm'; /** * @var string */ private static $controller_name = UserDefinedFormController::class; }
php
BSD-3-Clause
e33fff165d33a077ec4b20c2eef2ef8bca25d15a
2026-01-05T05:22:58.009669Z
false
silverstripe/silverstripe-userforms
https://github.com/silverstripe/silverstripe-userforms/blob/e33fff165d33a077ec4b20c2eef2ef8bca25d15a/code/Model/EditableCustomRule.php
code/Model/EditableCustomRule.php
<?php namespace SilverStripe\UserForms\Model; use InvalidArgumentException; use LogicException; use SilverStripe\CMS\Controllers\CMSMain; use SilverStripe\Control\Controller; use SilverStripe\Core\Convert; use SilverStripe\ORM\DataObject; use SilverStripe\Security\Member; use SilverStripe\Versioned\Versioned; /** * A custom rule for showing / hiding an EditableFormField * based the value of another EditableFormField. * * @property string $ConditionOption * @property int $ConditionFieldID * @property string $Display * @property string $FieldValue * @property int $ParentID * @method EditableFormField ConditionField() * @method EditableFormField Parent() */ class EditableCustomRule extends DataObject { private static $condition_options = [ 'IsBlank' => 'Is blank', 'IsNotBlank' => 'Is not blank', 'HasValue' => 'Equals', 'ValueNot' => 'Doesn\'t equal', 'ValueLessThan' => 'Less than', 'ValueLessThanEqual' => 'Less than or equal', 'ValueGreaterThan' => 'Greater than', 'ValueGreaterThanEqual' => 'Greater than or equal' ]; private static $db = [ 'Display' => 'Enum("Show,Hide")', 'ConditionOption' => 'Enum("IsBlank,IsNotBlank,HasValue,ValueNot,ValueLessThan,ValueLessThanEqual,ValueGreaterThan,ValueGreaterThanEqual")', 'FieldValue' => 'Varchar(255)' ]; private static $has_one = [ 'Parent' => EditableFormField::class, 'ConditionField' => EditableFormField::class ]; /** * Built in extensions required * * @config * @var array */ private static $extensions = [ Versioned::class . "('Stage', 'Live')" ]; private static $table_name = 'EditableCustomRule'; /** * @param Member $member * @return bool */ public function canDelete($member = null) { return $this->canEdit($member); } /** * @param Member $member * @return bool */ public function canEdit($member = null) { return $this->Parent()->canEdit($member); } /** * @param Member $member * @return bool */ public function canView($member = null) { return $this->Parent()->canView($member); } /** * Return whether a user can create an object of this type * * @param Member $member * @param array $context Virtual parameter to allow context to be passed in to check * @return bool */ public function canCreate($member = null, $context = []) { // Check parent page $parent = $this->getCanCreateContext(func_get_args()); if ($parent) { return $parent->canEdit($member); } // Fall back to secure admin permissions return parent::canCreate($member); } /** * Helper method to check the parent for this object * * @param array $args List of arguments passed to canCreate * @return DataObject Some parent dataobject to inherit permissions from */ protected function getCanCreateContext($args) { // Inspect second parameter to canCreate for a 'Parent' context if (isset($args[1]['Parent'])) { return $args[1]['Parent']; } // Hack in currently edited page if context is missing $controller = Controller::curr(); if ($controller instanceof CMSMain) { return $controller->currentRecord(); } // No page being edited return null; } /** * @param Member $member * @return bool */ public function canPublish($member = null) { return $this->canEdit($member); } /** * @param Member $member * @return bool */ public function canUnpublish($member = null) { return $this->canDelete($member); } /** * Substitutes configured rule logic with it's JS equivalents and returns them as array elements * * @return array * @throws LogicException If the provided condition option was not able to be handled */ public function buildExpression() { $formFieldWatch = $this->ConditionField(); //Encapsulated the action to the object $action = $formFieldWatch->getJsEventHandler(); // is this field a special option field $checkboxField = $formFieldWatch->isCheckBoxField(); $radioField = $formFieldWatch->isRadioField(); $target = sprintf('$("%s")', $formFieldWatch->getSelectorFieldOnly()); $fieldValue = Convert::raw2js($this->FieldValue); $conditionOptions = [ 'ValueLessThan' => '<', 'ValueLessThanEqual' => '<=', 'ValueGreaterThan' => '>', 'ValueGreaterThanEqual' => '>=' ]; // and what should we evaluate switch ($this->ConditionOption) { case 'IsNotBlank': case 'IsBlank': $expression = ($checkboxField || $radioField) ? "!{$target}.is(\":checked\")" : "{$target}.val() == ''"; if ((string) $this->ConditionOption === 'IsNotBlank') { //Negate $expression = "!({$expression})"; } break; case 'HasValue': case 'ValueNot': if ($checkboxField) { if ($formFieldWatch->isCheckBoxGroupField()) { $expression = sprintf( "$.inArray('%s', %s.filter(':checked').map(function(){ return $(this).val();}).get()) > -1", $fieldValue, $target ); } else { $expression = "{$target}.prop('checked')"; } } elseif ($radioField) { // We cannot simply get the value of the radio group, we need to find the checked option first. $expression = sprintf( '%s.closest(".field, .control-group").find("input:checked").val() == "%s"', $target, $fieldValue ); } else { $expression = sprintf('%s.val() == "%s"', $target, $fieldValue); } if ((string) $this->ConditionOption === 'ValueNot') { //Negate $expression = "!({$expression})"; } break; case 'ValueLessThan': case 'ValueLessThanEqual': case 'ValueGreaterThan': case 'ValueGreaterThanEqual': $expression = sprintf( '%s.val() %s parseFloat("%s")', $target, $conditionOptions[$this->ConditionOption], $fieldValue ); break; default: throw new LogicException("Unhandled rule {$this->ConditionOption}"); break; } $result = [ 'operation' => $expression, 'event' => $action, ]; return $result; } /** * Determines whether the rule is satisfied, based on provided form data. * Used for php validation of required conditional fields * * @param array $data Submitted form data * @return boolean * @throws LogicException Invalid ConditionOption is set for this rule. */ public function validateAgainstFormData(array $data) { $controllingField = $this->ConditionField(); if (!isset($data[$controllingField->Name])) { return false; } $valid = false; $targetFieldValue = $this->FieldValue; $actualFieldValue = $data[$controllingField->Name]; switch ($this->ConditionOption) { case 'IsNotBlank': $valid = ($actualFieldValue !== ''); break; case 'IsBlank': $valid = ($actualFieldValue === ''); break; case 'HasValue': $valid = ($actualFieldValue === $targetFieldValue); break; case 'ValueNot': $valid = ($actualFieldValue !== $targetFieldValue); break; case 'ValueLessThan': $valid = ($actualFieldValue < $targetFieldValue); break; case 'ValueLessThanEqual': $valid = ($actualFieldValue <= $targetFieldValue); break; case 'ValueGreaterThan': $valid = ($actualFieldValue > $targetFieldValue); break; case 'ValueGreaterThanEqual': $valid = ($actualFieldValue >= $targetFieldValue); break; default: throw new LogicException("Unhandled rule {$this->ConditionOption}"); break; } return $valid; } /** * Returns the opposite visibility function for the value of the initial visibility field, e.g. show/hide. This * will toggle the "hide" class either way, which is handled by CSS. * * @param string $initialState * @param boolean $invert * @return string */ public function toggleDisplayText($initialState, $invert = false) { $action = strtolower($initialState ?? '') === 'hide' ? 'removeClass' : 'addClass'; if ($invert) { $action = $action === 'removeClass' ? 'addClass' : 'removeClass'; } return sprintf('%s("hide")', $action); } /** * Returns an event name to be dispatched when the field is changed. Matches up with the visibility classes * added or removed in `toggleDisplayText()`. * * @param string $initialState * @param bool $invert * @return string */ public function toggleDisplayEvent($initialState, $invert = false) { $action = strtolower($initialState ?? '') === 'hide' ? 'show' : 'hide'; if ($invert) { $action = $action === 'hide' ? 'show' : 'hide'; } return sprintf('userform.field.%s', $action); } }
php
BSD-3-Clause
e33fff165d33a077ec4b20c2eef2ef8bca25d15a
2026-01-05T05:22:58.009669Z
false
silverstripe/silverstripe-userforms
https://github.com/silverstripe/silverstripe-userforms/blob/e33fff165d33a077ec4b20c2eef2ef8bca25d15a/code/Model/EditableFormField.php
code/Model/EditableFormField.php
<?php namespace SilverStripe\UserForms\Model; use SilverStripe\CMS\Controllers\CMSMain; use SilverStripe\CMS\Controllers\CMSPageEditController; use SilverStripe\Control\Controller; use SilverStripe\Core\ClassInfo; use SilverStripe\Core\Config\Config; use SilverStripe\Core\Manifest\ModuleLoader; use SilverStripe\Forms\CheckboxField; use SilverStripe\Forms\DropdownField; use SilverStripe\Forms\FieldList; use SilverStripe\Forms\FormField; use SilverStripe\Forms\GridField\GridField; use SilverStripe\Forms\GridField\GridFieldButtonRow; use SilverStripe\Forms\GridField\GridFieldConfig; use SilverStripe\Forms\GridField\GridFieldDeleteAction; use SilverStripe\Forms\GridField\GridFieldToolbarHeader; use SilverStripe\Forms\LiteralField; use SilverStripe\Forms\ReadonlyField; use SilverStripe\Forms\SegmentField; use SilverStripe\Forms\TabSet; use SilverStripe\Forms\TextField; use SilverStripe\ORM\DataObject; use SilverStripe\ORM\DB; use SilverStripe\ORM\FieldType\DBField; use SilverStripe\ORM\FieldType\DBVarchar; use SilverStripe\ORM\HasManyList; use SilverStripe\Core\Validation\ValidationException; use SilverStripe\Forms\Validation\CompositeValidator; use SilverStripe\UserForms\Extension\UserFormFieldEditorExtension; use SilverStripe\UserForms\Model\EditableFormField\EditableFieldGroup; use SilverStripe\UserForms\Model\EditableFormField\EditableFieldGroupEnd; use SilverStripe\UserForms\Model\EditableFormField\EditableFormStep; use SilverStripe\UserForms\Model\Submission\SubmittedFormField; use SilverStripe\UserForms\Modifier\DisambiguationSegmentFieldModifier; use SilverStripe\UserForms\Modifier\UnderscoreSegmentFieldModifier; use SilverStripe\Versioned\Versioned; use Symbiote\GridFieldExtensions\GridFieldAddNewInlineButton; use Symbiote\GridFieldExtensions\GridFieldEditableColumns; /** * Represents the base class of a editable form field * object like {@link EditableTextField}. * * @package userforms * * @property string $CustomErrorMessage * @property string $Default * @property string $DisplayRulesConjunction * @property string $ExtraClass * @property string $Name * @property int $ParentID * @property string $Placeholder * @property string $RightTitle * @property bool $Required * @property int $ShowInSummary * @property int $ShowOnLoad * @property int $Sort * @mixin Versioned * @method HasManyList<EditableCustomRule> DisplayRules() * @method DataObject Parent() */ class EditableFormField extends DataObject { /** * Set to true to hide from class selector * * @config * @var bool */ private static $hidden = false; /** * Define this field as abstract (not inherited) * * @config * @var bool */ private static $abstract = true; /** * Flag this field type as non-data (e.g. literal, header, html) * * @config * @var bool */ private static $literal = false; /** * Default sort order * * @config * @var string */ private static $default_sort = '"Sort"'; /** * A list of CSS classes that can be added * * @var array */ public static $allowed_css = []; /** * Set this to true to enable placeholder field for any given class * @config * @var bool */ private static $has_placeholder = false; /** * @config * @var array */ private static $summary_fields = [ 'Title' ]; /** * @config * @var array */ private static $db = [ 'Name' => 'Varchar', 'Title' => 'Varchar(255)', 'Default' => 'Varchar(255)', 'Sort' => 'Int', 'Required' => 'Boolean', 'CustomErrorMessage' => 'Varchar(255)', 'ExtraClass' => 'Text', 'RightTitle' => 'Varchar(255)', 'ShowOnLoad' => 'Boolean(1)', 'ShowInSummary' => 'Boolean', 'Placeholder' => 'Varchar(255)', 'DisplayRulesConjunction' => 'Enum("And,Or","Or")', ]; private static $table_name = 'EditableFormField'; private static $defaults = [ 'ShowOnLoad' => true, ]; private static $indexes = [ 'Name' => 'Name', ]; /** * @config * @var array */ private static $has_one = [ 'Parent' => DataObject::class, ]; /** * Built in extensions required * * @config * @var array */ private static $extensions = [ Versioned::class . "('Stage', 'Live')" ]; /** * @config * @var array */ private static $has_many = [ 'DisplayRules' => EditableCustomRule::class . '.Parent' ]; private static $owns = [ 'DisplayRules', ]; private static $cascade_deletes = [ 'DisplayRules', ]; private static $cascade_duplicates = [ 'DisplayRules', ]; /** * This is protected rather that private so that it's unit testable */ protected static $isDisplayedRecursionProtection = []; /** * @var bool */ protected $readonly; /** * Property holds the JS event which gets fired for this type of element * * @var string */ protected $jsEventHandler = 'change'; /** * Returns the jsEventHandler property for the current object. Bearing in mind it could've been overridden. * @return string */ public function getJsEventHandler() { return $this->jsEventHandler; } /** * Set the visibility of an individual form field * * @param bool * @return $this */ public function setReadonly($readonly = true) { $this->readonly = $readonly; return $this; } /** * Returns whether this field is readonly * * @return bool */ private function isReadonly() { return $this->readonly; } /** * @return FieldList */ public function getCMSFields() { $fields = FieldList::create(TabSet::create('Root')); // If created with (+) button if ($this->ClassName === EditableFormField::class) { $fieldClasses = $this->getEditableFieldClasses(); $fields->addFieldsToTab('Root.Main', [ DropdownField::create('ClassName', _t(__CLASS__.'.TYPE', 'Type'), $fieldClasses) ->setEmptyString(_t(__CLASS__ . '.TYPE_EMPTY', 'Select field type')) ]); return $fields; } // Main tab $fields->addFieldsToTab( 'Root.Main', [ ReadonlyField::create( 'Type', _t(__CLASS__.'.TYPE', 'Type'), $this->i18n_singular_name() ), CheckboxField::create('ShowInSummary', _t(__CLASS__.'.SHOWINSUMMARY', 'Show in summary gridfield')), LiteralField::create( 'MergeField', '<div class="form-group field readonly">' . '<label class="left form__field-label form-label" for="Form_ItemEditForm_MergeField">' . _t(__CLASS__.'.MERGEFIELDNAME', 'Merge field') . '</label>' . '<div class="form__field-holder">' . '<span class="readonly" id="Form_ItemEditForm_MergeField">$' . $this->Name . '</span>' . '</div>' . '</div>' ), TextField::create('Title', _t(__CLASS__.'.TITLE', 'Title')), TextField::create('Default', _t(__CLASS__.'.DEFAULT', 'Default value')), TextField::create('RightTitle', _t(__CLASS__.'.RIGHTTITLE', 'Right title')), SegmentField::create('Name', _t(__CLASS__.'.NAME', 'Name'))->setModifiers([ UnderscoreSegmentFieldModifier::create()->setDefault('FieldName'), DisambiguationSegmentFieldModifier::create(), ])->setPreview($this->Name) ] ); $fields->fieldByName('Root.Main')->setTitle(_t('SilverStripe\\CMS\\Model\\SiteTree.TABMAIN', 'Main')); // Custom settings if (!empty(EditableFormField::$allowed_css)) { $cssList = []; foreach (EditableFormField::$allowed_css as $k => $v) { if (!is_array($v)) { $cssList[$k]=$v; } elseif ($k === $this->ClassName) { $cssList = array_merge($cssList, $v); } } $fields->addFieldToTab( 'Root.Main', DropdownField::create( 'ExtraClass', _t(__CLASS__.'.EXTRACLASS_TITLE', 'Extra Styling/Layout'), $cssList )->setDescription(_t( __CLASS__.'.EXTRACLASS_SELECT', 'Select from the list of allowed styles' )) ); } else { $fields->addFieldToTab( 'Root.Main', TextField::create( 'ExtraClass', _t(__CLASS__.'.EXTRACLASS_Title', 'Extra CSS classes') )->setDescription(_t( __CLASS__.'.EXTRACLASS_MULTIPLE', 'Separate each CSS class with a single space' )) ); } // Validation $validationFields = $this->getFieldValidationOptions(); if ($validationFields && $validationFields->count()) { $fields->addFieldsToTab('Root.Validation', $validationFields->toArray()); $fields->fieldByName('Root.Validation')->setTitle(_t(__CLASS__.'.VALIDATION', 'Validation')); } // Add display rule fields $displayFields = $this->getDisplayRuleFields(); if ($displayFields && $displayFields->count()) { $fields->addFieldsToTab('Root.DisplayRules', $displayFields->toArray()); } // Placeholder if ($this->config()->has_placeholder) { $fields->addFieldToTab( 'Root.Main', TextField::create( 'Placeholder', _t(__CLASS__.'.PLACEHOLDER', 'Placeholder') ) ); } $this->extend('updateCMSFields', $fields); return $fields; } public function requireDefaultRecords() { parent::requireDefaultRecords(); // make sure to migrate the class across (prior to v5.x) DB::query("UPDATE \"EditableFormField\" SET \"ParentClass\" = 'Page' WHERE \"ParentClass\" IS NULL"); if (EditableFormField::has_extension(Versioned::class)) { DB::query("UPDATE \"EditableFormField_Live\" SET \"ParentClass\" = 'Page' WHERE \"ParentClass\" IS NULL"); DB::query("UPDATE \"EditableFormField_Versions\" SET \"ParentClass\" = 'Page' WHERE \"ParentClass\" IS NULL"); } } /** * Return fields to display on the 'Display Rules' tab * * @return FieldList */ protected function getDisplayRuleFields() { $allowedClasses = array_keys($this->getEditableFieldClasses(false) ?? []); $editableColumns = new GridFieldEditableColumns(); $editableColumns->setDisplayFields([ 'ConditionFieldID' => function ($record, $column, $grid) use ($allowedClasses) { return DropdownField::create($column, '', EditableFormField::get()->filter([ 'ParentID' => $this->ParentID, 'ClassName' => $allowedClasses, ])->exclude([ 'ID' => $this->ID, ])->map('ID', 'Title')); }, 'ConditionOption' => function ($record, $column, $grid) { $options = Config::inst()->get(EditableCustomRule::class, 'condition_options'); return DropdownField::create($column, '', $options); }, 'FieldValue' => function ($record, $column, $grid) { return TextField::create($column); } ]); // Custom rules $customRulesConfig = GridFieldConfig::create() ->addComponents( $editableColumns, new GridFieldButtonRow(), new GridFieldToolbarHeader(), new GridFieldAddNewInlineButton(), new GridFieldDeleteAction() ); return new FieldList( DropdownField::create( 'ShowOnLoad', _t(__CLASS__.'.INITIALVISIBILITY', 'Initial visibility'), [ 1 => 'Show', 0 => 'Hide', ] ), DropdownField::create( 'DisplayRulesConjunction', _t(__CLASS__.'.DISPLAYIF', 'Toggle visibility when'), [ 'Or' => _t('SilverStripe\\UserForms\\Model\\UserDefinedForm.SENDIFOR', 'Any conditions are true'), 'And' => _t('SilverStripe\\UserForms\\Model\\UserDefinedForm.SENDIFAND', 'All conditions are true'), ] ), GridField::create( 'DisplayRules', _t(__CLASS__.'.CUSTOMRULES', 'Custom Rules'), $this->DisplayRules(), $customRulesConfig ) ); } protected function onBeforeWrite() { parent::onBeforeWrite(); $formField = $this->getFormField(); if ($formField && !$formField->hasData()) { $this->Required = false; } // Set a field name. if (!$this->Name) { // New random name $this->Name = $this->generateName(); } elseif ($this->Name === 'Field') { throw new ValidationException('Field name cannot be "Field"'); } if (!$this->Sort && $this->ParentID) { $parentID = $this->ParentID; $this->Sort = EditableFormField::get() ->filter('ParentID', $parentID) ->max('Sort') + 1; } } /** * Generate a new non-conflicting Name value * * @return string */ protected function generateName() { do { // Generate a new random name after this class (handles namespaces) $classNamePieces = explode('\\', static::class); $class = array_pop($classNamePieces); $entropy = substr(sha1(uniqid()), 0, 5); $name = "{$class}_{$entropy}"; // Check if it conflicts $exists = EditableFormField::get()->filter('Name', $name)->count() > 0; } while ($exists); return $name; } /** * Flag indicating that this field will set its own error message via data-msg='' attributes * * @return bool */ public function getSetsOwnError() { return false; } /** * Return whether a user can delete this form field * based on whether they can edit the page * * @param Member $member * @return bool */ public function canDelete($member = null) { return $this->canEdit($member); } /** * Return whether a user can edit this form field * based on whether they can edit the page * * @param Member $member * @return bool */ public function canEdit($member = null) { $parent = $this->Parent(); if ($parent && $parent->exists()) { return $parent->canEdit($member) && !$this->isReadonly(); } elseif (!$this->exists() && Controller::curr()) { // This is for GridFieldOrderableRows support as it checks edit permissions on // singleton of the class. Allows editing of User Defined Form pages by // 'Content Authors' and those with permission to edit the UDF page. (ie. CanEditType/EditorGroups) // This is to restore User Forms 2.x backwards compatibility. $controller = Controller::curr(); if ($controller instanceof CMSPageEditController) { $parent = $controller->getRecord($controller->currentRecordID()); // Only allow this behaviour on pages using UserFormFieldEditorExtension, such // as UserDefinedForm page type. if ($parent && $parent->hasExtension(UserFormFieldEditorExtension::class)) { return $parent->canEdit($member); } } } // Fallback to secure admin permissions return parent::canEdit($member); } /** * Return whether a user can view this form field * based on whether they can view the page, regardless of the ReadOnly status of the field * * @param Member $member * @return bool */ public function canView($member = null) { $parent = $this->Parent(); if ($parent && $parent->exists()) { return $parent->canView($member); } return true; } /** * Return whether a user can create an object of this type * * @param Member $member * @param array $context Virtual parameter to allow context to be passed in to check * @return bool */ public function canCreate($member = null, $context = []) { // Check parent page $parent = $this->getCanCreateContext(func_get_args()); if ($parent) { return $parent->canEdit($member); } // Fall back to secure admin permissions return parent::canCreate($member); } /** * Helper method to check the parent for this object * * @param array $args List of arguments passed to canCreate * @return SiteTree Parent page instance */ protected function getCanCreateContext($args) { // Inspect second parameter to canCreate for a 'Parent' context if (isset($args[1]['Parent'])) { return $args[1]['Parent']; } // Hack in currently edited page if context is missing $controller = Controller::curr(); if ($controller instanceof CMSMain) { return $controller->currentRecord(); } // No page being edited return null; } /** * checks whether record is new, copied from SiteTree */ public function isNew() { if (empty($this->ID)) { return true; } if (is_numeric($this->ID)) { return false; } return stripos($this->ID ?? '', 'new') === 0; } /** * Set the allowed css classes for the extraClass custom setting * * @param array $allowed The permissible CSS classes to add */ public function setAllowedCss(array $allowed) { if (is_array($allowed)) { foreach ($allowed as $k => $v) { EditableFormField::$allowed_css[$k] = (!is_null($v)) ? $v : $k; } } } /** * Get the path to the icon for this field type, relative to the site root. * * @return string */ public function getIcon() { $classNamespaces = explode("\\", static::class); $shortClass = end($classNamespaces); $resource = ModuleLoader::getModule('silverstripe/userforms') ->getResource('images/' . strtolower($shortClass ?? '') . '.png'); if (!$resource->exists()) { return ''; } return $resource->getURL(); } /** * Return whether or not this field has addable options * such as a dropdown field or radio set * * @return bool */ public function getHasAddableOptions() { return false; } /** * Return whether or not this field needs to show the extra * options dropdown list * * @return bool */ public function showExtraOptions() { return true; } /** * Find the numeric indicator (1.1.2) that represents it's nesting value * * Only useful for fields attached to a current page, and that contain other fields such as pages * or groups * * @return string */ public function getFieldNumber() { // Check if exists if (!$this->exists()) { return null; } // Check parent $form = $this->Parent(); if (!$form || !$form->exists() || !($fields = $form->Fields())) { return null; } $prior = 0; // Number of prior group at this level $stack = []; // Current stack of nested groups, where the top level = the page foreach ($fields->map('ID', 'ClassName') as $id => $className) { if ($className === EditableFormStep::class) { $priorPage = empty($stack) ? $prior : $stack[0]; $stack = array($priorPage + 1); $prior = 0; } elseif ($className === EditableFieldGroup::class) { $stack[] = $prior + 1; $prior = 0; } elseif ($className === EditableFieldGroupEnd::class) { $prior = array_pop($stack); } if ($id == $this->ID) { return implode('.', $stack); } } return null; } public function getCMSTitle() { return $this->i18n_singular_name() . ' (' . $this->Title . ')'; } /** * Append custom validation fields to the default 'Validation' * section in the editable options view * * @return FieldList */ public function getFieldValidationOptions() { $fields = new FieldList( CheckboxField::create('Required', _t(__CLASS__.'.REQUIRED', 'Is this field Required?')) ->setDescription(_t(__CLASS__.'.REQUIRED_DESCRIPTION', 'Please note that conditional fields can\'t be required')), TextField::create('CustomErrorMessage', _t(__CLASS__.'.CUSTOMERROR', 'Custom Error Message')) ); $this->extend('updateFieldValidationOptions', $fields); return $fields; } /** * Return a FormField to appear on the front end. Implement on * your subclass. * * @return FormField */ public function getFormField() { user_error("Please implement a getFormField() on your EditableFormClass ". $this->ClassName, E_USER_ERROR); } /** * Updates a formfield with extensions * * @param FormField $field */ public function doUpdateFormField($field) { $this->extend('beforeUpdateFormField', $field); $this->updateFormField($field); $this->extend('afterUpdateFormField', $field); } /** * Updates a formfield with the additional metadata specified by this field * * @param FormField $field */ protected function updateFormField($field) { // set the error / formatting messages $field->setCustomValidationMessage($this->getErrorMessage()->RAW()); // set the right title on this field if ($this->RightTitle) { $field->setRightTitle($this->RightTitle); } // if this field is required add some if ($this->Required) { // Required validation can conflict so add the Required validation messages as input attributes $errorMessage = $this->getErrorMessage()->HTML(); $field->addExtraClass('requiredField'); $field->setAttribute('data-rule-required', 'true'); $field->setAttribute('data-msg-required', $errorMessage); if ($identifier = UserDefinedForm::config()->required_identifier) { $title = $field->Title() . " <span class='required-identifier'>". $identifier . "</span>"; $field->setTitle(DBField::create_field('HTMLText', $title)); } } // if this field has an extra class if ($this->ExtraClass) { $field->addExtraClass($this->ExtraClass); } // if ShowOnLoad is false hide the field if (!$this->ShowOnLoad) { $field->addExtraClass($this->ShowOnLoadNice()); } // if this field has a placeholder if (strlen($this->Placeholder ?? '') >= 0) { $field->setAttribute('placeholder', $this->Placeholder); } } /** * Return the instance of the submission field class * * @return SubmittedFormField */ public function getSubmittedFormField() { return SubmittedFormField::create(); } /** * Show this form field (and its related value) in the reports and in emails. * * @return bool */ public function showInReports() { return true; } /** * Return the error message for this field. Either uses the custom * one (if provided) or the default SilverStripe message * * @return DBVarchar */ public function getErrorMessage() { $title = strip_tags("'". ($this->Title ? $this->Title : $this->Name) . "'"); $standard = _t(__CLASS__ . '.FIELDISREQUIRED', '{name} is required', ['name' => $title]); // only use CustomErrorMessage if it has a non empty value $errorMessage = (!empty($this->CustomErrorMessage)) ? $this->CustomErrorMessage : $standard; return DBField::create_field('Varchar', $errorMessage); } /** * Get the formfield to use when editing this inline in gridfield * * @param string $column name of column * @param array $fieldClasses List of allowed classnames if this formfield has a selectable class * @return FormField */ public function getInlineClassnameField($column, $fieldClasses) { return DropdownField::create($column, false, $fieldClasses); } /** * Get the formfield to use when editing the title inline * * @param string $column * @return FormField */ public function getInlineTitleField($column) { return TextField::create($column, false) ->setAttribute('placeholder', _t(__CLASS__.'.TITLE', 'Title')) ->setAttribute('data-placeholder', _t(__CLASS__.'.TITLE', 'Title')); } /** * Get the JS expression for selecting the holder for this field * * @return string */ public function getSelectorHolder() { return sprintf('$("%s")', $this->getSelectorOnly()); } /** * Returns only the JS identifier of a string, less the $(), which can be inserted elsewhere, for example when you * want to perform selections on multiple selectors * @return string */ public function getSelectorOnly() { return "#{$this->Name}"; } /** * Gets the JS expression for selecting the value for this field * * @param EditableCustomRule $rule Custom rule this selector will be used with * @param bool $forOnLoad Set to true if this will be invoked on load * * @return string */ public function getSelectorField(EditableCustomRule $rule, $forOnLoad = false) { return sprintf("$(%s)", $this->getSelectorFieldOnly()); } /** * @return string */ public function getSelectorFieldOnly() { return "[name='{$this->Name}']"; } /** * Get the list of classes that can be selected and used as data-values * * @param $includeLiterals Set to false to exclude non-data fields * @return array */ public function getEditableFieldClasses($includeLiterals = true) { $classes = ClassInfo::getValidSubClasses(EditableFormField::class); // Remove classes we don't want to display in the dropdown. $editableFieldClasses = []; foreach ($classes as $class) { // Skip abstract / hidden classes if (Config::inst()->get($class, 'abstract', Config::UNINHERITED) || Config::inst()->get($class, 'hidden') ) { continue; } if (!$includeLiterals && Config::inst()->get($class, 'literal')) { continue; } $singleton = singleton($class); if (!$singleton->canCreate()) { continue; } $editableFieldClasses[$class] = $singleton->i18n_singular_name(); } asort($editableFieldClasses); return $editableFieldClasses; } public function getCMSCompositeValidator(): CompositeValidator { $validator = parent::getCMSCompositeValidator(); $validator->addValidator(EditableFormField\Validator::create()->setRecord($this)); return $validator; } /** * Extracts info from DisplayRules into array so UserDefinedForm->buildWatchJS can run through it. * @return array|null */ public function formatDisplayRules() { $holderSelector = $this->getSelectorOnly(); $result = [ 'targetFieldID' => $holderSelector, 'conjunction' => $this->DisplayRulesConjunctionNice(), 'selectors' => [], 'events' => [], 'operations' => [], 'initialState' => $this->ShowOnLoadNice(), 'view' => [], 'opposite' => [], ]; // Check for field dependencies / default foreach ($this->DisplayRules() as $rule) { // Get the field which is effected $formFieldWatch = EditableFormField::get()->setUseCache(true)->byID($rule->ConditionFieldID); // Skip deleted fields if (!$formFieldWatch) { continue; } $fieldToWatch = $formFieldWatch->getSelectorFieldOnly(); $expression = $rule->buildExpression(); if (!in_array($fieldToWatch, $result['selectors'] ?? [])) { $result['selectors'][] = $fieldToWatch; } if (!in_array($expression['event'], $result['events'] ?? [])) { $result['events'][] = $expression['event']; } $result['operations'][] = $expression['operation']; // View/Show should read $result['view'] = $rule->toggleDisplayText($result['initialState']); $result['opposite'] = $rule->toggleDisplayText($result['initialState'], true); $result['holder'] = $this->getSelectorHolder(); $result['holder_event'] = $rule->toggleDisplayEvent($result['initialState']); $result['holder_event_opposite'] = $rule->toggleDisplayEvent($result['initialState'], true); } return (count($result['selectors'] ?? [])) ? $result : null; } /** * Used to prevent infinite recursion when checking a CMS user has setup two or more fields to have * their display rules dependent on one another * * There will be several thousand calls to isDisplayed before memory is likely to be hit, so 100 * calls is a reasonable limit that ensures that this doesn't prevent legit use cases from being * identified as recursion */ private function checkIsDisplayedRecursionProtection(): bool { $count = count(array_filter(static::$isDisplayedRecursionProtection, fn($id) => $id === $this->ID)); return $count < 100; } /** * Check if this EditableFormField is displayed based on its DisplayRules and the provided data. * @param array $data * @return bool */ public function isDisplayed(array $data) { static::$isDisplayedRecursionProtection[] = $this->ID; $displayRules = $this->DisplayRules(); if ($displayRules->count() === 0) { // If no display rule have been defined, isDisplayed equals the ShowOnLoad property return $this->ShowOnLoad; } $conjunction = $this->DisplayRulesConjunctionNice(); // && start with true and find and condition that doesn't satisfy // || start with false and find and condition that satisfies $conditionsSatisfied = ($conjunction === '&&'); foreach ($displayRules as $rule) { $controllingField = $rule->ConditionField(); // recursively check - if any of the dependant fields are hidden, assume the rule can not be satisfied $ruleSatisfied = $this->checkIsDisplayedRecursionProtection() && $controllingField->isDisplayed($data) && $rule->validateAgainstFormData($data);
php
BSD-3-Clause
e33fff165d33a077ec4b20c2eef2ef8bca25d15a
2026-01-05T05:22:58.009669Z
true
silverstripe/silverstripe-userforms
https://github.com/silverstripe/silverstripe-userforms/blob/e33fff165d33a077ec4b20c2eef2ef8bca25d15a/code/Model/Recipient/EmailRecipient.php
code/Model/Recipient/EmailRecipient.php
<?php namespace SilverStripe\UserForms\Model\Recipient; use SilverStripe\Assets\FileFinder; use SilverStripe\CMS\Controllers\CMSMain; use SilverStripe\CMS\Controllers\CMSPageEditController; use SilverStripe\CMS\Model\SiteTree; use SilverStripe\Control\Controller; use SilverStripe\Control\Email\Email; use SilverStripe\Core\Manifest\ModuleResource; use SilverStripe\Core\Manifest\ModuleResourceLoader; use SilverStripe\Forms\CheckboxField; use SilverStripe\Forms\DropdownField; use SilverStripe\Forms\FieldGroup; use SilverStripe\Forms\FieldList; use SilverStripe\Forms\Form; use SilverStripe\Forms\FormField; use SilverStripe\Forms\GridField\GridField; use SilverStripe\Forms\GridField\GridFieldAddNewButton; use SilverStripe\Forms\GridField\GridFieldButtonRow; use SilverStripe\Forms\GridField\GridFieldConfig; use SilverStripe\Forms\GridField\GridFieldConfig_RecordEditor; use SilverStripe\Forms\GridField\GridFieldDeleteAction; use SilverStripe\Forms\GridField\GridFieldDetailForm; use SilverStripe\Forms\GridField\GridFieldToolbarHeader; use SilverStripe\Forms\HTMLEditor\HTMLEditorField; use SilverStripe\Forms\LiteralField; use SilverStripe\Forms\TabSet; use SilverStripe\Forms\TextareaField; use SilverStripe\Forms\TextField; use SilverStripe\Model\List\ArrayList; use SilverStripe\ORM\DataList; use SilverStripe\ORM\DataObject; use SilverStripe\ORM\DB; use SilverStripe\ORM\FieldType\DBField; use SilverStripe\ORM\HasManyList; use SilverStripe\Core\Validation\ValidationResult; use SilverStripe\Security\Member; use SilverStripe\UserForms\Model\EditableFormField; use SilverStripe\UserForms\Model\EditableFormField\EditableEmailField; use SilverStripe\UserForms\Model\EditableFormField\EditableMultipleOptionField; use SilverStripe\UserForms\Model\EditableFormField\EditableTextField; use SilverStripe\UserForms\Model\UserDefinedForm; use SilverStripe\UserForms\UserForm; use SilverStripe\View\Requirements; use Symbiote\GridFieldExtensions\GridFieldAddNewInlineButton; use Symbiote\GridFieldExtensions\GridFieldEditableColumns; /** * A Form can have multiply members / emails to email the submission * to and custom subjects * * @package userforms * @property string $CustomRulesCondition * @property string $EmailAddress * @property string $EmailBody * @property string $EmailBodyHtml * @property string $EmailFrom * @property string $EmailReplyTo * @property string $EmailSubject * @property string $EmailTemplate * @property int $FormID * @property int $HideFromData * @property int $SendPlain * @property int $SendEmailFromFieldID * @property int $SendEmailSubjectFieldID * @property int $SendEmailToFieldID * @method HasManyList<EmailRecipientCondition> CustomRules() * @method DataObject Form() * @method EditableFormField SendEmailFromField() * @method EditableFormField SendEmailSubjectField() * @method EditableFormField SendEmailToField() */ class EmailRecipient extends DataObject { private static $db = [ 'EmailAddress' => 'Varchar(200)', 'EmailSubject' => 'Varchar(200)', 'EmailFrom' => 'Varchar(200)', 'EmailReplyTo' => 'Varchar(200)', 'EmailBody' => 'Text', 'EmailBodyHtml' => 'HTMLText', 'EmailTemplate' => 'Varchar', 'SendPlain' => 'Boolean', 'HideFormData' => 'Boolean', 'HideInvisibleFields' => 'Boolean', 'CustomRulesCondition' => 'Enum("And,Or")' ]; private static $has_one = [ 'Form' => DataObject::class, 'SendEmailFromField' => EditableFormField::class, 'SendEmailToField' => EditableFormField::class, 'SendEmailSubjectField' => EditableFormField::class ]; private static $has_many = [ 'CustomRules' => EmailRecipientCondition::class, ]; private static $owns = [ 'CustomRules', ]; private static $cascade_deletes = [ 'CustomRules', ]; private static $cascade_duplicates = [ 'CustomRules', ]; private static $summary_fields = [ 'EmailAddress', 'EmailSubject', 'EmailFrom' ]; private static $table_name = 'UserDefinedForm_EmailRecipient'; /** * Disable versioned GridField to ensure that it doesn't interfere with {@link UserFormRecipientItemRequest} * * {@inheritDoc} */ private static $versioned_gridfield_extensions = false; /** * Setting this to true will allow you to select "risky" fields as * email recipient, such as free-text entry fields. * * It's advisable to leave this off. * * @config * @var bool */ private static $allow_unbound_recipient_fields = false; /** * The regex used to find template files for rendering emails. * By default this finds ss template files. */ private static string $email_template_regex = '/^.*\.ss$/'; public function requireDefaultRecords() { parent::requireDefaultRecords(); // make sure to migrate the class across (prior to v5.x) DB::query("UPDATE \"UserDefinedForm_EmailRecipient\" SET \"FormClass\" = 'Page' WHERE \"FormClass\" IS NULL"); } protected function onBeforeWrite() { parent::onBeforeWrite(); // email addresses have trim() applied to them during validation for a slightly nicer UX // apply trim() here too before saving to the database $this->EmailAddress = trim($this->EmailAddress ?? ''); $this->EmailFrom = trim($this->EmailFrom ?? ''); $this->EmailReplyTo = trim($this->EmailReplyTo ?? ''); } public function summaryFields() { $fields = parent::summaryFields(); if (isset($fields['EmailAddress'])) { $fields['EmailAddress'] = _t('SilverStripe\\UserForms\\Model\\UserDefinedForm.EMAILADDRESS', 'Email'); } if (isset($fields['EmailSubject'])) { $fields['EmailSubject'] = _t('SilverStripe\\UserForms\\Model\\UserDefinedForm.EMAILSUBJECT', 'Subject'); } if (isset($fields['EmailFrom'])) { $fields['EmailFrom'] = _t('SilverStripe\\UserForms\\Model\\UserDefinedForm.EMAILFROM', 'From'); } return $fields; } public function scaffoldFormFieldForHasMany( string $relationName, ?string $fieldTitle, DataObject $ownerRecord, bool &$includeInOwnTab ): FormField { $includeInOwnTab = true; return $this->scaffoldFormFieldForManyRelation($relationName, $fieldTitle, $ownerRecord); } public function scaffoldFormFieldForManyMany( string $relationName, ?string $fieldTitle, DataObject $ownerRecord, bool &$includeInOwnTab ): FormField { $includeInOwnTab = true; return $this->scaffoldFormFieldForManyRelation($relationName, $fieldTitle, $ownerRecord); } private function scaffoldFormFieldForManyRelation( string $relationName, ?string $fieldTitle, DataObject $ownerRecord ): FormField { $emailRecipientsConfig = GridFieldConfig_RecordEditor::create(10); $emailRecipientsConfig->getComponentByType(GridFieldAddNewButton::class) ->setButtonName( _t(UserDefinedForm::class . '.ADDNEWEMAILRECIPIENT', 'Add new Email Recipient') ); $emailRecipientsConfig->getComponentByType(GridFieldDetailForm::class) ->setItemRequestClass(UserFormRecipientItemRequest::class); return GridField::create( $relationName, $fieldTitle, $ownerRecord->$relationName(), $emailRecipientsConfig ); } /** * Get instance of UserForm when editing in getCMSFields * * @return UserDefinedForm|UserForm|null */ protected function getFormParent() { // If polymorphic relationship is actually defined, use it if ($this->FormID && $this->FormClass) { $formClass = $this->FormClass; return $formClass::get()->byID($this->FormID); } return null; } public function getTitle() { if ($this->EmailAddress) { return $this->EmailAddress; } if ($this->EmailSubject) { return $this->EmailSubject; } return parent::getTitle(); } /** * Generate a gridfield config for editing filter rules * * @return GridFieldConfig */ protected function getRulesConfig() { if (!$this->getFormParent()) { return null; } $formFields = $this->getFormParent()->Fields(); $config = GridFieldConfig::create() ->addComponents( new GridFieldButtonRow('before'), new GridFieldToolbarHeader(), new GridFieldAddNewInlineButton(), new GridFieldDeleteAction(), $columns = new GridFieldEditableColumns() ); $columns->setDisplayFields(array( 'ConditionFieldID' => function ($record, $column, $grid) use ($formFields) { return DropdownField::create($column, false, $formFields->map('ID', 'Title')); }, 'ConditionOption' => function ($record, $column, $grid) { $options = EmailRecipientCondition::config()->condition_options; return DropdownField::create($column, false, $options); }, 'ConditionValue' => function ($record, $column, $grid) { return TextField::create($column); } )); return $config; } /** * @return FieldList */ public function getCMSFields() { Requirements::javascript('silverstripe/userforms:client/dist/js/userforms-cms.js'); // Build fieldlist $fields = FieldList::create(Tabset::create('Root')->addExtraClass('EmailRecipientForm')); if (!$this->getFormParent()) { $fields->addFieldToTab('Root.EmailDetails', $this->getUnsavedFormLiteralField()); } // Configuration fields $fields->addFieldsToTab('Root.EmailDetails', [ $this->getSubjectCMSFields(), $this->getEmailToCMSFields(), $this->getEmailFromCMSFields(), $this->getEmailReplyToCMSFields(), ]); $fields->fieldByName('Root.EmailDetails')->setTitle(_t(__CLASS__ . '.EMAILDETAILSTAB', 'Email Details')); // Only show the preview link if the recipient has been saved. if (!empty($this->EmailTemplate)) { $request = Controller::curr()->getRequest(); $pageEditController = singleton(CMSPageEditController::class); $pageEditController->getRequest()->setSession($request->getSession()); $currentUrl = $request->getURL(); // If used in a regular page context, will have "/edit" on the end, if used in a trait context // it won't. Strip that off in case. It may also have "ItemEditForm" on the end instead if this is // an AJAX request, e.g. saving a GridFieldDetailForm $remove = ['/edit', '/ItemEditForm']; foreach ($remove as $badSuffix) { $badSuffixLength = strlen($badSuffix ?? ''); if (substr($currentUrl ?? '', -$badSuffixLength) === $badSuffix) { $currentUrl = substr($currentUrl ?? '', 0, -$badSuffixLength); } } $previewUrl = Controller::join_links($currentUrl, 'preview'); $preview = sprintf( '<p><a href="%s" target="_blank" class="btn btn-outline-secondary">%s</a></p><em>%s</em>', $previewUrl, _t('SilverStripe\\UserForms\\Model\\UserDefinedForm.PREVIEW_EMAIL', 'Preview email'), _t( 'SilverStripe\\UserForms\\Model\\UserDefinedForm.PREVIEW_EMAIL_DESCRIPTION', 'Note: Unsaved changes will not appear in the preview.' ) ); } else { $preview = sprintf( '<p class="alert alert-warning">%s</p>', _t( 'SilverStripe\\UserForms\\Model\\UserDefinedForm.PREVIEW_EMAIL_UNAVAILABLE', 'You can preview this email once you have saved the Recipient.' ) ); } // Email templates $fields->addFieldsToTab('Root.EmailContent', [ CheckboxField::create( 'HideFormData', _t('SilverStripe\\UserForms\\Model\\UserDefinedForm.HIDEFORMDATA', 'Hide form data from email?') ), CheckboxField::create( 'HideInvisibleFields', _t('SilverStripe\\UserForms\\Model\\UserDefinedForm.HIDEINVISIBLEFIELDS', 'Hide invisible fields from email?') ), CheckboxField::create( 'SendPlain', _t( 'SilverStripe\\UserForms\\Model\\UserDefinedForm.SENDPLAIN', 'Send email as plain text? (HTML will be stripped)' ) ), HTMLEditorField::create( 'EmailBodyHtml', _t('SilverStripe\\UserForms\\Model\\UserDefinedForm.EMAILBODYHTML', 'Body') ) ->addExtraClass('toggle-html-only'), TextareaField::create( 'EmailBody', _t('SilverStripe\\UserForms\\Model\\UserDefinedForm.EMAILBODY', 'Body') ) ->addExtraClass('toggle-plain-only'), LiteralField::create('EmailPreview', $preview) ]); $templates = $this->getEmailTemplateDropdownValues(); if ($templates) { $fields->insertBefore( 'EmailBodyHtml', DropdownField::create( 'EmailTemplate', _t('SilverStripe\\UserForms\\Model\\UserDefinedForm.EMAILTEMPLATE', 'Email template'), $templates )->addExtraClass('toggle-html-only') ); } $fields->fieldByName('Root.EmailContent')->setTitle(_t(__CLASS__ . '.EMAILCONTENTTAB', 'Email Content')); // Custom rules for sending this field $grid = GridField::create( 'CustomRules', _t('SilverStripe\\UserForms\\Model\\EditableFormField.CUSTOMRULES', 'Custom Rules'), $this->CustomRules(), $this->getRulesConfig() ); $grid->setDescription(_t( 'SilverStripe\\UserForms\\Model\\UserDefinedForm.RulesDescription', 'Emails will only be sent to the recipient if the custom rules are met. If no rules are defined, ' . 'this recipient will receive notifications for every submission.' )); $fields->addFieldsToTab('Root.CustomRules', [ DropdownField::create( 'CustomRulesCondition', _t('SilverStripe\\UserForms\\Model\\UserDefinedForm.SENDIF', 'Send condition'), [ 'Or' => _t( 'SilverStripe\\UserForms\\Model\\UserDefinedForm.SENDIFOR', 'Any conditions are true' ), 'And' => _t( 'SilverStripe\\UserForms\\Model\\UserDefinedForm.SENDIFAND', 'All conditions are true' ) ] ), $grid ]); $fields->fieldByName('Root.CustomRules')->setTitle(_t(__CLASS__ . '.CUSTOMRULESTAB', 'Custom Rules')); $this->extend('updateCMSFields', $fields); return $fields; } /** * Return whether a user can create an object of this type * * @param Member $member * @param array $context Virtual parameter to allow context to be passed in to check * @return bool */ public function canCreate($member = null, $context = []) { // Check parent page $parent = $this->getCanCreateContext(func_get_args()); if ($parent) { return $parent->canEdit($member); } // Fall back to secure admin permissions return parent::canCreate($member); } /** * Helper method to check the parent for this object * * @param array $args List of arguments passed to canCreate * @return SiteTree Parent page instance */ protected function getCanCreateContext($args) { // Inspect second parameter to canCreate for a 'Parent' context if (isset($args[1][Form::class])) { return $args[1][Form::class]; } // Hack in currently edited page if context is missing $controller = Controller::curr(); if ($controller instanceof CMSMain) { return $controller->currentRecord(); } // No page being edited return null; } public function canView($member = null) { if ($form = $this->getFormParent()) { return $form->canView($member); } return parent::canView($member); } public function canEdit($member = null) { if ($form = $this->getFormParent()) { return $form->canEdit($member); } return parent::canEdit($member); } /** * @param Member * * @return boolean */ public function canDelete($member = null) { return $this->canEdit($member); } /** * Determine if this recipient may receive notifications for this submission * * @param array $data * @param Form $form * @return bool */ public function canSend($data, $form) { // Skip if no rules configured $customRules = $this->CustomRules(); if (!$customRules->count()) { return true; } // Check all rules $isAnd = $this->CustomRulesCondition === 'And'; foreach ($customRules as $customRule) { $matches = $customRule->matches($data); if ($isAnd && !$matches) { return false; } if (!$isAnd && $matches) { return true; } } // Once all rules are checked return $isAnd; } /** * Make sure the email template saved against the recipient exists on the file system. * * @param string * * @return boolean */ public function emailTemplateExists($template = '') { $t = ($template ? $template : $this->EmailTemplate) ?? ''; return array_key_exists($t, (array) $this->getEmailTemplateDropdownValues()); } /** * Get the email body for the current email format * * @return string */ public function getEmailBodyContent() { if ($this->SendPlain) { return DBField::create_field('HTMLText', $this->EmailBody)->Plain(); } return DBField::create_field('HTMLText', $this->EmailBodyHtml); } /** * Gets a list of email templates suitable for populating the email template dropdown. * * @return array */ public function getEmailTemplateDropdownValues() { $templates = []; $finder = new FileFinder(); $finder->setOption('name_regex', static::config()->get('email_template_regex')); $parent = $this->getFormParent(); if (!$parent) { return []; } $emailTemplateDirectory = $parent->config()->get('email_template_directory'); $templateDirectory = ModuleResourceLoader::resourcePath($emailTemplateDirectory); if (!$templateDirectory) { return []; } $found = $finder->find(BASE_PATH . DIRECTORY_SEPARATOR . $templateDirectory); foreach ($found as $key => $value) { $template = pathinfo($value ?? ''); $absoluteFilename = $template['dirname'] . DIRECTORY_SEPARATOR . $template['filename']; // Optionally remove vendor/ path prefixes $resource = ModuleResourceLoader::singleton()->resolveResource($emailTemplateDirectory); if ($resource instanceof ModuleResource && $resource->getModule()) { $prefixToStrip = $resource->getModule()->getPath(); } else { $prefixToStrip = BASE_PATH; } $templatePath = substr($absoluteFilename ?? '', strlen($prefixToStrip ?? '') + 1); // Optionally remove "templates/" ("templates\" on Windows respectively) prefixes if (preg_match('#(?<=templates' . preg_quote(DIRECTORY_SEPARATOR, '#') . ').*$#', $templatePath ?? '', $matches)) { $templatePath = $matches[0]; } $templates[$templatePath] = $template['filename']; } return $templates; } /** * Validate that valid email addresses are being used */ public function validate(): ValidationResult { $result = parent::validate(); $checkEmail = [ 'EmailAddress' => 'EMAILADDRESSINVALID', 'EmailFrom' => 'EMAILFROMINVALID', 'EmailReplyTo' => 'EMAILREPLYTOINVALID', ]; foreach ($checkEmail as $check => $translation) { if ($this->$check) { //may be a comma separated list of emails $addresses = explode(',', $this->$check ?? ''); foreach ($addresses as $address) { $trimAddress = trim($address ?? ''); if ($trimAddress && !Email::is_valid_address($trimAddress)) { /** @phpstan-ignore translation.key (can't simplify the key without lots of duplicated code) */ $error = _t( __CLASS__.".$translation", "Invalid email address $trimAddress" ); $result->addError($error . " ($trimAddress)"); } } } } // if there is no from address and no fallback, you'll have errors if this isn't defined if (!$this->EmailFrom && empty(Email::getSendAllEmailsFrom()) && empty(Email::config()->get('admin_email'))) { $result->addError(_t(__CLASS__.".EMAILFROMREQUIRED", '"Email From" address is required')); } // Sending will also fail if there's no recipient defined if (!$this->EmailAddress && !$this->SendEmailToFieldID) { $result->addError(_t(__CLASS__.".EMAILTOREQUIRED", '"Send email to" address or field is required')); } return $result; } /** * @return FieldGroup|TextField */ protected function getSubjectCMSFields() { $subjectTextField = TextField::create( 'EmailSubject', _t('SilverStripe\\UserForms\\Model\\UserDefinedForm.TYPESUBJECT', 'Type subject') ) ->setAttribute('style', 'min-width: 400px;'); if ($this->getFormParent() && $this->getValidSubjectFields()) { return FieldGroup::create( $subjectTextField, DropdownField::create( 'SendEmailSubjectFieldID', _t( 'SilverStripe\\UserForms\\Model\\UserDefinedForm.SELECTAFIELDTOSETSUBJECT', '.. or select a field to use as the subject' ), $this->getValidSubjectFields()->map('ID', 'Title') )->setEmptyString('') ) ->setTitle(_t('SilverStripe\\UserForms\\Model\\UserDefinedForm.EMAILSUBJECT', 'Email subject')); } else { return $subjectTextField; } } /** * @return FieldGroup|TextField */ protected function getEmailToCMSFields() { $emailToTextField = TextField::create( 'EmailAddress', _t('SilverStripe\\UserForms\\Model\\UserDefinedForm.TYPETO', 'Type to address') ) ->setAttribute('style', 'min-width: 400px;'); if ($this->getFormParent() && $this->getValidEmailToFields()) { return FieldGroup::create( $emailToTextField, DropdownField::create( 'SendEmailToFieldID', _t( 'SilverStripe\\UserForms\\Model\\UserDefinedForm.ORSELECTAFIELDTOUSEASTO', '.. or select a field to use as the to address' ), $this->getValidEmailToFields()->map('ID', 'Title') )->setEmptyString(' ') ) ->setTitle(_t('SilverStripe\\UserForms\\Model\\UserDefinedForm.SENDEMAILTO', 'Send email to')) ->setDescription(_t( 'SilverStripe\\UserForms\\Model\\UserDefinedForm.SENDEMAILTO_DESCRIPTION', 'You may enter multiple email addresses as a comma separated list.' )); } else { return $emailToTextField; } } /** * @return TextField */ protected function getEmailFromCMSFields() { return TextField::create( 'EmailFrom', _t('SilverStripe\\UserForms\\Model\\UserDefinedForm.FROMADDRESS', 'Send email from') ) ->setDescription(_t( 'SilverStripe\\UserForms\\Model\\UserDefinedForm.EmailFromContent', "The from address allows you to set who the email comes from. On most servers this " . "will need to be set to an email address on the same domain name as your site. " . "For example on yoursite.com the from address may need to be something@yoursite.com. " . "You can however, set any email address you wish as the reply to address." )); } /** * @return FieldGroup|TextField */ protected function getEmailReplyToCMSFields() { $replyToTextField = TextField::create('EmailReplyTo', _t( 'SilverStripe\\UserForms\\Model\\UserDefinedForm.TYPEREPLY', 'Type reply address' )) ->setAttribute('style', 'min-width: 400px;'); if ($this->getFormParent() && $this->getValidEmailFromFields()) { return FieldGroup::create( $replyToTextField, DropdownField::create( 'SendEmailFromFieldID', _t( 'SilverStripe\\UserForms\\Model\\UserDefinedForm.ORSELECTAFIELDTOUSEASFROM', '.. or select a field to use as reply to address' ), $this->getValidEmailFromFields()->map('ID', 'Title') )->setEmptyString(' ') ) ->setTitle(_t( 'SilverStripe\\UserForms\\Model\\UserDefinedForm.REPLYADDRESS', 'Email for reply to' )) ->setDescription(_t( 'SilverStripe\\UserForms\\Model\\UserDefinedForm.REPLYADDRESS_DESCRIPTION', 'The email address which the recipient is able to \'reply\' to.' )); } else { return $replyToTextField; } } /** * @return DataList<EditableMultipleOptionField>|null */ protected function getMultiOptionFields() { if (!$form = $this->getFormParent()) { return null; } return EditableMultipleOptionField::get()->filter('ParentID', $form->ID); } /** * @return ArrayList<EditableFormField>|null */ protected function getValidSubjectFields() { if (!$form = $this->getFormParent()) { return null; } // For the subject, only one-line entry boxes make sense $validSubjectFields = ArrayList::create( EditableTextField::get() ->filter('ParentID', $form->ID) ->exclude('Rows:GreaterThan', 1) ->toArray() ); $validSubjectFields->merge($this->getMultiOptionFields()); return $validSubjectFields; } /** * @return DataList<EditableEmailField>|null */ protected function getValidEmailFromFields() { if (!$form = $this->getFormParent()) { return null; } // if they have email fields then we could send from it return EditableEmailField::get()->filter('ParentID', $form->ID); } /** * @return ArrayList<EditableFormField>|DataList<EditableFormField>|null */ protected function getValidEmailToFields() { if (!$this->getFormParent()) { return null; } // Check valid email-recipient fields if ($this->config()->get('allow_unbound_recipient_fields')) { // To address can only be email fields or multi option fields $validEmailToFields = ArrayList::create($this->getValidEmailFromFields()->toArray()); $validEmailToFields->merge($this->getMultiOptionFields()); return $validEmailToFields; } else { // To address cannot be unbound, so restrict to pre-defined lists return $this->getMultiOptionFields(); } } protected function getUnsavedFormLiteralField() { return LiteralField::create( 'UnsavedFormMessage', sprintf( '<p class="alert alert-warning">%s</p>', _t( 'SilverStripe\\UserForms\\Model\\UserDefinedForm.EMAIL_RECIPIENT_UNSAVED_FORM', 'You will be able to select from valid form fields after saving this record.' ) ) ); } }
php
BSD-3-Clause
e33fff165d33a077ec4b20c2eef2ef8bca25d15a
2026-01-05T05:22:58.009669Z
false
silverstripe/silverstripe-userforms
https://github.com/silverstripe/silverstripe-userforms/blob/e33fff165d33a077ec4b20c2eef2ef8bca25d15a/code/Model/Recipient/UserFormRecipientItemRequest.php
code/Model/Recipient/UserFormRecipientItemRequest.php
<?php namespace SilverStripe\UserForms\Model\Recipient; use SilverStripe\Core\Config\Config; use SilverStripe\Forms\GridField\GridFieldDetailForm_ItemRequest; use SilverStripe\Model\List\ArrayList; use SilverStripe\ORM\FieldType\DBField; use SilverStripe\UserForms\Model\EditableFormField\EditableFormHeading; use SilverStripe\UserForms\Model\EditableFormField\EditableLiteralField; use SilverStripe\Model\ArrayData; use SilverStripe\View\Requirements; use SilverStripe\View\SSViewer; /** * Controller that handles requests to EmailRecipient's * * @package userforms */ class UserFormRecipientItemRequest extends GridFieldDetailForm_ItemRequest { private static $allowed_actions = [ 'edit', 'view', 'ItemEditForm', 'preview' ]; /** * Renders a preview of the recipient email. */ public function preview() { // Enable theme for preview (may be needed for Shortcodes) Config::nest(); Config::modify()->set(SSViewer::class, 'theme_enabled', true); Requirements::clear(); $content = $this->customise([ 'Body' => $this->record->getEmailBodyContent(), 'HideFormData' => (bool) $this->record->HideFormData, 'Fields' => $this->getPreviewFieldData() ])->renderWith($this->record->EmailTemplate); Requirements::restore(); Config::unnest(); return $content; } /** * Get some placeholder field values to display in the preview * * @return ArrayList<ArrayData> */ protected function getPreviewFieldData() { $data = ArrayList::create(); $fields = $this->record->Form()->Fields(); foreach ($fields as $field) { if (!$field->showInReports()) { continue; } $data->push(ArrayData::create([ 'Name' => $field->dbObject('Name'), 'Title' => $field->dbObject('Title'), 'Value' => DBField::create_field('Varchar', '$' . $field->Name), 'FormattedValue' => DBField::create_field('Varchar', '$' . $field->Name) ])); } return $data; } }
php
BSD-3-Clause
e33fff165d33a077ec4b20c2eef2ef8bca25d15a
2026-01-05T05:22:58.009669Z
false
silverstripe/silverstripe-userforms
https://github.com/silverstripe/silverstripe-userforms/blob/e33fff165d33a077ec4b20c2eef2ef8bca25d15a/code/Model/Recipient/EmailRecipientCondition.php
code/Model/Recipient/EmailRecipientCondition.php
<?php namespace SilverStripe\UserForms\Model\Recipient; use LogicException; use SilverStripe\CMS\Controllers\CMSMain; use SilverStripe\CMS\Model\SiteTree; use SilverStripe\Control\Controller; use SilverStripe\ORM\DataObject; use SilverStripe\Security\Member; use SilverStripe\UserForms\Model\Recipient\EmailRecipient; use SilverStripe\UserForms\Model\EditableFormField; /** * Declares a condition that determines whether an email can be sent to a given recipient * * @property int $ConditionFieldID * @property string $ConditionOption * @property string $ConditionValue * @property int $ParentID * @method EditableFormField ConditionField() * @method EmailRecipient Parent() */ class EmailRecipientCondition extends DataObject { /** * List of options * * @config * @var array */ private static $condition_options = [ 'IsBlank' => 'Is blank', 'IsNotBlank' => 'Is not blank', 'Equals' => 'Equals', 'NotEquals' => "Doesn't equal", 'ValueLessThan' => 'Less than', 'ValueLessThanEqual' => 'Less than or equal', 'ValueGreaterThan' => 'Greater than', 'ValueGreaterThanEqual' => 'Greater than or equal', 'Includes' => 'Includes' ]; private static $db = [ 'ConditionOption' => 'Enum("IsBlank,IsNotBlank,Equals,NotEquals,ValueLessThan,ValueLessThanEqual,ValueGreaterThan,ValueGreaterThanEqual,Includes")', 'ConditionValue' => 'Varchar' ]; private static $has_one = [ 'Parent' => EmailRecipient::class, 'ConditionField' => EditableFormField::class ]; private static $table_name = 'UserDefinedForm_EmailRecipientCondition'; /** * * Determine if this rule matches the given condition * * @param $data * * @return bool|null * @throws LogicException */ public function matches($data) { $fieldName = $this->ConditionField()->Name; $fieldValue = isset($data[$fieldName]) ? $data[$fieldName] : null; $conditionValue = $this->ConditionValue; $result = null; switch ($this->ConditionOption) { case 'IsBlank': $result = empty($fieldValue); break; case 'IsNotBlank': $result = !empty($fieldValue); break; case 'ValueLessThan': $result = ($fieldValue < $conditionValue); break; case 'ValueLessThanEqual': $result = ($fieldValue <= $conditionValue); break; case 'ValueGreaterThan': $result = ($fieldValue > $conditionValue); break; case 'ValueGreaterThanEqual': $result = ($fieldValue >= $conditionValue); break; case 'NotEquals': case 'Equals': $result = is_array($fieldValue) ? in_array($conditionValue, $fieldValue) : $fieldValue == $conditionValue; if ($this->ConditionOption == 'NotEquals') { $result = !($result); } break; case 'Includes': $result = is_array($fieldValue) ? in_array($conditionValue, $fieldValue) : stripos($fieldValue ?? '', $conditionValue) !== false; break; default: throw new LogicException("Unhandled rule {$this->ConditionOption}"); break; } return $result; } /** * Return whether a user can create an object of this type * * @param Member $member * @param array $context Virtual parameter to allow context to be passed in to check * @return bool */ public function canCreate($member = null, $context = []) { // Check parent page $parent = $this->getCanCreateContext(func_get_args()); if ($parent) { return $parent->canEdit($member); } // Fall back to secure admin permissions return parent::canCreate($member); } /** * Helper method to check the parent for this object * * @param array $args List of arguments passed to canCreate * @return SiteTree Parent page instance */ protected function getCanCreateContext($args) { // Inspect second parameter to canCreate for a 'Parent' context if (isset($args[1]['Parent'])) { return $args[1]['Parent']; } // Hack in currently edited page if context is missing $controller = Controller::curr(); if ($controller instanceof CMSMain) { return $controller->currentRecord(); } // No page being edited return null; } public function canView($member = null) { return $this->Parent()->canView($member); } public function canEdit($member = null) { return $this->Parent()->canEdit($member); } public function canDelete($member = null) { return $this->canEdit($member); } }
php
BSD-3-Clause
e33fff165d33a077ec4b20c2eef2ef8bca25d15a
2026-01-05T05:22:58.009669Z
false
silverstripe/silverstripe-userforms
https://github.com/silverstripe/silverstripe-userforms/blob/e33fff165d33a077ec4b20c2eef2ef8bca25d15a/code/Model/Submission/SubmittedFileField.php
code/Model/Submission/SubmittedFileField.php
<?php namespace SilverStripe\UserForms\Model\Submission; use SilverStripe\Assets\File; use SilverStripe\Control\Director; use SilverStripe\ORM\FieldType\DBField; use SilverStripe\Versioned\Versioned; use SilverStripe\Security\Member; use SilverStripe\Security\Security; /** * A file uploaded on a {@link UserDefinedForm} and attached to a single * {@link SubmittedForm}. * * @package userforms * @property int $UploadedFileID * @method File UploadedFile() */ class SubmittedFileField extends SubmittedFormField { private static $has_one = [ 'UploadedFile' => File::class ]; private static $table_name = 'SubmittedFileField'; private static $owns = [ 'UploadedFile' ]; private static $cascade_deletes = [ 'UploadedFile' ]; /** * Return the value of this field for inclusion into things such as * reports. */ public function getFormattedValue(): ?DBField { $name = $this->getFileName(); $link = $this->getLink(false); if ($link) { $title = _t(__CLASS__ . '.DOWNLOADFILE', 'Download File'); $file = $this->getUploadedFileFromDraft(); if (!$file->canView()) { if (Security::getCurrentUser()) { // Logged in CMS user without permissions to view file in the CMS $default = 'You don\'t have the right permissions to download this file'; $message = _t(__CLASS__ . '.INSUFFICIENTRIGHTS', $default); return DBField::create_field('HTMLText', sprintf( '<span class="icon font-icon-lock" aria-hidden="true"></span> %s - <em>%s</em>', htmlspecialchars($name, ENT_QUOTES), htmlspecialchars($message, ENT_QUOTES) )); } else { // Userforms submission filled in by non-logged in user being emailed to recipient $message = _t(__CLASS__ . '.YOUMUSTBELOGGEDIN', 'You must be logged in to view this file'); return DBField::create_field('HTMLText', sprintf( '%s - <a href="%s" target="_blank">%s</a> - <em>%s</em>', htmlspecialchars($name, ENT_QUOTES), htmlspecialchars($link, ENT_QUOTES), htmlspecialchars($title, ENT_QUOTES), htmlspecialchars($message, ENT_QUOTES) )); } } else { // Logged in CMS user with permissions to view file in the CMS return DBField::create_field('HTMLText', sprintf( '%s - <a href="%s" target="_blank">%s</a>', htmlspecialchars($name, ENT_QUOTES), htmlspecialchars($link, ENT_QUOTES), htmlspecialchars($title, ENT_QUOTES) )); } } return null; } /** * Return the value for this field in the CSV export. * * @return string */ public function getExportValue() { return ($link = $this->getLink()) ? $link : ''; } /** * Return the link for the file attached to this submitted form field. * * @return string */ public function getLink($grant = true) { if ($file = $this->getUploadedFileFromDraft()) { if ($file->exists()) { $url = $file->getURL($grant); if ($url) { return Director::absoluteURL($url); } return null; } } } /** * As uploaded files are stored in draft by default, this retrieves the * uploaded file from draft mode rather than using the current stage. * * @return File */ public function getUploadedFileFromDraft() { $fileId = $this->UploadedFileID; return Versioned::withVersionedMode(function () use ($fileId) { Versioned::set_stage(Versioned::DRAFT); return File::get()->byID($fileId); }); } /** * Return the name of the file, if present * * @return string */ public function getFileName() { if ($file = $this->getUploadedFileFromDraft()) { return $file->Name; } } }
php
BSD-3-Clause
e33fff165d33a077ec4b20c2eef2ef8bca25d15a
2026-01-05T05:22:58.009669Z
false
silverstripe/silverstripe-userforms
https://github.com/silverstripe/silverstripe-userforms/blob/e33fff165d33a077ec4b20c2eef2ef8bca25d15a/code/Model/Submission/SubmittedFormField.php
code/Model/Submission/SubmittedFormField.php
<?php namespace SilverStripe\UserForms\Model\Submission; use SilverStripe\ORM\DataObject; use SilverStripe\ORM\FieldType\DBField; use SilverStripe\Security\Member; use SilverStripe\UserForms\Model\EditableFormField; /** * Data received from a UserDefinedForm submission * * @package userforms * @property string $Name * @property string $Value * @method SubmittedForm Parent() */ class SubmittedFormField extends DataObject { private static $db = [ 'Name' => 'Varchar', 'Value' => 'Text', 'Title' => 'Varchar(255)', 'Displayed' => 'Boolean', ]; private static $has_one = [ 'Parent' => SubmittedForm::class ]; private static $summary_fields = [ 'Title' => 'Title', 'FormattedValue' => 'Value' ]; private static $table_name = 'SubmittedFormField'; private static $indexes = [ 'Name' => 'Name', ]; /** * @param Member $member * @param array $context * @return boolean */ public function canCreate($member = null, $context = []) { return $this->Parent()->canCreate(); } /** * @param Member $member * * @return boolean */ public function canView($member = null) { return $this->Parent()->canView(); } /** * @param Member $member * * @return boolean */ public function canEdit($member = null) { return $this->Parent()->canEdit(); } /** * @param Member $member * * @return boolean */ public function canDelete($member = null) { return $this->Parent()->canDelete(); } /** * Generate a formatted value for the reports and email notifications. * Converts new lines (which are stored in the database text field) as * <brs> so they will output as newlines in the reports. * * @return DBField */ public function getFormattedValue() { return $this->dbObject('Value'); } /** * Return the value of this submitted form field suitable for inclusion * into the CSV * * @return DBField */ public function getExportValue() { return $this->Value; } /** * Find equivalent editable field for this submission. * * Note the field may have been modified or deleted from the original form * so this may not always return the data you expect. If you need to save * a particular state of editable form field at time of submission, copy * that value to the submission. * * @return EditableFormField */ public function getEditableField() { return $this->Parent()->Parent()->Fields()->filter([ 'Name' => $this->Name ])->First(); } }
php
BSD-3-Clause
e33fff165d33a077ec4b20c2eef2ef8bca25d15a
2026-01-05T05:22:58.009669Z
false
silverstripe/silverstripe-userforms
https://github.com/silverstripe/silverstripe-userforms/blob/e33fff165d33a077ec4b20c2eef2ef8bca25d15a/code/Model/Submission/SubmittedForm.php
code/Model/Submission/SubmittedForm.php
<?php namespace SilverStripe\UserForms\Model\Submission; use SilverStripe\Forms\FieldList; use SilverStripe\Forms\GridField\GridField; use SilverStripe\Forms\GridField\GridFieldButtonRow; use SilverStripe\Forms\GridField\GridFieldConfig; use SilverStripe\Forms\GridField\GridFieldDataColumns; use SilverStripe\Forms\GridField\GridFieldExportButton; use SilverStripe\Forms\GridField\GridFieldPrintButton; use SilverStripe\Forms\ReadonlyField; use SilverStripe\ORM\DataObject; use SilverStripe\ORM\DB; use SilverStripe\ORM\HasManyList; use SilverStripe\Security\Member; /** * @package userforms * @property int $SubmittedByID * @property int $ParentID * @method DataObject Parent() * @method Member SubmittedBy() * @method HasManyList<SubmittedFormField> Values() */ class SubmittedForm extends DataObject { private static $has_one = [ 'SubmittedBy' => Member::class, 'Parent' => DataObject::class, ]; private static $has_many = [ 'Values' => SubmittedFormField::class ]; private static $cascade_deletes = [ 'Values', ]; private static $summary_fields = [ 'ID', 'Created.Nice' => 'Created' ]; private static $table_name = 'SubmittedForm'; public function requireDefaultRecords() { parent::requireDefaultRecords(); // make sure to migrate the class across (prior to v5.x) DB::query("UPDATE \"SubmittedForm\" SET \"ParentClass\" = 'Page' WHERE \"ParentClass\" IS NULL"); } /** * Returns the value of a relation or, in the case of this form, the value * of a given child {@link SubmittedFormField} * * @param string * * @return mixed */ public function relField($fieldName) { // default case if ($value = parent::relField($fieldName)) { return $value; } // check values for a form field with the matching name. $formField = SubmittedFormField::get()->filter(array( 'ParentID' => $this->ID, 'Name' => $fieldName ))->first(); if ($formField) { return $formField->getFormattedValue(); } } /** * @return FieldList */ public function getCMSFields() { $this->beforeUpdateCMSFields(function (FieldList $fields) { $fields->removeByName('Values'); //check to ensure there is a Member to extract an Email from else null value if ($this->SubmittedBy() && $this->SubmittedBy()->exists()) { $submitter = $this->SubmittedBy()->Email; } else { $submitter = null; } //replace scaffolded field with readonly submitter $fields->replaceField( 'SubmittedByID', ReadonlyField::create('Submitter', _t(__CLASS__ . '.SUBMITTER', 'Submitter'), $submitter) ->addExtraClass('form-field--no-divider') ); $values = GridField::create( 'Values', SubmittedFormField::class, $this->Values()->sort('Created', 'ASC') ); $exportColumns = array( 'Title' => 'Title', 'ExportValue' => 'Value' ); $config = GridFieldConfig::create(); $config->addComponent(new GridFieldDataColumns()); $config->addComponent(new GridFieldButtonRow('after')); $config->addComponent(new GridFieldExportButton('buttons-after-left', $exportColumns)); $config->addComponent(new GridFieldPrintButton('buttons-after-left')); $values->setConfig($config); $fields->addFieldToTab('Root.Main', $values); }); $fields = parent::getCMSFields(); return $fields; } /** * @param Member * * @return boolean */ public function canCreate($member = null, $context = []) { $extended = $this->extendedCan(__FUNCTION__, $member); if ($extended !== null) { return $extended; } if ($this->Parent()) { return $this->Parent()->canCreate($member); } return parent::canCreate($member); } /** * @param Member * * @return boolean */ public function canView($member = null) { $extended = $this->extendedCan(__FUNCTION__, $member); if ($extended !== null) { return $extended; } if ($this->Parent()) { return $this->Parent()->canView($member); } return parent::canView($member); } /** * @param Member * * @return boolean */ public function canEdit($member = null) { $extended = $this->extendedCan(__FUNCTION__, $member); if ($extended !== null) { return $extended; } if ($this->Parent()) { return $this->Parent()->canEdit($member); } return parent::canEdit($member); } /** * @param Member * * @return boolean */ public function canDelete($member = null) { $extended = $this->extendedCan(__FUNCTION__, $member); if ($extended !== null) { return $extended; } if ($this->Parent()) { return $this->Parent()->canDelete($member); } return parent::canDelete($member); } /** * Before we delete this form make sure we delete all the field values so * that we don't leave old data round. * * @return void */ protected function onBeforeDelete() { if ($this->Values()) { foreach ($this->Values() as $value) { $value->delete(); } } parent::onBeforeDelete(); } }
php
BSD-3-Clause
e33fff165d33a077ec4b20c2eef2ef8bca25d15a
2026-01-05T05:22:58.009669Z
false
silverstripe/silverstripe-userforms
https://github.com/silverstripe/silverstripe-userforms/blob/e33fff165d33a077ec4b20c2eef2ef8bca25d15a/code/Model/EditableFormField/EditableTextField.php
code/Model/EditableFormField/EditableTextField.php
<?php namespace SilverStripe\UserForms\Model\EditableFormField; use SilverStripe\Core\ClassInfo; use SilverStripe\Forms\DropdownField; use SilverStripe\Forms\FieldGroup; use SilverStripe\Forms\FieldList; use SilverStripe\Forms\FormField; use SilverStripe\Forms\LiteralField; use SilverStripe\Forms\NumericField; use SilverStripe\Forms\TextareaField; use SilverStripe\Forms\TextField; use SilverStripe\Core\Validation\ValidationResult; use SilverStripe\UserForms\Model\EditableFormField; /** * EditableTextField * * This control represents a user-defined text field in a user defined form * * @package userforms * @property string $Autocomplete * @property int $MaxLength * @property int $MinLength * @property int $Rows */ class EditableTextField extends EditableFormField { private static $singular_name = 'Text Field'; private static $plural_name = 'Text Fields'; private static $has_placeholder = true; private static $autocomplete_options = [ 'off' => 'Off', 'on' => 'On', 'name' => 'Full name', 'honorific-prefix' => 'Prefix or title', 'given-name' => 'First name', 'additional-name' => 'Additional name', 'family-name' => 'Family name', 'honorific-suffix' => 'Suffix (e.g Jr.)', 'nickname' => 'Nickname', 'email' => 'Email', 'organization-title' => 'Job title', 'organization' => 'Organization', 'street-address' => 'Street address', 'address-line1' => 'Address line 1', 'address-line2' => 'Address line 2', 'address-line3' => 'Address line 3', 'address-level1' => 'Address level 1', 'address-level2' => 'Address level 2', 'address-level3' => 'Address level 3', 'address-level4' => 'Address level 4', 'country' => 'Country', 'country-name' => 'Country name', 'postal-code' => 'Postal code', 'bday' => 'Birthday', 'sex' => 'Gender identity', 'tel' => 'Telephone number', 'url' => 'Home page' ]; protected $jsEventHandler = 'keyup'; private static $db = [ 'MinLength' => 'Int', 'MaxLength' => 'Int', 'Rows' => 'Int(1)', 'Autocomplete' => 'Varchar(255)' ]; private static $defaults = [ 'Rows' => 1 ]; private static $table_name = 'EditableTextField'; public function getCMSFields() { $this->beforeUpdateCMSFields(function ($fields) { $fields->addFieldsToTab( 'Root.Main', [ NumericField::create( 'Rows', _t(__CLASS__.'.NUMBERROWS', 'Number of rows') )->setDescription(_t( __CLASS__.'.NUMBERROWS_DESCRIPTION', 'Fields with more than one row will be generated as a textarea' )), DropdownField::create( 'Autocomplete', _t(__CLASS__.'.AUTOCOMPLETE', 'Autocomplete'), $this->config()->get('autocomplete_options') )->setDescription(_t( __CLASS__.'.AUTOCOMPLETE_DESCRIPTION', 'Supported browsers will attempt to populate this field automatically with the users information, use to set the value populated' )) ] ); }); return parent::getCMSFields(); } public function validate(): ValidationResult { $result = parent::validate(); if ($this->MinLength > $this->MaxLength) { $result->addError(_t( __CLASS__ . '.MINMAXLENGTHCHECK', 'Minimum length should be less than the Maximum length.' )); } return $result; } /** * @return FieldList */ public function getFieldValidationOptions() { $fields = parent::getFieldValidationOptions(); $fields->merge([ FieldGroup::create( _t(__CLASS__.'.TEXTLENGTH', 'Allowed text length'), [ NumericField::create('MinLength', false) ->setAttribute('aria-label', _t(__CLASS__ . '.MIN_LENGTH', 'Minimum text length')), LiteralField::create( 'RangeLength', '<span class="userform-field__allowed-length-separator">' . _t(__CLASS__ . '.RANGE_TO', 'to') . '</span>' ), NumericField::create('MaxLength', false) ->setAttribute('aria-label', _t(__CLASS__ . '.MAX_LENGTH', 'Maximum text length')), ] )->addExtraClass('userform-field__allowed-length') ]); return $fields; } /** * @return TextareaField|TextField */ public function getFormField() { if ($this->Rows > 1) { $field = TextareaField::create($this->Name, $this->Title ?: false, $this->Default) ->setFieldHolderTemplate(EditableFormField::class . '_holder') ->setTemplate(str_replace('EditableTextField', 'EditableTextareaField', __CLASS__)) ->setRows($this->Rows); } else { $field = TextField::create($this->Name, $this->Title ?: false, $this->Default) ->setFieldHolderTemplate(EditableFormField::class . '_holder') ->setTemplate(EditableFormField::class); } $this->doUpdateFormField($field); return $field; } /** * Updates a formfield with the additional metadata specified by this field * * @param FormField $field */ protected function updateFormField($field) { parent::updateFormField($field); if (is_numeric($this->MinLength) && $this->MinLength > 0) { $field->setAttribute('data-rule-minlength', (int) $this->MinLength); } if (is_numeric($this->MaxLength) && $this->MaxLength > 0) { if (ClassInfo::hasMethod($field, 'setMaxLength')) { $field->setMaxLength((int) $this->MaxLength); } $field->setAttribute('data-rule-maxlength', (int) $this->MaxLength); } if ($this->Autocomplete) { $field->setAttribute('autocomplete', $this->Autocomplete); } } }
php
BSD-3-Clause
e33fff165d33a077ec4b20c2eef2ef8bca25d15a
2026-01-05T05:22:58.009669Z
false
silverstripe/silverstripe-userforms
https://github.com/silverstripe/silverstripe-userforms/blob/e33fff165d33a077ec4b20c2eef2ef8bca25d15a/code/Model/EditableFormField/EditableFileField.php
code/Model/EditableFormField/EditableFileField.php
<?php namespace SilverStripe\UserForms\Model\EditableFormField; use SilverStripe\Assets\File; use SilverStripe\Assets\Folder; use SilverStripe\Assets\Upload_Validator; use SilverStripe\Core\Config\Config; use SilverStripe\Core\Convert; use SilverStripe\Forms\FieldList; use SilverStripe\Core\Injector\Injector; use SilverStripe\Forms\FileField; use SilverStripe\Forms\LiteralField; use SilverStripe\Forms\NumericField; use SilverStripe\Forms\TreeDropdownField; use SilverStripe\Core\Validation\ValidationResult; use SilverStripe\Security\Member; use SilverStripe\Security\InheritedPermissions; use SilverStripe\UserForms\Control\UserDefinedFormAdmin; use SilverStripe\UserForms\Control\UserDefinedFormController; use SilverStripe\UserForms\Model\EditableFormField; use SilverStripe\UserForms\Model\Submission\SubmittedFileField; /** * Allows a user to add a field that can be used to upload a file. * * @package userforms * @property int $FolderConfirmed * @property int $FolderID * @property float $MaxFileSizeMB * @method Folder Folder() */ class EditableFileField extends EditableFormField { private static $singular_name = 'File Upload Field'; private static $plural_names = 'File Fields'; private static $db = [ 'MaxFileSizeMB' => 'Float', 'FolderConfirmed' => 'Boolean', ]; private static $has_one = [ 'Folder' => Folder::class // From CustomFields ]; private static $table_name = 'EditableFileField'; /** * Further limit uploadable file extensions in addition to the restrictions * imposed by the File.allowed_extensions global configuration. * @config */ private static $allowed_extensions_blacklist = [ 'htm', 'html', 'xhtml', 'swf', 'xml' ]; /** * Returns a string describing the permissions of a folder * @param Folder|null $folder * @return string */ public static function getFolderPermissionString(?Folder $folder = null) { $folderPermissions = static::getFolderPermissionTuple($folder); $icon = 'font-icon-user-lock'; if ($folderPermissions['CanViewType'] == InheritedPermissions::ANYONE) { $icon = 'font-icon-address-card-warning'; } return sprintf( '<span class="icon %s form-description__icon" aria-hidden="true"></span>%s %s', $icon, $folderPermissions['CanViewTypeString'], htmlspecialchars(implode(', ', $folderPermissions['ViewerGroups']), ENT_QUOTES) ); } /** * Returns an array with a view type string and the viewer groups * @param Folder|null $folder * @return array */ private static function getFolderPermissionTuple(?Folder $folder = null) { $viewersOptionsField = [ InheritedPermissions::INHERIT => _t(__CLASS__.'.INHERIT', 'Visibility for this folder is inherited from the parent folder'), InheritedPermissions::ANYONE => _t(__CLASS__.'.ANYONE', 'Unrestricted access, uploads will be visible to anyone'), InheritedPermissions::LOGGED_IN_USERS => _t(__CLASS__.'.LOGGED_IN', 'Restricted access, uploads will be visible to logged-in users'), InheritedPermissions::ONLY_THESE_USERS => _t(__CLASS__.'.ONLY_GROUPS', 'Restricted access, uploads will be visible to the following groups:') ]; if (!$folder) { return [ 'CanViewType' => InheritedPermissions::ANYONE, 'CanViewTypeString' => $viewersOptionsField[InheritedPermissions::ANYONE], 'ViewerGroups' => [], ]; } $folder = static::getNonInheritedViewType($folder); // ViewerGroups may still exist when permissions have been loosened $viewerGroups = []; if ($folder->CanViewType === InheritedPermissions::ONLY_THESE_USERS) { $viewerGroups = $folder->ViewerGroups()->column('Title'); } return [ 'CanViewType' => $folder->CanViewType, 'CanViewTypeString' => $viewersOptionsField[$folder->CanViewType], 'ViewerGroups' => $viewerGroups, ]; } /** * Returns the nearest non-inherited view permission of the provided * @param File $file * @return File */ private static function getNonInheritedViewType(File $file) { if ($file->CanViewType !== InheritedPermissions::INHERIT) { return $file; } $parent = $file->Parent(); if ($parent->exists()) { return static::getNonInheritedViewType($parent); } else { // anyone can view top level files $file->CanViewType = InheritedPermissions::ANYONE; } return $file; } /** * @return FieldList */ public function getCMSFields() { $this->beforeUpdateCMSFields(function (FieldList $fields) { $treeView = TreeDropdownField::create( 'FolderID', _t(__CLASS__.'.SELECTUPLOADFOLDER', 'Select upload folder'), Folder::class ); $treeView->setDescription(static::getFolderPermissionString($this->Folder())); $fields->addFieldToTab( 'Root.Main', $treeView ); // Warn the user if the folder targeted by this field is not restricted if ($this->FolderID && !$this->Folder()->hasRestrictedAccess()) { $fields->addFieldToTab("Root.Main", LiteralField::create( 'FileUploadWarning', '<p class="alert alert-warning">' . _t( 'SilverStripe\\UserForms\\Model\\UserDefinedForm.UnrestrictedFileUploadWarning', 'Access to the current upload folder "{path}" is not restricted. Uploaded files will be publicly accessible if the exact URL is known.', ['path' => Convert::raw2att($this->Folder()->Filename)] ) . '</p>' ), 'Type'); } $fields->addFieldToTab( 'Root.Main', NumericField::create('MaxFileSizeMB') ->setTitle('Max File Size MB') ->setDescription("Note: Maximum php allowed size is {$this->getPHPMaxFileSizeMB()} MB") ); $fields->removeByName('Default'); }); return parent::getCMSFields(); } public function validate(): ValidationResult { $result = parent::validate(); $max = static::get_php_max_file_size(); if ($this->MaxFileSizeMB * 1024 * 1024 > $max) { $result->addError("Your max file size limit can't be larger than the server's limit of {$this->getPHPMaxFileSizeMB()}."); } return $result; } public function getFolderExists(): bool { return $this->Folder()->ID !== 0; } public function createProtectedFolder(): void { $folderName = sprintf('page-%d/upload-field-%d', $this->ParentID, $this->ID); $folder = UserDefinedFormAdmin::getFormSubmissionFolder($folderName); $this->FolderID = $folder->ID; $this->write(); } public function getFormField() { $field = FileField::create($this->Name, $this->Title ?: false) ->setFieldHolderTemplate(EditableFormField::class . '_holder') ->setTemplate(__CLASS__) ->setValidator(Injector::inst()->get(Upload_Validator::class . '.userforms', false)); $field->setFieldHolderTemplate(EditableFormField::class . '_holder') ->setTemplate(__CLASS__); $field->getValidator()->setAllowedExtensions( array_diff( // filter out '' since this would be a regex problem on JS end array_filter(Config::inst()->get(File::class, 'allowed_extensions') ?? []), $this->config()->get('allowed_extensions_blacklist') ) ); if ($this->MaxFileSizeMB > 0) { $field->getValidator()->setAllowedMaxFileSize($this->MaxFileSizeMB * 1024 * 1024); } else { $field->getValidator()->setAllowedMaxFileSize(static::get_php_max_file_size()); } $folder = $this->Folder(); if ($folder && $folder->exists()) { $field->setFolderName( preg_replace("/^assets\//", "", $folder->Filename ?? '') ); } $this->doUpdateFormField($field); return $field; } /** * Return the value for the database, link to the file is stored as a * relation so value for the field can be null. * * @return string */ public function getValueFromData() { return null; } public function getSubmittedFormField() { return SubmittedFileField::create(); } /** * @return float */ public static function get_php_max_file_size() { $maxUpload = Convert::memstring2bytes(ini_get('upload_max_filesize')); $maxPost = Convert::memstring2bytes(ini_get('post_max_size')); return min($maxUpload, $maxPost); } public function getPHPMaxFileSizeMB() { return round(static::get_php_max_file_size() / 1024 / 1024, 1); } protected function onBeforeWrite() { parent::onBeforeWrite(); $folderChanged = $this->isChanged('FolderID'); // Default to either an existing sibling's folder, or the default form submissions folder if ($this->FolderID === null) { $inheritableSibling = EditableFileField::get()->filter([ 'ParentID' => $this->ParentID, 'FolderConfirmed' => true, ])->first(); if ($inheritableSibling) { $this->FolderID = $inheritableSibling->FolderID; } else { $folder = UserDefinedFormAdmin::getFormSubmissionFolder(); $this->FolderID = $folder->ID; } } if ($folderChanged) { $this->FolderConfirmed = true; } } }
php
BSD-3-Clause
e33fff165d33a077ec4b20c2eef2ef8bca25d15a
2026-01-05T05:22:58.009669Z
false
silverstripe/silverstripe-userforms
https://github.com/silverstripe/silverstripe-userforms/blob/e33fff165d33a077ec4b20c2eef2ef8bca25d15a/code/Model/EditableFormField/EditableDateField.php
code/Model/EditableFormField/EditableDateField.php
<?php namespace SilverStripe\UserForms\Model\EditableFormField; use SilverStripe\Forms\CheckboxField; use SilverStripe\Forms\FieldList; use SilverStripe\ORM\FieldType\DBDatetime; use SilverStripe\UserForms\Model\EditableFormField; use SilverStripe\UserForms\Model\EditableFormField\EditableDateField\FormField; /** * EditableDateField * * Allows a user to add a date field. * * @package userforms * @property int $DefaultToToday */ class EditableDateField extends EditableFormField { private static $singular_name = 'Date Field'; private static $plural_name = 'Date Fields'; private static $has_placeholder = true; private static $db = [ 'DefaultToToday' => 'Boolean' // From customsettings ]; private static $table_name = 'EditableDateField'; /** * @return FieldList */ public function getCMSFields() { $this->beforeUpdateCMSFields(function (FieldList $fields) { $fields->addFieldToTab( 'Root.Main', CheckboxField::create( 'DefaultToToday', _t('SilverStripe\\UserForms\\Model\\EditableFormField.DEFAULTTOTODAY', 'Default to Today?') ), 'RightTitle' ); }); return parent::getCMSFields(); } /** * Return the form field * */ public function getFormField() { $defaultValue = $this->DefaultToToday ? DBDatetime::now()->Format('yyyy-MM-dd') : $this->Default; $field = FormField::create($this->Name, $this->Title ?: false, $defaultValue) ->setFieldHolderTemplate(EditableFormField::class . '_holder') ->setTemplate(EditableFormField::class); $this->doUpdateFormField($field); return $field; } }
php
BSD-3-Clause
e33fff165d33a077ec4b20c2eef2ef8bca25d15a
2026-01-05T05:22:58.009669Z
false
silverstripe/silverstripe-userforms
https://github.com/silverstripe/silverstripe-userforms/blob/e33fff165d33a077ec4b20c2eef2ef8bca25d15a/code/Model/EditableFormField/EditableCountryDropdownField.php
code/Model/EditableFormField/EditableCountryDropdownField.php
<?php namespace SilverStripe\UserForms\Model\EditableFormField; use SilverStripe\Core\Manifest\ModuleLoader; use SilverStripe\Forms\CheckboxField; use SilverStripe\Forms\DropdownField; use SilverStripe\Forms\FieldList; use SilverStripe\Forms\TextField; use SilverStripe\i18n\i18n; use SilverStripe\UserForms\Model\EditableCustomRule; use SilverStripe\UserForms\Model\EditableFormField; /** * A dropdown field which allows the user to select a country * * @package userforms * @property bool $UseEmptyString * @property string $EmptyString */ class EditableCountryDropdownField extends EditableFormField { private static $singular_name = 'Country Dropdown'; private static $plural_name = 'Country Dropdowns'; private static $db = array( 'UseEmptyString' => 'Boolean', 'EmptyString' => 'Varchar(255)', ); private static $table_name = 'EditableCountryDropdownField'; /** * @return \SilverStripe\Forms\FieldList */ public function getCMSFields() { $this->beforeUpdateCMSFields(function (FieldList $fields) { $fields->removeByName('Default'); $fields->addFieldToTab( 'Root.Main', DropdownField::create('Default', _t(__CLASS__ . '.DEFAULT', 'Default value')) ->setSource(i18n::getData()->getCountries()) ->setHasEmptyDefault(true) ->setEmptyString('---') ); $fields->addFieldToTab( 'Root.Main', CheckboxField::create('UseEmptyString', _t(__CLASS__ . '.USE_EMPTY_STRING', 'Set default empty string')) ); $fields->addFieldToTab( 'Root.Main', TextField::create('EmptyString', _t(__CLASS__ . '.EMPTY_STRING', 'Empty String')) ); }); return parent::getCMSFields(); } public function getFormField() { $field = DropdownField::create($this->Name, $this->Title ?: false) ->setSource(i18n::getData()->getCountries()) ->setFieldHolderTemplate(EditableFormField::class . '_holder') ->setTemplate(EditableDropdown::class); // Empty string if ($this->UseEmptyString) { $field->setEmptyString($this->EmptyString ?: ''); } // Set default if ($this->Default) { $field->setValue($this->Default); } $this->doUpdateFormField($field); return $field; } public function getValueFromData($data) { if (!empty($data[$this->Name])) { $source = $this->getFormField()->getSource(); return $source[$data[$this->Name]]; } } public function getIcon() { $resource = ModuleLoader::getModule('silverstripe/userforms')->getResource('images/editabledropdown.png'); if (!$resource->exists()) { return ''; } return $resource->getURL(); } public function getSelectorField(EditableCustomRule $rule, $forOnLoad = false) { return "$(\"select[name='{$this->Name}']\")"; } }
php
BSD-3-Clause
e33fff165d33a077ec4b20c2eef2ef8bca25d15a
2026-01-05T05:22:58.009669Z
false
silverstripe/silverstripe-userforms
https://github.com/silverstripe/silverstripe-userforms/blob/e33fff165d33a077ec4b20c2eef2ef8bca25d15a/code/Model/EditableFormField/EditableLiteralField.php
code/Model/EditableFormField/EditableLiteralField.php
<?php namespace SilverStripe\UserForms\Model\EditableFormField; use SilverStripe\Core\Injector\Injector; use SilverStripe\Forms\FieldList; use SilverStripe\Forms\HTMLEditor\HTMLEditorConfig; use SilverStripe\Forms\HTMLEditor\HTMLEditorField; use SilverStripe\Forms\HTMLEditor\HTMLEditorSanitiser; use SilverStripe\Forms\CheckboxField; use SilverStripe\Forms\CompositeField; use SilverStripe\Forms\LiteralField; use SilverStripe\UserForms\Model\EditableFormField; use SilverStripe\View\Parsers\HTMLValue; /** * Editable Literal Field. A literal field is just a blank slate where * you can add your own HTML / Images / Flash * * @package userforms * @property string $Content * @property int $HideFromReports * @property int $HideLabel */ class EditableLiteralField extends EditableFormField { private static $singular_name = 'HTML Block'; private static $plural_name = 'HTML Blocks'; private static $table_name = 'EditableLiteralField'; /** * Mark as literal only * * @config * @var bool */ private static $literal = true; /** * Get the name of the editor config to use for HTML sanitisation. Defaults to the active config. * * @var string * @config */ private static $editor_config = null; private static $db = [ 'Content' => 'HTMLText', // From CustomSettings 'HideFromReports' => 'Boolean(0)', // from CustomSettings 'HideLabel' => 'Boolean(0)' ]; private static $defaults = [ 'HideFromReports' => false ]; /** * Returns the {@see HTMLEditorConfig} instance to use for sanitisation * * @return HTMLEditorConfig */ protected function getEditorConfig() { $editorConfig = $this->config()->get('editor_config'); if ($editorConfig) { return HTMLEditorConfig::get($editorConfig); } return HTMLEditorConfig::get_active(); } /** * Safely sanitise html content, if enabled * * @param string $content Raw html * @return string Safely sanitised html */ protected function sanitiseContent($content) { // Check if sanitisation is enabled if (!HTMLEditorField::config()->get('sanitise_server_side')) { return $content; } // Perform sanitisation $htmlValue = Injector::inst()->create(HTMLValue::class, $content); $santiser = Injector::inst()->create(HTMLEditorSanitiser::class, $this->getEditorConfig()); $santiser->sanitise($htmlValue); return $htmlValue->getContent(); } /** * Get HTML Content of this literal field * * @return string */ public function getContent() { // Apply html editor sanitisation rules $content = $this->getField('Content'); return $this->sanitiseContent($content); } /** * Set the content with the given value * * @param string $content */ public function setContent($content) { // Apply html editor sanitisation rules $content = $this->sanitiseContent($content); $this->setField('Content', $content); } /** * @return FieldList */ public function getCMSFields() { $this->beforeUpdateCMSFields(function (FieldList $fields) { $fields->removeByName(['Default', 'Validation', 'RightTitle']); $fields->addFieldsToTab('Root.Main', [ HTMLEditorField::create('Content', _t(__CLASS__ . '.CONTENT', 'HTML')) ->setRows(4) ->setColumns(20), CheckboxField::create( 'HideFromReports', _t(__CLASS__ . '.HIDEFROMREPORT', 'Hide from reports?') ), CheckboxField::create( 'HideLabel', _t(__CLASS__ . '.HIDELABEL', "Hide 'Title' label on frontend?") ) ]); }); return parent::getCMSFields(); } public function getFormField() { $content = LiteralField::create( "LiteralFieldContent-{$this->ID}]", $this->dbObject('Content')->forTemplate() ); $field = CompositeField::create($content) ->setName($this->Name) ->setFieldHolderTemplate(__CLASS__ . '_holder'); $this->doUpdateFormField($field); return $field; } protected function updateFormField($field) { parent::updateFormField($field); if ($this->HideLabel) { $field->addExtraClass('nolabel'); } else { $field->setTitle($this->Title); } } public function showInReports() { return !$this->HideFromReports; } }
php
BSD-3-Clause
e33fff165d33a077ec4b20c2eef2ef8bca25d15a
2026-01-05T05:22:58.009669Z
false
silverstripe/silverstripe-userforms
https://github.com/silverstripe/silverstripe-userforms/blob/e33fff165d33a077ec4b20c2eef2ef8bca25d15a/code/Model/EditableFormField/EditableRadioField.php
code/Model/EditableFormField/EditableRadioField.php
<?php namespace SilverStripe\UserForms\Model\EditableFormField; use SilverStripe\Forms\FieldList; use SilverStripe\UserForms\FormField\UserFormsOptionSetField; use SilverStripe\UserForms\Model\EditableCustomRule; /** * EditableRadioField * * Represents a set of selectable radio buttons * * @package userforms */ class EditableRadioField extends EditableMultipleOptionField { private static $singular_name = 'Radio Group'; private static $plural_name = 'Radio Groups'; private static $table_name = 'EditableRadioField'; /** * @return FieldList */ public function getCMSFields() { $this->beforeUpdateCMSFields(function (FieldList $fields) { $fields->removeByName('Default'); }); return parent::getCMSFields(); } public function getFormField() { $field = UserFormsOptionSetField::create($this->Name, $this->Title ?: false, $this->getOptionsMap()) ->setFieldHolderTemplate(EditableMultipleOptionField::class . '_holder') ->setTemplate(UserFormsOptionSetField::class); // Set default item $defaultOption = $this->getDefaultOptions()->first(); if ($defaultOption) { $field->setValue($defaultOption->Value); } $this->doUpdateFormField($field); return $field; } public function getSelectorField(EditableCustomRule $rule, $forOnLoad = false) { // We only want to trigger on load once for the radio group - hence we focus on the first option only. $first = $forOnLoad ? ':first' : ''; return "$(\"input[name='{$this->Name}']{$first}\")"; } public function isRadioField() { return true; } }
php
BSD-3-Clause
e33fff165d33a077ec4b20c2eef2ef8bca25d15a
2026-01-05T05:22:58.009669Z
false
silverstripe/silverstripe-userforms
https://github.com/silverstripe/silverstripe-userforms/blob/e33fff165d33a077ec4b20c2eef2ef8bca25d15a/code/Model/EditableFormField/EditableMemberListField.php
code/Model/EditableFormField/EditableMemberListField.php
<?php namespace SilverStripe\UserForms\Model\EditableFormField; use SilverStripe\Forms\DropdownField; use SilverStripe\Forms\FieldList; use SilverStripe\Security\Group; use SilverStripe\Security\Member; use SilverStripe\UserForms\Model\EditableFormField; /** * Creates an editable field that displays members in a given group * * @package userforms * @property int $GroupID * @method Group Group() */ class EditableMemberListField extends EditableFormField { private static $singular_name = 'Member List Field'; private static $plural_name = 'Member List Fields'; private static $has_one = [ 'Group' => Group::class ]; private static $table_name = 'EditableMemberListField'; /** * @return FieldList */ public function getCMSFields() { $this->beforeUpdateCMSFields(function (FieldList $fields) { $fields->removeByName('Default'); $fields->removeByName('Validation'); $fields->addFieldToTab( 'Root.Main', DropdownField::create( 'GroupID', _t('SilverStripe\\UserForms\\Model\\EditableFormField.GROUP', 'Group'), Group::get()->map() )->setEmptyString(' ') ); }); return parent::getCMSFields(); } public function getFormField() { if (empty($this->GroupID)) { return false; } $members = Member::map_in_groups($this->GroupID); $field = DropdownField::create($this->Name, $this->Title ?: false, $members) ->setTemplate(EditableDropdown::class) ->setFieldHolderTemplate(EditableFormField::class . '_holder'); $this->doUpdateFormField($field); return $field; } public function getValueFromData($data) { if (isset($data[$this->Name])) { $memberID = $data[$this->Name]; $member = Member::get()->byID($memberID); return $member ? $member->getName() : ''; } return false; } }
php
BSD-3-Clause
e33fff165d33a077ec4b20c2eef2ef8bca25d15a
2026-01-05T05:22:58.009669Z
false
silverstripe/silverstripe-userforms
https://github.com/silverstripe/silverstripe-userforms/blob/e33fff165d33a077ec4b20c2eef2ef8bca25d15a/code/Model/EditableFormField/EditableFieldGroupEnd.php
code/Model/EditableFormField/EditableFieldGroupEnd.php
<?php namespace SilverStripe\UserForms\Model\EditableFormField; use SilverStripe\Forms\FieldList; use SilverStripe\Forms\HiddenField; use SilverStripe\Forms\LabelField; use SilverStripe\UserForms\Model\EditableFormField; /** * Specifies that this ends a group of fields * * @method EditableFieldGroup Group() */ class EditableFieldGroupEnd extends EditableFormField { private static $belongs_to = [ 'Group' => EditableFieldGroup::class ]; /** * Disable selection of group class * * @config * @var bool */ private static $hidden = true; /** * Non-data type * * @config * @var bool */ private static $literal = true; private static $table_name = 'EditableFieldGroupEnd'; public function getCMSTitle() { $group = $this->Group(); return _t( __CLASS__.'.FIELD_GROUP_END', '{group} end', [ 'group' => ($group && $group->exists()) ? $group->CMSTitle : 'Group' ] ); } public function getCMSFields() { $this->beforeUpdateCMSFields(function (FieldList $fields) { $fields->removeByName(['MergeField', 'Default', 'Validation', 'DisplayRules']); }); return parent::getCMSFields(); } public function getInlineClassnameField($column, $fieldClasses) { return LabelField::create($column, $this->CMSTitle); } public function getInlineTitleField($column) { return HiddenField::create($column); } public function getFormField() { return null; } public function showInReports() { return false; } protected function onAfterWrite() { parent::onAfterWrite(); // If this is not attached to a group, find the first group prior to this // with no end attached $group = $this->Group(); if (!($group && $group->exists()) && $this->ParentID) { $group = EditableFieldGroup::get() ->filter([ 'ParentID' => $this->ParentID, 'Sort:LessThanOrEqual' => $this->Sort ]) ->where('"EditableFieldGroup"."EndID" IS NULL OR "EditableFieldGroup"."EndID" = 0') ->sort('"Sort" DESC') ->first(); // When a group is found, attach it to this end if ($group) { $group->EndID = $this->ID; $group->write(); } } } }
php
BSD-3-Clause
e33fff165d33a077ec4b20c2eef2ef8bca25d15a
2026-01-05T05:22:58.009669Z
false
silverstripe/silverstripe-userforms
https://github.com/silverstripe/silverstripe-userforms/blob/e33fff165d33a077ec4b20c2eef2ef8bca25d15a/code/Model/EditableFormField/EditableCheckboxGroupField.php
code/Model/EditableFormField/EditableCheckboxGroupField.php
<?php namespace SilverStripe\UserForms\Model\EditableFormField; use SilverStripe\UserForms\FormField\UserFormsCheckboxSetField; use SilverStripe\UserForms\Model\EditableCustomRule; /** * EditableCheckboxGroup * * Represents a set of selectable radio buttons * * @package userforms */ class EditableCheckboxGroupField extends EditableMultipleOptionField { private static $singular_name = 'Checkbox Group'; private static $plural_name = 'Checkbox Groups'; protected $jsEventHandler = 'click'; private static $table_name = 'EditableCheckboxGroupField'; public function getFormField() { $field = UserFormsCheckboxSetField::create($this->Name, $this->Title ?: false, $this->getOptionsMap()) ->setFieldHolderTemplate(EditableMultipleOptionField::class . '_holder') ->setTemplate(UserFormsCheckboxSetField::class); // Set the default checked items $defaultCheckedItems = $this->getDefaultOptions(); if ($defaultCheckedItems->count()) { $field->setDefaultItems($defaultCheckedItems->map('Value')->keys()); } $this->doUpdateFormField($field); return $field; } public function getValueFromData($data) { $result = ''; $entries = (isset($data[$this->Name])) ? $data[$this->Name] : false; if ($entries) { if (!is_array($data[$this->Name])) { $entries = [$data[$this->Name]]; } foreach ($entries as $selected => $value) { if (!$result) { $result = $value; } else { $result .= ', ' . $value; } } } return $result; } public function getSelectorField(EditableCustomRule $rule, $forOnLoad = false) { // watch out for checkboxs as the inputs don't have values but are 'checked if ($rule->FieldValue) { return "$(\"input[name='{$this->Name}[]'][value='{$rule->FieldValue}']\")"; } else { return "$(\"input[name='{$this->Name}[]']:first\")"; } } public function isCheckBoxField() { return true; } public function getSelectorFieldOnly() { return "[name='{$this->Name}[]']"; } public function isCheckBoxGroupField() { return true; } }
php
BSD-3-Clause
e33fff165d33a077ec4b20c2eef2ef8bca25d15a
2026-01-05T05:22:58.009669Z
false
silverstripe/silverstripe-userforms
https://github.com/silverstripe/silverstripe-userforms/blob/e33fff165d33a077ec4b20c2eef2ef8bca25d15a/code/Model/EditableFormField/EditableOption.php
code/Model/EditableFormField/EditableOption.php
<?php namespace SilverStripe\UserForms\Model\EditableFormField; use SilverStripe\ORM\DataObject; use SilverStripe\Security\Member; use SilverStripe\Versioned\Versioned; /** * Base Class for EditableOption Fields such as the ones used in * dropdown fields and in radio check box groups * * @package userforms * @property int $Default * @property string $Name * @property int $ParentID * @property int $Sort * @property string $Value * @mixin Versioned * @method EditableMultipleOptionField Parent() */ class EditableOption extends DataObject { private static $default_sort = 'Sort'; private static $db = [ 'Name' => 'Varchar(255)', 'Title' => 'Varchar(255)', 'Default' => 'Boolean', 'Sort' => 'Int', 'Value' => 'Varchar(255)', ]; private static $has_one = [ 'Parent' => EditableMultipleOptionField::class, ]; private static $extensions = [ Versioned::class . "('Stage', 'Live')", ]; private static $summary_fields = [ 'Title', 'Default', ]; protected static $allow_empty_values = false; private static $table_name = 'EditableOption'; /** * Returns whether to allow empty values or not. * * @return boolean */ public static function allow_empty_values() { return (bool) EditableOption::$allow_empty_values; } /** * Set whether to allow empty values. * * @param boolean $allow */ public static function set_allow_empty_values($allow) { EditableOption::$allow_empty_values = (bool) $allow; } /** * Fetches a value for $this->Value. If empty values are not allowed, * then this will return the title in the case of an empty value. * * @return string */ public function getValue() { $value = $this->getField('Value'); if (empty($value) && !EditableOption::allow_empty_values()) { return $this->Title; } return $value; } protected function onBeforeWrite() { if (!$this->Sort) { $this->Sort = EditableOption::get()->max('Sort') + 1; } parent::onBeforeWrite(); } /** * @param Member $member * @return boolean */ public function canEdit($member = null) { return $this->Parent()->canEdit($member); } /** * @param Member $member * @return boolean */ public function canDelete($member = null) { return $this->canEdit($member); } /** * @param Member $member * @return bool */ public function canView($member = null) { return $this->Parent()->canView($member); } /** * Return whether a user can create an object of this type * * @param Member $member * @param array $context Virtual parameter to allow context to be passed in to check * @return bool */ public function canCreate($member = null, $context = []) { // Check parent object $parent = $this->Parent(); if ($parent) { return $parent->canCreate($member); } // Fall back to secure admin permissions return parent::canCreate($member); } /** * @param Member $member * @return bool */ public function canPublish($member = null) { return $this->canEdit($member); } /** * @param Member $member * @return bool */ public function canUnpublish($member = null) { return $this->canDelete($member); } }
php
BSD-3-Clause
e33fff165d33a077ec4b20c2eef2ef8bca25d15a
2026-01-05T05:22:58.009669Z
false
silverstripe/silverstripe-userforms
https://github.com/silverstripe/silverstripe-userforms/blob/e33fff165d33a077ec4b20c2eef2ef8bca25d15a/code/Model/EditableFormField/EditableDropdown.php
code/Model/EditableFormField/EditableDropdown.php
<?php namespace SilverStripe\UserForms\Model\EditableFormField; use SilverStripe\Forms\CheckboxField; use SilverStripe\Forms\DropdownField; use SilverStripe\Forms\FieldList; use SilverStripe\Forms\TextField; use SilverStripe\UserForms\Model\EditableCustomRule; use SilverStripe\UserForms\Model\EditableFormField; /** * EditableDropdown * * Represents a modifiable dropdown (select) box on a form * * @package userforms * @property bool $UseEmptyString * @property string $EmptyString */ class EditableDropdown extends EditableMultipleOptionField { private static $singular_name = 'Dropdown Field'; private static $plural_name = 'Dropdowns'; private static $db = array( 'UseEmptyString' => 'Boolean', 'EmptyString' => 'Varchar(255)', ); private static $table_name = 'EditableDropdown'; /** * @return FieldList */ public function getCMSFields() { $this->beforeUpdateCMSFields(function (FieldList $fields) { $fields->addFieldToTab( 'Root.Main', CheckboxField::create('UseEmptyString') ->setTitle('Set default empty string') ); $fields->addFieldToTab( 'Root.Main', TextField::create('EmptyString') ->setTitle('Empty String') ); $fields->removeByName('Default'); }); return parent::getCMSFields(); } /** * @return DropdownField */ public function getFormField() { $field = DropdownField::create($this->Name, $this->Title ?: false, $this->getOptionsMap()) ->setFieldHolderTemplate(EditableFormField::class . '_holder') ->setTemplate(__CLASS__); if ($this->UseEmptyString) { $field->setEmptyString(($this->EmptyString) ? $this->EmptyString : ''); } // Set default $defaultOption = $this->getDefaultOptions()->first(); if ($defaultOption) { $field->setValue($defaultOption->Value); } $this->doUpdateFormField($field); return $field; } public function getSelectorField(EditableCustomRule $rule, $forOnLoad = false) { return "$(\"select[name='{$this->Name}']\")"; } }
php
BSD-3-Clause
e33fff165d33a077ec4b20c2eef2ef8bca25d15a
2026-01-05T05:22:58.009669Z
false
silverstripe/silverstripe-userforms
https://github.com/silverstripe/silverstripe-userforms/blob/e33fff165d33a077ec4b20c2eef2ef8bca25d15a/code/Model/EditableFormField/EditableFormStep.php
code/Model/EditableFormField/EditableFormStep.php
<?php namespace SilverStripe\UserForms\Model\EditableFormField; use SilverStripe\Forms\FieldList; use SilverStripe\Forms\FormField; use SilverStripe\Forms\LabelField; use SilverStripe\UserForms\FormField\UserFormsStepField; use SilverStripe\UserForms\Model\EditableFormField; /** * A step in multi-page user form * * @package userforms */ class EditableFormStep extends EditableFormField { private static $singular_name = 'Page Break'; private static $plural_name = 'Page Breaks'; /** * Disable selection of step class * * @config * @var bool */ private static $hidden = true; private static $table_name = 'EditableFormStep'; /** * @return FieldList */ public function getCMSFields() { $this->beforeUpdateCMSFields(function (FieldList $fields) { $fields->removeByName(['MergeField', 'Default', 'Validation', 'RightTitle']); }); return parent::getCMSFields(); } /** * @return FormField */ public function getFormField() { $field = UserFormsStepField::create() ->setName($this->Name) ->setTitle($this->Title); $this->doUpdateFormField($field); return $field; } protected function updateFormField($field) { // if this field has an extra class if ($this->ExtraClass) { $field->addExtraClass($this->ExtraClass); } } /** * @return boolean */ public function showInReports() { return false; } public function getInlineClassnameField($column, $fieldClasses) { return LabelField::create($column, $this->CMSTitle); } public function getCMSTitle() { $title = $this->getFieldNumber() ?: $this->Title ?: ''; return _t( __CLASS__.'.STEP_TITLE', 'Page {page}', ['page' => $title] ); } /** * Get the JS expression for selecting the holder for this field * * @return string */ public function getSelectorHolder() { return "$(\".step-button-wrapper[data-for='{$this->Name}']\")"; } }
php
BSD-3-Clause
e33fff165d33a077ec4b20c2eef2ef8bca25d15a
2026-01-05T05:22:58.009669Z
false
silverstripe/silverstripe-userforms
https://github.com/silverstripe/silverstripe-userforms/blob/e33fff165d33a077ec4b20c2eef2ef8bca25d15a/code/Model/EditableFormField/EditableEmailField.php
code/Model/EditableFormField/EditableEmailField.php
<?php namespace SilverStripe\UserForms\Model\EditableFormField; use SilverStripe\Forms\EmailField; use SilverStripe\Forms\FormField; use SilverStripe\UserForms\Model\EditableFormField; /** * EditableEmailField * * Allow users to define a validating editable email field for a UserDefinedForm * * @package userforms */ class EditableEmailField extends EditableFormField { private static $singular_name = 'Email Field'; private static $plural_name = 'Email Fields'; private static $has_placeholder = true; private static $table_name = 'EditableEmailField'; public function getSetsOwnError() { return true; } public function getFormField() { $field = EmailField::create($this->Name, $this->Title ?: false, $this->Default) ->setFieldHolderTemplate(EditableFormField::class . '_holder') ->setTemplate(EditableFormField::class); $this->doUpdateFormField($field); return $field; } /** * Updates a formfield with the additional metadata specified by this field * * @param FormField $field */ protected function updateFormField($field) { parent::updateFormField($field); $field->setAttribute('data-rule-email', true); } }
php
BSD-3-Clause
e33fff165d33a077ec4b20c2eef2ef8bca25d15a
2026-01-05T05:22:58.009669Z
false
silverstripe/silverstripe-userforms
https://github.com/silverstripe/silverstripe-userforms/blob/e33fff165d33a077ec4b20c2eef2ef8bca25d15a/code/Model/EditableFormField/Validator.php
code/Model/EditableFormField/Validator.php
<?php namespace SilverStripe\UserForms\Model\EditableFormField; use SilverStripe\Forms\Validation\RequiredFieldsValidator; use SilverStripe\UserForms\Model\EditableFormField; class Validator extends RequiredFieldsValidator { /** * * @var EditableFormField */ protected $record = null; /** * * @param EditableFormField $record * @return $this */ public function setRecord($record) { $this->record = $record; return $this; } /* * @return EditableFormField */ public function getRecord() { return $this->record; } public function php($data) { if (!parent::php($data)) { return false; } return true; } }
php
BSD-3-Clause
e33fff165d33a077ec4b20c2eef2ef8bca25d15a
2026-01-05T05:22:58.009669Z
false
silverstripe/silverstripe-userforms
https://github.com/silverstripe/silverstripe-userforms/blob/e33fff165d33a077ec4b20c2eef2ef8bca25d15a/code/Model/EditableFormField/EditableFormHeading.php
code/Model/EditableFormField/EditableFormHeading.php
<?php namespace SilverStripe\UserForms\Model\EditableFormField; use SilverStripe\Forms\CheckboxField; use SilverStripe\Forms\DropdownField; use SilverStripe\Forms\FieldList; use SilverStripe\Forms\HeaderField; use SilverStripe\UserForms\Model\EditableFormField; /** * Allows an editor to insert a generic heading into a field * * @package userforms * @property int $Level * @property int $HideFromReports */ class EditableFormHeading extends EditableFormField { private static $singular_name = 'Heading'; private static $plural_name = 'Headings'; private static $literal = true; private static $db = [ 'Level' => 'Int(3)', // From CustomSettings 'HideFromReports' => 'Boolean(0)' // from CustomSettings ]; private static $defaults = [ 'Level' => 3, 'HideFromReports' => false ]; private static $table_name = 'EditableFormHeading'; /** * @return FieldList */ public function getCMSFields() { $this->beforeUpdateCMSFields(function (FieldList $fields) { $fields->removeByName(['Default', 'Validation', 'RightTitle']); $levels = [ '1' => '1', '2' => '2', '3' => '3', '4' => '4', '5' => '5', '6' => '6' ]; $fields->addFieldsToTab('Root.Main', [ DropdownField::create( 'Level', _t(__CLASS__.'.LEVEL', 'Select Heading Level'), $levels ), CheckboxField::create( 'HideFromReports', _t('SilverStripe\\UserForms\\Model\\EditableFormField\\EditableLiteralField.HIDEFROMREPORT', 'Hide from reports?') ) ]); }); return parent::getCMSFields(); } public function getFormField() { $labelField = HeaderField::create('userforms-header-' . $this->ID, $this->Title ?: false) ->setHeadingLevel($this->Level); $labelField->addExtraClass('FormHeading'); $labelField->setAttribute('data-id', $this->Name); $this->doUpdateFormField($labelField); return $labelField; } protected function updateFormField($field) { // set the right title on this field if ($this->RightTitle) { $field->setRightTitle($this->RightTitle); } // if this field has an extra class if ($this->ExtraClass) { $field->addExtraClass($this->ExtraClass); } if (!$this->ShowOnLoad) { $field->addExtraClass($this->ShowOnLoadNice()); } } public function showInReports() { return !$this->HideFromReports; } public function getFieldValidationOptions() { return false; } public function getSelectorHolder() { return "$(\":header[data-id='{$this->Name}']\")"; } public function getSelectorOnly() { return "[data-id={$this->Name}]"; } public function getLevel() { return $this->getField('Level') ?: 3; } }
php
BSD-3-Clause
e33fff165d33a077ec4b20c2eef2ef8bca25d15a
2026-01-05T05:22:58.009669Z
false
silverstripe/silverstripe-userforms
https://github.com/silverstripe/silverstripe-userforms/blob/e33fff165d33a077ec4b20c2eef2ef8bca25d15a/code/Model/EditableFormField/EditableNumericField.php
code/Model/EditableFormField/EditableNumericField.php
<?php namespace SilverStripe\UserForms\Model\EditableFormField; use SilverStripe\Forms\FieldGroup; use SilverStripe\Forms\FormField; use SilverStripe\Forms\LiteralField; use SilverStripe\Forms\NumericField; use SilverStripe\UserForms\Model\EditableFormField; use SilverStripe\Core\Validation\ValidationResult; /** * EditableNumericField * * This control represents a user-defined numeric field in a user defined form * * @package userforms * @property int $MaxValue * @property int $MinValue */ class EditableNumericField extends EditableFormField { private static $singular_name = 'Numeric Field'; private static $plural_name = 'Numeric Fields'; private static $has_placeholder = true; private static $db = [ 'MinValue' => 'Int', 'MaxValue' => 'Int' ]; private static $table_name = 'EditableNumericField'; public function getSetsOwnError() { return true; } /** * @return NumericField */ public function getFormField() { $field = NumericField::create($this->Name, $this->Title ?: false, $this->Default) ->setFieldHolderTemplate(EditableFormField::class . '_holder') ->setTemplate(EditableFormField::class) ->addExtraClass('number'); $this->doUpdateFormField($field); return $field; } public function getFieldValidationOptions() { $fields = parent::getFieldValidationOptions(); $fields->push(FieldGroup::create( _t(__CLASS__.'.RANGE', 'Allowed numeric range'), [ NumericField::create('MinValue', false), LiteralField::create('RangeValue', _t(__CLASS__.'.RANGE_TO', 'to')), NumericField::create('MaxValue', false) ] )); return $fields; } /** * Updates a formfield with the additional metadata specified by this field * * @param FormField $field */ protected function updateFormField($field) { parent::updateFormField($field); if ($this->MinValue) { $field->setAttribute('data-rule-min', $this->MinValue); } if ($this->MaxValue) { $field->setAttribute('data-rule-max', $this->MaxValue); } } public function validate(): ValidationResult { $result = parent::validate(); if ($this->MinValue > $this->MaxValue) { $result->addError( _t(__CLASS__ . '.ORDER_WARNING', 'Minimum length should be less than the maximum length.') ); } return $result; } }
php
BSD-3-Clause
e33fff165d33a077ec4b20c2eef2ef8bca25d15a
2026-01-05T05:22:58.009669Z
false
silverstripe/silverstripe-userforms
https://github.com/silverstripe/silverstripe-userforms/blob/e33fff165d33a077ec4b20c2eef2ef8bca25d15a/code/Model/EditableFormField/EditableFieldGroup.php
code/Model/EditableFormField/EditableFieldGroup.php
<?php namespace SilverStripe\UserForms\Model\EditableFormField; use SilverStripe\Core\Convert; use SilverStripe\Forms\FieldList; use SilverStripe\Forms\LabelField; use SilverStripe\UserForms\FormField\UserFormsGroupField; use SilverStripe\UserForms\Model\EditableFormField; /** * Specifies that this ends a group of fields * * @property int $EditableFieldGroupEndID * @method EditableFieldGroupEnd End() */ class EditableFieldGroup extends EditableFormField { private static $has_one = [ 'End' => EditableFieldGroupEnd::class, ]; private static $owns = [ 'End', ]; private static $cascade_deletes = [ 'End', ]; /** * Disable selection of group class * * @config * @var bool */ private static $hidden = true; /** * Non-data field type * * @var bool */ private static $literal = true; private static $table_name = 'EditableFieldGroup'; public function getCMSFields() { $this->beforeUpdateCMSFields(function (FieldList $fields) { $fields->removeByName(['MergeField', 'Default', 'Validation', 'DisplayRules']); }); return parent::getCMSFields(); } public function getCMSTitle() { $title = $this->getFieldNumber() ?: $this->Title ?: 'group'; return _t( 'SilverStripe\\UserForms\\Model\\EditableFormField\\EditableFieldGroupEnd.FIELD_GROUP_START', 'Group {group}', ['group' => $title] ); } public function getInlineClassnameField($column, $fieldClasses) { return LabelField::create($column, $this->CMSTitle); } public function showInReports() { return false; } public function getFormField() { $field = UserFormsGroupField::create() ->setTitle($this->Title ?: false) ->setName($this->Name); $this->doUpdateFormField($field); return $field; } protected function updateFormField($field) { // set the right title on this field if ($this->RightTitle) { // Since this field expects raw html, safely escape the user data prior $field->setRightTitle(Convert::raw2xml($this->RightTitle)); } // if this field has an extra class if ($this->ExtraClass) { $field->addExtraClass($this->ExtraClass); } } }
php
BSD-3-Clause
e33fff165d33a077ec4b20c2eef2ef8bca25d15a
2026-01-05T05:22:58.009669Z
false
silverstripe/silverstripe-userforms
https://github.com/silverstripe/silverstripe-userforms/blob/e33fff165d33a077ec4b20c2eef2ef8bca25d15a/code/Model/EditableFormField/EditableMultipleOptionField.php
code/Model/EditableFormField/EditableMultipleOptionField.php
<?php namespace SilverStripe\UserForms\Model\EditableFormField; use SilverStripe\Forms\CheckboxField; use SilverStripe\Forms\FieldList; use SilverStripe\Forms\GridField\GridField; use SilverStripe\Forms\GridField\GridFieldButtonRow; use SilverStripe\Forms\GridField\GridFieldConfig; use SilverStripe\Forms\GridField\GridFieldDeleteAction; use SilverStripe\Forms\GridField\GridFieldToolbarHeader; use SilverStripe\Forms\Tab; use SilverStripe\Forms\TextField; use SilverStripe\ORM\HasManyList; use SilverStripe\Model\List\Map; use SilverStripe\Model\List\SS_List; use SilverStripe\UserForms\Model\EditableFormField; use Symbiote\GridFieldExtensions\GridFieldAddNewInlineButton; use Symbiote\GridFieldExtensions\GridFieldEditableColumns; use Symbiote\GridFieldExtensions\GridFieldOrderableRows; use Symbiote\GridFieldExtensions\GridFieldTitleHeader; /** * Base class for multiple option fields such as {@link EditableDropdownField} * and radio sets. * * Implemented as a class but should be viewed as abstract, you should * instantiate a subclass such as {@link EditableDropdownField} * * @see EditableCheckboxGroupField * @see EditableDropdownField * * @package userforms * @method HasManyList<EditableOption> Options() */ class EditableMultipleOptionField extends EditableFormField { /** * Define this field as abstract (not inherited) * * @config * @var bool */ private static $abstract = true; private static $has_many = [ 'Options' => EditableOption::class, ]; private static $owns = [ 'Options', ]; private static $cascade_deletes = [ 'Options', ]; private static $cascade_duplicates = [ 'Options', ]; private static $table_name = 'EditableMultipleOptionField'; /** * @return FieldList */ public function getCMSFields() { $this->beforeUpdateCMSFields(function ($fields) { $editableColumns = new GridFieldEditableColumns(); $editableColumns->setDisplayFields([ 'Title' => [ 'title' => _t(__CLASS__.'.TITLE', 'Title'), 'callback' => function ($record, $column, $grid) { return TextField::create($column); } ], 'Value' => [ 'title' => _t(__CLASS__.'.VALUE', 'Value'), 'callback' => function ($record, $column, $grid) { return TextField::create($column); } ], 'Default' => [ 'title' => _t(__CLASS__.'.DEFAULT', 'Selected by default?'), 'callback' => function ($record, $column, $grid) { return CheckboxField::create($column); } ] ]); $optionsConfig = GridFieldConfig::create() ->addComponents( new GridFieldToolbarHeader(), new GridFieldTitleHeader(), new GridFieldOrderableRows('Sort'), $editableColumns, new GridFieldButtonRow(), new GridFieldAddNewInlineButton(), new GridFieldDeleteAction() ); $optionsGrid = GridField::create( 'Options', _t('SilverStripe\\UserForms\\Model\\EditableFormField.CUSTOMOPTIONS', 'Options'), $this->Options(), $optionsConfig ); $fields->insertAfter('Main', Tab::create('Options', _t(__CLASS__.'.OPTIONSTAB', 'Options'))); $fields->addFieldToTab('Root.Options', $optionsGrid); }); $fields = parent::getCMSFields(); return $fields; } /** * Return whether or not this field has addable options such as a * {@link EditableDropdown} or {@link EditableRadioField} * * @return bool */ public function getHasAddableOptions() { return true; } /** * Gets map of field options suitable for use in a form * * @return array */ protected function getOptionsMap() { $optionSet = $this->Options(); $optionMap = $optionSet->map('Value', 'Title'); if ($optionMap instanceof Map) { return $optionMap->toArray(); } return $optionMap; } /** * Returns all default options * * @return SS_List */ protected function getDefaultOptions() { return $this->Options()->filter('Default', 1); } }
php
BSD-3-Clause
e33fff165d33a077ec4b20c2eef2ef8bca25d15a
2026-01-05T05:22:58.009669Z
false
silverstripe/silverstripe-userforms
https://github.com/silverstripe/silverstripe-userforms/blob/e33fff165d33a077ec4b20c2eef2ef8bca25d15a/code/Model/EditableFormField/EditableCheckbox.php
code/Model/EditableFormField/EditableCheckbox.php
<?php namespace SilverStripe\UserForms\Model\EditableFormField; use SilverStripe\Forms\CheckboxField; use SilverStripe\Forms\FieldList; use SilverStripe\UserForms\Model\EditableFormField; /** * EditableCheckbox * * A user modifiable checkbox on a UserDefinedForm * * @package userforms * @property int $CheckedDefault */ class EditableCheckbox extends EditableFormField { private static $singular_name = 'Checkbox Field'; private static $plural_name = 'Checkboxes'; protected $jsEventHandler = 'click'; private static $db = [ 'CheckedDefault' => 'Boolean' // from CustomSettings ]; private static $table_name = 'EditableCheckbox'; /** * @return FieldList */ public function getCMSFields() { $this->beforeUpdateCMSFields(function (FieldList $fields) { $fields->replaceField('Default', CheckboxField::create( "CheckedDefault", _t('SilverStripe\\UserForms\\Model\\EditableFormField.CHECKEDBYDEFAULT', 'Checked by Default?') )); }); return parent::getCMSFields(); } public function getFormField() { $field = CheckboxField::create($this->Name, $this->Title ?: false, $this->CheckedDefault) ->setFieldHolderTemplate(__CLASS__ . '_holder') ->setTemplate(__CLASS__); $this->doUpdateFormField($field); return $field; } public function getValueFromData($data) { $value = (isset($data[$this->Name])) ? $data[$this->Name] : false; return ($value) ? _t('SilverStripe\\UserForms\\Model\\EditableFormField.YES', 'Yes') : _t('SilverStripe\\UserForms\\Model\\EditableFormField.NO', 'No'); } public function isCheckBoxField() { return true; } }
php
BSD-3-Clause
e33fff165d33a077ec4b20c2eef2ef8bca25d15a
2026-01-05T05:22:58.009669Z
false