Generate javascript

See {@link \ValidFormBuilder\Base::toJS()}
@see \ValidFormBuilder\Base::toJS()
193553
public function toJS($intDynamicPosition = 0)
    {
        $strReturn = "objForm.addPage('" . $this->getId() . "');\n";

        foreach ($this->__elements as $field) {
            $strReturn .= $field->toJS($intDynamicPosition);
        }

        return $strReturn;
    }
657251
protected function script()
    {
        $trans = [
            'delete_confirm'    => trans('admin.delete_confirm'),
            'save_succeeded'    => trans('admin.save_succeeded'),
            'refresh_succeeded' => trans('admin.refresh_succeeded'),
            'delete_succeeded'  => trans('admin.delete_succeeded'),
            'confirm'           => trans('admin.confirm'),
            'cancel'            => trans('admin.cancel'),
        ];

        $nestableOptions = json_encode($this->nestableOptions);

        return <<<SCRIPT

        $('#{$this->elementId}').nestable($nestableOptions);

        $('.tree_branch_delete').click(function() {
            var id = $(this).data('id');
            swal({
                title: "{$trans['delete_confirm']}",
                type: "warning",
                showCancelButton: true,
                confirmButtonColor: "#DD6B55",
                confirmButtonText: "{$trans['confirm']}",
                showLoaderOnConfirm: true,
                cancelButtonText: "{$trans['cancel']}",
                preConfirm: function() {
                    return new Promise(function(resolve) {
                        $.ajax({
                            method: 'post',
                            url: '{$this->path}/' + id,
                            data: {
                                _method:'delete',
                                _token:LA.token,
                            },
                            success: function (data) {
                                $.pjax.reload('#pjax-container');
                                toastr.success('{$trans['delete_succeeded']}');
                                resolve(data);
                            }
                        });
                    });
                }
            }).then(function(result) {
                var data = result.value;
                if (typeof data === 'object') {
                    if (data.status) {
                        swal(data.message, '', 'success');
                    } else {
                        swal(data.message, '', 'error');
                    }
                }
            });
        });

        $('.{$this->elementId}-save').click(function () {
            var serialize = $('#{$this->elementId}').nestable('serialize');

            $.post('{$this->path}', {
                _token: LA.token,
                _order: JSON.stringify(serialize)
            },
            function(data){
                $.pjax.reload('#pjax-container');
                toastr.success('{$trans['save_succeeded']}');
            });
        });

        $('.{$this->elementId}-refresh').click(function () {
            $.pjax.reload('#pjax-container');
            toastr.success('{$trans['refresh_succeeded']}');
        });

        $('.{$this->elementId}-tree-tools').on('click', function(e){
            var action = $(this).data('action');
            if (action === 'expand') {
                $('.dd').nestable('expandAll');
            }
            if (action === 'collapse') {
                $('.dd').nestable('collapseAll');
            }
        });


SCRIPT;
    }
1036360
function toHTML()
    {

        // get the options of the select control
        $attributes = $this->get_attributes(array('options', 'value', 'multiple', 'other'));

        // if select box is not "multi-select" and the "other" attribute is set
        if (!isset($attributes['multiple']) && isset($attributes['other']))

            // add an extra options to the already existing ones
            $attributes['options'] += array('other' => $this->form_properties['language']['other']);

        // if the default value, as added when instantiating the object is still there
        // or if no options were specified
        if (($key = array_search('#replace-with-language#', $attributes['options'])) !== false || empty($attributes['options']))

            // put the label from the language file
            $attributes['options'][$key] = $this->form_properties['language']['select'];

        // use a private, recursive method to generate the select's content
        $optContent = $this->_generate($attributes['options'], $attributes['value']);

        // return generated HTML
        return '<select '. $this->_render_attributes() . '>' . $optContent . '</select>';

    }
