Laravel Auth::atempt keeps failing - oauth

I am using this code to authenticate user with Facebook and laravel-oauth2 package. But my Auth::atempt keeps failing.(Ecos FLAG) Can someone help me see the problem ? Here is my controller function and code for my route:
Route::get('oauth/{provider}', 'HomeController#provide');
public function provide($provider)
{
$init_p = $provider;
$provider = OAuth2::provider($provider, array(
'id' => 'MY ID',
'secret' => 'MY SECRET',
));
if ( ! isset($_GET['code']))
{
return $provider->authorize();
}
else
{
try
{
$params = $provider->access($_GET['code']);
$token = new Token_Access(array(
'access_token' => $params->access_token
));
$provided_user = $provider->get_user_info($token);
if($init_p == 'facebook')
{
if (User::whereFacebookUid($provided_user['uid'])->first())
{
if(Auth::check())
{
return Redirect::to('/testovi');
}
else
{
if (Auth::attempt(array('password' => $provided_user['uid'])))
{
return Redirect::to('/testovi');
}
else
{
echo("FLAG");
}
}
}
else
{
$user = new User;
$user->name = $provided_user['name'];
$user->email = $provided_user['email'];
$user->password = $provided_user['uid'];
$user->facebook_uid = $provided_user['uid'];
$user->save();
Auth::login($user);
return Redirect::to('testovi');
}
}
}
catch (OAuth2_Exception $e)
{
show_error('That didnt work: '.$e);
}
}
}

Solution was to HASH uid befor saving id to db. Details from:
Details
$user = new User;
$user->username = $provided_user['name'];
$user->email = $provided_user['email'];
$user->password = Hash::make($provided_user['uid']);
$user->facebook_uid = $provided_user['uid'];
$user->save();
Auth::login($user);
return Redirect::to('testovi');

Related

EntityManager persist expects parameter 1 to be an entity object, NULL given zend doctrine

