how to format a date in embeddedjs - mongodb

app.js
app.get('/user.html', function(req, res){
dbConnect.collection("users").find().toArray(function(err, docsData) {
res.render('user', {
data: docsData,
title: "EJS example",
header: "Some users"
});
});
});
user.html
<% data.forEach(function(user){ %>
<tr>
<td>
<%= user.date %>
</td>
</tr>
<% }) %>
output is
2014-12-24T09:47:07.436Z
this is the value coming from mongodb. I want to format this to Dec-24-2014. How to format it in embeddedjs.

You can use toDateString() to better format date in JavaScript :
<% data.forEach(function(user){ %>
<tr>
<td>
<%= user.date.toDateString() %>
</td>
</tr>
<% }) %>
If you want to display date in a custom format, you can use third party module like Moment.js. Using Moment.js your code would be like following:
app.js
var moment = require('moment');
app.get('/user.html', function(req, res){
dbConnect.collection("users").find().toArray(function(err, docsData) {
res.render('user', {
data: docsData,
title: "EJS example",
header: "Some users",
moment: moment
});
});
});
user.html
<% data.forEach(function(user){ %>
<tr>
<td>
<%= moment(user.date).format( 'MMM-DD-YYYY') %>
</td>
</tr>
<% }) %>
Hope this help!

Related

rendering different data values inside an ejs 'Scriptlet' tag

I'm kind of new to ejs ,I have been working on this ejs project we're part of my code involves me having to create a for statement which will loop through data in an object "data1" which is nested together with "data2" as follows
Data 1: var data1 = <%='some data'%> and
Data 2: var data2 = <%='second data'%>.
The code :
<% for (var i in data2.data1) {%>
"some action"
<%}%>
Problem is data2 is not being rendered when you include in the ejs 'Scriptlet' tag <% %>
Full code :
<html>
<body>
<table id="customers">
<tr>
<th align="center">
<% var clss = d2.className %>
<% for (var i in data[0].classes.clss.Monday
) {%>
<% var object = data[0].classes.clss.Monday
%>
<% if (object.hasOwnProperty(i)) { %>
<th><%- object[i][0] %></th>
<%}%>
<%}%>
</th>
</tr>
</body>
</html>

Can you the coccon gem without a direct nested association?

I have to convert my form to not using nested association. In other words, instead of
<%= link_to_add_association f, :contacts, class: 'btn btn-primary', partial: 'projects/contact_fields', data: {
association_insertion_node: '.contact_fields', association_insertion_method: :append
} do %>
<i class="fas fa-plus"></i>
<% end %>
<%= f.fields_for :contacts do |contact| %>
<%= render 'projects/contact_fields', f: contact %>
<% end %>
I would like to be able to just pass in a string to be used as the container (similar to how you can with field_for).
<%= link_to_add_association 'contacts[]', 'projects/contact_fields', class: 'btn btn-primary', partial: 'projects/contact_fields', data: {
association_insertion_node: '.contact_fields', association_insertion_method: :append
} do %>
<i class="fas fa-plus"></i>
<% end %>
<% #contacts.each_with_index do |contact, index| %>
<%= fields_for "contacts[#{index}]", contact do |c| %>
<%= render 'projects/contact_fields', f: c %>
<% end %>
<% end %>
Cocoon is currently unable to edit/manage a collection. Cocoon is just helping the form-behaviour for nested-children functionality in rails, so there is no simple solution to edit an array or collection. On the other hand, this is in general pretty simple to implement without cocoon.
Very high level, do something like:
#contacts.each do |contact|
= render `contacts/edit`, contact: contact
= render `contacts/new`
so render the edit form for each existing contact, and render an empty new form. You will have to edit your controller functionality a little, because you will always re-render the complete collection/index page (with all existing contacts in the collection?).
So you can just render multiple forms on one page. Using turbolinks this will render fast and feel actually completely the same. You could use xhr to update only specific parts of the page, but to get started that is not even needed.
So I ended up following drifting ruby and using code from the cocoon gem to implement something myself. I hope others can benefit from it. Thank you nathanvda for the cocoon gem which helped me with the code below, really wish I could have used it:
add this to your app/helpers/application_helper.rb
def link_to_add_row(*args, &block)
if block_given?
link_to_add_row(capture(&block), *args)
else
#byebug
name, association, new_object, partial, html_options = *args
html_options ||= {}
html_options[:class] = [html_options[:class], "custom_add_fields"].compact.join(' ')
id = 'NEW_RECORD'
fields = fields_for("#{association}[#{id}]", new_object, child_index: id) do |builder|
#byebug
render( partial, f: builder)
end
fields = CGI.escapeHTML(fields).html_safe
link_to(name, '#', class: html_options[:class], data: {id: id, fields: fields})
end
end
add to your app/assets/application.js
$(document).on('click', '.custom_remove_fields', function(event) {
$(this).prev('input[type=hidden]').val('1');
$(this).closest('tr').hide();
return event.preventDefault();
});
$(document).on('click', '.custom_add_fields', function(event) {
var regexp, time;
time = new Date().getTime();
regexp = new RegExp($(this).data('id'), 'g');
$('.contact_fields').append($(this).data('fields').replace(regexp, time));
return event.preventDefault();
});
In your template you can use the following to render a partial for the collection:
<%= link_to_add_row('contacts', contact.new, 'contact_fields', class: 'btn btn-primary') do %>
<i class="fas fa-plus"></i>
<% end %>
This is how I render the partial with the collections in my template:
<tbody class="contact_fields">
<% #contacts.each_with_index do |contact, index| %>
<%= fields_for "contacts[#{index}]", contact do |c| %>
<%= render 'contact_fields', f: c %>
<% end %>
<% end %>
</tbody>
This is what my contact_fields.html.erb partial looks like.
<tr class="nested-fields">
<td>
<%= f.text_field :fullname, class: 'form-control invoke-contacts-search contact-fullname' %>
</td>
<td>
<%= f.text_field :email, class: 'form-control invoke-contacts-search contact-email' %>
</td>
<td>
<%= f.text_field :phone, class: 'form-control contact-phone' %>
</td>
<td>
<%= f.text_field :department, class: 'form-control contact-department' %>
</td>
<td>
<%= f.text_field :manager, class: 'form-control contact-manager' %>
</td>
<td>
<%= f.hidden_field :id %>
<%= f.hidden_field :_destroy %>
<%= link_to '#', class: 'btn btn-danger custom_remove_fields' do %>
<i class="fas fa-trash-alt"></i>
<% end %>
</td>
</tr>

