Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Star Rating Bundle Laravel Package

boruta/star-rating-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps to First Use

  1. Installation:

    composer require boruta/star-rating-bundle
    

    Enable the bundle in config/bundles.php:

    Boruta\StarRatingBundle\StarRatingBundle::class => ['all' => true],
    
  2. Twig Configuration: Add the Twig paths in config/packages/twig.yaml:

    twig:
        paths:
            '%kernel.project_dir%/vendor/boruta/star-rating-bundle/Resources/views': BorutaStarRatingBundle
    
  3. Assets: Include CSS/JS in your base template (e.g., base.html.twig):

    <link rel="stylesheet" href="{{ asset('bundles/starrating/css/rating.css') }}">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
    <script src="{{ asset('bundles/starrating/js/rating.js') }}"></script>
    
  4. First Render: Use the bundle in a Twig template:

    {{ render_star_rating({ value: 3, max: 5, read_only: true }) }}
    

    For an interactive rating:

    {{ render_star_rating({ value: 3, max: 5, read_only: false, on_change: 'updateRating(event)' }) }}
    

Implementation Patterns

Core Workflows

Displaying Ratings

  • Static Ratings: Use read_only: true for display-only ratings (e.g., product reviews):
    {{ render_star_rating({ value: 4.5, max: 5, read_only: true }) }}
    
  • Interactive Ratings: Enable user input with read_only: false and specify a callback:
    {{ render_star_rating({
        value: 2,
        max: 5,
        read_only: false,
        on_change: 'handleRatingChange(event, rating)'
    }) }}
    
    JavaScript Handler:
    function handleRatingChange(event, rating) {
        fetch('/api/rate', {
            method: 'POST',
            body: JSON.stringify({ rating: rating }),
            headers: { 'Content-Type': 'application/json' }
        });
    }
    

Integration with Forms

  • Symfony Form Types: Extend the bundle’s functionality by creating a custom form type:
    // src/Form/StarRatingType.php
    use Boruta\StarRatingBundle\Form\StarRatingType;
    
    class CustomStarRatingType extends StarRatingType {
        public function configureOptions(OptionsResolver $resolver) {
            $resolver->setDefaults([
                'max' => 5,
                'read_only' => false,
            ]);
        }
    }
    
    Use in a form:
    {{ form_row(form.star_rating, { attr: { 'data-on-change': 'updateForm(event)' } }) }}
    

Dynamic Updates

  • AJAX Submissions: Pair with Symfony’s UpsertEntityFormType or custom controllers:
    // src/Controller/RatingController.php
    public function update(RatingRequest $request, RatingEntity $rating): Response {
        $rating->setValue($request->get('rating'));
        $em->persist($rating);
        $em->flush();
        return new JsonResponse(['success' => true]);
    }
    

Theming

  • Override the default Twig template by creating a custom template at:
    templates/BorutaStarRatingBundle/star_rating.html.twig
    
    Example customization:
    {% extends 'BorutaStarRatingBundle:star_rating.html.twig' %}
    {% block star_icon %}
        <i class="fas fa-star" style="color: {{ value <= loop.index0 ? '#ffc107' : '#ddd' }}"></i>
    {% endblock %}
    

Gotchas and Tips

Pitfalls

  1. jQuery Dependency:

    • The bundle requires jQuery 2.0.3. Using a newer version may break functionality.
    • Fix: Pin the version in your package.json or include the exact CDN link:
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
      
  2. Asset Paths:

    • Hardcoded paths in the bundle (e.g., bundles/starrating/) may fail in custom setups.
    • Fix: Use asset() consistently or override paths via Twig’s paths config.
  3. CSRF in AJAX:

    • Interactive ratings submitted via AJAX require CSRF tokens.
    • Fix: Include the token in your JavaScript:
      fetch('/api/rate', {
          method: 'POST',
          body: JSON.stringify({ rating: rating, _token: '{{ csrf_token('rating_submit') }}' }),
          headers: { 'Content-Type': 'application/json' }
      });
      
  4. Font Awesome Missing:

    • The bundle assumes Font Awesome is installed. Without it, stars may render as empty boxes.
    • Fix: Install via NPM:
      npm install font-awesome
      
      Then include in your layout:
      <link rel="stylesheet" href="{{ asset('node_modules/font-awesome/css/font-awesome.min.css') }}">
      

Debugging Tips

  1. Console Errors:

    • Check for Uncaught ReferenceError: $ is not defined → Missing jQuery.
    • Check for 404 on rating.css/rating.js → Verify asset() paths or Twig config.
  2. Event Not Triggering:

    • Ensure on_change is correctly bound in Twig:
      {{ render_star_rating({ on_change: 'myFunction(event, rating)' }) }}
      
    • Verify the JavaScript function exists and is accessible globally.
  3. Half-Stars Not Working:

    • The bundle supports half-stars by default (e.g., value: 4.5). If not rendering:
      • Check CSS for half classes or override the Twig template to include:
        {% if value >= loop.index0 + 0.5 %}
            <i class="fas fa-star"></i>
        {% elseif value > loop.index0 - 0.5 %}
            <i class="fas fa-star-half-alt"></i>
        {% else %}
            <i class="far fa-star"></i>
        {% endif %}
        

Extension Points

  1. Custom Icons:

    • Override the Twig template to use custom icons (e.g., SVG):
      {% block star_icon %}
          <svg class="star {{ 'filled' if value >= loop.index0 else 'empty' }}">
              {# SVG path data #}
          </svg>
      {% endblock %}
      
  2. Validation:

    • Add Symfony validation constraints to your entity:
      use Symfony\Component\Validator\Constraints as Assert;
      
      /**
       * @Assert\GreaterThanOrEqual(1)
       * @Assert\LessThanOrEqual(5)
       */
      private $rating;
      
  3. Server-Side Rendering:

    • For SSR (e.g., Symfony UX Turbo), ensure the bundle’s JS runs only in the browser:
      {% if app.environment == 'dev' %}
          {{ include('BorutaStarRatingBundle:star_rating.js') }}
      {% endif %}
      
  4. Localization:

    • Extend the bundle to support non-English labels (e.g., "Excellent" → "Excelente"):
      • Override the Twig template or use a translation extension:
        {{ 'star_rating.label'|trans({ 'max': max }, 'messages') }}
        
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky