I need to valid my form. My form has two collection but I can not to valid them...
Do you know how I can make that ?
CardEntryType :
namespace Dim\RestaurantBundle\Form\Type;
class CardEntryType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('cardEntryContent', 'collection', array(
'type' => 'text',
'prototype' => true,
'allow_add' => true,
'allow_delete' => true,
'by_reference' => false,
'options' => array(
'required' => false,
'attr' => array(
'class' => 'text',
'placeholder' => 'Nom de l\'entrée...',
'pattern' => '.{0,55}'),
),
))
->add('cardEntryPrice', 'collection', array(
'type' => 'text',
'allow_add' => true,
'prototype' => true,
'options' => array(
'required' => false,
'attr' => array(
'class' => 'text',
'placeholder' => 'Prix de l\'entrée...',
'pattern' => '.{0,10}'),
),
));
}
public function getDefaultOptions(array $options)
{
return array(
'data_class' => 'Dim\RestaurantBundle\Entity\TCardEntry',
);
}
public function getName()
{
return 'cardEntry';
}
}
The model of the entity:
namespace Dim\RestaurantBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use Doctrine\Common\Collections\ArrayCollection;
/**
* TCardEntry
*
* #ORM\Table(name="t_card_entry")
* #ORM\Entity
*/
class TCardEntry
{
/**
* #var integer
*
* #ORM\Column(name="card_entry_id", type="integer", nullable=false)
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $cardEntryId;
/**
* #var string
*
* #Assert\Length(
* min = "0",
* max = "55",
* minMessage = "Votre nom ne peut faire moins de {{ limit }} caractères.",
* maxMessage = "Votre nom ne peut faire plus de {{ limit }} caractères."
* )
*
* #ORM\Column(name="card_entry_content", type="text", nullable=false)
*/
private $cardEntryContent;
/**
* #var string
*
* #Assert\Length(
* min = "0",
* max = "10",
* minMessage = "Votre nom ne peut faire moins de {{ limit }} caractères.",
* maxMessage = "Votre nom ne peut faire plus de {{ limit }} caractères."
* )
*
* #ORM\Column(name="card_entry_price", type="string", length=10, nullable=false)
*/
private $cardEntryPrice;
/**
* Get cardEntryId
*
* #return integer
*/
public function getCardEntryId()
{
return $this->cardEntryId;
}
/**
* Set cardEntryContent
*
* #param string $cardEntryContent
* #return TCardEntry
*/
public function setCardEntryContent($cardEntryContent)
{
$this->cardEntryContent = $cardEntryContent;
return $this;
}
/**
* Get cardEntryContent
*
* #return string
*/
public function getCardEntryContent()
{
return $this->cardEntryContent;
}
/**
* Set cardEntryPrice
*
* #param string $cardEntryPrice
* #return TCardEntry
*/
public function setCardEntryPrice($cardEntryPrice)
{
$this->cardEntryPrice = $cardEntryPrice;
return $this;
}
/**
* Get cardEntryPrice
*
* #return string
*/
public function getCardEntryPrice()
{
return $this->cardEntryPrice;
}
}
My controller :
namespace Dim\RestaurantBundle\Controller;
class AdministrationController extends Controller
{
public function indexAction()
{
return $this->render('DimRestaurantBundle:Administration/Home:index.html.twig');
}
public function cardEntryAction(Request $request)
{
$TCardEntry = new TCardEntry();
$form = $this->createForm(new CardEntryType(), $TCardEntry);
if($request->isMethod('POST'))
{
$form->bind($request);
if($form->isValid())
{
die('form valid');
}
}
return $this->render('DimRestaurantBundle:Administration/CardEntry:index.html.twig', array('form' => $form->createView()));
}
}
When I submit my form I always have the same error :
Expected argument of type "string", "array" given
I'm very confused... Have you an idea ??
Thanks a lot of !
The bug is in reallity a bug from Symfony 2.5.
bug #11117 [Validator] Fix array notation in the
PropertyPath::append() (jakzal)
Changelog : http://symfony.com/blog/symfony-2-5-1-released
To fix the issue, I have updated Symfony 2.5 to Symfony 2.5.1.
Related
I tried to make Laravel-Vue-Sidebar-Filters and it works for categories,brands and prices but how to do it with attributes , attributevalues and productAttributes and thank you very much
I tried this code but nothing show in the page(for attributeValues)so please how to do it with the right way thank you very much:
public function prodat()
{
$sizes = AttributeValue::whereHas('attribute', function ($query) {
$query->where('code', 'size')->where('is_filterable', 1);
})->get();
return response()->json($sizes);
}
front.vue:
<h3 class="mt-2">Sizes </h3>
<div class="form-check" v-for="(size, index) in sizes">
<input class="form-check-input" type="checkbox" :value="size.id" :id="'size'+index" v-model="selected.sizes">
<label class="form-check-label" :for="'size' + index">
{{ size.value }}
</label>
</div>
I followed https://github.com/LaravelDaily/Laravel-Vue-Sidebar-Filters/commit/0dbffb076c9c16cace8a1b9cddef268e734af808
and how to make it for product attributes if I have this:
product.php:
protected $fillable = [
'brand_id', 'sku', 'name', 'slug', 'description', 'quantity',
'weight', 'price', 'sale_price', 'status', 'featured',
];
/**
* #var array
*/
protected $casts = [
'quantity' => 'integer',
'brand_id' => 'integer',
'status' => 'boolean',
'featured' => 'boolean'
];
/**
* #param $value
*/
public function setNameAttribute($value)
{
$this->attributes['name'] = $value;
$this->attributes['slug'] = Str::slug($value);
}
/**
* #return \Illuminate\Database\Eloquent\Relations\HasMany
*/
public function attributes()
{
return $this->hasMany(ProductAttribute::class);
}
attribute.php:
protected $fillable = [
'code', 'name', 'frontend_type', 'is_filterable', 'is_required'
];
/**
* #var array
*/
protected $casts = [
'is_filterable' => 'boolean',
'is_required' => 'boolean',
];
/**
* #return \Illuminate\Database\Eloquent\Relations\HasMany
*/
public function values()
{
return $this->hasMany(AttributeValue::class);
}
attributeValue.php:
protected $fillable = [
'attribute_id', 'value', 'price'
];
/**
* #var array
*/
protected $casts = [
'attribute_id' => 'integer',
];
/**
* #return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function attribute()
{
return $this->belongsTo(Attribute::class);
}
/**
* #return \Illuminate\Database\Eloquent\Relations\BelongsToMany
*/
public function productAttributes()
{
return $this->belongsToMany(ProductAttribute::class);
}
productAttribute.php:
protected $fillable = ['attribute_id', 'product_id', 'value', 'quantity', 'price'];
/**
* #return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function product()
{
return $this->belongsTo(Product::class);
}
/**
* #return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function attribute()
{
return $this->belongsTo(Attribute::class);
}
I am using Laravel 6 on a project (included with this chat system / project).
First time so searching for some things.
Using the debugging fucntion of xdebug w/ PHPStorm I can follow it perfectly.
This is what I see:
RegisterController:
protected function validator(array $data)
{
$data['name'] = htmlspecialchars($data['name']);
return Validator::make($data, [
'name' => ['required', 'string', 'max:100'],
'email' => ['required', 'string', 'email', 'max:255', 'unique:users', 'regex:/^[\w\-\.\+]+\#[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,4}$/'],
'password' => ['required', 'string', 'min:3', 'max:30', 'confirmed', new NoSpaceContaine()],
'min18years' => ['accepted'],
'accept_all_agreements' => ['accepted'],
'medical1' => ['accepted'],
'medical2' => ['accepted']
], [
'name.required' => 'A name is required',
'email.required' => 'An email is required',
'password.required' => 'A password is required',
'min18years.accepted' => 'An approval for min 18 years is required',
'accept_all_agreements.accepted' => 'An approval for agreements is required',
'medical1.accepted' => 'An approval for medical1 is required',
'medical2.accepted' => 'An approval for medical2 is required'
]);
}
$Data (from debugger, On purpose not selected the min18years checkbox):
$data = {array} [9]
_token = "oEMQFjasGoex4MDiThonh8Vw0e5UbyQ5o7GTRAi8"
name = "Peter7"
email = "my7#email.here"
password = "123"
password_confirmation = "123"
min18years = "0"
accept_all_agreements = "yes"
medical1 = "yes"
medical2 = "yes"
Illuminate\Validation\Validator.php:"
public function validate()
{
if ($this->fails()) {
throw new ValidationException($this);
}
return $this->validated();
}
Error get's thrown, the current data when calling "ValidationException":
$this:
$this = {Illuminate\Validation\Validator} [27]
translator = {Illuminate\Translation\Translator} [7]
container = {Illuminate\Foundation\Application} [33]
presenceVerifier = {Illuminate\Validation\DatabasePresenceVerifier} [2]
failedRules = {array} [1]
min18years = {array} [1]
Accepted = {array} [0]
excludeAttributes = {array} [0]
messages = {Illuminate\Support\MessageBag} [2]
messages = {array} [1]
min18years = {array} [1]
0 = "An approval for min 18 years is required"
format = ":message"
data = {array} [9]
_token = "oEMQFjasGoex4MDiThonh8Vw0e5UbyQ5o7GTRAi8"
name = "Peter7"
email = "my7#email.here"
password = "123"
password_confirmation = "123"
min18years = "0"
accept_all_agreements = "yes"
medical1 = "yes"
medical2 = "yes"
initialRules = {array} [7]
rules = {array} [7]
currentRule = "accepted"
implicitAttributes = {array} [0]
implicitAttributesFormatter = null
distinctValues = {array} [0]
after = {array} [0]
customMessages = {array} [7]
name.required = "A name is required"
email.required = "An email is required"
password.required = "A password is required"
min18years.accepted = "An approval for min 18 years is required"
accept_all_agreements.accepted = "An approval for agreements is required"
medical1.accepted = "An approval for medical1 is required"
medical2.accepted = "An approval for medical2 is required"
But when I follow the call to \Illuminate\Validation\ValidationException.php:
public function __construct($validator, $response = null, $errorBag = 'default')
{
parent::__construct('The given data was invalid.');
$this->response = $response;
$this->errorBag = $errorBag;
$this->validator = $validator;
}
and the $this didn't receive the messages that was passed along to this function.
$this:
$this = {Illuminate\Validation\ValidationException} [12]
validator = null
response = null
status = {int} 422
errorBag = null
redirectTo = null
message = ""
*Exception*string = ""
code = {int} 0
file = "C:\Sources\wachtweken.nl\vendor\laravel\framework\src\Illuminate\Validation\Validator.php"
line = {int} 386
*Exception*trace = {array} [44]
*Exception*previous = null
I hope this is clear when I go throgh te debug steps...
Added validator function as requested (but it's the default :
protected function validator(array $data)
{
$data['name'] = htmlspecialchars($data['name']);
return Validator::make($data, [
'name' => ['required', 'string', 'max:100'],
'email' => ['required', 'string', 'email', 'max:255', 'unique:users', 'regex:/^[\w\-\.\+]+\#[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,4}$/'],
'password' => ['required', 'string', 'min:3', 'max:30', 'confirmed', new NoSpaceContaine()],
'min18years' => ['accepted'],
'accept_all_agreements' => ['accepted'],
'medical1' => ['accepted'],
'medical2' => ['accepted']
], [
'name.required' => 'A name is required',
'email.required' => 'An email is required',
'password.required' => 'A password is required',
'min18years.accepted' => 'An approval for min 18 years is required',
'accept_all_agreements.accepted' => 'An approval for agreements is required',
'medical1.accepted' => 'An approval for medical1 is required',
'medical2.accepted' => 'An approval for medical2 is required'
]);
}
Full code from controller deeper down:
Post function of the forum goes here:
RegisterController.php:register
/**
* #param Request $request
*
* #return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
*/
public function register(Request $request)
{
try {
$this->validator($request->all())->validate();
event(new Registered($user = $this->create($request->all())));
$this->guard()->login($user);
return $this->registered($request, $user)
?: redirect($this->redirectPath());
} catch (Exception $e) {
return Redirect::back()->withInput()->withErrors(['error' => $e->getMessage()]);
}
}
Illuminate\Validation\Factory
class Validator {
/**
* Create a new Validator instance.
*
* #param array $data
* #param array $rules
* #param array $messages
* #param array $customAttributes
* #return \Illuminate\Validation\Validator
* #static
*/
public static function make($data, $rules, $messages = [], $customAttributes = [])
{
/** #var \Illuminate\Validation\Factory $instance */
return $instance->make($data, $rules, $messages, $customAttributes);
}
/**
* Validate the given data against the provided rules.
*
* #param array $data
* #param array $rules
* #param array $messages
* #param array $customAttributes
* #return array
* #throws \Illuminate\Validation\ValidationException
* #static
*/
public static function validate($data, $rules, $messages = [], $customAttributes = [])
{
/** #var \Illuminate\Validation\Factory $instance */
return $instance->validate($data, $rules, $messages, $customAttributes);
}
/**
* Register a custom validator extension.
*
* #param string $rule
* #param \Closure|string $extension
* #param string|null $message
* #return void
* #static
*/
There the exception is trigger and it goes to the
Illuminate\Validation\ValidationException:
<?php
namespace Illuminate\Validation;
use Exception;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Validator as ValidatorFacade;
class ValidationException extends Exception
{
/**
* The validator instance.
*
* #var \Illuminate\Contracts\Validation\Validator
*/
public $validator;
/**
* The recommended response to send to the client.
*
* #var \Symfony\Component\HttpFoundation\Response|null
*/
public $response;
/**
* The status code to use for the response.
*
* #var int
*/
public $status = 422;
/**
* The name of the error bag.
*
* #var string
*/
public $errorBag;
/**
* The path the client should be redirected to.
*
* #var string
*/
public $redirectTo;
/**
* Create a new exception instance.
*
* #param \Illuminate\Contracts\Validation\Validator $validator
* #param \Symfony\Component\HttpFoundation\Response|null $response
* #param string $errorBag
* #return void
*/
public function __construct($validator, $response = null, $errorBag = 'default')
{
parent::__construct('The given data was invalid.');
$this->response = $response;
$this->errorBag = $errorBag;
$this->validator = $validator;
}
/**
* Create a new validation exception from a plain array of messages.
*
* #param array $messages
* #return static
*/
public static function withMessages(array $messages)
{
return new static(tap(ValidatorFacade::make([], []), function ($validator) use ($messages) {
foreach ($messages as $key => $value) {
foreach (Arr::wrap($value) as $message) {
$validator->errors()->add($key, $message);
}
}
}));
}
/**
* Get all of the validation error messages.
*
* #return array
*/
public function errors()
{
return $this->validator->errors()->messages();
}
/**
* Set the HTTP status code to be used for the response.
*
* #param int $status
* #return $this
*/
public function status($status)
{
$this->status = $status;
return $this;
}
/**
* Set the error bag on the exception.
*
* #param string $errorBag
* #return $this
*/
public function errorBag($errorBag)
{
$this->errorBag = $errorBag;
return $this;
}
/**
* Set the URL to redirect to on a validation error.
*
* #param string $url
* #return $this
*/
public function redirectTo($url)
{
$this->redirectTo = $url;
return $this;
}
/**
* Get the underlying response instance.
*
* #return \Symfony\Component\HttpFoundation\Response|null
*/
public function getResponse()
{
return $this->response;
}
}
Your problem is the try/catch. You don't have to use it, if it throws an error, it will by default return back to the page where it came from (response()->back()) with input (->withInput()) and with the validation errors (errors will be populated for you to use in blade).
So, change your code to:
public function register(Request $request)
{
$this->validator($request->all())->validate();
event(new Registered($user = $this->create($request->all())));
$this->guard()->login($user);
return $this->registered($request, $user)
?: redirect($this->redirectPath());
}
Read this part of the documentation again, so you can see that this will work.
I want create a customer image attribute,so customer and admin can upload, update and delete profile image like avatar. I know how is this possible in magento 1,but not in magento 2
.If anyone have any idea please share. Thanks in advance.
create below module files. It worked on magento 2.1.4
Create : app\code\Sashas\CustomerAttribute\etc\module.xml
<?xml version="1.0" encoding="UTF-8"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../lib/internal/Magento/Framework/Module/etc/module.xsd">
<module name="Sashas_CustomerAttribute" setup_version="1.0.0">
<sequence>
<module name="Magento_Customer"/>
</sequence>
</module>
</config>
Create: app\code\Sashas\CustomerAttribute\Setup\InstallData.php
<?php
/**
* #author Sashas
* #category Sashas
* #package Sashas_CustomerAttribute
* #copyright Copyright (c) 2015 Sashas IT Support Inc. (http://www.extensions.sashas.org)
*/
namespace Sashas\CustomerAttribute\Setup;
use Magento\Customer\Setup\CustomerSetupFactory;
use Magento\Customer\Model\Customer;
use Magento\Eav\Model\Entity\Attribute\Set as AttributeSet;
use Magento\Eav\Model\Entity\Attribute\SetFactory as AttributeSetFactory;
use Magento\Framework\Setup\InstallDataInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;
/**
* #codeCoverageIgnore
*/
class InstallData implements InstallDataInterface
{
/**
* #var CustomerSetupFactory
*/
protected $customerSetupFactory;
/**
* #var AttributeSetFactory
*/
private $attributeSetFactory;
/**
* #param CustomerSetupFactory $customerSetupFactory
* #param AttributeSetFactory $attributeSetFactory
*/
public function __construct(
CustomerSetupFactory $customerSetupFactory,
AttributeSetFactory $attributeSetFactory
) {
$this->customerSetupFactory = $customerSetupFactory;
$this->attributeSetFactory = $attributeSetFactory;
}
/**
* {#inheritdoc}
*/
public function install(ModuleDataSetupInterface $setup, ModuleContextInterface $context)
{
/** #var CustomerSetup $customerSetup */
$customerSetup = $this->customerSetupFactory->create(['setup' => $setup]);
$customerEntity = $customerSetup->getEavConfig()->getEntityType('customer');
$attributeSetId = $customerEntity->getDefaultAttributeSetId();
/** #var $attributeSet AttributeSet */
$attributeSet = $this->attributeSetFactory->create();
$attributeGroupId = $attributeSet->getDefaultGroupId($attributeSetId);
$customerSetup->addAttribute(Customer::ENTITY, 'magento_username', [
'type' => 'varchar',
'label' => 'Magento Username',
'input' => 'image',
'required' => false,
'visible' => true,
'user_defined' => true,
'sort_order' => 1000,
'position' => 1000,
'system' => 0,
]);
$attribute = $customerSetup->getEavConfig()->getAttribute(Customer::ENTITY, 'magento_username')
->addData([
'attribute_set_id' => $attributeSetId,
'attribute_group_id' => $attributeGroupId,
'used_in_forms' => ['adminhtml_customer'],
]);
$attribute->save();
}
}
Create : app\code\Sashas\CustomerAttribute\registration.php
<?php
\Magento\Framework\Component\ComponentRegistrar::register(
\Magento\Framework\Component\ComponentRegistrar::MODULE,
'Sashas_customerAttribute',
__DIR__
);
?>
I am trying to add the custom attribute to registration form. And i have added the attribute successfully by the following code
class InstallData implements InstallDataInterface
{
/**
* #var EavSetupFactory Magento\Eav\Setup\EavSetupFactory
*/
private $eavSetupFactory;
/**
* #var $_eavConfig Config
*/
protected $eavConfig;
public function __construct(EavSetupFactory $eavSetupFactory, Config $eavConfig)
{
$this->eavSetupFactory = $eavSetupFactory;
$this->eavConfig = $eavConfig;
}
public function install(ModuleDataSetupInterface $setup, ModuleContextInterface $context)
{
$eavSetup = $this->eavSetupFactory->create(['setup' => $setup]);
$eavSetup->addAttribute(
\Magento\Customer\Model\Customer::ENTITY,
'mobile',
[
'type' => 'varchar',
'label' => 'Mobile',
'input' => 'text',
'required' => false,
'system' => false,
'position' => 100,
'visible' => true,
'user_defined' => true
]
);
$mobile = $this->eavConfig->getAttribute(\Magento\Customer\Model\Customer::ENTITY, 'mobile');
//$forms = ['adminhtml_customer', 'checkout_register', 'customer_account_create', 'customer_account_edit'];
$forms = ['adminhtml_customer'];
$mobile->setData(
'used_in_forms',
$forms
);
$mobile->save();
}
}
And to show at front-end i am using the layout handler customer_account_create with the following code
<referenceContainer name="form.additional.info">
<block class="Namespace\SMS\Block\Active" name="sms_block">
<action method="setTemplate" ifconfig="sms/actions/register" ifvalue="1">
<argument name="template" xsi:type="string">Namespace_SMS::sms/register.phtml</argument>
</action>
</block>
</referenceContainer>
Now it is showing the mobile field during registration. But when i try to create account mobile field value is empty after create account.
Note: I know if i add the 'customer_account_create', 'customer_account_edit' with used_in_form then mobile value save. But after this i can not use a specific template file to render mobile field.
Can you please let me know how can i solve this issue? Thank you very much.
I do not know whether it is 100% correct according to the coding rules. But I have resolved this issue using the observer and little bit changes in InstallData script.
InstallData.php is like this
class InstallData implements InstallDataInterface
{
/**
* Customer setup factory
*
* #var \Magento\Customer\Setup\CustomerSetupFactory
*/
private $customerSetupFactory;
/**
* Init
*
* #param \Magento\Customer\Setup\CustomerSetupFactory $customerSetupFactory
*/
public function __construct(\Magento\Customer\Setup\CustomerSetupFactory $customerSetupFactory) {
$this->customerSetupFactory = $customerSetupFactory;
}
public function install(ModuleDataSetupInterface $setup, ModuleContextInterface $context)
{
$setup->startSetup();
/** #var CustomerSetup $customerSetup */
$customerSetup = $this->customerSetupFactory->create(['setup' => $setup]);
$customerSetup->addAttribute(
\Magento\Customer\Model\Customer::ENTITY,
'mobile',
[
'type' => 'varchar',
'label' => 'Mobile',
'input' => 'text',
'required' => false,
'system' => false,
'position' => 100,
'visible' => true,
'user_defined' => true
]
);
$customerSetup->updateAttribute('customer', 'mobile', 'is_used_for_customer_segment', '1');
//$forms = ['adminhtml_customer', 'checkout_register', 'customer_account_create', 'customer_account_edit'];
$forms = ['adminhtml_customer'];
$attribute = $customerSetup->getEavConfig()->getAttribute('customer', 'mobile');
$attribute->setData('used_in_forms', ['adminhtml_customer']);
$attribute->addData([
'attribute_set_id' => 1,
'attribute_group_id' => 1
]);
$attribute->save();
$setup->endSetup();
}
}
then events.xml is like this
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
<event name="customer_register_success">
<observer name="sMSHandleCustomerSaveAfter" instance="\Namepace\SMS\Observer\CustomerRegisterObserver" />
</event>
</config>
And the observer is like this
class CustomerRegisterObserver implements ObserverInterface
{
/**
* #var \Magento\Customer\Model\CustomerFactory
*/
protected $_customerFactory;
function __construct(CustomerFactory $customerFactory)
{
$this->_customerFactory = $customerFactory;
}
public function execute(Observer $observer)
{
$customerData = $observer->getCustomer();
if($_POST['mobile']) {
$customer = $this->_customerFactory->create()->load($customerData->getId());
$customer->setData('mobile', $_POST['mobile']);
$customer->save();
}
}
}
IF someone is looking for the solution, nearly to the #Abbas answer, but modified in observer part:
<?php
namespace {Vendor}\Module\Observer;
use Magento\Framework\Event\Observer as EventObserver;
use Magento\Framework\Event\ObserverInterface;
class CustomerRegisterObserver implements ObserverInterface
{
/**
* #var \Magento\Customer\Model\CustomerFactory
*/
protected $_customerFactory;
protected $_customerRepository;
function __construct(
\Magento\Customer\Model\CustomerFactory $customerFactory,
\Psr\Log\LoggerInterface $logger
) {
$this->_customerFactory = $customerFactory;
$this->_logger = $logger;
}
public function execute(EventObserver $observer)
{
//$this->_logger->info("Observer CustomerRegisterObserver Loaded !");
$event = $observer->getEvent();
$customerData = $event->getCustomer();
if($_POST['mobile']) {
$customer = $this->_customerFactory->create()->load($customerData->getId());
$customer->setData('mobile', $_POST['mobile']);
$customer->save();
}
}
}
I'm using Larave 4.2, and everything works just fine. If I enter the correct credentials I will be taken to the correct URL (the one with auth filter). But the problem I'm currently experiencing is when one of the fields entered is incorrect and the user submits it will show a white screen.
I'm expecting of course that the user will be redirected back to login page with Input and display the error.
I've checked the filters, and quite sure it is still what came with Laravel and didn't change anything.
My routes
<?php
Route::get('login', function()
{
// just a shortcut to redirec to /login into /cms/login : prevents redirect LOOP
return Redirect::route('cms.login');
});
Route::group(array('prefix' => 'cms'), function()
{
Route::get('/', function()
{
if (Auth::guest())
{
return Redirect::route('cms.login');
}
else
{
return Redirect::route('cms.home');
}
});
Route::get('login', array(
'as' => 'cms.login',
'uses' => 'CMSController#login'
));
Route::post('login', array(
'as' => 'cms.postLogin',
'uses' => 'CMSController#userLogin'
));
Route::get('logout', array(
'as' => 'cms.logout',
'uses' => 'CMSController#userLogout'
));
Route::group(array('before' => 'auth'), function()
{
Route::get('home', array(
'as' => 'cms.home',
'uses' => 'CMSController#home'
));
Route::get('my-account', array(
'as' => 'cms.myaccount',
'uses' => 'AccountsController#myAccount'
));
Route::get('my-account/edit', array(
'as' => 'cms.edit-myaccount',
'uses' => 'AccountsController#editMyAccount'
));
Route::resource('accounts', 'AccountsController');
Route::resource('products', 'ProductsController');
Route::resource('news', 'NewsController');
Route::resource('settings', 'SettingsController');
Route::resource('homepage-sliders', 'HomepageSlidersController');
Route::resource('testimonials', 'TestimonialsController');
Route::resource('effects', 'EffectsController');
});
});
User model
<?php
use Illuminate\Auth\UserTrait;
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableTrait;
use Illuminate\Auth\Reminders\RemindableInterface;
class User extends Eloquent implements UserInterface, RemindableInterface {
use UserTrait, RemindableTrait;
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'users';
/**
* Fillable array
*
*/
protected $fillable = array('email', 'password', 'username', 'position', 'mobile');
/**
* The attributes excluded from the model's JSON form.
*
* #var array
*/
protected $hidden = array('password', 'remember_token');
/**
* Sets the Validation Rules when Logging In
*
* #var array
*/
public static $loginRules = array(
'email' => 'required|email',
'password' => 'required|alpha_dash|min:6'
);
/**
* Sets the Validation Rules creating a User
*
* #var array
*/
public static $rules = array(
'email' => 'required|email|unique:users',
'username' => 'required|min:2|unique:users',
'position' => 'required|',
'mobile-number' => 'required|numeric|digits:11',
'password' => 'required|alpha_dash|min:6|confirmed',
'password_confirmation' => 'required|alpha_dash|min:6'
);
/**
* Sets the Validation Rules updating a User
*
* #var array
*/
public static $updateRules = array(
'username' => 'required|min:2',
'password' => 'required|alpha_dash|min:6|confirmed',
'password_confirmation' => 'required|alpha_dash|min:6'
);
/**
* Defines many-to-many relationship with Module
*
*/
public function permissions()
{
return $this->belongsToMany('Module', 'permissions')->withPivot('add','edit', 'view','delete');
}
/**
* Get the unique identifier for the user.
*
* #return mixed
*/
public function getAuthIdentifier()
{
return $this->getKey();
}
/**
* Get the password for the user.
*
* #return string
*/
public function getAuthPassword()
{
return $this->password;
}
/**
* Get the e-mail address where password reminders are sent.
*
* #return string
*/
public function getReminderEmail()
{
return $this->email;
}
/**
* Gets the Remember Token
*
* #return string $this->remember_token
*/
public function getRememberToken()
{
return $this->remember_token;
}
/**
* Set the Remember Token
*
* #param string $value
*/
public function setRememberToken($value)
{
$this->remember_token = $value;
}
/**
* Get the Remember Token name
*
* #return string 'remember_token'
*/
public function getRememberTokenName()
{
return 'remember_token';
}
/**
* Get the password and Hash it before saving to the database.
*
* #param string $value
*/
public function setPasswordAttribute($value)
{
$this->attributes['password'] = Hash::make($value);
}
/**
* Checks if Guest User input invalid credentials
*
* #param array $credentials
* #return object $validation
*/
public static function loginIsInvalid($credentials)
{
$validation = Validator::make($credentials, self::$loginRules);
if ($validation->fails())
{
return $validation;
}
}
My CMSController
<?php
class CMSController extends BaseController {
/**
* Display the login page.
* GET /cms
*
* #return Response
*/
public function login()
{
return View::make('cms.login');
}
/**
* Accepts the post request for login
* of user in CMS
*
*/
public function userLogin()
{
$user_credentials['email'] = Input::get('email');
$user_credentials['password'] = Input::get('password');
//sets the remember_me variable
if (Input::has('remember'))
{
$remember_me = true;
}
else
{
$remember_me = false;
}
if ($errors = User::loginIsInvalid($user_credentials))
{
return Redirect::route('cms.login')->withInput()->withErrors($errors);
}
if (Auth::attempt(array(
'email' => $user_credentials['email'],
'password' => $user_credentials['password']), $remember_me))
{
return Redirect::route('cms.home');
}
}
/**
* Accepts the post request for logout
* of user in CMS
*
*/
public function userLogout()
{
Session::clear();
Auth::logout();
return Redirect::route('cms.login');
}
/**
* Directs user to home page
*
*/
public function home()
{
return View::make('cms.home');
}
}
Currently in your code there is nothing after Auth::attempt() - so if the Auth fails - it has no where to go.
Just add a return after the Auth::attempt() to make it work
if (Auth::attempt(array(
'email' => $user_credentials['email'],
'password' => $user_credentials['password']), $remember_me))
{
return Redirect::route('cms.home');
}
return Redirect::route('cms.login')->withInput()->withErrors($errors);