View specific mode in FullCalendar - fullcalendar

I'm trying to call a specific FullCalendar view, not necessarily my default view, through a URL.
Something like /my_calendar/?&mode=month.
I searched the documentation and couldn't easily find anything that points to this.
I found this though where they claim this is implemented in Drupal somehow. Not sure how to backport (if easily possible?).
Any idea on how to achieve this?

So on your calendar page, before your fullcalendar configuration you will need to add the following code. This will check if $_GET['mode'] is set in the url and if it is, it will use a switch to make sure it is a valid value and then assign the JavaScript variable to that value and echo it to the page and if it is not set or if the value does not match it will assign the default value of month.
<script>
<?php
if(isset($_GET['mode'])) {
switch ($_GET['mode']) {
case "month":
echo "var mode = 'month';";
break;
case "agendaWeek":
echo "var mode = 'agendaWeek';";
break;
default:
echo "var mode = 'month';";
break;
}
} else {
echo "var mode = 'month';";
}
?>
</script>
Then in your fullcalendar configuration you just need to set the following.
defaultView: mode,
Note: your IDE may say that mode is not defined if your fullcalendar configuration and fullcalendar page are separate. Thats fine as long as its defined on the calendar page before the script. With this code, a page like calendar.php?mode=agendaWeek will load the calendar with default view set to agendaWeek.

Related

Make flatpickr input required

