I need to make all the objects for skills as required. How can I achieve this?
this.feedbackForm = this.fb.group({
applicantId: [''],
comments: [''],
recommendation: [''],
skills: this.fb.array(
this.skills.map((t) => {
this.fb.control(t);
})
),
});
I need to make the skills as required for each object.
you can make the skills formArray as required, and then all the skills in it will be required
like this:
this.feedbackForm = this.fb.group({
applicantId: [''],
comments: [''],
recommendation: [''],
skills: this.fb.array(
this.skills.map((t) => {
this.fb.control(t);
}), {validators: Validators.required}
),
});
or in formControl specific
this.feedbackForm = this.fb.group({
applicantId: [""],
comments: [""],
recommendation: [""],
skills: this.fb.array(
this.skills.map((t) => {
this.fb.control(t, { validators: [Validators.required] });
})
),
});
i suggest reading formBuilder documentation
https://angular.io/guide/reactive-forms#creating-dynamic-forms
Related
Im writing these validations for every file in every component.ts
where the validations is required
is it possible to write all these in single ts file and reuse where
ever needed
validationmessages = {
username: [
{ type: 'required', message: 'Username is required.' },
],
password: [
{ type: 'required', message: 'Password is required.' }
],
email: [
{ type: 'required', message: 'Email is required.' },
]
};
constructor(private route: Router, private formbuilder: FormBuilder,
private userservice: UserService, private commondata: CommonData) {
this.loginform = this.formbuilder.group({
username: ['', Validators.required],
password: ['', Validators.required]
You can export a const variable from a ts file
validationMsg.ts
export const validationmessages = {
username: [
{ type: 'required', message: 'Username is required.' },
],
password: [
{ type: 'required', message: 'Password is required.' }
],
email: [
{ type: 'required', message: 'Email is required.' },
]
};
and import it afterwards
sometsfile.ts
import {validationmessages} from './validationMsg.ts'; //or correct path..
read more about Modules in Typescript
Simple stackblitz example
I have data from an API, like this:
{ actions: 1, created_at: "2020-11-27 18:13:50", id: 18, payment: "0.00", change: "A" }
And I need to send back the data modified by user, I am using Reactive Forms for this, I am showing the data with Angular Material tables.
I have an idea that it would be more or less like this:
this.form = fB.group({data: this.fB.array( [fB.group({here.the.group}} )
How can I create the formArray from the data I receive dynamically? The idea is to be able to edit from the table and send the new formArray as the new data
You can use setValue or patchValue, I like patchValue as it comes with fewer challenges in setting up
Lets say your data is like below
{
actions: 1,
created_at: "2020-11-27 18:13:50",
id: 18,
payment: "0.00",
change: "A",
data: [
{ id: 1, name: 'item 2'},
{ id: 2, name: 'item 3'},
{ id: 3, name: 'Item 3'}
]
}
You can implement below approach to set your form
this.form = fB.group({
actions: [''],
payment: [''],
change: [''],
data: this.fb.array([])
})
get formDataArray() {
return this.form.get('data') as FormArray
}
ngOnInit() {
this.myService.getData().subscribe(({actions, payment, change, data })=> {
this.form.patchValue({ actions, payment, change });
data.forEach(({id, name})=> {
this.formDataArray.push(
this.fb.group({id: [id], name: [name] })
)
})
})
}
My JSON is in this format. How do you design a Angular FormGroup for this to get and update this data easily. I am facing issues with writing a good structure for form group.
If the JSON structure is complex please suggest changes.
{
usertypes_id: "1",
name: "Admin",
permissions: "{"dashboard":{"name":"Dashboard","value":"Full"},"studioInformation":{"name":"Studio Information","value":"Full"},"studioLocation":{"name":"Studio Location","value":"Full"},"users":{"name":"Users","value":"Full"},"roles":{"name":"Roles","value":"Full"},"dancers":{"name":"Dancers","value":"Full"},
},
{
usertypes_id: "2",
name: "Staff",
permissions: "{"dashboard":{"name":"Dashboard","value":"Full"},"studioInformation":{"name":"Studio Information","value":"Full"},"studioLocation":{"name":"Studio Location","value":"Full"},"users":{"name":"Users","value":"Full"},"roles":{"name":"Roles","value":"Full"},"dancers":{"name":"Dancers","value":"Full"},
}
This is what I have already tried
constructor(
private rolesService: RolesService,
private menuItems: MenuItems,
private fb: FormBuilder
) {
}
ngOnInit() {
const name = this.fb.control("", [Validators.required]);
const permissions = this.fb.group({
dashboard: this.fb.group({
name: ["", Validators.required],
value: ["", Validators.required]
}),
studioInformation: this.fb.group({
name: ["", Validators.required],
value: ["", Validators.required]
}),
studioLocation: this.fb.group({
name: ["", Validators.required],
value: ["", Validators.required]
}),
users: this.fb.group({
name: ["", Validators.required],
value: ["", Validators.required]
}),
roles: this.fb.group({
name: ["", Validators.required],
value: ["", Validators.required]
}),
dancers: this.fb.group({
name: ["", Validators.required],
value: ["", Validators.required]
}),
staff: this.fb.group({
name: ["", Validators.required],
value: ["", Validators.required]
}),
courses: this.fb.group({
name: ["", Validators.required],
value: ["", Validators.required]
}),
classes: this.fb.group({
name: ["", Validators.required],
value: ["", Validators.required]
}),
});
this.roleForm = this.fb.group({
name: name,
permissions: permissions
})
}
I am trying to create the following associations using sequelize but I keep getting the following error “Error: Error: customer is not associated to order!”. I have bi-directional associations according to what I found in the documentation. I am confused about what the problem could be because when I look into the database tables I can see the foreign keys. For this example, I am trying to pull the order and customer associated with the particular order. Technically, I could do three seaprate db pull but that seems inefficient as opposed to joins.
'use strict';
module.exports = function(sequelize, DataTypes) {
var user = sequelize.define('user', {
username: DataTypes.STRING(30), //remove
password: DataTypes.STRING(255),
emailaddress: DataTypes.STRING(255),
firstname: DataTypes.STRING(30),
middlename: DataTypes.STRING(30), //remove
lastname: DataTypes.STRING(30),
approve: DataTypes.BOOLEAN,
roles: DataTypes.STRING(50),
isactive: DataTypes.BOOLEAN
}, {
classMethods: {
associate: function(models) {
// associations can be defined here
this.hasMany(models.order);
}
}
});
user.hook('afterCreate', function(usr, options) {
//hash the password
return user.update({ password: passwd }, {
where: {
id: usr.id
}
});
});
return user;
};
'use strict';
module.exports = function(sequelize, DataTypes) {
var order = sequelize.define('order', {
ponumber: DataTypes.STRING(30), //remove
orderdate: DataTypes.DATE,
shippingmethod: DataTypes.STRING(30),
shippingterms: DataTypes.STRING(30),
deliverydate: DataTypes.DATE,
paymentterms: DataTypes.STRING(30),
overridediscount: DataTypes.BOOLEAN,
shippingaddress: DataTypes.STRING(30),
shippingcity: DataTypes.STRING(30),
shippingstate: DataTypes.STRING(20),
shippingzipcode: DataTypes.STRING(10),
isactive: DataTypes.BOOLEAN
}, {
associate: function(models) {
// associations can be defined here
this.belongsTo(models.user);
this.belongsTo(models.customer);
}
});
order.hook('afterCreate', function(ord, options) {
//generate po number
return order.update({ ponumber: ponumbr }, {
where: {
id: ord.id
}//,
//transaction: options.transaction
});
});
return order;
};
'use strict';
module.exports = function(sequelize, DataTypes) {
var customer = sequelize.define('customer', {
customernumber: DataTypes.STRING(30), //remove
customerspecificationid: DataTypes.INTEGER,
customertypeid: DataTypes.INTEGER,
sportid: DataTypes.INTEGER,
customername: DataTypes.STRING(20), //remove
address: DataTypes.STRING(30),
city: DataTypes.STRING(30),
state: DataTypes.STRING(30),
zipcode: DataTypes.STRING(30),
ordercomplete: DataTypes.BOOLEAN,
isactive: DataTypes.BOOLEAN
}, {
associate: function(models) {
// associations can be defined here
this.hasMany(models.order);
}
});
customer.hook('afterCreate', function(cust, options) {
//generate the customer number
return customer.update({ customernumber: custnumber }, {
where: {
id: cust.id
}
});
});
return customer;
};
Here is the constructor and method inside of a repository class I want to join
constructor(model){
super(model.order);
this.currentmodel = model;
}
findById(id){
let that = this;
return new Promise(
function(resolve, reject) {
that.model.find({
where: { id: id },
include: [ that.currentmodel.customer, that.currentmodel.user ]
})
.then(function(order){
resolve(order);
})
.catch(function(err){
reject(err);
})
});
}
I have reviewed the documentation and searched the internet looking for a fix to this issue but I am not finding any answers. Could someone please shed some light on what I could be missing?
For the example above, I am trying to retrieve the user and the customer tied to the order record via the primary key. All of the findBy scenarios I have found so far would be getting a list of orders tied to the customer and user. What do I need to change in order to retrieve the order and customer whose foreign keys are tied to this order?
The problem is probably with how you are setting you association, kindly mention your strategy.
Following is working fine if you use the express index.js file setup and then query http://docs.sequelizejs.com/en/1.7.0/articles/express/
'use strict';
module.exports = function(sequelize, DataTypes) {
var customer = sequelize.define('customer', {
customernumber: DataTypes.STRING(30), //remove
customerspecificationid: DataTypes.INTEGER,
customertypeid: DataTypes.INTEGER,
sportid: DataTypes.INTEGER,
customername: DataTypes.STRING(20), //remove
address: DataTypes.STRING(30),
city: DataTypes.STRING(30),
state: DataTypes.STRING(30),
zipcode: DataTypes.STRING(30),
ordercomplete: DataTypes.BOOLEAN,
isactive: DataTypes.BOOLEAN
}, {
associate: function(models) {
// associations can be defined here
models.customer.hasMany(models.order);
}
});
customer.hook('afterCreate', function(cust, options) {
//generate the customer number
return customer.update({ customernumber: custnumber }, {
where: {
id: cust.id
}
});
});
return customer;
};
'use strict';
module.exports = function(sequelize, DataTypes) {
var order = sequelize.define('order', {
ponumber: DataTypes.STRING(30), //remove
orderdate: DataTypes.DATE,
shippingmethod: DataTypes.STRING(30),
shippingterms: DataTypes.STRING(30),
deliverydate: DataTypes.DATE,
paymentterms: DataTypes.STRING(30),
overridediscount: DataTypes.BOOLEAN,
shippingaddress: DataTypes.STRING(30),
shippingcity: DataTypes.STRING(30),
shippingstate: DataTypes.STRING(20),
shippingzipcode: DataTypes.STRING(10),
isactive: DataTypes.BOOLEAN
}, {
associate: function(models) {
// associations can be defined here
models.order.belongsTo(models.user);
models.order.belongsTo(models.customer);
}
});
order.hook('afterCreate', function(ord, options) {
//generate po number
return order.update({ ponumber: ponumbr }, {
where: {
id: ord.id
}//,
//transaction: options.transaction
});
});
return order;
};
'use strict';
module.exports = function(sequelize, DataTypes) {
var user = sequelize.define('user', {
username: DataTypes.STRING(30), //remove
password: DataTypes.STRING(255),
emailaddress: DataTypes.STRING(255),
firstname: DataTypes.STRING(30),
middlename: DataTypes.STRING(30), //remove
lastname: DataTypes.STRING(30),
approve: DataTypes.BOOLEAN,
roles: DataTypes.STRING(50),
isactive: DataTypes.BOOLEAN
}, {
classMethods: {
associate: function(models) {
// associations can be defined here
models.user.hasMany(models.order);
}
}
});
user.hook('afterCreate', function(usr, options) {
//hash the password
return user.update({ password: passwd }, {
where: {
id: usr.id
}
});
});
return user;
};
// index.js file where you shall associate the routes
var fs = require('fs')
, path = require('path')
, Sequelize = require('sequelize')
, lodash = require('lodash')
, sequelize = new Sequelize('sequelize_test', 'root', 'root')
, db = {}
fs.readdirSync(__dirname)
.filter(function(file) {
return (file.indexOf('.') !== 0) && (file !== 'index.js')
})
.forEach(function(file) {
var model = sequelize.import(path.join(__dirname, file))
db[model.name] = model
})
Object.keys(db).forEach(function(modelName) {
if (db[modelName].options.hasOwnProperty('associate')) {
db[modelName].options.associate(db)
}
})
// sequelize.sync({force: true})
module.exports = lodash.extend({
sequelize: sequelize,
Sequelize: Sequelize
}, db)
Put the above db code in respective files in db folder or whatever you like to name it and then you can use your query
var db = require('./db');
db.order.find({
where: { id: 0 },
include: [ db.customer, db.user ]
})
.then(function(order){
console.log(order)
})
I have a function which needs to be implemented with Bluebird Promises but unable to work it out. Here is a pseudo code
exports.addEmployees=function (req,res){
var data = [
{
firstName: 'XXXXX',
lastName: 'V',
phone: '9999999999',
dateOfBirth: '2010-08-02',
department: 'IT',
startDate: '2015-08-02',
created: now,
updated: now
},
{
firstName: 'YYYYY',
lastName: 'K',
phone: '8888888888',
dateOfBirth: '2011-08-02',
department: 'IT',
startDate: '2015-08-02',
created: now,
updated: now
},
];
async.each(data, function(item,callback){
req.db.Employee.create(item, callback);
},function(err){
if(err){
res.send("Error!");
}
res.send("Success!");
}
);
}
Thanks
Something like
var Promise = require("bluebird")
var data = [
{
firstName: 'XXXXX',
lastName: 'V',
phone: '9999999999',
dateOfBirth: '2010-08-02',
department: 'IT',
startDate: '2015-08-02',
created: now,
updated: now
},
{
firstName: 'YYYYY',
lastName: 'K',
phone: '8888888888',
dateOfBirth: '2011-08-02',
department: 'IT',
startDate: '2015-08-02',
created: now,
updated: now
},
];
Promise.map(data, function(item) {
return req.db.Employee.create(item)
.then(function(id){ return id })
.catch(MyError, function(e) {
e.item = item;
throw e;
})
}).then(function(idList) {
res.send("Success!");
}).catch(MyError, function(e) {
console.log("Operation failed on " + e.item + ": " + e.message);
res.send("Error!");
});
You need to define myError to make this work (https://github.com/petkaantonov/bluebird/blob/master/API.md#catchfunction-errorclassfunction-predicate-function-handler---promise)
P.S. Sure, req.db.Employee.create(item) should support promises, so probably you will need to promisify it: https://github.com/petkaantonov/bluebird/blob/master/API.md#promisepromisifyallobject-target--object-options---object