I use Ionic 3 native SQLite plugin. But below code is not working as expected. i.e. I cannot see console.log() data for the inserted data. It seems I'm doing wrong here. Can you tell me the right way?
Note: No errors. Just not working.
storeApiKeyInSqlite(key: string, name: string) {
this.sqlite.create({
name: 'MyInvoices.db',
location: 'default'
}).then((db: SQLiteObject) => {
db.executeSql('CREATE TABLE IF NOT EXISTS Apikeys(Id INT PRIMARY KEY NOT NULL, ApiKey NVARCHAR(100) NOT NULL, ApiName NVARCHAR(100) NULL)', [])
.then(() => {
db.executeSql('INSERT INTO Apikeys VALUES(NULL,?,?)', [key, name])
.then(() => {
db.executeSql('SELECT * FROM Apikeys', [])
.then(res => {
if (res.rows.length > 0) {
console.log(res.rows.item(0).Id);
console.log(res.rows.item(0).ApiKey);
console.log(res.rows.item(0).ApiName);
}
})
.catch(e => {
console.log(e);
});
}).catch(e => {
e => console.log(e)
});
}).catch(e => console.log(e));
}).catch(e => console.log(e));
}
Op's feedback:
This is the working solution for me:
storeApiKeyInSqlite(key: string, name: string) {
this.sqlite.create({
name: 'MyInvoices.db',
location: 'default'
}).then((db: SQLiteObject) => {
db.executeSql('CREATE TABLE IF NOT EXISTS Apikeys(rowid INTEGER PRIMARY KEY,ApiKey NVARCHAR(100) NOT NULL, ApiName NVARCHAR(100) NULL)', [])
.then(() => {
db.executeSql('INSERT INTO Apikeys VALUES(NULL,?,?)', [key, name])
.then(() => {
db.executeSql('SELECT * FROM Apikeys', [])
.then(res => {
if (res.rows.length > 0) {
console.log(res.rows.item(0).rowid);
console.log(res.rows.item(0).ApiKey);
console.log(res.rows.item(0).ApiName);
}
})
.catch(e => {
console.log(e);
});
}).catch(e => {
console.log(e)
});
}).catch(e => console.log(e));
}).catch(e => console.log(e));
}
Original answer:
You cant insert NULL for a PRIMARY KEY which you explicitly set as NOT NULL.
Make a query to:
db.executeSql('INSERT INTO Apikeys(ApiKey,ApiName) VALUES(?,?)', [key, name])
.then(() => {
db.executeSql('SELECT * FROM Apikeys', [])
.then(res => {
if (res.rows.length > 0) {
console.log(res.rows.item(0).Id);
console.log(res.rows.item(0).ApiKey);
console.log(res.rows.item(0).ApiName);
}
})
.catch(e => {
console.log(e);
});
}).catch(e => {
e => console.log(e)
});
Related
I'm working on Asp.net core and applying back-end validation using Fluent Validation.
The problem is, When I pass unknown property from postman over post request so it gives true response. I want to validate that unknown property.
Fluent Validation Code:
public class ScheduleADemoValidator : AbstractValidator<ScheduleADemo>
{
public ScheduleADemoValidator()
{
RuleFor(x => x.FirstName).NotEmpty().WithMessage("FirstName is required").MaximumLength(20);
RuleFor(x => x.LastName).NotEmpty().WithMessage("LastName is required").MaximumLength(20);
RuleFor(x => x.Iam).NotNull().Must(x => x == false || x == true);
RuleFor(x => x.Iaminterestedin).NotEmpty().NotEqual("-None-").WithMessage("Iaminterestedin is required");
RuleFor(x => x.Email).NotEmpty().WithMessage("Email is required").EmailAddress();
RuleFor(x => x.Phone).NotEmpty().WithMessage("Phone is required").Matches("^([0-9]{3})?[-]([0-9]{3})?[-]([0-9]{4})$");
RuleFor(x => x.NABP).NotNull().Matches("^([0-9]{7})$");
RuleFor(x => x.Pharmacyname).NotEmpty().WithMessage("Pharmacyname is required").MaximumLength(20);
RuleFor(x => x.Legalbusinessname).Length(0, 20);
RuleFor(x => x.Address).MaximumLength(50);
RuleFor(x => x.City).MaximumLength(50);
RuleFor(x => x.State).NotEmpty().NotEqual("-None-").WithMessage("State is required").Length(2);
RuleFor(x => x.ZipCode).Matches("^([0-9]{5})$");
RuleFor(x => x.IheardofPrimeRxfrom).NotEmpty().NotEqual("-None-").WithMessage("IheardofPrimeRxfrom is required").MaximumLength(30);
RuleFor(x => x.Iamlookingtobuywithin).NotEqual("-None-").WithMessage("-None- is not accepted").MaximumLength(30);
RuleFor(x => x.Iwouldliketoseeademofor).NotEmpty().NotEqual("-None-").WithMessage("Iwouldliketoseeademofor is required").MaximumLength(30);
RuleFor(x => x.Message).NotNull().MaximumLength(50);
}
protected override bool PreValidate(ValidationContext<ScheduleADemo> context, ValidationResult result)
{
if (context.InstanceToValidate == null)
{
result.Errors.Add(new ValidationFailure("", "Iam must be true or false"));
return false;
}
return true;
}
}
My controller code:
if (!validationResult.IsValid)
{
return Json(new { failure = validationResult.Errors.First().ErrorMessage });
}
var _savingScheduleADemo = new SavingScheduleADemo(_contentManager, _contentItemDisplayManager, _updateModelAccessor, _contentDefinitionManager, _session, _idGenerator);
var result = await _savingScheduleADemo.CreateScheduleADemo(
scheduleADemo.FirstName,
scheduleADemo.LastName,
scheduleADemo.Iam,
scheduleADemo.Iaminterestedin,
scheduleADemo.Email,
scheduleADemo.Phone,
scheduleADemo.NABP,
scheduleADemo.Pharmacyname,
scheduleADemo.Legalbusinessname,
scheduleADemo.Address,
scheduleADemo.City,
scheduleADemo.State,
scheduleADemo.ZipCode,
scheduleADemo.IheardofPrimeRxfrom,
scheduleADemo.Iamlookingtobuywithin,
scheduleADemo.Iwouldliketoseeademofor,
scheduleADemo.Message);
if (result)
{
return Json(new { success = true });
}
else
{
return Json(new { success = false });
}
}
Response on Postman over unknown field
Please give me your kind advice.
I use Gutenberg with WordPress for a website with students.
I would like to display a list with all students (roles : student)
and exclude from the list the student who is logged in.
I tried two solutions.
First solution with getUsers() function. When I'm logged like an administrator all works fine but when a student is logged, he does not have permission to view the list. Only administrators have permission.
Second solution with a custom API route. I got a promise pending.
First solution :
import { __ } from '#wordpress/i18n';
import { CheckboxControl } from '#wordpress/components';
import { registerPlugin } from '#wordpress/plugins';
import { PluginDocumentSettingPanel } from '#wordpress/edit-post';
import { useSelect, useDispatch } from '#wordpress/data';
import { useEntityProp } from '#wordpress/core-data';
import { useState, setState, useEffect } from '#wordpress/element';
const metaboxStudents = () => {
const postType = useSelect( ( select ) => {
return select( 'core/editor' ).getCurrentPostType();
});
if ( postType !== 'subject-imposed' ) {
return null;
}
const [ meta, setMeta ] = useEntityProp( 'postType', postType, 'meta' );
const authors = useSelect( ( select ) => {
return select( 'core' ).getUsers( { roles: 'student' } );
}, [] );
if ( !posts ) {
return null;
}
const handleCheckboxChange = (data) => {
const isChecked = meta._metafield_students.some(checkedCheckbox => checkedCheckbox === data);
if (isChecked) {
setMeta( { _metafield_students: meta._metafield_students.filter( ( checkedCheckbox) => checkedCheckbox !== data) } );
} else {
setMeta( { _metafield_students: meta._metafield_students.concat(data) } );
}
};
return(
<PluginDocumentSettingPanel
name="list-students"
title={ __( 'List of students', 'ccn-gut' ) }
className='editor-styles-metabox'
>
<div className="gut-checkboxes-group">
{ posts.map( ( data ) => (
wp.data.select("core").getCurrentUser().id !== data.id
? (
<CheckboxControl
label={ data.name }
key={`student-${data.id}`}
value={ data.id }
checked={ meta._metafield_students.some(checkedCheckbox => checkedCheckbox === data.id) }
onChange={ () => handleCheckboxChange(data.id) }
/>
) : null
) ) }
</div>
</PluginDocumentSettingPanel>
);
};
registerPlugin('plugin-document-students', {
render: metaboxStudents,
icon: null
});
Second solution :
PHP for my WordPress plugin :
wp_localize_script( 'wp-api', 'wpApiSettings', array(
'root' => esc_url_raw( rest_url() ),
'nonce' => wp_create_nonce( 'wp_rest' )
));
PHP for API route :
function student_api_rest() {
register_rest_route('api/v1/', 'students', array(
'methods' => 'GET',
'callback' => 'student_api_results'
));
}
function student_api_results($data) {
....
}
index.js :
import apiFetch from '#wordpress/api-fetch';
wp.apiFetch.use( apiFetch.createNonceMiddleware( wpApiSettings.nonce ) );
const [users, setUsers] = useState( null );
useEffect( () => {
wp.apiFetch( { path: '/api/v1/students' } ).then(
(result) => {
setUsers( result );
}
)
}, []);
console.log(users);
Which solution to choose and how to resolve one of those two solutions? Permission VS promise Pending
you should be able to add capabilities to the custom user types of "students". look for where the student role was activated, it should look something like this
add_role( $role, $display_name, $capabilities );
and your looking to add list_users as a capability I believe. You can find the full list of capabilities here https://wordpress.org/support/article/roles-and-capabilities/ and heres the link directly to the list_users section of that https://wordpress.org/support/article/roles-and-capabilities/#list_users
In my React Redux project, I am writing a thunk, and want it to dispatch only if the previous update if any has been completed. I'm aware that thunks are methods that help us delay dispatching actions to the reducer, and they can also be asynchronous. Here is what my thunk looks like right now:
myThunkMethod = () => async (dispatch, getState) =>{
dispatch(...my action...);
}
but I how can make dispatch be called only after the previous call / state update is complete
Here is what you need to do:
const firstThunk = () => (dispatch, getState) => {
// do or dispatch something here
return Promise.resoleved("first thunk resolved");
}
const secondThunk = () => (dispatch, getState) => {
// do or dispatch something here
return Promise.resolved("second thunk resolved")
}
const thirdThunk = () => (dispatch, getState) => {
// I want to first dispatch the first thunk
dispatch(firstThunk()).then(result => {
// first thunk successfully dispatched now it's time for secondThunk
dispatch(secondThunk()).then(res => {
// here both firstThunk and secondThunk dispatched successfully
})
})
}
You can combine and wait for thunks to complete as long as your thunk returns a promise: (dispatch,getState)=>Promise.
const thunkA = (arg) => (dispatch, getState) => {
//do stuff and RETURN PROMISE
return Promise;
};
const thunkB = (arg) => (dispatch, getState) => {
//do stuff and RETURN PROMISE
return Promise;
};
//combined thunk
const combinedThunk = (arg) => (dispatch, getState) =>
tunkA(arg)(dispatch, getState).then(() =>
thunkB(arg)(dispatch, getState)
);
//from component
const Component = () => {
const dispatch = React.useDispatch();
React.useEffect(() => {
dispatch(thunkA("some arg")).then(() =>
dispatch(thunkB("someArg"))
);
}, [dispatch]);
};
Here is how you can do a recursive thunk:
const recursiveThunk = (times) => (dispatch, getState) => {
if (times === 0) {
return;
}
dispatch(started());
somePromise().then(
(result) => {
dispatch(success());
return recursiveThunk(times - 1)(dispatch, getState);
},
(reject) => dispatch(failed())
);
};
It is unclear what you want in your question and your comment but if you want to call thunkA each time with an item from an array as parameter then you can do this:
const combinedThunk = (args) => (dispatch, getState) => {
if (args.length === 0) {
return;
}
return tunkA(args[0])(dispatch, getState).then(
() => combinedThunk(args.slice(1))(dispatch, getState),
(reject) => dispatch(failed(reject))
);
};
//call thunkA with 1, then 2 and then 3
dispatch(combinedThunk([1, 2, 3]));
In a Kendo grid (v2013.3) I want to auto-save a row when the user moves to a different row. So I code the change event, which fires when the row selection is changed, to call grid.saveChanges(). Then I re-select the row that we changed to (because the saveChanges seems to have canceled the row selection.) Finally, I call grid.editRow(row) so that the new row will be in edit mode.
This almost works fine. When the user changes a value in a row A, then clicks away to row B, the save action properly occurs and the web app sees the changed value. However, the UI itself reverts to the old value. This occurs because of the call to grid.editRow().
I suspect that Kendo is doing a cancel behind the scenes, even though the changed data is already saved.
Suggestions on how to address this problem? Here's the change handler:
ViLinking.gridItemSelected = function (e) {
var row = ViLinking.getSingleSelectedRow(this);
if (row == null) {
return;
}
var dataItem = this.dataItem(row);
if (dataItem == ViLinking.currentDataItem) {
return;
}
// apparently the row reference does not survive saveChanges() so prepare to re-get it.
ViLinking.currentDataItem = dataItem;
var dataUid = row.attributes["data-uid"];
var table = $(row).closest("table");
ViLinking.setKendoUpdateContentType(this);
this.saveChanges();
row = table.find('tr[data-uid="' + dataUid.value + '"]');
this.select(row);
this.editRow(row);
};
Here's the part of the view that generates the table (it's a child table)
<script id="ViDetailsTemplate" type="text/kendo-tmpl">
#(Html.Kendo().Grid<VendItemProxyForUi>()
.Name("details_#=ItemOid#")
.Columns(cs =>
{
cs.Bound(c => c.ItemOid).Hidden();
cs.Bound(c => c.VendorItemID);
cs.Bound(c => c.IsSplit);
cs.Bound(c => c.VendorItemName);
cs.Bound(c => c.VendorItemPackSize);
cs.Bound(c => c.IsCatchweight);
cs.Bound(c => c.IsApproved);
cs.Bound(c => c.UofMOidForUi).EditorTemplateName("UofmDdTemplate");//.ClientTemplate("#=UofMName#");
cs.Bound(c => c.UofMName);
cs.Command(command =>
{
command.Edit();
command.Destroy();
}).Width(200);
}
)
.Selectable()
.Editable(edit => edit.Mode(GridEditMode.InLine))
.DataSource(ds => ds
.Ajax()
.Model(mdl =>
{
mdl.Id(vi => vi.VendorItemID);
mdl.Field(f => f.VendorItemID).Editable(false);
mdl.Field(f => f.VendorItemName).Editable(false);
mdl.Field(f => f.IsSplit).Editable(false);
mdl.Field(f => f.IsCatchweight).Editable(false);
mdl.Field(f => f.DiscontinueDate).Editable(false);
mdl.Field(f => f.IsRestricted).Editable(false);
mdl.Field(f => f.VendorItemPackSize).Editable(false);
mdl.Field(f => f.IsApproved).Editable(true);
mdl.Field(f => f.UofMName).Editable(true);
}
)
.Read(read => read.Action("GetVisForGi", "ViLinkingWorksheet", new { _msk = Model.MultiSessionKey, itemOid="#=ItemOid#"}))
.Update(update => update.Action("SyncModelFromUi", "ViLinkingWorksheet", new { _msk = Model.MultiSessionKey, itemOid="#=ItemOid#", delete=false}))
.Destroy(update => update.Action("SyncModelFromUi", "ViLinkingWorksheet", new { _msk = Model.MultiSessionKey, itemOid="#=ItemOid#",delete=true}))
)
//.HtmlAttributes(new { style = "height:100px;" })
.Events(ev =>
{
ev.Change("ViLinking.gridItemSelected");
ev.Cancel("ViLinking.saveOnCancel");
})
//.Navigatable()
.ToClientTemplate())
</script>
1- View
#(Html.Kendo().Grid<User>()
.Name("GridName")
.Columns(columns =>
{
...
})
.Editable(editable => editable.Mode(GridEditMode.InCell))
.Pageable(p => p.PageSizes(new[] { 5, 10, 20, 50, 100 }))
.Groupable()
.Sortable()
.Selectable()
.Scrollable(s => s.Height("auto"))
.DataSource(ds => ds
.Ajax()
.Batch(true)
.ServerOperation(false)
.Events(events => events.Error("error_handler"))
.PageSize(20)
.Model(model =>
{
model.Id(a => a.Id);
})
.Read(read => read.Action("Read", "Users"))
.Update(update => update.Action("Update", "Users"))
)
.Events(events => events.Save("SaveChanges"))
)
<script>
function SaveChanges() {
setTimeout(function() {
$("#GridName").data("kendoGrid").dataSource.sync();
});
</script>
2- Controller
public ActionResult Update([DataSourceRequest] DataSourceRequest request, IEnumerable<User> models)
{
if (models != null && ModelState.IsValid)
{
if (models.Any())
{
foreach (var item in models)
{
Update(item); // Find item in database, modify the properties of the object & save change in database
}
}
}
return Json(models.ToDataSourceResult(request, ModelState));
}
Hi I'm using Kendo grid with dropdownlist, I followed the demo in http://demos.kendoui.com/web/grid/foreignkeycolumn.html
but Im recieving this error "DataBinding: 'System.Web.Mvc.SelectListItem' does not contain a property with the name 'Id'".
Could anyone help me to make my code work without error?
here is my viewModel :
public class AccountingViewModel
{
private string _code = string.Empty;
private string _description = string.Empty;
public int Id
{
get;set;
}
public string Code
{
get { return _code; }
set { _code = value; }
}
public string Description
{
get { return _description; }
set { _description = value; }
}
public int MajorCategoryId
{
get;set;
}
public SelectList MajorCategories
{
get;set;
}
}
Here is my Controller :
public ActionResult Index()
{
var majorCategory = new SelectList(new[]
{
new {Id="1",Name="Category1"},
new{Id="2",Name="Category2"},
new{Id="3",Name="Category3"},
},
"Id", "Name", 1);
ViewData["majorCategories"] = majorCategory;
return View(accountingService.GetAllAccountings());
}
Here is my Index View:
#model IEnumerable < PPMS.Model.ViewModels.AccountingViewModel >
< br/ >
< div class="k-grid" >
#(Html.Kendo().Grid(Model)
.Name("grid")
.Columns(columns =>
{
columns.Bound(p => p.Code);
columns.Bound(p => p.Description).Width(150);
columns.ForeignKey(p => p.MajorCategoryId, (System.Collections.IEnumerable)ViewData["majorCategories"], "Id", "Name")
.Title("MajorCategory").Width(150);
columns.Command(command => command.Destroy()).Width(110);
})
.ToolBar(toolBar =>
{
toolBar.Save();
toolBar.Create();
})
.Editable(editable => editable.Mode(GridEditMode.InCell))
.Filterable()
.Groupable()
.Pageable()
.Scrollable()
.HtmlAttributes(new { style = "height:430px;" })
.DataSource(dataSource => dataSource
.Ajax()
.Batch(true)
.PageSize(20)
.ServerOperation(false)
.Events(events => events.Error("errorHandler"))
.Model(model =>
{
model.Id(p => p.Id);
model.Field(p => p.Id).Editable(false);
model.Field(p => p.MajorCategoryId).DefaultValue(1);
})
.Create(create => create.Action("Create", "Accounting"))
.Read(read => read.Action("Index", "Accounting"))
.Update(update => update.Action("Edit", "Accounting"))
.Destroy(destroy => destroy.Action("Delete", "Accounting"))
)
)
</div>
<br/>
<script type="text/javascript">
function errorHandler(e) {
if (e.errors) {
var message = "Errors:\n";
$.each(e.errors, function (key, value) {
if ('errors' in value) {
$.each(value.errors, function () {
message += this + "\n";
});
}
});
alert(message);
}
}
</script>
I have updated my view into and is now binding the selectlist the problem now its displaying textbox inside the grid instead of a dropdownlist.. here is my updated Index view:
Here is my Index View:
#model IEnumerable < PPMS.Model.ViewModels.AccountingViewModel >
< br/ >
< div class="k-grid" >
#(Html.Kendo().Grid(Model)
.Name("grid")
.Columns(columns =>
{
columns.Bound(p => p.Code);
columns.Bound(p => p.Description).Width(150);
columns.ForeignKey(p => p.MajorCategoryId, (System.Collections.IEnumerable)ViewData["majorCategories"], "Value", "Text")
.Title("MajorCategory").Width(150);
columns.Command(command => command.Destroy()).Width(110);
})
.ToolBar(toolBar =>
{
toolBar.Save();
toolBar.Create();
})
.Editable(editable => editable.Mode(GridEditMode.InCell))
.Filterable()
.Groupable()
.Pageable()
.Scrollable()
.HtmlAttributes(new { style = "height:430px;" })
.DataSource(dataSource => dataSource
.Ajax()
.Batch(true)
.PageSize(20)
.ServerOperation(false)
.Events(events => events.Error("errorHandler"))
.Model(model =>
{
model.Id(p => p.Id);
model.Field(p => p.Id).Editable(false);
model.Field(p => p.MajorCategoryId).DefaultValue(1);
})
.Create(create => create.Action("Create", "Accounting"))
.Read(read => read.Action("Index", "Accounting"))
.Update(update => update.Action("Edit", "Accounting"))
.Destroy(destroy => destroy.Action("Delete", "Accounting"))
)
)
</div>
<br/>
<script type="text/javascript">
function errorHandler(e) {
if (e.errors) {
var message = "Errors:\n";
$.each(e.errors, function (key, value) {
if ('errors' in value) {
$.each(value.errors, function () {
message += this + "\n";
});
}
});
alert(message);
}
}
</script>
The foreign dropdown list should contain items which have a "value" and "text" property ?
Like:
var categories = [{
"value": 1,
"text": "Beverages"
},{
"value": 2,
"text": "Condiments"
}
}];