I'm using the amazing flatpickr on a project and need the calendar date to be mandatory.
I'm trying to have all the validation in native HTML, so I was naively trying with just adding the required attribute to the input tag, but that doesn't appear to be working.
Is there a way of natively making a date mandatory with flatpickr or do I need to write some custom checks?
You can easily achieve this by:
Passing allowInput:true in flatpickr config.
As example:
flatpickrConfig = {
allowInput: true, // prevent "readonly" prop
};
From the documentation:
Allows the user to enter a date directly into the input field. By
default, direct entry is disabled.
The downside of this solution is that you should enable the direct entry (but ideally form validation should occur whether or not direct entry is enabled).
But if you don't want to enable the direct entry to solve this problem, you can use the code below as a workaround:
flatpickrConfig = {
allowInput:true,
onOpen: function(selectedDates, dateStr, instance) {
$(instance.altInput).prop('readonly', true);
},
onClose: function(selectedDates, dateStr, instance) {
$(instance.altInput).prop('readonly', false);
$(instance.altInput).blur();
}
};
This code remove the readonly property when it is not in focus so that html validation can occur and add back the readonly prop when it is in focus to prevent manual input. More details about it here.
This is what I came up with to make as complete of a solution as possible. It prevents form submission (when no date selected and input is required), ensures browser native "field required" message pops up and prevents the user typing in the value directly.
flatpickrConfig = {
allowInput: true, // prevent "readonly" prop
onReady: function(selectedDates, dateStr, instance) {
let el = instance.element;
function preventInput(event) {
event.preventDefault();
return false;
};
el.onkeypress = el.onkeydown = el.onkeyup = preventInput; // disable key events
el.onpaste = preventInput; // disable pasting using mouse context menu
el.style.caretColor = 'transparent'; // hide blinking cursor
el.style.cursor = 'pointer'; // override cursor hover type text
el.style.color = '#585858'; // prevent text color change on focus
el.style.backgroundColor = '#f7f7f7'; // prevent bg color change on focus
},
};
There is one disadvantage to this: Keyboard shortcuts are disabled when the flatpickr is open (when the input has focus). This includes F5, Ctrl + r, Ctrl + v, etc. but excludes Ctrl + w in Chromium 88 on Linux for some reason. I developed this using a rather old flatpickr version 3.1.5, but I think it should work on more recent ones too.
In case you want to use altFormat (display one date format to user, send other date format to server), which also implies setting altInput: true, you have to also change the onReady function to use instance.altInput instead of instance.element.
The onReady event listener can probably be attached to the instance after initializing it. However, my intention of using flatpickr with vue-flatpickr-component where you cannot elegantly access the individual flatpickr instances, made me use the config field instead.
I haven't tested it on mobile devices.
After digging a bit into the GitHub repo, I found a closed issue that points out that the issue will not be addressed.
In the same Issue page there is a workaround that seems to do the trick:
$('.flatpickr-input:visible').on('focus', function () {
$(this).blur()
})
$('.flatpickr-input:visible').prop('readonly', false)
copy attr name from prior input type hidden to rendered flatpickr input
just do this
$('[name=date_open]').next('input').attr("name","date_open");
$('[name=date_close]').next('input').attr("name","date_close");
Have been working on this for a couple of days now, finally getting the result I was after.
NOTE: I am using flatpickr with jQuery validation
As you would know flatpickr uses an alternative field for the date input, the actual field where the date is stored is hidden, and this is the key.
jQuery validation has a set of defaults, and by default hidden fields are not subject to validation, which normally makes perfect sense. So we just have to turn on the validation of hidden fields to make this work.
$.validator.setDefaults({
ignore: []
});
So my validator rules are then fairly normal:
var valid = {
rules: { dateyearlevel: {required: true} },
messages: { dateyearlevel: {required: "The date is required"} }
};
$("#myform").validate(valid);
That should allow you to ensure the date is required.
In my situation I wanted my date to only be required is a checkbox was checked. To do this we changed the rule above:
var valid = {
rules: { dateyearlevel: {
required: function() { return $("#mycheckbox").is(":checked") }
} },
messages: { dateyearlevel: {required: "The date is required"} }
};
$("#myform").validate(valid);
In case this helps someone, I'm using parsley.js for frontend validation and it works good with flatpickr
enter image description here
Just to expand a bit more on this, I found the ignore value set as an empty array did the trick for me also. You can just add this to your validate call back. Also displaying was a bit of an issue so I updated the errorPlacement to allow for flatpickr inputs like so.
$('#my-form').validate({
errorPlacement: function (error, element) {
if (element.hasClass('js-flatpickr') && element.next('.js-flatpickr').length) {
error.insertAfter(element.next('.js-flatpickr'));
} else if (element.parent('.input-group').length) {
error.insertAfter(element.parent());
} else {
error.insertAfter(element);
}
},
ignore: [],
rules: {
'startdate': { required: true }
},
messages: {
'startdate': {required: "Start Date is required"}
},
submitHandler: function(form) {
// ajax form post
}
});
in my case vue ( dunno why ) , i would like to comment for comment by #mik13ST
fyi: the default allowInput i think is true, no need to define, i didnt set the properties and my flat-pickr also work on testing.
i use
// this work in flat-pickr || #code_01
<small class="text-danger">
{{ validationContext.errors[0] }}
</small>
instead of
// work for all element except <flat-pickr #code_02 , dunno why not work
<b-form-invalid-feedback>
{{ validationContext.errors[0] }}
</b-form-invalid-feedback>
full code
<validation-provider
#default="validationContext"
name="Waktu Selesai Berkegiatan *"
vid="Waktu Selesai Berkegiatan *"
rules="required"
>
<flat-pickr
id="Waktu Selesai Berkegiatan *"
v-model="item.pip_time_end_rl"
placeholder="Waktu Selesai Berkegiatan *"
class="form-control"
static="true"
:config="dpconfig"
:state="getValidationState(validationContext)"
/>
// put here the message of error ( required ) #code_01 instead of #code_02
</validation-provider>
if younot use composite,
just use
#default="{ errors }" // in validation provider
:state="errors.length > 0 ? false : null" // in element for example flat-pickr
{{ errors[0] }} // to print out the message

Excluding bootstrap from specific routes in Meteor

