Skip to content

Commit

Permalink
Merge pull request #11566 from craftcms/feature/address-fields-form-r…
Browse files Browse the repository at this point in the history
…equired

Conditionally show require `*` for address fields based on validation rules
  • Loading branch information
brandonkelly authored Jul 7, 2022
2 parents b4140bf + 4eaa4ce commit 8b5ae59
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 1 deletion.
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
# Release Notes for Craft CMS 4

## Unreleased

### Changed
- Address fields now show required indicators based on the configured validation rules. ([#11566](https://github.com/craftcms/cms/pull/11566))

## 4.1.2 - 2022-07-06

### Added
Expand Down
19 changes: 18 additions & 1 deletion src/helpers/Cp.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
namespace craft\helpers;

use Craft;
use craft\base\Element;
use craft\base\ElementInterface;
use craft\base\FieldLayoutElement;
use craft\behaviors\DraftBehavior;
Expand All @@ -24,6 +25,7 @@
use yii\base\Event;
use yii\base\InvalidArgumentException;
use yii\helpers\Markdown;
use yii\validators\RequiredValidator;

/**
* Class Cp
Expand Down Expand Up @@ -1257,7 +1259,22 @@ public static function addressFieldsHtml(Address $address): string
{
$formatRepo = Craft::$app->getAddresses()->getAddressFormatRepository()->get($address->countryCode);

$requiredFields = array_flip($formatRepo->getRequiredFields());
$requiredFields = [];
$scenario = $address->getScenario();
$address->setScenario(Element::SCENARIO_LIVE);
$activeValidators = $address->getActiveValidators();
$address->setScenario($scenario);

foreach ($activeValidators as $validator) {
if ($validator instanceof RequiredValidator) {
foreach ($validator->getAttributeNames() as $attr) {
if ($validator->when === null || call_user_func($validator->when, $address, $attr)) {
$requiredFields[$attr] = true;
}
}
}
}

$visibleFields = array_flip(array_merge(
$formatRepo->getUsedFields(),
$formatRepo->getUsedSubdivisionFields(),
Expand Down

0 comments on commit 8b5ae59

Please sign in to comment.