how to display mongodb date in symfony2 twig template? - mongodb

I have a website listing products using symfony2 and mongodb
I added the items into mongodb with create date and need to display all items in my twig template.
For this
In my controller I passed the array itemlist to twig template.
My twig template
{% for item in itemlist %}
<h4>{{item.name}}</h4>
<p>{{item.name}}</p>
{{item.createdate}}
{% endfor %}
Here I am not getting the item.createdate
How to directly display the mongo date in twig template?
is there any twig extension for this?

{{ sampleDate.sec|date('Y-m-d') }}

This is an extension class that might work for you:
class MongoDateExtension extends \Twig_Extension
{
/**
* #inheritdoc
*/
public function getName()
{
return 'mongoDate_extension';
}
public function getFilters()
{
return array(
new \Twig_SimpleFilter('convertMongoDate', array($this, 'convertMongoDateFilter')),
);
}
public function convertMongoDateFilter(\MongoDate $mongoDate)
{
return new \DateTime('#' . $mongoDate->sec);
}
}
Then register the class to your dependency injection container by adding the following snippet to your services.xml. Consider that you have to adjust the class path in the example.
<service id="twig.extension.mongo_date"
class="Path\To\Your\Bundle\Twig\Extension\MongoDateExtension">
<tag name="twig.extension"/>
</service>
The extension will convert the mongo date to a php \DateTime object. It will perform the transformation with an accuracy of seconds so if you need microseconds as well you will need to adjust the extension.
Finally in your twig template you can just use the twig date formatting extension:
{{ sampleDate|convertMongoDate|date('Y-m-d') }}
which will print 2013-11-05

I've experienced problems with timezones using sec.
Instead I used toDateTime which works fine.
{{ sampleDate.toDateTime|date('Y-m-d') }}
MongoDate::toDateTime

Th most simple way i found is :
{{ event.begin.toDateTime()|date("d/m/Y H:i:s") }}

Related

How to write where year in laravel one to many elequent relationship?

I'm setting up one-to-many relation in my code. Now, how can I use whereYear case in my blade template?
I've tried this code but it shows Method whereYear does not exist.
public function awards() {
return $this->hasMany(Award::class);
}
public function user() {
return $this->belongsTo(User::class);
}
$current_year = date("Y", strtotime(now()))
{{ $user->awards->whereYear('award_month', '=', $current_year)->sum('award_point') }}
You should call awards as a method, not as a property of User object, as in:
{{ $user->awards()->whereYear('award_month', '=', $current_year)->sum('award_point') }}
This way the method whereYear is forwarded to Query Builder. Your code sample didn't work, since in it you were calling this method on a Collection object.

Difference between modelAttribute and commandName attributes in form tag in spring?

In Spring 3, I have seen two different attribute in form tag in jsp
<form:form method="post" modelAttribute="login">
in this the attribute modelAttribute is the name of the form object whose properties are used to populate the form. And I used it in posting a form and in controller I have used #ModelAttribute to capture value, calling validator, applying business logic. Everything is fine here. Now
<form:form method="post" commandName="login">
What is expected by this attribute, is it also a form object whose properties we are going to populate?
If you look at the source code of FormTag (4.3.x) which backs your <form> element, you'll notice this
/**
* Set the name of the form attribute in the model.
* <p>May be a runtime expression.
*/
public void setModelAttribute(String modelAttribute) {
this.modelAttribute = modelAttribute;
}
/**
* Get the name of the form attribute in the model.
*/
protected String getModelAttribute() {
return this.modelAttribute;
}
/**
* Set the name of the form attribute in the model.
* <p>May be a runtime expression.
* #see #setModelAttribute
*/
public void setCommandName(String commandName) {
this.modelAttribute = commandName;
}
/**
* Get the name of the form attribute in the model.
* #see #getModelAttribute
*/
protected String getCommandName() {
return this.modelAttribute;
}
They are both referring to the same field, thus having same effect.
But, as the field name indicates, modelAttribute should be preferred, as others have also pointed out.
OLD WAY = commandName
...
<spring:url value="/manage/add.do" var="action" />
<form:form action="${action}" commandName="employee">
<div>
<table>
....
NEW WAY = modelAttribute
..
<spring:url value="/manage/add.do" var="action" />
<form:form action="${action}" modelAttribute="employee">
<div>
<table>
..
I had the same question a while ago, I can't remember the exact differences but from research I ascertained that commandName was the old way of doing it and in new applications you should be using modelAttribute
commandName = name of a variable in the request scope or session scope that contains the information about this form,or this is model for this view. Tt should be a been.
In xml based config, we will use command class to pass an object between controller and views. Now in annotation we are using modelattribute.

Custom Decorator Label in Zend Framework 2

