How to through error message in Yii2 Api? - api

Here is the code attached.
How can I throw an error message if any attribute is missing?
I need to check if all attributes are coming from the form or not. If any attribute is missing I want to throw an error message with proper error code.
$get_email = Null;
$get_password = Null;
$get_username = Null;
if (isset($_POST['username']) ) {
$get_username = $_POST['username'];
}
if (isset($_POST['email']) && isset($_POST['password']) ) {
$get_email = $_POST['email'];
$get_password = $_POST['password'];
}
if ($get_email == Null || $get_username == Null || $get_password == Null ) {
// through error code with message
}
else {
$model = new SignupForm();
$model->email = $get_email;
$model->username = $get_username;
$model->password = $get_password;
}

Here is the code through which I have achieved my goal.
$model = new SignupForm;
if (isset($_POST['username'] )) {
$model->username = $_POST['username'];
}
if (isset($_POST['email'] )) {
$model->email = $_POST['email'];
}
if (isset($_POST['password'] )) {
$model->password = $_POST['password'];
}
if($model->validate()){
$model->signup();
}
else{
return $model->getErrors();
}

Related

Yii2 Update the entry if it exists

Item $title defined earlier. I want what if found $find_title, update it with all fields from $title. Otherwise, create a new object
$find_title = Title::find()->where(["upc" => $title->upc])->one();
if ($find_title != null) {
$title->id = $find_title->id;
$title->save();
} else {
$title->save();
}
It worked in the laravel.
$find_title = Title::find()->where(["upc" => $title->upc])->one();
if ($find_title != null) {
$id = $title->id;
$find_title->attributes = $title->attributes;
$find_title->id = $id;
$find_title->save();
} else {
$title->save();
}
Here you assign all attributes of $title to $find_title, restore id, and then save;

How to fix '0 level missing for abstractListDefinition 0' error when using Emulator.getNumber()

I used docx4j to read the docx file. And I need to read the paragraph number format characters. I use Emulator.getNumber() to process, but I got this error. How should I deal with it?
try {
PPr pPr = ((P) p).getPPr();
if (pPr != null && pPr.getNumPr() != null) {
Emulator.ResultTriple triple = Emulator.getNumber(wordprocessingMLPackage, pPr);
if (triple != null) {
order = triple.getNumString();
}
}
} catch (Exception e) {
// throw error '0 level missing for abstractListDefinition 0'
e.printStackTrace();
}
Any help would be appreciated.Thanks.
docx4j version: 6.1.2
docx4j's html output uses it like so:
// Numbering
String numberText=null;
String numId=null;
String levelId=null;
if (pPrDirect.getNumPr()!=null) {
numId = pPrDirect.getNumPr().getNumId()==null ? null : pPrDirect.getNumPr().getNumId().getVal().toString();
levelId = pPrDirect.getNumPr().getIlvl()==null ? null : pPrDirect.getNumPr().getIlvl().getVal().toString();
}
ResultTriple triple = org.docx4j.model.listnumbering.Emulator.getNumber(
conversionContext.getWmlPackage(), pStyleVal, numId, levelId);
if (triple==null) {
getLog().debug("computed number ResultTriple was null");
} else {
if (triple.getBullet() != null) {
//numberText = (triple.getBullet() + " ");
numberText = "\u2022 ";
} else if (triple.getNumString() == null) {
getLog().error("computed NumString was null!");
numberText = ("?");
} else {
numberText = (triple.getNumString() + " ");
}
}
if (numberText!=null) {
currentParent.appendChild(document.createTextNode(
numberText + " "));
}
XSL-FO output:
if (pPrDirect!=null && pPrDirect.getNumPr()!=null) {
triple = org.docx4j.model.listnumbering.Emulator.getNumber(
conversionContext.getWmlPackage(), pStyleVal,
pPrDirect.getNumPr().getNumId().getVal().toString(),
pPrDirect.getNumPr().getIlvl().getVal().toString() );
} else {
// Get the effective values; since we already know this,
// save the effort of doing this again in Emulator
Ilvl ilvl = pPr.getNumPr().getIlvl();
String ilvlString = ilvl == null ? "0" : ilvl.getVal().toString();
triple = null;
if (pPr.getNumPr().getNumId()!=null) {
triple = org.docx4j.model.listnumbering.Emulator.getNumber(
conversionContext.getWmlPackage(), pStyleVal,
pPr.getNumPr().getNumId().getVal().toString(),
ilvlString );
}
}

