gpt4 book ai didi

jquery 不能从外部 symfony 包工作

转载 作者:太空宇宙 更新时间:2023-11-04 06:20:48 25 4
gpt4 key购买 nike

你好,我正在尝试实现这个 symfony 3.4 RatingBundle

https://github.com/blackknight467/StarRatingBundle

我得到了这个结果

pic one

css 工作完美,但星星不可点击,所以问题是 js 和星星之间没有链接

这是我的代码#update:我已经把js代码放到了twig页面中,让代码更清晰。

html. Twig

   {%  extends 'base.html.twig' %}

{% block body %}

<h1>Lists of Posts !</h1>

<div class="album py-5 bg-light">
<div class="container">

<h2>Search A Post !!</h2>

<div class="sidebar-search">

<div class="input-group custom-search-form">

<input type="text" id="search" class="form-control" placeholder="Search here">
</div>
<!-- /input-group -->
</div>
<ul class="nav" id="side-menu">
<li>
<a href="#"> resultats de recherche<span class="fa arrow"></span></a>
<ul class="nav nav-second-level" id="entitiesNav">
</ul>
</li>
</ul><br><br><br><br>

<script type="text/javascript" src="{{ asset('assets/js/jquery-2.2.3.min.js') }}"></script>

<script type="text/javascript">



$(function(){

// $( '.rating' ).click(function() {
// alert(parseInt($(this).find('input').val()));
// });


var labelWasClicked = function labelWasClicked(){

var input = $(this).siblings().filter('input');
if (input.attr('disabled')) {
return;
}
input.val($(this).attr('data-value'));

}

var turnToStar = function turnToStar(){
if ($(this).find('input').attr('disabled')) {
return;
}
var labels = $(this).find('div');
labels.removeClass();
labels.addClass('star');
}

var turnStarBack = function turnStarBack(){
var rating = parseInt($(this).find('input').val());

if (rating > 0) {
var selectedStar = $(this).children().filter('#rating_star_'+rating)
var prevLabels = $(selectedStar).nextAll();
prevLabels.removeClass();
prevLabels.addClass('star-full');
selectedStar.removeClass();
selectedStar.addClass('star-full');
}
}

$('.star, .rating-well').click(labelWasClicked);
$('.rating-well').each(turnStarBack);
$('.rating-well').hover(turnToStar,turnStarBack);

});
jQuery(document).ready(function() {
var searchRequest = null;
$("#search").keyup(function() {
var minlength = 1;
var that = this;
var value = $(this).val();
var entitySelector = $("#entitiesNav").html('');
if (value.length >= minlength ) {
if (searchRequest != null)
searchRequest.abort();
searchRequest = $.ajax({
type: "GET",
url: "{{ path('ajax_search') }}",
data: {
'q' : value
},
dataType: "text",
success: function(msg){
//we need to check if the value is the same
if (value===$(that).val()) {
var result = JSON.parse(msg);
$.each(result, function(key, arr) {
$.each(arr, function(id, value) {
if (key === 'posts') {
if (id !== 'error') {
console.log(value[1]);
entitySelector.append('<li><b>'+value[1]+'</b><a href="/pidev_symfony-officiel/web/app_dev.php/livre/detailedlivre/'+id+'">'+'<img src="/pidev_symfony-officiel/web/livimages/'+value[0]+'" style="width: 50px; height: 70px"/>'+'</a></li>');
} else {
entitySelector.append('<li class="errorLi">'+value+'</li>');
}
}
});
});
}
}
});
}
});
});
</script>
<div class="post-container">
<div class="row">


<section class="featured section-padding">
<div class="container">
<div class="row">
<div class="col-12 text-center">
<div class="heading">
<h1 class="section-title">Livres</h1>
<br>
</div>
</div>

{% for livre in livres %}

