The problem is explained short with the following code. $category->update() results with true (or $category->save()) but really nothing happens.
$category = Category::findFirst('id=' . (int)$id);
if ($this->request->isPost()) {
$category->setCategoryId($this->request->getPost('category_id', 'int'));
$category->setLanguageId($this->request->getPost('language_id', 'int'));
$category->setName($this->request->getPost('name', 'striptags'));
$category->setDescription($this->request->getPost('description', 'striptags'));
$category->setSort($this->request->getPost('sort'));
$category->setValid($this->request->getPost('valid'));
if (!$category->update()) {
$this->flash->error($category->getMessages());
} else {
$this->flash->success(
$this->translator->_('Category was updated successfully')
);
}
}
The model-classes are generated with getter- and setter-methods and protected member-variables with the phalcon-devtools.
What am I doing wrong?
I know this problem was also discussed here but i unfortunately have not enough points to write a comment :)
Phalcon Version 1.2.3, MySQL 5.5 + Apache on Debian with PHP5.4.4
It might be something as simple as a column that doesn't accept nulls and a null is being slipped in. If you don't explicitly tell Phalcon not to do so, even if you don't have any validation, Phalcon will enforce the not null constraint on the field implicitly.
Disable not null validations by adding this to the top of your bootstrap file and try again:
\Phalcon\Mvc\Model::setup([
'notNullValidations' => false
]);
Validation may be to blame? Check validators
Have you checked the php error log? I found that Phalcon is sometimes not as verbose as I would have liked it to be...
Related
So there is a form, and non-required fields, like say "first_name". When I leave this field empty, I got an error that "Column 'first_name' cannot be null", because indeed it can't. But why does Doctrine converts empty string to NULL?
But I have to questions regarding this:
Is this possible to disable it?
What's your opinion about it? Until now I was used to the fact that when a form field was empty, I simply inserted an empty string. Not NULL o_O But... somebody told me this is a principle we should follow. For me however, NULL means "there is no value", and '' (empty string) means something different - "there IS a value, but it's empty". What do you think?
p.s. I use MySql if it matters.
edit:
there is a similar question:
Symfony2 forms interpret blank strings as nulls but maybe there is a new solution as of 2016?
The only solution which work is the one from the accepted answer:
Or otherway when you have the function setRecap you can check if empty
or not set and set the value you expect.
public function setRecap($recap) {
if(!isset($recap)) {
$this->recap = ''
} else {
$this->recap = $recap;
}
}
But I have a lot of such fields, and this seems overkill to me, there must a simpler solution.
p.s. I did not try Thomas Decaux' answer below the accepted answer, because it seems hacky to me.
Well, as somebody suggested me, it's as simple as:
public function setUserName($userName) {
$this->userName = (string)$userName;
return $this;
}
In an entity.
Edit: plus, we need to give a default value for the variable, like:
$userName = '';
Frankly it would be best to allow NULL values for your first names in your DB. Doing what you did just make things more complicated.
Symfony is developped by professionals and to me that conversion seems reasonable, because an empty string isn't more interesting than NULL.
What you said above, that NULL and an empty strings are two different things, is true in a sense, but what does that mean to have an empty name (i.e. empty string)? Isn't it better to say that this guy has no known first name (i.e. NULL)?
EDIT:
In response to your first comment:
Well in that case, typecasting to string is the right approach.
Using CI for the first time and i'm smashing my head with this seemingly simple issue. My query wont insert the record.
In an attempt to debug a possible problem, the insert code has been simplified but i'm still getting no joy.
Essentially, i'm using;
$data = array('post_post' => $this->input->post('ask_question'));
$this->db->insert('posts', $data);
I'm getting no errors (although that possibly due to disabling them in config/database.php due to another CI related trauma :-$ )
Ive used
echo print $this->db->last_query();
to get the generated query, shown as below:
INSERT INTO `posts` (`post_post`) VALUES ('some text')
I have pasted this query into phpMyAdmin, it inserts no problem. Ive even tried using $this->db->query() to run the outputted query above 'manually' but again, the record will not insert.
The scheme of the DB table 'posts' is simply two columns, post_id & post_post.
Please, any pointers on whats going on here would be greatly appreciated...thanks
OK..Solved, after much a messing with CI.
Got it to work by setting persistant connection to false.
$db['default']['pconnect'] = FALSE;
sigh
Things generally look ok, everything you have said suggests that it should work. My first instinct would be to check that what you're inserting is compatible with your SQL field.
Just a cool CI feature; I'd suggest you take a look at the CI Database Transaction class. Transactions allow you to wrap your query/queries inside a transaction, which can be rolled back on failure, and can also make error handling easier:
$this->db->trans_start();
$this->db->query('INSERT INTO posts ...etc ');
$this->db->trans_complete();
if ($this->db->trans_status() === FALSE)
{
// generate an error... or use the log_message() function to log your error
}
Alternatively, one thing you can do is put your Insert SQL statement into $this->db->query(your_query_here), instead of calling insert. There is a CI Query feature called Query Binding which will also auto-escape your passed data array.
Let me know how it goes, and hope this helps!
I am having trouble sending a SQL statement through a DbContext using context.Database.ExecuteSqlCommand().
I am trying to execute
CREATE TABLE Phones([Id] [uniqueidentifier] NOT NULL PRIMARY KEY,
[Number] [int],[PhoneTypeId] [int])
GO
ALTER TABLE [dbo].[Phones] ADD CONSTRAINT [DF_Phones_Id]
DEFAULT (newid()) FOR [Id]
GO
This fails with the error string
Incorrect syntax near the keyword 'ALTER'.
Incorrect syntax near 'GO'.
However running that exact statement in SSMS runs without errors? Any issues I need to resolve regarding the default constraint throught the DbContext. I have see problems with people using constraints and not having IsDbGenerated set to true. I am not sure how that would apply here though.
GO is not a part of SQL, so it can't be executed with ExecuteSqlCommand(). Think of GO as a way to separate batches when using Management Studio or the command-line tools. Instead, just remove the GO statements and you should be fine. If you run into errors because you need to run your commands in separate batches, just call ExecuteSqlCommand() once for each batch you want to run.
I know, necroposting is bad maner, but may be this post would save someone's time. As it was mentioned in Dave's post, GO is not a part of SQL, so we can create little workaround to make it work
var text = System.IO.File.ReadAllText("initialization.sql");
var parts = text.Split(new string[] { "GO" }, System.StringSplitOptions.None);
foreach (var part in parts) { context.Database.ExecuteSqlCommand(part); }
context.SaveChanges();
In this case your commands would be splitted and executed without problems
Dave Markle beat me to it. In fact, you can change "GO" to any other string to separate batches.
An alternative implementation here is to use SMO instead of the Entity Framework. There is a useful method there called ExecuteNonQuery that I think will make your life a lot simpler. Here is a good implementation example.
I'm trying to create a text file that contains the value of a custom field I added on redmine. I tried to get it from an SQL query in the create method of the project_controller.rb (at line 80 on redmine 1.2.0) as follows :
sql = Mysql.new('localhost','root','pass','bitnami_redmine')
rq = sql.query("SELECT value
FROM custom_values
INNER JOIN projects
ON custom_values.customized_id=projects.id
WHERE custom_values.custom_field_id=7
AND projects.name='#{#project.name}'")
rq.each_hash { |h|
File.open('pleasework.txt', 'w') { |myfile|
myfile.write(h['value'])
}
}
sql.close
This works fine if I test it in a separate file (with an existing project name instead of #project.name) so it may be a syntax issue but I can't find what it is. I'd also be glad to hear any other solution to get that value.
Thanks !
(there's a very similar post here but none of the solutions actually worked)
First, you could use Project.connection.query instead of your own Mysql instance. Second, I would try to log the SQL RAILS_DEFAULT_LOGGER.info "SELECT ..." and check if it's ok... And the third, I would use identifier instead of name.
I ended up simply using params["project"]["custom_field_values"]["x"] where x is the custom field's id. I still don't know why the sql query didn't work but well, this is much simpler and faster.
I have a 'user' table with a field name 'process_salary?' which has a boolean datatype
#user = User.create(params[:user])
if #user.process_salary?
//some code here
else
//some code here
end
When I create a new object of user and check for process_salary it gives me following error
NoMethodError: undefined method `process_salary?' for #<User:0xb6ac2f68>
Why does this error occur? Can I avoid it without changing my column name?
When I check it with the debugger it crashes the first time, but after that it runs properly
The question-mark has a special meaning in ActiveRecord. It can be used to check whether a field is true. You are using it as part of your field name which wasn't such a good idea. You could try if #user.process_salary?? exists but I think ultimately it is easiest to change your database column to be called 'process_salary'.
Side note: The 'rails console' is really helpful for playing around with models.
As cellcortex posted, question marks at the end of column names are tricky in Rails. If you need to have it there for legacy reasons, you might be able access the attribute as follows:
#user['process_salary?']
or the more verbose:
#user.read_attribute['process_salary?']
You can of course test for nil using .nil?.