Can not edit the form from sails.js

Hey guys I'm really new at sails.js and I'm using version 1.0 of it. I just tried to create a CRUD application on adding article to my list and showing them. All goes right but when I want to delete or edit it says 404 error. I am going through this tutorial series and as I know this series is using sails js version 0.12.
I am using mongodb as my database as a default. Data insertion is going well but problem is when I wanted to edit or delete it. Here I think the problem is getting the id value from the url. I skipped the edit portion here and posted the delete portion here.
api/controllers/ ArticleController.js
module.exports = {
delete: function(req, res){
Articles.destroy({id:req.params.id}).exec(function(err){
if(err){
res.send(500,'Database Error');
}
res.redirect('/articles/list');
});
return false;
}
};
api/models/ Articles.js
module.exports = {
attributes: {
title:{
type:'string'
},
body:{
type:'string'
}
},
};
views/pages list.ejs
<h1 class="display-4">Articles</h1>
<table class="table table-striped">
<thead>
<tr>
<th>#</th>
<th>Title</th>
<th></th>
</tr>
</thead>
<tbody>
<% articles.forEach(function(article){ %>
<tr>
<td><%= article.id %></td>
<td><%= article.title %></td>
<td>
<form class="d-inline" action="/articles/delete/<%= article.id %>" method="POST">
<input type="submit" class="btn btn-danger" value="Delete">
</form>
</td>
</tr>
<% }) %>
</tbody>
</table>
config/route.js
module.exports.routes = {
'/': {
view: 'pages/homepage'
},
};

How to send email in Jenkins with groovy template?

