Angular clone object from function - json

I try clone my response json, but the id is the same..
I want to clone an item in my json to facilitate the addition of content.
The problem is following the same ID, then the answer is to update and no new item ..
the function:
$scope.cloneItem = function(id) {
$scope.itemtoclone = allDB.get({section: section, id: id}, function(){
$scope.itemnew = new allDB({section: section});
$scope.itemnew = angular.copy($scope.itemtoclone);
$scope.itemnew.$save(function(){
$mdToast.show($mdToast.simple({position: 'top right'}).content('Clone criado!'));
});
});
}
and the response:
GET http://localhost:5000/posts/25 304 Not Modified 7ms
POST http://localhost:5000/25 201 Created 2ms
json object to clone:
{
"id": 25,
"title": "Willian busca protagonismo igual ao de Neymar: \"Sempre joguei assim\"",
"subtitle": "Com 94% de aproveitamento nos passes na estreia da Copa América, jogador tem chamado a
responsabilidade e dividido a missão de criar os lances com o camisa 10",
"slug": "brasil-post-1",
"published": true,
"originalDate": "2015-06-16T03:00:00.000Z",
"excerpt": "Com 94% de aproveitamento nos passes na estreia da Copa América",
"$promise": {},
"$resolved": true,
"cats": [
2,
3,
4,
5,
7
]
}
Resolved, It was not quite what I wanted, but I help!
$scope.cloneItem = function(id) {
$scope.getclone = allDB.get({section: section, id: id}, function(response){
console.log(response);
$scope.itemnew = new allDB({section: section});
$scope.itemnew.title = response.title;
$scope.itemnew.subtitle = response.subtitle;
$scope.itemnew.excerpt = response.excerpt;
$scope.itemnew.$save(function(){
$mdToast.show($mdToast.simple({position: 'top right'}).content('Clone criado!'));
});
});
}

Related

How to bind a model json to a comboBox in controller?