813951
public function generate()
    {
        $code = array();

        if ($this->namespace !== null) {
            $code[] = $this->getIndentation() . 'namespace ' . $this->namespace;
            $code[] = '{';
            $code[] = null;

            // Temporarily add one more level of indentation.
            $this->addIndentationLevel(1);
        }

        $code = array_merge($code, $this->renderUsesLines());

        $indentation = $this->getIndentation();

        $doc = $this->generateDocumentation();
        if ($doc !== null) {
            $code[] = $doc;
        }

        $line = $indentation;
        if ($this->isFinal() === true) {
            $line .= 'final ';
        } elseif ($this->isAbstract() === true) {
            $line .= 'abstract ';
        }

        $line .= 'class ' . $this->name;

        if ($this->extends !== null) {
            $line .= ' extends ' . $this->extends;
        }

        if (count($this->implements) > 0) {
            $line .= ' implements ' . implode(', ', $this->implements);
        }

        $code[] = $line;
        $code[] = $indentation . '{';

        // Class uses.
        $classElements = $this->generateTraitUsesLines();

        // Class constants.
        $classElements = array_merge($classElements, $this->generateConstantsLines());

        // Class properties.
        $classElements = array_merge($classElements, $this->generatePropertiesLines());

        // Class methods.
        $classElements = array_merge($classElements, $this->generateMethodsLines());

        if (count($classElements) > 0) {
            $code[] = null;
            $code = array_merge($code, $classElements);
            // Remove last empty line.
            array_pop($code);
        }

        $code[] = $indentation . '}';

        if ($this->namespace !== null) {
            // Set back the indentation.
            $this->addIndentationLevel(-1);

            $code[] = $this->getIndentation() . '}';
        }

        return implode($this->getLineFeed(), $code);
    }
720732
public function generateAndIncludeInlineJavaScript()
    {
        $formName = $this->assetHandlerFactory->getFormObject()->getName();

        $javaScriptCode = $this->getFormRequestDataJavaScriptAssetHandler()
            ->getFormRequestDataJavaScriptCode();

        if (ExtensionService::get()->isInDebugMode()) {
            $javaScriptCode .= LF . $this->getDebugActivationCode();
        }

        $uri = $this->getAjaxUrl();

        $javaScriptCode .= LF;
        $javaScriptCode .= <<<JS
Fz.setAjaxUrl('$uri');
JS;

        $this->addInlineJs('FormZ - Initialization ' . $formName, $javaScriptCode);

        return $this;
    }
337909
public function requireJs()
    {
        $scripts = $this->dispatcher->scripts('script', $this->assets, $this->path);

        $required = [];
        $string   = '';
        if (isset($this->assets['script'])) {
            foreach ($this->assets['script'] as $js) {
                if (!is_null($require = array_get($js, 'attributes.require'))) {
                    $required["'" . implode("','", $require) . "'"][] = $js['source'];
                }
            }


            $idx = 0;
            foreach ($required as $names => $scripts) {
                $require = "require([$names],function(){ " . "require(['" . implode("','", $scripts) . "'],function(){ :replace })" . "  });";
                if ($idx > 0) {
                    $string = str_replace(':replace', $require, $string);
                } else {
                    $string = $require;
                }
                ++$idx;
            }
        }

        $inlines = implode('', $this->dispatcher->scripts('inline', $this->assets, $this->path));

        $string = !strlen($string) ? $inlines : str_replace(':replace', $inlines . $this->afterLoad(), $string);


        $require = "['" . implode("','", $scripts) . "']";
        return $this->requireInline($require, $string);
    }
946974
public function inlineJs() {
		// Process any actions first
		$this->processBulkActions();
		$this->truncateExports();
		$js = '';

		// Map the export form to equivalents in latest exports table
		$filetypes = \Pressbooks\Modules\Export\filetypes();
		$map = [];
		foreach ( $filetypes as $k => $v ) {
			$map[ "export_formats[{$k}]" ] = $this->getTinyHash( $this->getFormat( $v ) );
		}
		$map = wp_json_encode( $map, JSON_FORCE_OBJECT );
		$js .= "var _pb_export_formats_map = {$map}; ";

		// Pins
		$all_possible_pins = [];
		foreach ( $this->getFiles() as $filepath ) {
			$file = basename( $filepath );
			$key = 'pin[' . $this->getTinyHash( $file ) . ']';
			$all_possible_pins[ $key ] = $this->getTinyHash( $this->getFormat( $file ) );
		}
		$pins = get_transient( self::PIN );
		if ( ! is_array( $pins ) ) {
			$pins = [];
		}
		foreach ( $pins as $k => $v ) {
			if ( ! isset( $all_possible_pins[ $k ] ) ) {
				unset( $pins[ $k ] );
			}
		}
		$pins = wp_json_encode( $pins, JSON_FORCE_OBJECT );
		$js .= "var _pb_export_pins_inventory = {$pins}; ";

		return $js;
	}
