Build form form-specific javascript
Script updates require attribute if req is dependant on other fields

@return string
512978
public function build()
    {
        $this->debug->groupCollapsed(__METHOD__);
        $str = '';
        $strFunctions   = '';
        $strListen      = '';
        $strOnload      = '';
        $trigs = $this->getTriggers();
        $this->debug->log('trigs', $trigs);
        foreach ($trigs as $trigName => $trig) {
            $strFunc = $this->buildOnChangeFunc($trig);
            $strFunctions .= $strFunc."\n";
            $strOnload .= "\t".$trig['funcName']."();\n";
            $trigFields = $this->getFieldsWithName($trigName);
            foreach ($trigFields as $field) {
                // Listen to this field && call func when changed
                $strListen .= $this->buildListen($field, $trig['funcName'])."\n";
            }
        }
        if (!empty($strFunctions) || !empty($strListen)) {
            $str = '<script type="text/javascript">'."\n"
                .'//<![CDATA['."\n"
                .'$(function(){'."\n"
                    .'BDKForm.init("#'.$this->form->cfg['attribs']['id'].'");'."\n"
                    .$strFunctions
                    .$strListen
                    .'$(window).on("focus", function() {'."\n"
                        // .'console.log("window focused... re calculating required");'
                        .$strOnload
                    .'});'."\n"
                .'});'."\n"
                .'//]]>'."\n"
                .'</script>';
        }
        $this->debug->log('str!!', $str);
        $this->debug->groupEnd();
        return $str;
    }
499186
function () {

        var $form = null, _id = null, $target = null;

        if ( this.getAttribute ) {
            _id = this.getAttribute('id');
            $target = this;
        } else if ( typeof(this.target) && this.target.getAttribute ) {
            _id = this.target.getAttribute('id');
            $target = this.target
        }

        if ( typeof(instance.$forms[_id]) == 'undefined') {
            throw new Error('[ FormValidator::submit() ] not `$form` binded. Use `FormValidator::getFormById(id)` or `FormValidator::validateFormById(id)` first ')
        }

        triggerEvent(gina, $target, 'submit');

        return this;
    }
