Setting default initial values for select multiple component - antd

Using the select component i am having a hard time trying to set initial values.
As the docs. says im suppose to fill in the value prop with only string|number|string[]|number[].
Now the problem with this is that i need to show text on the input and send an id value on submit, but with this you show the same value you send.
<Select
mode="multiple"
defaultValue={tags} // => would need something like tags = [{id: 1, name: "Science"}]
placeholder="Select tags"
onSearch={this.fetchTags}
onChange={this.handleChange}
style={{ width: '100%' }}
>
{tags.map(tag => <Option value={tag.id} key={tag.id}>{tag.name}</Option>)}
</Select>

So "labelInValue" is what i really needed in case anyone else experience the same problem.

You can use value instead of defaulValue. Here is a sample code from my project:
const stateTasksOptions =
this.tasksStore.filters.init.state.map(item =>
<Select.Option key={item.id} value={item.id} title={<span className={`${item.id}Label`}>{item.title}</span>}>
<span className={`${item.id}Label`}>{item.title}</span> - <span class="normal-text">{item.help}</span>
</Select.Option>
)
return (
....
<Select
mode="multiple"
value={this.tasksStore.filters.selected.state.map(d => d)}
onChange={this.handleTasksStatus}
optionLabelProp="title"
>
{stateTasksOptions}
</Select>
....
)
And some css for colorizing.
Result:
this.tasksStore.filters.init.state looks like:
state = [
{id: "done", title: "Исполнена", help: "исполнены после 24.04.2017"},
{id: "active", title: "В работе", help: "текущие задачи"},
{id: "planned", title: "Запланирована", help: "задачи на будущее"},
{id: "missed", title: "Просрочена", help: "срок исполнения истек"},
{id: "archived", title: "Архив", help: "выполнены ранее 24.04.2017"}
]

Related

Array of strings - without nesting

I want my record level data of the form to looks like this:
{
names: ['foo name', 'bar name']
}
However I am having to nest which gives me:
{
names: [ { name: 'foo name' }, { name: 'bar name' }]
}
The nest is caused by this:
<FieldArray name="names">
{({ fields }) =>
fields.map((name, index) => (
<div key={name}>
<Field
name={`${name}.name`}
component="input"
placeholder="Name"
/>
</div>
))
}
</FieldArray>
Is there a way to avoid this nesting, and get a FieldArray of just strings?
Solved it, I just had to use
name={name}
instead of
name={`${name}.name`}
Cool!

Angular 5 - How to fill a FormArray

