Skip to content

Instantly share code, notes, and snippets.

@karandatwani92
Created October 4, 2022 06:05
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save karandatwani92/64e162fb420ce78e162c9f7e40eefbcc to your computer and use it in GitHub Desktop.
Save karandatwani92/64e162fb420ce78e162c9f7e40eefbcc to your computer and use it in GitHub Desktop.
Backpack Custom operation that uses Backpack fields
@if ($crud->hasAccess('email'))
<a href="{{ url($crud->route.'/'.$entry->getKey().'/email') }}" class="btn btn-sm btn-link text-capitalize"><i class="la la-envelope"></i> email</a>
@endif
<?php
/**
* Configurations for Backpack's UpdateOperation.
*
* @see https://backpackforlaravel.com/docs/crud-operation-update
*/
return [
// Define the size/looks of the content div for all CRUDs
// To override per view use $this->crud->setEditContentClass('class-string')
'contentClass' => 'col-md-8 bold-labels',
// When using tabbed forms (create & update), what kind of tabs would you like?
'tabsType' => 'horizontal', //options: horizontal, vertical
// How would you like the validation errors to be shown?
'groupedErrors' => true,
'inlineErrors' => true,
// when the page loads, put the cursor on the first input?
'autoFocusOnFirstField' => true,
// Where do you want to redirect the user by default, save?
// options: save_and_back, save_and_edit, save_and_new
'defaultSaveAction' => 'save_and_back',
// When the user chooses "save and back" or "save and new", show a bubble
// for the fact that the default save action has been changed?
'showSaveActionChange' => true, //options: true, false
// Should we show a cancel button to the user?
'showCancelButton' => true,
// Should we warn a user before leaving the page with unsaved changes?
'warnBeforeLeaving' => false,
// Before saving the entry, how would you like the request to be stripped?
// - false - use Backpack's default (ONLY save inputs that have fields)
// - invokable class - custom stripping (the return should be an array with input names)
// 'strippedRequest' => App\Http\Requests\StripBackpackRequest::class,
];
@extends(backpack_view('blank'))
@php
$defaultBreadcrumbs = [
trans('backpack::crud.admin') => url(config('backpack.base.route_prefix'), 'dashboard'),
$crud->entity_name_plural => url($crud->route),
trans('backpack::crud.add') => false,
];
// if breadcrumbs aren't defined in the CrudController, use the default breadcrumbs
$breadcrumbs = $breadcrumbs ?? $defaultBreadcrumbs;
@endphp
@section('header')
<section class="container-fluid">
<h2>
<span class="text-capitalize">{!! $crud->getHeading() ?? $crud->entity_name_plural !!}</span>
<small>{!! $crud->getSubheading() ?? trans('backpack::crud.add').' '.$crud->entity_name !!}.</small>
@if ($crud->hasAccess('list'))
<small><a href="{{ url($crud->route) }}" class="d-print-none font-sm"><i class="la la-angle-double-{{ config('backpack.base.html_direction') == 'rtl' ? 'right' : 'left' }}"></i> {{ trans('backpack::crud.back_to_all') }} <span>{{ $crud->entity_name_plural }}</span></a></small>
@endif
</h2>
</section>
@endsection
@section('content')
<div class="row">
<div class="{{ $crud->getCreateContentClass() }}">
{{-- Default box --}}
@include('crud::inc.grouped_errors')
<form method="post"
action="{{ url($crud->route.'/email/send/'.$entry->getKey()) }}"
@if ($crud->hasUploadFields('create'))
enctype="multipart/form-data"
@endif
>
{!! csrf_field() !!}
{{-- load the view from the application if it exists, otherwise load the one in the package --}}
@if(view()->exists('vendor.backpack.crud.form_content'))
@include('vendor.backpack.crud.form_content', [ 'fields' => $crud->fields(), 'action' => 'create' ])
@else
@include('crud::form_content', [ 'fields' => $crud->fields(), 'action' => 'create' ])
@endif
{{-- This makes sure that all field assets are loaded. --}}
<div class="d-none" id="parentLoadedAssets">{{ json_encode(Assets::loaded()) }}</div>
@include('crud::inc.form_save_buttons')
</form>
</div>
</div>
@endsection
<?php
namespace App\Http\Controllers\Admin\Operations;
use Backpack\CRUD\app\Library\CrudPanel\CrudPanelFacade as CRUD;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Facades\Mail;
use Exception;
use Validator;
use Alert;
use Illuminate\Http\Request;
use App\Http\Requests\EmailFormRequest;
trait EmailOperation
{
/**
* Define which routes are needed for this operation.
*
* @param string $segment Name of the current entity (singular). Used as first URL segment.
* @param string $routeName Prefix of the route name.
* @param string $controller Name of the current CrudController.
*/
protected function setupEmailRoutes($segment, $routeName, $controller)
{
Route::get($segment . '/{id}/email', [
'as' => $routeName . '.email',
'uses' => $controller . '@getEmailForm',
'operation' => 'email',
]);
Route::post($segment . '/email/send/{id}', [
'as' => $routeName . '.email-send',
'uses' => $controller . '@postEmailForm',
'operation' => 'email',
]);
}
/**
* Add the default settings, buttons, etc that this operation needs.
*/
protected function setupEmailDefaults()
{
CRUD::allowAccess('email');
CRUD::operation('email', function () {
CRUD::loadDefaultOperationSettingsFromConfig();
});
CRUD::operation('list', function () {
// CRUD::addButton('top', 'email', 'view', 'crud::buttons.email');
CRUD::addButton('line', 'email', 'view', 'crud::buttons.email');
});
}
protected function setupEmailOperation(){
$this->crud->addField([
'name' => 'from',
'type' => 'text',
'value' => config('mail.from.address'),
'wrapper' => [
'class' => 'form-group col-md-4',
],
'validationRules' => 'required|email'
]);
$this->crud->addField([
'name' => 'to',
'type' => 'text',
'value' => $this->crud->getCurrentEntry()->email,
'attributes' => [
'readonly' => 'readonly',
'disabled' => 'disabled',
],
'wrapper' => [
'class' => 'form-group col-md-4',
],
]);
$this->crud->addField([
'name' => 'reply_to',
'type' => 'text',
'value' => backpack_user()->email,
'wrapper' => [
'class' => 'form-group col-md-4',
],
'validationRules' => 'nullable|email'
]);
$this->crud->addField([
'name' => 'subject',
'type' => 'text',
'validationRules' => 'required|min:5',
]);
$this->crud->addField([
'name' => 'message',
'type' => 'textarea',
'validationRules' => 'required|min:5',
]);
$this->crud->addSaveAction([
'name' => 'send_email',
'redirect' => function ($crud, $request, $itemId) {
return $crud->route;
},
'button_text' => 'Send Email',
]);
}
/**
* Show the view for performing the operation.
*
* @return Response
*/
public function getEmailForm()
{
$this->crud->hasAccessOrFail('email');
$this->crud->setHeading('Send Email');
$this->crud->setSubHeading('Sending email to ' . backpack_user()->name);
$this->data['crud'] = $this->crud;
$this->data['entry'] = $this->crud->getCurrentEntry();
$this->data['saveAction'] = $this->crud->getSaveAction();
$this->data['title'] = "Send email to " . backpack_user()->name;
return view('crud::email_form', $this->data);
}
public function postEmailForm(Request $request)
{
$this->crud->hasAccessOrFail('email');
$request = $this->crud->validateRequest();
$entry = $this->crud->getCurrentEntry();
try {
// send the actual email
Mail::raw($request['message'], function ($message) use ($entry, $request) {
$message->from($request->from);
$message->replyTo($request->reply_to);
$message->to($entry->email, $entry->name);
$message->subject($request['subject']);
});
Alert::success('Mail Sent')->flash();
return redirect(url($this->crud->route));
} catch (Exception $e) {
// show a bubble with the error message
Alert::error("Error, " . $e->getMessage())->flash();
return redirect()->back()->withInput();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment