Loading different modal based on knockout.js value - html

So I have a table of people's information and I used codes that look something like below (people's location in this case):
<!-- ko foreach: filteredApplications -->
<div class="col-md-6">
<span>Location:</span>
<span data-bind="text: application.candidateLocation"></span>
</div>
to display location information for all people.
And when I click the "Preview Application" link, it is supposed to give me a modal like the attached image and show the information of the corresponding person.
I tried to remove the foreach knockout for the modal, but then it gives me an error saying that it cannot find the application.candidateLocation variable.
How do I have to approach this issue?
Please help!
EDIT (viewmodel):
public partial class Application
{
public dynamic JsonForm => new
{
CandidateLocation,
Job = this.Job.JsonForm,
CandidateStatus = this.CurrentStatuse.CandidateStatus,
};
public string CandidateLocation
{
get
{
switch (ApplicationCandidateType)
{
case ApplicationCandidateType.Standard:
return InsideApplication.CandidateApplication.Candidate.Location;
case ApplicationCandidateType.Guest:
return null;
case ApplicationCandidateType.Manual:
return null;
default:
throw new Exception("Unhandled ApplicationCandidateType");
}
}
}
function ViewModel() {
var self = this;
self.invite = ko.observable(false);
self.changeStylesInvite = function () {
self.invite(true);
}
self.notifications = ko.observableArray(#Html.Json(Model.Notifications.Select(o => o.JsonForm)) || []);
self.applications = ko.observableArray(#Html.Json(Model.ApplicationCompatibilities.Select(o => o.JsonForm)) || []);
self.applicationInvitations = ko.observableArray(#Html.Json(Model.ApplicationInvitations.Select(o => o.JsonForm)) || []);
self.applicationsFilter = ko.observable("new");
self.showHiddenApplications = ko.observable(false);
self.newApplicationsCount = ko.computed(function() {
return ko.utils.arrayFilter(self.applications(), function(i) {
return !i.application.isShortlisted && !i.application.isContactInfoSent && (self.showHiddenApplications() || !i.application.isHidden);
}).length;
});
self.shortlistedApplicationsCount = ko.computed(function() {
return ko.utils.arrayFilter(self.applications(), function(i) {
return i.application.isShortlisted && (self.showHiddenApplications() || !i.application.isHidden);
}).length;
});
self.connectedApplicationsCount = ko.computed(function() {
return ko.utils.arrayFilter(self.applications(), function(i) {
return i.application.isContactInfoSent && (self.showHiddenApplications() || !i.application.isHidden);
}).length;
});
self.allApplicationsCount = ko.computed(function() {
return ko.utils.arrayFilter(self.applications(), function(i) {
return (self.showHiddenApplications() || !i.application.isHidden);
}).length;
});

Related

I want to filter the list which i'm retrive the list of sobject and filter to remove the name starts with skyvvasolution__?

I have make field with picklist value and retrieve the sobject list and show in the form but with list i got the other custom object to that i don't want to show.
Component:
this is just a component to show the list.
<div class="slds-form-element slds-size_1-of-2 slds-float_left slds-p-around_xx-small">
<lightning:select name="Objects" label="Select SObject:" aura:id="onjId" value="
{!v.selectedValue}">
<aura:iteration aura:id="list" items="{!v.option}" var="objectname">
<option value="{!objectname}" text="{!objectname}"/>
</aura:iteration>
</lightning:select>
</div>
Controller:
helper.getObjectTypePicklist(component);
helper:(in comment I tried but not get the result)
getObjectTypePicklist: function(component) {
var action = component.get("c.getObjectName");
// var list = component.get("v.option");
// component.find("list").set("v.option", Replace(list,'Select Name Where
%skyvvasolutions__',''));
// action.setParams({
// Replace(list, 'skyvvasolutions__', '')
// });
action.setCallback(this, function(response) {
var state = response.getState();
if (state === "SUCCESS") {
var allValues = response.getReturnValue();
component.set("v.option", allValues);
}
else if (state === "ERROR") {
var errors = response.getError();
if (errors) {
if (errors[0] && errors[0].message) {
console.log("Error message: " +
errors[0].message);
}
}
else {
console.log("Unknown Error");
}
}
});
$A.enqueueAction(action);
}
Controller:
#AuraEnabled
public static List<String> getObjectName(){
List<String> objects=new List<String>();
List<Schema.SObjectType> gd = Schema.getGlobalDescribe().Values();
for(SObjectType sot:gd){
objects.add(sot.getDescribe().getName());
objects.sort();
}
return objects;
}
I just want to remove names from my list which starts with the skyvvasolution__

AngularJS + Parse REST API - Paging through more than 1,000 results

Im using Parse REST API + AngularJS and Im trying to be able to get more than 1000 items per query. I try to develop a recursive function and concatenate each query until I get all the data. My problem is that I am not able to concatenate the JSON objects successfully. Here is what I have:
$scope.getAllItems = function(queryLimit, querySkip, query) {
$http({method : 'GET',
url : 'https://api.parse.com/1/classes/myClass',
headers: { 'X-Parse-Application-Id':'XXX','X-Parse-REST-API-Key':'YYY'},
params: {limit:queryLimit, skip:querySkip},
}).success(function(data, status) {
query.concat(data.results);
if(query.lenth == queryLimit) {
querySkip += queryLimit;
queryLimit += 100;
$scope.getAllItems(queryLimit, querySkip, query);
} else {
$scope.clients = query;
}
})
.error(function(data, status) {
alert("Error");
});
};
var myQuery = angular.toJson([]); //Am I creating an empty JSON Obj?
$scope.getAllItems(100,0, myQuery);
Is there any better solution to achieve this?
There may be better, more concise ideas available, but this is what I worked out for myself.
In my service ...
fetch : function(page, perpage) {
var query = // build the query
// the whole answer to your question might be this line:
query.limit(perpage).skip(page*perpage);
return query.find();
},
fetchCount : function() {
var query = // build the same query as above
return query.count();
},
In the controller...
$scope.page = 0; // the page we're on
$scope.perpage = 30; // objects per page
MyService.fetchCount().then(function(count) {
var pagesCount = Math.ceil(count / $scope.perpage);
$scope.pages = [];
// pages is just an array of ints to give the view page number buttons
for (var i=0; i<pagesCount; i++) { $scope.pages.push(i); }
fetch();
});
function fetch() {
return MyService.fetch($scope.page, $scope.perpage)).then(function(results) {
$scope.results = results;
});
}
// functions to do page navigation
$scope.nextPage = function() {
$scope.page += 1;
fetch();
};
$scope.prevPage = function() {
$scope.page -= 1;
fetch();
};
$scope.selectedPage = function(p) {
$scope.page = p;
fetch();
};
Then paging buttons and results in my view (bootstrap.css)...
<ul class="pagination">
<li ng-click="prevPage()" ng-class="(page==0)? 'disabled' : ''"><a>«</a></li>
<li ng-repeat="p in pages" ng-click="selectedPage(p)" ng-class="(page==$index)? 'active' : ''"><a>{{p+1}}</a></li>
<li ng-click="nextPage()" ng-class="(page>=pages.length-1)? 'disabled' : ''"><a>»</a></li>
</ul>
<ul><li ng-repeat="result in results"> ... </li></ul>
I fixed my recursive function and now its working. Here it is:
$scope.getAllItems = function(queryLimit, querySkip, query, first) {
$http({method : 'GET',
url : 'https://api.parse.com/1/classes/myClass',
headers: { 'X-Parse-Application-Id':'XXX','X-Parse-REST-API-Key':'YYY'},
params: {limit:queryLimit, skip:querySkip},
}).success(function(data, status) {
if(first) {
query = data.results;
first = !first;
if(query.length == queryLimit) {
querySkip += queryLimit;
$scope.getAllItems(queryLimit, querySkip, query, first);
} else {
$scope.clients = query;
}
} else {
var newQ = data.results;
for (var i = 0 ; i < newQ.length ; i++) {
query.push(newQ[i]);
}
if(query.length == queryLimit + querySkip) {
querySkip += queryLimit;
$scope.getAllItems(queryLimit, querySkip, query, first);
} else {
$scope.clients = query;
}
}
})
.error(function(data, status) {
alert("Error");
});
};
Simply pushed each element to my empty array, also I was mutating queryLimit instead of querySkip in order to iterate through all the elements.

Angularjs ajax request in Symfony2 and Doctrine json response with relationships

I am trying to work with Symfony2, Doctrine and Angujarjs. There is no problem with Symfony2 or Doctrine but I have issues using an ajax request with angularjs. Either it doesn't load anything and I did make a mistake while loading the json (json comes from Symfony and its working) or if it's working, but the json doesn't contain any of the relationship's data.
So, what's the correct way to
A: create a response for angularjs with relationship data (such as articles and categories)
B: load the requested json into an angularjs variable
Here is my controller.js
var app = angular.module("MyApp", []) .config(['$interpolateProvider', function ($interpolateProvider) {
$interpolateProvider.startSymbol('[[');
$interpolateProvider.endSymbol(']]');
}]);
app.filter('offset', function() {
return function(input, start) {
start = parseInt(start, 10);
return input.slice(start);
};
});
app.filter('htmlToPlaintext', function() {
return function(text) {
return String(text).replace(/<[^>]+>/gm, '');
};
});
app.controller("PaginationCtrl", function($scope, $http) {
$scope.articlesPerPage = 8;
$scope.currentPage = 0;
function htmlToPlaintext(text) {
return String(text).replace(/<[^>]+>/gm, '');
}
// this should load the json from '/admin/jsonallarticles' into the articles variable
$http.get('/admin/jsonallarticles').success(function(data) {
$scope.articles = data;
});
$scope.range = function() {
var rangeSize = 5;
var ret = [];
var start;
start = $scope.currentPage;
if ( start > $scope.pageCount()-rangeSize ) {
start = $scope.pageCount()-rangeSize+1;
}
for (var i=start; i<start+rangeSize; i++) {
ret.push(i);
}
return ret;
};
$scope.prevPage = function() {
if ($scope.currentPage > 0) {
$scope.currentPage--;
}
};
$scope.prevPageDisabled = function() {
return $scope.currentPage === 0 ? "disabled" : "";
};
$scope.pageCount = function() {
return Math.ceil($scope.articles.length/$scope.articlesPerPage)-1;
};
$scope.nextPage = function() {
if ($scope.currentPage < $scope.pageCount()) {
$scope.currentPage++;
}
};
$scope.nextPageDisabled = function() {
return $scope.currentPage === $scope.pageCount() ? "disabled" : "";
};
$scope.setPage = function(n) {
$scope.currentPage = n;
};
});
This is my symfony2 function
public function jsonallarticlesAction() {
$articles = $this->getDoctrine()
->getRepository('AcmeBlogBundle:Articles');
if ( !$articles ) {
throw $this->createNotFoundException(
'Keine Beiträge gefunden!');
}
$queryArticles = $articles->createQueryBuilder('a')
->where('a.status = :status')
->setParameter('status', 0)
->orderBy('a.createdDate', 'DESC')
->getQuery()
->getResult(\Doctrine\ORM\Query::HYDRATE_ARRAY);;
$articles = array_values($queryArticles);
$response = new Response();
$response->setContent(json_encode($articles));
$response->headers->set('Content-Type', 'application/json');
return $response;
}
EDITED CONTROLLER
I tried using the serializer which comes with Symfony
$encoders = array(new XmlEncoder(), new JsonEncoder());
$normalizers = array(new GetSetMethodNormalizer());
$serializer = new Serializer($normalizers, $encoders);
$articles = $this->getDoctrine()
->getRepository('AcmeBlogBundle:Articles')
->findAll();
if ( !$articles ) {
throw $this->createNotFoundException(
'Keine Artikel gefunden!');
}
$serializer->serialize($articles, 'json');
return new Response(json_encode($json));
But I receive an error:
A circular reference has been detected (configured limit: 1).
For work with Angular.js you must write Rest API. For this you can use https://github.com/FriendsOfSymfony/FOSRestBundle
And for serialize your entities with needed data use http://jmsyst.com/bundles/JMSSerializerBundle
It compatible with FOSRestBundle.
As example of use those bundles you can look one our project https://github.com/stfalcon-studio/lost-and-found
I ran into the same issue and it was due to the fact that my Entity was related back to the same entity from my second entity on a different field. I just simply created this function in my Entity:
public function removeRelationsThatCauseCircularError()
{
$this->companyEvents = NULL;
}
And run the function before going through the serializer.

How can I aggregate when I'm mapping in KnockoutJS?

I'm working with KnockoutJS for a few days now and I have just faced with a simple problem that I cannot solve!
I have a model like this:
function Contact() {
var self = this;
self.name = ko.observable("");
self.phones = ko.observableArray([]);
self.faxes = ko.observableArray([]);
self.address = ko.observable("");
}
I have to call a service which will return repeatitive rows if each contact contains more that one phone or fax. e.g. :
{{"name":"Name1","phone":"1234","fax":"5654","address":"abc"},{{"name":"Name1","phone":"2323","fax":"8787","address":"abc"}}
I do a call like to server like this:
self.GetContacts = function () {
$.getJSON(self.queryUrl(),
function (data) {
if (data.results) {
self.contacts(ko.toJS(data.results));
}
});
There is no way to aggregate it on the serverside as it is an out-of-the-box tool and the only possible way is to aggregate it on the client side.
How can I aggregate them using my custom model, before binding them?
I would do something like that :
function aggragateContacts(data) {
var contacts = [];
ko.utils.arrayForEach(data, function (contactData) {
// looking an existing contact with the same name and address
var contact = ko.utils.arrayFirst(contacts, function (c) {
return c.name() == contactData.name && c.address() == contactData.address;
});
// otherwise create one
if (contact == null) {
contact = new Contact();
contact.name(contactData.name);
contact.address(contactData.address);
contacts.push(contact);
}
contact.phones.push(contactData.phone);
contact.fax.push(contactData.fax);
});
}
self.GetContacts = function () {
$.getJSON(self.queryUrl(),
function (data) {
if (data.results) {
self.contacts(aggragateContacts(ko.toJS(data.results)));
}
})
}

kendo treeview with new data source

Ok, so I have this situation here:
A CSHTML view with a kendo tree in it:
#(Html.Kendo().TreeView()
.Name("treeview")
.DataTextField("Name")
.DataSource(d => d.Read(r => r.Action("WorkedHours", "TaskManager")))
.Events(e => e.Select("onSelect"))
)
to the right of that there is a kendo grid. and above the tree there is a (kendo) dropdown list to select a user.
this is the controller method called by the tree:
public JsonResult WorkedHours(uint? id)
{
DocObjectArray docObjects = null;
if (id == null)
{
// get root elements
var loggedInUserRef = OmanagerUtils.GetInstance().LoggedInUser;
if (loggedInUserRef != null && loggedInUserRef.GetObject() != null && loggedInUserRef.GetObject().SubObjects != null)
{
for (int i = 0; i < loggedInUserRef.GetObject().SubObjects.GetLength(); i++)
{
var item = loggedInUserRef.GetObject().SubObjects.GetAt(i);
if (item.ToString() == TaskManagerConstants.UserWorkHours)
{
docObjects = item.TreeSubObjects;
break;
}
}
}
}
else
{
// get sub objects of a root object
var rootObj = new DocObjectRef((int)id);
docObjects = rootObj.GetObject().TreeSubObjects;
}
var returnDocObjects = new List<OmanagerItem>();
for (int i = 0; i < docObjects.GetLength(); i++)
{
var item = docObjects.GetAt(i);
var hasChildren = true;
if (item.TreeSubObjects == null)
{
hasChildren = false;
}
else
{
if (item.TreeSubObjects.GetLength() == 0)
{
hasChildren = false;
}
}
var listItem = new OmanagerItem
{
hasChildren = hasChildren,
id = item.GetOID(),
Name = item.ToString()
};
returnDocObjects.Add(listItem);
}
return Json(returnDocObjects, JsonRequestBehavior.AllowGet);
}
now, the problem is that i have to be able to select a user from the dropdown list and refresh the tree with this new data.
$("#employee").kendoDropDownList({
change: function () {
var postdata = {
id:$("#employee").val()
}
$.ajax({
url: "TaskManager/WorkedHours",
cache: false,
type: "POST",
data: postdata,
success: function (data) {
$("#treeview").data("kendoTreeView").setDataSource(data);
},
});
}
});
the problem is what do i do with this data? because my attempt did not really work.
many thanks.
You can use OutputCache attribute on WorkedHours action:
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "None")]
public JsonResult WorkedHours(uint? id)
{
// rest of method
}
It helped in my case :)
Maybe this little snippet is of any help to you.
Similar to your code in the change event of my dropdown I'm calling a function that will change the request data of my TreeView DataSource.
After changing it, it calls the read() handler of the datasource so it re-reads the data:
function loadTreeViewData() {
var employee = $('#employee').getKendoDropDownList().dataItem();
WorkedHoursDataSource.transport.options.read.data = {Employee_Id:employee.id};
WorkedHoursDataSource.read();
}