<div class="col-xs-6 col-sm-6 col-md-6 col-lg-4">
<div class="featured-box">
<figure>
{#<img class="img-fluid" src="{{ asset('livimages/' ~ livre.image) }}" style="width: 270px;height: 350px">#}
<a href="{{ path('detailed_livre',{'id': livre.idLivre}) }}"><img class="img-fluid" src="{{ asset('livimages/' ~ livre.image) }}" style="width: 50px; height: 70px" alt=""></a>
</figure>
<div class="content-wrapper">
<div class="feature-content">
<h4>{{ livre.libelle }}</a></h4>
<p class="listing-tagline">{{ livre.description|trim }}</p>

<p class="rating">{{ '4'|rating }}</p>


</div>

</div>
</div>
</div>
{% endfor %}

</div>
</div>

</section>



</div>

</div>
</div>
</div>
{% endblock %}

{% block javascripts %}


{% endblock %}


PHP:

<?php

namespace Esprit\LoisirBundle\Form;

use blackknight467\StarRatingBundle\Form\RatingType;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\Extension\Core\Type\TextareaType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;

class LivreType extends AbstractType
{
/**
* {@inheritdoc}
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('libelle')
->add('description' ,TextareaType::class)
->add('file')
->add('auteur')
->add('url')
->add('type', ChoiceType::class, array('label' => 'Type',
'choices' => array(' PDF' => 'pdf',
'Audio' => 'audio'),
'required' => true,))
->add('categorie', ChoiceType::class, array('label' => 'Categorie',
'choices' => array(
' Historique' => 'historique',
' Biographique' => 'biographique',
' Politique' => 'politique',
' Voyages' => 'Voyages',
'Jeunesse' => 'Jeunesse'),
'required' => true,))
->add('rating', RatingType::class, [
'label' => 'Rating'
]);

}/**
* {@inheritdoc}
*/
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'Esprit\LoisirBundle\Entity\Livre'
));
}

/**
* {@inheritdoc}
*/
public function getBlockPrefix()
{
return 'esprit_loisirbundle_livre';
}


}

Controller .php

<?php

namespace Esprit\LoisirBundle\Controller;

use Esprit\LoisirBundle\Entity\Livre;
use Esprit\LoisirBundle\Entity\Utilisateur;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

/**
* Livre controller.
*
*/
class LivreController extends Controller
{
/**
* Lists all livre entities.
*
*/
public function indexAction()
{
$em = $this->getDoctrine()->getManager();

//$livres = $em->getRepository('EspritLoisirBundle:Livre')->findAll();
$livres = $em->getRepository('EspritLoisirBundle:Livre')->findBy([], ['idLivre' => 'DESC']);

return $this->render('livre/index.html.twig', array('livres' => $livres));
}

/**
* Creates a new livre entity.
*
*/
public function newAction(Request $request)
{
/* ====== sesssion try */

$user = $this->container->get('security.token_storage')->getToken()->getUser();
$user1=new Utilisateur();
$user1= $this->getDoctrine()->getRepository(Utilisateur::class) ->find($user->getId());

/* ====== sesssion try */

$livre = new Livre();
$form = $this->createForm('Esprit\LoisirBundle\Form\LivreType', $livre);
$form->handleRequest($request);

if ($form->isSubmitted() && $form->isValid()) {
/* ===== session */
$livre->setIdUtilisateur($user1);
/* ===== session */

$em = $this->getDoctrine()->getManager();
/* =====Image Up====== */
$livre -> uploadPicture();
/* =====Image Up====== */
$em->persist($livre);
$em->flush();

return $this->redirectToRoute('livre_show', array('idLivre' => $livre->getIdlivre()));
}

return $this->render('livre/new.html.twig', array(
'livre' => $livre,
'form' => $form->createView(),
));
}

/**
* Finds and displays a livre entity.
*
*/
public function showAction(Livre $livre)
{
$deleteForm = $this->createDeleteForm($livre);

return $this->render('livre/show.html.twig', array(
'livre' => $livre,
'delete_form' => $deleteForm->createView(),
));
}

/**
* Displays a form to edit an existing livre entity.
*
*/
public function editAction(Request $request, Livre $livre)
{
$deleteForm = $this->createDeleteForm($livre);
$editForm = $this->createForm('Esprit\LoisirBundle\Form\LivreType', $livre);
$editForm->handleRequest($request);

if ($editForm->isSubmitted() && $editForm->isValid()) {
$this->getDoctrine()->getManager()->flush();

return $this->redirectToRoute('livre_edit', array('idLivre' => $livre->getIdlivre()));
}

return $this->render('livre/edit.html.twig', array(
'livre' => $livre,
'edit_form' => $editForm->createView(),
'delete_form' => $deleteForm->createView(),
));
}

/**
* Deletes a livre entity.
*
*/
public function deleteAction(Request $request, Livre $livre)
{
$form = $this->createDeleteForm($livre);
$form->handleRequest($request);

if ($form->isSubmitted() && $form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->remove($livre);
$em->flush();
}

return $this->redirectToRoute('livre_index');
}

/**
* Creates a form to delete a livre entity.
*
* @param Livre $livre The livre entity
*
* @return \Symfony\Component\Form\Form The form
*/
private function createDeleteForm(Livre $livre)
{
return $this->createFormBuilder()
->setAction($this->generateUrl('livre_delete', array('idLivre' => $livre->getIdlivre())))
->setMethod('DELETE')
->getForm()
;
}

public function showdetailedAction($id)
{
$em= $this->getDoctrine()->getManager();
$liv=$em->getRepository('EspritLoisirBundle:Livre')->find($id);
return $this->render('@EspritLoisir/Livre/detailedpost.html.twig', array(
'libelle'=>$liv->getLibelle(),
'description'=>$liv->getDescription(),
'image'=>$liv->getImage(),
'auteur'=>$liv->getAuteur(),
'url'=>$liv->getUrl(),
'type'=>$liv->getType(),
'categorie'=>$liv->getCategorie(),
//'posts'=>$liv,
'comments'=>$liv,
'idLivre'=>$liv->getIdLivre()
));
}


public function listlivreAction(Request $request)
{
$em=$this->getDoctrine()->getManager();
$livres=$em->getRepository('EspritLoisirBundle:Livre')->findAll();
return $this->render('livre/list.html.twig', array(
"livres" =>$livres
));
}

public function searchAction(Request $request)
{
$em = $this->getDoctrine()->getManager();
$requestString = $request->get('q');
$livres = $em->getRepository('EspritLoisirBundle:Livre')->findEntitiesByString($requestString);
if(!$livres) {
$result['posts']['error'] = "0 books given ";
} else {
$result['posts'] = $this->getRealEntities($livres);
}
return new Response(json_encode($result));
}
public function getRealEntities($livres){
foreach ($livres as $livres){
$realEntities[$livres->getIdLivre()] = [$livres->getImage(),$livres->getLibelle()];
}
return $realEntities;
}
}


