Skip to content

Add method to disable event #16

@wize-wiz

Description

@wize-wiz

Like in #9, I too was searching for a solution to disable the event when editing a resource.

E.g. I have a news resource where the title generates a slug, but on edit this slug should not be changed. Now I could simply do an if/else if the request is an update or not, and just replace the Slug field with a disabled text field, but easier would be if I could just add a method like disableEvents($disable = true) with a default set to true.

I don't know what you (@drobee) think about this idea, but I did a quick edit and came with this solution.

src/Slug.php

// constructor
public function __construct(...) {
  ...   
  $this->disableEvents(false); // default to false
  ...
}

// method
public function disableEvents(bool $disable = true) {
  // I choose `meta` because somehow setOptions() sets a boolean to string "1" instead of `true`.
  return $this->withMeta(['disableEvents' => $disable]);
}

resources/js/components/Slug/FormField.vue

Changed the mounted method for a return if event should not be used.

    mounted() {
        // return if event should be disabled
        if(this.field.disableEvents) {
            return;
        }
        const eventType = this.field.options.event || 'keyup';
        Nova.$on('field-update-' + eventType + '-' + this.field.name, ({value}) => {
          this.generateSlug(value);
    },

I could make PR if you agree.


Another thing, I also added a delay for the generate slug request.

src/Slug.php

// added eventDelay to default options
protected $options = [
    'event' => 'keyup',
    'eventDelay' => 200
];

// method
public function eventDelay(int $delay) {
  return $this->setOption('eventDelay', $delay);
}

Mounted function with delay

// return if event disabled
if(this.field.disableEvents) {
    return;
}
this.eventDelayTimeout = null;
const eventType = this.field.options.event || 'keyup';
Nova.$on('field-update-' + eventType + '-' + this.field.name, ({value}) => {
    // clear timeout if any
    if(this.eventDelayTimeout !== null) { clearTimeout(this.eventDelayTimeout); }
    // delay generation of slug
    this.eventDelayTimeout = setTimeout((function() {
        this.generateSlug(value)
    }).bind(this), this.options.eventDelay);
})

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions