Fill the form with previous data if necessary to handle partial update
171644
def _add_entry(self, formdata=None, data=unset_value, index=None):
        '''
        
        '''
        if formdata:
            prefix = '-'.join((self.name, str(index)))
            basekey = '-'.join((prefix, '{0}'))
            idkey = basekey.format('id')
            if prefix in formdata:
                formdata[idkey] = formdata.pop(prefix)
            if hasattr(self.nested_model, 'id') and idkey in formdata:
                id = self.nested_model.id.to_python(formdata[idkey])
                data = get_by(self.initial_data, 'id', id)

                initial = flatten_json(self.nested_form,
                                       data.to_mongo(),
                                       prefix)

                for key, value in initial.items():
                    if key not in formdata:
                        formdata[key] = value
            else:
                data = None
        return super(NestedModelList, self)._add_entry(formdata, data, index)
714026
def form_valid(self, form):
        '''  '''

        startDate = form.cleaned_data.get('startDate')
        repeatEvery = form.cleaned_data.get('repeatEvery')
        periodicity = form.cleaned_data.get('periodicity')
        quantity = form.cleaned_data.get('quantity')
        endDate = form.cleaned_data.get('endDate')

        # Create a list of start dates, based on the passed  values of repeatEvery,
        # periodicity, quantity and endDate.  This list will be iterated through to
        # create the new instances for each event.
        if periodicity == 'D':
            delta = {'days': repeatEvery}
        elif periodicity == 'W':
            delta = {'weeks': repeatEvery}
        elif periodicity == 'M':
            delta = {'months': repeatEvery}

        repeat_list = []
        this_date = startDate

        if quantity:
            for k in range(0, quantity):
                repeat_list.append(this_date)
                this_date = this_date + relativedelta(**delta)
        elif endDate:
            while (this_date <= endDate):
                repeat_list.append(this_date)
                this_date = this_date + relativedelta(**delta)

        # Now, loop through the events in the queryset to create duplicates of them
        for event in self.queryset:

            # For each new occurrence, we determine the new startime by the distance from
            # midnight of the first occurrence date, where the first occurrence date is
            # replaced by the date given in repeat list
            old_min_time = event.localStartTime.replace(hour=0, minute=0, second=0, microsecond=0)

            old_occurrence_data = [
                (x.startTime - old_min_time, x.endTime - old_min_time, x.cancelled)
                for x in event.eventoccurrence_set.all()
            ]

            old_role_data = [(x.role, x.capacity) for x in event.eventrole_set.all()]

            for instance_date in repeat_list:

                # Ensure that time zones are treated properly
                combined_datetime = datetime.combine(instance_date, datetime.min.time())
                new_datetime = ensure_timezone(combined_datetime, old_min_time.tzinfo)

                # Removing the pk and ID allow new instances of the event to
                # be created upon saving with automatically generated ids.
                event.id = None
                event.pk = None
                event.save()

                # Create new occurrences
                for occurrence in old_occurrence_data:
                    EventOccurrence.objects.create(
                        event=event,
                        startTime=new_datetime + occurrence[0],
                        endTime=new_datetime + occurrence[1],
                        cancelled=occurrence[2],
                    )

                # Create new event-specific role data
                for role in old_role_data:
                    EventRole.objects.create(
                        event=event,
                        role=role[0],
                        capacity=role[1],
                    )

                # Need to save twice to ensure that startTime etc. get
                # updated properly.
                event.save()

            return super(RepeatEventsView, self).form_valid(form)
272542
def save(self):
        """"""
        if ( self._new or
            (self._validID() and self._changed) or
            (self._updated and self._changed > self._updated) ):
            # Don't save if we have not loaded existing data!
            self._saveDB()
            return True
        return False
734669
protected function fillDataForEmpty()
    {
        // Fill list references if they are empty
        $columns = [];

        // Add columns for attributes
        foreach ($this->info->attributes as $attribute) {

            if ($attribute->hidden || ! $this->shouldAttributeBeDisplayedByDefault($attribute, $this->info)) {
                continue;
            }

            $columns[ $attribute->name ] = $this->makeModelListColumnDataForAttributeData($attribute, $this->info);
        }

        // Add columns for relations?
        // Perhaps, though it may be fine to leave this up to manual configuration.
        // todo: consider


        $this->info->list->columns = $columns;
    }
