Many-to-Many Ajax Forms (Symfony2 Forms) - symfony

I have a many-to-many relationship in mongodb between Players and Tournaments.
I want to be able to add many Players to a Tournament at once. This is trivial to do without ajax, but we have a DB of thousands of Players, and so the form select becomes huge.
We want to use ajax for this. Is it possible to create a single widget (with js) to handle this properly? If so, any hints on what jquery plugin (or other) to use?
If not, whats the standard strategy to do this? I suppose I could heavily change the view for this form and use an ajax autocomplete to add one player at a time, and then some more code to delete each player one at a time. However, I'd really like to have a single widget I can re-use because its so much cleaner and seems much more efficient.
I have been playing with Select2 all day (similar to jQuery Chosen) and I have it working for adding many Players via ajax, but it does not allow me to set the already attached players when I initially load the page, so I won't be able to see who's already in the tournament and would have to retype everyone in.
Thanks for ANY input on this matter! I can't find anything via Google.

I was able to accomplish this by $.ajax after the constructor within the onload function where //website/jsonItem is a json-encoded list of all items, and //website/jsonItemUser is a json-encoded list of all items attached to user. I used // to keep the https/http consistent between calls.
$(document).ready(function(){
$('.selectitem').select2({
minimumInputLength:0
,multiple: true
,ajax: {
url: "//website/jsonItem"
,dataType: 'jsonp'
,data: function (term, page) {
return {
q: term, // search term
limit: 20,
page: page
};
}
,results: function (data, page) {
var more = (page * 20) < data.total;
return {
results: data.objects, more: more
};
}
}
,initSelection: function(element, callback){
var items=new Array();
$.ajax({
url: "//website/jsonItemUser"
});
callback(items);
}
});
$.ajax({
url: "//website/jsonItemUser"
,dataType: 'jsonp'
,success: function(items, status, ob) {
$('.selectitem').select2('data',items);
}
});
});

Related

Detect users input values from any wordpress form

I'm trying to develop a wordpress plugin, I need to get users input data from any form in a specific page (not knowing its action) I come up so far with this solution which is to get values using javascript and then passing it to php:
jQuery(function ($) {
$(document).ready(function(){
$( "form" ).submit(function( event ) {
if($( "form" ).valid()){
var inputs = $( "form input" );
var inputValues = [];
inputs.each(function(index){
if($(this).attr('type') !== 'submit')
inputValues.push($(this).val());
});
}
event.preventDefault();
});
});
});
I tried to pass the Javascript variable inputValues to my plugin using Ajax
$.ajax({
type: 'POST',
url: '../wp-content/plugins/myplugin/myplugin.php',
data: {'variable': inputValues},
});
But I get problems with the url for some pages and I couldn't use $_POST['variable'] in myplugin.php file.
Is there a way to accomplish what I'm trying to do, or do you know an alternative solution?
Thanks in advance.
in terms of how to implement AJAX calls using WordPress, please check out the WordPress Codex. You're not doing it correctly.
JavaScript seems like a round about way of doing this. I would suggest to hook into one of hooks that are being called almost every single time like template_redirect (https://codex.wordpress.org/Plugin_API/Action_Reference/template_redirect).
Then you can check what's in the $_POST variable and do what you need to do with it. This would even Capture AJAX forms as long as the URL links to a proper AJAX WordPress endpoint.
Hope this helps

SAPUI5 OPA5 How to trigger a select event

Below a typical action to test if a sap.m.Select contains an item with the name xyz and then select it.
success: function(oSelect) {
var oItems = oSelect.getItems();
$.each(oItems, function(i,v) {
if(oItems[i].getText() === "TestItemNameILikeToSelect") {
oTestOpa5TestItem = oItems[i];
}
});
if(oTestOpa5TestItem !== null) {
oSelect.setSelectedKey(oTestOpa5TestItem.getKey());
oTestOpa5TestItem.$().trigger("tap");
}
},
When I start the test run it does correctly select the proper item from the list and sets it visibly in the browser, but it does not trigger the attached event that is behind (e.g. change="onListItemChanged").
My application works fine, but I don't find a way to create a working test for it.
Thanks in advance
OPA5 has an 'Action' interface and two default implementations e.g. 'EnterText' and 'Press'. The recommended usage is to define an action block on the waitFor() options like this:
When.waitFor({
id: "myButton",
actions: new Press()
});
What you use is the 'old way' but it has some shortcomings:
success block is not synchronized with XHR requests but action is.
Sending a click/tap event to a control could require selecting some internal element. Imagine a click to nav container - there are several places you could click actually. Actions handle those details and define a standard behavior you could depend on.
It is better to encapsulate your selection logic inside a matchers block and even abstract it to a custom matcher. This way your success block will be cleaner and you could reuse the matcher in several places in your test.
OPA5 Actions
Have a look at the official UI5 Demo Kit, under samples > OPA5 > Code: Simulating user interactions on UI5 controls with OPA5, You will be able to find numerous examples of OPA 5 testing regarding general user interactions. In your case for the select:
opaTest("Should select an item in a sap.m.Select", function(Given, When, Then) {
When.waitFor({
id: "mySelect",
actions: new Press(),
success: function(oSelect) {
this.waitFor({
controlType: "sap.ui.core.Item",
matchers: [
new Ancestor(oSelect),
new Properties({ key: "Germany"})
],
actions: new Press(),
success: function() {
Opa5.assert.strictEqual(oSelect.getSelectedKey(), "Germany", "Selected Germany");
},
errorMessage: "Cannot select Germany from mySelect"
});
},
errorMessage: "Could not find mySelect"
});
});
https://sapui5.hana.ondemand.com/#/entity/sap.ui.test.Opa5/sample/sap.ui.core.sample.OpaAction/code/Opa.js

Meteor JS & Blaze - Show Only Once on Load

I have a partial that show's a notification modal to agree to the site's terms and service that I would only like to show once (once they click I agree it goes away).
Is there anyway to do that with Meteor?
Assuming you want to store a boolean in the DB indicating that the user has accepted the terms (so they never get asked again), you could add a field called hasAcceptedTerms somewhere on the user object (e.g. in the user's profile). Once you do that you could write your template like this:
<template name="myTemplate">
{{#if areTermsVisible}}
(put terms partial here)
{{/if}}
</template>
Where areTermsVisible looks like:
Template.myTemplate.helpers({
areTermsVisible: function() {
var user = Meteor.user();
return user && user.profile && !user.profile.hasAcceptedTerms;
}
});
And the code to record the acceptance looks like:
Template.myTemplate.events({
'click .accept-terms': function() {
var userId = Meteor.userId();
var modifier = {$set: {'profile.hasAcceptedTerms': true}};
Meteor.users.update(userId, modifier);
}
});
Maybe not surprisingly, the best way to deal with cookies policy notification is by using cookies. The problem is not meteor-specific, but there are at least two good atmosphere packages that can help you to deal with the problem:
https://atmospherejs.com/mrt/cookies
https://atmospherejs.com/chuangbo/cookie
What you need to do is basically, set cookie
Cookie.set('userHasAcceptedPolicy', true, { year: 1 });
with whatever arguments you like, and as soon as the user clicks the "accept" button. Then, before you decide if you need to show the policy notification you can use:
Cookies.get('userHasAcceptedPolicy');
to see if there's a need to do so. So it's pretty much the same solution as #DavidWeldon suggested but it does not require referencing the Meteor.user() object, so the user does not need to have an account to accept the policy.
Please note, that - at least in case of mrt:cookies - Cookies.get is a reactive data source, which is quite helpful when it comes to rendering templates.
There's plenty of ways...
This isn't a Meteor specific question.
Template.notifications.events({
'click #close-modal': function(e, t) {
$('#modal').hide();
}
})

Framework7 starter page "pageInit" NOT WORKING

anyone using framework7 to create mobile website? I found it was great and tried to learn it by myself, now I meet this problem, after I create my App, I want to do something on the starter page initialization, here, my starter page is index.html, and I set data-page="index", now I write this below:
$$(document).on('pageInit', function (e) {
var page = e.detail.page;
// in my browser console, no "index page" logged
if (page.name === 'index') {
console.log("index page");
});
// but I changed to any other page other than index, it works
// my browser logged "another page"
if(page.name === 'login') {
console.log('another page');
}
});
Anyone can help? Thank you so much.
I have also encountered with the same problem before.
PageInit event doesn't work for initial page, only for pages that you navigate to, it will only work for index page if you navigate to some other page and then go back to index page.
So I see two options here:
Just not use pageInit event for index page - make its initialization just once (just make sure you put this javascript after all its html is ready, or e.g. use jquery's on document ready event)
Leave index page empty initially and load it dynamically via Framework7's mainView.loadContent method, then pageInit event would work for it (that was a good option for me as I had different index page each time, and I already loaded all other pages dynamically from underscore templates)
I am facing same issue and tried all solutions in various forums.. nothing actually worked. But after lot of RnD i stumbled upon following solution ...
var $$ = Dom7;
$$(document).on('page:init', function (e) {
if(e.detail.page.name === "index"){
//do whatever.. remember "page" is now e.detail.page..
$$(e.detail.page.container).find('#latest').html("my html here..");
}
});
var me = new Framework7({material: true});
var mainview = me.addView('.view-main', {});
.... and whatever else JS here..
this works perfectly..
surprisingly you can use "me" before initializing it..
for using for first page u better use document ready event. and for reloading page event you better use Reinit event.
if jquery has used.
$(document).on('ready', function (e) {
// ... mainView.activePage.name = "index"
});
$(document).on('pageReinit', function (e) {
//... this event occur on reloading anypage.
});

Render a Backbone.js collection

I am a Backbone.js n00b and trying to get my head around it. I know how to render a model using a view and the built-in underscore.js templating engine. Now I'm trying to render a collection and that's where I get stuck. There is no server here, so I'm not fetching anything remotely, just a simple HTML page with some JavaScript.
ContinentModel = Backbone.Model.extend({});
ContinentsCollection = Backbone.Collection.extend({
model: ContinentModel,
initialize: function () {
this.continentsView = new ContinentsView;
this.bind("reset", this.continentsView.render);
}
});
ContinentsView = Backbone.View.extend({
el: '#continents',
template: _.template($('#continents-template').html()),
render: function() {
var renderedContent = this.template(this.collection.toJSON());
$(this.el).html(renderedContent);
return this;
}
});
$(function() {
var continentsCollection = new ContinentsCollection();
continentsCollection.reset([{name: "Asia"}, {name: "Africa"}]);
});
It breaks on the template attribute line in the view but I'm not sure that's where I need to look. Am I supposed to render a collection or do I miss the point completely here (maybe collections are just grouping objects and I shouldn't look at it as a list I can render)?
Thanks for helping...
The problem is that when you define ContinentsView, the template is evaluated and it uses $('#continents-template') - but the DOM is not ready yet, so it does not find the template.
To solve it, simply move the template assignment in the initialize function:
ContinentsView = Backbone.View.extend({
el: '#continents',
initialize: function() {
this.template = _.template($('#continents-template').html());
}
...
Regarding collections, yes, they are grouping objects, specifically sets of models.
You should make the code so the models (and collections) do NOT know about the views, only the views know about models.
ContinentModel = Backbone.Model.extend({});
ContinentsCollection = Backbone.Collection.extend({
model: ContinentModel,
// no reference to any view here
});
ContinentsView = Backbone.View.extend({
el: '#continents',
initialize: function() {
this.template = _.template($('#continents-template').html());
// in the view, listen for events on the model / collection
this.collection.bind("reset", this.render, this);
},
render: function() {
var renderedContent = this.template(this.collection.toJSON());
$(this.el).html(renderedContent);
return this;
}
});
$(function() {
var continentsCollection = new ContinentsCollection();
continentsCollection.reset([{name: "Asia"}, {name: "Africa"}]);
// initialize the view and pass the collection
var continentsView = new ContinentsView({collection: continentsCollection});
});
It is also worth noting there are additional complexities that quickly rear their heads when rendering a collection in a view. For instance, the view generally needs to be re-rendered when models are added or removed from the collection. It isn't rocket science to implement your own solution, but it is probably worth looking into existing solutions since there are quite a few tried and tested ones out there.
Backbone.CollectionView is a robust collection view class that handles selecting models in response to mouse clicks, reordering the collection based on drag and drop, filtering visible models, etc.
Several popular frameworks built on top of backbone also provide simple collection view classes, like Backbone.Marionette, Chaplin, and Layout Manager.
Even though Backbone itself does not provide any structure for rendering a collection, it is a non-trivial problem and lots of people have different opinions on how it should be done. Luckily it is such a common need that there are quite a few good options already in the eco system.

Resources