I have my custom module Customer feedback/Inquiry form in which customer can ask Inquiry related to product or they can able to give feedback related to store.In admin side i listed out all the feedbacks in admin grid.
Now I want to integrate the Mail functionality like when I click on particular feedback edit section there will be separate section for mail body where i will enter the reply, click on send button and mail goes to particular customer which mail Id has been already present in that particular edit section.
Here is code for my AdminHtml controller file
<?php
class Foo_Bar_Adminhtml_BazController extends Mage_Adminhtml_Controller_Action
{
public function indexAction()
{
// Let's call our initAction method which will set some basic params for each action
$this->_initAction()
->renderLayout();
}
public function newAction()
{
// We just forward the new action to a blank edit form
$this->_forward('edit');
}
public function editAction()
{
$this->_initAction();
// Get id if available
$id = $this->getRequest()->getParam('id');
$model = Mage::getModel('foo_bar/baz');
if ($id) {
// Load record
$model->load($id);
// Check if record is loaded
if (!$model->getId()) {
Mage::getSingleton('adminhtml/session')->addError($this->__('This baz no longer exists.'));
$this->_redirect('*/*/');
return;
}
}
$this->_title($model->getId() ? $model->getName() : $this->__('New Baz'));
$data = Mage::getSingleton('adminhtml/session')->getBazData(true);
if (!empty($data)) {
$model->setData($data);
}
Mage::register('foo_bar', $model);
$this->_initAction()
->_addBreadcrumb($id ? $this->__('Edit Baz') : $this->__('New Baz'), $id ? $this->__('Edit Baz') : $this->__('New Baz'))
->_addContent($this->getLayout()->createBlock('foo_bar/adminhtml_baz_edit')->setData('action', $this->getUrl('*/*/save')))
->renderLayout();
}
public function saveAction()
{
if ($postData = $this->getRequest()->getPost()) {
$model = Mage::getSingleton('foo_bar/baz');
$model->setData($postData);
try {
$model->save();
Mage::getSingleton('adminhtml/session')->addSuccess($this->__('The baz has been saved.'));
$this->_redirect('*/*/');
return;
}
catch (Mage_Core_Exception $e) {
Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
}
catch (Exception $e) {
Mage::getSingleton('adminhtml/session')->addError($this->__('An error occurred while saving this baz.'));
}
Mage::getSingleton('adminhtml/session')->setBazData($postData);
$this->_redirectReferer();
}
}
public function deleteAction()
{
// check if we know what should be deleted
$itemId = $this->getRequest()->getParam('id');
if ($itemId) {
try {
// init model and delete
/** #var $model Magentostudy_News_Model_Item */
$model = Mage::getModel('foo_bar/baz');
$model->load($itemId);
if (!$model->getId()) {
Mage::throwException(Mage::helper('foo_bar')->__('Unable to find a Baz.'));
}
$model->delete();
// display success message
$this->_getSession()->addSuccess(
Mage::helper('foo_bar')->__('The Baz has been deleted.')
);
} catch (Mage_Core_Exception $e) {
$this->_getSession()->addError($e->getMessage());
} catch (Exception $e) {
$this->_getSession()->addException($e,
Mage::helper('foo_bar')->__('An error occurred while deleting the baz.')
);
}
}
// go to grid
$this->_redirect('*/*/');
}
public function messageAction()
{
$data = Mage::getModel('foo_bar/baz')->load($this->getRequest()->getParam('id'));
echo $data->getContent();
}
/**
* Initialize action
*
* Here, we set the breadcrumbs and the active menu
*
* #return Mage_Adminhtml_Controller_Action
*/
protected function _initAction()
{
$this->loadLayout()
// Make the active menu match the menu config nodes (without 'children' inbetween)
->_setActiveMenu('sales/foo_bar_baz')
->_title($this->__('Sales'))->_title($this->__('Baz'))
->_addBreadcrumb($this->__('Sales'), $this->__('Sales'))
->_addBreadcrumb($this->__('Baz'), $this->__('Baz'));
return $this;
}
/**
* Check currently called action by permissions for current user
*
* #return bool
*/
protected function _isAllowed()
{
return Mage::getSingleton('admin/session')->isAllowed('sales/foo_bar_baz');
}
}
I want some hooks from which i will able to send mail to particular customer.
Here is the image of my admin grid section
The most easiest way is to create a new transactional mail and set the subject to a placeholder and the same for the body.
this is the transactional mail function:
/**
* Send transactional email to recipient
*
* #param int $templateId
* #param string|array $sender sneder informatio, can be declared as part of config path
* #param string $email recipient email
* #param string $name recipient name
* #param array $vars varianles which can be used in template
* #param int|null $storeId
* #return Mage_Core_Model_Email_Template
*/
public function sendTransactional($templateId, $sender, $email, $name, $vars=array(), $storeId=null)
so the first to do is, create a new transactional mail under System->Transactional Mails. Just fill it with some random stuff for now. then
go to where ever you want to send the email and add
Mage::getModel('core/email_template')
->sendTransactional(
{the transactional email id we just created},
$sender,
$recepientEmail,
$recepientName,
array(
'subject' => '{your subject}',
'body' => '{you body}'
)
);
replace {your subject} and {your body} with the corresponding from you input fields.
after doing that go back to your transactional email template and replace our random stuff with that:
enter {{var subject}} in the subject field
and {{var body}} in die content field of the transactional mail
i didn't tried this but it should work.
hope that helps
Related
I am trying to submit a payment against Paypal Sandbox, using the Omnipay Paypal module.
I think that I have everything set up in terms of sandbox account, and my transaction is working if I don't specify a card as payment method. I am correctly redirected to the Paypal sandbox, where I need to enter my test credentials before I can submit my payment. Then I am redirected back to my original web site, where I can store the confirmed payment details.
However, when I want to use a credit card, I get an error message saying : Payee account is invalid.
Here is my controller code :
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Omnipay\Omnipay;
use Omnipay\Common\CreditCard;
use App\Payment;
class PaymentController extends Controller
{
private $gateway;
public function __construct()
{
$this->gateway = Omnipay::create('PayPal_Rest');
$this->gateway->setClientId(env('PAYPAL_CLIENT_ID'));
$this->gateway->setSecret(env('PAYPAL_CLIENT_SECRET'));
$this->gateway->setTestMode(env('PAYPAL_SANDBOX_MODE'));;
}
/**
* Call a view.
*/
public function index()
{
return view('payment');
}
/**
* Initiate a payment on PayPal.
*
* #param \Illuminate\Http\Request $request
*/
public function charge(Request $request)
{
if($request->input('submit'))
{
$card = new CreditCard(array(
'number' => '<my test credit card number>',
'expiryMonth' => '03',
'expiryYear' => '2024',
'cvv' => '<my ccv>',
));
try {
$response = $this->gateway->purchase(array(
'amount' => $request->input('amount'),
'currency' => env('PAYPAL_CURRENCY'),
'returnUrl' => url('success'),
'cancelUrl' => url('error'),
'card' => $card
))->send();
if ($response->isRedirect()) {
$response->redirect(); // this will automatically forward the customer
} else {
// not successful
return $response->getMessage();
}
} catch(Exception $e) {
return $e->getMessage();
}
}
}
/**
* Charge a payment and store the transaction.
*
* #param \Illuminate\Http\Request $request
*/
public function success(Request $request)
{
// Once the transaction has been approved, we need to complete it.
if ($request->input('paymentId') && $request->input('PayerID'))
{
$transaction = $this->gateway->completePurchase(array(
'payer_id' => $request->input('PayerID'),
'transactionReference' => $request->input('paymentId'),
));
$response = $transaction->send();
if ($response->isSuccessful())
{
// The customer has successfully paid.
$arr_body = $response->getData();
// Insert transaction data into the database
$payment = new Payment;
$payment->payment_id = $arr_body['id'];
$payment->payer_id = $arr_body['payer']['payer_info']['payer_id'];
$payment->payer_email = $arr_body['payer']['payer_info']['email'];
$payment->amount = $arr_body['transactions'][0]['amount']['total'];
$payment->currency = env('PAYPAL_CURRENCY');
$payment->payment_status = $arr_body['state'];
$payment->save();
return "Payment is successful. Your transaction id is: ". $arr_body['id'];
} else {
return $response->getMessage();
}
} else {
return 'Transaction is declined';
}
}
/**
* Error Handling.
*/
public function error()
{
return 'User cancelled the payment.';
}
}
Can you see where my problem could be ?
Usually Laravel's form request returns a generic 400 code on failing validation like this:
{
"message": "The given data is invalid",
"errors": {
"person_id": [
"A person with ID c6b853ec-b53e-4c35-b633-3b1c2f27869c does not exist"
]
}
}
I'd like to return a 404 if a request does not pass my custom rule.
My custom rule checks if a record exists in the DB:
class ValidatePersonExists implements Rule
{
/**
* Determine if the validation rule passes.
*
* #param string $attribute
* #param mixed $value
* #return bool
public function passes($attribute, $value)
{
return Person::where('id', $value)->exists();
}
/**
* Get the validation error message.
*
* #return string
*/
public function message()
{
return "A person with ID :input does not exist";
}
}
If I throw a ModelNotFoundException on failure of the exists() check, where can I catch it to respond with a friendly 404 response?
Here's my form request where I am using the rule:
public function rules()
{
return [
'person_id' => ['bail', 'required', 'uuid', new ValidatePersonExists],
];
}
you can modify app/Exceptions/Handler.php, here is how i used it
use Illuminate\Database\Eloquent\ModelNotFoundException;
public function render($request, Exception $e)
{
$status = method_exists($e, 'getStatusCode') ? $e->getStatusCode() : 500;
//here im using translation, you can set your own message
$response = [
'errors' => trans("response.$status.response"),
'message' => trans("response.$status.message")
];
if (config('app.debug')) {
$response['exception'] = get_class($e);
$response['message'] = $e->getMessage();
$response['trace'] = $e->getTrace();
}
//ModelNotFoundException statusCode is 0 so i need to pass it manually
if($e instanceof ModelNotFoundException){
$response['errors'] = new \Illuminate\Support\ViewErrorBag;
$response['response'] = 404; // im using translation here
return response()->view("errors.index", $response, 404);
}
return parent::render($request, $e);
}
in my blade a simple translation message:
<p>{{trans("response.{$response}.response")}}</p>
<p>{{trans("response.{$response}.message")}}</p>
I've found a solution, but I'm not 100% happy with it.
Basically I've created a class (ApiRequest.php) to extend Illuminate's FormRequest class, and in this ApiRequest class I'm intercepting the IlluminateValidationException and doing some logic on the failed validation, checking if the Request failed on my exists() rule. If it does, I'm changing the status code to 404:
Here's my class:
abstract class ApiRequest extends IlluminateFormRequest
{
/**
* Handle a failed validation attempt.
*
* #param \Illuminate\Contracts\Validation\Validator $validator
* #return void
*
* #throws \GetCandy\Api\Exceptions\ValidationException
*/
protected function failedValidation(Validator $validator)
{
$failedRules = $validator->failed();
$statusCode = $this->getStatusCode($failedRules);
$response = new JsonResponse([
'message' => 'The given data is invalid',
'errors' => $validator->errors(),
], $statusCode);
throw new IlluminateValidationException($validator, $response);
}
private function getStatusCode($failedRules)
{
$statusCode = 400;
foreach ($failedRules as $rule) {
if (Arr::has($rule, "App\Http\Requests\Rules\ValidatePersonExists")) {
$statusCode = 404;
}
}
return $statusCode;
}
}
Hope this helps someone, if anyone has a better solution feel free to post an answer.
i need to send a copy of welcome email to specific mail.
what i did is i tried to create module to do it programmatically, i created a overrid that handle execute CreatePost.php but it sent before.
<?php
/**
* Copyright © Cinemanext, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Cinemanext\ForceLogin\Controller\Account;
use \Magento\Framework\App\ObjectManager;
/**
* #SuppressWarnings(PHPMD.TooManyFields)
* #SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/
class CreatePost extends \Magento\Customer\Controller\Account\CreatePost
{
}
this option exist in order mail, you can send copy to specific email.
how i can add same function to welcome mail.
Try below code
<?php
namespace Cinemanext\ForceLogin\Controller\Account;
use Magento\Framework\App\Action\Context;
use Magento\Framework\View\Result\PageFactory;
use Magento\Store\Model\StoreManagerInterface;
use Magento\Customer\Model\CustomerFactory;
use Magento\Customer\Model\AddressFactory;
use Magento\Framework\Message\ManagerInterface;
use Magento\Framework\Escaper;
use Magento\Framework\UrlFactory;
use Magento\Customer\Model\Session;
use Magento\Customer\Model\Registration;
use Magento\Framework\Data\Form\FormKey\Validator;
use Magento\Framework\App\ObjectManager;
class CreatePost extends \Magento\Framework\App\Action\Action
{
/**
* #var \Magento\Store\Model\StoreManagerInterface
*/
protected $storeManager;
/**
* #var \Magento\Customer\Model\CustomerFactory
*/
protected $customerFactory;
/**
* #var \Magento\Customer\Model\AddressFactory
*/
protected $addressFactory;
/**
* #var \Magento\Framework\Message\ManagerInterface
*/
protected $messageManager;
/**
* #var \Magento\Framework\Escaper
*/
protected $escaper;
/**
* #var \Magento\Framework\UrlFactory
*/
protected $urlFactory;
/**
* #var \Magento\Customer\Model\Session
*/
protected $session;
/**
* #var Magento\Framework\Data\Form\FormKey\Validator
*/
private $formKeyValidator;
/**
* #param Context $context
* #param StoreManagerInterface $storeManager
* #param CustomerFactory $customerFactory
* #param AddressFactory $addressFactory
* #param ManagerInterface $messageManager
* #param Escaper $escaper
* #param UrlFactory $urlFactory
* #param Session $session
* #param Validator $formKeyValidator
*/
public function __construct(
Context $context,
StoreManagerInterface $storeManager,
CustomerFactory $customerFactory,
AddressFactory $addressFactory,
ManagerInterface $messageManager,
Escaper $escaper,
UrlFactory $urlFactory,
Session $session,
Validator $formKeyValidator = null
)
{
$this->storeManager = $storeManager;
$this->customerFactory = $customerFactory;
$this->addressFactory = $addressFactory;
$this->messageManager = $messageManager;
$this->escaper = $escaper;
$this->urlModel = $urlFactory->create();
$this->session = $session;
$this->formKeyValidator = $formKeyValidator ?: ObjectManager::getInstance()->get(Validator::class);
// messageManager can also be set via $context
// $this->messageManager = $context->getMessageManager();
parent::__construct($context);
}
/**
* Default customer account page
*
* #return void
*/
public function execute()
{
/** #var \Magento\Framework\Controller\Result\Redirect $resultRedirect */
$resultRedirect = $this->resultRedirectFactory->create();
// if ($this->session->isLoggedIn() || !$this->registration->isAllowed()) {
// $resultRedirect->setPath('*/*/');
// return $resultRedirect;
// }
// check if the form is actually posted and has the proper form key
if (!$this->getRequest()->isPost() || !$this->formKeyValidator->validate($this->getRequest())) {
$url = $this->urlModel->getUrl('*/*/create', ['_secure' => true]);
$resultRedirect->setUrl($this->_redirect->error($url));
return $resultRedirect;
}
$websiteId = $this->storeManager->getWebsite()->getWebsiteId();
$firstName = 'John';
$lastName = 'Doe';
$email = 'johndoe4#example.com';
$password = 'Test1234';
// instantiate customer object
$customer = $this->customerFactory->create();
$customer->setWebsiteId($websiteId);
// check if customer is already present
// if customer is already present, then show error message
// else create new customer
if ($customer->loadByEmail($email)->getId()) {
//echo 'Customer with the email ' . $email . ' is already registered.';
$message = __(
'There is already an account with this email address "%1".',
$email
);
// #codingStandardsIgnoreEnd
$this->messageManager->addError($message);
} else {
try {
// prepare customer data
$customer->setEmail($email);
$customer->setFirstname($firstName);
$customer->setLastname($lastName);
// set null to auto-generate password
$customer->setPassword($password);
// set the customer as confirmed
// this is optional
// comment out this line if you want to send confirmation email
// to customer before finalizing his/her account creation
$customer->setForceConfirmed(true);
// save data
$customer->save();
// save customer address
// this is optional
// you can skip saving customer address while creating the customer
$customerAddress = $this->addressFactory->create();
$customerAddress->setCustomerId($customer->getId())
->setFirstname($firstName)
->setLastname($lastName)
->setCountryId('US')
->setRegionId('12') // optional, depends upon Country, e.g. USA
->setRegion('California') // optional, depends upon Country, e.g. USA
->setPostcode('90232')
->setCity('Culver City')
->setTelephone('888-888-8888')
->setFax('999')
->setCompany('XYZ')
->setStreet(array(
'0' => 'Your Customer Address 1', // compulsory
'1' => 'Your Customer Address 2' // optional
))
->setIsDefaultBilling('1')
->setIsDefaultShipping('1')
->setSaveInAddressBook('1');
try {
// save customer address
$customerAddress->save();
} catch (Exception $e) {
$this->messageManager->addException($e, __('We can\'t save the customer address.'));
}
// send welcome email to the customer
$customer->sendNewAccountEmail();
//echo 'Customer with the email ' . $email . ' is successfully created.';
$this->messageManager->addSuccess(
__(
'Customer account with email %1 created successfully.',
$email
)
);
$url = $this->urlModel->getUrl('*/*/create', ['_secure' => true]);
$resultRedirect->setUrl($this->_redirect->success($url));
//$resultRedirect->setPath('*/*/');
return $resultRedirect;
} catch (StateException $e) {
$url = $this->urlModel->getUrl('customer/account/forgotpassword');
// #codingStandardsIgnoreStart
$message = __(
'There is already an account with this email address. If you are sure that it is your email address, click here to get your password and access your account.',
$url
);
// #codingStandardsIgnoreEnd
$this->messageManager->addError($message);
} catch (InputException $e) {
$this->messageManager->addError($this->escaper->escapeHtml($e->getMessage()));
foreach ($e->getErrors() as $error) {
$this->messageManager->addError($this->escaper->escapeHtml($error->getMessage()));
}
} catch (LocalizedException $e) {
$this->messageManager->addError($this->escaper->escapeHtml($e->getMessage()));
} catch (\Exception $e) {
$this->messageManager->addException($e, __('We can\'t save the customer.'));
}
}
$this->session->setCustomerFormData($this->getRequest()->getPostValue());
$defaultUrl = $this->urlModel->getUrl('*/*/create', ['_secure' => true]);
$resultRedirect->setUrl($this->_redirect->error($defaultUrl));
return $resultRedirect;
}
}
I am very new to testing, but have now found it essential to automate my testing.
I have a test that is working fine up until it gets to the link '/cart' it gets to the link '/cart' no problem, but any other link I try to click afterwards always ends up back at the cart.
here is my error after trying to navigate away from the cart.
Failed asserting that two strings are equal.
--- Expected
+++ Actual
## ##
-'http://ngwenya-mtb.dev/events'
+'http://ngwenya-mtb.dev/cart'
And here is my test script
use Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;
class ExampleTest extends TestCase {
//use Illuminate\Foundation\Testing\WithoutMiddleware;
//use DatabaseTransactions;
//use withoutMiddleware;
//use DatabaseMigrations;
/**
*
* A basic functional test example.
* Please choose a unique email address for your new participant
* #return void
*/
public function testNewUserRegistration() {
$this->visit('http://ngwenya-mtb.dev/')
// View Event
->click('View event details')
->seePageIs('/event?id=30')
->click('#enter-race47')
->press('Enter yourself to this race')
->seePageIs('/events/courses/register/addtocart')
//->withSession(['This email is already registered' => 'alert-danger'])
/////////////////////////////////////////////
// Fill the register for for new user
/////////////////////////////////////////////
->type('Bingo', 'first_name')
->type('11111111', 'password')
->type('11111111', 'password_confirmation')
->type(''.substr(md5(time()), 0, 12).'#tesing.com', 'email')
//->check('terms')
->select('Male', 'gender')
->select('1985', 'year')
->select('07', 'month')
->select('21', 'day')
->select('Small', 'shirt_size')
->select('Swaziland ID', 'id_type')
->type('badassnumber', 'id_number')
->select('Swazi', 'nationality')
//Contact details Physical
->type('Dawlish', 'town_physical')
->select('Swaziland', 'country_physical')
->type('864741', 'phone_cell')
//Emergency contact details 1
->type('Simon', 'emergency_contact_1')
->type('Brother', 'emergency_relationship_1')
->type('864741', 'emergency_phone_1');
$this->press('Register');
$this->seePageIs('/cart');
/////////////////////////////////////////////
// Add a new user
/////////////////////////////////////////////
$this->visit('http://ngwenya-mtb.dev/');
$this->click('#events-link')
->seePageIs('/events');
dd($this->response->getContent());exit;
$this->click('#event-30');
$this->seePageIs('/event?id=30');
$this->click('#enter-race48');
$this->press('Enter someone else to this race');
$this->seePageIs('/events/courses/register/addtocart');
}
}
Everything is working fine up until this comment
/////////////////////////////////////////////
// Add a new user
/////////////////////////////////////////////
Here is my Registration controller
<?php
namespace App\Http\Controllers;
use Vinkla\Hashids\HashidsManager;
use Illuminate\Routing\Controller as BaseController;
use Sentinel\FormRequests\RegisterRequest;
use Sentinel\FormRequests\EmailRequest;
use Sentinel\FormRequests\ResetPasswordRequest;
use Sentinel\Repositories\Group\SentinelGroupRepositoryInterface;
use Sentinel\Repositories\User\SentinelUserRepositoryInterface;
use Sentinel\Traits\SentinelRedirectionTrait;
use Sentinel\Traits\SentinelViewfinderTrait;
use Sentry;
use View;
use Request;
use Event;
use Redirect;
use Session;
use Config;
use App\Models\Users;
use Illuminate\Support\Facades\Input;
use Gloudemans\Shoppingcart\Facades\Cart;
class RegistrationController extends BaseController
{
/**
* Traits
*/
use SentinelRedirectionTrait;
use SentinelViewfinderTrait;
/**
* Constructor
*/
public function __construct(
SentinelUserRepositoryInterface $userRepository,
SentinelGroupRepositoryInterface $groupRepository,
HashidsManager $hashids
) {
$this->userRepository = $userRepository;
$this->groupRepository = $groupRepository;
$this->hashids = $hashids;
}
/**
* Show the registration form, if registration is allowed
*
* #return Response
*/
public function registration()
{
// Is this user already signed in? If so redirect to the post login route
if (Sentry::check()) {
return $this->redirectTo('session_store');
}
//If registration is currently disabled, show a message and redirect home.
if (! config('sentinel.registration', false)) {
return $this->redirectTo(['route' => 'home'], ['error' => trans('Sentinel::users.inactive_reg')]);
}
// All clear - show the registration form.
return $this->viewFinder(config('sentinel.view.user_register', 'Sentinel::users.register'));
}
/**
* Process a registration request
*
* #return Response
*/
public function register(RegisterRequest $request)
{
// Gather input
$data = $request->all();
// collect cart items
$email = Input::get('email');
$course_id = Input::get('course_id');
$event_name = Input::get('event_name');
$entry_fee = Input::get('entry_fee');
// check user exists
if (Users::where('email', '=', $email)->exists()) {
// user found
$request->session()->flash('alert-danger', 'Warning: This email is already registered.');
Input::flash();
return View::make('sentinel.users.register')
->with('course_id',$course_id)
->with('event_name',$event_name)
->with('entry_fee',$entry_fee);
}
// Add user and course to cart
if ($course_id) {
$firstUserRowId = Cart::add($course_id, $event_name , 1, $entry_fee, [
'first_name' => Input::get('first_name'),
'last_name' => Input::get('last_name'),
'email' => Input::get('email'),
'no_email' => 0,
'master_user' => 1,
'gender' => Input::get('gender'),
'dob' => Input::get('dob'),
'shirt_size' => Input::get('shirt_size'),
'id_type' => Input::get('id_type'),
'id_number' => Input::get('id_number'),
'nationality' => Input::get('nationality'),
'phone_cell' => Input::get('phone_cell'),
'town_physical' => Input::get('town_physical'),
'country_physical' => Input::get('country_physical'),
'emergency_contact_1' => Input::get('emergency_contact_1'),
'emergency_relationship_1' => Input::get('emergency_relationship_1'),
'emergency_phone_1' => Input::get('emergency_phone_1'),
]);
}
// get email from request
$email = $request->only('email');
foreach ($email as $userModel) {}
// Edit date of birth from request
$year = Input::get('year');
$month = Input::get('month');
$day = Input::get('day');
$dob = $year.'-'.$month.'-'.$day;
$data['dob'] = $dob;
// Attempt Registration
$result = $this->userRepository->store($data);
// Log user in
FunctionsController::loginUser($userModel);
// It worked! Use config to determine where we should go.
return $this->redirectViaResponse('registration_complete', $result);
}
/**
* Activate a new user
*
* #param int $id
* #param string $code
*
* #return Response
*/
public function activate($hash, $code)
{
// Decode the hashid
$id = $this->hashids->decode($hash)[0];
// Attempt the activation
$result = $this->userRepository->activate($id, $code);
// It worked! Use config to determine where we should go.
return $this->redirectViaResponse('registration_activated', $result);
}
/**
* Show the 'Resend Activation' form
*
* #return View
*/
public function resendActivationForm()
{
return $this->viewFinder('Sentinel::users.resend');
}
/**
* Process resend activation request
* #return Response
*/
public function resendActivation(EmailRequest $request)
{
// Resend the activation email
$result = $this->userRepository->resend(['email' => e($request->get('email'))]);
// It worked! Use config to determine where we should go.
return $this->redirectViaResponse('registration_resend', $result);
}
/**
* Display the "Forgot Password" form
*
* #return \Illuminate\View\View
*/
public function forgotPasswordForm()
{
return $this->viewFinder('Sentinel::users.forgot');
}
/**
* Process Forgot Password request
* #return Response
*/
public function sendResetPasswordEmail(EmailRequest $request)
{
// Send Password Reset Email
$result = $this->userRepository->triggerPasswordReset(e($request->get('email')));
// It worked! Use config to determine where we should go.
return $this->redirectViaResponse('registration_reset_triggered', $result);
}
/**
* A user is attempting to reset their password
*
* #param $id
* #param $code
*
* #return Redirect|View
*/
public function passwordResetForm($hash, $code)
{
// Decode the hashid
$id = $this->hashids->decode($hash)[0];
// Validate Reset Code
$result = $this->userRepository->validateResetCode($id, $code);
if (! $result->isSuccessful()) {
return $this->redirectViaResponse('registration_reset_invalid', $result);
}
return $this->viewFinder('Sentinel::users.reset', [
'hash' => $hash,
'code' => $code
]);
}
/**
* Process a password reset form submission
*
* #param $hash
* #param $code
* #return Response
*/
public function resetPassword(ResetPasswordRequest $request, $hash, $code)
{
// Decode the hashid
$id = $this->hashids->decode($hash)[0];
// Gather input data
$data = $request->only('password', 'password_confirmation');
// Change the user's password
$result = $this->userRepository->resetPassword($id, $code, e($data['password']));
// It worked! Use config to determine where we should go.
return $this->redirectViaResponse('registration_reset_complete', $result);
}
}
It seems that when you click and a your link "Register" your redirection fail, so check if you have multiple "Register" links/buttons, and if they are pointing to the right URL
And for easiest debugging, you should make less assertions per Test, you will gain in visibility :)
Is there a way to access the context of a whole form inside a validator of a fieldset-element? It seems the standard behaviour is that the context contains just the form-data of the fieldset where the element resides.
This is my custom validator:
/**
* Returns if the given value is valid
*
* #param string $value
* #param array $context
* #return boolean
*/
public function isValid($value, array $context = array())
{
$this->setValue($value);
$bookingId = isset($context['auftrag_buchung_id'])
? (int) $context['auftrag_buchung_id']
: null;
try {
$anlieferung = new \DateTime($value);
} catch (\Exception $e) {
$this->error(self::NOT_DATETIME);
return false;
}
try {
$booking = $this->table->getById($this->user, $bookingId);
} catch (\Exception $e) {
$this->error(self::NOT_FOUND);
return false;
}
if (!$this->isInBookingRange($value, $booking)) {
$this->error(self::NOT_IN_BOOKINGRANGE);
return false;
}
return true;
}
My problem is $context has just the form-data of the fieldset where i configured this validator. But I have to check against a value that is not inside the fieldset
It should be possible to inject the form instance into the validator when assigning the validator to the form using an InputFilter.
//
$form = new \Zend\Form\Form();
/* ..following could be within __construct() Method of the Form object */
//
$element = new \Zend\Form\Element\Text('text');
$form->add($element);
//
$inputFilter = new \Zend\InputFilter\InputFilter();
//
$textInput = new \Zend\InputFilter\Input('text');
// Add validator with injected form instance
$textInput->getValidatorChain()
->attach(new CustomValidator($form));
$inputFilter->add($textInput)
//
$form->setInputFilter($inputFilter);
With thi ssettings you should be able to use the form data within your validation class:
class CustomValidator {
private $form;
public function __construct($form) {
$this->form = $form;
}
public function isValid($value) {
// Access form data
$this->form->getData();
}
}