500228
public function js()
    {
        $args = [];
        $args = func_get_args();

        if (isset($args[1])) {
            $args[1] = array_merge($args[1], ['type' => 'static']);
        } else {
            $args[1] = ['type' => 'static'];
        }

        return call_user_func_array([new static($this->container), 'script'], $args);
    }
905838
protected function getJavaScriptFiles()
    {
        $formObject = $this->assetHandlerFactory->getFormObject();

        $javaScriptFiles = $this->getFieldsValidationJavaScriptAssetHandler()
            ->getJavaScriptValidationFiles();

        $conditionProcessor = $this->getConditionProcessor($formObject);

        $javaScriptFiles = array_merge($javaScriptFiles, $conditionProcessor->getJavaScriptFiles());

        return $javaScriptFiles;
    }
993562
function toHtml(){
        global $PAGE;

        // Enhance the select with javascript.
        $this->_generateId();
        $id = $this->getAttribute('id');

        if (!$this->isFrozen()) {
            $PAGE->requires->js_call_amd('core/form-autocomplete', 'enhance', $params = array('#' . $id, $this->tags, $this->ajax,
                $this->placeholder, $this->casesensitive, $this->showsuggestions, $this->noselectionstring));
        }

        $html = parent::toHTML();

        // Hacky bodge to add in the HTML code to the option tag. There is a nicer
        // version of this code in the new template version (see export_for_template).
        if ($this->valuehtmlcallback) {
            $html = preg_replace_callback('~value="([^"]+)"~', function($matches) {
                $value = html_entity_decode($matches[1]);
                $htmlvalue = call_user_func($this->valuehtmlcallback, $value);
                if ($htmlvalue !== false) {
                    return $matches[0] . ' data-html="' . s($htmlvalue) . '"';
                } else {
                    return $matches[0];
                }
            }, $html);
        }

        return $html;
    }
447404
private function cmdJs()
    {
        echo "\n - JS -\n";
        if ($js = $this->config->get('js')) {
            if (!$this->subCmd) {
                foreach ($js as $k => $v) {
                    echo "\n - $k:\n";
                    $this->minify($v->filename, $v->add, $this->yuicompressor, $this->config->baseDir);
                }
                return;
            }

            if (isset($js->{$this->subCmd})) {
                echo "\n - ".$this->subCmd."\n";
                $this->minify($js->{$this->subCmd}->filename,
                  $js->{$this->subCmd}->add,
                  $this->yuicompressor,
                  $this->config->baseDir);
            } else {
                echo "\n Err: Not found!\n";
                return;
            }
        }
    }
1000560
public function controlDataForJs()
    {
        $prop = $this->property();

        $data = [
            // Selectize Control
            'title'                    => (string)$prop->label(),
            'translations'             => [
                'statusTemplate'       => $this->translator()->translate('Step [[ current ]] of [[ total ]]'),
            ],
            'copy_items'               => $this->allowClipboardCopy(),
            'allow_update'             => $this->allowUpdate(),
            'allow_create'             => $this->allowCreate(),

            'form_ident'               => $this->formIdent(),
            'selectize_selector'       => '#'.$this->inputId(),
            'selectize_options'        => $this->selectizeOptions(),
            'choice_obj_map'           => $this->choiceObjMap(),
            'selectize_property_ident' => $prop->ident(),
            'selectize_templates'      => $this->selectizeTemplates(),
            'selectize_property'       => json_encode($this->property()),
            'remote_source'            => $this->remoteSource(),

            // Base Property
            'required'                 => $this->required(),
            'l10n'                     => $this->property()->l10n(),
            'multiple'                 => $this->multiple(),
            'multiple_separator'       => $this->property()->multipleSeparator(),
            'multiple_options'         => $this->property()->multipleOptions(),
        ];

        if ($prop instanceof ObjectProperty) {
            if ($prop->objType()) {
                $data['pattern']  = $prop->pattern();
                $data['obj_type'] = $prop->objType();
            }
        }

        return $data;
    }
