Zend DB Update not updating - zend-framework

I dont know why this particular bit of code is simply not updating despite using this style of coding elsewhere succesfully.No exception is being thrown.
CREATE TABLE `accounts` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`accounts_username` varchar(60) DEFAULT NULL,
`accounts_fullname` varchar(600) DEFAULT NULL,
`accounts_email` varchar(600) DEFAULT NULL,
`accounts_password` varchar(600) DEFAULT NULL,
`accounts_status` varchar(600) DEFAULT NULL,
`accounts_roles` varchar(600) DEFAULT NULL,
`accounts_comments` text,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=latin1
In my form I have the code
public function __construct($options = null)
{
parent::__construct($options);
$optionsrole = array(
'guest' => 'guest',
'user' => 'user',
'writer' => 'writer',
'admin' => 'admin'
);
$optionsstatus = array(
'active' => 'active',
'pending' => 'pending'
);
$this->setName('account');
$id = new Zend_Form_Element_Hidden('id');
$username = new Zend_Form_Element_Text('accounts_username');
$username->setLabel('Username')
->setRequired(true)
->addFilter('StripTags')
->addFilter('StringTrim')
->addValidator('NotEmpty');
$fullname = new Zend_Form_Element_Text('accounts_fullname');
$fullname->setLabel('Fullname')
->setRequired(true)
->addFilter('StripTags')
->addFilter('StringTrim')
->addValidator('NotEmpty');
$email = new Zend_Form_Element_Text('accounts_email');
$email->setLabel('Email')
->setRequired(true)
->addFilter('StripTags')
->addFilter('StringTrim')
->addValidator('NotEmpty')
->addValidator(new Zend_Validate_EmailAddress());
$password = new Zend_Form_Element_Password('accounts_password');
$password->setLabel('Password')
->setRequired(true)
->addFilter('StripTags')
->addFilter('StringTrim')
->addValidator('NotEmpty');
$status = new Zend_Form_Element_Select('accounts_status');
$status->setLabel('Status')
->setRequired(true)
//->addMultiOptions(array('Active','Pending'));
->addMultiOptions($optionsstatus);
$role = new Zend_Form_Element_Select('accounts_roles');
$role->setLabel('Role')
->setRequired(true)
//->addMultiOptions(array('guest','user','writer','admin'));
->addMultiOptions($optionsrole);
$comments = new Zend_Form_Element_Textarea('accounts_comments');
$comments->setLabel('Comments')
//->setAttrib('size',200)
->setAttrib('rows',20)
->setAttrib('cols',50);
$submit = new Zend_Form_Element_Submit('submit');
$submit->setAttrib('id', 'submitbutton');
$this->addElements(array($id, $username, $fullname,$email,
$password,$status,$role,$comments,$submit));
}
In my accounts controller
public function editAction()
{
$this->view->title = "Edit User Account";
$this->view->headTitle($this->view->title, 'PREPEND');
$form = new Form_Account();
$form->submit->setLabel('Save');
$accounts = new Model_DbTable_Account();
$this->view->form = $form;
if ($this->getRequest()->isPost()) {
$formData = $this->getRequest()->getPost();
if ($form->isValid($formData)) {
/*
if($accounts->checkUnique($formData['accounts_username'])){
$this->view->errorMessage = "Username already taken. Please choose another one.";
return;
}
*/
$id = (int)$form->getValue('id');
$username = $form->getValue('accounts_username');
$fullname = $form->getValue('accounts_fullname');
$email = $form->getValue('accounts_email');
$password = $form->getValue('accounts_password');
$status = $form->getValue('accounts_status');
$roles = $form->getValue('accounts_roles');
$comments = $form->getValue('accounts_comments');
//$accounts = new Model_DbTable_Account();
$accounts->updateaccount($username, $fullname,$email,
$password,$status,$roles,$comments);
$this->_redirect('/account');
} else {
$form->populate($formData);
}
} else {
$id = $this->_getParam('id', 0);
if ($id > 0) {
$account = new Model_DbTable_Account();
$form->populate($account->getaccount($id));
}
}
}
In my model
public function updateaccount($id,$username, $fullname, $email,
$password,$status,$roles,$comments)
{
$data = array(
'accounts_username' => $username,
'accounts_fullname' => $fullname,
'accounts_email' => $email,
'accounts_password' => md5($password),
'accounts_status' => $status,
'accounts_roles' => $roles,
'accounts_comments' => $comments,
);
$this->update($data, 'id = '. (int)$id);
}
Am i missing something?

