Zend Framewok not populating all table field's value - zend-framework

I'm beginner for Zend Framework and using Zend Framework 2.5 veresion. I'm getting same issue and can't be resolved.My Model.php is different than show above.
Model.php
namespace User;
use Zend\ModuleManager\Feature\AutoloaderProviderInterface;
use Zend\ModuleManager\Feature\ConfigProviderInterface;
class Module implements AutoloaderProviderInterface, ConfigProviderInterface{
public function getAutoloaderConfig(){
return array(
'Zend\Loader\StandardAutoloader' => array(
'namespaces' => array(
__NAMESPACE__ => __DIR__.'/src/'.__NAMESPACE__,
)
)
);
}
public function getConfig(){
return include __DIR__. '/config/module.config.php';
}
}
My 'tbl_user' has fields with '_' like 'first_name', 'last_name', 'contact_num' which are not listing. other without underscore '_' fields are listing.
What is wrong with me, can anyone help me?
My output is:
User\Model\User Object
(
[id:protected] => 4
[first_name:protected] =>
[last_name:protected] =>
[contact_num:protected] =>
[email:protected] => dev#email.com
[designation:protected] => C++Programmer
[text:protected] =>
[name:protected] =>
[profile_pic:protected] =>
)
here is my Model 'User.php'
<?php
namespace User\Model;
class User implements UserInterface{
protected $id;
protected $first_name;
protected $last_name;
protected $contact_num;
protected $email;
protected $designation;
protected $text;
protected $name;
protected $profile_pic;
public function getId(){
return $this->id;
}
public function setId($id){
$this->id = $id;
}
public function getName(){
return $this->name;
}
public function setName($first_name, $last_name){
$this->name = $first_name.' '.$last_name;
}
public function getContact(){
return $this->contact_num;
}
public function setContact($contact_num){
$this->contact_num = $contact_num;
}
public function getEmail(){
return $this->email;
}
public function setEmail($email){
$this->email = $email;
}
public function getDesignation(){
return $this->designation;
}
public function setDesignation($designation){
$this->designation = $designation;
}
public function getProfilePic(){
return $this->profile_pic;
}
public function setProfilePic($profile_pic){
$this->profile_pic = $profile_pic;
}
/*public function getText(){
return $this->text;
}
public function setText($text){
$this->text = $text;
}*/
}
?>
and this is my 'ZendDbSqlMapper.php'
<?php
namespace User\Mapper;
use User\Model\UserInterface;
use Zend\Db\Adapter\AdapterInterface;
use Zend\Db\Adapter\Driver\ResultInterface;
use Zend\Db\ResultSet\HydratingResultSet;
use Zend\Stdlib\Hydrator\HydratorInterface;
use Zend\Db\Sql\Sql;
use Zend\Db\Sql\Insert;
use Zend\Db\Sql\Update;
class ZendDbSqlMapper implements UserMapperInterface{
protected $dbAdapter;
protected $hydrator;
protected $userPrototype;
public function __construct(
AdapterInterface $dbAdapter,
HydratorInterface $hydrator,
UserInterface $userPrototype
){
$this->dbAdapter = $dbAdapter;
$this->hydrator = $hydrator;
$this->userPrototype = $userPrototype;
}
public function find($id){
$sql = new Sql($this->dbAdapter);
$select = $sql->select('tbl_users');
$select->where(array('id = ?' => $id));
$stmt = $sql->prepareStatementForSqlObject($select);
$result = $stmt->execute();
if($result instanceof ResultInterface && $result->isQueryResult() && $result->getAffectedRows()){
return $this->hydrator->hydrate($result->current(), $this->userPrototype);
}
throw new \InvalidArgumentException("User with given ID:{$id} not found");
}
public function findAll(){
$sql = new Sql($this->dbAdapter);
$select = $sql->select('tbl_users');
$stmt = $sql->prepareStatementForSqlObject($select);
$result = $stmt->execute();
//\Zend\Debug\Debug::dump($result); die;
if($result instanceof ResultInterface && $result->isQueryResult()){
//$resultSet = new ResultSet();
$resultSet = new HydratingResultSet($this->hydrator, $this->userPrototype);
//\Zend\Debug\Debug::dump($resultSet->initialize($result)); die;
return $resultSet->initialize($result);
}
return array();
}
public function save(UserInterface $userObject){
$userData = $this->hydrator->extract($userObject);
unset($userData['id']);
if($userObject->getId()){
$action = new Update('tbl_users');
$action->setData($userData);
$action->where(array('id = ?' => $userObject->getId()));
}else{
$action = new Insert('tbl_users');
$action->values($userData);
}
$sql = new Sql($this->dbAdapter);
$stmt = $sql->prepareStatementForSqlObject($action);
$result = $stmt->execute();
if($result instanceof ResultInterface){
if($newId = $result->getGeneratedValue()){
$userObject->setId($newId);
}
return $userObject;
}
return new \Exception("Database Error");
}
}
?>
here is 'ListController.php'
<?php
namespace User\Controller;
use User\Service\UserServiceInterface;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
class ListController extends AbstractActionController{
protected $userService;
public function __construct(UserServiceInterface $userService){
$this->userService = $userService;
}
public function indexAction(){
return new ViewModel(array(
'users' => $this->userService->findAllUsers()
));
}
public function detailAction(){
$id = $this->params()->fromRoute('id');
try {
$user = $this->userService->findUser($id);
}catch(\InvalidArgumentException $ex){
return $this->redirect()->toRoute('user');
}
return new ViewModel(
array( 'user' =>$user )
);
}
}
?>
thank you.

Related

It doesn't find my class even if it exists

This is the error:
Fatal error: Class 'Admin_Controller' not found in C:\xampp\htdocs\ci-blog-master\application\modules\admin\controllers\Settings.php on line 4
A PHP Error was encountered
Severity: Error
Message: Class 'Admin_Controller' not found
Filename: controllers/Settings.php
Line Number: 4
Backtrace:
And here is my code for :
Admin_controller.php
<?php defined('BASEPATH') OR exit('No direct script access allowed');
class Admin_Controller extends MY_Controller {
function __construct()
{
parent::__construct();
}
}
And here is my Settings.php
class Settings extends Admin_Controller {
public function __construct(){
parent::__construct();
$this->allow_group_access(array('admin'));
$this->load->model('Category');
$this->data['parent_menu'] = 'post';
}
public function index(){
$this->session->set_flashdata('message',message_box('Setting is the coming soon feature!','danger'));
redirect('admin/posts/index');
$config['base_url'] = site_url('admin/categories/index/');
$config['total_rows'] = count($this->Category->find());
$config['per_page'] = 10;
$config["uri_segment"] = 4;
$this->data['categories'] = $this->Category->find($config['per_page'], $this->uri->segment(4));
$this->data['pagination'] = $this->bootstrap_pagination($config);
$this->render('admin/categories/index');
}
public function add(){
$this->form_validation->set_rules('name', 'name', 'required|is_unique[categories.name]');
$this->form_validation->set_rules('status', 'status', 'required');
if($this->form_validation->run() == true){
$category = array(
'name' => $this->input->post('name'),
'status' => $this->input->post('status')
);
$this->Category->create($category);
$this->session->set_flashdata('message',message_box('Category has been saved','success'));
redirect('admin/categories/index');
}
$this->render('admin/categories/add');
}
public function edit($id = null){
if($id == null){
$id = $this->input->post('id');
}
$this->form_validation->set_rules('name', 'name', 'required');
$this->form_validation->set_rules('status', 'status', 'required');
if($this->form_validation->run() == true){
$category = array(
'name' => $this->input->post('name'),
'status' => $this->input->post('status')
);
$this->Category->update($category, $id);
$this->session->set_flashdata('message',message_box('Category has been saved','success'));
redirect('admin/categories/index');
}
$this->data['category'] = $this->Category->find_by_id($id);
$this->render('admin/categories/edit');
}
public function delete($id = null){
if(!empty($id)){
$this->Category->delete($id);
$this->session->set_flashdata('message',message_box('Category has been deleted','success'));
redirect('admin/categories/index');
}else{
$this->session->set_flashdata('message',message_box('Invalid id','danger'));
redirect('admin/categories/index');
}
}
public function update_multiple(){
#test commit
#test commit di branch sendiri
}
}
You can put more classes in MY_Controller.php file:
<?php defined('BASEPATH') OR exit('No direct script access allowed');
class MY_Controller extends CI_Controller
{
public function __construct()
{
parent::__construct();
}
public function some_mycontr_method()
{
// appropriate code here
}
}
class Admin_Controller extends MY_Controller
{
public function __construct()
{
parent::__construct();
}
public function some_admin_method()
{
// appropriate code here
}
}

Symfony2, Keep form data across redirect

How to use session for retrieving data during redirect? I am getting the error message: "exception 'Symfony\Component\Form\Exception\AlreadySubmittedException' with message 'You cannot change the data of a submitted form."
C:\Bitnami\wampstack-5.5.30-0\sym_prog\proj3_27\src\MeetingBundle\Controller\UserController.php
/**
* Creates a new User entity.
*
* #Route("/new", name="user_new")
* #Method({"GET", "POST"})
*/
public function newAction(Request $request)
{
$user = new User();
$form = $this->createForm(new UserType(), $user);
$form->handleRequest($request);
$session = $this->getRequest()->getSession();
$form->setData(unserialize($session->get('userFilter')));
if ( $form->isSubmitted() && $form->isValid() ) {
$session->set( 'userFilter', serialize($form->getData()) );
$em = $this->getDoctrine()->getManager();
$em->persist($user);
$em->flush();
return $this->redirectToRoute('user_edit', array('id' => $user->getId()));
}
return $this->render('MeetingBundle::user/new.html.twig', array(
'user' => $user,
'form' => $form->createView(),
));
} // public function newAction(Request $request)
C:\Bitnami\wampstack-5.5.30-0\sym_prog\proj3_27\src\MeetingBundle\EventListener\ExceptionListener.php
<?php
namespace MeetingBundle\EventListener;
use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Router;
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
use Symfony\Bundle\FrameworkBundle\Templating\EngineInterface;
//every time the Kernel throws the kernel.exception event, the function onKernelException() is called.
/* also must create service :
meeting.exception_listener:
class: MeetingBundle\EventListener\ExceptionListener
arguments: [#templating, #kernel, #router]
tags:
- { name: kernel.event_listener, event: kernel.exception, method: onKernelException }
*/
class ExceptionListener
{
protected $templating;
protected $kernel;
protected $router;
public function __construct( EngineInterface $templating, $kernel, Router $router)
{
$this->templating = $templating;
$this->kernel = $kernel;
$this->router = $router;
}
public function onKernelException(GetResponseForExceptionEvent $event)
{
$exception = $event->getException();
$request=$event->getRequest();
$referer = $event->getRequest()->headers->get('referer');
$msg="";
$excStr=$exception->__toString(); // returns string finally!
$bdup=strpos( $excStr , 'Integrity constraint violation: 1062 Duplicate entry' );
if($bdup) {
$msg=" This username is already taken. Choose another username. ";
}
if(strlen($msg)!=0) {
// flash messsages are displayed in layout.html
$request->getSession()
->getFlashBag()
->add('Error', $msg);
}
$response = new RedirectResponse($referer); // redirect to the error page
if ($exception instanceof HttpExceptionInterface) {
$response->setStatusCode($exception->getStatusCode());
$response->headers->replace($exception->getHeaders());
} else {
$response->setStatusCode(Response::HTTP_INTERNAL_SERVER_ERROR);
}
$event->setResponse($response);
}
}

How to create a complete custom form

how have I to create a custom Magento form? I don't need any extension or sample that mention the contact form. I mean that I need to understand how Magento with the modified Zend form handler works.
So the question is:
Does anybody have a code example for Magento created in a controller ?
<?php
class Mage_Contacts_IndexController extends Mage_Core_Controller_Front_Action
{
const XML_PATH_EMAIL_RECIPIENT = 'contacts/email/recipient_email';
const XML_PATH_EMAIL_SENDER = 'contacts/email/sender_email_identity';
const XML_PATH_EMAIL_TEMPLATE = 'contacts/email/email_template';
const XML_PATH_ENABLED = 'contacts/contacts/enabled';
public function preDispatch()
{
parent::preDispatch();
if( !Mage::getStoreConfigFlag(self::XML_PATH_ENABLED) ) {
$this->norouteAction();
}
}
public function indexAction()
{
$this->loadLayout();
$this->getLayout()->getBlock('contactForm')
->setFormAction( Mage::getUrl('*/*/post') );
$this->_initLayoutMessages('customer/session');
$this->_initLayoutMessages('catalog/session');
$this->renderLayout();
}
public function postAction()
{
$post = $this->getRequest()->getPost();
if ( $post ) {
$translate = Mage::getSingleton('core/translate');
/* #var $translate Mage_Core_Model_Translate */
$translate->setTranslateInline(false);
try {
$postObject = new Varien_Object();
$postObject->setData($post);
$error = false;
if (!Zend_Validate::is(trim($post['name']) , 'NotEmpty')) {
$error = true;
}
if (!Zend_Validate::is(trim($post['comment']) , 'NotEmpty')) {
$error = true;
}
if (!Zend_Validate::is(trim($post['email']), 'EmailAddress')) {
$error = true;
}
if (Zend_Validate::is(trim($post['hideit']), 'NotEmpty')) {
$error = true;
}
if ($error) {
throw new Exception();
}
$mailTemplate = Mage::getModel('core/email_template');
/* #var $mailTemplate Mage_Core_Model_Email_Template */
$mailTemplate->setDesignConfig(array('area' => 'frontend'))
->setReplyTo($post['email'])
->sendTransactional(
Mage::getStoreConfig(self::XML_PATH_EMAIL_TEMPLATE),
Mage::getStoreConfig(self::XML_PATH_EMAIL_SENDER),
Mage::getStoreConfig(self::XML_PATH_EMAIL_RECIPIENT),
null,
array('data' => $postObject)
);
if (!$mailTemplate->getSentSuccess()) {
throw new Exception();
}
$translate->setTranslateInline(true);
Mage::getSingleton('customer/session')->addSuccess(Mage::helper('contacts')->__('Your inquiry was submitted and will be responded to as soon as possible. Thank you for contacting us.'));
$this->_redirect('*/*/');
return;
} catch (Exception $e) {
$translate->setTranslateInline(true);
Mage::getSingleton('customer/session')->addError(Mage::helper('contacts')->__('Unable to submit your request. Please, try again later'));
$this->_redirect('*/*/');
return;
}
} else {
$this->_redirect('*/*/');
}
}
}

Zend Framework - Passing a variable request in controller

In one of these php frameworks I've noticed a posibility to request the object Request in action as $this->request->paramName
class MyRequest extends Zend_Controller_Request_Http{
public $params = array();
public function __construct() {
$this->params = $this->getParams();
parent::__construct();
}
public function __get($name) {
if (isset($this->_params[$name])) {
return $this->_params[$name];
}
}
public function __isset($name) {
return isset($this->_params[$name]);
}
}
in MyController I've added variable request
public $request = null;
How can I change that standart Request to my one?
public function __construct(
Zend_Controller_Request_Abstract $request,
Zend_Controller_Response_Abstract $response,
array $invokeArgs = array()) {
$request = new MyRequest();
parent::__construct($request, $response, $invokeArgs);
$this->request = $this->getRequest();
}
This function has given no results.
Option 1 is make method _initRequest() in bootstrap:
protected function _initRequest() {
$this->bootstrap ( 'FrontController' );
$front = $this->getResource ( 'FrontController' );
$request = $front->getRequest ();
if (null === $front->getRequest ()) {
$request = new MyRequest();
$front->setRequest ( $request );
}
return $request;
}
A bit dirty and untested solution. Would love to hear if it works.
//Bootstrap:
public function _initRequest()
{
$this->bootstrap('frontController');
$front = $this->getResource('frontController');
$front->setRequest(new MyRequest());
}
Try this it might help you:
in controller file
public function exampleAction(){
$result = $this->_request;
$model = new Employer_Model_JobInfo();
$results = $model->sample($result);
}
// the above line stores the values sent from the client side in $result.then sends that values to Model file with parameter $result ..
in model file
class Employer_Model_JobInfo extends Gears_Db_Table_Abstract{
public function sample($param){
$paramVal = $param->getParam('name');
$paramVal1 = $param->getParam('email');
}
}
The name and email are what name used to sent the data from client to server.

Doctrine ODM (MongoDB) - Get a complete array of an object?

