when bootstrap date picker date select some action call in ember js controller - ember.js

I am new to ember, developing Filtering by date functionality using ember js.
handle bars:
<div class="input-group date" data-behavior="ActiveRock.filterDatePicker" data-date-before-field="#filter_end_date">
<input type="text" class="form-control" id="filter_start_date" {{action filterPortfolios}}/>
<span class="input-group-addon">
<span class="glyphicon glyphicon-calendar"></span>
</span>
</div>
Behaviour:
$ ->
ActiveRock.datePicker = (el) ->
el.datepicker(
format: 'yyyy/mm/dd'
autoclose: true
).on('show', (e) ->
$('.datepicker').css('z-index', '1151')
true
).on('hide', (e) ->
logic
return false
true
)
controller action: filterPortfolios
included bootstrap datepicker
but it is not working, please suggest any solution.
Thanks,
Prasad.

In behavior I written like taht
$(function() {
return ExamplePicker.filterDatePicker = function(el) {
return el.datepicker({
format: 'yyyy/mm/dd',
autoclose: true
}).on('changeDate', function(e) {
var controller;
controller = App.__container__.lookup("controller:<controller_name>");
controller.send("<action_name>");
return true;
});
};
});

Related

Unit Testing Login Vue Jest ValidationProvider

I am new to Jest and I am trying to mock the store, an action and to assert that the method was indeed called. Basically I want to check the login function.
I cannot query the button because I am retrieving only a part of the component and I don't know what I'm missing.
Where my Vue component looks like:
<ValidationObserver id="observer" v-slot="{ invalid }" :class="['w-full h-full']">
<form class="flex flex-col justify-around h-full" #submit.prevent="onSubmit">
<ValidationProvider v-slot="{ errors }" name="accessCode" :class="['w-full py-6']">
<sd-field :class="['sd-field_secondary', { ['sd-invalid ']: errors && errors.length > 0 }]">
<label for="email">{{ $t("form.access-code") }}</label>
<sd-input v-model="accessCode" type="accessCode" />
<span class="sd-error">{{ errors[0] }}</span>
</sd-field>
</ValidationProvider>
<div class="btn-group-y">
<button class="btn btn-fixed btn-blueDark" type="submit">
<span>{{ $t("account.login") }}</span>
</button>
<!-- <button class="btn btn-link" type=""> //TODO: temporary hide
<span>{{ $t("account.forgot_id") }}</span>
</button> -->
</div>
</form>
</ValidationObserver>
***MY TEST FILE***
import login from "../../pages/index/login";
import Vuex from "vuex";
import { mount, createLocalVue } from "#vue/test-utils";
const localVue = createLocalVue();
localVue.use(Vuex);
describe("Login form", () => {
it("calls the login action correctly", () => {
const loginMock = jest.fn(() => Promise.resolve());
const store = new Vuex.Store({
actions: {
onSubmit: loginMock,
},
});
const wrapper = mount(login, { localVue, store, stubs: { ValidationObserver: true } });
console.log(wrapper.html());
// wrapper.find("button").trigger("click");
// expect(loginMock).toHaveBeenCalled();
});
});
console.log(wrapper.html()) returns only a part of component
<div class="h-full w-full"><validationobserver id="observer"
class="w-full h-full"> </validationobserver>
</div>
With a warning also:
> console.error node_modules/vue/dist/vue.runtime.common.dev.js:621
> [Vue warn]: Unknown custom element: <ValidationObserver> - did you register the
> component correctly? For recursive components, make sure to provide the "name" option.
> found in
> ---> <Anonymous>
> <Root>
I would like to understand how this works, I have tried to stub and other ways found but with no success.
I can get rid of the warning by adding the stubs: { ValidationObserver: true } to mount but I actually need to access the elements inside.
Thank you!

Ember Octane How to Get Error Messages to be Displayed?

This question is related to Ember Octane Upgrade How to pass values from component to controller
How do I get Ember Octane to display on the webpage? For instance, if the old password and new password are the same we want that error to display on the page.
Ember-Twiddle here
Code example:
User Input Form
ChangePasswordForm.hbs
<div class="middle-box text-center loginscreen animated fadeInDown">
<div>
<h3>Change Password</h3>
<form class="m-t" role="form" {{on "submit" this.changePassword}}>
{{#each this.errors as |error|}}
<div class="error-alert">{{error.detail}}</div>
{{/each}}
<div class="form-group">
<Input #type="password" class="form-control" placeholder="Old Password" #value={{this.oldPassword}} required="true" />
</div>
<div class="form-group">
<Input #type="password" class="form-control" placeholder="New Password" #value={{this.newPassword}} required="true" />
</div>
<div class="form-group">
<Input #type="password" class="form-control" placeholder="Confirm Password" #value={{this.confirmPassword}} required="true" />
</div>
<div>
<button type="submit" class="btn btn-primary block full-width m-b">Submit</button>
</div>
</form>
</div>
</div>
Template Component
ChangePassword.hbs
<Clients::ChangePasswordForm #chgpwd={{this.model}} #changePassword={{action 'changePassword'}} #errors={{this.errors}} />
Component
ChangePasswordForm.js
import Component from '#glimmer/component';
import { tracked } from '#glimmer/tracking';
import { action } from '#ember/object';
export default class ChangePasswordForm extends Component {
#tracked oldPassword;
#tracked newPassword;
#tracked confirmPassword;
#tracked errors = [];
#action
changeOldPassword(ev) {
this.oldPassword = ev.target.value;
}
#action
changeNewPassword(ev) {
this.newPassword = ev.target.value;
}
#action
changeConfirmPassword(ev) {
this.confirmPassword = ev.target.value;
}
#action
changePassword(ev) {
ev.preventDefault();
this.args.changePassword({
oldPassword: this.oldPassword,
newPassword: this.newPassword,
confirmPassword: this.confirmPassword
});
}
}
Controller
ChangePassword.js
import Controller from '#ember/controller';
import { inject as service } from '#ember/service';
import { action } from '#ember/object';
export default class ChangePassword extends Controller {
#service ajax
#service session
#action
changePassword(attrs) {
if(attrs.newPassword == attrs.oldPassword)
{
shown in the UI.
this.set('errors', [{
detail: "The old password and new password are the same. The password was not changed.",
status: 1003,
title: 'Change Password Failed'
}]);
}
else if(attrs.newPassword != attrs.confirmPassword)
{
this.set('errors', [{
detail: "The new password and confirm password must be the same value. The password was not changed.",
status: 1003,
title: 'Change Password Failed'
}]);
}
else
{
let token = this.get('session.data.authenticated.token');
this.ajax.request(this.store.adapterFor('application').get('host') + "/clients/change-password", {
method: 'POST',
data: JSON.stringify({
data: {
attributes: {
"old-password" : attrs.oldPassword,
"new-password" : attrs.newPassword,
"confirm-password" : attrs.confirmPassword
},
type: 'change-passwords'
}
}),
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/vnd.api+json',
'Accept': 'application/vnd.api+json'
}
})
.then(() => {
this.transitionToRoute('clients.change-password-success');
})
.catch((ex) => {
this.set('errors', ex.payload.errors);
});
}
}
}
Model
ChangePassword.js
import Route from '#ember/routing/route';
import AbcAuthenticatedRouteMixin from '../../mixins/efa-authenticated-route-mixin';
export default class ChangePasswordRoute extends Route.extend(AbcAuthenticatedRouteMixin) {
model() {
// Return a new model.
return {
oldPassword: '',
newPassword: '',
confirmPassword: ''
};
}
}
In your form component, you reference the errors like
{{#each this.errors as |error|}}
<div class="error-alert">{{error.detail}}</div>
{{/each}}
From class components -> glimmer components, there's been a fundamental shift in the way you access the component's arguments vs the component's own values (for the better!)
In class components, arguments are assigned directly to the class
instance. This has caused a lot of issues over the years, from methods
and actions being overwritten, to unclear code where the difference
between internal class values and arguments is hard to reason about.
New components solve this by placing all arguments in an object
available as the args property.
When referencing an argument to a component in javascript, you use: this.args.someArg. In the template, you use the shorthand #someArg. These are known as "named arguments" (feel free to read the rfc for more info). When you, as you did here, use this.errors in your template, you are looking for a local component property errors.
Just to emphasize, this does not work because errors is passed to Clients::ChangePasswordForm via #errors here:
<Clients::ChangePasswordForm #chgpwd={{this.model}} #changePassword={{action 'changePassword'}} #errors={{this.errors}} />
and must be #errors in the template
{{#each #errors as |error|}}
<div class="error-alert">{{error.detail}}</div>
{{/each}}

How to add text input to dropzone upload

I'd like to allow users to submit a title for each file that is dragged into Dropzone that will be inputted into a text input. But i don't know how to add it. Everyone can help me?
This is my html code code
<form id="my-awesome-dropzone" class="dropzone">
<div class="dropzone-previews"></div> <!-- this is were the previews should be shown. -->
<!-- Now setup your input fields -->
<input type="email" name="username" id="username" />
<input type="password" name="password" id="password" />
<button type="submit">Submit data and files!</button>
</form>
And this is my script code
<script>
Dropzone.options.myAwesomeDropzone = { // The camelized version of the ID of the form element
// The configuration we've talked about above
url: "upload.php",
autoProcessQueue: false,
uploadMultiple: true,
parallelUploads: 100,
maxFiles: 100,
maxFilesize:10,//MB
// The setting up of the dropzone
init: function() {
var myDropzone = this;
// First change the button to actually tell Dropzone to process the queue.
this.element.querySelector("button[type=submit]").addEventListener("click", function(e) {
// Make sure that the form isn't actually being sent.
e.preventDefault();
e.stopPropagation();
myDropzone.processQueue();
});
// Listen to the sendingmultiple event. In this case, it's the sendingmultiple event instead
// of the sending event because uploadMultiple is set to true.
this.on("sendingmultiple", function() {
// Gets triggered when the form is actually being sent.
// Hide the success button or the complete form.
});
this.on("successmultiple", function(files, response) {
// Gets triggered when the files have successfully been sent.
// Redirect user or notify of success.
});
this.on("errormultiple", function(files, response) {
// Gets triggered when there was an error sending the files.
// Maybe show form again, and notify user of error
});
},
accept: function (file, done) {
//maybe do something here for showing a dialog or adding the fields to the preview?
},
addRemoveLinks: true
}
</script>
You can actually provide a template for Dropzone to render the image preview as well as any extra fields. In your case, I would suggest taking the default template or making your own, and simply adding the input field there:
<div class="dz-preview dz-file-preview">
<div class="dz-image"><img data-dz-thumbnail /></div>
<div class="dz-details">
<div class="dz-size"><span data-dz-size></span></div>
<div class="dz-filename"><span data-dz-name></span></div>
</div>
<div class="dz-progress"><span class="dz-upload" data-dz-uploadprogress></span></div>
<div class="dz-error-message"><span data-dz-errormessage></span></div>
<input type="text" placeholder="Title">
</div>
The full default preview template can be found in the source code of dropzone.js.
Then you can simply pass your custom template to Dropzone as a string for the previewTemplate key of the option parameters. For example:
var myDropzone = new Dropzone('#yourId', {
previewTemplate: "..."
});
As long as your element is a form, Dropzone will automatically include all inputs in the xhr request parameters.
I am doing something fairly similar. I accomplished it by just adding a modal dialog with jquery that opens when a file is added. Hope it helps.
this.on("addedfile", function() {
$("#dialog-form").dialog("open");
});
In my answer, substitute your "title" field for my "description" field.
Add input text or textarea to the preview template. For example:
<div class="table table-striped files" id="previews">
<div id="template" class="file-row">
<!-- This is used as the file preview template -->
<div>
<span class="preview"><img data-dz-thumbnail /></span>
</div>
<div>
<p class="name" data-dz-name></p>
<input class="text" type="text" name="description" id="description" placeholder="Searchable Description">
</div> ... etc.
</div>
</div>
Then in the sending function, append the associated data:
myDropzone.on("sending", function(file, xhr, formData) {
// Get and pass description field data
var str = file.previewElement.querySelector("#description").value;
formData.append("description", str);
...
});
Finally, in the processing script that does the actual upload, receive the data from the POST:
$description = (isset($_POST['description']) && ($_POST['description'] <> 'undefined')) ? $_POST['description'] : '';
You may now store your description (or title or what have you) in a Database etc.
Hope this works for you. It was a son-of-a-gun to figure out.
This one is kind of hidden in the docs but the place to add additional data is in the "sending" event. The sending event is called just before each file is sent and gets the xhr object and the formData objects as second and third parameters, so you can modify them.
So basically you'll want to add those two additional params and then append the additional data inside "sending" function or in your case "sendingmultiple". You can use jQuery or just plain js to get the values. So it should look something like:
this.on("sendingmultiple", function(file, xhr, formData) {
//Add additional data to the upload
formData.append('username', $('#username').val());
formData.append('password', $('#password').val());
});
Here is my solution:
Dropzone.autoDiscover = false;
var myDropzone = new Dropzone("#myDropzone", {
url: 'yourUploader.php',
init: function () {
this.on(
"addedfile", function(file) {
caption = file.caption == undefined ? "" : file.caption;
file._captionLabel = Dropzone.createElement("<p>File Info:</p>")
file._captionBox = Dropzone.createElement("<input id='"+file.filename+"' type='text' name='caption' value="+caption+" >");
file.previewElement.appendChild(file._captionLabel);
file.previewElement.appendChild(file._captionBox);
}),
this.on(
"sending", function(file, xhr, formData){
formData.append('yourPostName',file._captionBox.value);
})
}
});
yourUploader.php :
<?php
// Your Dropzone file named
$myfileinfo = $_POST['yourPostName'];
// And your files in $_FILES
?>
$("#my-awesome-dropzone").dropzone({
url: "Enter your url",
uploadMultiple: true,
autoProcessQueue: false,
init: function () {
let totalFiles = 0,
completeFiles = 0;
this.on("addedfile", function (file) {
totalFiles += 1;
localStorage.setItem('totalItem',totalFiles);
caption = file.caption == undefined ? "" : file.caption;
file._captionLabel = Dropzone.createElement("<p>File Info:</p>")
file._captionBox = Dropzone.createElement("<textarea rows='4' cols='15' id='"+file.filename+"' name='caption' value="+caption+" ></textarea>");
file.previewElement.appendChild(file._captionLabel);
file.previewElement.appendChild(file._captionBox);
// this.autoProcessQueue = true;
});
document.getElementById("submit-all").addEventListener("click", function(e) {
// Make sure that the form isn't actually being sent.
const myDropzone = Dropzone.forElement(".dropzone");
myDropzone.processQueue();
});
this.on("sending", function(file, xhr, formData){
console.log('total files is '+localStorage.getItem('totalItem'));
formData.append('description[]',file._captionBox.value);
})
}
});
For those who want to keep the automatic and send datas (like an ID or something that does not depend on the user) you can just add a setTimeout to "addedfile":
myDropzone.on("addedfile", function(file) {
setTimeout(function(){
myDropzone.processQueue();
}, 10);
});
Well I found a solution for me and so I am going to write it down in the hope it might help other people also. The basic approach is to have an new input in the preview container and setting it via the css class if the file data is incoming by succeeding upload process or at init from existing files.
You have to integrate the following code in your one.. I just skipped some lines which might necessary for let it work.
photowolke = {
render_file:function(file)
{
caption = file.title == undefined ? "" : file.title;
file.previewElement.getElementsByClassName("title")[0].value = caption;
//change the name of the element even for sending with post later
file.previewElement.getElementsByClassName("title")[0].id = file.id + '_title';
file.previewElement.getElementsByClassName("title")[0].name = file.id + '_title';
},
init: function() {
$(document).ready(function() {
var previewNode = document.querySelector("#template");
previewNode.id = "";
var previewTemplate = previewNode.parentNode.innerHTML;
previewNode.parentNode.removeChild(previewNode);
photowolke.myDropzone = new Dropzone("div#files_upload", {
init: function() {
thisDropzone = this;
this.on("success", function(file, responseText) {
//just copy the title from the response of the server
file.title=responseText.photo_title;
//and call with the "new" file the renderer function
photowolke.render_file(file);
});
this.on("addedfile", function(file) {
photowolke.render_file(file);
});
},
previewTemplate: previewTemplate,
});
//this is for loading from a local json to show existing files
$.each(photowolke.arr_photos, function(key, value) {
var mockFile = {
name: value.name,
size: value.size,
title: value.title,
id: value.id,
owner_id: value.owner_id
};
photowolke.myDropzone.emit("addedfile", mockFile);
// And optionally show the thumbnail of the file:
photowolke.myDropzone.emit("thumbnail", mockFile, value.path);
// Make sure that there is no progress bar, etc...
photowolke.myDropzone.emit("complete", mockFile);
});
});
},
};
And there is my template for the preview:
<div class="dropzone-previews" id="files_upload" name="files_upload">
<div id="template" class="file-row">
<!-- This is used as the file preview template -->
<div>
<span class="preview"><img data-dz-thumbnail width="150" /></span>
</div>
<div>
<input type="text" data-dz-title class="title" placeholder="title"/>
<p class="name" data-dz-name></p><p class="size" data-dz-size></p>
<strong class="error text-danger" data-dz-errormessage></strong>
</div>
<div>
<div class="progress progress-striped active" role="progressbar" aria-valuemin="0" aria-valuemax="100" aria-valuenow="0">
<div class="progress-bar progress-bar-success" style="width:0%;" data-dz-uploadprogress></div>
</div>
</div>
</div>

date entries in emberjs templates

When I set {{input value=sDate type='date'}} in a handlebar template in emberjs, I get the html5 datepicker when using Chrome. Unfortunately, html5 datepicker is not supported in Firefox. How do I switch over to the jqueryUI datepicker instead?
The best way would be to create your own component and to call element.datepicker(); in your component's didInsertElement hook.
Here is an [Ember.Component][1] implementation of Bootstrap DatePicker:
Note: You should be able to adapt the setupDatePicker function easily to use jqueryUI datepicker.
date_picker_component.js
Chipmunk.DatePickerComponent = Ember.Component.extend({
setupDatePicker: {
var self = this;
return this.$('.datepicker').datepicker({
separator: "-",
autoclose: true
}).on("changeDate", function(event) {
return self.set("value", self.format(event.date));
});
}.on('didInsertElement'),
formattedValue: {
var value = this.get('value');
if (value) {
return this.format(value);
}
}.property('value'),
format: function(value) {
return moment.utc(value).format("YYYY-MM-DD");
}
});
date-picker.handlebars
<div class="date datepicker" data-date-format="yyyy-mm-dd">
<input class="form-control" size="16" type="text" readonly {{bindAttr value="formattedValue" rel="rel"}}>
<span class="add-on"><i class="icon-th"></i></span>
</div>
Usage:
{{date-picker value=sDate}}

EmberJS file upload via jquery-file-upload

I have an Ember.js controller and I'm attempting to send a file to my rails controller with jquery file upload.
I started with this:
myControllerAction: ->
$('#fileupload').fileupload(
url: "/api/v1/comics"
dataType: 'json'
formData:
comic: {
title: self.get('comicTitle')
prompt_one_id: self.get('prompts')[0].get('id')
prompt_two_id: self.get('prompts')[1].get('id')
}
)
Which did work, but it sent the form as soon as a file was selected. I want to do it all when the user submits the form. So I tried this:
didInsertElement: ->
$('#fileupload').fileupload(
url: "/api/v1/comics"
dataType: 'json'
formData:
comic: {
title: self.get('comicTitle')
prompt_one_id: self.get('prompts')[0].get('id')
prompt_two_id: self.get('prompts')[1].get('id')
}
add: (e, data) ->
data.submit()
progressall: (e, data) ->
progress = parseInt(data.loaded / data.total * 100, 10)
$('#progress .bar').css('width', progress + '%')
)
myControllerAction: ->
self = #
$('#fileupload').fileupload('add')
However that doesn't work. It throws a javascript error:
Uncaught Error: cannot call methods on fileupload prior to initialization; attempted to call method 'add'
I thought setting everything up on element insertion would be initializing the object. So I'm not sure where I'm going wrong. Anyone have any suggestions?
EDIT: To add template
<form enctype="multipart/form-data">
<div class="control-group">
<label class="control-label" for="inputTitle">Title</label>
<div class="controls">
{{input type="text" valueBinding="comicTitle"}}
{{input type="file" id="fileupload" valueBinding="comicFile"}}
</div>
</div>
<button {{action myControllerAction}} id="upload_comic" class="btn btn-inverse">Upload Comic</button>
<div id="progress">
<div class="bar" style="width: 0%;"></div>
</div>
</form>
Not sure what's the cause of the error, but try to do it with the afterRender callback. Also use this.$('#fileupload') instead of $('#fileupload'). Code:
didInsertElement: ->
Ember.run.scheduleOnce('afterRender', this, 'setupFileUpload')
setupFileUpload: ->
$('#fileupload').fileupload(
url: "/api/v1/comics"
dataType: 'json'
formData:
comic: {
title: self.get('comicTitle')
prompt_one_id: self.get('prompts')[0].get('id')
prompt_two_id: self.get('prompts')[1].get('id')
}
add: (e, data) ->
data.submit()
progressall: (e, data) ->
progress = parseInt(data.loaded / data.total * 100, 10)
$('#progress .bar').css('width', progress + '%')
)