generate fk field related to class wait popup crud
970767
def get_fk_popup_field(cls, *args, **kwargs):
        
        kwargs['popup_name'] = cls.get_class_verbose_name()
        kwargs['permissions_required'] = cls.permissions_required
        if cls.template_name_fk is not None:
            kwargs['template_name'] = cls.template_name_fk
        return ForeignKeyWidget('{}_popup_create'.format(cls.get_class_name()), *args, **kwargs)
439283
void submitForm(CmsForm formParam, final Map<String, String> fieldValues, Set<String> editedFields) {

        String modelGroupId = null;

        if (CmsInheritanceContainerEditor.getInstance() != null) {
            CmsInheritanceContainerEditor.getInstance().onSettingsEdited();
        }
        if (m_contextsWidget != null) {
            String newTemplateContexts = m_contextsWidget.getFormValueAsString();
            if ((newTemplateContexts == null) || "".equals(newTemplateContexts)) {
                newTemplateContexts = CmsTemplateContextInfo.EMPTY_VALUE;
                // translate an empty selection to "none"
            }
            fieldValues.put(CmsTemplateContextInfo.SETTING, newTemplateContexts);
        }
        final boolean hasFormatterChanges;
        if (m_formatterSelect != null) {
            fieldValues.put(
                CmsFormatterConfig.getSettingsKeyForContainer(m_containerId),
                m_formatterSelect.getFormValueAsString());
            hasFormatterChanges = true;
        } else {
            hasFormatterChanges = false;
        }
        if (m_createNewCheckBox != null) {
            m_elementWidget.setCreateNew(m_createNewCheckBox.isChecked());
            fieldValues.put(CmsContainerElement.CREATE_AS_NEW, Boolean.toString(m_createNewCheckBox.isChecked()));
        }
        if (m_modelGroupSelect != null) {
            GroupOption group = GroupOption.valueOf(m_modelGroupSelect.getFormValueAsString());
            switch (group) {
                case disabled:
                    fieldValues.put(CmsContainerElement.MODEL_GROUP_STATE, ModelGroupState.noGroup.name());
                    fieldValues.put(CmsContainerElement.USE_AS_COPY_MODEL, Boolean.toString(false));
                    break;
                case copy:
                    fieldValues.put(CmsContainerElement.MODEL_GROUP_STATE, ModelGroupState.isModelGroup.name());
                    fieldValues.put(CmsContainerElement.USE_AS_COPY_MODEL, Boolean.toString(true));
                    break;
                case reuse:
                    fieldValues.put(CmsContainerElement.MODEL_GROUP_STATE, ModelGroupState.isModelGroup.name());
                    fieldValues.put(CmsContainerElement.USE_AS_COPY_MODEL, Boolean.toString(false));
                    break;
                default:
                    break;
            }
            if (group != GroupOption.disabled) {
                modelGroupId = CmsContainerpageController.getServerId(m_elementBean.getClientId());
            }
        }

        if ((m_modelGroupBreakUp != null) && m_modelGroupBreakUp.isChecked()) {
            fieldValues.put(CmsContainerElement.MODEL_GROUP_STATE, ModelGroupState.noGroup.name());
        }

        final Map<String, String> filteredFieldValues = new HashMap<String, String>();
        for (Map.Entry<String, String> entry : fieldValues.entrySet()) {
            String key = entry.getKey();
            String value = entry.getValue();
            if ((value != null) && (value.length() > 0)) {
                filteredFieldValues.put(key, value);
            }
        }
        final String changeModelGroupId = modelGroupId;
        m_controller.reloadElementWithSettings(
            m_elementWidget,
            m_elementBean.getClientId(),
            filteredFieldValues,
            new I_CmsSimpleCallback<CmsContainerPageElementPanel>() {

                public void execute(CmsContainerPageElementPanel result) {

                    if (isTemplateContextChanged()) {
                        // if the context multiselect box isn't displayed, of course it can't change values,
                        // and this code won't be executed.
                        CmsContainerpageController.get().handleChangeTemplateContext(
                            result,
                            filteredFieldValues.get(CmsTemplateContextInfo.SETTING));
                    }
                    if (hasFormatterChanges) {
                        updateCss();
                    }
                    if (result.getElement().getInnerHTML().contains(CmsGwtConstants.FORMATTER_RELOAD_MARKER)
                        && !CmsContainerpageController.get().isGroupcontainerEditing()) {
                        CmsContainerpageController.get().reloadPage();
                    }
                    if (m_modelGroupSelect != null) {
                        m_controller.setModelGroupElementId(changeModelGroupId);
                    }
                }

            });
    }
