I'm working on an app with Symfony/Twig, and I want to scan a directory and add all photos of this directory in a Bootstrap carousel.
Controller
public function index(int $id, ManagerRegistry $doctrine): Response
{
$entityManager = $doctrine->getManager();
$establishment = $entityManager->getRepository(Establishment::class)->find($id);
$establishmentName = $establishment->getEstablishmentName();
$establishmentDirectory = $this->getParameter('media_directory').'/establishments_pages/'.$establishmentName;
$establishmentAssetDir = '/ressources/uploads/establishments_pages/'.$establishmentName;
$photos = [];
$buttons = [];
$count = 0;
$count1 = 1;
if ($establishmentDirectory) {
$results = scandir($establishmentDirectory);
foreach ($results as $value) {
if ($value !== '.'
&& $value !== '..'
&& $value !== 'Suite Deluxe'
&& $value !== 'Suite standard'
&& $value !== 'Suite VIP') {
if ($count === 0) {
$button = '<button type="button" data-bs-target="#carouselExampleIndicators" data-bs-slide-to="0" class="active" aria-current="true" aria-label="Slide '.$count1.'"></button>';
$photo = '<div class="carousel-item active"><img src="{{ asset("'.$establishmentAssetDir.'/'.$value.'")}}" class="d-block w-100" alt="Photo de l\'hotel"></div>';
array_push($buttons, $button);
array_push($photos, $photo);
$count++;
$count1++;
} else {
$button = '<button type="button" data-bs-target="#carouselExampleIndicators" data-bs-slide-to="'.$count.'" aria-label=" Slide '.$count1.'"></button>';
$photo = '<div class="carousel-item"><img src="{{ asset("'.$establishmentAssetDir.'/'.$value.'")}}" class="d-block w-100" alt="Photo de l\'hotel"></div>';
array_push($buttons, $button);
array_push($photos, $photo);
$count++;
$count1++;
}
}
}
} else {
echo 'Le dossier n\'existe pas.';
}
dump($photos);
return $this->render('establishment/establishment.html.twig', [
'id' => $id,
'establishment' => $establishment,
'establishmentName' => $establishmentName,
'establishmentDirectory' => $establishmentDirectory,
'buttons' => $buttons,
'photos' => $photos,
]);
}
When I dump $photos in this Controller, I obtain what I'm looking to do: real paths to the photos with all slashes.
array:3 [▼
0 => "<img src="{{ asset("/ressources/uploads/establishments_pages/Chez Eros/HM_francesca-saraco-dS27XGgRyQ-unsplash-625fd4f334cbd.j ▶"
1 => "<img src="{{ asset("/ressources/uploads/establishments_pages/Chez Eros/eddi-aguirre-ZAVHbpOn4Jk-unsplash-625fd4f33559c.jpg")}}" class ▶"
2 => "<img src="{{ asset("/ressources/uploads/establishments_pages/Chez Eros/marten-bjork-n-IKQDCyrG0-unsplash-625fd4f3364ae.jpg")}}" class ▶"
]
But when Twig interprets this code, it transforms all slashes to spaces, EVEN IF I put the unescape function on false!
The TWIG code :
<div id="carouselExampleIndicators" class="carousel slide" data-bs-ride="carousel">
{% autoescape false %}
<div class="carousel-indicators">
{% for button in buttons %}
{{ button }}
{% endfor %}
</div>
<div class="carousel-inner">
{% for photo in photos %}
{{photo}}
{% endfor %}
</div>
{% endautoescape %}
<button class="carousel-control-prev" type="button" data-bs-target="#carouselExampleIndicators" data-bs-slide="prev">
<span class="carousel-control-prev-icon" aria-hidden="true"></span>
<span class="visually-hidden">Previous</span>
</button>
<button class="carousel-control-next" type="button" data-bs-target="#carouselExampleIndicators" data-bs-slide="next">
<span class="carousel-control-next-icon" aria-hidden="true"></span>
<span class="visually-hidden">Next</span>
</button>
</div>
The result in debug toolbar on chrome:
<img src="{{ asset(" ressources="" uploads="" establishments_pages="" chez="" eros="" hm_francesca-saraco-ds27xggryq-unsplash-625fd4f334cbd.jpg")}}"="" class="d-block w-100" alt="Photo de l'hotel">
I already try to add "|raw" inline on the photo variable in TWIG, but it doesn't change anything!
Can anybody help me to keep my paths?
Related
I created a form with builderform. The view shows a list of private messages when you click one of the messages, a modal window opened, all of this works, but when I copy the form into the modal, only the last private message shows this form, others modal windows doesn't print this.
This is my form:
class MessageReplyFormType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('reply', TextareaType::class, array(
'label'=>false,
'required'=>true,
"attr" => array('placeholder'=>'Escribe aquí tu mensaje...')
))
->add('image', FileType::class, [
'label' => false,
'required' => false,
'data_class' => null,
'mapped' => false,
'attr'=>[
'class' => 'input-image',
'lang'=>'es',
'placeholder' => "Subir imagen ..."
],
'constraints' => [ new Image(['maxSize' => '500k'])
]
])
->add('send', SubmitType::class, array(
"label" => 'send',
"attr" => array(
"class" => "form-submit btn btn-default btn-vibrisas btn-reply"
)
))
;
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'data_class' => MessageReply::class,
]);
}
}
Here my view...
<div class="card">
<div class="card-body publications-container">
<h1 class="pub">Mensajes privados</h1>
<hr>
{% for p in private_messages %}
<div class="card message-card">
<div class="card-body message-body" >
<!-- Information about each message -->
</div>
</div>
<!-- The Modal -->
<div id="openMessage-{{ p.id }}" tabindex="-1" class="openMessage modal fade" role="dialog">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<!-- Modal Header -->
<div class="modal-header">
<!-- basic message information -->
</div>
<!-- Modal body -->
<div class="modal-body">
<div class="message-f">
{{ p.emitter.name }}<br>
{{ p.message }}<br>
{% if p.image != null %}
<div class="openImage" data-toggle="modal" data-target="#openImage-{{ p.id }}" href="/uploads/users/messages/{{ p.image }}">
<img class="message-image" src="{{ asset('/uploads/users/messages/'~p.image) }}"/>
</div>
<div id="openImage-{{ p.id }}" class="openImage modal" tabindex="-1" role="dialog">
<div class="modal-dialog modal-dialog-centered">
<div class="modal-content">
<img src="{{ asset('/uploads/users/messages/'~p.image) }}"/>
</div>
</div>
</div>
{% endif %}
</div>
{% form_theme message_reply 'bootstrap_4_layout.html.twig' %}
{{ form_start(message_reply) }}
<input type="text" name="idmessage" required class="form-control border-input hidden" placeholder="" value="{{ p.id }}">
{{ form_end(message_reply) }}
</div>
</div>
</div>
</div>
<!-- end modal -->
{% endfor %}
</div>
I'm trying to customize the template of the Media Browser when you click the "Add Media" button within Edit Post page, but it is not working.
My intention is to add the filename over the thumbnail as a caption, so I don't need to select the image to check its filename on the Attachment Details panel.
I've found this really nice answer on how to customize the Attachment Details template by overriding it in media-templates.php:
https://stackoverflow.com/a/25948448/8717608
It works flawless.
So in theory I should be able to adapt that answer to override the Attachment template, which is found here, in the line 506:
https://github.com/WordPress/WordPress/blob/master/wp-includes/media-template.php
This my version:
add_action( 'wp_enqueue_media', 'add_media_overrides' );
function add_media_overrides() {
add_action( 'admin_footer-post.php', 'override_media_templates' );
}
function override_media_templates(){
?>
<script type="text/html" id="tmpl-attachment_custom">
<div class="attachment-preview js--select-attachment type-{{ data.type }} subtype-{{ data.subtype }} {{ data.orientation }}">
<div class="thumbnail">
<# if ( data.uploading ) { #>
<div class="media-progress-bar"><div style="width: {{ data.percent }}%"></div></div>
<# } else if ( 'image' === data.type && data.sizes ) { #>
<div class="centered">
<img src="{{ data.size.url }}" draggable="false" alt="" style="height: 90%; transform: translate(-50%,-55%);"/>
<div style="
transform: translate(-50%,-100%);
background-color: black;
color: white;
margin-top: 50%;
font-size: 80%;
z-index: 9999;
position: relative;
vertical-align: middle;
">{{ data.filename }}</div>
</div>
<# } else { #>
<div class="centered">
<# if ( data.image && data.image.src && data.image.src !== data.icon ) { #>
<img src="{{ data.image.src }}" class="thumbnail" draggable="false" alt="" />
<# } else if ( data.sizes && data.sizes.medium ) { #>
<img src="{{ data.sizes.medium.url }}" class="thumbnail" draggable="false" alt="" />
<# } else { #>
<img src="{{ data.icon }}" class="icon" draggable="false" alt="" />
<# } #>
</div>
<div class="filename">
<div>{{ data.filename }}</div>
</div>
<# } #>
</div>
<# if ( data.buttons.close ) { #>
<button type="button" class="button-link attachment-close media-modal-icon"><span class="screen-reader-text"><?php _e( 'Remove' ); ?></span></button>
<# } #>
</div>
<# if ( data.buttons.check ) { #>
<button type="button" class="check" tabindex="-1"><span class="media-modal-icon"></span><span class="screen-reader-text"><?php _e( 'Deselect' ); ?></span></button>
<# } #>
<#
var maybeReadOnly = data.can.save || data.allowLocalEdits ? '' : 'readonly';
if ( data.describe ) {
if ( 'image' === data.type ) { #>
<input type="text" value="{{ data.caption }}" class="describe" data-setting="caption"
placeholder="<?php esc_attr_e( 'Caption this image…' ); ?>" {{ maybeReadOnly }} />
<# } else { #>
<input type="text" value="{{ data.title }}" class="describe" data-setting="title"
<# if ( 'video' === data.type ) { #>
placeholder="<?php esc_attr_e( 'Describe this video…' ); ?>"
<# } else if ( 'audio' === data.type ) { #>
placeholder="<?php esc_attr_e( 'Describe this audio file…' ); ?>"
<# } else { #>
placeholder="<?php esc_attr_e( 'Describe this media file…' ); ?>"
<# } #> {{ maybeReadOnly }} />
<# }
} #>
</script>
<script>
jQuery(document).ready( function($) {
if( typeof wp.media.view.Attachment != 'undefined' ){
wp.media.view.Attachment.prototype.template = wp.media.template( 'attachment-custom' );
}
});
</script>
<?php
}
By clicking Add Media button I was expecting to see all the thumbs with its filename in a black background, but nothing is happening.
Looks like I'm missing something...
There was a typo, and instead of:
wp.media.view.Attachment.prototype.template = wp.media.template( 'attachment-custom' );
Should be:
wp.media.view.Attachment.prototype.template = wp.media.template( 'attachment_custom' );
I have a variable extracted in my Twig file which is the result of a selected :
<div class="col-sm-7">
<div class="product-information"><!--/product-information-->
<img src="images/product-details/new.jpg" class="newarrival" alt="" />
<h2>{{ produit.nom }}</h2>
<p>{{ produit.categorie.nomcat }}</p>
<p>{{ produit.description }}</p>
<span>
<span>€ {{ produit.prix}}</span>
</span>
<p>
<script>
function myFunction() {
var x = document.getElementById("co").value;
document.getElementById("demo").innerHTML = x;
}
</script>
<b>Couleur :</b>
<select id="co" onchange="myFunction()">
{% for coul in produit.couleur %}
<option value="{{ coul.nomc }}">{{ coul.nomc }}</option>
{% endfor %}
</select>
</p>
<p><b>Marque :</b> {{ produit.marque}}</p>
<p>
<a href="{{ path('ajouter', { 'id' : produit.id }) }}">
<button type="button" class="btn btn-fefault cart" >
<i class="fa fa-shopping-cart"></i>
Ajouter au Panier
</button>
</a>
</p>
</div><!--/product-information-->
i try to extract the selected item from the select by put it in a variable,
somthing like that : {% set var %} <p id=demo> </p>
when i put the variable {{ var }} i get the selected item in my screen
but when i put it in the path i get the problem :
the path is somthing like that : ../../../id/ /
he put the balise p not the value of my variable
I have tried : <a href="{{ path('ajouter', { 'id' : produit.id, 'coul' : {{ var }} }) }}">
you can use FOSJsRoutingBundle to generate routes on client side (right in JS)
I have a form that contains a hidden field, it uses this field to send a variable that indicates the id of the item to remove, to the action. I have a table that displays the content of the database table 'profil', for every line there is a button "supprimer" that deletes this line, but as i said, it only deletes the first line. Apparentlu this loop creates only one form for the first item, so I want to create this form for every item in the table.
{% if profils %}
<div id="prof_table">
<table style="background-color: #f9f9f9;position: absolute;top:10vmin;left: 5vmin;"
class="table table-responsive table-bordered">
<tr>
<th style="color: #1b6d85"> Identificateur </th>
<th style="color: #1b6d85"> Libellé</th>
<th style="color: #1b6d85"> Actions</th>
</tr>
{% for profil in profils %}
<tr><td>{{ profil.id }}</td><td>{{ profil.libelle }}</td>
<td>
<button id="delete" class="btn btn-danger btn-xs">
<a data-fancybox data-src="#hidden-content3" href="javascript:;"
style="color: #ffffee;text-decoration: none;">Supprimer</a>
</button>
</td></tr>
<!-- HERE IS THE POPUP FORM TO DELETE PROFILES-->
<div style="display: none; height: 40vh; width: 30vw;" id="hidden-content3">
<span style="position:relative;top:10vmin;font-size: medium;"></span>
{% if form3 %}
<label style="display:inline-table;">
<span style="font-size: medium;">Etes vous surs de vouloir supprimer ce profil?</span>
</label>
</section>
{{ form_start(form3, { attr: {novalidate: 'novalidate'} }) }}
<section class="col-lg-9 col-md-9 col-sm-9 col-xs-9" style="position: relative; left: 5vmin;top: 6vmin">
<label style="display:inline-table;">
<span>{{form_widget(form3.idprof, {attr: { value : profil.id}} )}}</span>
</label>
</section>
<section class="col-lg-5 col-md-5 col-sm-5 col-xs-5" style="position: relative; left: 5vmin;top: 6vmin">
<span>{{ form_widget(form3.Confirmer) }}</span>
</section>
{{ form_end(form3) }}
{% endif %}
</div>
{% endfor %}
</table>
</div>
{% else %}
{{ "Aucun profil n'a été trouvé." }}
{% endif %}
/**
* #Route("/webmaster/gestProf/{idprof}", defaults={"idprof": 0},name="gestProf")
* Method ("POST")
* #Template()
*/
public function gestProfAction(Request $request)
{
$session = new Session();
$session->start();
$em=$this
->getDoctrine()
->getManager();
$repository = $em->getRepository("CNAMCMSBundle:profil");
$profils = $repository->findAll();
foreach ($profils as $prof) {
$id = $prof->getId();
$libelle = $prof->getLibelle();
}
$prof = new profil();
$form3 = $this->createFormBuilder($prof, array('csrf_protection' => false))
->setMethod("POST")
->add('idprof', 'hidden', array('mapped' => false))
->add('Confirmer', 'submit', array('attr' => array('class' => 'btn btn-primary btn-block rounded_btn', 'id' => 'login_btn',
'style' => "width:6vw;height:5vh;padding:0px 0px; position:relative;left:5vmin;top:1vmin;font-size:2vmin;")))
->getForm();
$form3->handleRequest($request);
if ($form3->isSubmitted()) {
//$idprof = $request->request->get('idprof');
$idprof = $form3->get('idprof')->getData();
$repository = $em->getRepository("CNAMCMSBundle:profil");
$prof = $repository->findOneById($idprof);
$em=$this
->getDoctrine()
->getManager();
$em->remove($prof);
$em->flush();
}
var_dump($request->getContent());
return $this->render('CNAMCMSBundle:Default:gestProf.html.twig', array('profils'=>$profils,
'form3'=>$form3->createView()
));
}
I'm developping a blog using Symfony 2.7. I've an ArticleBundle and a CommentBundle. My entities Article and Comment are linked by a ManyToOne relation.
When I try to send a comment, it fails. The $form->isValid() method returns false.
Here, my add method to send a comment :
public function addAction(Article $article, Request $request){
$comment = new Comment();
$form = $this->createForm(new CommentType(), $comment);
$form->handleRequest($request);
if($form->isValid()){
$comment->setArticle($article);
$em = $this->getDoctrine()->getManager();
$em->persist($comment);
$em->flush();
return $this->redirect($this->generateUrl('esgi_article_view', array(
'id' => $article->getId()
)));
} else{
return $this->render('ESGICommentBundle:Comment:add.html.twig', array(
'form' => $form->createView(),
'article' => $article
));
}
}
My comment form is inclued into article's view like this :
{{ render(controller("ESGICommentBundle:Comment:add", { 'id' : article.id })) }}
And here my form :
{{ form_start(form) }}
<div class="form-group">
<div class="row">
<div class="col-xs-12 col-sm-6 col-md-8">
{{ form_label(form.author, "Auteur") }}
{{ form_widget(form.author, { 'attr' : { 'class' : 'form-control' } }) }}
{{ form_errors(form.author) }}
</div>
</div>
<div class="row">
<div class="col-xs-12 col-sm-6 col-md-8">
{{ form_label(form.email, "Email (optionnel)") }}
{{ form_widget(form.email, { 'attr' : { 'class' : 'form-control' } }) }}
{{ form_errors(form.email) }}
</div>
</div>
<div class="row">
<div class="col-xs-12 col-sm-6 col-md-8">
{{ form_label(form.content, "Commentaire") }}
{{ form_widget(form.content, { 'attr' : { 'class' : 'form-control' } }) }}
{{ form_errors(form.content) }}
</div>
</div>
</div>
<button class="btn btn-success" type="submit">Poster</button>
{{ form_end(form) }}
Thanks, have a nice day !
IF you submit the form, you should have all the errors in the profiler bar(there is a form icon which you can click to see errors in the submitted form)