Backbone model is not getting populated - javascript

app.Model.BrandModel = Backbone.Model.extend({
idAttribute: 'brandId',
defaults: {
name : '',
description : '',
brandImage : '',
user : '',
showPro : false,
proDescription : ''
},
url : function(){
return '/rest/brands/' + brandId;
}
});
I can see from firebug that my my server is returning the following JSON response.Also the request is successful.
brandId "fc692c70-4096-11e3-a0f2-3c970e02b4ec"
name "Galeria"
user "940ee800-4090-11e3-80c0-3c970e02b4ec"
description "This is galeria"
brandImage "/brand-images/fc692c70-...3-a0f2-3c970e02b4ec.jpg"
proDescription ""
showPro false
I am calling like this.
var brandModel = new app.Model.BrandModel();
brandModel.fetch();
but my model is not getting populated and the values are still default one.
my controller
#RequestMapping(value = "/rest/brands/{brandId}",
method = RequestMethod.GET,
produces = "application/json")
#ResponseBody
public Brand getBrand(#PathVariable("brandId") String brandId, HttpServletResponse response) {

I don't see where you are telling your code WHICH brandId to fetch... Have you tried this?
var brandModel = new app.Model.BrandModel({brandId: "fc692c70-4096-11e3-a0f2-3c970e02b4ec"});
brandModel.fetch();
More information: How do I fetch a single model in Backbone?

fetch performs an asynchronous HTTP (Ajax) request, so I passeed fetch a success callback and now i am seeing the modal values.
brandModel.fetch({
success: function(){
console.log(brandModel.toJSON());
}
});

Should be:
app.Model.BrandModel = Backbone.Model.extend({
idAttribute: 'brandId',
urlRoot : '/rest/brands/',
defaults: {
name : '',
description : '',
brandImage : '',
user : '',
showPro : false,
proDescription : ''
}
});
Then like #David mentioned:
var brandModel = new app.Model.BrandModel({brandId: "fc692c70-4096-11e3-a0f2-3c970e02b4ec"});
brandModel.fetch();

Also return '/rest/brands/' + brandId; probably should be return '/rest/brands/' + this.get("brandId");

Related

Laravel cannot retrieve data from multiple model with Ajax

Hi I am beginner with Ajax at the Laravel. I wanted to fetch data with Laravel Eagerload function to my blade modal.
This is my Expenses Model
protected $fillable = [
'name',
'surname',
'email',
'password',
'status',
'role',
];
protected $hidden = [
'password',
'remember_token',
];
public function Expense () {
return $this->hasMany(ExpensesModel::class);
}
This is my Expenses Model
`
{
use HasFactory;
protected $table = 'expenses';
protected $fillable = [
'id',
'emp_id',
'expense_input_date',
'expense_type',
'expense_category',
'reason',
'status'
];
public function UserExpense () {
return $this->belongsTo(User::class, 'emp_id' );
}
My controller
This is My controller function
public function edit (Request $request) {
$req_id = array('id' => $request->id);
if($request->ajax()) {
$employee = ExpensesModel::with('UserExpense')->where('id' ,$req_id)->first();
return response()->json($employee);
}
}
This is my blade script
`
function editFunc(id){
$.ajax({
type:"POST",
url: "{{ url('/expenses/advancedtable/edit') }}",
data: { id: id },
dataType: 'json',
success: function(res){
$('#EmployeeModal').html("Edit Employee");
$('#employee-modal').modal('show');
$('#id').val(res.id);
$('#emp_id').val(res.name);
$('#expense_input_date').val(res.expense_input_date);
$('#expense_type').val(res.expense_type);
$('#expense_category').val(res.expense_category);
$('#expense_slip_no').val(res.expense_slip_no);
$('#expense_amount').val(res.expense_amount);
$('#currency').val(res.currency);
$('#description').val(res.description);
}
});
}
I tried everyting but it does not work. I wanted to retrive user name from User Model by using foreign key on the Expenses model emp_id.
is there something I missed somewhere can you help me with this.
Thank you.
Here how its work.
First of all change relationship in your User and Expenses model like this.
// User Model
public function userExpense() {
return $this->hasMany(ExpensesModel::class,'emp_id','id');
}
// ExpensesModel
public function user() {
return $this->hasOne(User::class,'id','emp_id');
}
Then change your controller function.
// controller function
public function edit (Request $request) {
$req_id = $request->id;
$employeeExpense = ExpensesModel::with('user')->where('id' ,$req_id)->first();
return response()->json($employeeExpense);
}
Then change your ajax sucess function.
// ajax sucsess function
success: function(res) {
console.log(res); // to view your response from controller in webbrowser's console
$('#EmployeeModal').html("Edit Employee");
$('#employee-modal').modal('show');
$('#id').val(res.id);
$('#emp_id').val(res.user.name); // it will print user name
$('#expense_input_date').val(res.expense_input_date);
$('#expense_type').val(res.expense_type);
$('#expense_category').val(res.expense_category);
$('#expense_slip_no').val(res.expense_slip_no);
$('#expense_amount').val(res.expense_amount);
$('#currency').val(res.currency);
$('#description').val(res.description);
}
when you use 'with' eloqunt method it will add relationship function name to your query result, so you want to get user details then you should be do like res.user.userfield this is applicable for hasOne only.
For other relationship you will refer to this https://laravel.com/docs/9.x/eloquent-relationships

How to get push id uniquely

I'm building a forum, and I'm in the step of views. I have this (simplified) code:
//Setting Views
//Adding Them..
$scope.views = $firebaseObject(refService.ref().child("Topics"))
refService.ref().child("Topics").once("value", function(snapshot) {
snapshot.forEach(function(childSnapshot) {
var key = childSnapshot.key();
var childData = childSnapshot.val();
if(childData.DateCreated == $stateParams.DATE && childData.Email == $stateParams.EMAIL){
refService.ref().child("Topics").child(childData.pushKey).child("Views").child(currentAuth.uid).set({
Views : true
})
}
})
})
//Viewing them
$scope.viewableView = $firebaseObject(refService.ref().child("Topics"))
As you can see adding the views was pretty easy job. And I did it correctly. The problem is with displaying the number of views, and I have to do it using AngularFire's $firebaseObject, or $firebaseArray... Here is the structure in database:
{
"Topics" : {
"-KG9rDNLZksJDiLfAXwH" : {
"Avatar" : "http://cs624223.vk.me/v624223037/2b1bb/GRTKddkmXiw.jpg",
"DateCreated" : 1461544873669,
"Email" : "abogale2#gmail.com",
"Title" : "Check",
"UID" : "3caf2136-7a2d-4ae4-a4a9-119f2b08133c",
"Username" : "BruhBrhu",
"Value" : "Check",
"Views" : {
"3caf2136-7a2d-4ae4-a4a9-119f2b08133c" : {
"Views" : true
}
},
"pushKey" : "-KG9rDNLZksJDiLfAXwH"
}
},
"UserAuthInfo" : {
"3caf2136-7a2d-4ae4-a4a9-119f2b08133c" : {
"BronzeBadge" : 0,
"Description" : "Just a wierd 15 year old coder...",
"Email" : "abogale2#gmail.com",
"GoldBadge" : 0,
"Image" : "http://cs624223.vk.me/v624223037/2b1bb/GRTKddkmXiw.jpg",
"Moderator" : false,
"Password" : "KfUcQ1yedOi1gEnGP6i1KQ==",
"PlatinumBadge" : 0,
"SilverBadge" : 0,
"UID" : "3caf2136-7a2d-4ae4-a4a9-119f2b08133c",
"Username" : "BruhBrhu"
}
}
}
As you can see I used push(), to get the topic.. My Concern now is how to view the topics! Please Help! I can't think of a "algorithm" to do it!
Mind you, all of the topics have unique ID's. I have to get the specific ID The user is in.
This worked for me:
refService.ref().child("Topics").once("value", function(snapshot) {
snapshot.forEach(function(childSnapshot) {
var key = childSnapshot.key();
var childData = childSnapshot.val();
if(childData.DateCreated == $stateParams.DATE && childData.Email == $stateParams.EMAIL){
refService.ref().child("Topics").child(childData.pushKey).child("Views").on("value", function(snapshot){
console.log(snapshot.numChildren())
$scope.countViews = snapshot.numChildren();
})
}
})
})
I dont know how but somehow $scope.countViews, became three way binded to my HTML, so it actually shows!
You're nesting keys inside an object, which the Firebase documentation explicitly recommends against.
But it can work once you realize that you can also add methods to the scope:
var app = angular.module('app', ['firebase']);
app.constant('FB_URL', 'https://yours.firebaseio.com/');
app.controller('MainCtrl', function(FB_URL, $scope, $firebaseArray, $firebaseObject) {
var ref = new Firebase(FB_URL);
$scope.topics = $firebaseArray(ref.child('Topics'));
$scope.getCount = function(obj) {
return Object.keys(obj).length;
};
});
And the view:
<body ng-controller='MainCtrl'>
<ol><li ng-repeat='topic in topics'>{{topic.Title}} - {{topic.Username}} - {{getCount(topic.Views)}}</li></ol>
</body>
Working jsbin: http://jsbin.com/dapoga/edit?html,js,output

Meteor using namedContext to addInvalidKeys to an AutoForm form returning an error

I have the following SimpleSchema where I am trying to add custom validation to validate against entering duplicate customer name, yet whenever I try to save a new customer I get error:
Exception in delivering result of invoking
'adminCheckNewCustomerName': TypeError: Cannot read property
'namedContext' of null
can someone please tell me what I am doing wrong / missing here to validate the customer name against duplicate records? Thanks
schema.js:
AdminSection.schemas.customer = new SimpleSchema({
CustomerName: {
type: String,
label: "Customer Name",
unique: true,
custom: function() {
if (Meteor.isClient && this.isSet) {
Meteor.call("adminCheckNewCustomerName", this.value, function(error, result) {
if (result) {
Customer.simpleSchema().namedContext("newCustomerForm").addInvalidKeys([{
name: "CustomerName",
type: "notUnique"
}]);
}
});
}
}
}
});
UI.registerHelper('AdminSchemas', function() {
return AdminSection.schemas;
});
form.html:
{{#autoForm id="newCustomerForm" schema=AdminSchemas.customer validation="submit" type="method" meteormethod="adminNewCustomer"}}
{{>afQuickField name="CustomerName"}}
<button type="submit" class="btn btn-primary">Save Customer</button>
{{/autoForm}}
collections.js:
this.Customer = new Mongo.Collection("customers");
Check collection2 code for fetching the schema attached to a collection:
_.each([Mongo.Collection, LocalCollection], function (obj) {
obj.prototype.simpleSchema = function () {
var self = this;
return self._c2 ? self._c2._simpleSchema : null;
};
});
This cryptic homonym _c2 (one of two hard things in programming...) comes from attachSchema:
self._c2 = self._c2 || {};
//After having merged the schema with the previous one if necessary
self._c2._simpleSchema = ss;
Which means that you have forgotten to attachSchema or fiddled with the property of your collection.
To solve:
Customer.attachSchema(AdminSchemas.customer);
//Also unless this collection stores only one customer its variable name should be plural

regarding AJAX, symfony2 - contollerAction

i called a controllerAction in symfony2 from jquery script in twig template for form validation and verification. After a successful response i called another controller from jquery script using $.post() for rendering a template for user-dashboard. but all i am getting is a template displayed in console but not in the user browser window. How to achieve this in the above stated way. ??
Thanks for help (in advance)
AKSHAT.
<script>
// my jquery code
$(document).ready(function()
{
$('.sign_in_box').click(function()
{
var data = new Object();
data.email=$('.email_txt').val();
data.password=$('.pwd_txt').val();
$.ajax('{{ path('login_login_validation') }}', {
type : 'POST',
data : data,
success : function(response){
var json = JSON.parse(response);
var flag = json.success;
if(flag)
{
$('#pwd_login_error').css('opacity' , '0');
$('#email_login_error').css('opacity' , '0' );
$.ajax('{{ path('login_login_verification') }}',{
type : 'POST',
data : data,
success : function(response){
var login = JSON.parse(response);
if(login.login)
{
alert("login success");
$.post('{{ path('login_dashboard') }}', data);
}
else
{
$('#pwd_login_error').css('opacity' , '0.5' );
}
}});
}
else
{
$('#pwd_login_error').css('opacity' , '0' );
$('#email_login_error').css('opacity' , '0.5' );
}
}
});
});
});
</script>
//////////////////////////////////////////////////////////////////////////////////////////////////////////
// controller
<?php
namespace Login\Bundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
class DashboardController extends Controller
{
public function indexAction()
{
$email = $this->get('request')->get('email');
return $this->render('LoginBundle:Dashboard:index.html.twig', array('email'=> $email));
}
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////
// routing file
login_homepage:
pattern: /
defaults: { _controller: LoginBundle:Homepage:index }
login_login_validation:
pattern: /ajax_validate
defaults: { _controller: LoginBundle:Login:validation }
login_login_verification:
pattern: /ajax_verify
defaults: { _controller: LoginBundle:Login:verification }
login_dashboard:
pattern: /dashboard
defaults: { _controller: LoginBundle:Dashboard:index }
/////////////////////////////////////////////////////////////////////////////////////////////////////////////
// twig file
{% block message %}
hello ! {{ email | json_encode | raw }}
welcome to dashboard .
{% endblock%}
The only wrong thing is this your are rendering the index page . after successfull login you have to redirect you page by
window.location = "http://somewhereelse.com";
Or You can also append data in any div , Its on to you which way you want to follow .

How to use the Ember.Select value to filter JSON?

I want to filter my JSON using Ember.Select value instead of hardcoding it. Here's my App.js
App = Ember.Application.create({});
App.IndexRoute = Ember.Route.extend({
renderTemplate : function(controller) {
this.render('MyApp', {
controller : controller
});
},
model : function() {
return App.MyTemplateModel.find();
}
});
App.IndexController = Ember.ArrayController.extend({
filteredContent : Ember.computed.oneWay("content"),
last : function() {
var filtered = this.get('content').filterProperty('last_name', "Solow");
this.set("filteredContent", filtered);
}
});
App.MyTemplateModel = Ember.Model.extend({
id : Ember.attr(),
last_name : Ember.attr(),
first_name : Ember.attr(),
suffix : Ember.attr(),
expiration : Ember.attr()
});
App.controller = Ember.Object.create({
selectedProgrammer : null,
content : [Ember.Object.create({
last_name : "Solow",
id : 1
}), Ember.Object.create({
last_name : "Tom",
id : 2
})]
});
App.MyTemplateModel.url = "http://ankur1.local/index.php/api/example/users/";
App.MyTemplateModel.adapter = Ember.RESTAdapter.create();
var existing = App.MyTemplateModel.find();
App.MyTemplateModel.camelizeKeys = true;
In the line,
var filtered = this.get('content').filterProperty('last_name', "Solow");
I am harcoding "Solow" but I want to use Ember.Select value.
I tried doing this,
var selectedProgrammer = App.controller.get("selectedProgrammer");
var filtered = this.get('content').filterProperty('lastName', App.controller.get('selectedProgrammer'));
this.set("filteredContent", filtered);
But it does nothing & moreover, here's what I am doing on HTML,
<script type="text/x-handlebars" data-template-name="MyApp">
{{#each item in filteredContent }}
<tr><td>
{{id}} <p> {{item.first_name}} {{item.expiration}}</p>
</td></tr>
{{/each}}
<button {{action last}}>filter</button>
{{view Ember.Select
contentBinding="App.controller.content"
optionValuePath="content.id"
optionLabelPath="content.last_name"
selectionBinding="App.controller.selectedProgrammer"}}
</script>
Furthermore, here's a sample of JSON, http://pastebin.com/7dyNQi4K
Where I might be wrong or What changes I might have to make?
Your Ember.Select is bound to App.controller.selectedProgrammer, when the select changes, it will receive an object. So in your controller you access the last_name property from that object using App.controller.get('selectedProgrammer.last_name').
App.IndexController = Ember.ArrayController.extend({
filteredContent : Ember.computed.oneWay("content"),
last : function() {
var lastName = App.controller.get('selectedProgrammer.last_name');
var filtered = this.get('content').filterProperty('last_name', lastName);
this.set("filteredContent", filtered);
}
});

Categories

Resources