I am using Jenkins server for CI and I am trying to send a post-build email using email-ext plugin and groovy template: appsgt.groovy, code below. My default content is empty and my pre send script field is as follows ${SCRIPT, script="managed:appsgt"}.
But I get an error # line 1 column for column 1: unexpected token <
If I change script to template I still get an error for another line, meanwhile email template testing creates nicely formated data.
<STYLE>
BODY, TABLE, TD, TH, P {
font-family:Verdana,Helvetica,sans serif;
font-size:11px;
color:black;
}
</STYLE>
<BODY>
<%
float versionadjust = 103.0f
float newversion = (build.number + 103) / 1000
def realVersion = newversion.round(3)
%>
<TABLE>
<TR><TD align="right"><IMG SRC="${rooturl}static/e59dfe28/images/32x32/<%= build.result.toString() == 'SUCCESS' ? "blue.gif" : build.result.toString() == 'FAILURE' ? 'red.gif' : 'yellow.gif' %>" />
</TD><TD valign="center"><B style="font-size: 200%;">BUILD ${build.result}</B></TD></TR>
<TR><TD>Build URL</TD><TD>${rooturl}${build.url}</TD></TR>
<TR><TD>Project:</TD><TD>${project.name}</TD></TR>
<TR><TD>Project version:</TD><TD>${realVersion}</TD></TR>
<TR><TD>Date of build:</TD><TD>${it.timestampString}</TD></TR>
<TR><TD>Build duration:</TD><TD>${build.durationString}</TD></TR>
</TABLE>
<BR/>
<!-- CHANGE SET -->
<%
def changeSet = build.changeSet
if(changeSet != null) {
def hadChanges = false %>
<TABLE width="100%">
<TR><TD class="bg1" colspan="2"><B>CHANGES</B></TD></TR>
<% changeSet.each() { cs ->
hadChanges = true %>
<TR>
<TD colspan="2" class="bg2"> Revision <B><%= cs.metaClass.hasProperty('commitId') ? cs.commitId : cs.metaClass.hasProperty('revision') ? cs.revision :
cs.metaClass.hasProperty('changeNumber') ? cs.changeNumber : "" %></B> by
<B><%= cs.author %>: </B>
<B>(${cs.msgAnnotated})</B>
</TD>
</TR>
<% cs.affectedFiles.each() { p -> %>
<TR>
<TD width="10%"> ${p.editType.name}</TD>
<TD>${p.path}</TD>
</TR>
<% }
}
if(!hadChanges) { %>
<TR><TD colspan="2">No Changes</TD></TR>
<% } %>
</TABLE>
<BR/>
<% } %>
<!-- CONSOLE OUTPUT -->
<% if(build.result==hudson.model.Result.FAILURE) { %>
<TABLE width="100%" cellpadding="0" cellspacing="0">
<TR><TD class="bg1"><B>CONSOLE OUTPUT</B></TD></TR>
<% build.getLog(100).each() { line -> %>
<TR><TD class="console">${org.apache.commons.lang.StringEscapeUtils.escapeHtml(line)}</TD></TR>
<% } %>
</TABLE>
<BR/>
<% } %>
</BODY>
${SCRIPT, script="managed:appsgt"}
^ That should be:
${SCRIPT, template="managed.template"}
...unless I'm misunderstanding your question.
source: https://wiki.jenkins-ci.org/display/JENKINS/Email-ext+plugin#Email-extplugin-Scriptcontent

MVC : Model does not submit for multiple forms

This is related to ASP.Net MVC 2
I have a model (MoviesForAll) bound to my view and this model has a collection of class ICollection. I want my user to buy single ticket at a time by clicking submit button 'Buy this ticket' so I have placed a button besides each row representing the ticket details. This lead to following sequence
<%#Page Title="title" Language="C#" MasterPageFile="~/Views/Shared/MyMaster.Master"
Inherits="System.Web.Mvc.ViewPage<OnlineBooking.Movies.MoviesForAll>">
<Table>
<% for(i=0; i<Model.Tickets.count; i++)
{ %>
<tr>
<% using (Html.BeginForm(myaction(), FormMethod.Post, new {id="myform"}))
{ %>
<td>
<%= Model.tickets[i].ticketID %>
<%= Html.HiddenFor(m=>m.tickets[i].ticketID) %>
</td>
<td>
<%= Model.tickets[i].seatNo %>
<%= Html.HiddenFor(m=>m.tickets[i].seatNo) %>
</td>
...
...
<td>
<input type="submit" value="buy this ticket" runat="server">
</td>
<% } %>
</tr>
<% } %>
</table>
This creates a form for each row of tickets having single submit button in that form.
The problem is, when I submit first row (having index 0) by clicking the button, it gets submitted properly and I can see the values in controller method. But no other row gets through to controller even if I have used hidden fields to bind it.
Am I missing anything here specific to index or something?
Thanks in advance..
I would suggest having one form for all the rows, then on each row use the button element instead of an input as follows:
<button type="submit" value="<%= Model.tickets[i].ticketID %>" name="buyticket">Buy this ticket</button>
You should have a parameter on your controller action called buyticket and that should have the ticket id of the button which was clicked
How about the following:
<table>
<% for(i = 0; i < Model.Tickets.Count; i++) { %>
<tr>
<% using (Html.BeginForm("myaction", FormMethod.Post, new { id = "myform" })) { %>
<td>
<%= Model.tickets[i].ticketID %>
</td>
<td>
<%= Model.tickets[i].seatNo %>
</td>
...
...
<td>
<%= Html.Hidden("TicketId", Model.tickets[i].ticketID) %>
<%= Html.Hidden("SeatNumber", Model.tickets[i].seatNo) %>
<input type="submit" value="buy this ticket" />
</td>
<% } %>
</tr>
<% } %>
</table>
and then:
public class TicketToPurchaseViewModel
{
public int TicketId { get; set; }
public int SeatNumber { get; set; }
}
and the action:
[HttpPost]
public ActionResult myaction(TicketToPurchaseViewModel ticket)
{
...
}
Remark: notice that I have removed the runat="server" attribute from the submit button as well because this is something that you definitely don't want to see in an ASP.NET MVC application.