I did find the problem.I was not passing the $id creteria and therefore no record was been updated.
$accounts->updateaccount($username, $fullname,$email,
$password,$status,$roles,$comments);
It should have instead read
$accounts->updateaccount($id,$username, $fullname,$email,
$password,$status,$roles,$comments);

Related

How to send Email confirmation link via smtp Cakephp

I am working in cakephp and want to send confirmation link on user signup but i do not know much about SMTP.
Here is What i have written I am using Token to confirm email which will expire next time if user hit the same confirmation link.
Here is usercontroller/signup method:
public function signup()
{
$this->layout = 'main';
if ($this->request->is('post')) {
$this->User->create();
$this->request->data['User']['password'] = AuthComponent::password($this->request->data['User']['password']);
$hash = sha1($this->request->data['User']['username'] . rand(0, 100));
$this->request->data['User']['tokenhash'] = $hash;
if ($this->User->validates()) {
$this->User->save($this->request->data);
$ms = 'Click on the link below to complete registration ';
$ms .= 'http://localhost/FindTutor/users/verify/t:' . $hash . '/n:' . $this->data['User']['username'] . '';
$ms = wordwrap($ms, 70);
$this->Email->from = 'usman.jamil0308#gmail.com';
$this->Email->to = $this->request->data['User']['email'];
$this->Email->subject = 'Confirm Registration..';
$this->Email->send($ms);
$this->Session->setFlash('Please Check your email for validation Link');
$this->redirect('/users/login');
}
}
}
Here is users/verify method to confirm if user hit the confirmation link.
public function verify(){
//check if the token is valid
if (!empty($this->passedArgs['n']) && !empty($this->passedArgs['t'])){
$name = $this->passedArgs['n'];
$tokenhash = $this->passedArgs['t'];
$results = $this->User->findByUsername($name);
if ($results['User']['activate']==0){
//check the token
if($results['User']['tokenhash']==$tokenhash)
{
$results['User']['activate']=1;
//Save the data
$this->User->save($results);
$this->Session->setFlash('Your registration is complete');
$this->redirect('/users/login');
exit;
}
else{
$this->Session->setFlash('Your registration failed please try again');
$this->redirect('/users/register');
}
}
else {
$this->Session->setFlash('Token has alredy been used');
$this->redirect('/users/register');
}
}else
{
$this->Session->setFlash('Token corrupted. Please re-register');
$this->redirect('/users/register');
}
}
Error is somthing like this:
mail(): Failed to connect to mailserver at "localhost" port 25, verify your "SMTP" and "smtp_port" setting in php.ini or use ini_set()
try to use mailjet and configure your sever (wamp or xampp)the directorie sendmail and configure your app.php like that
'EmailTransport' => [
'default' => [
'className' => 'Mail',
// The following keys are used in SMTP transports
'host' => 'localhost',
'port' => 25,
'timeout' => 30,
'username' => '',
'password' => '',
'client' => null,
'tls' => null,
],
'mailjet' => [
'className' => 'smtp',
// The following keys are used in SMTP transports
'host' => 'in-v3.mailjet.com',
'username' => 'copy that from your account mailjet',
'password' => 'copy that from your account mailjet',
'port' => 587,
'timeout' => 3000,
'client' => null,
'tls' => null,
],
],
'Email' => [
'default' => [
'transport' => 'mailjet',
'from' => 'xxxxxx#gmail.com',
//'charset' => 'utf-8',
//'headerCharset' => 'utf-8',
],
],
public $smtp = array(
'host' => 'ssl://smtp.gmail.com',
'port' => 465,
'username' => 'your email id',
'password' => 'your password',
'transport' => 'Smtp',
);
App::uses('CakeEmail', 'Network/Email');
$Email = new CakeEmail('smtp');
$Email->from('info#email.com');
$Email->to($email);
$message = "hello";
$Email->send($message);
First Include Email Component in your App Controller like this :
public $components = array(
'Email'
);
Create a sendMail function in your App controller like this
public function _sendMail( $to, $from, $replyTo, $subject, $element,$parsingParams = array(),$attachments ="", $sendAs = 'html', $bcc = array()){
$port = '';
$timeout = '';
$host = '';
$username = '';
$password = '';
$client = '';
$toAraay = array();
if (!is_array($to)) {
$toAraay[] = $to;
} else {
$toAraay = $to;
}
$this->Email->smtpOptions = array(
'port' => "$port",
'timeout' => "$timeout",
'host' => "$host",
'username' => "$username",
'password' => "$password",
'client' => "$client"
);
$this->Email->delivery = 'smtp';
foreach ($parsingParams as $key => $value) {
$this->set($key, $value);
}
foreach ($toAraay as $email) {
$this->Email->to = $email;
$this->Email->subject = $subject;
$this->Email->replyTo = $replyTo;
$this->Email->from = $from;
if(!empty($bcc)){
$this->Email->cc = $bcc[0];
}
if ($attachments!="") {
$this->Email->attachments = array();
$this->Email->attachments[0] = $attachments ;
}
$this->Email->template = $element;
$this->Email->sendAs = $sendAs;
$this->Email->send();
$this->Email->reset();
}
}
Create a sendmail.ctp file in View/Emails/html
Add this content in file and also add your header or footer
<?php echo $message; ?>
Now whenever you want to send email call this function like this :
$this->_sendMail($to, $from, $replyTo, $subject, 'sendmail', array('message' => $message), "", 'html', $bcc = array());
Now you can implement your logic for verification email like this :
$message = 'Click on the link below to complete registration ';
$message .= 'http://localhost/FindTutor/users/verify/t:' . $hash . '/n:' . $this->data['User']['username'] . '';
$from = 'usman.jamil0308#gmail.com';
$to = $this->request->data['User']['email'];
$subject = 'Confirm Registration..';
$replyTo = 'usman.jamil0308#gmail.com';
$this->_sendMail($to, $from, $replyTo, $subject, 'sendmail', array('message' => $message), "", 'html', $bcc = array());

Zend 1.12 login not working

i'm creating a login system using salt and password two columns but it's not working my code of action
public function indexAction() {
$form = new Admin_Form_Login();
$request = $this->getRequest();
if ($request->isPost()) {
if ($form->isValid($request->getPost())) {
if ($this->_process($form->getValues())) {
// We're authenticated! Redirect to the home page
$this->_helper->redirector('', 'dashboard');
} else {
echo 'Password is wrong';
}
}
}
$this->view->form = $form;
}
protected function _process($values) {
// Get our authentication adapter and check credentials
$adapter = $this->_getAuthAdapter();
$adapter->setIdentity($values['email']);
$adapter->setCredential($values['password']);
$auth = Zend_Auth::getInstance();
$result = $auth->authenticate($adapter);
if ($result->isValid()) {
$user = $adapter->getResultRowObject();
$auth->getStorage()->write($user);
return true;
}
return false;
}
protected function _getAuthAdapter() {
$dbAdapter = Zend_Db_Table::getDefaultAdapter();
$authAdapter = new Zend_Auth_Adapter_DbTable($dbAdapter);
$authAdapter->setTableName('eg_user_login')
->setIdentityColumn('email')
->setCredentialColumn('password')
->setCredentialTreatment("MD5(CONCAT(? , salt))");
return $authAdapter;
}
and code of registration action is
$regForm = new Admin_Form_Register();
$this->view->form = $regForm;
if ($this->getRequest()->isPost()) {
if ($regForm->isValid($this->_request->getPost())) {
$values = $regForm->getValues($this->_request->getPost());
$pass = $values['pass1'];
$salt = sha1($pass);
$password = MD5($salt . $pass);
$data = array(
'f_name' => $values['fname'],
'l_name' => $values['lname'],
'gender' => $values['gender'],
'email' => $values['email'],
'contact' => $values['contact'],
'password' => $password,
'salt' => $salt,
'created_on' => date("d-m-y"),
'user_role' => $values['userrole'],
'status' => 0
);
$db = new Admin_Model_Userreg();
$db->insert($data);
}
}
it is displaying any error,i think problem in encryption and decryption in password.
login page is not redirecting to dashboard and not storing the user instance .... please help me. thank you.

Phalcon uniqueness on update

folks. The uniqueness validator in my form works as expected on adding new records, but on updating an exsisting record, it throws an error that the url already exists. It exists, in fact, but only in the current record.
Here is my controller:
$feed = Feeds::findFirst($id);
$feedForm = new FeedForm($feed, array('edit' => true));
if ($this->request->isPost() == true) {
$feedData = $this->request->getPost();
if ($feedForm->isValid($feedData, $feed)) {
if ($feed->save()) {
$this->flash->success("Feed successfuly updated.");
} else {
$this->flash->error("Update failed.");
}
} else {
foreach ($feedForm->getMessages() as $message) {
$this->flash->error($message);
}
}
}
And my form class:
class FeedForm extends FormBase {
public $options;
public function initialize($entity = null, $options = null) {
parent::initialize();
$this->setEntity($entity);
$this->options = $options;
$status = new Radio('status');
$status->addValidator(
new PresenceOf(
array(
'message' => 'The status is required.'
)
));
$this->add($status);
$name = new Text('name');
$name->addValidator(
new PresenceOf(
array(
'message' => 'The name is required.'
)
));
$name->addValidator(
new StringLength(
array(
'max' => 50,
'messageMaximum' => 'The name you entered is too long.'
)
));
$this->add($name);
$xml = new Text('xml');
$xml->addValidator(
new PresenceOf(
array(
'message' => 'The URL address is required.'
)
));
$xml->addValidator(
new StringLength(
array(
'max' => 2048,
'messageMaximum' => 'The URL address you entered is too long.'
)
));
$xml->addValidator(
new Url(
array(
'message' => 'The URL you entered is invalid.'
)
));
$xml->addValidator(
new Uniqueness(
array(
'model' => 'Sravnisite\Admin\Models\Feeds',
'table' => 'feeds',
'column' => 'xml',
'message' => 'The entered URL address already exists.'
)
));
$periodOptions = array();
for ($i = 4; $i <= 24; $i++) {
array_push($periodOptions, $i);
}
$this->add($xml);
$period = new Select('period', $periodOptions);
$period->addValidator(
new PresenceOf(
array(
'message' => 'The period is required.'
)
));
$this->add($period);
$shopID = new Select('shop_id', Shops::find(), array('using' => array('id', 'name')));
$shopID->addValidator(
new PresenceOf(
array(
'message' => 'The shop is required.'
)
));
$this->add($shopID);
}
}
Any ideas?
The form validation doesn't know to ignore the record you are updating - so for uniqueness it finds the record you're trying to update and gives an error. You could do some complicated find logic to keep the uniqueness validation in the form but it is better moved to the model. Your result would end up something like:
Controller
$feed = Feeds::findFirst($id);
$feedForm = new FeedForm($feed, array('edit' => true));
if ($this->request->isPost() == true) {
$feedData = $this->request->getPost();
if ($feedForm->isValid($feedData, $feed)) {
if ($feed->save()) {
$this->flash->success("Feed successfuly updated.");
} else {
$this->flash->error("Update failed.");
// Get each of the validation messages from the model
foreach ($feed->getMessages() as $message) {
$this->flash->error($message);
}
}
} else {
foreach ($feedForm->getMessages() as $message) {
$this->flash->error($message);
}
}
}
Form
// Exactly the same as you currently have but without the Uniqueness Validator
Model
class Feeds extends Phalcon\Mvc\Model
/**
* Validate that xml URLs are unique
*/
public function validation()
{
$this->validate(new Uniqueness(array(
"field" => "xml",
"message" => "The url must be unique."
)));
return $this->validationHasFailed() != true;
}

validating dynamic forms in symfony2 returns "this value is not valid"

I have 3 entities: Country, State and City with the following relationships, and i have another entity named Location which have all of theme for setting user location,
i have a form too, for getting user's location data. which should be generated dynamically, because the entities are related to each other, and for example if the state changed, the cities must be changed too.
i used the code below in my listener for doing this:
/**
* #param FormFactoryInterface $factory
* #param EntityManager $om
*/
public function __construct($factory, $om)
{
$this->factory = $factory;
$this->om = $om;
}
public static function getSubscribedEvents()
{
return array(
FormEvents::PRE_BIND => 'preBind',
FormEvents::PRE_SET_DATA => 'preSetData',
);
}
/**
* #param event FormEvent
*/
public function preSetData(FormEvent $event)
{
$company = $event->getData();
if (null === $company)
{
return;
}
// company has country => edit action
if($company->getCountry()){
//retrieve location
$country = $company->getCountry();
$state = $company->getState();
$city = $company->getCity();
if(is_object($state) && is_object($city) && is_object($country))
{
$states = $country->getStates();
$cities = $state->getCities();
}
else
{
$cities = array();
$states = array();
}
}else{
// new location action
$states = array();
$cities = array();
}
$form = $event->getForm();
$this->customizeForm($form, $cities,$states);
}
public function preBind(FormEvent $event)
{
$dataForm = $event->getData();
$countryId = $dataForm['country'];
$stateId = $dataForm['state'];
$cityId = $dataForm['city'];
$country = $this->om
->getRepository('GMBundle:Country')
->find($countryId);
$state = $this->om
->getRepository('GMBundle:State')
->find($stateId);
$city = $this->om
->getRepository('GMBundle:City')
->find($cityId);
if(is_object($state) && is_object($city) && is_object($country))
{
$states = $country->getStates();
$cities = $state->getCities();
}
else
{
$cities = array();
$states = array();
}
$form = $event->getForm();
$this->customizeForm($form, $cities, $states);
}
protected function customizeForm($form, $cities, $states)
{
$form
->add($this->factory->createNamed('state', 'entity', null, array(
'choices' => $states,
'label' => 'state',
'required' => true,
'empty_value' => 'choose state',
'class' => 'GMBundle:State',
)))
->add($this->factory->createNamed('city', 'entity', null, array(
'choices' => $cities,
'label' => 'city',
'required' => true,
'empty_value' => 'choose city',
'class' => 'GMBundle:City',
)))
;
}
when i want to edit my form, i got the error This value is not valid.
it seems that symfony doesn't changed the data, for example if user had selected X as Stated and now wants to select Y for his state, symfony said the chosen city is not valid and must be selected from X's cities, which was his previous choice.
any idea how i can resolve it? or where i'm doing something wrong!?
-thanks

How to prepend language to every url in Zend Framework

So, I've set up a simple means of changing languages:
protected function _initRoutes()
{
$this->bootstrap('FrontController');
$this->_frontController = $this->getResource('FrontController');
$router = $this->_frontController->getRouter();
$route = new Zend_Controller_Router_Route(
':language/:controller/:action/*',
array(
'language' => 'en',
'module' => 'default',
'controller' => 'index',
'action' => 'index'
)
);
$router->addRoute('lang_default', $route);
}
protected function _initLanguage()
{
$front = Zend_Controller_Front::getInstance();
$front->registerPlugin(new JP_Controller_Plugin_Language());
}
And:
class JP_Controller_Plugin_Language
extends Zend_Controller_Plugin_Abstract
{
public function routeShutdown(Zend_Controller_Request_Abstract $request)
{
$locale = new Zend_Locale();
$options = array('scan' => Zend_Translate::LOCALE_FILENAME);
$translate = new Zend_Translate('array', APPLICATION_PATH . '/translations/', 'auto', $options);
$requestParams = $this->getRequest()->getParams();
$language = (isset($requestParams['language'])) ? $requestParams['language'] : false;
if ($language == false) {
$language = ($translate->isAvailable($locale->getLanguage())) ? $locale->getLanguage() : 'en';
}
if (!$translate->isAvailable($language)) {
throw new Zend_Controller_Action_Exception('This page, in this language doesn\'t exist', 404);
} else {
$locale->setLocale($language);
$translate->setLocale($locale);
Zend_Form::setDefaultTranslator($translate);
setcookie('lang', $locale->getLanguage(), null, '/');
Zend_Registry::set('Turniri_Language', $language);
Zend_Controller_Front::getInstance()->setBaseUrl('/'.Zend_Registry::get('Turniri_Language'));
Zend_Registry::set('Zend_Locale', $locale);
Zend_Registry::set('Zend_Translate', $translate);
}
}
}
So, now I've got a wish. I'd like to use the same approach that I've been using until now, like seting Form Action like this:
$form->setAction("/path/to/some/action");
but I'd also like for the system to automatically prepend the language id to the url. How could this be done?
using setBaseUrl() didn't do it.