Zend Framework 2 - Gobal Variable that are accessible to controller/model that are initialize in local.php or global.php - zend-framework

Hello everyone please someone help me how to create a global variable in zend framework 2 to be use in table prefix that are accessible in controller and model.
Thanks and regards to all.

In your config/database.local.php you can define which you want globally
<?
return array(
'service_manager' => array(
'factories' => array(
//'Zend\Db\Adapter\Adapter' => 'Zend\Db\Adapter\AdapterServiceFactory',
'Zend\Db\Adapter\Adapter' => function ($serviceManager) {
$adapterFactory = new Zend\Db\Adapter\AdapterServiceFactory();
$adapter = $adapterFactory->createService($serviceManager);
\Zend\Db\TableGateway\Feature\GlobalAdapterFeature::setStaticAdapter($adapter);
return $adapter;
}
),
),
'db' => array(
'driver' => 'pdo',
'dsn' => 'mysql:dbname=testdb;host=localhost',
'username' => 'root',
'password' => '',
),
'msg' => array(
'add' => 'Data Inserted Successfully',
'edit' => 'Data Updated Successfully',
'delete' => 'Data Deleted Successfully',
),
);
?>
Controller File:
DemoController.php
<?php
namespace Demo\Controller;
use Zend\Mvc\Controller\AbstractActionController;
class DemoController extends AbstractActionController
{
public function indexAction($cms_page_name='whyus')
{
/*Call config file to fetch current cms page id-- fetch config file from database.local.php*/
$config = $this->getServiceLocator()->get('Config');
$all_msg = $config['msg'];
}
}
?>

Related

Zend2 Module can't be initialized