44906
public function generate()
    {
        $url = sprintf(
            'system/modules/icon-wizard/public/popup.php?table=%s&amp;field=%s&amp;name=ctrl_%s&amp;id=%s',
            $this->strTable,
            $this->strField,
            $this->name,
            \Input::get('id')
        );

        $template = <<<HTML
<div class="iconWizard"><input type="hidden" name="%s" id="ctrl_%s" value="%s"%s
<span class="icon">%s</span> <span class="title">%s</span><a href="%s"
onclick="Backend.getScrollOffset();Backend.openModalIframe({url:'%s', width: %s, title: '%s'});return false"
 title="%s" class="tl_submit">%s</a></div>
HTML;

        return sprintf(
            $template,
            $this->name,
            $this->name,
            $this->icon,
            $this->strTagEnding,
            $this->icon ? sprintf($this->iconTemplate, $this->icon) : '',
            $this->icon ? $this->icon : '-',
            $url,
            $url,
            790,
            $GLOBALS['TL_LANG']['MSC']['iconWizard'][0],
            $GLOBALS['TL_LANG']['MSC']['iconWizardlink'][1],
            $GLOBALS['TL_LANG']['MSC']['iconWizardlink'][0]
        );
    }
767860
function generateDropFieldSql( $table, $field_name, $params )
    {
        return $this->OtherSchema->generateDropFieldSql( $table, $field_name, $params );
    }
930099
public function generateDetailViewField($attribute, $fk, $tableSchema = null)
    {
        if (is_null($tableSchema)) {
            $tableSchema = $this->getTableSchema();
        }
        if (in_array($attribute, $this->hiddenColumns)) {
            return "['attribute' => '$attribute', 'visible' => false],\n";
        }
        $humanize = Inflector::humanize($attribute, true);
        if ($tableSchema === false || !isset($tableSchema->columns[$attribute])) {
            if (preg_match('/^(password|pass|passwd|passcode)$/i', $attribute)) {
                return "";
            } else {
                return "'$attribute',\n";
            }
        }
        $column = $tableSchema->columns[$attribute];
        $format = $this->generateColumnFormat($column);
//        if($column->autoIncrement){
//            return "";
//        } else
        if (array_key_exists($attribute, $fk)) {
            $rel = $fk[$attribute];
            $labelCol = $this->getNameAttributeFK($rel[3]);
//            $humanize = Inflector::humanize($rel[3]);
//            $id = 'grid-' . Inflector::camel2id(StringHelper::basename($this->searchModelClass)) . '-' . $attribute;
//            $modelRel = $rel[2] ? lcfirst(Inflector::pluralize($rel[1])) : lcfirst($rel[1]);
            $output = "[
            'attribute' => '$rel[7].$labelCol',
            'label' => " . $this->generateString(ucwords(Inflector::humanize($rel[5]))) . ",
        ],\n";
            return $output;
        } else {
            return "'$attribute" . ($format === 'text' ? "" : ":" . $format) . "',\n";
        }
    }
270720
function () {
	          var _this = this;
	          var args = [];
	          for (var _i = 0; _i < arguments.length; _i++) {
	              args[_i - 0] = arguments[_i];
	          }
	          var instanceCtx = new _ExecutionContext(_ctx, this, _classStmt.name, _ctx.vars);
	          _classStmt.fields.forEach(function (field) { _this[field.name] = undefined; });
	          _executeFunctionStatements(ctorParamNames, args, _classStmt.constructorMethod.body, instanceCtx, _visitor);
	      }
617495
function(searchTerm) {
    var suggestions = [ ];
    var popup = this.getElement({type: "searchBar_autoCompletePopup"});
    var treeElem = this.getElement({type: "searchBar_suggestions"});

    // Enter search term and wait for the popup
    this.type(searchTerm);

    this._controller.waitForEval("subject.popup.state == 'open'", TIMEOUT, 100,
                                 {popup: popup.getNode()});
    this._controller.waitForElement(treeElem, TIMEOUT);

    // Get all suggestions
    var tree = treeElem.getNode();
    this._controller.waitForEval("subject.tree.view != null", TIMEOUT, 100,
                                 {tree: tree});
    for (var i = 0; i < tree.view.rowCount; i ++) {
      suggestions.push(tree.view.getCellText(i, tree.columns.getColumnAt(0)));
    }

    // Close auto-complete popup
    this._controller.keypress(popup, "VK_ESCAPE", {});
    this._controller.waitForEval("subject.popup.state == 'closed'", TIMEOUT, 100,
                                 {popup: popup.getNode()});

    return suggestions;
  }
1074104
def handle_class_prepared(sender, **kwargs):
    
    from .settings import M2M_REGISTRY, FK_REGISTRY
    from .registration import registry
    sender_app = sender._meta.app_label
    sender_name = sender._meta.model_name

    for key, val in list(FK_REGISTRY.items()):
        app_name, model_name = key.split('.')
        if app_name == sender_app and sender_name == model_name:
            registry.register_model(app_name, sender, 'ForeignKey', val)

    for key, val in list(M2M_REGISTRY.items()):
        app_name, model_name = key.split('.')
        if app_name == sender_app and sender_name == model_name:
            registry.register_model(app_name, sender, 'ManyToManyField', val)
1118368
protected void populateData(final T selectedBaseEntity) {
        this.selectedBaseEntity = selectedBaseEntity;
        editButton.setEnabled(selectedBaseEntity != null);
        manageMetadataBtn.setEnabled(selectedBaseEntity != null);
        if (selectedBaseEntity == null) {
            setName(getDefaultCaption(), "");
        } else {
            setName(getDefaultCaption(), getName());
        }
        populateLog();
        populateDescription();
        populateDetailsWidget();
    }
475458
def js_for_has_many(class_string, &form_block)
      assoc_name       = assoc_klass.model_name
      placeholder      = "NEW_#{assoc_name.to_s.underscore.upcase.gsub(/\//, '_')}_RECORD"
      opts = {
        for: [assoc, assoc_klass.new],
        class: class_string,
        for_options: { child_index: placeholder }
      }
      html = template.capture { __getobj__.send(:inputs_for_nested_attributes, opts, &form_block) }
      text = new_record.is_a?(String) ? new_record : I18n.t('active_admin.has_many_new', model: assoc_name.human)

      template.link_to text, '#', class: "button has_many_add", data: {
        html: CGI.escapeHTML(html).html_safe, placeholder: placeholder
      }
    end
456019
public function fillFields()
    {
        // Fill the fields from $_POST array
        foreach ($_POST as $key => $val) {
            
            // Get int value form field parent id
            if ($key == 'ParentID' && $val == 0) {
                
                $this[$key] = null;
                
                // Get other fields
            } elseif ($key != 'StructureID') {
                
                $this[$key] = $val;
            }
        }

        // Save data about application
        $this['applicationGenerate'] = isset($_POST['generate-application'])&&($_POST['generate-application'] == true) ? 1 : 0;
        $this['applicationOutput'] = isset($_POST['output-application'])&&($_POST['output-application'] == true) ? 1 : 0;
        $this['applicationOutputStructure'] = isset($_POST['output-structure-application'])&&($_POST['output-structure-application'] == true) ? 1 : 0;
        $this['applicationRenderMain'] = isset($_POST['render-main-application'])&&($_POST['render-main-application'] == true) ? 1 : 0;

        // If application need to generate then set system property to 1 or 0
        $this['system'] = isset($_POST['generate-application'])&&($_POST['generate-application'] == true) ? 1: 0;

        // Save icon
        $icon = isset($_POST['icon-application']) ? filter_var($_POST['icon-application']) : null;
        if (strlen($icon) > 0) {
            $this['applicationIcon'] = $icon;
        }

        /** TODO: Authenticated user can be not instance of user table */
        if (!$this->query->entity('\samson\activerecord\user')->where('user_id', $this->UserID)->first()) {
            $this->UserID = 1;
        }
        // Save object
        $this->save();

        if (isset($_POST['ParentID']) && $_POST['ParentID'] != 0) {
            // Create new relation
            $strRelation = new \samson\activerecord\structure_relation(false);
            $strRelation->parent_id = $_POST['ParentID'];
            $strRelation->child_id = $this->id;

            // Save relation
            $strRelation->save();
        }
    }