I was hoping anyone could give some input on this,
I'm creating a meteor app in which I would like to use bootstrap to creating the admin environment, but have the visitor facing side using custom css. When I add the bootstrap package to my app using meteor it's available on every page, is there a way to restrict the loading of bootstrap to routes that are in '/admin' ?
When you add bootstrap package it's not possible. You can, however, add bootstrap csses to public directory and then load them in a header subtemplate that will only be rendered when you're in the dashboard.
EDIT
But then how would you go about creating seperate head templates?
Easy:
<head>
...
{{> adminHeader}}
...
</head>
<template name="adminHeader">
{{#if adminPage}}
... // Put links to bootstrap here
{{/if}}
</template>
Template.adminHeader.adminPage = function() {
return Session.get('adminPage');
}
Meteor.router.add({
'/admin': function() {
Session.set('adminPage', true);
...
}
});
DISCLAIMER: I am unsure of a 'meteor way' to do this, so here is how I would do it with plain JS.
jQuery
$("link[href='bootstrap.css']").remove();
JS - Credit to javascriptkit
function removejscssfile(filename, filetype){
var targetelement=(filetype=="js")? "script" : (filetype=="css")? "link" : "none" //determine element type to create nodelist from
var targetattr=(filetype=="js")? "src" : (filetype=="css")? "href" : "none" //determine corresponding attribute to test for
var allsuspects=document.getElementsByTagName(targetelement)
for (var i=allsuspects.length; i>=0; i--){ //search backwards within nodelist for matching elements to remove
if (allsuspects[i] && allsuspects[i].getAttribute(targetattr)!=null && allsuspects[i].getAttribute(targetattr).indexOf(filename)!=-1)
allsuspects[i].parentNode.removeChild(allsuspects[i]) //remove element by calling parentNode.removeChild()
}
}
removejscssfile("bootstrap.css", "css")
However, doing that would complete remove it from the page. I am not sure whether meteor would then try to readd it when a user goes to another page. If that does not automatically get readded, then you have an issue of bootstrap not being included when someone goes from the admin section to the main site, which would break the look of the site.
The way I would get around that would be to disable and enable the stylesheets:
Meteor.autorun(function(){
if(Session.get('nobootstrap')){
$("link[href='bootstrap.css']").disabled = true;
}else{
$("link[href='bootstrap.css']").disabled = false;
}
});
There my be other bootstrap resources which may need to be removed, take a look at what your page is loading.
To use jQuery in the same way but for the javascript files, remember to change link to script and href to src
From my tests, Meteor does not automatically re-add the files once they have been removed so you would need to find some way of re-adding them dynamically if you want the same user to be able to go back and forth between the main site and the admin site. Or simply if the http referrer to the main site is from the admin, force reload the page and then the bootstrap resources will load and everything will look pretty.
P.s. make sure you get the href correct for the jQuery version
If somebody is interested in including any js/css files, I've written a helper for it:
if (Meteor.isClient) {
// dynamic js / css include helper from public folder
Handlebars.registerHelper("INCLUDE_FILES", function(files) {
if (files != undefined) {
var array = files.split(',');
array.forEach(function(entity){
var regex = /(?:\.([^.]+))?$/;
var extension = regex.exec(entity)[1];
if(extension == "js"){
$('head').append('<script src="' + entity + '" data-dynamicJsCss type="text/javascript" ></script>');
} else if (extension == "css"){
$('head').append('<link href="' + entity + '" data-dynamicJsCss type="text/css" rel="stylesheet" />');
};
});
}
});
Router.onStop(function(){
$("[data-dynamicJsCss]").remove();
});
}
Then simply use:
{{INCLUDE_FILES '/css/html5reset.css, /js/test.js'}}
in any of your loaded templates :)

Custom Controls and Web Resources (scripts)

I am developing a Server Custom Control (.NET), a "DatePicker" with the jQueryUI Plugin.
So, i have the next script, that is loaded as a webResource:
JavaScript
$(function () {
$("#" + ctrlInput).datepicker({
maxDate: MaxDate,
minDate: MinDate
});
});
As you can see, i have javascript variables, so, for loading the script and the variables, i do the next:
C#
string javascriptVariables = String.Format(
"var MinDate = '{0}'; var MaxDate = '{1}'; var ctrlInput = '{2}';",
MinDate ?? DateTime.MinValue.ToShortDateString(),
MaxDate ?? DateTime.MaxValue.ToShortDateString(),
_textBox.ClientID
);
// Load javascript variables (it will be load every time i add a control)
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "dateValues" + _textBox.ClientID, javascriptVariables, true);
// Load jQueryPlugin (it is loaded only once, and this is the problem)
Page.ClientScript.RegisterClientScriptResource(this.GetType(), "[[resourceName]]");
It works fine. The problem is when i add this control to a page more than once.
And it is because the script variables are loaded fine, but the RegisterClientScriptResource doesn't load the jQuery Plugin again! And i don't know how i can force the load! Because i can't set the resource key to the RegisterClientScriptResource
Does anybody know how to solve this?
Thanks
I don't think you're taking the problem the right way.
Using global variables (in js) especially when they're actually only used locally is a very bad idea. source
Loading jQuery or a jQuery plugin more than once can also be a source of bugs. source
What i would do is to think of another way of passing variables to your javascript, something like data attributes.
You're probably having an html input generated with from server control, add data attributes for your dates :
<input type="text" ... data-mindate="01/01/2013" data-maxdate="12/31/2013" />
Next step is, instead of feeding the global variables to the datepicker function, use the data attributes :
$('#whatever').data('mindate');
or
$('#whatever').attr('data-mindate');
And a fast demo : http://jsfiddle.net/JjemN/