56754
function handlePermissionUpdate() {
            permissionArea.find("form").submit(function (e) {
                e.preventDefault();
                //console.log(e);
                var form = e.currentTarget;
                appendFormFields(form);
                Rocket.Util.submitFormAsync(form, function (responseData) {
                    //console.log(responseData);
                    if (responseData && responseData.status && responseData.status == "success") {
                        location.reload();
                    }
                });
            });
        }
237137
protected function loadFormData()
    {
        parent::loadFormData();

        if (! isset($this->formData['change_method'])) {
            $this->formData['change_method'] = null;
        }
        $this->formData['orig_org_id'] = $this->request->getParam(\MUtil_Model::REQUEST_ID2);
    }
1031484
def before_update(self, context, current, resource):
        

        # Return if the budget data package fields have not been filled in
        if not self.are_budget_data_package_fields_filled_in(resource):
            return

        if resource.get('upload', '') == '':
            # If it isn't an upload we check if it's the same url
            if current['url'] == resource['url']:
                # Return if it's the same
                return
            else:
                self.data.load(resource['url'])
        else:
            self.data.load(resource['upload'].file)

        self.generate_budget_data_package(resource)
958808
public function initUpdate()
    {
        $this->addAction(['icon' => 'edit'], new jsModal('Edit', $this->pageUpdate, [$this->name => $this->jsRow()->data('id'), $this->name.'_sort' => $this->getSortBy()]));

        $this->pageUpdate->set(function () {
            $this->model->load($this->app->stickyGet($this->name));

            // Maybe developer has already created form
            if (!is_object($this->formUpdate) || !$this->formUpdate->_initialized) {
                $this->formUpdate = $this->pageUpdate->add($this->formUpdate ?: $this->formDefault);
            }

            $this->formUpdate->setModel($this->model, $this->fieldsUpdate ?: $this->fieldsDefault);

            if ($sortBy = $this->getSortBy()) {
                $this->formUpdate->stickyGet($this->name.'_sort', $sortBy);
            }

            // set save handler with reload trigger
            // adds default submit hook if it is not already set for this form
            if (!$this->formUpdate->hookHasCallbacks('submit')) {
                $this->formUpdate->onSubmit(function ($form) {
                    $form->model->save();

                    return $this->jsSaveUpdate();
                });
            }
        });
    }
1134560
def get_update_object(self, form):
        
        pk = form.cleaned_data['pk']
        queryset = self.get_queryset()
        try:
            obj = queryset.get(pk=pk)
        except queryset.model.DoesNotExist:
            obj = None

        return obj
1364175
public function updateEditForm(Form $form) {
        $record=$form->getRecord();
        if($record) {
            $kapostRefID=$record->KapostRefID;
            if(empty($kapostRefID)) {
                return;
            }

            //Make the fields all read only
            $oldFields=$form->Fields();
            $form->setFields($oldFields->makeReadonly());
            
            //Make the fields that should be non-readonly editable again
            if(is_array($record->config()->non_readonly_settings_fields)) {
                foreach($record->config()->non_readonly_settings_fields as $fieldName) {
                    $oldField=$oldFields->dataFieldByName($fieldName);
                    if($oldField) {
                        $form->Fields()->replaceField($fieldName, $oldField);
                    }
                }
            }
        }
    }
578705
function() {
		var record, newvalues;
		
		// Validate the Form
	  	if ( !this.dialog.getForm().validate() ) return ;
	
		// Insert a new row
      this.datatable.addRow({});

		// Set the Selected Record
		var rowIndex = this.datatable.getRecordSet().getLength() - 1;
		this.selectedRecord = rowIndex;
		
		// Update the row
		newvalues = this.dialog.getValue();
		this.datatable.updateRow( this.selectedRecord , newvalues );
		
		// Get the new record
		record = this.datatable.getRecord(this.selectedRecord);
					
		// Fire the add event
      this.itemAddedEvt.fire(record);
		
		// Hide the dialog 
      this.dialog.hide();
   }