865030
protected static function prepareManyToOne(&$ret, $instance, $value, $fkField, $annotationArray) {
		$member = $annotationArray ["member"];
		$fk = OrmUtils::getFirstKey ( $annotationArray ["className"] );
		$key = $annotationArray ["className"] . "|" . $member . "|" . $fkField . "|";
		if (! isset ( $ret [$key] )) {
			$ret [$key] = new PendingRelationsRequest ();
		}
		$ret [$key]->addPartObject ( $instance, $fk . "= ?", $value );
	}
1231877
private static void onBind(Class clazz)
    {

        if (((MetamodelImpl) em.getMetamodel()).getEntityMetadataMap().isEmpty())
        {

            EntityMetadata metadata = new EntityMetadata(clazz);
            metadata.setPersistenceUnit(getPersistenceUnit());

            setSchemaAndPU(clazz, metadata);

            new TableProcessor(em.getEntityManagerFactory().getProperties(),
                    ((EntityManagerFactoryImpl) em.getEntityManagerFactory()).getKunderaMetadataInstance())
                            .process(clazz, metadata);

            KunderaMetadata kunderaMetadata = ((EntityManagerFactoryImpl) em.getEntityManagerFactory())
                    .getKunderaMetadataInstance();

            new IndexProcessor(kunderaMetadata).process(clazz, metadata);

            ApplicationMetadata appMetadata = kunderaMetadata.getApplicationMetadata();

            ((MetamodelImpl) em.getMetamodel()).addEntityMetadata(clazz, metadata);
            ((MetamodelImpl) em.getMetamodel()).addEntityNameToClassMapping(clazz.getSimpleName(), clazz);
            appMetadata.getMetamodelMap().put(getPersistenceUnit(), em.getMetamodel());

            Map<String, List<String>> clazzToPuMap = new HashMap<String, List<String>>();
            List<String> persistenceUnits = new ArrayList<String>();
            persistenceUnits.add(getPersistenceUnit());
            clazzToPuMap.put(clazz.getName(), persistenceUnits);
            appMetadata.setClazzToPuMap(clazzToPuMap);
            new SchemaConfiguration(em.getEntityManagerFactory().getProperties(), kunderaMetadata, getPersistenceUnit())
                    .configure();

        }

    }
