Zend 1.12 login not working - zend-framework

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.

Related

Codeigniter 4 Rest API - 301 Moved Permanently

I have Codeigniter 4 web app that run REST API with firebase/php-jwt on Laragon 5.0.0210523 environment that run Apache-2.4.47, PHP-8.1.7, and MongoDB-4.0.28. I followed a tutorial and it works fine both server REST API and it REST client. After day work, i stop laragon server. In the next day i try run REST API server then tried then run the client but it failed and gave 301 moved permanently error, but i still can access it from postman.
REST API server side
composer.json
***
"require": {
"php": "^7.4 || ^8.0",
"codeigniter4/framework": "^4.0",
"mongodb/mongodb": "^1.12",
"firebase/php-jwt": "^6.3"
},
***
.env file
***
JWT_SECRET_KEY = SomeThing$089
JWT_TIME_TO_LIVE = 3600
app.baseURL = 'http://ci4-api.localhost'
***
Route.php
***
$routes->get('/', 'Home::index');
$routes->resource('api/users');
$routes->post('api/auth', [\App\Controllers\Api\Auth::class, 'index']);
***
JWT_Helper.php
use App\Models\ModelUsers;
use Firebase\JWT\JWT;
use Firebase\JWT\Key;
/**
* #throws Exception
*/
function getJWT($authHeader)
{
if (is_null($authHeader)){
throw new Exception("Authentication JWT failed");
}
return explode(" ", $authHeader)[1];
}
function validateJWT($encodedToken)
{
$key = getenv('JWT_SECRET_KEY');
$decodedToken = JWT::decode($encodedToken, new Key($key, 'HS256'));
$modelUsers = new ModelUsers();
$modelUsers->get_email($decodedToken->email);
}
function createJWT($email): string
{
$timeRequest = time();
$timeToken = getenv('JWT_TIME_TO_LIVE');
$timeExpired = $timeRequest + $timeToken;
$payload = [
'email' => $email,
'iat' => $timeRequest,
'exp' => $timeExpired,
];
return JWT::encode($payload, getenv('JWT_SECRET_KEY'), 'HS256');
}
FilterJWT.php
namespace App\Filters;
use CodeIgniter\API\ResponseTrait;
use CodeIgniter\Filters\FilterInterface;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use Config\Services;
use Exception;
class FilterJWT implements FilterInterface
{
use ResponseTrait;
public function before(RequestInterface $request, $arguments = null)
{
$header = $request->getServer('HTTP_AUTHORIZATION');
try {
helper('jwt');
$encodedToken = getJWT($header);
validateJWT($encodedToken);
return $request;
} catch (Exception $ex) {
return Services::response()->setJSON(
[
'error' => $ex->getMessage(),
]
)->setStatusCode(ResponseInterface::HTTP_UNAUTHORIZED);
}
}
public function after(RequestInterface $request, ResponseInterface $response, $arguments = null)
{
// TODO: Implement after() method.
}
}
Filters.php
***
public $aliases = [
'csrf' => CSRF::class,
'toolbar' => DebugToolbar::class,
'honeypot' => Honeypot::class,
'invalidchars' => InvalidChars::class,
'secureheaders' => SecureHeaders::class,
'auth' => FilterJWT::class,
];
public $filters = [
'auth' => [
'before' => [
'api/users/*',
'api/users'
]
]
];
***
ModelUsers.php
namespace App\Models;
use App\Libraries\MongoDb;
class ModelUsers
{
private $database = 'ci4_api';
private $collection = 'user';
private $conn;
function __construct()
{
$mongodb = new MongoDb();
$this->conn = $mongodb->getConn();
}
function get_user_list() {
try {
$filter = [];
$query = new \MongoDB\Driver\Query($filter);
$result = $this->conn->executeQuery($this->database. '.' . $this->collection, $query);
return $result->toArray();
} catch (\MongoDB\Driver\Exception\RuntimeException $ex) {
show_error('Error while fetching users: ' . $ex->getMessage(), 500);
}
}
***
Auth.php
namespace App\Controllers\Api;
use App\Controllers\BaseController;
use App\Models\ModelUsers;
use CodeIgniter\API\ResponseTrait;
use CodeIgniter\Validation\Validation;
use Config\Services;
class Auth extends BaseController
{
use ResponseTrait;
private ModelUsers $model;
private Validation $validation;
function __construct()
{
$this->model = new ModelUsers();
$this->validation = Services::validation();
}
public function index()
{
$email = $this->request->getVar('email');
$password = $this->request->getVar('password');
$password_hash = password_hash($password, PASSWORD_DEFAULT);
$data1 = [
'email' => $email,
'password' => $password
];
if (!$this->validation->run($data1, 'login')) {
$errors = $this->validation->getErrors();
$response = [
'status' => 201,
'error' => null,
'messages' => [
'errors' => [
$errors
]
],
];
return $this->respond($response);
}
$data1 = $this->model->get_email($email);
//return $this->respond($data1, 200);
if (!$data1) {
$response = [
'status' => 201,
'error' => null,
'messages' => [
'error' => 'Data user atau password tidak ada1'
],
];
return $this->respond($response, 200);
}
$password_user = $data1->password;
if (password_verify($password_hash, $password_user) != 0){
$response = [
'status' => 201,
'error' => null,
'messages' => [
'error' => 'Data user atau password tidak ada2'
],
];
return $this->respond($response, 200);
}
helper('jwt');
$response = [
'message' => 'Auth berhasil dilakukan',
'data' => $data1,
'access_token' => createJWT($email)
];
return $this->respond($response, 200);
}
***
users.php
namespace App\Controllers\Api;
use App\Controllers\BaseController;
use App\Models\ModelUsers;
use CodeIgniter\API\ResponseTrait;
use CodeIgniter\HTTP\Response;
use CodeIgniter\Validation\Validation;
use Config\Services;
class Users extends BaseController
{
use ResponseTrait;
private ModelUsers $model;
private Validation $validation;
function __construct()
{
$this->model = new ModelUsers();
$this->validation = Services::validation();
}
public function index(): Response
{
$data = $this->model->get_user_list();
$count = count($data);
if ($count <= 0) {
$data = [
'status' => 201,
'error' => null,
'message' => [
'success' => 'Tidak ada data daftar pegawai'
],
];
}
return $this->respond($data, 200);
}
***
REST Client
.env file
***
app.baseURL = 'http://ci4-test.localhost'
***
Routes.php
***
$routes->get('/rest', [\App\Controllers\Rest\RestClient::class, 'index']);
***
RestClient.php
namespace App\Controllers\Rest;
use App\Controllers\BaseController;
use Config\Services;
class RestClient extends BaseController
{
public function index()
{
$client = Services::curlrequest();
$token = "someToken";
$url = "http://ci4-api.localhost/api/users/";
$headers = [
'Authorization' => 'Bearer ' . $token,
];
$response = $client->request('GET', $url, ['headers' => $headers, 'http_errors' => false]);
return $response->getBody();
}
}
Postman
api auth
api all user list
I have already tried some simple solution, like reload all laragon service like apache server and mongodb, restart the windows and tried find online, but it only suggest that the url is incorectly used like in this one []https://stackoverflow.com/questions/56700991/codeigniter-301-moved-permanently[3]
Is there anyone have same issue or solution, thanks in advance.
After trying some few more time, i found the problem. It still around about url similiar like in case of Codeigniter 301 Moved Permanently, but my problem i added "/" on my url.
eg
RestClient.php
//Read all users
$url = "http://ci4-api.localhost/api/users/";
Maybe i added it after copy paste process
so the correct url is
RestClient.php
//Read all users
$url = "http://ci4-api.localhost/api/users";
hopefully help some people facing same problem

CodeIgniter 4: Call to member function on null where post request is valid in var_dump()

** Very new to CodeIgniter so please be kind! **
I have an issue with my two user authentication forms: users/register.php and users/login.php where I cannot pass the post input to functions in my model.
As of now, I'm getting the error Call to member function addUser() on null on the registration form and a validation error on the login form that states the username/password don't match any credentials in the database. Both seem to stem from post being null although it is not.
I have done a var_dump on $login which is defined as $login = $this->request->getPost() as well as inspected the request in Firefox Developers Browser to find all the post data correctly displayed. I am stumped. Why can't I pass this array to my model?
Here is a screenshot of the post request for login.php (the same can be said for registration.php and is not included).
These are my routes:
// Login and Registration
$routes->match(['get', 'post'], 'users/register', 'Users::register');
$routes->match(['get', 'post'], 'users/login', 'Users::login', ["filter" => "noauth"]);
Here is my model UserModel.php in its entirety:
class UserModel extends Model
{
protected $DBGroup = 'default';
protected $table = 'users';
protected $primaryKey = 'username';
protected $useAutoIncrement = false;
protected $insertID = 0;
protected $returnType = 'object';
protected $useSoftDelete = false;
protected $allowedFields = [
'username',
'password',
'id',
'role',
'profile_image',
'profile_views',
'last_login',
'about_me',
'age',
'gender',
'occupation',
'hometown',
'country',
'fav_shape',
'fav_color',
'created',
'modified',
];
// Dates
protected $useTimestamps = true;
protected $dateFormat = 'datetime';
protected $createdField = 'created';
protected $modifiedField = 'modified';
// Callbacks
protected $allowCallbacks = true;
protected $beforeInsert = ['beforeInsert'];
public function __construct()
{
parent::__construct();
}
protected function beforeInsert(array $data)
{
$data = $this->passwordHash($data);
return $data;
}
protected function passwordHash(array $data)
{
if (isset($data['password'])) {
$data['password'] = password_hash($data['password'], PASSWORD_DEFAULT);
}
return $data;
}
public function lastLogin($username)
{
$this->builder()
->where('username', $username)
->update('last_login', date('Y-m-d H:i:s'));
}
public function addUser($newUser)
{
$builder = $this->builder()
->set($newUser)
->insert();
if ($builder->affected_rows() == 1) {
return TRUE;
} else {
return FALSE;
}
}
public function getUser($username)
{
$builder = $this->builder()
->where(['username' => $username])
->limit(1);
if ($builder->countAllResults() === 1) {
return $builder->get()->getRow();
} else {
return FALSE;
}
}
}
Here are excerpts from my controller Users.php:
class Users extends BaseController
{
protected $userModel;
public function __construct()
{
$userModel = new UserModel();
}
public function login()
{
$validation = \Config\Services::validation();
// Set session variable
$session = session();
if ($this->request->getMethod() === 'post' && ! empty($_POST)) {
$validation->getRuleGroup('login');
$validation->setRuleGroup('login');
$validation->withRequest($this->request)->run();
$recaptchaResponse = trim($this->request->getVar('g-recaptcha-response'));
$userIp = $this->request->getIPAddress();
$secret = env('recaptcha2_secretkey');
$credential = [
'secret' => $secret,
'response' => $recaptchaResponse,
'remoteip' => $userIp,
];
$verify = curl_init();
curl_setopt($verify, CURLOPT_URL, 'https://www.google.com/recaptcha/api/siteverify');
curl_setopt($verify, CURLOPT_POST, TRUE);
curl_setopt($verify, CURLOPT_POSTFIELDS, http_build_query($credential));
curl_setopt($verify, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($verify, CURLOPT_RETURNTRANSFER, TRUE);
$response = curl_exec($verify);
$status = json_decode($response, TRUE);
curl_close($verify);
if (empty($validation->getErrors()) && $status['success']) {
$login = $this->request->getPost();
$user = $this->userModel->getUser($login['username']);
// Storing session values
$this->setUserSession($user);
// Storing success message
$session->setFlashdata('success', 'You have successfully logged in!');
// Update last login datetime
$this->userModel->lastLogin($login['username']);
// Redirecting to dashboard after login
if ($user['role'] == 1) {
return redirect()->to('admin/dashboard');
} elseif ($user['role'] == 0) {
return redirect()->to('members/dashboard');
}
} else {
$data = [
'title' => 'Login',
'errors' => $validation->getErrors(),
];
echo view('templates/index_header', $data);
echo view('users/login');
echo view('templates/footer', $data);
}
} else {
$data = [
'title' => 'Login',
];
echo view('templates/index_header', $data);
echo view('users/login');
echo view('templates/footer', $data);
}
}
/**
* Sets session with user id, username, isLoggedIn, and role for use in member/admin site
* #param model user data
* #return boole if session was set successfully
*/
private function setUserSession($user)
{
$data = [
'id' => $user->id,
'username' => $user->username,
'profile_image' => $user->profile_image,
'isLoggedIn' => true,
'role' => $user->role,
];
if (session()->set($data)) {
return true;
} else {
return false;
}
}
public function register()
{
$validation = \Config\Services::validation();
if ($this->request->getMethod() == 'post' && ! empty($_POST)) {
$validation->getRuleGroup('registration');
$validation->setRuleGroup('registration');
$validation->withRequest($this->request)->run();
if (empty($validation->getErrors())) {
$newUser = $this->request->getPost();
if ($this->userModel->addUser($newUser)) {
$this->session->setFlashdata('success', 'Successful Registration');
$data['title'] = 'Login';
echo view('templates/index_header', $data);
echo view('users/login');
echo view('templates/footer', $data);
} else {
$this->session->setFlashdata('error', 'Something went wrong with your registration! Please try again.');
}
} else {
$data = [];
$data = [
'title' => 'Register',
'script' => 'js/click_link',
'errors' => $validation->getErrors(),
];
echo view('templates/index_header', $data);
echo view('users/register', $data);
echo view('templates/footer', $data);
}
} else {
$data = [
'title' => 'Register',
'script' => 'js/click_link',
];
echo view('templates/index_header', $data);
echo view('users/register', $data);
echo view('templates/footer', $data);
}
}
}
These are my validation rules in Config\Validation:
/**
* Registration
*/
public $registration = [
'username' => 'required|is_unique[users.username,username]|min_length[5]|max_length[25]|alpha_dash|badWordsFilter[username]',
'password' => 'required|min_length[8]|max_length[255]|regex_match[/^(?=.*[!##$%^&*-])(?=.*[0-9])(?=.*[A-Z]).{8,255}$/]',
'pass_confirm' => 'required|matches[password]',
'about_me' => 'permit_empty|max_length[250]|alpha_numeric_punct|badWordsFilter[about_me]',
'occupation' => 'permit_empty|max_length[50]|alpha_space|badWordsFilter[occupation]',
'hometown' => 'permit_empty|max_length[50]|alpha_space|badWordsFilter[hometown]',
'age' => 'permit_empty|less_than[100]|greater_than[0]|numeric',
'country' => 'permit_empty',
];
/**
* Password Verification
*/
public $login = [
'password' => 'required|validateUser[username,password]',
];
This is my custom rule to authenticate username and password credentials User_rules:
class User_rules
{
/**
* Checks if input username exists in database and then checks whether the input password matches the hash for that username
* #param string $str is the input password
* #param string $fields are the associated form fields that are being used
* #param array $data is an array containing the values for the fields indexed by field names
* #return boolean true or false depending on if the user exists and the password matches the hashed password stored in the database
*/
public function validateUser(string $str, string $fields, array $data)
{
$userModel = new UserModel();
$user = $userModel->getUser($data['username']);
if(!$user) {
return FALSE;
}
return password_verify($data['password'], $user->password);
}
Lastly, my view for login.php:
<div class='form-container'>
<?= form_open('users/login',['autocomplete' => FALSE]); ?>
<div class='form-header'>
<h2>Login</h2>
</div>
<div class='form-body'>
<div class='form-row'>
<div class='input-container'>
<i class='fas fa-user'></i>
<?php $attributes = [
'type' => 'text',
'name' => 'username',
'class' => 'input-field',
'id' => 'username',
'placeholder' => 'Username',
'required' => TRUE,
]; ?>
<?= form_input($attributes); ?>
</div>
</div>
<div class='form-row'>
<div class='input-container'>
<i class='fas fa-lock'></i>
<?php $attributes = [
'type' => 'password',
'name' => 'password',
'class' => 'input-field',
'placeholder' => 'Password',
'required' => TRUE,
]; ?>
<?= form_input($attributes); ?>
</div`>
</div>
</div>
<div class='captcha-container'>
<div class='g-recaptcha' data-sitekey='<?= env('recaptcha2_sitekey'); ?>'></div>
</div>
<div class='form-footer'>
<?php $submit = [
'name' => 'loginSubmit',
'value' => 'Login',
'class' => 'submit-btn',
];?>
<?= form_submit($submit); ?>
</div>
<h4 style='text-align: center'>Not a member yet? Register
<a href= <?= site_url('users/register'); ?> title = 'Register'> HERE</a>
</h4>
<?= form_close(); ?>
</div>
It was a stupid mistake. Someone on the codeigniter forum answered my question here: CodeIgniter Forum
basically in my constructor I needed $this->userModel = new UserModel(); instead of $userModel = new UserModel();.

How to update data using session in codeigniter

This my code in codeigniter but it doesn't update in database, I'm beginner ni codeigniter, how could I fix this error, or what is wrong in my code?
THis is my Controller:
function edit() {
$role = $this->session->userdata('role');
$this->form_validation->set_rules('firstname', 'firstname', 'required|xss_clean');
$this->form_validation->set_rules('lastname', 'lastname', 'required|xss_clean');
if ($this->form_validation->run() == FALSE) {
//set page data
$data['title'] = 'Update Profile';
if($role!=''){
$data['admin'] = $this->M_user->get($this->session->userdata('user_id'));
}else{
$data['admin'] = $this->M_administrator->getAdmin($this->session->userdata('id_admin'));
}
$data['sitename'] = $this->M_website->getName();
$data['content'] = 'admin/myaccount/edit';
//parse template
$this->parser->parse('admin/template', $data);
} else {
if($role!=''){
if ($this->M_user->updateStatus($_POST['user_id'])) {
//SAVE ADMIN ACTION LOG
//save_admin_action(array('module' => Constant::AM_ACCOUNT, 'action' => Constant::AL_EDIT, 'title' => $this->form_validation['username'], 'object_id' => $id));
//redirect page
$this->session->set_flashdata('saved', TRUE);
redirect('admin/myaccount');
}
}else{
if ($this->M_administrator->updateStatus($_POST['id_admin'])) {
//SAVE ADMIN ACTION LOG
//save_admin_action(array('module' => Constant::AM_ACCOUNT, 'action' => Constant::AL_EDIT, 'title' => $this->form_validation['username'], 'object_id' => $id));
//redirect page
$this->session->set_flashdata('saved', TRUE);
redirect('admin/myaccount');
}
}
}
}
This is my model administrator:
function updateStatus($post, $id){
$data = array(
'firstname' => $post['firstname'],
'lastname' => $post['lastname']
);
$this->db->where('id_admin', $id);
if($this->db->update('admin', $data)){
return TRUE;
}else{
return FALSE;
}
}
user Model:
function updateStatus($post, $id){
$data = array(
'firstname' => $post['firstname'],
'lastname' => $post['lastname']
);
$this->db->where('user_id', $id);
if($this->db->update('user', $data)){
return TRUE;
}else{
return FALSE;
}
}
pass firstname and last name to your updatestatus model function if you are not getting that value in model so you are not able to change
print your query using $this->db->last_query(); to get query output and post your query here
Change your where clause to
$this->db->where('id_admin', $post);

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.

ZEND, Edit form

I have a Zend form to add something to database. And then I want to use this form to edit what I added to the databese. Is any possibility to use this form (fill it from database and display it???)
I have this in my controller:
public function editAction() {
if (Zend_Auth::getInstance()->hasIdentity()) {
try {
$form = new Application_Form_NewStory();
$request = $this->getRequest();
$story = new Application_Model_DbTable_Story();
$result = $story->find($request->getParam('id'));
// $values = array(
// 'title' => $result->title,
// 'story' => $result->story,
// );
if ($this->getRequest()->isPost()) {
if ($form->isValid($request->getPost())) {
$data = array(
'title' => $form->getValue("title"),
'story' => $form->getValue("story"),
);
$where = array(
'id' => $request->getParam('id'),
);
$story->update($data, $where);
}
}
$this->view->form = $form;
$this->view->titleS= $result->title;
$this->view->storyS= $result->story;
} catch (Exception $e) {
echo $e;
}
} else {
$this->_helper->redirector->goToRoute(array(
'controller' => 'auth',
'action' => 'index'
));
}
}
In my view:
<?php
try
{
$tmp = $this->form->setAction($this->url());
//$tmp->titleS=$this->title;
//$tmp->storyS=$this->story;
//echo $tmp->title = "aaaaa";
}
catch(Exception $e)
{
echo $e;
}
And when I try to change something in this view I mean give any value different then NULL I have error that I can not do it so is any possibility to reuse this form? Or not?
Thanks!
Zend_Form has method populate(), which sets values of the form based on array data. So just do:
$form->populate($result->current()->toArray());
and form will be populated based on keys from array.