Here my Module.php:
<?php
/**
* Zend Framework (http://framework.zend.com/)
*
* #link http://github.com/zendframework/ZendSkeletonModule for the canonical source repository
* #copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com)
* #license http://framework.zend.com/license/new-bsd New BSD License
*/
namespace Users;
use Zend\ModuleManager\Feature\AutoloaderProviderInterface;
use Zend\Mvc\ModuleRouteListener;
class Module implements AutoloaderProviderInterface
{
public function getAutoloaderConfig()
{
return array(
'Zend\Loader\ClassMapAutoloader' => array(
__DIR__ . '/autoload_classmap.php',
),
'Zend\Loader\StandardAutoloader' => array(
'namespaces' => array(
// if we're in a namespace deeper than one level we need to fix the \ in the path
__NAMESPACE__ => __DIR__ . '/src/' . __NAMESPACE__,
),
),
);
}
public function getConfig()
{
return include __DIR__ . '/config/module.config.php';
}
public function onBootstrap($e)
{
// You may not need to do this if you're doing it elsewhere in your
// application
$eventManager = $e->getApplication()->getEventManager();
$moduleRouteListener = new ModuleRouteListener();
$moduleRouteListener->attach($eventManager);
}
}
And here my module.config.php:
<?php
return array(
'controllers' => array(
'invokables' => array(
'Users\Controller\Index' => 'Users\Controller\IndexController',
),
),
'router' => array(
'routes' => array(
'users' => array(
'type' => 'Literal',
'options' => array(
// Change this to something specific to your module
'route' => '/users',
'defaults' => array(
// Change this value to reflect the namespace in which
// the controllers for your module are found
'__NAMESPACE__' => 'Users\Controller',
'controller' => 'Index',
'action' => 'index',
),
),
'may_terminate' => true,
'child_routes' => array(
// This route is a sane default when developing a module;
// as you solidify the routes for your module, however,
// you may want to remove it and replace it with more
// specific routes.
'default' => array(
'type' => 'Segment',
'options' => array(
'route' => '/[:controller[/:action]]',
'constraints' => array(
'controller' => '[a-zA-Z][a-zA-Z0-9_-]*',
'action' => '[a-zA-Z][a-zA-Z0-9_-]*',
),
'defaults' => array(
),
),
),
),
),
),
),
'view_manager' => array(
'template_path_stack' => array(
'users' => __DIR__ . '/../view',
),
),
);
But when I try to see the index page I get this:
( ! ) Fatal error: Uncaught
Zend\ModuleManager\Exception\RuntimeException: Module (Users) could
not be initialized. in
/var/www/html/communicationapp/vendor/zendframework/zendframework/library/Zend/ModuleManager/ModuleManager.php
on line 195
( ! ) Zend\ModuleManager\Exception\RuntimeException: Module (Users) could not be initialized. in /var/www/html/communicationapp/vendor/zendframework/zendframework/library/Zend/ModuleManager/ModuleManager.php
on line 195
Anyone knows what's wrong with this code?
A couple of things to check:
The filename is Module.php - that exact case.
That Module.php is in module/Users (i.e. not in module/Users/src/)
I used internal server of php where I don't have xdebug enabled it got this:
127.0.0.1:48908 [500]: /public/ - Uncaught Zend\ModuleManager\Listener\Exception\InvalidArgumentException: Config being merged must be an array, implement the Traversable interface, or be an instance of Zend\Config\Config. boolean given. in /var/www/html/communicationapp/vendor/zendframework/zendframework/library/Zend/ModuleManager/Listener/ConfigListener.php:342
Stack trace:
0 /var/www/html/communicationapp/vendor/zendframework/zendframework/library/Zend/ModuleManager/Listener/ConfigListener.php(127): Zend\ModuleManager\Listener\ConfigListener->addConfig('Users', false)
1 [internal function]: Zend\ModuleManager\Listener\ConfigListener->onLoadModule(Object(Zend\ModuleManager\ModuleEvent))
2 /var/www/html/communicationapp/vendor/zendframework/zendframework/library/Zend/EventManager/EventManager.php(444): call_user_func(Array, Object(Zend\ModuleManager\ModuleEvent))
3 /var/www/html/communicationapp/vendor/zendframework/zendframework/library/Zend/EventManager/EventManager.php(205): Zend\EventManager\EventManager->triggerListeners('loadModule in /var/www/html/communicationapp/vendor/zendframework/zendframework/library/Zend/ModuleManager/Listener/ConfigListener.php on line 342

Zend framework 2 form element normalization

I am migrating an application from Zend 1 to Zend 2 and starting to desperate with one issue. The application works with different locales and therefore, I need to store the data in a normalized way in the database. In Zend 1 I used this code:
public function normalizeNumber( $value )
{
// get the locale to change the date format
$this->_locale = Zend_Registry::get('Zend_Locale' );
return Zend_Locale_Format::getNumber($value, array('precision' => 2, 'locale' => $this->_locale));
}
Unfortunately Zend 2 does not has this Zend_Locale_Format::getNumber any more and I was not able to figure out what function did replace it. I have tried with NumberFormat, but I get only localized data not normalized. I need this function to normalize data I receive from a form via POST. Can someone give some advice?
thanks
Just to complete my question. The Form element definition I am using is the following:
namespace Profile\Form;
use Zend\Form\Form;
use Zend\InputFilter\InputFilterProviderInterface;
class Profile Extends Form implements InputFilterProviderInterface
{
protected $model;
public function __construct( $model, $name = 'assignmentprofile')
{
parent::__construct( $name );
$this->setAttribute( 'method', 'post');
$this->model = $model;
...
$this->add( array(
'name' =>'CommutingRate',
'type' =>'Zend\Form\Element\Text',
'options' => array( // list of options to add to the element
'label' => 'Commuting rate to be charged:',
'pattern' => '/[0-9.,]/',
),
'attributes' => array( // Attributes to be passed to the HTML lement
'type' =>'text',
'required' => 'required',
'placeholder' => '',
),
));
}
public function getInputFilterSpecification()
{
return array(
...
'CommutingRate' => array(
'required' => true,
'filters' => array(
array( 'name' => 'StripTags', ),
array( 'name' => 'StringTrim'),
array( 'name' => 'NumberFormat', 'options' => array('locale' => 'en_US', 'style' => 'NumberFormatter::DECIMAL', 'type' => 'NumberFormatter::TYPE_DOUBLE',
))
),
'validators' => array(
array( 'name' => 'Float',
'options' => array( 'messages' => array('notFloat' => 'A valid numeric entry is required')),
),
),),
...
);
}
}
As mentioned before, I am able to localized the data and validate it in the localized manner, but i am failing to convert it back to a normalized manner...

ZF2 Form: NumberFormat-filter with localization

hy,
how can I define the NumberFormat-filter for an input in a fieldset which is aware of the current locale? What I want is that numbers like 1000.33 are displayed in the view like this: 1.000,33 (or whatever locale is specified) I have tried it with the InputFilterProviderInterface, but it doesn't has any effect in the view:
<?php
namespace Customer\Form;
use Customer\Entity\OfferDay;
use DoctrineModule\Stdlib\Hydrator\DoctrineObject as DoctrineHydrator;
use Zend\Form\Fieldset;
use Zend\InputFilter\InputFilterProviderInterface;
class OfferDayFieldset extends Fieldset implements InputFilterProviderInterface
{
public function __construct($em)
{
parent::__construct('offerDayFieldset');
$this->setHydrator(new DoctrineHydrator($em))
->setObject(new OfferDay());
$this->add(array(
'name' => 'price',
'type' => 'Text',
'options' => array(
'label' => '',
),
));
}
public function getInputFilterSpecification()
{
return array(
'price' => array(
'required' => false,
'filters' => array(
array(
'name' => 'NumberFormat',
'options' => array(
'locale' => 'de_DE',
),
),
),
),
);
}
}
In the view I output the input via the formRow()-function.
I also know that you can use the NumberFormat-Filter programmatically like this (l18n Filters - Zend Framework 2):
$filter = new \Zend\I18n\Filter\NumberFormat("de_DE");
echo $filter->filter(1234567.8912346);
// Returns "1.234.567,891"
but I wanna use the array-notation.
Has anybody done something like this or something similar?
ok this seems not as trivial as I thought :) but I got a solution.
first define the filter like this:
public function getInputFilterSpecification()
{
return array(
'price' => array(
'required' => false,
'filters' => array(
array(
'name' => 'NumberFormat',
'options' => array(
'locale' => 'de_DE',
'style' => NumberFormatter::DECIMAL,
'type' => NumberFormatter::TYPE_DOUBLE,
),
),
),
),
);
}
whereas locale is the currently used locale. This formats the numbers into the currect format before saving it to the database.
In the view, you can use the filter view helper to convert the numbers to the right format:
<?php
$this->plugin("numberformat")
->setFormatStyle(NumberFormatter::DECIMAL)
->setFormatType(NumberFormatter::TYPE_DOUBLE)
->setLocale("de_DE");
?>
<p>
<?php
$currentElement = $form->get('price');
$currentElement->setValue($this->numberFormat($currentElement->getValue()));
echo $this->formRow($currentElement);
?>
</p>
Result:
Database: 12.345 ->
View: 12,345 -> Database: 12.345