I want to bind a model json with a comboBox inside the controller (not in a xml view).
I made a model Json called types.json and I passed to the controller, but, when I bind the values inside the created model to the combobox, didn't show nothing.
Can you please help me. I can't find the problem here.
That is parts of my code, below, who I think is important to this question.
my MODEL JSON - name: types.json
"types": [
{
"text": "Férias",
"key": "01"
},
{
"text": "something",
"key": "02"
},
]
my CONTROLLER - name: Page.controller.js
handleAppointmentCreate: function (oEvent) {
var oStartDate = oEvent.getParameter("startDate"),
oEndDate = oEvent.getParameter("endDate"),
oCalendarRow = oEvent.getParameter("calendarRow"),
oEmpId = oCalendarRow.getKey(),
_oYearStartDate = oStartDate.getFullYear(),
_oMonthStartDate = oStartDate.getMonth() + 1,
_oDateStartDate = oStartDate.getDate(),
_oYearEndDate = oEndDate.getFullYear(),
_oMonthEndDate = oEndDate.getMonth() + 1,
_oDateEndDate = oEndDate.getDate(),
_HourStart = oStartDate.getHours(),
_oMinStart = oStartDate.getMinutes(),
_oSecStart = oStartDate.getSeconds(),
_oHourEnd = oEndDate.getHours(),
_oMinEnd = oEndDate.getMinutes(),
_oSecEnd = oEndDate.getSeconds(),
sStartDate = _oYearStartDate + "-" + _oMonthStartDate + "-" + _oDateStartDate,
sEndDate = _oYearEndDate + "-" + _oMonthEndDate + "-" + _oDateEndDate,
sStartHour = _HourStart + ":" + _oMinStart + ":" + _oSecStart,
sEndHour = _oHourEnd + ":" + _oMinEnd + ":" + _oSecEnd,
sIdEmp = oEmpId;
var dataModel = this.getOwnerComponent().getModel("Model");
this.getView().setModel(dataModel, "DataModel");
if (!this.oConfirmDialog) {
this.oConfirmDialog = new Dialog({
type: DialogType.Message,
title: "Novo agendamento",
content: [
new HorizontalLayout({
content: [
new VerticalLayout({
width: "120px",
content: [
new Text({ text: "Id de funcionário: " }),
new Text({ text: "Data de inicio: " }),
new Text({ text: "Data de término: " }),
new Text({ text: "Hora de inicio: " }),
new Text({ text: "Hora de término: " })
]
}),
new VerticalLayout({
content: [
new Text({text: sIdEmp }),
new Text({ text: sStartDate }),
new Text({ text: sEndDate }),
new Text({ text: sStartHour }),
new Text({ text: sEndHour })
]
})
]
}),
new TextArea("confirmationTitle", {
width: "100%",
placeholder: "Adicione o titulo do agendamento"
//required:"true" - não pode ter
}),
new TextArea("confirmationDetails", {
width: "100%",
placeholder: "Adicione detalhes do agendamento"
//required:"true" - não pode ter
}),
new sap.m.ComboBox({
items: {
path: "DataModel>/types",
template: {
Type: "sap.ui.core.ListItem",
text: "{DataModel>Key}",
enabled: true
}
}
})
],
beginButton: new Button({
type: ButtonType.Emphasized,
text: "Submeter",
press: function () {
var sIdEmp1 = sIdEmp,
sStartDate1 = sStartDate,
sEndDate1 = sEndDate,
sStartHour1 = sStartHour,
sEndHour1 = sEndHour,
sTitle = Core.byId("confirmationTitle").getValue(),
sDetails = Core.byId("confirmationDetails").getValue();
this.addAppointment(sIdEmp1, sStartDate1, sEndDate1, sStartHour1, sEndHour1, sTitle, sDetails);
this.oConfirmDialog.close();
}.bind(this)
}),
endButton: new Button({
text: "Cancelar",
press: function () {
this.oConfirmDialog.close();
}.bind(this)
})
});
}
this.oConfirmDialog.open();
},
First of all, there's a typo. In your model you have the string "key", but when creating the ComboBox you used "Key", with an uppercase K. Be sure that you put the same on both places.
If this don't solves your problem, try using sap.ui.core.Item instead of sap.ui.core.ListItem, as it is the control that the aggregation items accepts:
new sap.m.ComboBox({
items: {
path: "DataModel>/types",
template: new sap.ui.core.Item({
key: "{DataModel>key}",
text: "{DataModel>text}"
})
},
enabled: true
})
Also, remember that ComboBox is ony recomended when you will have between 13 and 200 results. For less than 13 options to show use sap.m.Select instead.

I cannot output the value of the foreign key via jsonresponse serealize