1202721
function getValidationScript()
    {
        if (empty($this->_rules) || empty($this->_attributes['onsubmit'])) {
            return '';
        }

        include_once('HTML/QuickForm/RuleRegistry.php');
        $registry =& HTML_QuickForm_RuleRegistry::singleton();
        $test = array();
        $js_escape = array(
            "\r"    => '\r',
            "\n"    => '\n',
            "\t"    => '\t',
            "'"     => "\\'",
            '"'     => '\"',
            '\\'    => '\\\\'
        );

        foreach ($this->_rules as $elementName => $rules) {
            foreach ($rules as $rule) {
                if ('client' == $rule['validation']) {
                    unset($element);

                    $dependent  = isset($rule['dependent']) && is_array($rule['dependent']);
                    $rule['message'] = strtr($rule['message'], $js_escape);

                    if (isset($rule['group'])) {
                        $group    =& $this->getElement($rule['group']);
                        // No JavaScript validation for frozen elements
                        if ($group->isFrozen()) {
                            continue 2;
                        }
                        $elements =& $group->getElements();
                        foreach (array_keys($elements) as $key) {
                            if ($elementName == $group->getElementName($key)) {
                                $element =& $elements[$key];
                                break;
                            }
                        }
                    } elseif ($dependent) {
                        $element   =  array();
                        $element[] =& $this->getElement($elementName);
                        foreach ($rule['dependent'] as $idx => $elName) {
                            $element[] =& $this->getElement($elName);
                        }
                    } else {
                        $element =& $this->getElement($elementName);
                    }
                    // No JavaScript validation for frozen elements
                    if (is_object($element) && $element->isFrozen()) {
                        continue 2;
                    } elseif (is_array($element)) {
                        foreach (array_keys($element) as $key) {
                            if ($element[$key]->isFrozen()) {
                                continue 3;
                            }
                        }
                    }

                    $test[$elementName][] = $registry->getValidationScript($element, $elementName, $rule);
                }
            }
        }
        $js = '
<script type="text/javascript">
//<![CDATA[
function qf_errorHandler(element, _qfMsg) {
  div = element.parentNode;
  if (_qfMsg != \'\') {
    span = document.createElement("span");
    span.className = "error";
    span.appendChild(document.createTextNode(_qfMsg.substring(3)));
    br = document.createElement("br");

    var errorDiv = document.getElementById(element.name + \'_errorDiv\');
    if (!errorDiv) {
      errorDiv = document.createElement("div");
      errorDiv.id = element.name + \'_errorDiv\';
    }
    while (errorDiv.firstChild) {
      errorDiv.removeChild(errorDiv.firstChild);
    }
    
    errorDiv.insertBefore(br, errorDiv.firstChild);
    errorDiv.insertBefore(span, errorDiv.firstChild);
    element.parentNode.insertBefore(errorDiv, element.parentNode.firstChild);

    if (div.className.substr(div.className.length - 6, 6) != " error"
        && div.className != "error") {
      div.className += " error";
    }

    return false;
  } else {
    var errorDiv = document.getElementById(element.name + \'_errorDiv\');
    if (errorDiv) {
      errorDiv.parentNode.removeChild(errorDiv);
    }

    if (div.className.substr(div.className.length - 6, 6) == " error") {
      div.className = div.className.substr(0, div.className.length - 6);
    } else if (div.className == "error") {
      div.className = "";
    }

    return true;
  }
}';
        $validateJS = '';
        foreach ($test as $elementName => $jsArr) {
            $js .= '
function validate_' . $this->_attributes['id'] . '_' . $elementName . '(element) {
  var value = \'\';
  var errFlag = new Array();
  var _qfGroups = {};
  var _qfMsg = \'\';
  var frm = element.parentNode;
  while (frm && frm.nodeName != "FORM") {
    frm = frm.parentNode;
  }
' . join("\n", $jsArr) . '
  return qf_errorHandler(element, _qfMsg);
}
';
            $validateJS .= '
  ret = validate_' . $this->_attributes['id'] . '_' . $elementName.'(frm.elements[\''.$elementName.'\']) && ret;';
            unset($element);
            $element =& $this->getElement($elementName);
            $valFunc = 'validate_' . $this->_attributes['id'] . '_' . $elementName . '(this)';
            $onBlur = $element->getAttribute('onBlur');
            $onChange = $element->getAttribute('onChange');
            $element->updateAttributes(array('onBlur' => $onBlur . $valFunc,
                                             'onChange' => $onChange . $valFunc));
        }
        $js .= '
function validate_' . $this->_attributes['id'] . '(frm) {
  var ret = true;
' . $validateJS . ';
  return ret;
}
//]]>
</script>';
        return $js;
    }
1110657
function traitEntityAttachHtml_formBuild() {
        $this->traitEntity_formBuild();
        $this->form->putTbSubmit($this->traitEntityAttach_btnText())
                   ->addClass('btn btn-' . $this->traitEntityAttach_btnClass());
    }
125355
public function getRequiredFields()
    {
        // Generate required field validator
        $requiredNames = $this
            ->getController()
            ->data()
            ->Fields()
            ->filter('Required', true)
            ->column('Name');
        $requiredNames = array_merge($requiredNames, $this->getEmailRecipientRequiredFields());
        $required = new RequiredFields($requiredNames);
        $this->extend('updateRequiredFields', $required);
        $required->setForm($this);
        return $required;
    }
638377
function($form) {
        var $form = $form, _id = null;
        if ( typeof($form) == 'undefined' ) {
            if ( typeof(this.target) != 'undefined' ) {
                _id = this.target.getAttribute('id');
            } else {
                _id = this.getAttribute('id');
            }

            $form = instance.$forms[_id]
        } else if ( typeof($form) == 'string' ) {
            _id = $form;
            _id = _id.replace(/\#/, '');

            if ( typeof(instance.$forms[_id]) == 'undefined') {
                throw new Error('[ FormValidator::resetErrorsDisplay([formId]) ] `'+$form+'` not found')
            }

            $form = instance.$forms[_id]
        }
        //reseting error display
        handleErrorsDisplay($form['target'], []);

        return $form
    }
1300675
public function index()
    {
        $form = $this->bulkEditForm();
        $form->setTemplate([
            'type' => 'Includes',
            'SilverStripe\\Admin\\LeftAndMain_EditForm',
        ]);
        $form->addExtraClass('center cms-content');
        $form->setAttribute('data-pjax-fragment', 'CurrentForm Content');

        Requirements::javascript('colymba/gridfield-bulk-editing-tools:client/dist/js/main.js');
        Requirements::css('colymba/gridfield-bulk-editing-tools:client/dist/styles/main.css');
        Requirements::add_i18n_javascript('colymba/gridfield-bulk-editing-tools:lang');

        if ($this->request->isAjax()) {
            $response = new HTTPResponse(
                Convert::raw2json(array('Content' => $form->forAjaxTemplate()->getValue()))
            );
            $response->addHeader('X-Pjax', 'Content');
            $response->addHeader('Content-Type', 'text/json');
            $response->addHeader('X-Title', 'SilverStripe - Bulk ' . $this->gridField->list->dataClass . ' Editing');

            return $response;
        } else {
            $controller = $this->getToplevelController();

            return $controller->customise(array('Content' => $form));
        }
    }
1140713
public function loadRequirements()
    {
        // Load Required Themed JavaScript:
        
        if (ContentController::config()->load_themed_js) {
            
            foreach ($this->getRequiredThemedJS() as $js) {
                Requirements::themedJavascript($js);
            }
            
        }
        
        // Load Required Themed CSS:
        
        if (ContentController::config()->load_themed_css) {
            
            foreach ($this->getRequiredThemedCSS() as $css => $media) {
                Requirements::themedCSS($css, $media);
            }
            
        }
        
        // Load Required JavaScript:
        
        if (ContentController::config()->load_js) {
            
            foreach ($this->getRequiredJS() as $js) {
                Requirements::javascript($js);
            }
            
        }
        
        // Load Required CSS:
        
        if (ContentController::config()->load_css) {
            
            foreach ($this->getRequiredCSS() as $css => $media) {
                Requirements::css($css, $media);
            }
            
        }
        
        // Load Required Custom CSS:
        
        if (ContentController::config()->load_custom_css) {
            
            if ($css = $this->getCustomCSSAsString()) {
                Requirements::customCSS($css, $this->HTMLID);
            }
            
        }
        
        // Load Required JavaScript Templates:
        
        foreach ($this->getRequiredJSTemplates() as $file => $params) {
            ViewTools::singleton()->loadJSTemplate($file, $params['vars'], $params['id']);
        }
    }
937663
private function dynamicFormCheck()
    {
        if ($this->field->hasDynamicForms()) {
            $this->dynamicFormParentName = $this->field->getName();
            $value = $this->field->getValue();
            $forms = $this->field->getDynamicForms();
            $this->includeDynamicFormJavascript = true;
            foreach ($forms as $dynamicTriggerValue => $form) {
                $this->dynamicFormVisible = ($value == $dynamicTriggerValue);
                $dynamicFields = $form->getFields();
                $this->processFields($dynamicFields, $dynamicTriggerValue);
            }
            unset($this->dynamicFormParentName);
        }
    }
491358
public function getAttributesForForm(Form $form)
    {
        // Obtain Attributes (from parent):
        
        $attributes = parent::getAttributesForForm($form);
        
        // Define Group Class:
        
        $attributes['data-group-class'] = $this->config()->group_class;
        
        // Define Error Wrapper Class:
        
        $attributes['data-error-wrapper-class'] = $this->config()->error_wrapper_class;
        
        // Define Error Classes:
        
        $attributes['data-group-error-class']   = $this->config()->group_error_class;
        $attributes['data-field-error-class']   = $this->config()->field_error_class;
        
        // Define Success Classes:
        
        $attributes['data-group-success-class'] = $this->config()->group_success_class;
        $attributes['data-field-success-class'] = $this->config()->field_success_class;
        
        // Define Trigger Events:
        
        $attributes['data-parsley-trigger'] = $this->getTriggerOn();
        
        // Answer Attributes:
        
        return $this->flatten($attributes);
    }
348175
protected function getAttributeText()
    {
        $attribute = array_get($this->formFieldData->options(), 'location_name', 'location');

        if ( ! $attribute) {
            $attribute = false;
        }

        return $attribute;
    }
1285665
protected function get_module_form() {
        global $CFG, $PAGE;

        if ($this->_moduleform) {
            return $this->_moduleform;
        }

        $cm = reset($this->cms);
        $course = $this->course;
        $modname = $cm->modname;

        $modmoodleform = "$CFG->dirroot/mod/$modname/mod_form.php";
        if (file_exists($modmoodleform)) {
            require_once($modmoodleform);
        } else {
            print_error('noformdesc');
        }

        list($cmrec, $context, $module, $data, $cw) = get_moduleinfo_data($cm, $course);
        $data->return = 0;
        $data->sr = 0;
        $data->update = $modname;

        // Initialise the form but discard all JS requirements it adds, our form has already added them.
        $mformclassname = 'mod_'.$modname.'_mod_form';
        $PAGE->start_collecting_javascript_requirements();
        $this->_moduleform = new $mformclassname($data, 0, $cmrec, $course);
        $PAGE->end_collecting_javascript_requirements();

        return $this->_moduleform;
    }
101544
protected function prepareJsAttributes()
    {
        $attributes = [];
        foreach ($this->columns as $column) {
            $model = $column->getModel();
            $inputID = str_replace(['-0', '-0-'], '', $column->getElementId(0));
            if ($this->form instanceof ActiveForm && $model instanceof Model) {
                $field = $this->form->field($model, $column->name);
                foreach ($column->attributeOptions as $name => $value) {
                    if ($field->hasProperty($name)) {
                        $field->$name = $value;
                    }
                }
                $field->render('');
                $attributeOptions = array_pop($this->form->attributes);
                if (isset($attributeOptions['name']) && $attributeOptions['name'] === $column->name) {
                    $attributes[$inputID] = ArrayHelper::merge($attributeOptions, $column->attributeOptions);
                } else {
                    $this->form->attributes[] = $attributeOptions;
                }
            } else {
                $attributes[$inputID] = $column->attributeOptions;
            }
        }

        return $attributes;
    }
1267703
public function applyParsley()
    {
        $this->parsleyEnabled = true;

        $useCurrent = self::config()->use_current;

        // Include your own version of jQuery (>= 1.8) and entwine
        // You can also simply call globalRequirements()
        Requirements::javascript('zenvalidator/javascript/parsley-2.8.1/parsley.min.js', ['defer' => true]);

        $lang = strtolower(substr(i18n::get_locale(), 0, 2));
        if ($lang != 'en') {
            Requirements::javascript('zenvalidator/javascript/parsley-2.8.1/i18n/' . $lang . '.js', ['defer' => true]);
        }

        if ($this->form) {
            if ($this->defaultJS) {
                $this->form->addExtraClass('parsley');
                Requirements::javascript('zenvalidator/javascript/zenvalidator.js', ['defer' => true]);
            } else {
                $this->form->addExtraClass('custom-parsley');
            }

            foreach ($this->constraints as $fieldName => $constraints) {
                foreach ($constraints as $constraint) {
                    try {
                        $constraint->applyParsley();
                    } catch (Exception $ex) {
                        throw new Exception("An exception occured while applying constraint on $fieldName : " . $ex->getMessage());
                    }
                }
            }
        }

        return $this;
    }
962635
private function buildEditForm()
    {
        $form = '';
        foreach ($this->fields as $field) {
            $title = addslashes($field->label);
            $label = $field->title;
            if (in_array($field->validation,
                    $this->starred) && $field->type != 'password' && $field->type != 'file' && $field->type != 'photo'
            ) {
                $title .= '*';
            }
            if ($field->type == 'relationship') {
                $label = $field->relationship_name . '_id';
            }
            if ($field->type == 'checkbox') {
                $field->default = '$' . $this->model . '->' . $label . ' == 1';
            }
            $temp = file_get_contents(__DIR__ . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . 'Templates' . DIRECTORY_SEPARATOR . 'fields' . DIRECTORY_SEPARATOR . $field->type);
            $temp = str_replace([
                'old(\'$LABEL$\')',
                '$LABEL$',
                '$TITLE$',
                '$VALUE$',
                '$STATE$',
                '$SELECT$',
                '$TEXTEDITOR$',
                '$HELPER$',
                '$WIDTH$',
                '$HEIGHT$',
            ], [
                'old(\'$LABEL$\',$' . $this->resource . '->' . $label . ')',
                $label,
                $title,
                $field->type != 'radio' ?
                    $field->value != '' ? ', "' . $field->value . '"' : ''
                    : "'$field->value'",
                $field->default,
                '$' . $field->relationship_name,
                $field->texteditor == 1 ? ' ckeditor' : '',
                $this->helper($field->helper),
                $field->dimension_w,
                $field->dimension_h,
            ], $temp);
            $form .= $temp;
        }
        $this->formFieldsEdit = $form;
    }
1020127
public function getLoaderJS()
    {
        if ($this->newFile) {
            return '';
        }

        $r = '';

        $r .= $this->getProjectProperties();

        // FIRST STEP: Load all modules and entities
        $r .= $this->getModules();
        $r .= $this->getClasses();
        $r .= $this->getAbstracts();
        $r .= $this->getInterfaces();

        // SECOND STEP: Add the attributes
        $r .= $this->getAttributes();

        // THIRD STEP: After attributes entity properties
        $r .= $this->getClassLikeAfterAttributesProperties();

        // FOURTH STEP: Relationships
        $r .= $this->getRelationships();

        $r .= $this->getAutocodeProperties();

        // Finalise
        $r .= 'for (var i in Connectable.prototype.connectables) Connectable.prototype.connectables[i].reDraw();' . PHP_EOL;
        $r .= 'Link.prototype.reDrawLinks();' . PHP_EOL;
        $r .= 'System.prototype.runtime = true;' . PHP_EOL;

        return $r;
    }
637862
public function build(){

        $html = '';
        if ($this->isBuildFormElement == true){
            $html .= $this->buildHeader();
        }

        $html .= $this->buildElements();

        if ($this->isBuildFormElement == true){
            $html .= "</form>";
        }

        return $html;
    }