How to edit data when combining angularjs and mongodb - mongodb

I'm a beginner in the AngularJs and MongoDb world (i started learning today!!)
Actually i'm trying to do something very basic : Display a list of record, with an add button and a edit link with each record.
I'm using this lib https://github.com/pkozlowski-opensource/angularjs-mongolab to connect to mongoweb.
Actually my data is displayed, when i try to add a record it works, but the problem is when i try to display the edit form!
Here is my index.html file, in which i display the data with a form to add a record and with the edit links :
<div ng-controller="AppCtrl">
<ul>
<li ng-repeat="team in teams">
{{team.name}}
{{team.description}}
edit
</li>
</ul>
<form ng-submit="addTeam()">
<input type="text" ng-model="team.name" size="30" placeholder="add new team here">
<input type="text" ng-model="team.description" size="30" placeholder="add new team here">
<input class="btn-primary" type="submit" value="add">
</form>
</div>
And here is my edit.html code, which displays an edit form :
<div ng-controller="EditCtrl">
<form ng-submit="editTeam()">
<input type="text" name="name" ng-model="team.name" size="30" placeholder="edit team here">
<input type="text" name="description" ng-model="team.description" size="30" placeholder="edit team here">
<input class="btn-primary" type="submit" value="validate edit">
</form>
</div>
And finally my js code:
var app = angular.module('app', ['mongolabResource']);
app.constant('API_KEY', '____________________________');
app.constant('DB_NAME', 'groups');
app.factory('Teams', function ($mongolabResource) {
return $mongolabResource('teams');
});
app.controller('AppCtrl', function ($scope, Teams) {
$scope.teams = Teams.query();
$scope.addTeam = function() {
varteam = {
name: $scope.team.name,
description: $scope.team.description
};
$scope.teams.push(varteam);
Teams.save($scope.team);
$scope.team.name = '';
$scope.team.description = '';
};
});
app.controller('EditCtrl', function ($scope, Teams) {
//????????
});
My AppCtrl works perfecty, it displays the data w add records perfectly.
Now i want to add the js code for the edit, but i don't even know form where to start ? how do i a get the id parameter in the url ? how do i tell the view to fill out the form fields from the values from the database ? And finally how do i update the databse.
I know that i asked a lot of question but i'm really lost! thank you

There are of course many possible solutions.
One solution is to use angularjs routing. See http://docs.angularjs.org/tutorial/step_07 for a tutorial.
Basically replace your ul list with something like:
<ul>
<li ng-repeat="team in teams">
{{team.name}}
{{team.description}}
edit
</li>
</ul>
Then you can create a route that responde to your url:
yourApp.config(['$routeProvider',
function($routeProvider) {
$routeProvider.
when('/teams', {
templateUrl: 'partials/team-list.html',
controller: 'TeamListCtrl'
}).
when('/teams/:teamId', {
templateUrl: 'partials/team-detail.html',
controller: 'TeamDetailCtrl'
}).
otherwise({
redirectTo: '/teams'
});
}]);
In this way from the detail controller (that will replace your EditCtrl) you can access the id parameter using: $routeParams.teamId
Anyway I suggest to study well all the tutorials for a better overview.

Related

How to pass a data like a database data or php constant data to display in a form in main.js

We build a custom bundle follow with this instructor https://blog.sulu.io/how-to-develop-a-bundle-in-the-sulu-admin-1
We need to know how to pass data from a database to render radio input choices or dropdown select.
We try to create an add/edit form and in the form, we have a radio and dropdown we made with hardcore in HTML file in Vendor/TransportationBundle/Resources/public/js/components/transportation/form/form.html
The code is
<div class="grid-row">
<label for="transportation-transportationType"><%= translations.transportationType %></label>
<div class="custom-radio">
<input name="transportationType" id="transportation-transportationType-1" type="radio"
class="form-element content-type" value="1" data-mapper-property="transportationType">
<span class="icon"></span>
</div>
<span class="clickable"><%= translations.private_shuttle %></span>
<div class="custom-radio">
<input name="transportationType" id="transportation-transportationType-2" type="radio"
class="form-element content-type" value="2" data-mapper-property="transportationType">
<span class="icon"></span>
</div>
<span class="clickable"><%= translations.shared_shuttle %></span>
<div class="custom-radio">
<input name="transportationType" id="transportation-transportationType-3" type="radio"
class="form-element content-type" value="3" data-mapper-property="transportationType">
<span class="icon"></span>
</div>
<span class="clickable"><%= translations.airplane %></span>
</div>
Is this have a way to change those radio to fetch the data from an array or a way to fetch the data from some controller action? or Have another way to use twig file with twig feature instead of html file?
Please provide a solution for us? Thank you
Sorry for my English.
You can e.g. check this Controller from the core. You can get data from wherever you want in the controller and pass it to the template:
<?php
class AcmeController {
public function testAction() {
$data = /* Get data somehow */;
return $this->render('template', ['data' => $data]);
}
}
Then you can access the data using the data twig variable in the rendered template.

Template not reactive in meteor on adding new data?

