Phoenix Datepicker to only show available dates - datepicker

I am working on a simple booking system using the Phoenix framework. At the moment, I have a route for new bookings, displaying a date picker which takes the values from a "booking" model with the following attributes:
:time, Ecto.DateTime
:description, :string
belongs_to :user, Test.User
When I head to "bookings/new", my form is correctly displayed and I can pick whatever date I want. However, I am now trying to figure out how to remove unavailable dates from the picker.
As far as I can see, the form is taking the values from ecto's DateTime primitive type, however coming from an OOP background I cannot figure out what resource I need to update in order to remove unavailable dates. Do I have to create a custom type?
Thanks in advance

I am quite late to respond to this but I hope it will be able to help someone; you can use the builder option when using the date_select on forms.
<%= date_select f, :time, builder: fn b -> %>
<%= b.(:day, prompt: "Date") %> /
<%= b.(:month, prompt: "Month") %> /
<%= b.(:year, prompt: "Year") %>
<% end %>
That's how you can customize it if you need just the day, month and year. You can do the same with time too.

You can't block arbitrary dates in the default DateTime picker. You can restrict the range (e.g. limit the years to 1234 to 1243 or months to January to June), but since they're independent <select> inputs, you can't hide specific combinations. Two ways to solve this that I can think of are:
Do the validation on the server. You can use AJAX to do the validation as soon as the user selects, without a page refresh, if you want.
Use JavaScript to restrict the range, either blocking selecting a taken date using custom JS, or use an existing, full fledged DatePicker / Calendar library.

Related

Automatically set date in the front matter of a Jekyll page

When I create a post, in the front matter I have to insert layout, title, date etc. My concern is regarding date front matter. It is very inconvenient to insert date time and time offset in date field manually.
I'm not able to figure out how to do this automatically. I want the front matter date to update automatically with system time.
The date variable in front matter is an optional variable that you can set to be able to override the date that you set when you title your post according what Jekyll is looking for (i.e. 2019-12-14-post-title.md). It should only refer to the date the post was originally made, and not the current system date. Except for certain edge cases, you really shouldn't have to define date in the front matter.
You can use Liquid templating to post the current time to a page by passing the "now" keyword to date in your liquid template as follows:
This page was last updated at {{ "now" | date: "%Y-%m-%d %H:%M" }}.
to get the the output:
This page was last updated at 2019-12-14 17:48.
However this method has a big drawback for Jekyll usage, because it will refer to the current date when the page was last generated from the template and not when the page is being visited by the user.
The best way to access the current system time is likely to use javascript instead. This is fairly easy depending on your familiarity with the language, but essentially you can make a Date object and then output the info you are looking to display. Here is a quick snippet I made that shows a couple methods that act on the Date object to output different values such as the date, time, and year:
<!DOCTYPE html>
<html>
<body>
<h3>The toDateString() method converts a date to a date string:</h3>
<p id="demo1"></p>
<h3>The toLocaleTimeString() method outputs formatted time:</h3>
<p id="demo2"></p>
<h3>The getFullYear() method outputs the year:</h3>
<p id="demo3"></p>
<script>
// create date object
var d = new Date();
// use toDateString() to output formatted date
document.getElementById("demo1").innerHTML = d.toDateString();
// use toLocaleTimeString() to output formatted time
document.getElementById("demo2").innerHTML = d.toLocaleTimeString();
// use getFullYear() to output year
document.getElementById("demo3").innerHTML = d.getFullYear();
</script>
</body>
</html>
W3schools has a good rundown of the Date object and how to format output if you need more examples and reference on usage.
If you need to know how to use Javascript with Jekyll there is a helpful post on Jekyll Talk that will help.
First of all, you do not HAVE to insert 'layout, title, date etc'. You can use Front Matter defaults for them. This only makes sense for the layout as the title can or should be default, nor the date.
The date MUST be set in your filename and can be overridden in the Front Matter. Please note that this is ONLY true for the built-in collection posts. If you use a custom collection you do not need a date at all.
However, if you choose to use posts nevertheless and you want to add the date automatically, there is only one real option: Use a CMS that automates this input, like Forestry.io or CloudCannon.

Multiple form inputs for the same field