912114
private function prepareJs()
    {
        switch ($this->treeType) {
            case self::TREE_TYPE_ADJACENCY :
                return $this->adjacencyJs();
            case self::TREE_TYPE_NESTED_SET :
                return $this->nestedSetJs();
        }
    }
74455
public function compile(JsUtils $js=NULL, &$view=NULL) {
		if (isset($js)) {
			$this->formElementsPrefix=$js->config()->getVar("formElementsPrefix");
			foreach ( $this->futureElements as $futureElement ) {
				$futureElementValue=$this->getPrefix($futureElement);
				$futureElementValues=explode("_", $futureElementValue);
				switch($futureElementValues [0]) {
					case "input":
						$control=new HtmlInput($futureElement);
						$control->setClass("form-control");
						$control->setLabel($this->getPart($futureElement));
						break;
					case "checkbox":
						$control=new HtmlInputCheckbox($futureElement);
						$control->setLabel($this->getPart($futureElement), false);
						break;
					case "radio":
						$name=$this->getPart($futureElement);
						$label=$this->getPart($futureElement, 2);
						$control=new HtmlInputRadio($futureElement);
						$control->setProperty("name", strtolower($name));
						$control->setLabel($label, false);
						break;
					case "select":
						$control=new HtmlSelect($futureElement,"");
						$control->setProperty("size", $futureElementValues [1]);
						$control->setClass("form-control");
						break;
					default:
						$control=new HtmlInput($futureElement);
						$control->setClass("form-control");
						$control->setLabel($this->getPart($futureElement));
						break;
				}
				$this->addElement($control);
			}
		}
		foreach ( $this->formGroups as $group ) {
			$this->addContent($group);
		}
		return parent::compile($js, $view);
	}
274642
protected function getInlineJavaScript()
    {
        static $shown = false;

        if (!$shown) {
            $javascript = $this->getInlineJavaScriptTranslations();
            $shown = true;
        } else {
            $javascript = '';
        }

        if (isset($this->valid_range_start)) {
            $start_date = $this->valid_range_start->formatLikeIntl(
                'MM/dd/yyyy'
            );
        } else {
            $start_date = '';
        }

        if (isset($this->valid_range_end)) {
            // JavaScript calendar is inclusive, subtract one second from range
            $tmp = clone $this->valid_range_end;
            $tmp->subtractSeconds(1);
            $end_date = $tmp->formatLikeIntl('MM/dd/yyyy');
        } else {
            $end_date = '';
        }

        $javascript .= sprintf(
            "var %s_obj = new SwatCalendar('%s', '%s', '%s');",
            $this->id,
            $this->id,
            $start_date,
            $end_date
        );

        return $javascript;
    }
821225
protected function buildForm()
    {
        if ($this->form) {
            return;
        }

        // append parent object if any
        // todo : clean the way the Admin class can retrieve set the object
        if ($this->isChild() && $this->getParentAssociationMapping()) {
            $parent = $this->getParent()->getObject($this->request->get($this->getParent()->getIdParameter()));

            $propertyAccessor = $this->getConfigurationPool()->getPropertyAccessor();
            $propertyPath = new PropertyPath($this->getParentAssociationMapping());

            $object = $this->getSubject();

            $value = $propertyAccessor->getValue($object, $propertyPath);

            if (\is_array($value) || ($value instanceof \Traversable && $value instanceof \ArrayAccess)) {
                $value[] = $parent;
                $propertyAccessor->setValue($object, $propertyPath, $value);
            } else {
                $propertyAccessor->setValue($object, $propertyPath, $parent);
            }
        }

        $formBuilder = $this->getFormBuilder();
        $formBuilder->addEventListener(FormEvents::POST_SUBMIT, function (FormEvent $event) {
            $this->preValidate($event->getData());
        }, 100);

        $this->form = $formBuilder->getForm();
    }
779460
private function getJS()
    {

        if (strlen($this->JSrenderDocReady . $this->JSrender) == 0) {
            return "";
        }

        $js = "
                    <script type=\"text/javascript\">

                    ";
        if (strlen($this->JSrenderDocReady) > 0) {
            $js .= "   $(document).ready(function()
                        {
                        {$this->JSrenderDocReady}
                        } )
                      ";
        }
        $js .= $this->JSrender . "


                    </script>"
        ;

        return $js;
    }