Symfony 5 Convert string to datetime - symfony

In Symfony 5 I have a form where users enter into text fields and also a date. This is then redirected into a display controller that displays matching rows from the database. The date needed to be converted into a string for the redirect to work.
$firstName = $findPt->getFirstName();
$surname = $findPt->getSurname();
$username = $findPt->getUsername();
$dob = $findPt->getDateOfBirth();
$dobStringValue = $dob->format('Y-m-d');
return $this->redirectToRoute('app_displayClients', ['firstName' => $firstName,
'surname' => $surname,
'username' => $username,
'dob' => $dobStringValue]);
However in the display controller I then need to convert it back into a datetime to use it but that doesn't seem possible. I've tried various options, such as $dobDateTime= new DateTime($dateStr);
Please let me know if this question isn't clear or you need more information.
Many thanks in advance for any help.

You can reconvert it using DateTime::createFromFormat
$dobStringValue = $dob->format('Y-m-d');
$dobReconverted = \DateTime::createFromFormat('Y-m-d', $dobStringValue);

Thanks Agnohendrix, that was helpful. I didn't need to format as it was already a string but used $dobReconverted = \DateTime::createFromFormat('Y-m-d', $dobStringValue);
The \ seemed to have been what made it work, maybe this is something to do with using Symfony.

It works with "\Datetime" and not with "Datetime" because "Datetime" needs to be defined with a "use Datetime" to work; that's why the error "Did you forget a use statement for..." came out.

Related

Retrieve specific record by term

I am trying to get a single record from my database using doctrine. I am unsure how to use the findBy() method.
My current code is below:
$token = $em->getRepository('APIBundle:Token')->findBy();
Any help will be appreciated
You just need to include an array of what you want the findBy() method to use. Please see the below code:
$token = $em->getRepository('APIBundle:Token')->findBy(array('string' => $string));
Just name the 'string' part of the code as whatever field you are searching, and replace the $string with the variable.

Laravel 5.2 PHPunit form submit create new record

I have the following code.
Login user and validation works, returns true.
The problem is seePageIs, it returns an error. But after posting the respons has to go to company lister page. So if i change the ->seePageIs('admin/company') to ->seePageIs('admin/company/create') it works.
What's wrong?
Error:
Failed asserting that two strings are equal.
Expected :'http://localhost/admin/company'
Actual :'http://localhost/admin/company/create'
Test:
public function testExample()
{
$this->be(User::find(4));
$rules = array(
'companyname' => 'required',
'email' => 'required|email',
);
$data = [
'companyname' => 'aa',
'email' => 'aaaa#aa.nl']
;
$v = $this->app['validator']->make( $data, $rules);
$this->visit('admin/company/create')
->press('Create')
->assertTrue($v->passes())
->seePageIs('admin/company');
}
I'm not sure I understand your code very well and your question, but maybe it is this line:
$this->visit('admin/company/create')
->press('Create')
->assertTrue($v->passes())
->seePageIs('admin/company/create');
I just changed the line seePageIs() to add create at the end. Maybe that is the problem?
Try it.
If not, can you show your code for assertEquals(...)... Thanks!
EDIT #2
Hi there Bas; based on your comments and what I think you are trying to do:
If after creating the company, then you want to check it, then you probably need to do this instead:
$this->visit('admin/company')
->seePageIs('admin/company');
Which just goes to the company page an verifies that is the correct page.

Pimcore: Setting DateTime Class Fields on Objects

I'm writing an importer and am getting stuck with actually creating the objects. Specifically, I'm having troubles with DateTime fields. I have a class called blogArticle and I'm using them just as the Pimcore demo data uses them for blog articles.
$newPost = new Object\BlogArticle();
$newPost->setCreationDate( time() );
$newPost->setPublished( true );
$newPost->setText( $text ); // text input field
$newPost->setTitle( $title ); // text input field
$newPost->setDate( $date ); // datetime input field
$newPost->setKey( \Pimcore\File::getValidFilename( $key ) );
$newPost->setParentId( $id );
$newPost->save();
The exact error I am getting is:
Whoops\Exception\ErrorException thrown with message "Call to a member function getTimestamp() on a non-object"
Stacktrace:
#0 Whoops\Exception\ErrorException in /.../pimcore/models/Object/ClassDefinition/Data/Datetime.php:73
I cannot find anything in the documentation apart from how the value is stored in the database for this field type. Literally zero documentation on how to appropriately assign values to class fields per field type.
SOLUTION
Thanks to Igor Benko on solving this one!
$newPost_date = new DateTime( "2016-07-01 12:10:37" );
$newPost->setDate( $newPost_date );
It seems that your system is still set to use the Zend_Date. DateTime is used only if you have a clean install of Pimcore 4, otherwise the compatibility layer is turned on by default after the update. The compatibility layer uses Zend_Date instead.
In your system.php you have to turn the flag useZendDate to false in order to use DateTime class.
You need to pass an instance of DateTime class to the setter. Something like this:
$date=new DateTime("2016-07-01 12:10:37");
$newPost->setDate($date);
See this:
https://www.pimcore.org/wiki/display/PIMCORE4/Update+from+Version+3.x+to+Version+4#UpdatefromVersion3.xtoVersion4-PHP%27sDateTimereplacesZend_Date
EDIT: Updated the answer after #GrafikMatthew updated his question.

Send a message to an updated number in Silverstripe

I have a SendSMS() function in customer.php file, and I am updating the MobileTelephone field in the database. When the mobile number is updated a message should go to the new number. In my case, database updates and message goes to the previous number. I want to make them go to the new number. Any suggestions?
Below is my function:
Below function is in MyAccountPage.php
function changeMyContactDetails($data,$form){
$member = Customer::CurrentUser();
//debug::show($member);
if($member){
if($data['MobileTelephone']!=$member-> MobileTelephone){
//sleep(10);
$verified = array(
'IsMobileVerified' => 'N',
//'MobileVeryDate' => date(MYSQL_DATETIME, strtotime(SS_Datetime::now()))
);
//sleep(10);
$member->update($verified);
$member->write();
//sleep(10);
$member = Customer::CurrentUser();
$member->SendSMS();
}
$form->saveInto($member);
$member->write();
}
return $this->redirectBack();
}
You have not altered member before sending the message.
use Form::saveInto first, not after sending.
This could also be done directly from member, in onAfterWrite(), using $this->isChanged('MobileTelephone').
That way it is centralised so it doesn't matter which form/process updates the number.
It is best to achieve this through an Extension: http://docs.silverstripe.org/en/developer_guides/model/extending_dataobjects/

SonataAdminBundle Exporter issue with many to many

currently I'm using sonata admin bundle to export a "order" data, how can I export the data with manytomany relationship? I saw a post, it helps a bit, but I still not sure how to get the data in many to many relationship.
Here is my code:
public function getExportFields() {
return [
$this->getTranslator()->trans('Order Number') => 'id',
$this->getTranslator()->trans('First Name') => 'customer.First_name',
$this->getTranslator()->trans('Last Name') => 'customer.Last_name',
...]
Here is fine, but when I try to get 'OrderToProduct' or 'product.name' it failed or only output empty string. I spent to much time on this already, hope someone can give a clue. Thank you.
Well, you can't use product.name, because product is a collection.
Export action iterates through objects and get properties with path defined and tries to stringify them.
What you need to do is a workaround - define some method in Order class - i.e. getProductsAsString(), make it return string you need, and then add
$this->getTranslator()->trans('Products') => 'productsAsString'
But still - it will put whole string in single cell of xls, csv, xml you are trying to export.

Resources