Clicking on a date in Vue.js Fullcalendar

My goal is to retrieve a date value from the onDateClick function of fullCalendar using vue.js and then pass this data to a prop that can be stored in my backend via Laravel. However, I am encountering various undefined errors no matter how I approach the problem. Although I am able to trigger the modal popup successfully, I struggle to obtain a visible return value. I have experimented with multiple approaches but nothing seems to be effective so far. Below is some sample code that illustrates my attempts:

import { Table, TableColumn, Select, Option } from 'element-ui';
import FullCalendar from '@fullcalendar/vue';
import dayGridPlugin from '@fullcalendar/daygrid';
import Modal from '@/components/Modal'
import timeGridPlugin from '@fullcalendar/timegrid'
import interactionPlugin from '@fullcalendar/interaction'
import BaseInput from '@/components/Inputs/BaseInput'
import flatPicker from 'vue-flatpickr-component';
import 'flatpickr/dist/flatpickr.css';
import DropzoneFileUpload from '@/components/Inputs/DropzoneFileUpload';

const today = new Date();
const y = today.getFullYear();
const m = today.getMonth();
const d = today.getDate();
export default {
  name: 'CalendarForm',
  components: {
    FullCalendar,
    Modal,
    BaseInput,
    flatPicker,
    DropzoneFileUpload,
    [TableColumn.name]: TableColumn,
    [Table.name]: Table,
  },
  data(){
    let yearAndMonth = `${y}-${m + 1}`
    return {
      calendarPlugins: [dayGridPlugin, timeGridPlugin, interactionPlugin],
      formData: new FormData(),
      tableData: [],
      deleteNotice: false,
      deleteId: false,
      canAdd: false,
      canDelete: false,
      events: {
        type: 'POST',
        url: 'calendar/show',
        failure: function(response) {
          console.log(response);
        },
      },
      header: {
        left: 'title',
        center: false,
        right: 'prev, next today',
      },
      showAddModal: false,
      showEditModal: false,
        model: {
          name: null,
          className: 'bg-default',
          description: null,
          start: '',
          end: '',
          files: [],
        },
        eventColors: ['bg-info', 'bg-orange', 'bg-red', 'bg-green', 'bg-default', 'bg-blue', 'bg-purple', 'bg-yellow']
    };
  },
  methods: {
      created() {
         this.init();
      },
      init() {
        window.axios.post('calendar/show')
        .then((response) => {
          this.tableData = response.data.events.data;
          this.canAdd = response.data.can_add;
          this.canDelete = response.data.can_delete;
        });
      },
      calendarApi() {
        return this.$refs.fullCalendar.getApi()
      },
      changeView(viewType) {
        this.defaultView = viewType
        this.calendarApi().changeView(viewType)
      },
      next() {
        this.calendarApi().next()
      },
      prev() {
        this.calendarApi().prev()
      },
      onDateClick({ date }) {
        this.showAddModal = true
        this.model.start = date
        this.model.end = date
      },
      save() {
      this.formData.append('name', this.model.name);
      this.formData.append('date', this.onDateClick(date));
      this.formData.append('description', this.model.description);
      for (var i = 0; i < this.model.files.length; i++) {
        const file = this.model.files[i];
        this.formData.append('files[' + i + ']', file);
      }

      window.axios.post(window.location.origin + '/calendar/store',
        this.formData,
        {
          headers: {
            'Content-Type': 'multipart/form-data',
          },
        })
        .then((response) => {
          this.init();
        }).catch((err) => {
          console.log(err);
        });
    },
    previewFiles(val) {
      this.model.files.push(val);
    },
    confirmDelete(id) {
      this.deleteNotice = true;
      this.deleteId = id;
    },
    handleDelete() {
      window.axios.post('calendar/destroy', { id: this.deleteId })
        .then((response) => {
          this.deleteNotice = false;
          this.deleteId = false;
          this.init();
        });
    },
    },
};
</script>

Answer №1

It appears that your onDateClick function is correctly implemented, and saving the date returned by Full Calendar into this.model should be functioning as expected (consider adding a console.log at this point to double-check the date). The date you receive should be in plain JavaScript Date format, which is not yet formatted.

In order to properly handle the date in your save() method, you will need to convert it to a format that aligns with what your Laravel backend expects, most likely 'YYYY-MM-DD HH:mm'. For this task, you can utilize moment.js as recommended by @renato, or alternatively perform the formatting on your own.


Additionally, as the creator of Vue Cal, I suggest exploring a Vue.js full calendar solution with no external dependencies.

You may find this option more suitable for your Vue project, offering a user-friendly experience. Unlike a mere Vue wrapper, Vue Cal is a standalone Vue.js library.

Answer №2

moment("your chosen date").format('YYYY-MM-DD') 

If you need to customize the output date format, this is the code snippet for you.

Remember to utilize moment.js library for this functionality.

Check out moment.js documentation here.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Determine selected option in Radio Button

FORM : <form id="approvalPenambahanUserInt" name="approvalPenambahanUserInt" action="" method="post"> <div class="form-group"> <div class="col-sm-12"> <label for= ...

What is the procedure for updating or adding data to a JSON file with angularJS?

After successfully creating a local JSON file and retrieving data from it using app.controller('appCtrl', function($scope, $http){ $http.get('employees.json').success(function(data){ $scope.employees=angular.fromJson(data.employee ...

The type '{}' cannot be assigned to type 'IntrinsicAttributes & FieldsProp'. This error message is unclear and difficult to understand

"The error message "Type '{}' is not assignable to type 'IntrinsicAttributes & FieldsProp'.ts(2322)" is difficult to understand. When I encountered this typeerror" import { useState } from "react"; import { Card } fr ...

"Displaying events on fullcalendar using data retrieved from a PHP server with a

After creating my first RESTful PHP server, specially designed for responding to fullcalendar events callback, I encountered a strange issue. Even though the output from my server matches the string produced by the json-events.php file in the fullcalendar ...

Navigating views with ReactJS using ES5

I have been searching for ReactJs guides, but most of them are based in ES5. As a result, I have begun using ReactJS in this manner. Now that I understand how to create all my components, I am ready to build a small single-page-application. However, I am s ...

Trouble with displaying days on the Datepicker

I'm currently facing an issue with my datepicker. I have a specific set of days that should be highlighted on the calendar, and it needs to be constantly updated. For example, past days are removed from the calendar automatically to keep it current. H ...

Updating the background image without having to validate the cache

I have implemented a basic image slideshow on my website using a simple Javascript function. The function runs every 5 seconds to update the CSS "background-image" property of a div element. While it is functional, I've noticed that each time the func ...

Envelop a HTML element within another HTML element with the help of jQuery

Unique link Here is some sample HTML: <div><img src="http://i.imgur.com/4pB78ee.png"/></div> I am looking to use jQuery to wrap the img tag with an a tag, like this: $(function() { var a = '<a href="http://i.imgur.com/4pB78e ...

Unveiling the mysteries of JSONP in conjunction with AJAX

JSONP allows for bypassing the same origin policy in JavaScript by using <script> tags to load third party data. However, I am uncertain about how JSONP is utilized together with AJAX. My assumption is that: When an AJAX call is initiated, a <sc ...

Testing the scope of an Angular directive

Encountering an issue with the unit test In my code, I have: describe('test controller', function () { var =$compile, scope, rootScope; beforeEach(module('myApp')); beforeEach(inject(function (_$compile_, _$rootScope_) { ...

Using React js to transform objects into arrays for useState

Hey there! I'm currently working on a webshop demo project for my portfolio. I've encountered an issue while trying to fetch data from commerce.js. The data is in the form of objects, which are causing problems when I try to map them. I've a ...

Notification prompt when removing items

I currently have a table set up with a delete <a> tag that allows users to delete data. I would like to add a confirmation message asking the user if they are sure they want to delete before proceeding. I attempted to achieve this using JavaScript bu ...

Add a file to your Google Drive by utilizing AJAX with Google Apps Script

Currently, I am working on a code to upload an image file to Google Drive using app script. I have encountered an issue where I am unable to retrieve the file from the request.parameters. I attempted to use formData as well, but it did not resolve the pro ...

Manipulate text within a text area using jQuery

Good afternoon. How can I use JavaScript to update the text in a textarea input? I currently have some content in my textarea that includes a PublisherImprintName tag, and I want to remove it using jQuery. <PublisherInfo> <PublisherName>A ...

Exploring the power of asynchronous Mongoose queries using the async await

I have a system where authenticated users can create new user accounts and assign them to specific groups. The middleware flow for this process is outlined in the following route: router.post('/account/add-users', userController.validateRegist ...

Getting the response data from an XMLHttpRequest - Full guide with screenshots

Currently, I am working with autocomplete jQueryUI and have this code snippet: .autocomplete({ source: function( request, response ) { var results = $.getJSON( url, { term: extractLast( request.term ) }, response ); console.log(results); ...

Passing the AngularJS ng-model from a template to a directive's controller

I have created a directive with a controller that is responsible for building a form to post comments to an API through CommentsService Here is a snippet of how my directive looks: app.directive('appComments', function( CommentService ) { r ...

Create an HTML and CSS code that allows you to split paragraph text into columns within a

I am seeking a way to create dynamic paragraph column text using only the Here is an example of how it could be displayed in HTML: <div> <p> Sed ut perspiciatis, unde omnis iste natus error sit voluptatem accusantium doloremque laudantiu ...

Incorporate different courses tailored to the specific job role

https://i.stack.imgur.com/iGwxB.jpg I am interested in dynamically applying different classes to elements based on their position within a list. To elaborate: I have a list containing six elements, and the third element in this list is assigned the class ...

Retrieving Distinct Values in CouchDB

In my database, there are documents that represent different rooms. Each room has properties like "floor" and "hotel", among others. What I need to do is fetch all the floors associated with a specific hotel from the database. Something like getAllFloorsOn ...