iv'e got a problem to receive a complete array (with all the data of the embedded childs collections and objects) of my document. My document looks exactly like this one:
use Doctrine\Common\Collections\ArrayCollection;
/** #Document(collection="user") */
class User {
/** #Id */
protected $id;
/** #String */
protected $firstname;
/** #String */
protected $lastname;
/** #EmbedMany(targetDocument="Email") */
protected $email;
/** #EmbedMany(targetDocument="Address") */
protected $address;
/** #EmbedMany(targetDocument="Subscription") */
protected $subscription;
/**
* Construct the user
*
* #param array $properties
* #throws User_Exception
*/
public function __construct(array $properties = array()) {
$this->email = new ArrayCollection();
$this->address = new ArrayCollection();
$this->subscription = new ArrayCollection();
foreach($properties as $name => $value){
$this->{$name} = $value;
}
}
...
I need a complete array of an embedded collection to output the whole data and render it by json. My query looks like this:
$query = $this->_dbContainer->getDocumentManager()->createQueryBuilder('User')->field('deletedAt')->exists(false);
$result = $query->field('id')->equals($id)->getQuery()->getSingleResult();
For example, if i call the toArray() function like this:
$array = $result->getSubscription()->toArray();
print_r($array);
Then the output ist just an array on top level:
[0] => Object Subscription...
[1] => Object Subscription...
...
How can i easily get an array like this?
[0] => array('subscriptionLabel' => 'value1', 'field' => 'value1', ...)
[1] => array('subscriptionLabel' => 'value2', 'field' => 'value2', ...)
...
Are there any best practises or maybe some missing helper scripts to prevent something ugly like this code (how to handle child -> child -> child szenarios? ugly -> ugly ugly -> ugly ugly ugly -> ...):
$example = array();
foreach($result->getSubscription() as $key => $subscription) {
$example[$key]['subscriptionLabel'] = $subscription->getSubscriptionLabel();
$example[$key]['field'] = $subscription->getField();
...
}
Thanks a lot,
Stephan
Damn simple answer! Just use ->hydrate(false) and it's done.
For find queries the results by
default are hydrated and you get
document objects back instead of
arrays. You can disable this and get
the raw results directly back from
mongo by using the hydrate(false)
method:
<?php
$users = $dm->createQueryBuilder('User')
->hydrate(false)
->getQuery()
->execute();
print_r($users);
I ran into this same need recently and solved it by creating a base class for all my entities with a toArray() function and JsonSerializable. It converts all nested references as well.
/**
* #ODM\MappedSuperclass
*/
abstract class BaseDocument implements \JsonSerializable
{
public function jsonSerialize() {
return $this->toArray();
}
public function toArray() {
$getter_names = get_class_methods(get_class($this));
$gettable_attributes = array();
foreach ($getter_names as $key => $funcName) {
if(substr($funcName, 0, 3) === 'get') {
$propName = strtolower(substr($funcName, 3, 1));
$propName .= substr($funcName, 4);
$value = $this->$funcName();
if (is_object($value) && get_class($value) == 'Doctrine\ODM\MongoDB\PersistentCollection') {
$values = array();
$collection = $value;
foreach ($collection as $obj) {
$values[] = $obj->toArray();
}
$gettable_attributes[$propName] = $values;
}
else {
$gettable_attributes[$propName] = $value;
}
}
}
return $gettable_attributes;
}
}
Now I can serialize the entity as an array or json string with json_encode($doc). Bam.
Tanks to Rooster242, you can even recursively apply toArray to embedded documents which themself extends BaseDocument by using the php is_subclass_of function :
/**
* #ODM\MappedSuperclass
*/
abstract class BaseDocument implements \JsonSerializable
{
public function jsonSerialize() {
return $this->toArray();
}
public function toArray() {
$getter_names = get_class_methods(get_class($this));
$gettable_attributes = array();
foreach ($getter_names as $key => $funcName) {
if(substr($funcName, 0, 3) === 'get') {
$propName = strtolower(substr($funcName, 3, 1));
$propName .= substr($funcName, 4);
$value = $this->$funcName();
if (is_object($value) && is_subclass_of($value,"BaseDocument")) {
$gettable_attributes[$propName] = $value->toArray();
} elseif (is_object($value) && get_class($value) == 'Doctrine\ODM\MongoDB\PersistentCollection') {
$values = array();
$collection = $value;
foreach ($collection as $obj) {
if (is_subclass_of($obj,"BaseDocument")) {
$values[] = $obj->toArray();
} else {
$values[] = $obj;
}
}
$gettable_attributes[$propName] = $values;
}
else {
$gettable_attributes[$propName] = $value;
}
}
}
return $gettable_attributes;
}
}
Just made this a bit more generic, works perfect. Just dont forget to extend it with your documents and embeds.
<?php
namespace App\Documents;
use Doctrine\ODM\MongoDB\Mapping\Annotations as ODM;
use Doctrine\ODM\MongoDB\PersistentCollection;
/**
* #ODM\MappedSuperclass
*/
abstract class BaseDocument implements \JsonSerializable
{
/**
* #return array
*/
public function jsonSerialize()
{
return $this->toArray();
}
/**
* #return array
*/
public function toArray()
{
$getterNames = get_class_methods(get_class($this));
$gettableAttributes = [];
foreach ($getterNames as $funcName) {
if (substr($funcName, 0, 3) !== 'get') {
continue;
}
$propName = strtolower(substr($funcName, 3, 1));
$propName .= substr($funcName, 4);
$value = $this->$funcName();
$gettableAttributes[$propName] = $value;
if (is_object($value)) {
if ($value instanceof PersistentCollection) {
$values = [];
$collection = $value;
foreach ($collection as $obj) {
/** #var BaseDocument $obj */
if ($obj instanceof \JsonSerializable) {
$values[] = $obj->toArray();
} else {
$values[] = $obj;
}
}
$gettableAttributes[$propName] = $values;
} elseif ($value instanceof \JsonSerializable) {
/** #var BaseDocument $value */
$gettableAttributes[$propName] = $value->toArray();
}
}
}
return $gettableAttributes;
}
}