I want to create a list of all customers in my custom module I am building, but I can't seem to figure out the problem. I tried this:
public function getAllOptions($withEmpty = true, $defaultValues = false)
{
$source = Mage::getModel('eav/config')->getAttribute('customer', 'firstname');
return $source->getSource()->getAllOptions($withEmpty, $defaultValues);
}
But it gives me an error:
Source model "" not found for attribute "firstname"
#0 /var/www/c8do/app/code/core/Mage/Eav/Model/Entity/Attribute/Abstract.php(387): Mage::exception('Mage_Eav', 'Source model ""...')
When I tried to replace firstname with gender, it works properly (give female/male).
$collection = Mage::getModel('customer/customer')->getCollection()
->addAttributeToSelect('firstname')
->addAttributeToSelect('lastname')
->addAttributeToSelect('email');
If you don't need firstname, lastname or email, you can skip this lines.
Related
Hello I have tried every forum and resource i have and can still not find the answer to my question.
I am making a booking management system. One of the features is the admin can search someones email and get their details from the database. So i put a line edit so i can get the QString from the email and then i tried to parse it into a SQL query. Thought this would be easy but QT said no. so i am at a complete loss.
Any help will be much appreciated.
The code:
QString email = ui->lineEdit_custsearch->text();
QSqlQuery qry;
QString dets = "SELECT firstname FROM customer WHERE email=="+email+"";
if (qry.exec(dets))
{
for (int i = 0;qry.next();i++)
{
ui->lineEdit_first->setText(qry.value(0).toString());
}
}
In SQL you only need to use a single '=', sign, might be worth giving that a try?
SELECT firstname FROM customer WHERE email="+email+"
Just a suggestion, to make it more readable, it might be worth using string interpolation too so something like the below:
string email = '';
QString dets = $"SELECT firstname FROM customer WHERE email='{email}'";
I have a scenario where i need to pass the body values to an environment variable and use those in another API. In Postman
Below is the body,
{
"firstName" : "Firstname",
"lastName" : "lastname",
"email" : "{{timestamp}}#test.com",
"password" : "{{timestamp}}",
"country" : 8l16
}
Below is the Pre-req script,
postman.setEnvironmentVariable("timestamp", (new
Date).getTime());
// I have copied the Bodyand paste it in a variable called Obj in
Pre-req
// Then i used the below script to get the body
pm.environment.set("rawBody", JSON.stringify(obj));
But the environmental values of timestamp , email and password is coming as below. The timestamp value is correct and other two are wrong.
timestamp = 1566076106769
email = {{timestamp}}#test.com
password = {{timestamp}}
The timestamp value is not getting substituted in email and password,i want the environmental variable value to set as,
Expected values,
email = 1566076106769#test.com
password = 1566076106769
So how can i assign the body element value to an environment/global variable to use in another API call?
Easy. You have set the environmental variable but never got it.
"{ }" doesn't work in code of Tests and Pre-request Script.
Make it like this:
const timestamp = pm.environment.get('timestamp');
email = `${timestamp} #test.com`;
password = timestamp;
I have a set of basic unit tests in grails and I am getting some strange, inconsistent behaviour. So basically the unit tests are for a Service for interacting with my User Domain.
The issue is at a high level - If I run the full Spec of tests - 4 tests fail each time. If I run them individually - they pass. The obvious thing here is that there is state being held between tests - but given this is a unit test - there shouldn't be (and I have verified that with logging).
The components in play here are:
UserService
User Domain
Address Domain
UserCommand (Verifiable)
So looking at the Spec I have the following in setup:
User user
def setup() {
println "================ Setting Up User (${User.count()}) ================"
// Set the roles
new Role(authority: "ROLE_ADMIN").save()
new Role(authority: "ROLE_OPERATOR").save()
def role = new Role(authority: "ROLE_USER").save()
def userAddress = new Address()
userAddress.with {
name = "Name"
address1 = "Address 1"
address2 = "Address 2"
townCity = "Town"
postcode = "BT19"
county = "Down"
}
// Create an admin user
user = new User()
user.with {
christianName = "Phil"
surname = "Preston"
email = "p#p.com"
username = "admin"
password = "password123"
phone = ""
skype = ""
address = userAddress
}
println(user.properties)
// Save the test user
if (user.validate()) {
println "Saving"
user.save(flush: true, failOnErrors: true)
UserRole.create(user, role)
}
else {
user.errors.allErrors.eachWithIndex { i, x ->
println "${i} - ${x}"
}
}
assert user
}
And the two simple tests are as follows:
void "Test updateUser - changing a user password"() {
given: "An update to the user"
UserCommand cmd = new UserCommand()
cmd.with {
id = user.id
christianName = user.christianName
surname = user.surname
username = user.username
email = user.email
skype = user.skype
phone = user.phone
password = "newPassword"
passwordCheck = "newPassword"
isAdmin = user.isAdmin()
isOperator = user.isOperator()
}
when: "attempt to update"
User updated = service.updateUser(cmd)
then: "the password should be update - but nothing else"
updated.password == cmd.password
}
void "Test updateUser - changing a user detail"() {
given: "An update to the user"
UserCommand cmd = new UserCommand()
cmd.with {
id = user.id
christianName = user.christianName
surname = user.surname
username = user.username
email = "update#update.com"
skype = user.skype
phone = user.phone
password = user.password
isAdmin = user.isAdmin()
isOperator = user.isOperator()
}
when: "attempt to update"
User updated = service.updateUser(cmd)
then: "the email should be update - but nothing else"
updated.email == cmd.email
}
(There are others - but this is all to demonstrate the problem)
So the strangeness is as follows:
The first test passes, the second one fails.
If I swap the order - the first one still passes, second fails
If I run both individually - they both will pass
The code in setup() prints the number of User objects (0) each time
It verifies the object is created each time (assert and logging)
The unit test fails because I throw an exception when validation fails forthe User domain object I am udating. So the following:
def updateUser(UserCommand userCommand) {
assert userCommand
// Get the current
User foundUser = User.findById(userCommand.id)
def wasAdmin = foundUser.admin
def wasOperator = foundUser.operator
// Bind Data
bindData(foundUser, userCommand, ['class', 'operator', 'admin', 'address'])
foundUser?.address?.with {
name = userCommand.name
address1 = userCommand.address1
address2 = userCommand.address2
townCity = userCommand.townCity
county = userCommand.county
postcode = userCommand.postcode
}
// THIS VALIDATION FAILS ON SECOND TEST
if (foundUser.validate()) {
foundUser.save()
// ... removed
return foundUser.refresh()
}
else {
Helper.copyErrorToCmd(foundUser, userCommand)
log.error("Errors: ${foundUser.errors.allErrors}")
throw new UserServiceException(cmd: userCommand, message: "There were errors updating user")
}
The errors on the User domain object are basically (shortened):
'skype': rejected value [null]
'phone': rejected value [null]
So you can see that I have empty strings for these fields - and with conversion to null (as Grails will do), this is the reason. However the issue with that is:
It should fail for both, and certainly fail when run individually
Both fields are marked as nullable: true in the constraints
In UserService I have used the debugger to check the objects that are being saved when running both tests - the phone and skype are null for both tests, yet one fails and one doesn't
So the constraints in the User domain object are as follows:
static constraints = {
christianName blank: false
surname blank: false
username blank: false, unique: true, size: 5..20
password blank: false, password: true, minSize: 8
email email: true, blank: false
phone nullable: true
skype nullable: true
address nullable: true
}
And I am using a Command object which has the following constraints:
static constraints = {
importFrom User
importFrom Address
password blank: false, password: true, minSize: 8
passwordCheck(blank: false, password: true, validator: { pwd, uco -> return pwd == uco.password })
}
Note I have even tried adding the Skype and phone fields in the UserCommand constraints closure as well.
This issue goes away if I add text to the fields in setup, but thats not going to possible in the actual app as these fields can be left blank.
Any help on how this inconsistency happens would be greatly appreciated.
RECREATION
I have added a minimal GitHub project which recreates the issue: Github Project Recreating Issue. To see the problem:
./grailsw test-app
Will run the two test, first passes second fails. To run the failed test individually run:
./gradlew test --tests "org.arkdev.bwmc.accountmission.UserServiceSpec.*Test updateUser - changing a user detail"
And you can see the test pass.
The issue seems to be that the skype and phone fields are nullable:true for the first test, and nullable:false on the second test (I step into user.validate(), and step into the GrailsDomainClassValidator.java, in the validate(Object,Errors,boolean) call I can see the constrainedProperties Map (which is basically field -> constraints). This shows that skype is NullableConstraint.nullable == true, on the first call of setup, but is showing that NullableConstraint.nullable == false on the setup call for the second test.). This makes no sense.
After the first call
bindData(foundUser, userCommand, ['class', 'operator', 'admin', 'address'])
in UserService.updateUser(UserCommand) (called by feature method Test updateUser - changing a user password) the static member User.constraints becomes null. Go figure. I have no idea whatsoever how Grails works, so maybe someone else can make sense of it. But to me it seems that this should not happen. Maybe you are somehow making a mistake in that call.
You shouldn't have to test the constraints in the framework technically but I've had similar issues before so I can see why you would want to.
Is it possible to post your full test? Are you using #TestFor/#Mock at all? Just as a check, but I assume you must have #Mock otherwise you would get a different error creating the domain classes? #Mock is required for the constraints to be used (or #GrailsUnitTestMixin afaik).
You say in your comment "The values in your app can be blank"; it should be noted that this is not the same as nullable as well. If it really can be blank you should change/add it and then "" will work
You also are not using 'failOnError: true' as you have typoed it.
Sorry I don't have enough rep to write as a comment.
I am using using Effort (for EF4) to do some unit tests.
var ctx= Effort.ObjectContextFactory.CreateTransient<TheContext>(Shared.Connection);
ctx.companies.AddObject(new company() { ID = 100, name = "Agent", is_agent = true });
ctx.SaveChanges(System.Data.Objects.SaveOptions.DetectChangesBeforeSave);
The ID column in the company is an identity field. After executing the above query, it turns out the ID value is 1 instead of 100. Is there any way to control Identity_insert while using Effort
This is just to add the solution on this thread. #MrBlueSky add the archieved links of the solution on the comments above. But, DbConfiguration which is used on the link, does not exists anymore on the latest Effort. The solution still exists on Effort.EF6 [version="1.3.0"]. And you can use the method SetIdentityFields on EffortConnection.DbManager to turn on or off the identity fields
if (Effort.DbConnectionFactory.CreateTransient() is EffortConnection connection)
{
connection.Open();
connection.DbManager.SetIdentityFields(false);
connection.DbManager.ClearMigrationHistory();
connection.Close();
}
Turning on
// Add data with explicitly set id
Person initPerson = new Person { Id = 5, FirstName = "John", LastName = "Doe" };
dataInitContext.People.Add(initPerson);
dataInitContext.SaveChanges();
Assert.AreEqual(5, initPerson.Id);
// Enable identity field
connection.Open();
connection.DbManager.SetIdentityFields(true);
connection.Close();
I upgraded a project from MVC3 to MVC4 and noticed that one of my validators wasn't triggering anymore. I chased it down to a custom DataType in the Shared/EditorTemplates folder that is used for capturing Social Security numbers in various forms across the site. (We only show the last 4 digits when the page is loaded after a save, to explain the regex.)
SSN.cshtml
#{
var ssn = (string)ViewData.TemplateInfo.FormattedModelValue;
if (!String.IsNullOrWhiteSpace(ssn)){
ssn = "###-##-" + Model.Substring(Model.Length - 4, 4);
}
}
#Html.TextBox("", ssn, new { #class = "text-box single-line ssn", pattern = #"^(\d{3}|###)-(\d{2}|##)-\d{4}$", placeholder = "###-##-####", title = "Expected pattern is ###-##-####" })
It seems like in MVC4 the unobtrusive validation wants to look for data-val-regex-pattern as an attribute of the rendered text box, not just pattern. Has anyone ran into this before?
Note: I'd like to keep the validation on the custom data type so I don't have to always remember to add it to each model.
Thanks!
You can have your own custom validator and put it in the model property. here is an example
public class SocialSecurityAttribute : RegularExpressionAttribute
{
public SocialSecurityAttribute () : base(#"^(\d{3}|###)-(\d{2}|##)-\d{4}$") { }
}
Then register it in the global asax.cs Application start as follows
DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(SocialSecurityAttribute), typeof(RegularExpressionAttributeAdapter));
When you use it , it will be like any other built in attributes
[SocialSecurity(ErrorMessage ...)]
public string SocialSecurityNumber{get;set;}
I like implementing like this as the code can be reused . Otherwise you can just use RegularExpressionAttribute passsing the regex
I found out that in order to get MVC4 to render the correct data attributes to the input field, I'd need to replace the hyphens with underscores in the anonymous object passed to the TextBox helper. Here's the code that I ended up with:SSN.cshtml
#{
var ssn = (string)ViewData.TemplateInfo.FormattedModelValue;
if (!String.IsNullOrWhiteSpace(ssn) && ssn.Length == 11)
{
ssn = "###-##-" + Model.Substring(Model.Length - 4, 4);
}
else {
ssn = "";
}
}
#Html.TextBox("", ssn,
new
{
#class = "text-box single-line ssn",
data_val = "true",
data_val_regex_pattern = #"^(\d{3}|###)-(\d{2}|##)-\d{4}$",
data_val_regex = "Expected pattern is ###-##-####",
placeholder = "###-##-####"
}
)