样式:

https://github.com/blackknight467/StarRatingBundle/blob/master/Resources/public/css/rating.css

js :

https://github.com/blackknight467/StarRatingBundle/blob/master/Resources/public/js/rating.js

我的主要问题是如何在html页面中调用它

$('.star, .rating-well').click(labelWasClicked);
$('.rating-well').each(turnStarBack);
$('.rating-well').hover(turnToStar,turnStarBack);

按要求在 new.html.twig 中测试:

{% extends 'base.html.twig' %}
{% form_theme form 'bootstrap_4_layout.html.twig' %}

{% block body %}
<link rel="stylesheet" type="text/css" href="{{ asset('assets/public/css/rating.css') }}" />
<script src="{{ asset('assets/public/js/rating.js') }}"></script>
<h1>Livre creation</h1>

{{ form_start(form) }}
{{ form_widget(form) }}
<input type="submit" value="Create" class="btn btn-primary" />
{{ form_end(form) }}
{{ '2'|rating }}

<ul>
<li>
<a href="{{ path('livre_index') }}">Back to the list</a>
</li>
</ul>
{% endblock %}


最佳答案

如果我理解 library如果工作正常,那么我认为 rating twig 过滤器仅用于显示评级。

为了实际评分,您需要将 RatingType 放在一个表单中(就像您所做的那样)显示该表单,然后提交并保存结果。

在您提供的 twig 文件中,您似乎在遍历 Livre(我假设)实体的集合,在这种情况下,您只能查看 livre 的评级。现在我看到你在 {{ '4'|rating }} 中有一个硬编码的 4,但我想在某些时候它应该变成 {{ livre .rating|rating }}(假设您将在 rating 列下的 Livre 实体中保留评分)以反射(reflect)实际评分。

您添加到 twig 文件中的 javascript 代码放错了地方。就像我提到的那样,您似乎处于“查看”环境中。要实际使用此脚本给出评级,您需要在显示 LivreType 表单的页面上(因为它是包含 RatingType 字段的页面)。如果可以,请粘贴包含 LivreType 表单的 Twig 文件。

javascript 代码也是不必要的,因为您应该能够使用 asset twig 函数从包本身导入脚本(这是您粘贴到 twig 文件中的内容)。它应该,根据 the readme file ,看起来像这样:

<script src="{{ asset('bundles/starrating/js/rating.js') }}"></script>

如果你想在查看 Livre 实体的集合时能够给出评分,恐怕你需要改变整个方法,有很多方法可以实现这一点,例如显示 RatingType 表单而不仅仅是评分。

另一个注意事项 - 我不确定您使用的库是否按预期工作。我自己没试过,但是来自 what I can see ,似乎评级的实际值不正确。在 5 星系统(默认)和点击第 4 星的情况下,我链接的代码将给出 2 的值,因为在 data-value="{{ stars - star + 1 }}" stars5star4

其实那里的代码是对的,只是stars的div元素是按降序添加的。

关于jquery 不能从外部 symfony 包工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55524932/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com