Dynamically create multiple forms in angular2 - angular2-template

I am fetching some data from database and on the basis of number of results I want to create forms . For eg. If I am getting total 3 rows with columns as name,age and class . Then I need to create three form elements with name, age and class as form element. Thanks in advance

You can use FormArray to create multiple form groups.
With FormBuilder we can create a FormGroup for the FormControls. In the FormGroup define a variable as FormArray and dynamically add FormControls to that array.
public dataForm = FormGroup;
const dbData = // data from database eg. [{name:x, age: 8, class: A},..]
...
constructor(
private _fb: FormBuilder
) {}
...
ngOnInit() {
this.dataForm = this._fb.group({
subFormList: this._fb.array([])
});
this.getValues();
}
getValues() {
const control = <FormArray> this.dataForm.get('subFormList');
for (row of this.dbData) {
const temp = this._fb.group({
name: [row['name']],
age: [row['age']],
class: [row['class']]
});
control.push(temp);
}
}
Hope this will help you.

Related

How to add additional properties to be passed through sequelize object in express

So for example I have a sequelize model as follows:
// MyModel.js
module.exports = (sequelize, DataTypes) => {
const MyModel = sequelize.define('MyModel',{
foo: DataTypes.STRING,
});
return MyModel
}
And then I use this model to express templating engine using controller as follows:
app.get('/foobar',async function(req,res,next){
var myModel = await MyModel.findById('abcd1234');
myModel.bar = bar
return res.render('foobar',{
myModel: myModel
});
})
and my foobar.pug is like this:
html
#{JSON.stringify(myModel)}
Apparently I can find the field called foo, but I can't get the field called bar, how do I pass this additional calculated field from my controller through my model?
Reason behind this is :
var myModel = await MyModel.findById('abcd1234');
// will return an instance of MyModel not json
// So you can't just do
myModel.bar = bar;
To make it happen ( Convert instance to JSON Object )
var myModel = await MyModel.findById('abcd1234').toJSON();
// Now this will return the JSON object and not instance of MyModel
// Now this will work
myModel.bar = bar;
toJSON() is sequelizejs's model's method , you can convert it via javascript function also.
If you want to retain the sequelize object , retain it in different variable
var myModelInstance = await MyModel.findById('abcd1234');
var myModel = myModelInstance.get({plain: true});
// OR
var myModel = myModelInstance.toJSON();
// Now this will work
myModel.bar = bar;
These are the possible ways of doing , but because of lack of
requirement and code this is the best I can suggest , you can still
look into GETTER , if you need the extra fields inside
instance.
For anyone looking for this in 2K22 and after :D,
you can use DataType.VIRTUAL when registering a field,
this allow predefining additional fields that will be used and keep it at serialize time but not persist into database.

Yii2 - loadMultiple with form model

I have a very simple scenario where I'm receiving a list of Variance Positions from the end user. To be able to validate the structure of the input, I created the following model for the single item that I should receive:
class VariancePositionsForm extends Model{
public $id;
public $position;
public function rules()
{
return [
[['id','position'], 'required'],
[['id', 'position'], 'integer'],
];
}
}
And in the controller, I have the following:
$variancePositions = [];
for($i=0;$i<sizeof(Yii::$app->request->post());$i++)
{
$variancePositions[] = new VariancePositionsForm();
}
VariancePositionsForm::loadMultiple($variancePositions, Yii::$app->request->post());
When I try to var_dump($variancePositions) however, I'm finding that its empty. In other words, loadMultiple() is not loading the models. What am I doing wrong?
Because you don't load the model from the form, only from json you have to add an empty string into the last parameter in this function:
VariancePositionsForm::loadMultiple($variancePositions, Yii::$app->request->post(), '');
look here:
https://github.com/yiisoft/yii2/blob/master/framework/base/Model.php#L884

Phalcon query builder can't get joined table data

