CakePHP view variable as datetime instead of string - string

In my AppController beforeFilter i am saving user data to variables for use in my view. I need to grab the last_login field that is a datetime and then use the dateformat function to display the date i want but cakephp is outputting this variable as a string, is there a way to putput as the format of the table? (datetime).
// Set user variables for each page load
$id = $this->Auth->user('id');
// Set $id
$user_data = $this->User->findById($id);
// Set User Last Login
$user_lastlogin = $user_data['User']['last_login'];
$this->set('lastLogin', $user_lastlogin);
View
<?php echo date_format($lastLogin, 'F jS \at h:i:s A'); ?>
Error
Warning (2): date_format() expects parameter 1 to be DateTime, string given

Firstly your code is messy. Try this:
$this->User->id = $this->Auth->user('id');
$this->set('lastLogin', $this->User->field('last_login'));
Cake has a class for doing dates and times.
echo CakeTime::niceShort($lastLogin);
Generally you should do the data to string in the view, making it part of the controller or model will have a negative impact on your application if you need to do other things with the data.

Related

Android Studio Room query to get a random row of db and saving the rows 2nd column in variable

like the title mentions I want a Query that gets a random row of the existing database. After that I want to save the data which is in a specific column of that row in a variable for further purposes.
The query I have at the moment is as follows:
#Query("SELECT * FROM data_table ORDER BY RANDOM() LIMIT 1")
fun getRandomRow()
For now I am not sure if this query even works, but how would I go about writing my function to pass a specific column of that randomly selected row to a variable?
Ty for your advice, tips and/or solutions!
Your query is almost correct; however, you should specify a return type in the function signature. For example, if the records in the data_table table are mapped using a data class called DataEntry, then the query could read as shown below (note I've also added the suspend modifier so the query must be run using a coroutine):
#Query("SELECT * FROM data_table ORDER BY RANDOM() LIMIT 1")
suspend fun getRandomRow(): DataEntry?
If your application interacts with the database via a repository and view model (as described here: https://developer.android.com/topic/libraries/architecture/livedata) then the relevant methods would be along the lines of:
DataRepository
suspend fun findRandomEntry(): DataEntry? = dataEntryDao.getRandomRow()
DataViewModel
fun getRandomRecord() = viewModelScope.launch(Dispatchers.IO) {
val entry: DataEntry? = dataRepository.findRandomEntry()
entry?.let {
// You could assign a field of the DataEntry record to a variable here
// e.g. val name = entry.name
}
}
The above code uses the view model's coroutine scope to query the database via the repository and retrieve a random DataEntry record. Providing the returning DataEntry record is not null (i.e. your database contains data) then you could assign the fields of the DataEntry object to variables in the let block of the getRandomRecord() method.
As a final point, if it's only one field that you need, you could specify this in the database query. For example, imagine the DataEntry data class has a String field called name. You could retrieve this bit of information only and ignore the other fields by restructuring your query as follows:
#Query("SELECT name FROM data_table ORDER BY RANDOM() LIMIT 1")
suspend fun getRandomRow(): String?
If you go for the above option, remember to refactor your repository and view model to expect a String instead of a DataEntry object.

Exporting Laravel Model to Excel but with modification of created_at column to only date not datetime

i tried to modify a collection before returning it to be exported with maatwebsite Excel. The column i tried to modify is the created_date column (the default created_date of laravel) so that when exported to excel, i only get the date not datetime.
i tried:
namespace App\Exports;
use App\Invoice;
use Maatwebsite\Excel\Concerns\FromCollection;
class InvoicesExport implements FromCollection
{
public function collection()
{
$temp = Invoice::all();
$len = count($temp);
for($i=0;$i<$len;$i+=1){
$temp[$i]->created_at = $temp[$i]->created_at->format('m/d/Y')
}
return $temp;
}
}
in the controller:
public function export()
{
return Excel::download(new InvoicesExport, 'invoices.xlsx');
}
but, when exported, the result in the excel file is, for example: '07/26/2016T00:00:00.000000Z'
i noticed that the time become zero, and when i tried:
$temp[$i]->created_at = "some random string"
the laravel in webpage return error said that "some random string" cannot be parsed to datetime by Carbon Class constructor.
how can i make the exporting does not construct datetime with the string i give in the 'created_at' column, but just return the plain string instead? if let's say, i can't modify the database so i can't create extra column and extra column for this simple thing is too much, i think.
If you are using Maatwebsite\Excel 2.1 try column formatting by the setColumnFormat($array) method.
If Maatwebsite\Excel 3.1, try with the WithMapping interface.
created_at is marked as 'datetime' in the $cast property of your model by default so when you set it it's automatically cast as date (with Carbon::parse('the value you gave'))
If you want to export your collection with some values formatted you should not mutate the objects of the original objects but create new dedicated objects/arrays that will not interfere with model behavior nor corrupt your existing objects.

Impex Export: Colon in multivalue attribute is escaped by double backslash - How to remove this behavior?

Hybris: 6.3.0.0-SNAPSHOT (the behavior is the same with 6.3.0.21)
When exporting impex, we noticed a difference when exporting a non-multivalue Type attribute versus exporting a multivalue Type attribute.
When exporting String attribute data without colon, a non-multivalue attribute can be exported as Experts, while a multivalue attribute can be exported as Experts|Hybris.
When exporting Type with String attribute data with colons (e.g. URL), the colon is escaped with a double backslash (for multivalue only). A non-multivalue attribute can be exported as https://experts.hybris.com, while a multivale attribute can be exported as https\://experts.hybris.com if there is only 1 value or as https\://experts.hybris.com|https\://help.hybris.com if there are 2 values.
How can I stop the export from escaping the colon? Is there a method I can override to change this behavior? I would like to change the result to https://experts.hybris.com|https://help.hybris.com or to "https://experts.hybris.com"|"https://help.hybris.com".
Business Case: We want to copy the URL from the exported impex, but the URL contains double backslashes. The exported impex is not meant to be reimported.
Notes #`: The URLs are stored in a collection (e.g. Product.newAttribute, where newAttribute is a collection of custom types which has a String). So, the Impex header looks something like "INSERT_UPDATE Product;newAttribute(data)"
Notes #2: (UPDATE: Didn't work) Currently, I'm checking if it's possible with a CSVCellDecorator; this is for import only.
Notes #3: Currently, I'm checking if it's possible with AbstractSpecialValueTranslator.
For this specific case, I created a new translator, extending AbstractValueTranslator. Then, I implemented the exportValue method, joining the string data (which are URLs), without escaping them.
public String exportValue(final Object value) throws JaloInvalidParameterException
{
String joinedString = "";
if (value instanceof Collection)
{
final Collection valueCollection = (Collection) value;
if (!valueCollection.isEmpty())
{
final ArrayList<CustomType> list = (ArrayList<CustomType>) valueCollection;
final StringJoiner joiner = new StringJoiner("|");
for (final CustomType customType : list)
{
// data is a URL
joiner.add(customType.getData());
}
// value would be something like "https://experts.hybris.com|https://help.hybris.com"
joinedString = joiner.toString();
}
}
return joinedString;
}
Reference:
Customization: https://help.hybris.com/1808/hcd/ef51040168d743879c015b7de232ce40.html
I think that might not be possible, since the colon is used to separate keys for referenced types. As in
...;catalogVersion(catalog(id),version);...
...;myCatalog:Staged;...
Why not run search/replace on the result?

getting a list of forms that contain a specified field, is there a better method

The following code is a script object on an XPage in it I loop through an array of all the forms in a database, looking for all the forms that contain the field "ACIncludeForm". My method works but it takes 2 - 3 seconds to compute which really slows the load of the XPage. My question is - is there a better method to accomplish this. I added code to check to see if the sessionScope variable is null and only execute if needed and the second time the page loads it does so in under a second. So my method really consumes a lot of processor time.
var forms:Array = database.getForms();
var rtn = new Array;
for (i=0 ; i<forms.length; ++i){
var thisForm:NotesForm = forms[i];
var a = thisForm.getFields().indexOf("ACIncludeForm");
if (a >= 0){
if (!thisForm.isSubForm()) {
if (thisForm.getAliases()[0] == ""){
rtn.push(thisForm.getName() + "|" + thisForm.getName() );
}else{
rtn.push(thisForm.getName() + "|" + thisForm.getAliases()[0] );
}
}
}
thisForm.recycle()
}
sessionScope.put("ssAllFormNames",rtn)
One approach would be to build an index of forms by yourself. For example, create an agent (LotusScript or Java) that gets all forms and for each form, create a document with for example a field "form" containing the form name and and a field "fields" containing all field names (beware of 32K limit).
Then create a view that displays all these documents and contains the value of the "fields" field in the first column so that each value of this field creates one line in this view.
Having such a view, you can simply make a #DbLookup from your XPage.
If your forms are changed, you only need to re-run the agent to re-build your index. The #DbLookup should be pretty fast.
Place the form list in a static field of a Java class. It will stay there for a long time (maybe until http boot). In my experience applicationScope values dissappear in 15 minutes.

How to convert DateTime value into Filename in J2ME

I am doing a Java mobile program using J2ME.
I want to save date time field value into a Mysql, I am trying to convert the datetime field into a long and saving it in Mysql if its possible.
In c# ToFileTime() method which does it, is there anything like that in J2ME??
public DateField getDateField() {
if (dateField == null) {
// write pre-init user code here
dateField = new DateField("dateField", DateField.DATE_TIME);
dateField.setDate(new java.util.Date(System.currentTimeMillis()));
// write post-init user code here
long myFileTime = dateField.
}
return dateField;
}
you need to correct 2 lines
//no need to pass system current time. new Date() creates current time date
dateField.setDate(new java.util.Date());
// gettime returns time in millis
long myFileTime = dateField.getDate().getTime();

Resources