according to this post: Zend Framework 2 - Form Element Decorators , i've tried the solution from iroybot (thanks to him) and it worked.
but new problem occurs. Here the details:
In the render method in FormCollection.php (View Helper) i throw object like this:
<?php
namespace Cust\View\Helper;
use Zend\Form\ElementInterface;
use Zend\Form\View\Helper\FormCollection as BaseFormCollection;
class FormCollection extends BaseFormCollection
{
public function render(ElementInterface $element)
{
return sprintf('<table class="table table-condensed">%s</table>',parent::render($element));
}
}
and in the render method in FormElement.php (View Helper), i throw :
<?php
namespace Cust\View\Helper;
use Zend\Form\ElementInterface;
use Zend\Form\View\Helper\FormElement as BaseFormElement;
class FormElement extends BaseFormElement
{
public function render(ElementInterface $element)
{
$req = '';
if($element->getOption('required')){
$req = 'required';
}
return sprintf('<tr><td>%s</td><td>%s</td> </tr>',$element->getLabel(),parent::render($element));
}
}
and the form render in the table perfectly. but before table, the label show in the tag label. so the label display twice, first in span tag, and the second in the row of the table...
i don't know how to solve this..
please give me advice..
thanks
bestregards

Symfony2,Doctrine,MongoDb: Unable to pass query result to view

I'm trying to work my way through the DoctrineMongoDBBundle tutorial in the Symfony documentation book. I have created the test "Products" collection, and am able to insert into it without any problems, however, I can't seem to be able to read back out of it. Or at least, I can't get any result to print in my view.
The SymfonyProfiler is showing that the query is being executed. However, nothing shows up on my screen. And if I don't comment out my foreach loop in the view, then the toolbar doesn't even show up.
Controller Code:
/**
* #route("/dbReadTest2/{id}")
* #Template()
*/
public function showAction()
{
$repository = $this->get('doctrine_mongodb')
->getManager()
->getRepository('AcmeStoreBundle:Product');
$products = $repository->findAll();
return $this->render('AcmeStoreBundle:Default:index.html.twig', array(
'products' => $products,
));
}
View Code:
{% if products.count %}
In if Block
<ul>
{% for product in products %}
In For Loop
<li>{{ product.name }} </li>
{% endfor %}
</ul>
{% else %}
<p>. There are no products yet!</p>
{% endif %}
<p>End of Page</p>
The only output that I get after loading is "In If Block". None of the other comments show up.
Thank you!
I work with doctrine this way:
Controller:
$products = $this->getDoctrine()->getRepository("AcmeStoreBundle:Product")->findProducts();
ProductRepository:
class GalleryRepository extends EntityRepository
{
public function findProducts(){
return $this->getEntityManager()->getRepository("TLWEntitiesBundle:Product")->findAll();
}
}
The rest of the code seems ok.
#user2566987
1) definitely your codes in twig to access the passing $products variable is wrong. I don't have enough time to code it for you but i can guide you to the solution
2) replace all code in your view with {{ dump(products) }} then reload the page you will see all your data from there decide whether they are php data object or php data array and output them with the appropriate syntax.
3) You can not access a property field of a class if they are not existing for example is count a private member of class products. I do not see it there in the link tutorial http://symfony.com/doc/master/bundles/DoctrineMongoDBBundle/index.html
i hope it helps.

Symfony Forms: "Array to string conversion" exception in modified DateType class

I'd like to build a custom DateType class. In order to do this, I copied the class Symfony\Component\Form\Extension\Core\Type\DateType to my src/ directory and changed the class name and getName().
<?php
namespace FooBar\CoreBundle\Form\Type;
use Symfony\Component\Form\AbstractType;
// ...
class MonthType extends AbstractType
{
// ...
public function getName()
{
return 'month';
}
// ...
}
I also registered the new type:
foobar.form.type.month:
class: FooBar\CoreBundle\Form\Type\MonthType
tags:
- { name: form.type, alias: month }
However if I try to use my new type, an exception (Array to string conversion in /var/www/foobar/app/cache/dev/twig/4d/99/945***.php) is thrown:
public function buildForm(FormBuilderInterface $builder, array $options)
{
$default = new \DateTime('now');
$builder
->add('season', 'month', array('data' => $default))
;
}
Note: If I change 'month' to 'date' everything works flawlessly.
Does anyone know why the exception is thrown and how I can get rid of it?
How to fix
You have to define the block month_widget and use as form field template to make sf2 render the field properly.
For instance, write below in your .twig.
{% form_theme form _self %}
{% block month_widget %}
<input type="text" value="{{ value.year }}">
<input type="text" value="{{ value.month }}">
{% endblock %}
and customize the presentation as your like.
The default theme file Symfony/Bridge/Twig/Resources/views/Form/form_div_layout.html.twig may help.
See below for more details.
http://symfony.com/doc/current/cookbook/form/create_custom_field_type.html#creating-a-template-for-the-field
Cause of error
Symfony2 does not have the rendering block named month_widget.
MonthType that you created is child of FormType (because inherited getParent() returns 'form')
month_widget could not be found (because you haven't defined it yet), so it next tries to render form_widget.
In form_widget, there is only simple text field like <input type="text" value="{{ value }}" ..., and fails here because value is not a scalar.
The value actually isn't a DateTime but array because of DateTimeToArrayTransformer used in the class.
(as class name says, DateTime is converted into array)
So, the error is Array to string conversion.