I will fill the customerNumberContainers which looks like this:
this.form = new FormGroup({
customerNumberContainers: new FormArray([
new FormGroup({
contactTenant: new FormControl('', [Validators.required, Validators.minLength(2)]),
customerNumber: new FormControl('', [Validators.required, Validators.minLength(2)])
}),
]),
Therefore I do this after I get the values over
this.contactService.findContactById(this.id).subscribe(response => { ...
Set values into form:
let customerNumberContainersFormArray: FormArray = this.form.controls.customerNumberContainers as FormArray;
customerNumberContainersFormArray.controls["0"].controls.contactTenant.value = 'TestValue';
but it is not shown with:
in Controller:
get customerNumberContainers(): FormArray {
return this.form.get("customerNumberContainers") as FormArray;
}
in Template:
<div formArrayName="customerNumberContainers">
<div *ngFor="let customerNumberContainer of customerNumberContainers.controls; index as i" [formGroupName]="i">
<mat-input-container class="full-width-input">
<input matInput formControlName="contactTenant">
</mat-input-container>
</div>
Does anyone known what I am doing wrong. It seems for me that values with *ngFor arn't refreshed.
why dont You just patch whole form with model ? like this:
set up your model, for example:
export class Tenants {
id: number;
customerNumberContainers: TenantContact[];
}
export class TenantContact {
contactTenant: string;
customerNumber: string;
}
fetch it from service like u always do but it should match above models and patch whole form (or setValue)
this.contactService.findContactById(this.id).subscribe((tenats: Tenants) => {
this.form.patchValue(tenats);
});

Rails_Admin related dropdowns

Is there a way to filter a dropdown list based on another dropdown's value ?
For example, if we have: Class and Student Models where Student have class_id; is there a way to filter the Students shown in the dropdown based on the selected Class ?
EDIT
Apparently, rails_admin gem has an association relationship which I was looking for; but it doesn't work perfectly.
Given two <select> elements "Class" and "Student", with the Student list containing data-class_id attributes referencing values from the Class list (see snippet below), you can filter the "Student" dropdown based on the "Class" dropdown's value using the following vanilla-JavaScript code:
var firstSelectId = "Class";
var secondSelectId = "Student";
var data_attr = "class_id";
this.addEventListener("DOMContentLoaded", function(event) {
var firstSelect = document.getElementById(firstSelectId);
var secondSelect = document.getElementById(secondSelectId);
firstSelect.addEventListener("change", function(event) {
var value = event.target.value;
Array.prototype.forEach.call(secondSelect.options, function(item) {
item.style.display = (item.dataset[data_attr] === value) ? 'inline' : 'none';
});
var selected = secondSelect.selectedOptions[0];
if (selected && selected.dataset[data_attr] !== event.target.value) {
secondSelect.selectedIndex = -1;
}
});
firstSelect.dispatchEvent(new Event('change'));
});
<form id="myform">
Select a class and student:
<select id="Class">
<option value="1">Class1</option>
<option value="2">Class2</option>
<option value="3">Class3</option>
</select>
<select id="Student">
<option value="StudentA" data-class_id="1">A</option>
<option value="StudentB" data-class_id="2">B</option>
<option value="StudentC" data-class_id="3">C</option>
<option value="StudentD" data-class_id="2">D</option>
<option value="StudentE" data-class_id="1">E</option>
<option value="StudentF" data-class_id="1">F</option>
</select>
</form>
If you can use Javascript, this Railscast will help you:
In this instance, your dropdowns may look like this:
<%= f.collection_select :class_id, Class.all, :id, :name, {:prompt => "Select a Class"}, {:id => "class"} %>
<%= f.collection_select :student_id, Student.all, :id, :name, {:prompt => "Select a Student"}, {:id => "student"} %>
And you would use Javascript to change the options in the Student dropdown. You can get the value of the class using:
class_id = $("#class").find(":selected").text()
This is the related link: https://github.com/sferik/rails_admin/wiki/Associations-scoping which edited the origin question

Display Update button & save values in database

We are displaying table grid as below image, in last column you can see commission as 10 & 0.
i need to provide an Update button below that and provide an option to edit 10 & 0 , so if we click on "update" button, it should save in database.
we are using below code to display table grid.
php
function getDesignerCollection()
{
$user_home = new USER();
$stmt = $user_home->runQuery("SELECT * FROM tbl_users");
$stmt->execute(array(":uid" => $_SESSION['userSession']));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$stmt->execute();
$i=0;
while($data = $stmt->fetch())
{
$responce[$i]=array($data['userID'],
ucfirst($data['name']),
$data['commission1'],
$data['joining_date']);
$i++;
}
echo json_encode($responce);
}
script
var __TEST_DATA__=eval('<?php echo getDesignerCollection();?>');
var grid_demo_id = "myGrid" ;
var dsOption= {
fields :[
{name : 'userID' },
{name : 'name' },
{name : 'commission1'},
{name : 'joining_date'}
],
recordType : 'array',
data : __TEST_DATA__
}
function my_renderId(value ,record,columnObj,grid,colNo,rowNo)
{
var no= record[columnObj.fieldIndex];
return "<input type='checkbox' value='"+record[0]+"' name='userID'/>";
}
var colsOption = [
{id: 'userID' , header: "Customer Id" , width :"90",renderer : my_renderId},
{id: 'name' , header: "Designer Name" , width :"140"},
{id: 'commission1' , header: "commission1" , width :"120"},
{id: 'joining_date' , header: "Customer Since" , width :"120"}
];
now to provide an update button , i am trying below code :
form
<form method="post" name="update" action="updateform.php" />
commission1:
<input type="text" name="commission1" />
<input type="submit" name="Submit" value="update" />
</form>
updateform.php
$sql = "UPDATE tbl_users SET commission1 = '$commission1' WHERE userID= :uid";
$result = $conn->query($sql);
where i need to use form code to display "update" button below values 10 & 0
I am new to php & tried lot before posting here, but did't got any idea related to my code.

django - how to override admin templates

I want to change the way the add new object page looks in the admin page.
I do not want to change the fields but want to arrange the inputs, for example 2 fields on the firt line, then some paragraph then two other fields.
I read about add_form_template and my guess is that this is supposed to allow me to change the template without defining the form.
Here is my attempt which does not show the fields:
Does anyone know whether I need to define the form and pass it in and how?
If I have to pass in the form, then what is add_form_template used for?
from settings import BASE_DIR
import os
#admin.register(Owner)
class OwnerAdmin(admin.ModelAdmin):
add_form_template = os.path.join(BASE_DIR, 'dealer/templates/add_owner.html')
list_display = ('name', 'country', 'city', 'car')
#admin.register(Car)
class CarAdmin(admin.ModelAdmin):
list_display = ('name',)
//----- add_owner.html
{% extends "admin/base.html" %}
{% block content %}
<h1>New Owner</h1>
<form method="POST" class="post-form">{% csrf_token %}
{{ form.as_p }}
<button type="submit" class="save btn btn-default">Create</button>
</form>
{% endblock %}
You don't have to change the admin templates to customize your field's layout. Use fieldsets instead:
# admin.py
#admin.register(Owner)
class OwnerAdmin(admin.ModelAdmin):
# ...
fieldsets = (
(None, {
'fields': (
('name', 'country'),
'city'
)
}),
('Another Fieldset', {
'description': 'Some information to display...',
'fields': (
'car',
),
}),
)

Resources