I have a Rails model called request_form. In the form I have multiple boxes that can be selected, similar to the "What can we craft for you section" in the following site http://mostlyserious.io/get-started/
I have a field called number_of_guests that can be a handful of values depending on which section is clicked. I plan on using javascript to grab the value of the clicked element and assigning it to the request_no_of_guest param. However, in the form I have that same field rendered 5 times to allow for each selection. What is the best way about this? Is there a better way to handle this? I thought about creating a controller method that loops through each instance of that request_no_of_guests param and determining which instance is populated and then sending that up.
Is this the best way to handle this case?
Well as you did not provide any useful detail I will answer as I understood the question.
Let’s have a quick look at what this might look like. To do so, we’ll imagine a demo app into which you can enter the name of a professor and select their various areas of expertise.
Professor has a field expertise which is String.
The form can be as follows:
<%= label_tag 'expertise_physics', 'Physics' %>
<%= check_box_tag 'professor[expertise][]', 'Physics', checked('Physics'), id: 'expertise_physics' %>
<%= label_tag 'expertise_maths', 'Maths' %>
<%= check_box_tag 'professor[expertise][]', 'Maths', checked('Maths'), id: 'expertise_maths' %>
alter app/controllers/professors_controller.rb
from
params.require(:professor).permit(:name, :expertise)
to
params.require(:professor).permit(:name, expertise:[])
Then in app/models/professor.rb
before_save do
self.expertise.gsub!(/[\[\]\"]/, "") if attribute_present?("expertise")
end
and in /app/helpers/professors_helper.rb
def checked(area)
#professor.expertise.nil? ? false : #professor.expertise.match(area)
end
This way you can grab the different values selected in the form into the expertise attribute, however this is not recommended if you are planning to query the selected options. The right way would be create a new model called Expertise and then create the relationship professor has_many expertises.
But if you are looking for something simple, then use the above code.

Adding DateTime attribute to SpineJS models

I am looking for the best way to handle Dates & Times on my SpineJS models. I am working on creating an event calendar of sorts. The first hurdle being to display a nice 6 week calendar. It must start on the last Sunday of the previous month, ending on the first Saturday of the next month.
I was using DateJs (http://www.datejs.com/) and handling some date things in the View template but wanted to move some of this to a model to cleanup said view.
The function I am working on is called 'firstDay'. This will find the date where we start our calendar (the last Sunday of the previous month)
firstDay: () ->
Date.today().set({month: #month}).moveToFirstDayOfMonth().moveToDayOfWeek(0, -1)
My attempted usage:
<% day = cal.firstDay %>
// initialize the table header, etc
<tbody>
<% while !day.equals(cal.lastDay): %>
// render each calendar tile/square
And here is the error:
Uncaught TypeError: Object function () {
return Date.today().set({
month: this.month
}).moveToFirstDayOfMonth().moveToDayOfWeek(0, -1);
} has no method 'equals'
So my Spine model appears to be unaware of DateJS... I guess that makes sense. It looks like the function itself is being returned, not the evaluation of the function... if that makes sense.
Any guidance here would be appreciated on the best way to incorporate dates and times into my models.
thanks
So my problem was quite simple... syntax. Being very new to coffescript and spinejs I guess I was looking at too many things at once and missed the obvious.
The proper way to call this function from a coffeescript/eco template is:
<% day = cal.firstDay() %>
I was missing the parenthesis on the function call. This mistake should be easy to recognize if I run across the error again in the future. In fact it should have been obvious in the first place... again, too many new things.

Grails - how to hide a date inside a form

I have an 'edit' view for a model that has several fields (one of which is a date). I only want a few of the fields visible to allow edits, so I just hide the other fields using <g:hiddenField>
But one of the fields is of type TimeStamp and I can't seem to find a way to hide this in the form. I tried
<g:form method="post" >
<g:textField name="firstName" value="${applicationUserInstance?.firstName}" />
<g:textField name="lastName" value="${applicationUserInstance?.lastName}" />
<g:datePicker name="createDate" style="visibility:hidden;" precision="day" value="${applicationUserInstance.createDate}" />
The date picker is still visible. Any idea how to hide the date so that I can just pass this to the update method upon submit of the form. Many thanks.
Just re-iterating Rob's comment here. No need to put that on the form. The only data you need on the form is the data you are updating and the ID of what is being updated. Everything else will just stay the same...
def update = {
def applicationUserInstance = User.get(param.id)
// at this point applicationUserInstance.createDate is
// correct.
applicationUserInstance.properties = params
// since no createDate was in the params, it doesn't change.
// so you're good
applicationUserInstance.save(flush:true)
}
Actually my answer below might not be the right answer to your question. Otherwise if you really just have a createdDate-field, which should keep track, when the entry was created in the database, I suggest you do it the Grails-way and use the reserved keywords 'dateCreated' and 'lastUpdated'
Check http://grails.org/doc/1.3.7/guide/5.%20Object%20Relational%20Mapping%20(GORM).html#5.5.1 Events and Auto Timestamping
on how to use these. If you use these then my answer below will be helpful to control the visibility of these fields 'dateCreated', 'lastUpdated'
Suggestions for 'dateCreated', 'lastUpdated'
Probably you want this timestamp to be created automatically as you found it in the Grails documentation but you do not want it to be visible in your view.
Now, to exclude this timestamp from being visible, first
grails install-templates
I assume you have grails-1.3.7
Go to src/templates/scaffolding and check your gsp-files, e.g. 'create' and 'edit'
Search for this line:
<% excludedProps = ["version", "id",
and edit for example 'dateCreated'
<% excludedProps = ["dateCreated", "version", "id",
There is also a tutorial on this topic http://www.ibm.com/developerworks/java/library/j-grails01209/index.html
Greetings,
Jan

Do you use <%: %> or <%= %> for html helpers in ASP.NET MVC 2.0?

I know they now have this in ASP.NET MVC 2.0 <%: Model.CustomerName %>
So when you make HTML helpers is it better to use this way now (provided that you do not want to do HTML encoding)?
Using <%: %> should be used whenever you display user entered/submitted data to make your web pages safer.
But sometimes it's just not viable to HTML encode everything. What if you do want to preserve some HTML formatting? In this case you will have to use the regular <%= %> statement. Let's think of an example where this is the case.
Real-life example
Let's say you have some web content where users can submit their comments. You would like to provide the ability to preserve some formatting (at least line breaks). In this case you will have to preserve <br/> elements when later displaying these comments. You have two choices:
Cleanup and format comments when you store them in the DB - in this case you would strip all HTML tags from submitted comments and then replace all new lines (\n) with <br/>. When you would like to display this comment you could then call <%= Comment %>
Cleanup and format comments when you display them - in this case you would most probably call this <%= Html.Encode(Comment).Replace("\n", "<br/>") %>
Which one is better/safer depends on each particular case, but cleaning up HTML tags is always a nice step to include in any of the two. Everything also depends on allowed formatting definition. Should those be entered as regular tags or something similar to markdown or something completely different depends on you and the code in the end will most certainly depend on it.
Second approach advantages/disadvantages
advantage
Let's say that you do provide some formatting capabilities but after about a year or so you decide to change formatting rules or something related to them (which is quite common). If you use the second approach the new rules will work with old comments as well, because they were stored as is, while the first approach will loose its significance with old data. One example would be if you'd auto-detect web links in these comments in the cleanup/formatting phase. Using the first approach all links in old comments would stay unclickable, but if you used the second one even older comments with links would format them as clickable.
disadvantage
Second approach uses much more processing than the first one, because every comment would have to be preprocessed each time it's displayed, while in the first approach they're processed only once when we store them in the DB. Depending on the formatting/cleanup complexity and quantity of comments on each page this may become significant.
If processing does become a problem you should think of an alternative to use first approach, but while cleaning up and re-formatting the comment you'd save both versions in your DB. Original submitted comments as well as processed ones. So when you do change formatting rules you can always reformat old comments because you stored originals.
Yes, you always want to use <%: Model.CustomerName %> from now on where you can. Only in very specific cases should you use <%= %> but try not to use it at all.
If you are creating your own html helpers that you don't want to be encoded, then just return a MvcHtmlString from them.
E.g. This is a extension method I created to display a tick icon if the passed in value is true.
public static MvcHtmlString MECross(this HtmlHelper html, string value, string text)
{
if (Convert.ToBoolean(value))
{
string spanTag = string.Format("<span class=\"replace icon-cross\" title=\"{0}\"><em></em>{1}</span>",
html.AttributeEncode(text),
html.Encode(text));
return MvcHtmlString.Create(spanTag);
}
return MvcHtmlString.Empty;
}
Note that I Encode and AttributeEncode anything that could be dangerous in my extension method and then return a MvcHtmlString.
HTHs,
Chares