46937
public function postSave()
    {
        if (isset($this->historyLimit) && $this->revisionHistory()->count() >= $this->historyLimit) {
            $LimitReached = true;
        } else {
            $LimitReached = false;
        }
        if (isset($this->revisionCleanup)){
            $RevisionCleanup=$this->revisionCleanup;
        }else{
            $RevisionCleanup=false;
        }

        // check if the model already exists
        if (((!isset($this->revisionEnabled) || $this->revisionEnabled) && $this->updating) && (!$LimitReached || $RevisionCleanup)) {
            // if it does, it means we're updating

            $changes_to_record = $this->changedRevisionableFields();

            $revisions = array();

            foreach ($changes_to_record as $key => $change) {
                $revisions[] = array(
                    'revisionable_type' => $this->getMorphClass(),
                    'revisionable_id' => $this->getKey(),
                    'key' => $key,
                    'old_value' => array_get($this->originalData, $key),
                    'new_value' => $this->updatedData[$key],
                    'user_id' => $this->getSystemUserId(),
                    'created_at' => new \DateTime(),
                    'updated_at' => new \DateTime(),
                );
            }

            if (count($revisions) > 0) {
                if($LimitReached && $RevisionCleanup){
                    $toDelete = $this->revisionHistory()->orderBy('id','asc')->limit(count($revisions))->get();
                    foreach($toDelete as $delete){
                        $delete->delete();
                    }
                }
                $revision = Revisionable::newModel();
                \DB::table($revision->getTable())->insert($revisions);
                \Event::dispatch('revisionable.saved', array('model' => $this, 'revisions' => $revisions));
            }
        }
    }
103162
def _fill_form(form):
        
        clicked = False
        last_element = None
        for field in form:
            if field['text']:
                field['element'].clear()
                field['element'].send_keys(field['text'])
            if field['click']:
                field['element'].click()
                clicked = True
            last_element = field['element']
        if last_element:
            if not clicked:
                last_element.submit()
1082138
protected function setFormData()
    {
        foreach ($this->validFields as $field => $params) {
            if (isset($params["rename"])) {
                $field = $params["rename"];
            }
            if ($params['type'] == "single") {
                if (isset($this->fieldData[$field])) {
                    $this->formData[$field] = $this->fieldData[$field];
                }
            } elseif ($params['type'] == "product") {
                if (!isset($this->formData[$field])) {
                    $this->formData[$field] = array();
                }
                foreach ($this->products as $num => $product) {
                    if (isset($product[$params["paramName"]])) {
                        $this->formData[$field][$num] = $product[$params["paramName"]];
                    }
                }
            }
        }
    }
856322
function prepareFormData() {

            var data = {},
                matches,
                index;

            for (var i in formData) {
                if (!formData.hasOwnProperty(i)) continue;

                index = 0;
                matches = i.split(/\[(.+?)]/g);

                var tmpObject = {},
                    tmpArray = [];

                for (var k = matches.length - 1; k >= 0; k--) {
                    if (matches[k] === "") {
                        matches.splice(k, 1);
                        continue;
                    }

                    if (tmpArray.length < 1) {
                        tmpObject[matches[k]] = Number(formData[i]) || formData[i];
                    } else {
                        tmpObject = {};
                        tmpObject[matches[k]] = tmpArray[tmpArray.length - 1];
                    }
                    tmpArray.push(tmpObject)

                }

                data = $.extend(true, data, tmpObject);

            }

            formData = data;

        }
422047
def pre_save(self, instance, add):
        
        # get currently entered slug
        value = self.value_from_object(instance)
        slug = None

        # auto populate (if the form didn't do that already).
        # If you want unique_with logic, use django-autoslug instead.
        # This model field only allows parameters which can be passed to the form widget too.
        if self.populate_from and (self.always_update or not value):
            value = getattr(instance, self.populate_from)

        # Make sure the slugify logic is applied,
        # even on manually entered input.
        if value:
            value = force_text(value)
            slug = self.slugify(value)
            if self.max_length < len(slug):
                slug = slug[:self.max_length]

        # make the updated slug available as instance attribute
        setattr(instance, self.name, slug)
        return slug
848634
public function updateEditForm(Form $form) {
        $record=$form->getRecord();
        if($record) {
            $kapostRefID=$record->KapostRefID;
            if(empty($kapostRefID)) {
                return;
            }

            //Make the fields all read only
            $oldFields=$form->Fields();
            $form->setFields($oldFields->makeReadonly());
            
            //Make the fields that should be non-readonly editable again
            foreach($record->config()->non_readonly_fields as $fieldName) {
                $oldField=$oldFields->dataFieldByName($fieldName);
                if($oldField) {
                    $form->Fields()->replaceField($fieldName, $oldField);
                }
            }
            
            
            //Loop through the wysiwyg fields that need to be made safe and sanitize their html
            foreach($record->config()->make_safe_wysiwyg_fields as $fieldName) {
                $field=$form->Fields()->dataFieldByName($fieldName);
                if($field) {
                    $field->setName($field->getName().'_safe');
                    $field->setValue($this->sanitizeHTML($field->Value()));
                }
            }
        }
    }