Having error in updating my record in database my method as follows

What I have done wrong in this code ? (I am using MVC4 and EF)
As an example: Please clear this am fresher to use MVC4
EditResponse response = new EditResponse();
try
{
using (WeMatchContext db = new WeMatchContext())
{
B_MEMBER_REGISTER update = new B_MEMBER_REGISTER();
var output = db.B_MEMBER_REGISTER.Where(x => x.MEMBER_ID == model.MEMBER_ID).FirstOrDefault();
if(output != null )
{
update.FIRST_NAME = model.FIRST_NAME;
update.LAST_NAME = model.LAST_NAME;
update.GENDER = model.GENDER;
update.DOB = model.DOB;
int resultcount = db.SaveChanges();
if (resultcount > 0)
{
response.MEMBER_ID = update.MEMBER_ID;
response.ResultCode = 0;
response.Message = "Updated Successfully";
}
You have to attach updated data with the db entity. please try this,
using (WeMatchContext db = new WeMatchContext())
{
var update = db.B_MEMBER_REGISTER.Where(x => x.MEMBER_ID == model.MEMBER_ID).FirstOrDefault();
if(update != null )
{
update.FIRST_NAME = model.FIRST_NAME;
update.LAST_NAME = model.LAST_NAME;
update.GENDER = model.GENDER;
update.DOB = model.DOB;
//below line of code is very important.
db.B_MEMBER_REGISTER.Attach(update);
db.Entry(update).State = EntityState.Modified;
int resultcount = db.SaveChanges();
if (resultcount > 0)
{
response.MEMBER_ID = update.MEMBER_ID;
response.ResultCode = 0;
response.Message = "Updated Successfully";
}
}
}

Error: Only primitive types or enumeration types are supported in this context

[HttpPost]
public ActionResult Dep_Save_Attachments(int in_queue_id, HttpPostedFileBase httpfile, string authorized_by, string authorized_to, string confirmed_by, string approved_by)
{
if (httpfile != null)
{
var folder = Server.MapPath("~/Attachments/Laptops/" + in_queue_id + "/");
var prev_fa = db.File_Attachments.Where(x => x.inventory_table_id == in_queue_id).Where(x => x.is_active == true).ToList();
var prev_hfa = db.HW_Authorization_Forms.Where(x => x.file_attachments_id == prev_fa.FirstOrDefault().file_attachments_id).Where(x => x.is_active == true).ToList();
if (!Directory.Exists(folder))
{
Directory.CreateDirectory(folder);
}
if (prev_fa.Count != 0)
{
foreach (var pf in prev_fa)
{
pf.is_active = false;
db.Entry(pf).State = EntityState.Modified;
db.SaveChanges(); ;
}
}
if (prev_hfa.Count != 0)
{
foreach (var hpf in prev_hfa)
{
hpf.is_active = false;
db.Entry(hpf).State = EntityState.Modified;
db.SaveChanges(); ;
}
}
try
{
string path = System.Web.HttpContext.Current.Server.MapPath("~/Attachments/Laptops/" + in_queue_id + "/") + System.IO.Path.GetFileName(httpfile.FileName);
httpfile.SaveAs(path);
File_Attachments fa = new File_Attachments();
fa.file_attachments_id = 1;
fa.inventory_table_name = "Laptops_Transactions";
fa.inventory_table_id = in_queue_id;
fa.file_name = System.IO.Path.GetFileName(httpfile.FileName);
fa.file_path = "http://" + Request.Url.Host + ":" + Request.Url.Port + "/Attachments/Laptops/" + httpfile.FileName;
fa.created_by = #User.Identity.Name.Remove(0, 9).ToLower();
fa.created_date = System.DateTime.Now;
fa.is_active = true;
db.File_Attachments.Add(fa);
db.SaveChanges();
Laptops_Transactions laptops_trans = db.Laptops_Transactions.Find(in_queue_id);
laptops_trans.lp_trans_type = "deployed";
laptops_trans.lp_date_returned = System.DateTime.Now;
db.Entry(laptops_trans).State = EntityState.Modified;
db.SaveChanges();
HW_Authorization_Forms hwf = new HW_Authorization_Forms();
hwf.hw_authorization_forms_id = 1;
hwf.file_attachments_id = fa.file_attachments_id;
hwf.hw_authorized_by = authorized_by;
hwf.hw_authorized_to = authorized_to;
hwf.hw_confirmed_by = confirmed_by;
hwf.hw_approved_by = approved_by;
hwf.hw_approved_date = fa.created_date;
hwf.created_by = fa.created_by;
hwf.created_date = fa.created_date;
hwf.hw_authorized_date = fa.created_date;
hwf.hw_confirmed_date = fa.created_date;
hwf.is_active = true;
db.HW_Authorization_Forms.Add(hwf);
db.SaveChanges();
}
catch
{
}
}
else
{
return Content("<script language='javascript' type='text/javascript'>alert('Please Attach the Deployment Authorization Form! Kindly go back to previous page');</script>");
}
return RedirectToAction("Index");
}
The error is on this line:
var prev_hfa = db.HW_Authorization_Forms.Where(x => x.file_attachments_id == prev_fa.FirstOrDefault().file_attachments_id).Where(x => x.is_active == true).ToList();
This is my code in the controller, actually this is working already but it suddenly have a error. I really don't have an idea why i have this kind of error where before it works perfectly.
Please help me with this. Need some advice. Thanks in advance.
The error is because of Datatype issue i guess, you need to confirm you are doing with correct datatype, file_attachments_id of database and from your comparing value must be same.
Also, is_active must be of datatype Boolean. Correcting this may solve your error.

Rewriting search button from web forms application to mvc4

I have a web forms application with a service reference
and I need to rewrite only the front-end of it in mvc4
I'm having trouble with search button (still new to programming)
this is the code of it in web forms
private void btnSearch_Click(object sender, EventArgs e)
{
ClearViewers();
btnSearch.Enabled = false;
btnSyncronise.Enabled = false;
PersonalInformation localInfo = null;
PersonInfo[] registryInfo = null;
needsUpdate = false;
Cursor = Cursors.WaitCursor;
try
{
if ((String.IsNullOrEmpty(txtPersonalNumber.Text)) || (txtPersonalNumber.Text.Length != 11) || (Regex.Match(txtPersonalNumber.Text, "^\\d{11}$").Success == false))
{
MessageBox.Show(#"blabla" + Environment.NewLine + #"blablabla" + Environment.NewLine + #"blabla", #"blabla", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
using (PersonalInfoServiceClient proxy = new PersonalInfoServiceClient())
{
try
{
localInfo = proxy.GetLocalInfoForPerson(txtPersonalNumber.Text.Trim());
if (localInfo != null)
{
ssStatusLocal.ForeColor = Color.Green;
ssStatusLocal.Text = #"found personal ID";
lblFirstName.Text = localInfo.FirstName;
lblLastName.Text = localInfo.LastName;
lblMiddleName.Text = localInfo.MiddleName;
lblBirthDate.Text = String.Format("{0:MM/dd/yyyy}", localInfo.BirthDate);
if (localInfo.PersonStatus == PersonStatus.Active)
lblStatus.Text = #"active";
else if (localInfo.PersonStatus == PersonStatus.Rejected)
lblStatus.Text = #"passive";
else if (localInfo.PersonStatus == PersonStatus.Dead)
lblStatus.Text = #"dead";
else
lblStatus.Text = #"unknown";
lblSex.Text = (Convert.ToInt32(localInfo.Sex) == 1) ? #"male" : #"female";
lblAddress.Text = localInfo.Address;
lbBirthPlace.Text = localInfo.BirthPlace;
lbCitizenShip.Text = (string.IsNullOrEmpty(localInfo.CitizenShip) && string.IsNullOrEmpty(localInfo.CitizenShipCode)) ? localInfo.CitizenShip : localInfo.CitizenShip + " / " + localInfo.CitizenShipCode;
lbDoubleCitizenShip.Text = (string.IsNullOrEmpty(localInfo.DoubleCitizenShip) && string.IsNullOrEmpty(localInfo.DoubleCitizenShipCode)) ? localInfo.DoubleCitizenShip : localInfo.DoubleCitizenShip + " / " + localInfo.DoubleCitizenShipCode;
lblRegion.Text = localInfo.RegionName;
if (localInfo.Photo != null)
{
MemoryStream MS = new MemoryStream(localInfo.Photo);
pictureBox2.Image = Image.FromStream(MS);
}
documentInformationBindingSource1.DataSource = localInfo.Documents;
}
else
{
ssStatusLocal.ForeColor = Color.Red;
ssStatusLocal.Text = #"personal ID not found";
}
}
catch
{
ssStatusLocal.ForeColor = Color.Red;
ssStatusLocal.Text = #"error";
throw;
}
try
{
registryInfo = proxy.GetRegistryInfoForPerson(txtPersonalNumber.Text.Trim());
if (registryInfo != null && registryInfo.Length > 0)
{
ssStatusCivil.ForeColor = Color.Green;
ssStatusCivil.Text = #"found personal ID";
btnSyncronise.Enabled = true;
RegistryPersonInfos list = new RegistryPersonInfos();
foreach (PersonInfo personInfo in registryInfo)
{
RegistryPersonInfo registryPersonInfo = new RegistryPersonInfo()
{
BirthDate = personInfo.BirthDate
,
IsDead = (personInfo.IsPersonDead) ? "yes" : "no"
,
FirstName = personInfo.FirstName
,
LastName = personInfo.LastName
,
MiddleName = personInfo.MiddleName
,
DocumentStatusName = personInfo.DocumentStatusStr
,
DocumentStatus = personInfo.DocumentStatusEnum.ToString()
,
PersonalNumber = personInfo.PrivateNumber
,
DocumentRejectDate = personInfo.RejectedDate
,
DocumentType = (personInfo.IsIdCard) ? (string.IsNullOrEmpty(personInfo.IdCardNumber)) ? "one" : "two" : "three"
,
DocumentSerie = (personInfo.IsIdCard) ? personInfo.IdCardSerial : string.Empty
,
DocumentNumber = (personInfo.IsIdCard) ? (string.IsNullOrEmpty(personInfo.IdCardNumber)) ? string.Empty : personInfo.IdCardNumber : personInfo.PaspNumber
};
list.Add(registryPersonInfo);
}
registryPersonInfoBindingSource.DataSource = list;
}
else
{
ssStatusCivil.ForeColor = Color.Red;
ssStatusCivil.Text = #"Personal ID not found";
}
}
catch
{
ssStatusCivil.ForeColor = Color.Red;
ssStatusCivil.Text = #"error";
throw;
}
}
}
catch (Exception x)
{
lblFirstName.Text = String.Empty;
lblLastName.Text = String.Empty;
lblMiddleName.Text = String.Empty;
lblStatus.Text = String.Empty;
needsUpdate = false;
dgwMain.DataSource = null;
MessageBox.Show(
String.Format(
"error during loading. {0} error: {1} {2} info: {3}",
Environment.NewLine, x.Message, Environment.NewLine,
(x.InnerException == null) ? string.Empty : x.InnerException.Message), #"Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
Cursor = Cursors.Default;
btnSearch.Enabled = true;
}
}
how do you write this in controller?
the controller can't find labels, there is no picturebox
I have no idea how to get data via service reference
could you help ?