I built a simply CRUB using spring boot and thymeleaf but the form does not save values to the database on submit.
Here is my controller:
#Controller
public class ClientController {
private static final Logger LOG = LoggerFactory.getLogger(ClientController.class);
#Autowired
private ClientRepository clientRepository;
#GetMapping("/patients")
public String getAllClients(Model model) {
List<Client> clients = clientRepository.findAll();
model.addAttribute("clients", clients);
return "patient/list-patients";
}
#GetMapping("/add-patient")
public String addClient(Model model) {
model.addAttribute("client", new Client());
return "patient/add-patient";
}
#PostMapping("/add-patient")
public String addClient(#Valid #ModelAttribute Client client, BindingResult bindingResult) {
LOG.info("Saving client: {}", client);
if (bindingResult.hasErrors()) {
return "patient/add-patient";
}
clientRepository.save(client);
return "redirect:/add-patient";
}
#GetMapping("/edit/{id}")
public String editClient(#PathVariable("id") Long id, Model model) {
model.addAttribute("client", clientRepository.findById(id).orElse(null));
return "patient-edit";
}
#GetMapping("/delete/{id}")
public String deleteClient(#PathVariable("id") Long id) {
clientRepository.deleteById(id);
return "redirect:/patients";
}
}
The model has the following code:
#Entity
#Data
public class Client {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String patientId;
#Size(min=2, max=30)
private String firstName;
#Size(min=2, max=30)
private String lastName;
private String otherName;
private String gender;
private String email;
private Date dateOfBirth;
private String ageGroup;
private String phoneNumber;
private String address;
// Identity
private String cardType;
private String cardNumber;
private String iDCardNumber;
//getters and setters
}
And finally, the form is as follows:
< div >
<
form action = "#"
th: action = "#{/add-patient}"
method = "post" >
<
p >
<
label
for = "firstName" > First Name: < /label> <
input type = "text"
id = "firstName"
name = "firstName" / >
<
/p> <
p >
<
label
for = "lastName" > Last Name: < /label> <
input type = "text"
id = "lastName"
name = "lastName" / >
<
/p> <
p >
<
label
for = "otherName" > Other Name(s): < /label> <
input type = "text"
id = "otherName"
name = "otherName" / >
<
/p> <
p >
<
label
for = "dateOfBirth" > Date of Birth: < /label> <
input type = "date"
id = "dateOfBirth"
name = "dateOfBirth" / >
<
/p> <
p >
<
label
for = "address" > Address: < /label> <
input type = "text"
id = "address"
name = "address" / >
<
/p> <
p >
<
label
for = "email" > Email: < /label> <
input type = "email"
id = "email"
name = "email" / >
<
/p> <
p >
<
label
for = "phoneNumber" > Phone Number: < /label> <
input type = "tel"
id = "phoneNumber"
name = "phoneNumber" / >
<
/p> <
p >
<
label
for = "gender" > Gender: < /label> <
select id = "gender"
name = "gender" >
<
option value = "Male" > Male < /option> <
option value = "Female" > Female < /option> <
option value = "Other" > Other < /option> <
/select> <
/p> <
p >
<
label
for = "ageGroup" > Age Group: < /label> <
select id = "ageGroup"
name = "ageGroup" >
<
option value = "Under 18" > Under 18 < /option> <
option value = "18-25" > 18 - 25 < /option> <
option value = "26-35" > 26 - 35 < /option> <
option value = "36-45" > 36 - 45 < /option> <
option value = "46-55" > 46 - 55 < /option> <
option value = "Over 55" > Over 55 < /option> <
/select> <
/p> <
p >
<
label
for = "cardType" > Card Type: < /label> <
select id = "cardType"
name = "cardType" >
<
option value = "passport" > Passport < /option> <
option value = "Ghana Card" > Ghana Card < /option> <
/select> <
/p> <
p >
<
label
for = "cardNumber" > Card Number: < /label> <
input type = "text"
id = "cardNumber"
name = "cardNumber" / >
<
/p> <
input type = "submit"
value = "Save" / >
<
/form> <
/div>
Solved it, apparently i have to update my controller with the method:
#PostMapping("/add-patient")
public String addClient(#ModelAttribute Client client) {
LOG.info("Saving client: {}", client);
// Format the date
Date date = client.getDateOfBirth();
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
String strDate = dateFormat.format(date);
client.setDateOfBirth(client.getDateOfBirth());
clientRepository.save(client);
return "redirect:/add-patient";
}
and finally add
#DateTimeFormat(pattern = "yyyy-MM-dd")
Worked for me
Related
I have a issue here for the connect mysql.
I have a vps that contain mysql server have a database name is 'tuyendungbg'. it's had table and data in there. But when i'm connect and query to select data, that have error for 'Table 'tuyendungbg.Careers' doesn't exist'.
here is my controller :
[HttpGet("/nganh-nghe/{slug?}")]
public IActionResult Index(string slug, [FromQuery(Name =
"p")] int currentPage, int
pageSize)
{
if (!string.IsNullOrEmpty(slug))
{
var career = _context.Careers.FirstOrDefault(x =>
x.Slug.Equals(slug));
if (career != null)
{
ViewBag.CareerName = career.CareerName;
//var qr = _context.Careers.ToList();
var qr = (from p in
_context.CompanyCareers.Where(x => x.CareerId ==
career.ID)
from b in _context.Companies.Where(x =>
x.Id == p.CompanyId)
from i in
_context.IndustrialAreas.Where(x => x.ID ==
b.IndustrialAreaId).DefaultIfEmpty()
select new CompanyModelView()
{
Id = b.Id,
CompanyName = b.CompanyName,
BasicSalary = b.BasicSalary,
Allowance = b.Allowance,
DateCreate = b.DateCreate,
JobTitle = b.JobTitle,
Src = b.Src,
_IndustrialArea = i,
Address = b.Address,
Slug = b.Slug,
WorkTypes = (from tc in
_context.CompanyWorkTypes.Where(x =>
x.CompanyId == b.Id)
from type in
_context.WorkTypes.Where(x => x.Id
==
tc.TypeId)
select type)
}
).OrderByDescending(x => x.DateCreate).ToList();
// var worktype = (from w in
_context.CompanyWorkTypes.Where(x =>
x.CompanyId
== qr.))
var totalCate = qr.Count();
if (pageSize <= 0) pageSize = 10;
int countPages =
(int)Math.Ceiling((double)totalCate / pageSize);
if (currentPage > countPages)
currentPage = countPages;
if (currentPage < 1)
currentPage = 1;
var pagingModel = new PagingModel()
{
countpages = countPages,
currentpage = currentPage,
generateUrl = (pageNumber) =>
Url.Action(nameof(Index), new
{
p = pageNumber,
pageSize = pageSize
})
};
ViewBag.pagingModel = pagingModel;
ViewBag.totalPost = totalCate;
ViewBag.cateIndex = (currentPage - 1) * pageSize;
var companies = qr.Skip((currentPage - 1) *
pageSize)
.Take(pageSize).ToList();
ViewBag.JobCount = companies.Count();
//Set slider menu
var leftSlider = new LeftSliderModel()
{
Areas = new SelectList(_context.Areas,
nameof(Area.ID),
nameof(Area.NameArea)),
Careers = new SelectList(_context.Careers,
nameof(Career.ID),
nameof(Career.CareerName)),
WorkTypes = _context.WorkTypes.ToList(),
Experiences = _context.Experiences.ToList()
};
ViewBag.LeftSlider = leftSlider;
return View(companies);
}
}
return NotFound();
}
I'm building a webapp in which are inputboxes with a date. How can I bind the data to my background code?
I tried just doing it directly but i guess an inputbox can only handle strings so a made a convert to string method and so on.
<div>
<label>start date: </label>
<input [(ngModel)]="item.stringStartDate" placeholder="start date" type="date">
</div>
void set startDate(DateTime startDate)
{
_startDate = startDate;
}
void set stringStartDate(String startDate)
{
this.startDate = parseDate(startDate);
}
static DateTime parseDate(String formattedString)
{
final RegExp r = new RegExp(
r'^(\d\d)-?(\d\d)-?([+-]?\d{4,6})');
Match match = r.firstMatch(formattedString);
if (match != null)
{
int years = int.parse(match[3]);
int month = int.parse(match[2]);
int day = int.parse(match[1]);
return new DateTime(years, month, day);
}
else
{
throw new FormatException("Invalid date format", formattedString);
}
}
static String dateToString(DateTime date){
if (date == null)
return null;
String ret = "${date.year}/";
if (date.month < 10)
ret+="0";
ret+="${date.month}/";
if (date.day < 10)
ret += "0";
ret+="${date.day}";
return ret;
}
it should be separated by - instead of /
you can use toIso8601String and substring
DateTime _date = new DateTime.now();
String get date => _date.toIso8601String().substring(0, 10);
void set date(value) {
if (value is DateTime) {
_date = value;
} else if (value is String) {
_date = DateTime.parse(value);
}
}
I wanted to create the ability to have "random" (pseudo-random) colors generated and came up with this code intended to create all and any color.
I'm very new to programming and wanted to see if anyone on S.O. had any comments or criticisms, the code works great. Only problem is the colors occasionally being too similar making it difficult to differentiate bewteen them.
I know this is likely a very brute force fashion of coding but its what I thought of.
Hexidecimal generator
public class colorGenerator
{
public var color:int;
private var randomnumber:Number;
private var first:String = "";
public function colorGenerator():void
{
var colorstring:String = "0x";
var transfer:String = "0x";
for ( var i:uint = 0; i < 6; i++)
{
randomhex();
colorstring += first;
}
transfer = colorstring;
color = int(transfer);
}
public function randomhex():void
{
randomnumber = Math.random();
if ( -1 < randomnumber < ((.99 / 16) * 1))
first = "0";
else if ( ((.99/16)*1) < randomnumber < ((.99/16)*2))
first = "1";
else if ( ((.99/16)*2)< randomnumber < ((.99/16)*3))
first = "2";
else if ( ((.99/16)*3)< randomnumber < ((.99/16)*4))
first = "3";
else if ( ((.99/16)*4)< randomnumber < ((.99/16)*5))
first = "4";
else if ( ((.99/16)*5)< randomnumber < ((.99/16)*6))
first = "5";
else if ( ((.99/16)*6)< randomnumber < ((.99/16)*7))
first = "6";
else if ( ((.99/16)*7)< randomnumber < ((.99/16)*8))
first = "7";
else if ( ((.99/16)*8)< randomnumber < ((.99/16)*9))
first = "8";
else if ( ((.99/16)*9)< randomnumber < ((.99/16)*10))
first = "9";
else if ( ((.99/16)*10)< randomnumber < ((.99/16)*11))
first = "A";
else if ( ((.99/16)*11)< randomnumber < ((.99/16)*12))
first = "B";
else if ( ((.99/16)*12)< randomnumber < ((.99/16)*13))
first = "C";
else if ( ((.99/16)*13)< randomnumber < ((.99/16)*14))
first = "D";
else if ( ((.99/16)*14)< randomnumber < ((.99/16)*15))
first = "E";
else if ( ((.99/16)*15)< randomnumber < 2)
first = "F";
}
}
I then just assign the hexidecimal value to a variable in another class
var acolor:colorGenerator = new colorGenerator;
var COLOR:uint = acolor.color
Thanks for any comments!
This should work as well.
Math.random() * 0xFFFFFF;
Not tested but this should be more "random":
var red : int = Math.floor(Math.random()*255);
var green : int = Math.floor(Math.random()*255);
var blue : int = Math.floor(Math.random()*255);
var color : int = red << 16 | green << 8 | blue;
We are using mySQL with WCF Restful service, we want to fetch our database content PACKAGEID wise...as mentioned below:
PackageId=2
{
StartRange = 1;
EndRange = 100;
IsDiscountAndChargeInPer = 1;
Discount =10;
ServiceCharge = 20;![enter image description here][1]
},
{
StartRange =101;
EndRange = 500;
IsDiscountAndChargeInPer = 1;
Discount =10;
ServiceCharge = 20;
}
PackageId=3
{
StartRange = 1;
EndRange = 100;
IsDiscountAndChargeInPer = 1;
Discount =10;
ServiceCharge = 20;
}
We have created a Result class to return result from out wcf service...for above service we have result class defined as below
[DataContract]
public class PackagePointRangeConfigurationResult : ResultBase
{
[DataMember]
public List<PackagePointRangeResult> Result;
}
public class PackagePointRangeResult
{
public int PackageId { get; set; }
public List<PointPlanInfo> Result { get; set; }
}
For fetching record we use following linq query:
var result = (from planinfo in db.mst_pointplan_info
join entityType in db.mst_entity_type
on planinfo.entityId equals entityType.id
where planinfo.entityId == entityId
&& planinfo.is_deleted != true
&& planinfo.system_id == systemId
&& entityType.enity_enum_id == entityId
group planinfo by planinfo.package_id into gplan
select new PackagePointRangeConfigurationResult
{
Result = (from planinfo in gplan
select new PackagePointRangeResult
{
PackageId = planinfo.package_id,
PointPlanInfo = (from pointPlanInfo in gplan
select new PointPlanInfo
{
StartRange = planinfo.start_range,
EndRange = planinfo.end_range,
IsDiscountAndChargeInPer = planinfo.is_discount_and_charge_in_per,
Discount = planinfo.discount,
ServiceCharge = planinfo.servicecharge,
AtonMerchantShare =planinfo.aton_merchant_share,
CommunityShare = planinfo.community_share
}).ToList()
}).ToList()
}).FirstOrDefault();
But it gives me below error:
LINQ to Entities does not recognize the method 'System.Collections.Generic.List1[PointPlanInfo] ToList[PointPlanInfo](System.Collections.Generic.IEnumerable1[PointPlanInfo])' method, and this method cannot be translated into a store expression.
I am able to do this query just fine with the test repository which is In Memory
when I move to the sqlRepository I get this error
Unsupported overload used for query operator 'Intersect'.
I assume it is because sending the query to sql is too complicated for Linq to Sql to do when it is not dealing with the Model.Model.Talent Type. Is there some way around doing a search like this with Intersect?
thanks
public class TalentService : ITalentService
{
ITalentRepository _repository = null;
private IQueryable<Talent> BasicSearch(string searchExpression)
{
IQueryable<Talent> t;
string[] sa = searchExpression.Trim().ToLower().Replace(" ", " ").Split(' ');
t = _repository.GetTalents();
foreach (string s in sa)
{
t = t.Intersect(AddBasicSearch(s), new TalentComparer());
}
return t;
}
private IQueryable<Talent> AddBasicSearch(string s)
{
IQueryable<Talent> t2 = _repository.GetTalents()
.Where(tal => tal.EyeColor.ToString().ToLower().Contains(s)
|| tal.FirstName.ToLower().Contains(s)
|| tal.LastName.ToLower().Contains(s)
|| tal.LanguagesString.ToLower().Contains(s)
);
return t2;
}
}
public class SqlTalentRepository:ITalentRepository
{
public IQueryable<Model.Model.Talent> GetTalents()
{
var tal = from t in _db.Talents
let tLanguage = GetTalentLanguages(t.TalentID)
where t.Active == true
select new Model.Model.Talent
{
Id = t.TalentID,
FirstName = t.FirstName,
LastName = t.LastName,
TalentLanguages = new LazyList<Model.Model.TalentLanguage>(tLanguage),
LanguagesString = t.TalentLanguages.ToLanguageNameString(_LanguageRepository.GetLanguages())
};
return tal ;
}
public IQueryable<Model.Model.TalentLanguage> GetTalentLanguages(int iTalentId)
{
var q = from y in this.talentLanguageList
let Languages = _LanguageRepository.GetLanguages()
where y.TalentId == iTalentId
select new Model.Model.TalentLanguage
{
TalentLanguageId = y.TalentLanguageId,
TalentId = y.TalentId,
LanguageId = y.LanguageId,
Language = Languages.Where(x => x.LanguageId == y.LanguageId).SingleOrDefault()
};
return q.AsQueryable<Model.Model.TalentLanguage>();
}
}
public static class TalentExtensions
{
public static string ToLanguageNameString(this IEnumerable<TalentLanguage> source
, IEnumerable<Model.Model.Language> allLanguages)
{
StringBuilder sb = new StringBuilder();
const string del = ", ";
foreach (TalentLanguage te in source)
{
sb.AppendFormat("{0}{1}", allLanguages
.Where(x => x.LanguageId == te.LanguageID).SingleOrDefault().LanguageName, del);
}
string sReturn = sb.ToString();
if (sReturn.EndsWith(del))
sReturn = sReturn.Substring(0, sReturn.Length - del.Length);
return sReturn;
}
}
public class TestTalentRepository : ITalentRepository
{
IList<Talent> talentList;
public TestTalentRepository(ILanguageRepository _LanguageRepo )
{
this._LanguageRepository = _LanguageRepo;
talentList = new List<Talent>();
talentLanguageList = new List<TalentLanguage>();
for (int i = 0; i < 55; i++)
{
var t = new Talent();
t.Id = i;
t.FirstName = (i % 3 == 0) ? "Ryan" : "Joe";
t.LastName = (i % 2 == 0) ? "Simpson" : "Zimmerman";
AddLanguagesToTestTalent(i, t);
talentList.Add(t);
}
}
private void AddLanguagesToTestTalent(int i, Talent t)
{
IList<Language> Languages = _LanguageRepository.GetLanguages().ToList<Language>();
Random rLanguages = new Random();
int numLanguages = rLanguages.Next(Languages.Count - 1) + 1;
t.TalentLanguages = new LazyList<TalentLanguage>();
for (int j = 0; j < numLanguages; j++)
{
var x = new TalentLanguage();
x.TalentLanguageId = j;
x.TalentId = i;
Random random2 = new Random();
int rand = random2.Next(Languages.Count);
var y = Languages.ElementAtOrDefault(rand);
Languages.RemoveAt(rand);
x.Language = y;
x.LanguageId = y.LanguageId;
t.TalentLanguages.Add(x);
}
}
public IQueryable<Talent> GetTalents()
{
var ts = from t in this.talentList
let tLanguage = GetTalentLanguages(t.Id)
where t.Active == true
select new Model.Model.Talent
{
Id = t.Id,
FirstName = t.FirstName,
LastName = t.LastName,
TalentLanguages = new LazyList<Model.Model.TalentLanguage>(tLanguage),
LanguagesString = t.TalentLanguages.ToLanguageNameString(_LanguageRepository.GetLanguages()),
City = t.City,
};
return ts.AsQueryable<Model.Model.Talent>();
}
public IQueryable<Model.Model.TalentLanguage> GetTalentLanguages(int iTalentId)
{
var q = from y in this.talentLanguageList
let Languages = _LanguageRepository.GetLanguages()
where y.TalentId == iTalentId
select new Model.Model.TalentLanguage
{
TalentLanguageId = y.TalentLanguageId,
TalentId = y.TalentId,
LanguageId = y.LanguageId,
Language = Languages.Where(x => x.LanguageId == y.LanguageId).SingleOrDefault()
};
return q.AsQueryable<Model.Model.TalentLanguage>();
}
}
If you're trying to find entries which match all of those criteria, you just need multiple where clauses:
private static readonly char[] SplitDelimiters = " ".ToCharArray();
private IQueryable<Talent> BasicSearch(string search)
{
// Just replacing " " with " " wouldn't help with "a b"
string[] terms = search.Trim()
.ToLower()
.Split(SplitDelimiters,
StringSplitOptions.RemoveEmptyEntries);
IQueryable<Talent> query = _repository.GetTalents();
foreach (string searchTerm in terms)
{
query = AddBasicSearch(query, searchTerm);
}
return query;
}
private IQueryable<Talent> AddBasicSearch(IQueryable<Talent> query, string s)
{
return query.Where(tal =>
tal.EyeColor.ToString().ToLower().Contains(s)
|| tal.FirstName.ToLower().Contains(s)
|| tal.LastName.ToLower().Contains(s)
|| tal.LanguagesString.ToLower().Contains(s)
);
}