Skip to content

Overriding and adding actions to components

Valentin Ballestrino edited this page Aug 30, 2016 · 3 revisions

You'll find the following examples here to walk you through the steps to override and add actions to existing components :

  1. Overriding which resources are shown in the index table
  2. Adding an action to the controller

1. Overriding which resources are shown in the index table

In this example, we want to remove trashed widgets from the widgets index table in our admin component.

First, we create the target controller :

rails generate controller admin/widgets

And edit it to inherit from the default :crud resources controller and add our custom code to it :

# app/controllers/admin/widgets_controller.rb
module Admin
  class WidgetsController < Para::Admin::CrudResourcesController
    def index
      super
      @resources = @resources.where(trashed: false)
    end
  end
end

We then add an endpoint in our routes that'll allow accessing that controller :

# config/routes.rb
para_at '/' do
  crud_component controller: 'widgets'
end

Finally, we configure our component to tell it to use that controller to manage its resources :

# config/components.rb
component :widgets, :crud, controller: 'widgets'

2. Adding an action to the controller

Here, we want to create a controller action that will allow us to send an e-mail to tell the customer that his order is shipped.

rails generate controller admin/orders

Inherit from the right controller and add our action :

# app/controllers/admin/orders_controller.rb
module Admin
  class OrdersController < Para::Admin::CrudResourcesController
    def send_shipping_email
      OrderMailer.shipping_sent(@resource).deliver_later
    end
  end
end

We then add the corresponding action in our routes :

# config/routes.rb
para_at '/' do
  crud_component controller: 'orders' do
    member do
      post :send_shipping_email
    end
  end
end

Configure the component to use the created controller :

# config/components.rb
component :orders :crud, controller: 'orders'

Finally, you can use the action in your views, in the form for instance :

# app/views/admin/orders/_form.html.haml
= form.input :shipment do
  = link_to 'Send shipping e-mail', @component.relation_path(form.object, action: :send_shipping_email)
Clone this wiki locally