1280818
function getSyncMethod(model, options = {}) {
  const forceAjaxSync = options.ajaxSync;
  const hasLocalStorage = getLocalStorage(model);

  return !forceAjaxSync && hasLocalStorage ? localSync : ajaxSync;
}
561284
function (context, callback) {

            var self = this,
                options = {},
                model,
                processor,
                isPatch = context.request.method === "PATCH",
                upsert = this.$resourceConfiguration.$.upsert,
                defaults;


            flow()
                .seq("collection", function (cb) {
                    self._findCollection(context, cb);
                })
                .seq(function (cb) {
                    model = this.vars.collection.createItem(self.$resourceId);
                    defaults = _.clone(model.$);
                    // check if model exists
                    if (upsert && !isPatch) {
                        cb();
                    } else {
                        model.fetch(null, cb);
                    }
                })
                .seq(function () {
                    if (!isPatch) {
                        model.clear();
                        model.set(defaults);
                    }

                    var payload = context.request.params;

                    processor = self.$restHandler.$restDataSource.getProcessorForModel(model);

                    model.set(processor.parse(model, payload || {}));

                    options.action = DataSource.ACTION.UPDATE;

                    // TODO: add hook to add session data like user id
                    if (upsert === true) {
                        options.upsert = true;
                        model.set(model.idField, model.factory.prototype.convertIdentifier(self.$resourceId));
                    }
                })
                .seq(function () {
                    self._generateAutoValues(model);
                })
                .seq(function (cb) {
                    self._validate(model, context, cb);
                })
                .seq(function (cb) {
                    self._beforeModelSave(model, context, cb);
                })
                .seq(function (cb) {
                    self._beforeModelUpdate(model, context, cb);
                })
                .seq(function (cb) {
                    model.validateAndSave(options, cb);
                })
                .seq(function (cb) {
                    self._afterModelUpdate(model, context, cb);
                })
                .exec(function (err, results) {
                    if (!err) {
                        // TODO: do correct invalidation
                        results.collection.invalidatePageCache();

                        self._fetchAllHrefsForModel(model, context);

                        // TODO: generate the location header
                        var body = JSON.stringify(processor.compose(model, null));

                        var response = context.response;
                        response.writeHead(200, "", {
                            'Content-Type': 'application/json'
                            // TODO : add updated date in head ???
//                            'Location': context.request.urlInfo.uri
                        });

                        response.write(body);
                        response.end();

                        callback(null);
                    } else {
                        if (!(err instanceof HttpError)) {
                            var statusCode = 400;
                            if (err === DataSource.ERROR.NOT_FOUND) {
                                statusCode = 404;
                            }
                            err = new HttpError(err, statusCode);
                        }
                        callback(err);
                    }
                });

        }
802639
function getNextId(db, collectionName, fieldName, callback) {
    if (typeof fieldName == "function") {
        callback = fieldName;
        fieldName = null;
    }

    fieldName = fieldName || getOption(collectionName, "field");
    var collection = db.collection(defaultSettings.collection);
    var step = getOption(collectionName, "step");

    collection.findAndModify(
        {_id: collectionName, field: fieldName},
        null,
        {$inc: {seq: step}},
        {upsert: true, new: true},
        function (err, result) {
            if (err) {
                if (err.code == 11000) {
                    process.nextTick(getNextId.bind(null, db, collectionName, fieldName, callback));
                } else {
                    callback(err);
                }
            } else {
                if (result.value && result.value.seq) {
                    callback(null, result.value.seq);
                } else {
                    callback(null, result.seq);
                }
            }
        }
    );
}
1196911
public function generatePopup()
    {
        $GLOBALS['TL_JAVASCRIPT']['cca.dc-general.vanillaGeneral'] = 'bundles/ccadcgeneral/js/vanillaGeneral.js';

        $environment = $this->getEnvironment();
        $translator  = $environment->getTranslator();
        $template    = new ContaoBackendViewTemplate('widget_treepicker_popup');

        $icon = new GenerateHtmlEvent($this->titleIcon);
        $environment->getEventDispatcher()->dispatch(ContaoEvents::IMAGE_GET_HTML, $icon);

        $template
            ->setTranslator($translator)
            ->set('id', 'tl_listing')
            ->set('name', $this->strName)
            ->set('class', ($this->strClass ? ' ' . $this->strClass : ''))
            ->set('icon', $icon->getHtml())
            ->set('title', $translator->translate($this->title ?: 'MSC.treePicker', '', [$this->sourceName]))
            ->set('fieldType', $this->fieldType)
            ->set('resetSelected', $translator->translate('MSC.resetSelected'))
            ->set('selectAll', $translator->translate('MSC.selectAll'))
            ->set('values', StringUtil::deserialize($this->varValue, true));

        // Create Tree Render with custom root points.
        $tree = '';
        foreach ($this->getRootIds() as $pid) {
            $tree .= $this->generateTreeView($this->loadCollection($pid), 'tree');
        }

        $template->set('tree', $tree);

        // Load the fonts for the drag hint.
        $GLOBALS['TL_CONFIG']['loadGoogleFonts'] = true;

        return $template->parse();
    }