I want to get json serialized the name of the products insted of the id ones. I tried to add natural_keys method on the parent model with no luck.
I can receive the json data good but in this way:
[{"model": "ocompra.compradetail", "pk": 1, "fields": {"producto": 238, "precio": "620.00", "cantidad": 1}}, {"model": "ocompra.compradetail", "pk": 2, "fields": {"producto": 17, "precio": "65.00", "cantidad": 2}}]
Any suggestions will be much appreciated!
Thanks,
views.py
def detalle(request):
template_name = "ocompra/compra_ok.html"
contexto={}
data={}
if request.method=="GET":
cat = CompraDetail.objects.all().order_by("codigo")
contexto={"obj":cat}
if request.method=="POST":
codigos=request.POST.getlist("codigos[]")#Codigo/s de la Orden de Compra
codigos= [int(x) for x in codigos]#Convierte la lista en integer
items_detalle = CompraDetail.objects.filter(compra__in=codigos).select_related('producto')
for item in items_detalle:
print(item.producto.nombre, item.cantidad, item.precio, item.subtotal)
#data['success'] = True
#print (data)
return JsonResponse(serializers.serialize('json', items_detalle,fields=('producto', 'cantidad','precio'), use_natural_foreign_keys=True), safe=False)
#return JsonResponse(data)
return render(request,template_name,contexto)
models.py
from django.db import models
from django.utils.timezone import datetime
from articulos.models import Articulos
# Create your models here.
class CompraHead(models.Model):
numero=models.AutoField(primary_key=True)
cliente= models.CharField(max_length=200,default="Consumidor Final")
direccion=models.CharField(max_length=100,null=True,blank=True)
telefono=models.CharField(max_length=50,null=True,blank=True)
fecha=models.DateField(default=datetime.now)
observaciones=models.CharField(max_length=400)
subtotal=models.DecimalField(default=0.00,max_digits=9,decimal_places=2)
descuento=models.IntegerField(default=0.0)
total=models.DecimalField(default=0.00,max_digits=9,decimal_places=2)
class CompraDetail(models.Model):
compra=models.ForeignKey(CompraHead,on_delete=models.CASCADE)
producto=models.ForeignKey(Articulos,on_delete=models.CASCADE)
precio= models.DecimalField(max_digits=10,decimal_places=2)
cantidad=models.IntegerField(default=0)
subtotal=models.DecimalField(default=0.00,max_digits=9,decimal_places=2)
def natural_key(self):
return (self.producto.nombre)
js
var token = '{{csrf_token}}';
var data = JSON.stringify({"codigos":codigos});
data = {"codigos[]":codigos};
console.log(data);
$.ajax({
headers: { "X-CSRFToken": token },
"url": '/ocompra/detalle/',
"type": "POST",
"dataType": "json",
data: data,
success: function(data){
// if(data['success']){
//location.reload(true);
// alert(data)
// alert("Se actualizo correctamente.");
//}
alert(data)
var obj = JSON.parse(data);
for (i in obj)
alert('Producto: '+obj[i].fields.producto +'\n' + 'Cantidad: '+ obj[i].fields.cantidad +'\n' + 'Precio: '+obj[i].fields.precio )
},
error: function(a,b,c){
alert(c);
}
});
});
the solution was to declarate the method Natural key in the Articulo's Model Class instead of compraDetail one:
def natural_key(self):
return (self.pk, self.nombre, self.stock)
You also check this documentation

identify how to retrieve result set data (node.js + sequelize + foreign key mysql)

