I've made a mail function with an try/catch situation. It checks if the mail template exists, if not it needs to return redirect / back to the page with a message(return redirect('dashboard')->with('status', "Mail doesn't exists");)
Is it possible to redirect with a variable using a twig page? Or is there just something that I am doing wrong?
This is my mail function(DashboardController.php)
public function MailContact($date_id, $contact_id)
{
try
{
$contact = Contact::find($contact_id);
$date = Date::find($date_id);
$mail = Mails::where('datetype_id', $date->datetype_id)->first();
$html = $mail->html;
Mail::to($contact->email)->send(new Anniversary($html));
return redirect('dashboard');
}
catch(\Exception $ex )
{
return redirect('dashboard')->with("Mail doesn't exists");
}
}
This is the twig page('dashboard.twig')
<div class="box-body no-padding" style="width: 100%; padding-top:20px;">
<ul class="telephoneKingList" style=" display: inline-block;
width: 100%;">
{% for dates in datestodayUser %}
{% if dates is not empty %}
<li data-id="{{ dates.id }}">
{{ dates.contact.fullname }}, {{ dates.contact.relation.company }} <br>
{{ dates.description }}<br>
{# Place where Error needs to be #}
<a role="button" id="edit-button" href="/dashboard/mail/{{ dates.id }}/{{ dates.contact.id }}" class="btn btn-primary btn-sm"><i class="fa fa-envelope"></i></a>
</li>
<hr>
{% endif %}
{% else %}
<li>
Geen data beschikbaar.
</li>
{% endfor %}
</ul>
You can do
return redirect('dashboard')->with(['message'=>"Mail doesn't exists"]);
and then in your twig
{{message}} will give you the message
Use
redirect('dashboard')->withErrors(["Mail doesn't exists"])
and in your twig you need to access the errors using
{{ errors.first() }}
Laravel has a middleware included out of the box called ShareErrorsFromSession which shares the session errors with all views.
Related
I have written a Twig custom function (in a Twig custom extension). I notice the template does not read the function and keeps throwing me the "Method Exists" error.
Was wondering if you have faced this before. Any ideas ?
The custom extension file; $post and $list are both objects:
<?php
namespace App\Twig;
use Twig\Extension\AbstractExtension;
use Twig\TwigFunction;
class ShowContentExtension extends AbstractExtension
{
public function getFunctions()
{
return [
new TwigFunction('ShowList', [$this, 'ShowList']),
new TwigFunction('ShowPost', [$this, 'ShowPost'])
];
}
public function ShowList($list) {
foreach ($list->post as $post) {
$this->ShowPost($post);
}
}
public function ShowPost($post) {
return !((count(array_keys($post->documents))) < 2 && array_key_exists('header', $post->documents));
}
}
and this is where they are being called:
{% if ShowList(list) %}
<h2 >{{ title }}</h2>
<div>
<div>
{% for post in list %}
{% if post|length > 0 %}
{% include ./_links.html.twig' with { 'list': list} %}
{% endif %}
{% endfor %}
</div>
</div>
{% endif %}
and :
{% if ShowPost(post) %}
<div>
<div>
<a href="{{ post.link }}">
<span>{{ post.title }}</span>
</a>
</div>
</div>
{% endif %}
and this is the screenshot of the error :
error screenshot
I have try following code for custom block. it is working fine when I does add content from admin. but, just issue for special character.
admin\view\template\extension\module\theme_module.twig
<div class="tab-content">
{% for language in languages %}
<div id="tab8-language-{{ language.language_id }}" class="tab-pane">
<div class="form-group">
<div class="col-sm-10">
<textarea name="custom_block[{{ language.language_id }}][description]" data-toggle="summernote" data-lang="{{ summernote }}" class="form-control" id="input-description8{{ language.language_id }}">{{ custom_block[language.language_id].description ? custom_block[language.language_id].description }}</textarea>
</div>
</div>
</div>
{% endfor %}
</div>
admin\controller\extension\module\theme_module.php
if (isset($this->request->post['custom_block'])) {
$data['custom_block'] = $this->request->post['custom_block'];
} else {
$data['custom_block'] = $this->config->get('custom_block');
}
catalog\controller\common\header.php
$data['config_language_id'] = $this->config->get('config_language_id');
$data['custom_block'] = $this->config->get('custom_block');
catalog\view\theme\default\template\common\header.twig
{% set lang = config_language_id %}
{% if custom_block[lang]['description'] %}
{{ custom_block[lang]['description'] | convert_encoding('UTF-8', 'HTML-ENTITIES') }}
{% endif %}
when I does add content something like from admin: ľščťžýáíé
So, does Output: ľšÄťžýáÃé
The correct way is to do this in the controller file.
For example in:
catalog\controller\product\category.php
Create your variable:
$data['my_var'] = html_entity_decode($data['my_var'][$this->config->get('config_language_id')]['description'], ENT_QUOTES, 'UTF-8');
And in catalog\view\theme\default\template\product\category.twig, echo it:
{{ my_var }}
Output:
ľščťžýáíé
I think you should do something like this
{{custom_block.lang.description | convert_encoding('UTF-8', 'HTML-ENTITIES')}}
You can also try
#Digicart suggestion
Im working with Symfony (const version="2.5.10") and using XAMPP with PHP version of 5.5.19
My problem is I keep on getting out of memory error. Because I think I query thousand of data (rows) in the database. For info, I have a lot of data in the database. I want to use flush() or anything that could be use to optimize my data handling.
Here is my code in my indexAction controller:
public function indexAction(){
$em = $this->getDoctrine()->getManager();
$po = $em->getRepository('MatrixEdiBundle:EdiTransactionDetail')->findDocs('850');
return $this->render('MatrixEdiBundle:Matrix:index.html.twig', array('po' => $po));
}
index.html.twig
{% extends '::layout.html.twig' %}
{# {% include 'MatrixEdiBundle:Matrix:header.html.twig'%} #}
{% block body %}
<div class="content">
</br>
<table id="datTable" class="table table-bordered table-condensed table-hover">
<thead>
<th colspan="8">Edi Matrix</th>
<tr>
<th>Po Numbers</th>
<th>Trading Partner Id</th>
<th>PO 855 Acknowledgement</th>
<th>PO 997 Acknowledgement</th>
<th>Advance Shipment Notice</th>
<th>Invoice</th>
<th>Purchase Order Change</th>
<th>Order Status</th>
</tr>
</thead>
<tbody>
{% for tran in po %}
<tr>
<td><a href="{{ path('matrix_edi_showpo', {'po_num': tran.poNumber}) }}"data-toggle="modal" data-target="#myModal">{{tran.poNumber}}</td>
<td>{{tran.ediTransaction.senderId}}</td>
<td><a href="{{ path('matrix_edi_findAll', {'po_num': tran.poNumber, 'sender_id': tran.ediTransaction.senderId, 'doc_type': 855}) }}"data-toggle="modal"data-target="#myModal">
{{ render(controller('MatrixEdiBundle:Matrix:matrix', {
'po_num': tran.poNumber, 'sender_id': tran.ediTransaction.senderId, 'reciever_id': tran. ediTransaction.receiverId, 'doc_type': 855, 'gs_number': tran.ediTransaction.gsNumber })) }}</a>
</td>
<td><a href="{{ path('matrix_edi_poack', {'gs_number': tran.ediTransaction.gsNumber, 'receiver_id': tran.ediTransaction.receiverId, 'sender_id': tran.ediTransaction.senderId}) }}"data-toggle="modal"data-target="#myModal">
{{ render(controller('MatrixEdiBundle:Matrix:matrix', {
'po_num': tran.poNumber, 'sender_id': tran.ediTransaction.senderId, 'reciever_id': tran. ediTransaction.receiverId, 'doc_type': 997, 'gs_number': tran.ediTransaction.gsNumber })) }}</a>
</td>
<td><a href="{{ path('matrix_edi_findAll', {'po_num': tran.poNumber, 'sender_id': tran.ediTransaction.senderId, 'doc_type': 856}) }}"data-toggle="modal"data-target="#myModal">{{ render(controller('MatrixEdiBundle:Matrix:matrix', {
'po_num': tran.poNumber, 'sender_id': tran.ediTransaction.senderId, 'reciever_id': tran.ediTransaction.receiverId, 'doc_type': 856, 'gs_number': tran.ediTransaction.gsNumber }))}}</a>
</td>
<td>{{ render(controller('MatrixEdiBundle:Matrix:matrix', {'po_num': tran.poNumber, 'sender_id': tran.ediTransaction.senderId, 'reciever_id': tran.ediTransaction.receiverId, 'doc_type': 810, 'gs_number': tran.ediTransaction.gsNumber})) }}
</td>
<td>{{ render(controller('MatrixEdiBundle:Matrix:matrix', {'po_num': tran.poNumber, 'sender_id': tran.ediTransaction.senderId, 'reciever_id': tran.ediTransaction.receiverId, 'doc_type':860, 'gs_number': tran.ediTransaction.gsNumber})) }}
</td>
<td><a href="{{ path('matrix_edi_findAll', {'po_num': tran.poNumber, 'sender_id': tran.ediTransaction.senderId, 'doc_type': 870}) }}"data-toggle="modal"data-target="#myModal">{{ render(controller('MatrixEdiBundle:Matrix:matrix', {
'po_num': tran.poNumber, 'sender_id': tran.ediTransaction.senderId, 'reciever_id': tran.ediTransaction.receiverId, 'doc_type': 870, 'gs_number': tran.ediTransaction.gsNumber
})) }}</a></td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="false" >
<div class="modal-dialog">
<div class="modal-content" style="width: 650px;">
<div class="modal-header" style="background-color: #2d6ca2; color: white;">
<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true" style="color: white;">×</span><span class="sr-only">Close</span></button>
<h4 class="modal-title" id="myModalLabel" >Details</h4>
</div>
<div class="modal-body">
Loading, please wait......
<div class="bootstrap-table">
<div class="fixed-table-container" style="height: 299px; padding-bottom: 37px;">
<div class="fixed-table-body">
<div class="fixed-table-loading" style="top: 27px; display: none;">Loading, please wait…</div>
</div>
<div class="fixed-table-pagination"></div>
</div>
</div><div class="clearfix"></div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary" data-dismiss="modal" >Close</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
{% endblock %}
{% block javascripts %}
{% javascripts
'bundles/matrixdoc/js/jQuery.js'
'bundles/matrixdoc/js/jquery.dataTables.min.js'
'bundles/matrixdoc/js/dataTables.bootstrap.js'
'bundles/matrixdoc/js/bootstrap.js'
%}
<script src="{{ asset_url }}"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#datTable').dataTable( {
"scrollY": "400px",
"scrollCollapse": true,
"pagingType": "simple",
});
$('body').on('hidden.bs.modal', '.modal', function () {
$(this).removeData('bs.modal');
});
$(document).on("hidden.bs.modal", function (e) {
$(e.target).removeData("bs.modal").find(".modal-content").empty();
});
});
</script>
{% endjavascripts %}
{% endblock %}
You should use pagination getting your data with limits and coupled with partial to get your needed fields if you don't need everything.
http://zrashwani.com/pagination-optimization-symfony2-doctrine/#.VV1av_mSwbg
for partial in DQL , simple example for user:
//partial_fields is an array, which can be passed like this $repo->getPartialUser($user_id, array('field1', 'field2', 'etc..');
public function getPartialUser($id, $partial_fields){
$qb = $this->_em->createQueryBuilder()
->select('partial u.{'.implode(',',$partial_fields).'}')
->from('AcmeUserBundle:User', 'u')
->where('u.id = :id')
->setParameter('id', $id);
$result = $qb->getQuery()->getOneOrNullResult();
return $result;
}
EDIT EXAMPLE CODE :
i will give you an example but you will probably still need to adapt it to your code or maybe it will work out of the box.
First you need a new twig with simple piece of code to show pages numbers for navigation below the table (note that i will not use datatables paginator but we will keep it for table layout rendering) :
pager.html.twig
<div class="pagination">
<div class="pagination-buttons">
{% if pagination.page>1 %}
<a href="{{ path(pagination.route,
pagination.route_params|merge({'page': 1})) }}"><<</a>
<a href="{{ path(pagination.route,
pagination.route_params|merge({'page': pagination.page-1})) }}"><</a>
{% endif %}
{#display p numbers only from p-4 to p+4 but don't go <1 or >pages_count#}
{% for p in range(max(pagination.page-4, 1),
min(pagination.page+4, pagination.pages_count)) %}
<a{% if p == pagination.page %} class="current-page"{% endif %}
href="{{ path(pagination.route,
pagination.route_params|merge({'page': p})) }}">{{ p }}</a>
{% endfor %}
{% if pagination.page<pagination.pages_count %}
<a href="{{ path(pagination.route,
pagination.route_params|merge({'page': pagination.page+1})) }}">></a>
<a href="{{ path(pagination.route,
pagination.route_params|merge({'page': pagination.pages_count})) }}">>></a>
{% endif %}
</div>
</div>
EdiTransactionDetailRepository:
add a function with your field that you use in your table :
public function getPagedDocs($page = 1, $limit = 50)
{
$qb = $this->_em->createQueryBuilder()
->select('partial d.{field1,field2 , etc..},
partial et.{field1,field2, etc..}'
))//select doc fields and second partial for your join select edittransaction fields if you have other joins add another partial etc..
->from('YourBundle:DocsEntity', 'd')
->innerJoin('d.ediTransaction', 'et')//not sure which join you need i have no clue but i believe you will want an inner one since you will want a doc to have a ediTransaction because i didn't see any checks in your twig for it if null.
->setFirstResult(($page - 1) * $limit)
->setMaxResults($limit);
$paginator = new Paginator($qb, $fetchJoinCollection = false);//for more performance fetchjoincollection to false if you have joined tables
$paginator->setUseOutputWalkers(false);//for more performance set to false for more information http://www.doctrine-project.org/jira/browse/DDC-2890
return $paginator;
}
PS: Change limit to how many records you want to show in each page depending on the load of data you have make it lower if it is slow for 50 this is depend on how much data each row have.
Next the indexAction in your controller :
public function indexAction($page){
$em = $this->getDoctrine()->getManager();
$po = $em->getRepository('MatrixEdiBundle:EdiTransactionDetail')->getPagedDocs($page, 50);
$count = $po->count();
$pagination = array(
'page' => $page,
'route' => 'docs_index_route_name', //i dont know which name you have but it should be the route name of this indexAction
'route_params' => array()
);
if ($max_records > 0)
$pagination['pages_count'] = max(ceil($count / $max_records), 1);
return $this->render('MatrixEdiBundle:Matrix:index.html.twig', array('po' => $po,
'pagination' => $pagination
));
}
Routing:
You need to modify the route of your indexAction as we added a parameter page you need to add it for the route too :
index_docs:
pattern: /index/{page}
defaults: { _controller: "YourBundle:Controller:index", page: 1 }
NOTE : you will need to change the names and stuff i dont know you controller names and bundles so normally you will only need to add /{page} to the pattern and , page:1 to your _controller config which is the default value.
Last thing to do is your index.html.twig which need to include our pager.html.twig
include this piece of code after you close your table :
{% if po|length > 0 and pagination['pages_count'] is defined and pagination['pages_count'] > 0 %}
{#---------Pager----------#}
<div style="text-align:center;">
{% include 'YourBundle:EntityDoc:pager.html.twig' %}
</div>
{% endif %}
NOTE : The include is the path to the file where you create the pager.html.twig i assume you are familiar with how this works.
So if i didn't forget anything this should work out of the box , it should enhance greatly your performance but i am afraid that your render controller there for each row may still be problematic. But try this solution first and see, it depends what you put inside those controllers.
I'm improving my web application by adding more languages. I've done it following this tutorial: https://coderwall.com/p/eiqd_g
Everything seemed to work fine, but now I've figured out that when trying to create a new post on the forum (HerzultForumBundle), I get the above exception.
I can see in the debugger:
in kernel.root_dir/cache/dev/classes.php at line 8422
function twig_array_merge($arr1, $arr2)
{
if (!is_array($arr1) || !is_array($arr2)) {
throw new Twig_Error_Runtime('The merge filter only works with arrays or hashes.');
}
return array_merge($arr1, $arr2);
}
at twig_array_merge (null, array('_locale' => 'en'))
in kernel.root_dir/cache/dev/twig/c7/1/9188032d83474dae4ab5fad0cdaf278f4614c031cf7a5531428c5812bd57.php at line 200
echo ">
\t <a href=\"";
// line 81
echo twig_escape_filter($this->env, $this->env->getExtension('routing')->getPath($this->getAttribute($this->getAttribute((isset($context["app"]) ? $context["app"] : $this->getContext($context, "app")), "request"), "get", array(0 => "_route"), "method"), twig_array_merge($this->getAttribute($this->getAttribute((isset($context["app"]) ? $context["app"] : $this->getContext($context, "app")), "request"), "get", array(0 => "_route_params"), "method"), array("_locale" => (isset($context["locale"]) ? $context["locale"] : $this->getContext($context, "locale"))))), "html", null, true);
echo "\">";
echo twig_escape_filter($this->env, (isset($context["locale"]) ? $context["locale"] : $this->getContext($context, "locale")), "html", null, true);
echo "</a>
So it seems like the twig_array_merge() function is getting a null value as first parameter. And the HerzultForumBundle:Topic:new.html.twig template seems to be the cause.
The HerzultForumBundle:Topic:new.html.twig template holds the below code:
{% extends 'HerzultForumBundle::layout.html.twig' %}
{% block title %}New Reply{% endblock %}
{% block content %}
<div class="forum post_new">
<ul class="crumbs">
<li>Forum</li>
<li>{{ topic.category.name }}</li>
<li>{{ topic.subject }}</li>
<li>New Reply</li>
</ul>
<div class="main">
<h2>New Reply</h2>
<form action="{{ url('herzult_forum_topic_post_create', { 'slug': topic.slug, 'categorySlug' : topic.category.slug }) }}" method="post">
{{ form_widget(form) }}
<div>
<button type="submit" name="reply">Add post</button>
</div>
</form>
</div>
<div class="side">
<p>Back to the topic</p>
</div>
</div>
{% endblock %}
My guess is that the exception comes from this line:
<form action="{{ url('herzult_forum_topic_post_create', { 'slug': topic.slug, 'categorySlug' : topic.category.slug }) }}" method="post">
But don't know how to solve it. Any idea? The forum was working perfectly before.
Well, here was my problem, in the base template:
<ul id="languages">{% for locale in ['en', 'fr', 'es', 'de'] %}
<li {% if locale == app.request.locale %}class="active"{% endif %}>
{{ locale }}
</li>
{% endfor %}
</ul>
So figured that app.request.get('_route_params') was null. I tried:
<ul id="languages">{% for locale in ['en', 'fr', 'es', 'de'] %}
<li {% if locale == app.request.locale %}class="active"{% endif %}>
{% if app.request.get('_route_params') %} {{ locale }}{% endif %}
</li>
{% endfor %}
</ul>
And yes! It works. I won't have translations on the forum but never mind, I think it's pretty understandable in english.
I had a similar bug "The merge filter only works with arrays or hashes in ..." in the template. whatever line it was, whatever change i did the line of the error moved but the message remained the same..
It appeared after I added i18n compatibility to my site only on the page where there was a form.
the reason was me using a ->forward() to another template depending on the presence of error or not.
So this error is indeed linked to routing problem.
I ended up rendering the template instead of forwarding to another page.
I have a custom validator on my Symfony2 project.
The validation works fine, but the method is somehow accessed twice.
Here is my custom validator: My other resolved question
The problem is the next:
As you can see, the error message is displayed twice. When I am trying to var dump something in the validate method, the vardump is also displayed twice. Any idea why the validate is called twice? This is called when I am using $form->bind($request); in my controller.
EDIT
Here is the twig template:
{% extends 'MerrinMainBundle::layout.html.twig' %}
{% block page_title %}
MDPI Conversion system (Merrin) 3.0 - New Conversion
{% endblock %}
{% block main %}
{% for flashMessage in app.session.flashbag.get('user-notice') %}
<div class="flash-notice">
{% autoescape false %}
{{ flashMessage }}
{% endautoescape %}
</div>
{% endfor %}
<h1>Create New Manuscript</h1>
{% if valid == false %}
<div class="error">
{{ form_errors(form) }}
{{ form_errors(form.doi) }}
{{ form_errors(form.publisher) }}
{{ form_errors(form.file) }}
</div>
{% endif %}
<form action="{{ path }}" method="POST" {{ form_enctype(form) }}>
</form>
{% endblock %}
And the controller call
public function createAction()
{
$em_scipub = $this->getDoctrine()->getManager();
$em_mdpipub = $this->getDoctrine()->getManager('mdpipub');
$enquiry = new Manuscript();
$formType = new NewManuscriptType();
$form = $this->createForm($formType, $enquiry);
$request = $this->getRequest();
$valid = true;
$error = '';
if ($request->isMethod('POST')) {
$form->bind($request);
if ($form->isValid()) {
... do something ...
$em_scipub->persist($enquiry);
$em_scipub->flush();
$flash_message = "<a href='edit/".$enquiry->getId()."'>New Manuscript</a> sucessfully created.";
$this->get('session')->getFlashBag()->set('user-notice', $flash_message);
return $this->redirect($this->generateUrl('MerrinMainBundle_new'));
}
else
$valid = false;
}
$path = $this->generateUrl('MerrinMainBundle_new');
return $this->render('MerrinMainBundle:Pages:new_conversion.html.twig.twig', array(
'valid' => $valid,
'path' => $path,
'form' => $form->createView(),
) );
}
EDIT2:
The validate function:
public function validate($value, Constraint $constraint)
{
$doi = $value->getDoi();
preg_match('/[^\/]+/i', $doi, $publisherDoiAbbr);
if($publisherDoiAbbr[0] !== $value->getPublisher()->getDoiAbbreviation()) {
$this->context->addViolation($constraint->message_publisher_DOI);
}
else {
preg_match("/[a-z]+/",$doi, $journalDoiAbbr);
$em_mdpipub = $this->entityManager;
$journal = $em_mdpipub->getRepository('MerrinMdpiPubBundle:Journal')->findOneBy(array('doi_abbreviation' => $journalDoiAbbr));
if($journal == null) {
$this->context->addViolation($constraint->message_journal_DOI);
}
}
preg_match('/\d*$/i', $doi, $doiNumericPart);
if(strlen($doiNumericPart[0]) < 8) {
$this->context->addViolation($constraint->message_volume_issue_firstpage_DOI);
}
}
And the twig template:
{% extends 'MerrinMainBundle::layout.html.twig' %}
{% block page_title %}
MDPI Conversion system (Merrin) 3.0 - New Conversion
{% endblock %}
{% block main %}
{% for flashMessage in app.session.flashbag.get('user-notice') %}
<div class="flash-notice">
{% autoescape false %}
{{ flashMessage }}
{% endautoescape %}
</div>
{% endfor %}
<h1>Create New Manuscript</h1>
{% if valid == false %}
<div class="error">
{{ form_errors(form) }}
{{ form_errors(form.doi) }}
{{ form_errors(form.publisher) }}
{{ form_errors(form.file) }}
</div>
{% endif %}
<form action="{{ path }}" method="POST" {{ form_enctype(form) }}>
<div style="float:left;">
<table width="700">
<tr>
<td>
{{ form_label(form.doi) }}
</td>
<td>
{{ form_widget(form.doi, { 'attr': {'size': 40} }) }}
</td>
</tr>
<tr>
<td>
{{ form_label(form.publisher) }}
</td>
<td>
{{ form_widget(form.publisher) }}
</td>
</tr>
<tr>
<td>
{{ form_label(form.file) }}
</td>
<td>
{{ form_widget(form.file) }}
</td>
</tr>
<tr>
<td>
</td>
<td>
<input class="submit-confirm-button" type="submit" name="update-text" value="submit" />
<a class="cancel-link" href="{{ path('MerrinMainBundle_homepage' ) }}">Cancel</a>
</td>
</tr>
</table>
</div>
{{ form_rest(form) }}
</form>
{% endblock %}
EDIT 3:
Here is how I am applying the validator to the entity:
/**
* Manuscript
*
* #IsDOI()
* #ORM\Table(name="manuscripts")
* #ORM\Entity(repositoryClass="Merrin\MainBundle\Repository\ManuscriptRepository")
* #ORM\HasLifecycleCallbacks
*
*/
class Manuscript
{
....
}
EDIT 4:
When I try to vardump the
$form->getErrors();
I am getting an array with two values:
array(2) {
[0]=>
object(Symfony\Component\Form\FormError)#507 (4) {
["message":"Symfony\Component\Form\FormError":private]=>
string(77) "The Publisher DOI abbreviation does not correspond to the DOI you filled in !"
["messageTemplate":protected]=>
string(77) "The Publisher DOI abbreviation does not correspond to the DOI you filled in !"
["messageParameters":protected]=>
array(0) {
}
["messagePluralization":protected]=>
NULL
}
[1]=>
object(Symfony\Component\Form\FormError)#542 (4) {
["message":"Symfony\Component\Form\FormError":private]=>
string(77) "The Publisher DOI abbreviation does not correspond to the DOI you filled in !"
["messageTemplate":protected]=>
string(77) "The Publisher DOI abbreviation does not correspond to the DOI you filled in !"
["messageParameters":protected]=>
array(0) {
}
["messagePluralization":protected]=>
NULL
}
}
This is possible if you are using validation groups and apply validator to several groups. And what #IsDOI() annotation mean? If its apply validation possible that you first add validator in validation.yml and second via this custom annotation.
The problem is that you're rendering it twice.
Here:
{{ form_errors(form) }}
followed by:
{{ form_errors(form.doi) }}
{{ form_errors(form.publisher) }}
{{ form_errors(form.file) }}
Since you are displaying the errors in single place, I recommend using only the first method.
As stated in the form_errors twig reference:
form_errors(view)
Renders any errors for the given field.
{{ form_errors(form.name) }}
{# render any "global" errors #}
{{ form_errors(form) }}
Since you have a lot of custom code (EntityManager, Validator) it is hard to tell the error with the amount of code you provide because it's not possible to recreate the error locally.
But here are my suggestions:
In your Validator there are two possible cases the following violation gets thrown
$this->context->addViolation($constraint->message_publisher_DOI);
On both occasions the error message is the same. Maybe both of these cases apply. Try to debug this by adding an individual error message for both cases.
I don't know the code of your Form-Class but maybe you apply your custom validator to multiple fields? Also remove validations for each field individually to see where the duplicate error message is thrown.
One last mistake I can imagine would be a custom Form-Template. If you have one check whether or not you maybe call the {{ form_error(form) }} block or any other block multiple times.
I hope one of my suggestions did help you.