Can I enable users on Plone4 to show/hide the Portlet column on-the-fly

The Portlets in Plone are quite handy but I'd like to be able to provide some method to users to be able to temporarily hide/show the portlets column. That is, by clicking a button, the portlets column should collapse and you see the content page in full width. Then clicking again and the portlets panel on the left expands and the main content page width shrinks to accommodate.
I've observed the HTML ID of the portlets column is "portal-column-one" and I tried adding a button to the page that runs javascript to set the visibility property of that element to "hidden" but this seemed to have no effect. I was able to go into Firebug and add style="visibility:hidden;" to the "portal-column-one" element and it had the effect of making the region invisible w/o resizing the page.
I am using Plone 4.1. I have the site configured with navigation portlet on all pages except the main page which has Navigation, Review List and Recent Changes.
So it seems it must be possible to embed some javascript in the page (I was thinking of adding this to the plone.logo page which I've already customized). But I guess its more complicated than the few stabs I've made at it.
Thanks in advance for any advice.
Solution (Thanks to input from Ulrich Schwarz and hvelarde):
The solution I arrived at uses JavaScript to set CSS attributes to show/hide the Portlets Column (Left side) and expand the content column to fill the space the porlets column filled.
I started by customizing the Plone header template to add a link for the user to toggle the view of the Porlets column. I also put the necessary javascript functions in this header.
To customize the header, go to the following page (need to be logged in as Admin of your Plone site):
http://SERVER/SITE/portal_view_customizations/zope.interface.interface-plone.logo
Where:
SERVER is the address and port of your site (e.g. localhost:8080)
SITE is the short name of your Plone Site
To create this page:
Go to Site Setup (as Admin)
Go to Zope Management Interface
Click on "portal_view_customizations"
Click on "plone.logo" (or at least this is where I choose to put the button so it would be located just above the navigation Portlet)
Add the following to the page:
<script>
function getById(id) {
return document.getElementById(id);
}
function TogglePortletsPanel() {
var dispVal = getById('portal-column-one').style.display
if( dispVal == "none") { // Normal display
SetPortletsPanelState("inline");
} else { // Full Screen Content
SetPortletsPanelState("none");
}
}
function SetPortletsPanelState(dispVal) {
var nav = getById('portal-column-one');
var content = getById('portal-column-content');
if( dispVal == "none") { // Normal display
nav.style.display='none';
content.className='cell width-full position-0';
// Set cookie to updated value
setCookie("portletDisplayState","none",365);
} else { // Full Screen Content
nav.style.display='inline';
content.className='cell width-3:4 position-1:4';
// Set cookie to updated value
setCookie("portletDisplayState","inline",365);
}
}
function InitializePortletsPanelState() {
var portletDisplayState=getCookie("portletDisplayState");
//alert("portletDisplayState="+portletDisplayState)
if (portletDisplayState!=null) SetPortletsPanelState(portletDisplayState);
}
function setCookie(c_name,value,exdays) {
//alert(c_name+"="+value);
// cookie format: document.cookie = 'name=value; expires=Thu, 2 Aug 2001 20:47:11 UTC; path=/'
var exdate=new Date();
exdate.setDate(exdate.getDate() + exdays);
var exp= ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
document.cookie=c_name + "=" + escape(value) + exp + "; path=/";
}
function getCookie(c_name) {
var i,x,y,ARRcookies=document.cookie.split(";");
for (i=0;i<ARRcookies.length;i++) {
x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
x=x.replace(/^\s+|\s+$/g,"");
if (x==c_name) return unescape(y);
}
}
function addLoadEvent(func) {
var oldonload = window.onload;
if (typeof window.onload != 'function') {
window.onload = func;
} else {
window.onload = function() {
if (oldonload) {oldonload(); }
func();
}
}
}
addLoadEvent(InitializePortletsPanelState);
</script>
<a style="font-size:50%;" href="javascript:TogglePortletsPanel();">Toggle Portlets Panel</a>
6. Save the page
Notes:
I got the names of the plone div elements using Firebug.
I also used Firebug to experiment with different settings to speed up prototyping. For example, editing the HTML inline to verify settings do as expected.
There is a slight but of delay until the Left Portlet panel is hidden. This is only obvious on Safari for me (which is probably due to how fast it is) but not on Firefox or IE.
Maybe it's just a matter of setting the right property: you want display:none, not visibility:hidden.
But even then, the content area will probably not reflow automatically, you'll need to (dynamically) change the class on it as well.
Specifically, you'll need to put classes width-full and position-0 on portal-column-content, instead of width-1:2 and position-1:4.
This must be achieved client side by javascript (jquery).
You must first read documentation about the css grid framework used by plone: deco.gs. The website is down so, git clone this repo: https://github.com/limi/deco.gs and open pages in a webbrowser
Note: you just have to change css classes on the containers.
Try adi.fullscreen, it respects Plone's css-structure as Ulrich Schwarz thoughtfully mentioned.

Image load timeout in Internet Explorer

I have a page for an internal app that displays document images streamed from a document storage system using a web service. The problem I am having is that when a user does their search they may get hundreds of hits, which I have to display on one large page so they can print them all. This works fine in Firefox, but in IE it stops loading the images after a while so I get a hundred or so displayed and the rest just have the broken image symbol. Is there a setting somewhere that I can change this timeout?
If the issue is indeed a timeout, you might be able to work around it by using a "lazy load" script and adding new images to the document only after existing images have loaded.
There are a lot of ways to do this, but here's a simple example I threw together and tested. Instead of this:
<img src="image001.jpg" />
<img src="image002.jpg" />
<img src="image003.jpg" />
<img src="image004.jpg" />
<!-- Etc etc etc -->
You could do this:
<div id="imgsGoHere">
</div>
<script type="text/javascript">
function crossBrowserEventAttach(objectRef, eventName, functionRef)
{
try {
objectRef.addEventListener(eventName, functionRef, false);
}
catch(err) {
try {
objectRef.attachEvent("on" + eventName, functionRef);
}
catch(err2) {
// event attachment failed
}
}
}
function addImageToPage()
{
var newImageElement = document.createElement("img");
newImageElement.src = imageArray[nextImageNumber];
var targetElement = document.getElementById("imgsGoHere");
targetElement.appendChild(newImageElement);
nextImageNumber++;
if (nextImageNumber < imageArray.length) {
crossBrowserEventAttach(newImageElement, "load", addImageToPage);
crossBrowserEventAttach(newImageElement, "error", addImageToPage);
}
}
var nextImageNumber = 0;
var imageArray = new Array();
imageArray[imageArray.length] = "image001.jpg";
imageArray[imageArray.length] = "image002.jpg";
imageArray[imageArray.length] = "image003.jpg";
// .
// .
// .
// Snip hundreds of rows
// .
// .
// .
imageArray[imageArray.length] = "image999.jpg";
addImageToPage();
</script>
Each image is added to the page only after the previous image loads (or fails to load). If your browser is timing out, I think that will fix it.
Of course, the problem might actually not be a timeout, but rather that you're running out of memory/system resources and IE is giving up. Or there might be an IE DOM limitation like Sra said.
No final solution, but some hints...
I think the ie Dom hangs up. I,ve seen this in other cases. I needed simply to show the images and used a js which loads the image the time they came into focus, but that want work if you directly hit print I think. Can you use the new css ability to store imagedata directly instead of links. That should solve your problem. I am not quite sure but I think it is supported since ie 7
My guess is that you have to work around the IE setting, the easiest way to do it is simply not showing images that are not loaded or replacing them with a default image:
your html:
<img src="http://domain.com/image.jpg" />
your js:
$('img').load(function(){
// ... loaded
}).error(function(){
// ... not loaded, replace
$(this).attr('src','/whatever/default.jpg');
// ... not loaded, hide
$(this).hide();
});
That is a problem with microsoft. Unfortunately, this is a setting that would have to be changed on every single computer, as there is no remote way to alter it. To change it on your computer, try opening regedit and adding the RecieveTimeout DWORD with a Value of (#of minutes)*6000. Hope this helps-CodeKid1001
Edit: Sorry about that, I forgot to put in the file path:
HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\InternetSettings
I used something similar to laod HD pictures as a background using ASP Pages
But i used jQuery to handle the images and its loading. This is a sample for 1 image but with a bit of tweaking you can load dynamically
myImage = new Image();
$(myImage).load(function ()
{
$(this).hide(); //Stops the loading effect of large images. can be removed
$('.csBackground li').append(this); //Append image to where you need it
$(myImage).show();
}).attr('src', settings.images[0]) //I pass an array from ASP code behind so 0 can be 'i'
.error( function { checkImages(); } ) //try and relaod the image or something?
So instead of changing the timeout- just try and reload the images on error.
Otherwise i only found a solution that is client specific (HTTP Timeout)
http://support.microsoft.com/kb/813827

Resources