I searched for several posts. There is a lot of information about membership and join; but my problem I couldn't solve. I believe that partly because I am a first-timer in the tools.
Let's go to the data:
Categoria.js
const db = require("./db");
const Categoria = db.sequelize.define('categorias', {
nome: {
type : db.Sequelize.STRING
},
slug: {
type: db.Sequelize.TEXT
}
})
module.exports = Categoria
Postagem.js
const Categoria = require("./Categoria");
const db = require("./db");
const Postagem = db.sequelize.define('postagens', {
titulo: {
type : db.Sequelize.STRING,
required : true
},
slug: {
type: db.Sequelize.TEXT,
required : true
},
descricao: {
type : db.Sequelize.STRING,
required : true
},
conteudo: {
type : db.Sequelize.STRING,
required : true
},
categoriaId: { // esse atributo é chave estrangeira
type: db.Sequelize.INTEGER,
required : true,
allowNull: false,
references: { // Postagem belongsTo Categoria 1:1
model: 'categorias', // nome da tabela
key: 'id' // nome da coluna na tabela
}
}
})
Postagem.belongsTo(Categoria, { foreignKey: 'categoriaId', foreignKeyConstraint: true, as: 'categoria' });
module.exports = Postagem
Data reading:
router.get("/postagens",(req, res) => {
Postagem.findAll({
include:[
{
model: Categoria,
require: true,
as: 'categoria'
}]
}).then(function(postagens){
console.log(postagens)
res.render("admin/postagens", {postagens: postagens})
}).catch(function(erro){
req.flash("error_msg", "Erro ao procurar postagens: " + erro)
res.redirect("/admin")
})
})
The select sentence (perfect):
SELECT `postagens`.`id`, `postagens`.`titulo`, `postagens`.`slug`, `postagens`.`descricao`, `postagens`.`conteudo`, `postagens`.`categoriaId`, `postagens`.`createdAt`, `postagens`.`updatedAt`, `categoria`.`id` AS `categoria.id`, `categoria`.`nome` AS `categoria.nome`, `categoria`.`slug` AS `categoria.slug`, `categoria`.`createdAt` AS `categoria.createdAt`, `categoria`.`updatedAt` AS `categoria.updatedAt` FROM `postagens` AS `postagens` LEFT OUTER JOIN `categorias` AS `categoria` ON `postagens`.`categoriaId` = `categoria`.`id`;
Json postagens:
[
postagens {
dataValues: {
id: 2,
titulo: 'UX',
slug: 'ux',
descricao: 'O que é UX?',
conteudo: 'O conceito de ux na web bla bla bla bla bla e mais bla',
categoriaId: 1,
createdAt: 2020-10-21T14:05:32.000Z,
updatedAt: 2020-10-21T14:05:32.000Z,
categoria: [categorias]
},
...
Question:
It does not show the categoria content, it only appears: categoria: [categorias].
What should I do to access the field categoria.nome?
Just get plain objects from model instances like this:
const plainObjects = postagens.map(x => x.get({ plain: true }))

Return nested List from web api using Entity Framework and navigation properties

I'm trying to return a JSON with a nested list using Navigation properties but I keep getting null in the 'Usuario' collection here's the output.
[
{
"$id": "1",
"id": 1,
"encabezado": "Como llamar a un metodo en c#",
"cuerpo": "Estoy intentando llamar un metodo metodo() pero no puedo alguna sugerencia xD?",
"points": 0,
"Usuario": null,
"Respuestas": []
},
{
"$id": "2",
"id": 2,
"encabezado": "Como cambiar conection String",
"cuerpo": "Es posible cambiar el conection string en asp.net si ya esta creada?",
"points": 1,
"Usuario": null,
"Respuestas": []
}
]
here's my .edmx
And finally this is where I have the web api
namespace AskTecProject.Controllers
{
public class QuestionController : ApiController
{
[HttpGet]
public List<Pregunta> GetQuestions()
{
using (asktecdbEntities entities = new asktecdbEntities())
{
List<Pregunta> p = entities.Usuarios.Where(m => m.id.Equals(1)).SelectMany(m => m.Preguntas).ToList<Pregunta>();
return p;
}
}
}
}
I got his query from Getting a related collection but I'm still having trouble with this, I'll appreciate any help
You should use Eager Loading:
List<Pregunta> preguntas = entities.Usuarios
.Where(u => u.id.Equals(1))
.SelectMany(u => u.Preguntas)
.Include(p => p.Usuario) // here
.ToList<Pregunta>();
Side note - seems like all your Preguntas entities will have same Usuario entity with id = 1. Also you don't need to specify generic parameter for ToList method - parameter should be inferred.

Saved db field as YYYY-MM-DD; need display and sort as DD-MM-YYYY

I have a MySQL date field that is saved, for example, as 2015-06-26 and I need to display and sort it in a datatable as 26-06-2015.
I think that "it's not rocket science" but I've read a bunch of articles without understand where I should start from (server-side, some plugin or not, moment, etc).
This is my debug code: debug.datatables.net/aninog
This is JS code:
var dettagli = [];
var table = $('#tabellaDati').DataTable( {
"stateSave": true,
"language": {
"sEmptyTable": "Nessun dato presente nella tabella",
"sInfo": "Vista da _START_ a _END_ di _TOTAL_ elementi",
"sInfoEmpty": "Vista da 0 a 0 di 0 elementi",
"sInfoFiltered": "(filtrati da _MAX_ elementi totali)",
"sInfoPostFix": "",
"sInfoThousands": ",",
"sLengthMenu": "Visualizza _MENU_ elementi",
"sLoadingRecords": "Caricamento...",
"sProcessing": "Elaborazione...",
"sSearch": "Cerca:",
"sZeroRecords": "La ricerca non ha portato alcun risultato.",
"oPaginate": {
"sFirst": "Inizio",
"sPrevious": "Precedente",
"sNext": "Successivo",
"sLast": "Fine"
},
"oAria": {
"sSortAscending": ": attiva per ordinare la colonna in ordine crescente",
"sSortDescending": ": attiva per ordinare la colonna in ordine decrescente"
}
},
"data": datiTabella,
"columns": [
{
"sWidth": "8%",
"className": 'details-control',
"orderable": false,
"data": null,
"render": function(data, type, row, meta) {
return '<a class="btn btn-xs" href="incarico_form.php?action=edit&id='+data.id+'&pageFrom=<?=pathinfo($_SERVER['PHP_SELF'], PATHINFO_FILENAME ); ?>" title="Modifica"><span class="glyphicon glyphicon-edit"></span></a>'+
'<a class="btn btn-xs delete-object" delete-id="'+data.id+'" title="Elimina"><span class="glyphicon glyphicon-trash"></span></a>'+
'<a class="btn btn-xs" href="" id="mostraDettaglio" title="dettaglio"><span class="glyphicon glyphicon-folder-open"></span></a>';
}
},
{ "data": "id" },
{ "data": "protocollo" },
{ "data": "nomeAssicurato"},
{ "data": "sinistro"},
{ "data": "tipoEvento"},
{ "data": "dataSinistro"},
{ "data": "dataSopralluogo"},
{ "data": "dataIncarico"},
{ "data": "idStatoPratica"},
{ "data": "idStatoPerizia"},
{ "data": "nomeIncaricato"},
{ "data": "dataScadenza"},
],
"order": [[1, 'asc']],
"initComplete": function( settings, json ) {
function format ( d ) {
// `d` is the original data object for the row
// carica il template del dettaglio
// usando JsRender
$.ajax ({
async: false,
type: "POST",
url: "incaricodetail.html",
cache: false,
success: function(data){
templateHtml = data;
}
});
var template = $.templates(templateHtml);
var htmlOutput = template.render(d);
return htmlOutput;
}
// carica i dati formattati in html nell'array dettagli
// for (i=0; i < this.api().data().length; i++) {
// data = this.api().row(i).data();
// dettagli[i] = format(data);
// }
// Aggiungo un listener come 'delegato' in modo che possa funzionare anche su elementi della pagina aggiunti in un secondo momento tramite salto ad altra pagina o filtro
$('#tabellaDati tbody').on('click', '#mostraDettaglio', function () {
// alert("click");
var tr = $(this).closest('tr');
var row = table.row( tr );
var span = $(this).find("span");
if ( row.child.isShown() ) {
// This row is already open - close it
row.child.hide();
span.removeClass("glyphicon glyphicon-folder-close").addClass("glyphicon glyphicon-folder-open");
}
else {
// Open this row
// row.child(dettagli[row.index()]).show(); //carica dati da array dettagli
row.child( format(row.data())).show(); //carica dati da ajax
span.removeClass("glyphicon glyphicon-folder-open").addClass("glyphicon glyphicon-folder-close");
}
return false;
});
},
});
The field with date is dataIncarico
This is probably best done using momentjs. In your column definition add a render and a type like this:
{
"data": "dataIncarico",
"type": "date-uk",
"render": function(data){
return moment(data).isValid() ? moment(data).format("DD/MM/YYYY") : "";
}
}
That takes care of the formatting and also tells datatables to use a different function to order the data:
$.extend($.fn.dataTableExt.oSort, {
"date-uk-pre": function (a){
if(moment(a, "DD/MM/YYYY").isValid()){
return parseInt(moment(a, "DD/MM/YYYY").format("X"), 10);
}else{
return 0;
}
},
"date-uk-asc": function (a, b) {
return a - b;
},
"date-uk-desc": function (a, b) {
return b - a;
}
});
If you're looking to search using the server-side script your'll need to input the date in YYYY-MM-DD format or look at using a date input.
Hope that helps.