Comparing DateTime object in symfony (with propel) - datetime

I want to compare two DateTime objects in php code. I'm using Symfony 1.4 with Propel.
$article = $obj->getArticle();
if($article->getVisibleFrom() <= new DateTime()) {
DO_SOMETHING();
}
The problem is that I'm getting string from getVisibleFrom() getter (instead of DateTime object).
In database visible_from field is type of DATETIME.
I read that with Doctrine I could use function getDateTimeObject('visible_from').

You can change the default behavior at build time by changing build properties: http://www.propelorm.org/reference/buildtime-configuration.html#datetime_settings
And here is the doc for the temporal getters: http://www.propelorm.org/reference/active-record.html#temporal_columns
William

Related

Linq to entity enum not comparing

Here is my Enum:
public enum AdvertStatus
{
Active,
Archived
}
And my entity type:
public record Advertisement
{
...
public AdvertStatus Status { get; set; }
...
}
In database it's stored as int, Database is Postgree
When I try to compare it like so:
data = data.Where(x => x.Status == searchValues.Status);
Entity Framework throws an exception sayng:
.Status == (int)__searchValues_Status_3)' could not be translated. Either rewrite the query in a form that can be translated, or switch to client evaluation explicitly by inserting a call to 'AsEnumerable', 'AsAsyncEnumerable', 'ToList', or 'ToListAsync'.
I tried solutions from this question: LINQ TO ENTITY cannot compare to enumeration types but it did't work.
EDIT 1:
data is database table context IQueryable<AdvertisementDTO>
searchValues.Status is type of AdvertStatus from search filter
The issue may be higher up in your Linq query, such as you are attempting to project with a Select or ProjectTo before filtering. For simple types like int/string this should work, but depending on how your DTO is declared you might be introducing problems for mpgsql.
For instance if your query is something like:
var query = _context.Advertisements
.Select(x => new AdvertisementDTO
{
// populate DTO
}).Where(x => x.Status == searchValues.Status)
// ....
then npgsql may be having issues attempting to resolve the types between what is in the DTO and the enumeration in your searchValues. From what the exception detail looks like, npgsql is trying to be "safe" with the enum and casting to intbut feeding that to PostgreSQL that results in invalid SQL. I did some quick checks and the DTO would need to be using the same Enum type (C# complains if the DTO cast the value to int, cannot use == between AdvertStatus and int fortunately) The project may have something like a value converter or other hook trying to translate enumerations which is getting brought into the mix and gunking up the works.
Try performing the Where conditions prior to projection:
var query = _context.Advertisements
.Where(x => x.Status == searchValues.Status)
.Select(x => new AdvertisementDTO
{
// populate DTO
})
// ....
If the data value is stored as an Int then this should work out of the box. npgsql does support mapping to string (which would require a ValueConverter) as well as database declared enumerations. (https://www.postgresql.org/docs/current/datatype-enum.html) However, Int columns should work fine /w enums.
If that doesn't work, I'd try with a new DbContext instance pointed at the DB and a simple entity with that Enum to load a row from that table to eliminate whether npgsql is translating the enum correctly, just to eliminate any possible converters or other code that the main DbContext/models/DTOs may be contributing.
It was all my mistake in higher repo Select projection.
Thanks you all for help. Cheers.

Spring Data JPA not parsing response as proper JSON string

We are using Spring MVC 4.1.2 and Spring Data JPA 1.9.0. Everything works fine but when we have custom query with only selected field for a given entity then our json response does not include property name in the response, instead it just included property value.
If I correctly guess, your custom query looks like:
SELECT e.myProperty FROM Entity e [WHERE ...]
The effect of this is that you get a List<Object[]> containing only the array of property values instead of an object that has a field with the name myProperty and its value is the value in the database.
The solution is to create a custom data-transfer object, which has this one field and assign the value in the constructor
public class MyPropertyDTO { // find a better name, though :)
private int myProperty;
public MyPropertyDTO(int myProperty) {
this.myProperty = myProperty;
}
public int getMyProperty() {
return myProperty;
}
}
Then rewrite your query as:
SELECT NEW com.mycompany.MyPropertyDTO(e.myProperty) FROM Entity e [WHERE ...]
In theory you could even use your original Entity class, add a json view on myProperty and create the matching constructor instead of creating a brand new class.

Symfony2, Doctrine, How set datetime to Entity

i can not understand how can i persist datetime to database. I have string
(string) $oXml->currentTime
actually it's not a string but we convert it, so how can i add it to entity without error
Fatal error: Call to a member function format() on a non-object in...
current code
$currentTime = \DateTime::createFromFormat('Y-m-d H:m:s', (string) $oXml->currentTime);
$cachedUntil = \DateTime::createFromFormat('Y-m-d H:m:s', (string) $oXml->cachedUntil);
$oApiKeyInfo
->setCurrentTime($currentTime)
->setCachedUntil($cachedUntil)
not working :(
You need to pass the a DateTime object. Create it with a new statement, you can specify the time to use with the first constructor parameter.
$currentTime = new \DateTime((string) $oXml->currentTime);
$cachedUntil = new \DateTime((string) $oXml->cachedUntil);
$oApiKeyInfo->setCurrentTime($currentTime)
->setCachedUntil($cachedUntil);
If you need to specify a Timezone you can use the DateTimeZone class and pass it as the second parameter to the DateTime constructor.

Breeze: How can I create a GUID key for new entities on the client?

Using Breeze, what is the simplest way to populate a GUID key when an entity is created?
I'll assume that your entity is configured such that the client is responsible for setting the Guid key for new entities. That's the default for the Guid key of an Entity Framework Code First entity; it is as if the key property were adorned with [DatabaseGenerated(DatabaseGeneratedOption.None)]
The obvious approach is to set the key after creating the entity and before adding it to the manager, e.g.:
function createFoo() {
var foo = fooType.createEntity();
foo.id(breeze.core.getUuid()); // Knockout implementation
manager.addEntity(foo);
}
This may be all you ever need.
On the other hand, you may find that you're creating new Foos in many places and for some strange reason you can't use the createFoo function. You certainly don't want to repeat that code.
You can extend the Foo entity type with id-setting behavior after which you'd be able to write:
function createFoo() {
var foo = fooType.createEntity(); // foo.id is set for you
manager.addEntity(foo);
}
There are two approaches to consider - custom constructor and type initializer; both are described in "Extending Entities"
Constructor
You can initialize the key inside a custom constructor. Breeze calls the constructor both when you create the entity and when it materializes a queried entity. Breeze will replace the initial key value when materializing.
Here's an example that assumes the Knockout model library.
function Foo() {
foo.id(breeze.core.getUuid()); // using KO
}
// one way to get the MetadataStore
var store = manager.metadataStore;
// register the ctor with the Foo type
store.registerEntityTypeCtor("Foo", Foo);
Pretty simple. The only downside is that Breeze will generate a Guid every time it makes an entity, whether creating a new one or materializing one from a query. It's wasted effort during materialization but so what? Well, I suppose that might become a performance issue although I wouldn't assume so until I had measured it.
Initializer
Suppose you measured and the repeated Guid generation is a serious problem (really?). You could set the key in a type initializer instead and only call the Guid generator when creating a new entity.
Breeze calls a type initializer after the entity has been created or materialized from query just before returning that entity to the application. Clearly you don't want to overwrite a materialized key from the database so you'll test the key value to make sure it's not real (i.e. to make sure you're fixing a created entity) before assigning it. Here's an example.
function fooInitializer(foo) {
var emptyGuid = "00000000-0000-0000-0000-000000000000";
if (foo.id() !=== emptyGuid) {
foo.id(breeze.core.getUuid());
}
}
var store = manager.metadataStore;
// register the initializer; no ctor in this example
store.registerEntityTypeCtor("Foo", function(){}, fooInitializer);
Assuming you have a Guid surrogate Key on all your entities like we have in our case, you could code a createInstance factory that does the following in a very generic approach:
function createInstance(breezeEntityManager, typeName) {
var keyProperty = breezeEntityManager.metadataStore.getEntityType(typeName, false).dataProperties.filter(function (p) {
return p.isPartOfKey;
})[0];
var config = {};
config[keyProperty.name] = breeze.core.getUuid();
return breezeEntityManager.createEntity(typeName, config);
}
This way, you won't have to create an initializer for all your entities.

Grails data binding

A Grails controller received is called with the following request parameters:
defaultPrice[0].amount 22
defaultPrice[0].currency 1
defaultPrice[0].id
defaultPrice[1].amount 33
defaultPrice[1].currency 3
defaultPrice[1].id
I've defined the following command class:
class PriceCommand {
BigDecimal amount
Integer currency
Integer id
}
I attempt to bind the request parameters to a `List' in the action
def save = {List<PriceCommand> defaultPrice ->
}
But within the action, defaultPrice is null.
It requires an command with existing list of data, with specified name, that will be filled with data from request.
Try
import org.apache.commons.collections.ListUtils
import org.apache.commons.collections.Factory
class PriceListCommand {
List<PriceCommand> defaultPrice = ListUtils.lazyList([], {new PriceCommand()} as Factory)
}
and use this command inside controller. It should works
I'm not sure if this is what your looking but it may help...
1.) I think indexed params only work if you have a parent-child or one-to-many relationship. For example you might need to introduce a PriceCommandParent which contains a list of PriceCommand. I may be wrong on this and I welcome any corrections.
2.) I've found that indexed params aren't as magically as some of the other areas of Grails/Groovy so sometimes i'd rather deal with the mapping myself. Below is how i've handled it in the past....
def things = []
params.each{name, value->
if (name.matches('^(thing\\[\\d+\\])$')){ //<-- look for 'thing[x]'
things.add(new Thing(params[name]);
}
}
Let me know if any of this is of help

Resources