I have this addaction controller and i'm getting this exception error though user are getting added.
public function addAction() {
$requestObj = $this->getRequest();
$viewModelObj = new ViewModel();
$errorMsg = array();
$userObj = new Entity\User();
try {
$userRepo = $this->getDoctrineRepository('User');
if ($this->getRequest()->getQuery('id')) {
$userObj = $userRepo->findOneBy(array('id'=>$this->getRequest()->getQuery('id')));
}
if ($requestObj->isPost()) {
$postData = $requestObj->getPost()->getArrayCopy();
$currentUser = $this->getFromSession('user');
$error = false;
if (trim($requestObj->getPost('firstName')) == "") {
$errorMsg[] = "First name is required";
$error = true;
}
if ($this->getRequest()->getQuery('id')) {
if($userObj->getCellPhone() != $postData['cellPhone']) {
if($userRepo->findOneBy(array('cellPhone'=> $postData['cellPhone']))) {
$errorMsg[] = "Cell Phone is already exists.";
$error = true;
}
}
} else {
$existUserByEmailObj = $userRepo->findOneBy(array('email'=> $postData['email']));
$existUserByCellObj = $userRepo->findOneBy(array('cellPhone'=> $postData['cellPhone']));
if($existUserByEmailObj){
$errorMsg[] = "Email is already exists.";
$error = true;
}
if($existUserByCellObj){
$errorMsg[] = "Cell Phone is already exists.";
$error = true;
}
}
if ($userObj->getId() && trim($requestObj->getPost('password')) == "") {
$postData['password'] = $userObj->getPassword();
} else if (trim($requestObj->getPost('password')) == "") {
// user add
$errorMsg[] = "Password is required";
$error = true;
}
// in edit if password is empty then insert previous password
// populate object with form data
$hydratorObj = new Hydrator\ClassMethods();
$hydratorObj->hydrate($postData, $userObj);
if($error == false) {
$userObj->setUpdatedBy($currentUser->getId());
$eMObj = $this->getDoctrineEntityManager();
if ($userObj->getId()) {
//$userObj->setIsVerified(2);
$eMObj->merge($userObj);
} else {
$userObj->setCreatedDate(new \DateTime("now"));
$userObj->setCreatedBy($currentUser->getId());
//$userObj->setIsVerified(2);
$eMObj->persist($userObj);
}
$eMObj->flush();
// Set User Sms Number
$userSmsNumberRepo = $this->getDoctrineRepository('UserSmsNumber');
$userSmsNumberObj = $userSmsNumberRepo->findOneBy(array('user'=> $userObj->getId()));
if(!$userSmsNumberObj) {
$smsNumberRepo = $this->getDoctrineRepository('SmsNumber');
$smsNumberObj = $smsNumberRepo->findSmsNumber();
if ($smsNumberObj) {
$userSmsNumberObj = new Entity\UserSmsNumber();
$userSmsNumberObj->setUser($userObj);
$userSmsNumberObj->setSmsNumber($smsNumberObj);
$smsNumberObj->setNoOfAssignee((int)$smsNumberObj->getNoOfAssignee() + 1);
}
$eMObj->persist($userSmsNumberObj);
$eMObj->merge($smsNumberObj);
$eMObj->flush();
// Send Email Alert to Admin if last one SmsNumber is exists.
$lastSmsNumber = $smsNumberRepo->lastOneSmsNumber();
if($lastSmsNumber == 0 || $lastSmsNumber == 1) {
$settingObj = $this->getDoctrineRepository('Setting');
$adminEmail = $settingObj->findValueByFieldName('ADMIN_EMAIL');
$sendArr = array($adminEmail => 'Fence-alert');
$placeholderArr = array('NAME' => 'Admin', 'SMSNUMBER' => $smsNumberObj->getSmsNumber(), 'NOOFASSIGNEE' => (int)$smsNumberObj->getNoOfAssignee());
$sendMailObj = new SendEmail($this->serviceLocator);
$sendMailObj->send($sendArr, 'SMSNUMBER_ALERT', $placeholderArr, $toAdmin = TRUE);
}
}
$this->flashMessenger()->addMessage('User Saved Successfully!');
$this->redirect()->toUrl(BASE_URL.'/admin/user');
}
}
$form = new UserForm($this->getServiceLocator(), 'formUser');
$form->bind($userObj);
$form->get('password')->setAttribute('type', 'text');
$form->get('password')->setValue($userObj->getPassword());
$viewModelObj->setVariables(array(
'errorMsg' => $errorMsg,
'form' => $form,
'userObj' => $userObj
));
return $viewModelObj;
} catch(\Exception $e) {
print_r($e);
$this->flashMessenger()->addMessage('Exception Error: User not saved.');
return $this->redirect()->toUrl(BASE_URL.'/admin/user');
}
}
error:
Doctrine\ORM\ORMInvalidArgumentException Object ( [message:protected] => EntityManager#persist() expects parameter 1 to be an entity object, NULL given.
...............................................................................................................................................................................................................................................................................................
I checked the code and I think the problem could be this:
At the row number 82 you check if $userSmsNumberObj is an object.
If it's null you enter in the if statement
At row number 85 you check if $smsNumberObj is an object or null
In case $smsNumberObj is null you jump to row 92 without instantiate a new UserSmsNumber and you try to persist a null value
I think you have to check if $userSmsNumberObj is an object before try to persist at row 92.

Rxjs BehaviorSubject error handling when used with mergemap

I have the following code
#Injectable()
export class ReceptionService {
private generalInfoDataSrc$ = new BehaviorSubject<any>(null);
public generalInfoData = this.generalInfoDataSrc$.asObservable();
setGeneralInfo(dataSrc: GeneralInfoMModal) {
this.generalInfoDataSrc$.next(dataSrc);
}
}
From my component1 I will set the above as
OnSelect(patient: any) {
let generalInfo = new GeneralInfoMModal();
generalInfo.id = patient.id;
// some other code here
// this.recepService.setGeneralInfo(generalInfo);
}
// from component2
//
ngOnInit() { getPatientDetails() }
getPatientDetails() {
this.receptionService.generalInfoData.pipe(mergeMap(response => {
if (response && response.id) {
this.loading = true;
return this.receptionService.get('User/Get' + response.id, this.sourceobj);
} else {
return of(null);
}
}), takeUntil(this.unsubscribe$)).subscribe(response => {
this.patient = response;
this.loading = false;
}, error => {
this.loading = false;
// this.utility.showMsg('An error occurred while getting user.')
}, () => {
})
}
Every things works well. I keep on selecting a user thereby calling the User/Get api. But if in case if the api returns an error then error part is executed after which when there is a change in behaviorsubject(user is selected) it doesn't call the User/Get. Is there other way of handling errors with behaviorsubject or any other approach to handle the idea. How a behaviorsubject should be used in such a case.
If you are using the same behavior subject over and over again, and if there is an error, you need to set the behavior subject back to null, so that when the next user is set, it will get the latest value.
Try something like this:
getPatientDetails() {
this.receptionService.generalInfoData.pipe(mergeMap(response => {
if (response && response.id) {
this.loading = true;
return this.receptionService.get('User/Get' + response.id, this.sourceobj);
} else {
return of(null);
}
}), takeUntil(this.unsubscribe$)).subscribe(response => {
this.patient = response;
this.loading = false;
}, error => {
this.loading = false;
///////////////////////////////// ADD THIS LINE ///////////////////////
this.recepService.setGeneralInfo(null);
// this.utility.showMsg('An error occurred while getting user.')
}, () => {
})

ZF2 - BootStrap redirects

My users are required to confirm their email addresses before they have access to the application.
I have a specific route that they are sent to if they log in and their email is not confirmed: "customer/register-landing" this will send an email and the view will explain what they need to do.
I am using bootstrap for brevity.
This is what I have so far and the last bit I am struggling to work out (the re-direct part)
//I run console related queries and this breaks if run
if ( $e->getRequest() instanceof \ZF\ContentNegotiation\Request )
{
//Get a user object
$authService = $sm->get( AuthorizationService::class );
$userObject = $authService->getIdentity();
if (!$userObject instanceof User ) {
return;
}
if ($userObject->getIsEmailConfirmed() == 1) {
return;
}
//So we have a logged in user who needs to confirm their email
$redirect = $em->attach(MvcEvent::EVENT_DISPATCH,
function($e){
$route = $e->getRouteMatch();
if ($route->getMatchedRouteName() != 'customer/register-landing')
{
//Redirect to the route: customer/register-landing
}
}
);
}
What do I need to do to re-direct to the actual page? I had a look around and I found this code:
$em->getSharedManager()->attach('Zend\Mvc\Controller\AbstractActionController', 'dispatch', function($e) {
$controller = $e->getTarget();
$controller->plugin('redirect')->toRoute('customer/register-landing');
}, 100);
However when I add it to the class it does not work:
$redirect = $em->attach(MvcEvent::EVENT_DISPATCH,
function($e){
$route = $e->getRouteMatch();
if ($route->getMatchedRouteName() != 'customer/register-landing')
{
$em->getSharedManager()->attach('Zend\Mvc\Controller\AbstractActionController', 'dispatch', function($e) {
$controller = $e->getTarget();
$controller->plugin('redirect')->toRoute('customer/register-landing');
}, 100);
}
}
);
What is the correct way to do this?
i solved this with next code. if you need all code go to https://github.com/Gimalca/piderapido/blob/master/module/Admin/Module.php
class Module {
public function onBootstrap(MvcEvent $e) {
}
public function init(ModuleManager $moduleManager) {
$moduleName = $moduleManager->getEvent()->getModuleName();
if ($moduleName == 'Admin') {
$events = $moduleManager->getEventManager();
$sharedEvents = $events->getSharedManager();
// This define modules need Login
$sharedEvents->attach(array(__NAMESPACE__, 'Admin', 'Account'), 'dispatch', array($this, 'initAuth'), 100);
}
}
public function initAuth(MvcEvent $e) {
//This get router strings
$routerMatch = $e->getRouteMatch();
$module = $routerMatch->getMatchedRouteName();
$controller = $routerMatch->getParam('controller');
$action = $routerMatch->getParam('action');
//This get Authenticate Class
$app = $e->getApplication();
$sm = $app->getServiceManager();
$auth = $sm->get('Admin\Model\LoginAdmin');
// This redirect all. but is login interface not
if ($controller != 'Admin\Controller\Login' && !$auth->isLoggedIn()) {
$controller = $e->getTarget();
return $controller->redirect()->toRoute('admin',array('controller'=>'login','action' => 'index'));
}
if ($auth->isLoggedIn()) {
$viewModel = $e->getViewModel();
$viewModel->userIdentity = $auth->getIdentity();
}
}

asp.net-MVC Unexplained Production Exception

After moving my application to production, I get the regular Object reference not set to an instance of an object. exception logged in my event viewer.
This exception occurs intermittently few times a day, the problem is that I cannot put my hand on the problem, the logged exception details are not helpful, as there are no code line numbers included in the stack trace.
The Exception occurs on an action in my home controller which is the entry point action for each user arriving at the web site.
Can anyone help me reason with the below trace:
ERROR => Object reference not set to an instance of an object.
(XXX.XXX.Web.Controllers.HomeController.Index)
(
<>c__DisplayClass2b.<BeginInvokeAction>b__1c =>
<>c__DisplayClass33.<BeginInvokeActionMethodWithFilters>b__32 =>
<>c__DisplayClass46.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3f =>
AsyncInvocationWithFilters.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3d =>
WrappedAsyncResult`2.CallEndDelegate =>
AsyncControllerActionInvoker.<BeginInvokeSynchronousActionMethod>b__39 =>
ControllerActionInvoker.InvokeActionMethod =>
ReflectedActionDescriptor.Execute =>
<no type>.lambda_method => HomeController.Index )
System.NullReferenceException: Object reference not set to an instance of an object.
at XXXX.XXXX.Web.Controllers.HomeController.Index()
Code:
[SSOAuthorize]
public ActionResult Index()
{
try
{
ViewBag.ShowXXXAccountPrompt = false;
ViewBag.IsErrored = "false";
#region "Session Check"
if (_webHttpContext == null)
{
return RedirectToAction("signout", "Federation");
}
if (_webHttpContext.Session == null)
{
return RedirectToAction("signout", "Federation");
}
if (_webHttpContext.Session.PortalUser == null)
{
return RedirectToAction("signout", "Federation");
}
#endregion
if (_webHttpContext.Session.PortalUser != null)
{
if (!string.IsNullOrEmpty(_webHttpContext.Session.PortalUser.UserName))
{
var user = _usersManagementService.GetUserByUsername(_webHttpContext.Session.PortalUser.UserName);
var latestsubline = _subscriptionLineService.GetLatestLineByUserName(_webHttpContext.Session.PortalUser.UserName);
var isDualAccount = latestsubline == null ? false : latestsubline.Action == (int)Entities.SubscriptionLineAction.Activate? latestsubline.IsDualAccount : false;
isDualAccount = isDualAccount == null ? false : isDualAccount;
if(user == null)
{
//whenever there is no account Just Create it, the subscriptionLines table is irrelevant
_usersManagementService.CreateUser(_webHttpContext.Session.PortalUser.UserName, isDualAccount);
}
if (user.Status == AccountStatus.Inactive)
{
//Account Re-Activation Logic
if (_usersManagementService.CreateAccountHistory(user))
{
user.FirstLogonOn = DateTime.Now;
user.DeactivatedOn = null;
user.Status = AccountStatus.Active;
user.IsDualAccount = isDualAccount;
_usersManagementService.UpdateAccount(user);
#region "Check XXX Dual Account"
try
{
if (_webHttpContext.Session.MultipleAccountDialogueInformed == false)
{
_webHttpContext.Session.MultipleAccountDialogueInformed = true;
if (user.IsDualAccount == true)
{
ViewBag.ShowXXXAccountPrompt = true;
}
else
{
ViewBag.ShowXXXAccountPrompt = false;
}
}
}
catch (Exception ex)
{
_logger.Log(LogLevel.Error, "XXX Account Service _ " + ex.Message, ex);
}
#endregion
}
else
{
ViewBag.IsErrored = "true";
return View(_webHttpContext.Account);
}
}
else
{
#region "Check XXX Dual Account"
try
{
if (_webHttpContext.Session.MultipleAccountDialogueInformed == false)
{
_webHttpContext.Session.MultipleAccountDialogueInformed = true;
if (user.IsDualAccount == true)
{
ViewBag.ShowXXXAccountPrompt = true;
}
else
{
ViewBag.ShowXXXAccountPrompt = false;
}
}
}
catch (Exception ex)
{
_logger.Log(LogLevel.Error, "XXX Account Service _ " + ex.Message, ex);
}
#endregion
}
_webHttpContext.BrowserDetails.OperatingSystem = Entities.OperatingSystem.MacinXXXh;
_webHttpContext.Session.PortalUser.Id = user.Id;
if (_webHttpContext.BrowserDetails.OperatingSystem == Entities.OperatingSystem.Windows)
{
ViewBag.ProductType = "ZZZ";
var YYYInstallsDetails = GetYYYInstallsDetails(0);
ViewBag.RemainingInstallCount = YYYInstallsDetails.NumberOfSeatsAvailable;
ViewBag.YYYInstallsDetails = YYYInstallsDetails.YYYCustomersLicenseDetailsList;
ViewBag.YYYInstallsDetailsCount = YYYInstallsDetails.YYYCustomersLicenseDetailsList.Count;
ViewBag.DownloadPageUrl = getDownloadPageUrl(ProductType.ComputerProtectionNT);
ViewBag.ProductId = (int)ProductType.ComputerProtectionNT;
}
else if (_webHttpContext.BrowserDetails.OperatingSystem == Entities.OperatingSystem.MacinXXXh)
{
ViewBag.ProductType = "MacZZZ";
var YYYInstallsDetails = GetYYYInstallsDetails(1);
ViewBag.RemainingInstallCount = YYYInstallsDetails.NumberOfSeatsAvailable;
ViewBag.YYYInstallsDetails = YYYInstallsDetails.YYYCustomersLicenseDetailsList;
ViewBag.YYYInstallsDetailsCount = YYYInstallsDetails.YYYCustomersLicenseDetailsList.Count;
ViewBag.DownloadPageUrl = getDownloadPageUrl(ProductType.ComputerProtectionOSX);
ViewBag.ProductId = (int)ProductType.ComputerProtectionOSX;
}
else if (_webHttpContext.BrowserDetails.OperatingSystem == Entities.OperatingSystem.Other)
{
ViewBag.ProductType = "AndroidZZZ";
var YYYInstallsDetails = GetYYYInstallsDetails(2);
ViewBag.RemainingInstallCount = YYYInstallsDetails.NumberOfSeatsAvailable;
ViewBag.YYYInstallsDetails = YYYInstallsDetails.YYYCustomersLicenseDetailsList;
ViewBag.YYYInstallsDetailsCount = YYYInstallsDetails.YYYCustomersLicenseDetailsList.Count;
ViewBag.DownloadPageUrl = getDownloadPageUrl(ProductType.ComputerProtectionAndroid);
ViewBag.ProductId = (int)ProductType.ComputerProtectionAndroid;
}
ViewBag.ZZZInstallUrl = PortalConfig.ZZZInstallUrl;
ViewBag.ScInstallUrl = PortalConfig.SafeCentralInstallUrl;
ViewBag.MacZZZInstallUrl = PortalConfig.MacZZZInstallUrl;
ViewBag.TTTTEmail = _webHttpContext.Session.PortalUser.UserName;
}
else // if primary username coming back from sso is empty
{
return RedirectToAction("signout", "Federation");
}
}
else // if the portal user is null
{
return RedirectToAction("signout", "Federation");
}
}
catch (Exception ex)
{
ViewBag.IsErrored = "true";
_logger.Log(LogLevel.Error, ex.Message, ex);
}
return View(_webHttpContext.Account);
}

Zend framework $form->isValid($formData) Return invalid and I dont know why

I have a 2-steps-form (Fancy Name), but, when I submit this form, the validation return false all time, I debugged it and I receive all the parameters I want, but for some reason the isValid is false and get some error in the RadioButton element, this is the code:
This is the forms/Users.php
public function signup()
{
$contryModel = new Application_Model_Country();
$countries = $contryModel->getCountries();
foreach ($countries as $array)
{
if(isset($array['id_country'])){
$countryArr[$array['id_country']] = $array['country'];
}
}
array_unshift($countryArr, '-- Select Your Country --');
$name = new Zend_Form_Element_Text('Name');
$name->setLabel('Name')
->setRequired(true)
->addValidator('NotEmpty');
$lastname = new Zend_Form_Element_Text('LastName');
$lastname->setLabel('Last Name')
->setRequired(true)
->addValidator('NotEmpty');
$email = new Zend_Form_Element_Text('Email');
$email->setLabel('Email')
->setRequired(true)
->addValidator('NotEmpty');
$website = new Zend_Form_Element_Text('Website');
$website->setLabel('Website')
->setRequired(true)
->addValidator('NotEmpty');
$country = new Zend_Form_Element_Select('Country');
$country->setLabel('Country')
->setRequired(true)
->addValidator('NotEmpty')
->addMultiOptions($countryArr);
$city = new Zend_Form_Element_Select('City');
$city->setLabel('City')
->setRequired(true)
->addValidator('NotEmpty')
->addMultiOptions(array('-- Select Your City --'))
->setRegisterInArrayValidator(false)
->setAttrib('disabled',true);
$password = new Zend_Form_Element_Password('Password');
$password->setLabel('Password')
->setRequired(true)
->addValidator('NotEmpty');
$rpassword = new Zend_Form_Element_Password('RepeatPassword');
$rpassword->setLabel('Repeat Password')
->setRequired(true)
->addValidator('NotEmpty');
$why = new Zend_Form_Element_Textarea('Why');
$why->setRequired(true)
->addValidator('NotEmpty')
->setAttrib('cols', '50')
->setAttrib('rows', '4');
$job = new Zend_Form_Element_Text('Job');
$job->setLabel("Job")
->setRequired(true)
->addValidator('NotEmpty');
$boxes = new Application_Model_Colors();
$res = $boxes->getColors();
foreach($res as $colors){
$colorArr[$colors['id']]['color'] = $colors['color'];
$colorArr[$colors['id']]['overColor'] = $colors['overColor'];
}
$color = new Zend_Form_Element_Radio('color');
$color->setLabel('Color')
->addMultiOptions($colorArr)
->addValidator('NotEmpty');
$save = new Zend_Form_Element_Submit('Submit');
$save->setLabel('Save');
$this->addElements(array($name, $lastname, $email, $website, $password, $rpassword, $job, $country, $city, $color, $why, $save));
}
*This is a part of the view * where I format the Radios
<?php
foreach($this->form->color->options as $key=>$colors){
echo "<label><input type='radio' value='$key' name='color'><div class='registrationBoxes' style='background-color:#".$colors['color']."' data-color='".$colors['color']."' data-overColor='".$colors['overColor']."' value='".$colors['color']."'></div></label>";
}
?>
And here is the Controller
public function indexAction()
{
$form = new Application_Form_Users();
$form->signup();
$this->view->form = $form;
if($this->getRequest()->isPost())
{
$formData = $this->getRequest()->getPost();
if($form->isValid($formData))
{
$formData = $this->getRequest()->getPost();
$name = $formData['Name'];
$lastName = $formData['LastName'];
$email = $formData['Email'];
$website = $formData['Website'];
$password = $formData['Password'];
$rpassword = $formData['RepeatPassword'];
$job = $formData['Job'];
$country = $formData['Country'];
$city = $formData['City'];
$color = $formData['color'];
$why = $formData['Why'];
$date_create = date('Y-m-d H:i:s');
$position = new Application_Model_Country();
$latLong = $position->getLatLong($city);
if($password == $rpassword){
$data = array( 'name'=>$name,
'last_name'=>$lastName,
'email'=>$email,
'website'=>$website,
'password'=>md5($password),
'date_create'=>$date_create,
'job'=>$job,
'country'=>$country,
'city'=>$city,
'color'=>$color,
'why'=>$why,
'latitude'=>$latLong['latitude'],
'longitude'=>$latLong['longitude']
);
$add = new Application_Model_Users();
$res = $add->insertUser($data);
if($res){
$this->view->message = "Registration Successfuly.";
$this->_redirect("/contact");
}else{
$this->view->errorMessage = "We have a problem with your registration, please try again later.";
}
}else{
$this->view->errorMessage = "Password and confirm password don't match.";
$form->populate($formData);
}
} else {
$this->view->errorMessage = "There is an error on your registration, all fields are requried";
$form->populate($formData);
}
}
}
a die(var_dump()) return this:
array(12) {
["Name"]=>
string(9) "Some name"
["LastName"]=>
string(13) "Some lastName"
["Email"]=>
string(21) "Someemail#hotmail.com"
["Password"]=>
string(5) "Some "
["RepeatPassword"]=>
string(5) "Some "
["Website"]=>
string(12) "Some website"
["Job"]=>
string(8) "Some job"
["Country"]=>
string(1) "7"
["City"]=>
string(3) "434"
["color"]=>
string(1) "3"
["Why"]=>
string(10) "Emotional!"
["Submit"]=>
string(4) "Save"
}
As you can see, all the parameters are coming and with value, but for no reason the isValid is returning false, some idea guys?
Thanks.-
EDIT
This is a part of the Zend/form.php code required by Tonunu
public function __construct ($options = null)
{
if (is_array($options)) {
$this->setOptions($options);
} elseif ($options instanceof Zend_Config) {
$this->setConfig($options);
}
// Extensions...
$this->init();
$this->loadDefaultDecorators();
}
public function __clone ()
{
$elements = array();
foreach ($this->getElements() as $name => $element) {
$elements[] = clone $element;
}
$this->setElements($elements);
$subForms = array();
foreach ($this->getSubForms() as $name => $subForm) {
$subForms[$name] = clone $subForm;
}
$this->setSubForms($subForms);
$displayGroups = array();
foreach ($this->_displayGroups as $group) {
$clone = clone $group;
$elements = array();
foreach ($clone->getElements() as $name => $e) {
$elements[] = $this->getElement($name);
}
$clone->setElements($elements);
$displayGroups[] = $clone;
}
$this->setDisplayGroups($displayGroups);
}
public function setOptions (array $options)
{
if (isset($options['prefixPath'])) {
$this->addPrefixPaths($options['prefixPath']);
unset($options['prefixPath']);
}
if (isset($options['elementPrefixPath'])) {
$this->addElementPrefixPaths($options['elementPrefixPath']);
unset($options['elementPrefixPath']);
}
if (isset($options['displayGroupPrefixPath'])) {
$this->addDisplayGroupPrefixPaths(
$options['displayGroupPrefixPath']);
unset($options['displayGroupPrefixPath']);
}
if (isset($options['elementDecorators'])) {
$this->_elementDecorators = $options['elementDecorators'];
unset($options['elementDecorators']);
}
if (isset($options['elements'])) {
$this->setElements($options['elements']);
unset($options['elements']);
}
if (isset($options['defaultDisplayGroupClass'])) {
$this->setDefaultDisplayGroupClass(
$options['defaultDisplayGroupClass']);
unset($options['defaultDisplayGroupClass']);
}
if (isset($options['displayGroupDecorators'])) {
$displayGroupDecorators = $options['displayGroupDecorators'];
unset($options['displayGroupDecorators']);
}
if (isset($options['elementsBelongTo'])) {
$elementsBelongTo = $options['elementsBelongTo'];
unset($options['elementsBelongTo']);
}
if (isset($options['attribs'])) {
$this->addAttribs($options['attribs']);
unset($options['attribs']);
}
$forbidden = array('Options', 'Config', 'PluginLoader', 'SubForms',
'View', 'Translator', 'Attrib', 'Default');
foreach ($options as $key => $value) {
$normalized = ucfirst($key);
if (in_array($normalized, $forbidden)) {
continue;
}
$method = 'set' . $normalized;
if (method_exists($this, $method)) {
$this->$method($value);
} else {
$this->setAttrib($key, $value);
}
}
if (isset($displayGroupDecorators)) {
$this->setDisplayGroupDecorators($displayGroupDecorators);
}
if (isset($elementsBelongTo)) {
$this->setElementsBelongTo($elementsBelongTo);
}
return $this;
}
In order to check if your form is valid, you have to put your data into it, using this method !
$form->setData($formData)
and then you can ask for validation
$form->isValid()
So what you need is :
$formData = $this->getRequest()->getPost();
$form->setData($formData);
if($form->isValid()){
//Blablablabla
}

Resources