This are the event listeners for my two templates,specified in events.js
// event listeners on the addSiteForm template
Template.addCommentForm.events({
// this runs when they click the add button... you need to compete it
'click .js-add-comment':function(event){
var comment_text = $('#comment_input').val();// get the form value using jquery...
var user = 'anonymous person';
// the 'this' variable contains
// the data that this template is displaying
// which is the Website item
var site = this;
if (Meteor.user()){
user = Meteor.user().emails[0].address
}
var comment = {"text":comment_text,
"siteId":site._id,
"createdOn":new Date(),
"createdBy":user};// create a simple object to insert to the collectoin
Comments.insert(comment);
console.log("events start");
console.log("totla coomets are "+Comments.find({}).count()+"\n");
console.log("commenst in site "+Comments.find({siteId:site._id}).count()+"\n");
console.log("site id is "+site._id);
console.log("events end");
return false;
}
});
// event listeners on the addSiteForm template
Template.addSiteForm.events({
// this runs when they click the add button... you need to compete it
'click .js-add-site':function(event){
var url = $('#url_input').val();// get the form value using jquery...
var user = 'anonymous person';
if (Meteor.user()){
user = Meteor.user().emails[0].address
}
var site = {"url":url,
"createdOn":new Date(),
"createdBy":user};// create a simple object to insert to the collectoin
Websites.insert(site);
return false;
}
});
The router function is specified in router.js
Router.configure({
layoutTemplate: 'ApplicationLayout'
});
// the main route. showing the list of sites.
Router.route('/', function () {
this.render('siteList');
});
// this route is for the discussion page for a site
Router.route('/discussSite/:_id', function () {
var siteId = this.params._id;
site = Websites.findOne({_id:siteId});
this.render('discussSite', {data:site});
});
the main.js contain the collections
// shared code
Websites = new Mongo.Collection("websites");
Comments = new Mongo.Collection("comments");
helpers is
// this helper gets the data from the collection for the site-list Template
Template.siteList.helpers({
'all_websites':function(){
return Websites.find({});
},
'safer_email':function(email){
if (email.indexOf('#')!=-1){// we have an email
return email.split('#')[0];
}
else{// probably anonymouse.
return email;
}
}
});
Template.discussSite.helpers({
'comments':function(siteId){
//console.log("helper comments "+this.site);
// complete the code here so that it reruns
console.log(this.params.site._id);
return Comments.find({siteId:siteId});
// all the comments with a siteId equal to siteId.
}
});
the html file is in main.html.here it first displays the websites available in the webpage.On clicking this the user is routed to a new page.Here the user can add comments for the website
<head>
<title>week_4_peer_assessment</title>
</head>
<body>
</body>
<!-- this is the template that iron:router renders every time -->
<template name="ApplicationLayout">
<div class="container">
Home
{{>loginButtons}}
<h1>SiteAce - discuss your favourite websites</h1>
<!-- iron router will select what to render in place of yield-->
{{> yield }}
</div>
</template>
<template name="discussSite">
<h3>Discussing: {{url}} </h3>
{{> addCommentForm}}
<!-- write some code here that iterates through the comments and displays
the comment text and the author -->
<!-- clue - you have already written the 'comments' helper function -->
<ul>
{{#each comments}}
<li>{{text}} (added by {{safer_email createdBy}})
</li>
{{/each}}
</ul>
</template>
<template name="addCommentForm">
<div class="row">
<div class="col-lg-6">
<div class="input-group">
<input type="text" id="comment_input" class="form-control" placeholder="Enter your comment">
<input type="hidden" id="site_id" class="form-control" placeholder="Enter your comment">
<span class="input-group-btn">
<button class="btn btn-default js-add-comment" type="submit">Add!</button>
</span>
</div><!-- /input-group -->
</div><!-- /.col-lg-6 -->
</div>
</template>
<template name="siteList">
Fill in the form and click submit to add a site:
{{>addSiteForm}}
<h3>Sites you have added:</h3>
<ul>
{{#each all_websites}}
<li>{{url}} (added by {{safer_email createdBy}})
<br/>discuss
<br/>visit site
</li>
{{/each}}
</ul>
</template>
<template name="addSiteForm">
<div class="row">
<div class="col-lg-6">
<div class="input-group">
<input type="text" id="url_input" class="form-control" placeholder="Enter website URL...">
<span class="input-group-btn">
<button class="btn btn-default js-add-site" type="submit">Add!</button>
</span>
</div><!-- /input-group -->
</div><!-- /.col-lg-6 -->
</div>
</template>
The starup.js contains the start up code run by the server
Meteor.startup(function(){
if (!Websites.findOne()){// nothing in the database yet
var site = {"url":"http://www.google.com",
"createdOn":new Date(),
"createdBy":"Michael"};// create a simple object to insert to the collectoin
Websites.insert(site);
site = {"url":"http://www.yeeking.net",
"createdOn":new Date(),
"createdBy":"Janet"};// create a simple object to insert to the collectoin
Websites.insert(site);
site = {"url":"http://www.coursera.org",
"createdOn":new Date(),
"createdBy":"Jose"};// create a simple object to insert to the collectoin
Websites.insert(site);
}
});
This is what your template should be: (I removed safer_email. It was erroring. Not sure if it was something else you were working on.)
<template name="discussSite">
<h3>Discussing: {{url}} </h3>
{{> addCommentForm}}
<!-- write some code here that iterates through the comments and displays
the comment text and the author -->
<!-- clue - you have already written the 'comments' helper function -->
<ul>
{{#each comments}}
<li>{{text}} (added by {{createdBy}})</li>
{{/each}}
</ul>
</template>
helper:
your helper function is designed to take in siteId as an input, yet you are not passing one to it.
this._id or Router.current().params._id will get you the siteId that you are looking for. You'd used this.site._id which used to error out as this.site was not valid.You can further see what the this object contains by doing a console.log(this). That would have helped you sort this out faster.
'comments':function(){
console.log("site id in helper is ",this._id); // or Router.current().params._id;
console.log(Comments.find({siteId:this._id}).fetch());
return Comments.find({siteId:this._id});
}

Foundation 5 & Abide: a custom validator for a set of checkboxes?

I would like to create a validator for abide for a set of checkboxes.
Let's consider a set of 5 checkboxes. The user is asked to check 3 max, and at least 1.
So, here is my work-in-progress code:
<div data-abide-validator='checkboxes' data-abide-validator-values='1,3'>
<input type="checkbox"/>
<input type="checkbox"/>
<input type="checkbox"/>
<input type="checkbox"/>
<input type="checkbox"/>
</div>
<script>
$(document).foundation({
validators: {
checkboxes: function(el, required, parent) {
var countC = el.find(':checked').length;
alert(countC);
}
}
});
</script>
At this point, I just try to count the checked inputs. But it seems I can't even trigger the validator... I think I could manage to code my validation stuff if only I could figure out how to trigger it.
Indeed I didn't find many examples of the custom validator, and the official doc did not help me much.
Your HTML markup is not really "correct" for abide. You should be attaching the data-abide-validator attribute to the inputs, not the parent div. Additionally, you need some better markup so abide's default error display can work (and some better use of foundation's grid system to lay it out). I would point you toward the Abide Validation Page on Zurb's site for some examples of form markup.
I've taken the liberty of restructuring your markup to be something that is more becoming of a foundation layout:
<form action="/echo/html/" method="POST" data-abide>
<div class="row">
<div class="small-12 columns checkbox-group" data-abide-validator-limit="1,3">
<label>Check some boxes</label>
<small class="error">You have checked an invalid number of boxes.</small>
<ul class="small-block-grid-3">
<li>
<label>
<input type="checkbox" data-abide-validator="checkbox_limit" value="1" /> 1
</label>
</li>
<li>
<label>
<input type="checkbox" data-abide-validator="checkbox_limit" value="2" /> 2
</label>
</li>
<li>
<label>
<input type="checkbox" data-abide-validator="checkbox_limit" value="3" /> 3
</label>
</li>
<li>
<label>
<input type="checkbox" data-abide-validator="checkbox_limit" value="4" /> 4
</label>
</li>
<li>
<label>
<input type="checkbox" data-abide-validator="checkbox_limit" value="5" /> 5
</label>
</li>
</ul>
</div>
</div>
<div class="row">
<div class="small-12 columns">
<button type="submit">Submit</button>
</div>
</div>
</form>
As to your JS code. It's not correct either. You need to address the abide -> validators namespace of the options, not just validators. I've rewritten your JS code to not only do that, but give the desired effect you wanted:
$(document).foundation({
abide: {
validators: {
checkbox_limit: function(el, required, parent) {
var group = parent.closest( '.checkbox-group' );
var limit = group.attr('data-abide-validator-limit').split(',');
var countC = group.find(':checked').length;
if( countC >= limit[0] && countC <= limit[1] ) {
group.find('small.error').hide();
//return true so abide can clear any invalid flags on this element
return true;
} else {
group.find('small.error').css({display:'block'});
//return false and let abide do its thing to make sure the form doesn't submit
return false;
}
}
}
}
});
In order to check adjacent elements when doing custom validation, you need to have something to target. The el variable in the validation function will be the DOM element of the input/field that is being validated. The required variable will tell you if the field is flagged as being required or not (boolean). The parent variable will be set to the "parent" of the field. I say "parent" because although the label tag is technically the parent of the input element, abide is smart enough to realize that the label is part of the field's element structure and skip over it to the li element instead.
From there, you need a way to identify a common parent. So I added the checkbox-group class to whatever element I decided to make the "parent" of all the checkboxes in the group. This is not a Foundation or Abide "magic" class, but rather something of my own creation for use in the validation function.
From there, you can easily trace the few lines of the validation function to see the workflow: Find the group container object, parse the limits off the container's data-abide-validator-limits attribute, count the number of checked inputs in the container, check if the number checked is between the limits, display/hide the error message and return true/false so abide knows if the field validated or not.
I've got a working Fiddle of it if you care to check it out yourself ;) Hopefully this was informative for you, and I wish you the best of luck playing with the awesome that is Foundation!

How to use Parsley.js with dynamic content

I am using parsley.js 2.0.2. for client side form validation.
Now I noticed on the Parsley Website that parsley 2.x has dynamic form validation.
I have a form on my page with parsley. It works correctly and does validate. Now on the same page I have a link that dynamically adds a form from an external file. Issue is now parsley.js won't validate the newly added form.
On the parsley website they have an example where one can use JavaScript to validate but I tried it and it does not work. Here is the snippet code of the example:
<script src="jquery.js"></script>
<script src="parsley.min.js"></script>
<form id="form">
...
</form>
<script type="text/javascript">
$('#form').parsley();
</script>
I am aware that the content in the DOM changed but is there a way that I can tell parsley to validate this newly added form or something that will trigger the validation process?
I will appreciate the help!
Thanks
Here is my form on the index.php page (This form does successfully validate):
<form action="server.php" method="post" name="main-form" id="myForm" data-parsley-validate>
<div>
<label for="njsform-name">Name</label>
<input name="name" type="text" id="njsform-name" placeholder="Mike" data-parsley-required="true" data-parsley-minlength="2">
</div>
<div>
<label for="njsform-email">Surname</label>
<input name="email" type="text" id="njsform-email" placeholder="Gates" data-parsley-required="true" parsley-minlength="2">
</div>
<div class="submitWrap">
<input class="submit" type="submit" value="Apply Now" />
</div>
Here is the link that gets the external content
<ul class="services-list">
<li><a class="s-option" href="views/form-short_term_loans.php">My Link</a></li>
</ul>
Here is the code I am using to dynamically change the content (does successfully retrieve external form and populates):
$(document).ready(function() {
var hash = window.location.hash.substr(1);
var href = $('.services-list li a').each(function(){
var href = $(this).attr('href');
if(hash==href.substr(0,href.length-5)){
var toLoad = hash+'.html #form-section';
$('#form-section').load(toLoad)
}
});
$('.services-list li a').click(function(){
var toLoad = $(this).attr('href')+' #form-section';
$('#form-section').hide('fast',loadContent);
$('#load').remove();
$('#intro-section').append('<span id="load">Getting required form...</span>');
$('#load').fadeIn('normal');
window.location.hash = $(this).attr('href').substr(0,$(this).attr('href').length-5);
function loadContent() {
$('#form-section').load(toLoad,'',showNewContent())
}
function showNewContent() {
$('#form-section').show('normal',hideLoader());
}
function hideLoader() {
$('#load').fadeOut('normal');
}
return false;
});
});
The second form is just a duplicate but the form id is myForm2 and the name second-form
Add a call to
$('#xxxxxx').parsley();
After the load of the new form. With xxxxx the id of the new form inserted in the DOM

Facebook form post data not present on backend

I am attempting to post form data to my app using Facebook. My form is integrated with a dialog and I am using form.submit() to submit the form. Please see my code. The post data does not appear on the backend (e.g. load-cargo-radio, city-id, train-id), but the fb_sig* data does. Does anyone know if there are any caveats regarding posting form data with Facebook? Thanks!
Note: I have tried both using my server domain and my fb callback url for the form action. Neither works.
<div id="action_prompt">
Loading cargo...
</div>
<fb:js_string var="fbjs_load_cargo_select">
<div id="load_cargo_select">
<form id="load_cargo_select_form" action="http://railsacrosseurope.com/turn/load_cargo_select" method="POST">
<p>Your train has stopped in the city of Arhus.</p>
<p>Arhus produces the following goods:</p>
<ul>
<li>Dairy</li>
</ul>
<p>Your train is hauling the following goods:</p>
<ul>
<li>Timber</li>
</ul>
<p>What would you like to do?</p>
<input type="radio" id="load_cargo_radio" value="1">Load new goods</input>
<input type="radio" id="load_cargo_radio" value="2">Discard existing goods</input>
<input type="hidden" id="city_id" value="3" />
<input type="hidden" id="train_id" value="15" />
<input type="submit" id="submit" value="Submit" />
</form>
</div>
</fb:js_string>
.
.
.
<script type="text/javascript">
var dialog = new Dialog().showChoice('Load Cargo', fbjs_load_cargo_select, 'Okay', 'Pass');
dialog.onconfirm = function() {
// Submit the form if it exists, then hide the dialog.
frm = document.getElementById('load_cargo_select_form');
if (frm) { frm.submit(); }
dialog.hide();
};
dialog.oncancel = function() {
form = document.getElementById('redirect_form');
form.setAction('http://apps.facebook.com/rails_across_europe/turn/move_trains_auto/');
form.submit();
}
</script>
[/code]
The problem was not with Facebook. The problem was that I left out the "name" attribute for my input elements.