Including settings in to module class

Im my module.config.php file got following excerpt:
return array(
'service_manager' => array(
'aliases' => array(
'Util\Dao\Factory' => 'modelFactory',
),
'factories' => array(
'modelFactory' => function($sm) {
$dbAdapter = $sm->get('Doctrine\ORM\EntityManager');
return new \Util\Dao\Factory($dbAdapter);
},
)
),
'doctrine' => array(
'driver' => array(
'application_entities' => array(
'class' => 'Doctrine\ORM\Mapping\Driver\AnnotationDriver',
'cache' => 'array',
'paths' => array(
__DIR__ . '/../src/Application/Model'
),
),
'orm_default' => array(
'drivers' => array(
'Application\Model' => 'application_entities'
)
),
),
),
How do i put the block "doctrine" in module class?
Well, this is actually fairly simple. Probably your Module class has the method getConfig(). That method usually loads moduleName/config/module.config.php.
So in whatever function you are, simply call the getConfig()-method. This is pure and basic php ;)
//Module class
public function doSomethingAwesome() {
$moduleConfig = $this->getConfig();
$doctrineConfig = isset($moduleConfig['doctrine'])
? $moduleConfig['doctrine']
: array('doctrine-config-not-initialized');
}
However you need to notice that this only includes your Modules config. If you need to gain access to the merged configuration, you'll need to do that in the onBootstrap()-method. Which would be done like this:
//Module class
public function onBootstrap(MvcEvent $mvcEvent)
{
$application = $mvcEvent->getApplication();
$serviceLocator = $application->getServiceLocator();
$mergedConfig = $serviceLocator->get('config');
$doctrineConfig = isset($mergedConfig['doctrine'])
? $mergedConfig['doctrine']
: array('doctrine-config-not-initialized');
}
This works similar if you're attaching to some events...

CakePHP not showing my form errors

I'm trying to create a login form for my web application.
Form validation errros are not showing even though I'm using the $validate Array.
user.php
public $validate = array(
'email' => array(
'notEmpty' => array(
'rule' => 'notEmpty',
'message' => 'notEmpty',
'required' => true
),
'isEmail' => array(
'rule' => 'email'
),
'isUnique' => array(
'rule' => 'isUnique'
)
),
'password' => array(
'notEmpty' => array(
'rule' => 'notEmpty'
),
'minLength' => array(
'rule' => array('minLength', 8)
)
)
);
I can't see an error in my user model, so I show you my controller and my view.
users_controller.php
class UsersController extends AppController {
public $name = 'Users';
public $helpers = array(
'Form'
);
public function login() {
if(!empty($this->data)) {
if ($this->Auth->user() != null) {
$this->Session->setFlash('You are now logged in.', 'flash/success');
$this->redirect('/');
} else {
$this->Session->setFlash('You could not get logged in. Please see errors below.', 'flash/error');
}
}
}
login.ctp
echo $this->Form->create('User', array('action' => 'login'));
echo $this->Form->input('User.email', array(
'label' => __('email address:', true),
'error' => array(
'notEmpty' => __('Email address must not be blank.', true),
'isEmail' => __('Email address must be valid.', true),
)
));
echo $this->Form->input('User.password', array('label' => __('password:', true)));
echo $this->Form->end('Log in');
I hope you can help me. I can't find my mistake since hours. Is there maybe a component or an helper which I need to include?
put echo $this->Session->flash('auth'); before form->create. You don't have to validate login form, Auth will take care of that for you. Read the cookbook: http://book.cakephp.org/view/1250/Authentication
Since you are using Auth, the minLength validation for password is useless.
Validation doesn't occur automatically unless you're saving into the database. Change the first line of the login method in the controller to
if( !empty( $this->data ) && $this->User->validates() ) {
...