I have 2 table 'sanpham' and 'danhmuc'. I use phalcon query builder to get data from 2 tables.
$laytin = $this->modelsManager->createBuilder()
->from("sanpham")
->innerJoin('danhmuc','sanpham.danhmuc=danhmuc.sodanhmuc')
->where('sanpham.sosanpham = '.$id.'')
->getQuery()
->getSingleResult();
$breadcrumbs = array('/' => Tool::getTranslation()->_('trangchu'),"/Loai-san-pham/".$laytin->tendep."/".$laytin->sodanhmuc => $laytin->tendanhmuc,'' => $laytin->tieudesanpham );
The query runs, but $laytin->tendep, $laytin->sodanhmuc, $laytin->tendanhmuc in 'danhmuc' table doesn't display. Every column in 'sanpham' table (such as: $laytin->tieudesanpham) displays properly.
You can add specific columns with:
$this->modelsManager->createBuilder()->columns('danhmuc.tend‌​ep, danhmuc.sodanhmuc')
With this method you will have to add each column you want in your output. QueryBuilder docs.
Another method is to query the Sanpham model.
For example:
class Sanpham extends \Phalcon\Mvc\Model
{
public static function findSomething($something)
{
// this is your actual query, it replaces the queryBuilder
return self::query()
->where('sanpham.sosanpham = :id:', ['id' => $something])
->innerJoin('danhmuc', 'sanpham.danhmuc = danhmuc.sodanhmuc')
->execute()->getFirst();
}
public function initialize()
{
// define the relation to danhmuc
$this->belongsTo('danhmuc', 'danhmuc', 'sodanhmuc');
}
}
class Danhmuc extends \Phalcon\Mvc\Model
{
public function initialize()
{
// there are other options besides "hasMany", like "hasOne".
// this is your relation to sanpham
$this->hasMany('sodanhmuc', 'sanpham', 'danhmuc');
}
}
class YourController extends \Phalcon\Mvc\Controller
{
public function testAction()
{
// get your first record in Sanpham matching "12345"
$sanpham = Sanpham::findSomething(12345);
// from your Sanpham object, get the related danhmuc object.
// this works because we defined the relations (belongsTo and hasMany)
$danhmuc = $sanpham->getRelated('danhmuc');
// now you have access to the values of danhmuc via the $danhmuc variable
$breadcrumbs = [
'/' => Tool::getTranslation()->_('trangchu'),
"/Loai-san-pham/" . $danhmuc->tendep => $danhmuc->tendanhmuc,
'' => $danhmuc->tieudesanpham,
];
}
}
Check the Phalcon model docs for more info on this.

phalcon - Relationships not defined when converting resultset to array?

I have tested it with 2 methods:
The first:
class ProjectsController extends ControllerBase
{
public function indexAction()
{
$row = array();
$projects = Projects::find();
foreach ($projects as $project) {
foreach($project->employees as $employee){
echo "Employee: " . $employee->name;
}
}
exit;
}
}
Output:
Employee: Admin
The second:
class ProjectsController extends ControllerBase
{
public function indexAction()
{
$row = array();
$projects = Projects::find();
$projects = $projects->toArray();
foreach ($projects as $project) {
foreach($project["employees"] as $employee){
echo $employee->name;
}
}
exit;
}
}
Output:
Notice: Undefined index: employees in app/controllers/ProjectsController.php on line 10
When converting the resultset to array the relationships aren't added to the array, is there a workaround to add it to the array?
The reason I converted the resultset to an array is to edit results for example calculating progress or something like that, without saving it to the database.
Things like this:
foreach($projects as &$project){
//count all the todos.
$todos = Todos::find("project_id = '".$project["id"]."'");
$numberOfTodos = $todos->count();
//count all the todos that are done.
$todos = Todos::find("project_id = '".$project["id"]."' AND status_id = 9");
$numberOfDoneTodos = $todos->count();
$project["percentageDone"] = ($numberOfDoneTodos / $numberOfTodos) * 100;
var_dump($row);exit;
}
$this->view->setVar("projects",$projects);
So I don't have to do calculations on the view side and only have to output it
Yes, when you convert a result set to an array only scalar values are converted.
But for adding a calculated property to your model there's no need to convert it to an array, you can change or create new properties as you wish and it will only be saved to the database when you call for example $project->save() and just properties that match a column name will be stored in the database.
For adding calculated properties I'd recommend you to use the event afterFetch that gets fired for each model retrieved from the database:
class Projects extends \Phalcon\Mvc\Model
{
...
public function afterFetch()
{
//Adds a calculated property when a project is retrieved from the database
$totalTodos = Todos::count("project_id = $this->id");
$completeTodos = Todos::count("project_id = $this->id AND status_id = 9");
$this->percentageDone = round(($completeTodos / $totalTodos) * 100, 2);
}
}

Cannot get data updates on NotifyPropertyChanged collection

I'm building a Mango app that writes data to a SqlCe database; I have a ListBox bound to a DataSource that must show items when they are added to the database, but when I add/update data I cannot get updates and they are only shown when I reload the page.
Here are some snippets:
public class TimeTrackerViewModel: INotifyPropertyChanged, INotifyPropertyChanging
{
private List<TimeItems> _timeItems;
public List<TimeItems> TimeItems
{
get { return _timeItems; }
set
{
NotifyPropertyChanging("TimeItems");
_timeItems = value;
NotifyPropertyChanged("TimeItems");
}
}
public void LoadCollectionsFromDatabase()
{
// Specify the query for all to-do items in the database.
var times = from t in db.Times
select new TimeItems
{
DtIn = t.DtIn,
DtOut = t.DtOut,
Id = t.Id
};
// Query the database and load all to-do items.
TimeItems = new List<TimeItems>(times);
}
.....
.....
}
When I add data to the Times table I don't see db updates to the listBox bound to the TimeItems collection.
What am I doing wrong?
Make TimeItems an ObservableCollection