Add generic way to pass entity fields in via the url.
authoreileen <emcnaughton@wikimedia.org>
Wed, 23 May 2018 04:24:57 +0000 (16:24 +1200)
committereileen <emcnaughton@wikimedia.org>
Wed, 6 Jun 2018 11:03:04 +0000 (23:03 +1200)
These are validated by an Alphanumeric rule, at minimum, which only
permits letters, numbers & underscore.

In honesty I don't have a specific reason to want to be able to get these
specific fields from the url - I am looking to establish a pattern
that can be used more generically (e.g search forms) to safely retrieve data from
fields assigned to the form using the new fieldsArray spec

CRM/Core/Form/EntityFormTrait.php
CRM/Member/Form/MembershipStatus.php

index 564edf6754e5b740a11149d9ccc30c0f6b75ae06..f0031490f3ed674c330a1fe953cae2f594b6775e 100644 (file)
@@ -131,6 +131,47 @@ trait CRM_Core_Form_EntityFormTrait {
     }
   }
 
+  /**
+   * Get the defaults for the entity.
+   */
+  protected function getEntityDefaults() {
+    $defaults = [];
+    if ($this->_action != CRM_Core_Action::DELETE &&
+      $this->getEntityId()
+    ) {
+      $params = ['id' => $this->getEntityId()];
+      $baoName = $this->_BAOName;
+      $baoName::retrieve($params, $defaults);
+    }
+    foreach ($this->entityFields as $fieldSpec) {
+      $value = CRM_Utils_Request::retrieveValue($fieldSpec['name'], $this->getValidationTypeForField($fieldSpec['name']));
+      if ($value !== FALSE) {
+        $defaults[$fieldSpec['name']] = $value;
+      }
+    }
+    return $defaults;
+  }
+
+  /**
+   * Get the validation rule to apply to a function.
+   *
+   * Alphanumeric is designed to always be safe & for now we just return
+   * that but in future we can use tighter rules for types like int, bool etc.
+   *
+   * @param string $fieldName
+   *
+   * @return string|int|bool
+   */
+  protected function getValidationTypeForField($fieldName) {
+    switch ($this->metadata[$fieldName]['type']) {
+      case CRM_Utils_Type::T_BOOLEAN:
+        return 'Boolean';
+
+      default:
+        return 'Alphanumeric';
+    }
+  }
+
   /**
    * Set translated fields.
    *
index 10b468febd9c5530001950861151f9d24065bb32..e51f08918ef63049c999ef4221faae0aaf0a8838 100644 (file)
@@ -106,13 +106,7 @@ class CRM_Member_Form_MembershipStatus extends CRM_Core_Form {
    * @return array
    */
   public function setDefaultValues() {
-    $defaults = array();
-
-    if ($this->getEntityId()) {
-      $params = array('id' => $this->getEntityId());
-      $baoName = $this->_BAOName;
-      $baoName::retrieve($params, $defaults);
-    }
+    $defaults = $this->getEntityDefaults();
 
     if ($this->_action & CRM_Core_Action::ADD) {
       $defaults['is_active'] = 1;