I have this code (which works fine):
Class SsoRequserTable
public function fetchAll()
{
$select = new Select();
$select->from("sso_requser");
$select->join('sso_workunit', 'sso_workunit.sso_workunit_id = sso_requser.sso_workunit_id', array("unitname"), 'left');
echo $select->getSqlString();
$result = $this->tableGateway->selectWith($select);
return $result;
}
class SsoRequser
class SsoRequser{
public $sso_requser_id;
public $firstname;
public $lastname;
public $fullname;
public $sso_workunit_id;
public function exchangeArray($data){
$this->sso_requser_id = (!empty($data['sso_requser_id'])) ? $data['sso_requser_id'] : null;
$this->firstname = (!empty($data['firstname'])) ? $data['firstname'] : null;
$this->lastname = (!empty($data['lastname'])) ? $data['lastname'] : null;
$this->fullname = (!empty($data['fullname'])) ? $data['fullname'] : null;
$this->sso_workunit_id = (!empty($data['sso_workunit_id'])) ? $data['sso_workunit_id'] : null;
}
}
Module.php
public function getServiceConfig() {
return array(
'invokables' => array(
// 'Aclplugin' => 'Auth\Controller\Plugin\Aclplugin',
),
'factories' => array('SSO\Model\SsoRequserTable' => function($sm) {
$tableGateway = $sm->get('SsoRequserTableGateway');
$table = new SsoRequserTable($tableGateway);
return $table;
},
'SsoRequserTableGateway' => function ($sm) {
$dbAdapter = $sm->get('postgresql_adapter');
$resultSetPrototype = new HydratingResultSet();
$resultSetPrototype->setObjectPrototype(new SsoRequser());
return new TableGateway('sso_requser', $dbAdapter, null, $resultSetPrototype);
},
),
);
}
But I can`t get the sso_workunit columns to work. I have read the Zend Documentation and nothing effectively worked for me. I need name to have an alias "unitname".
And i got the message error "Undefined property: SSO\Model\Entity\SsoRequser::$unitname "
Whether I should add unitname in class SsoRequser ?
Anyone can help me ?
Related
I have added a field to my Prestashop registration form and I want to display and update it from the user interface. I already have a good part since the field appears, we can fill it and it is displayed in the database. The problem is that I am missing an essential part; the possibility to display it in the user interface and the update, can someone help me ? I have a get function and I think I need a set function too to be able to update, but I don't know what to write in it
My module files
<?php
if (!defined('_PS_VERSION_')) {
exit;
}
use PrestaShop\PrestaShop\Adapter\Presenter\Object\ObjectPresenter;
require_once dirname(__FILE__) . '/classes/CustomerFonction.php';
class AddJob extends Module
{
public function __construct()
{
$this->name = 'addjob';
$this->tab = 'others';
$this->version = '1.0.0';
$this->author = 'advisa';
$this->need_instance = 0;
$this->ps_versions_compliancy = [
'min' => '1.6',
'max' => '1.7.99',
];
$this->bootstrap = true;
parent::__construct();
$this->displayName = $this->l('AddJob');
$this->description = $this->l('Add job in registration form');
}
public function install()
{
return parent::install() &&
$this->installSql() &&
$this->registerHook('additionalCustomerFormFields') &&
$this->registerHook('actionCustomerAccountAdd');
}
public function uninstall()
{
return (
parent::uninstall()
);
}
/*
public function installSql()
{
$sqlInstall = "ALTER TABLE " . _DB_PREFIX_ . "customer "
. "ADD fonction VARCHAR(255) NULL";
return Db::getInstance()->execute($sqlInstall);
} */
public function installSql()
{
$sqlQuery = array();
$sqlQuery[] = 'CREATE TABLE IF NOT EXISTS `' . _DB_PREFIX_ . 'addjob_addfonction` (
`id_addfonction` INT(10) PRIMARY KEY NOT NULL AUTO_INCREMENT,
`id_customer` INT(10),
`fonction` VARCHAR(255)
)';
$db = Db::getInstance();
foreach ($sqlQuery as $query) {
if (!$db->execute($query)) {
return false;
}
}
return true;
}
public function hookAdditionalCustomerFormFields($param)
{
$field = array();
$field['fonction'] = (new FormField())
->setName('fonction')
->setType('text')
//->setRequired(true)
->setLabel($this->l('Fonction'));
if($this->context->customer->id !== null){
$data = new CustomerFonction($this->context->customer->id);
$field['fonction']->setValue($data->fonction ?? '');
}
return $field;
}
public function hookActionCustomerAccountAdd($param)
{
$customeField = new CustomerFonction();
$customeField->id_customer = $param['newCustomer']->id;
$customeField->fonction = Tools::getValue('fonction', '');
$customeField->add();
}
public function hookActionCustomerAccountUpdate($param)
{
$customerId = $this->context->customer->id;
$customerField = new CustomerFonction($customerId);
$customerField->id_customer = $customerId;
$customerField->fonction = Tools::getValue('fonction', '');
$customerField->save();
}
}
And my ObjectModel classes
<?php
class CustomerFonction extends ObjectModel
{
public $id_addfonction;
public $id_customer;
public $fonction;
public static $definition = [
'table' => 'addjob_addfonction',
'primary' => 'id_addfonction',
'multilang' => false,
'fields' => [
'id_customer' => ['type' => self::TYPE_INT],
'fonction' => ['type'=>self::TYPE_STRING, 'size'=> 255],
],
];
public static function getFonctionByCustomer($id_customer): ?string
{
$sql = new DbQuery();
$sql->select('fonction');
$sql->from('addjob_fonction');
$sql->where('id_customer = ' . $id_customer);
return Db::getInstance()->getValue($sql);
}
public static function getByCustomerId(): self
{
}
public static function setFonctionByCustomer(string $fonction, $id): self
{
}
}
how can i work with JSONB (postgresql) in zend framework 3?.
for example i want make query's like this
SELECT id, data->'title' AS title, data->'description' as description FROM tablename
SELECT jsonb_array_elements_text(data->'tags') as tag FROM tablename WHERE id = 1;
Or EXECUTE a function like a
SELECT myFunction()
jsonb_each(jsonb)
INSERT INTO tablename VALUES (1,'{"title": "title 1","category":"category 2"}')
UPDATE tablename SET data = jsonb_set(data,'{"image","quality"}','{" copyright":"company X","registered":true}') where id=2;
ETC.
I have a model and only get the id value
<?php
namespace EntityModel\Model;
class Entity
{
public $idEntity;
public $title;
public $description;
public $access;
public $category;
public $isVisible;
public $urlProyect;
public $urlDownload;
public $pedagogicUse;
public $PublicatorUser;
/**
* [exchangeArray description]
* #param array $data [description]
* #return [type] [description]
*/
public function exchangeArray(array $data)
{
$this->id = !empty($data['id']) ? $data['id'] : null;
$this->title = !empty($data['title']) ? $data['title'] : null;
$this->description = !empty($data['description']) ? $data['description'] : null;
$this->access = !empty($data['access']) ? $data['access'] : null;
$this->category = !empty($data['category']) ? $data['category'] : null;
$this->isVisible = !empty($data['isvisible']) ? $data['isvisible'] : null;
$this->urlProyect = !empty($data['urlproyect']) ? $data['urlproyect'] : null;
$this->urlDownload = !empty($data['urldownload']) ? $data['urldownload'] : null;
$this->PedagogicUse = !empty($data['pedagogicUse']) ? $data['pedagogicUse'] : null;
$this->publicatorUser = !empty($data['publicatoruser']) ? $data['publicatoruser'] : null;
}
}
I want to return the jsonb object in the exchangeArray method like id=>4,title=>"title"
How can i implement this ideas, i follow the tutotial from ZF3 and i don't know how implement, maybe here is not the place for this question, but i appreciate if you give me a feedback, i don´t want to use ORM for this project. Thanks
This is the model file we can make a query with this methods
class EntityTable
{
protected $tableGateway;
protected $dbAdapter;
public function __construct(TableGatewayInterface $tableGateway)
{
$this->tableGateway = $tableGateway;
$this->dbAdapter = $tableGateway->adapter;
}
public function getAllFromQuery()
{
$query = $this->dbAdapter->query("SELECT count(*) FROM tablename WHERE data ? 'isVisible';", Adapter::QUERY_MODE_EXECUTE);
$data = $query->toArray();
return $data;
}
it´s important than you have declare in your db adapter
'db' => [
'driver' => 'Pgsql', // pdo not support all the pg_ functions
'database' => 'database',
'username' => 'user',
'password' => 'pass'
]
In a Action call
public function indexAction()
{
return new ViewModel([
'data' =>$this->table->getAllFromQuery()
]);
}
and the view
<?= var_dump($this->data) ?>
AND THE RESULT IS THAT
array(1) { [0]=> array(1) { ["count"]=> string(1) "6" } }
Well this is a want to take from the data base but, how can i pass the data array into a entity exchangeArray method??
i get it!!
public function getAllFromQuery()
{
$query = $this->dbAdapter->createStatement("SELECT id,
data->>'title' as title,
data->>'acess' as access,
data->>'category' as category
FROM tablename");
$data= $query->execute();
/* OR if you want execute a function from postgres */
//$query = $this->dbAdapter->query("SELECT totalregistrosdinamico('tablename')", Adapter::QUERY_MODE_EXECUTE);
$resultSetPrototype = new ResultSet();
$resultSetPrototype->initialize($data);
$resultSetPrototype->setArrayObjectPrototype(new Model\EntityName());
return $resultSetPrototype;
}
I need to retrive data from 2 tables using join.
I have this code, but it fails with Call to undefined method Zend\Db\ResultSet\ResultSet::from():
public function getUsers($id){
$id = (int) $id;
$rowset = $this->tableGateway->select()->from(array('u' => 'user'))
->join(array('l' => 'levels'),
'u.user_id = l.id_user');
$row = $rowset->current();
if (!$row) {
throw new \Exception("Could not find row $id");
}
return $row;
}
The SQL command would be:
select user.*,levels.name from user left join levels on user.user_id=levels.id_user
Thanks
UPDATE
Using #Mohamad changes I get:
The table name of the provided select object must match that of the table
My UsersTable.php looks like this now:
<?php
// module/Users/src/Users/Model/UsersTable.php:
namespace Users\Model;
use Zend\Db\TableGateway\TableGateway;
use Zend\Db\Sql\Select;
class UsersTable
{
protected $tableGateway;
public function __construct(TableGateway $tableGateway)
{
$this->tableGateway = $tableGateway;
}
public function fetchAll()
{
$select = new Select();
$select->from('levels');
$select->join('user', 'levels.id=user.user_id',Select::SQL_STAR,Select::JOIN_RIGHT);
$rowset = $this->tableGateway->selectWith ( $select );
$resultSet = $rowset->current();
if (!$resultSet) {
throw new \Exception("Could not find row $id");
}
return $resultSet;
}
i think you must pass two TableGetway to UserTable construct. you have to change Module.php
look this:
public function getServiceConfig()
{
return array(
'factories' => array(
'User\Model\UserTable' => function($sm) {
$userTableGateway = $sm->get('UserTableGateway');
$levelTableGateway = $sm->get('LevelTableGateway');
$table = new UserTable($userTableGateway,$levelTableGateway);
return $table;
},
'UserTableGateway' => function ($sm) {
$dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
$resultSetPrototype = new ResultSet();
$resultSetPrototype->setArrayObjectPrototype(new User());
return new TableGateway('user', $dbAdapter, null, $resultSetPrototype);
},
'LevelTableGateway' => function ($sm) {
$dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
$resultSetPrototype = new ResultSet();
$resultSetPrototype->setArrayObjectPrototype(new Level());
return new TableGateway('level', $dbAdapter, null, $resultSetPrototype);
},
),
);
}
then in your model:
protected $userTableGateway;
protected $levelTableGateway;
public function __construct($userTableGateway,$levelTableGateway)
{
$this->userTableGateway = $userTableGateway;
$this->levelTableGateway = $levelTableGateway;
}
public function fetchAll()
{
$select = new Select();
$select->from('levels');
$select->join('user', 'levels.id=user.user_id',Select::SQL_STAR,Select::JOIN_RIGHT);
$rowset = $this->levelTableGateway->selectWith ( $select );
$resultSet = $rowset->current();
if (!$resultSet) {
throw new \Exception("Could not find row $id");
}
return $resultSet;
}
i hope helped you
I want to get 3 separate row from 'cms' table.but all time i only got first row why?
My Cms.php page is:
<?php
namespace Front\Model;
use Zend\Db\TableGateway\AbstractTableGateway;
class Cms extends AbstractTableGateway {
public function __construct($adapter) {
$this->table = 'cms';
$this->adapter = $adapter;
}
public function getCmsContent($id){
$id = (int) $id;
$rowset = $this->select(array('id'=>$id));
if (!$row = $rowset->current()){
throw new \Exception ('Row not found');
}
return $row;
}
}
My Controller is :FrontController.php is:
use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
use Front\Model\Cms;
use Front\Model\Setting;
use Front\Model\Slider;
class FrontController extends AbstractActionController
{
public function indexAction()
{
$this->layout()->slider_data = $this->getSlider()->fetchAll();
$this->layout()->setting_data = $this->getSetting()->getSettingContent(1);
return array('cms_data'=>$this->getCms()->getCmsContent('1,2,3'));
}
public function getSlider(){
return $this->getServiceLocator()->get('Front/Model/Slider');
}
public function getCms(){
return $this->getServiceLocator()->get('Front\Model\Cms');
}
public function getSetting(){
return $this->getServiceLocator()->get('Front/Model/Setting');
}
}
My Model is:
namespace Front;
class Module
{
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';
}
// Add this method:
public function getServiceConfig()
{
return array(
'factories' => array(
'Front\Model\AlbumTable' => function($sm) {
$dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
$table = new \Front\Model\AlbumTable($dbAdapter);
return $table;
},
'Front\Model\Cms' => function($sm) {
$dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
$table = new \Front\Model\Cms($dbAdapter);
return $table;
},
'Front\Model\Setting' => function($sm) {
$dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
$table = new \Front\Model\Setting($dbAdapter);
return $table;
},
'Front\Model\Slider' => function($sm) {
$dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
$table = new \Front\Model\Slider($dbAdapter);
return $table;
},
),
);
}
}
?>
My View:index.php Page is:
<?php print_R($cms_data); ?>
try this code block and change the $condition according to you
public function getCmsContent($id){
$id = (int) $id;
$select = new Select();
$select->from(array('t' => $this->table))
->where(array($condition));
$statement = $this->adapter->createStatement();
$select->prepareStatement($this->adapter, $statement);
$result = $statement->execute();
$rows = array();
if ($result->count()) {
$rows = new ResultSet();
return $rows->initialize($result)->toArray();
}
}
You try:
class Cms extends AbstractTableGateway {
public function __construct($adapter) {
$this->table = 'cms';
$this->adapter = $adapter;
}
public function getCmsContent($id){
return $this->select(array(
new Expression('id IN (?)', array($id)),
));
}
}
Get contents
$contents = $this->getCms()->getCmsContent(array(1, 2, 3));
$results = array();
foreach($contents as $content){
$results[] = $content;
}
print_r($results);
i am trying to insert user data using AbstractTableGateway in UserTable. But i am receiving Error .
I have try solution a lot but i am not to understand what is the problem here.
C:\wamp\www\1625\vendor\ZF2\library\Zend\Db\ResultSet\ResultSet.php:68
Message:
Object must be of type ArrayObject, or at least implement exchangeArray
I am trying to save data using
$user = new User();
$user->userExchangeData($user_data);
$this->getUserTable()->saveUser($object);
My Usertable Model is
<?php
namespace User\Model;
use Zend\Db\TableGateway\AbstractTableGateway;
use Zend\Db\Adapter\Adapter;
use Zend\Db\ResultSet\ResultSet;
class UserTable extends AbstractTableGateway
{
protected $table = 'y2m_user';
public function __construct(Adapter $adapter)
{
$this->adapter = $adapter;
$this->resultSetPrototype = new ResultSet();
$this->resultSetPrototype->setArrayObjectPrototype(new User());
$this->initialize();
}
public function fetchAll()
{
$resultSet = $this->select();
return $resultSet;
}
public function getUser($user_id)
{
$id = (int) $user_id;
$rowset = $this->select(array('user_id' => $user_id));
$row = $rowset->current();
if (!$row) {
throw new \Exception("Could not find row $user_id");
}
return $row;
}
public function saveUser(User $user)
{
$data = array(
'user_given_name' => $user->user_given_name,
'user_first_name' => $user->user_first_name,
'user_middle_name' => $user->user_middle_name,
'user_last_name' => $user->user_last_name,
'user_status' => $user->user_status,
'user_added_ip_address' => $user->user_added_ip_address,
'user_email' => $user->user_email,
'user_password' => $user->user_password,
'user_gender' => $user->user_gender,
'user_timeline_photo_id' => $user->user_timeline_photo_id,
'user_language_id' => $user->user_language_id,
'user_user_type_id' => $user->user_user_type_id,
'user_profile_photo_id' => $user->user_profile_photo_id,
'user_friend_request_reject_count' => $user->user_friend_request_reject_count,
'user_mobile' => $user->user_mobile,
'user_verification_key' => $user->user_verification_key,
'user_added_timestamp' => $user->user_added_timestamp,
'user_modified_timestamp' => $user->user_modified_timestamp,
'user_modified_ip_address' => $user->user_modified_ip_address,
);
$user_id = (int)$user->user_id;
if ($user_id == 0) {
$this->insert($data);
} else {
if ($this->getUser($user_id)) {
$this->update($data, array('user_id' => $user_id));
} else {
throw new \Exception('Form id does not exist');
}
}
}
public function deleteUser($user_id)
{
$this->delete(array('user_id' => $user_id));
}
}
my User Model is
<?php
namespace User\Model;
use Zend\InputFilter\InputFilter;
class User
{
public $user_id;
public $user_given_name;
public $user_first_name;
public $user_middle_name;
public $user_last_name;
public $user_status;
public $user_added_ip_address;
public $user_email;
public $user_password;
public $user_gender;
public $user_timeline_photo_id;
public $user_language_id;
public $user_user_type_id;
public $user_profile_photo_id;
public $user_friend_request_reject_count;
public $user_mobile;
public $user_verification_key;
public $user_added_timestamp;
public $user_modified_timestamp;
public $user_modified_ip_address;
protected $inputFilter;
/**
* Used by ResultSet to pass each database row to the entity
*/
public function userExchangeData($data)
{
$this->user_id = (isset($data['user_id'])) ? $data['user_id'] : null;
$this->user_given_name = (isset($data['user_given_name'])) ? $data['user_given_name'] : null;
$this->user_first_name = (isset($data['user_first_name'])) ? $data['user_first_name'] : null;
$this->user_middle_name = (isset($data['user_middle_name'])) ? $data['user_middle_name'] : null;
$this->user_last_name = (isset($data['user_last_name'])) ? $data['user_last_name'] : null;
$this->user_status = (isset($data['user_status'])) ? $data['user_status'] : null;
$this->user_added_ip_address = (isset($data['user_added_ip_address'])) ? $data['user_added_ip_address'] : null;
$this->user_email = (isset($data['user_email'])) ? $data['user_email'] : null;
$this->user_password = (isset($data['user_password'])) ? $data['user_password'] : null;
$this->user_gender = (isset($data['user_gender'])) ? $data['user_gender'] : null;
$this->user_timeline_photo_id = (isset($data['user_timeline_photo_id'])) ? $data['user_timeline_photo_id'] : null;
$this->user_language_id = (isset($data['user_language_id'])) ? $data['user_language_id'] : null;
$this->user_user_type_id = (isset($data['user_user_type_id'])) ? $data['user_user_type_id'] : null;
$this->user_profile_photo_id = (isset($data['user_profile_photo_id'])) ? $data['user_profile_photo_id'] : null;
$this->user_friend_request_reject_count = (isset($data['user_friend_request_reject_count'])) ? $data['user_friend_request_reject_count'] : null;
$this->user_mobile = (isset($data['user_mobile'])) ? $data['user_mobile'] : null;
$this->user_verification_key = (isset($data['title'])) ? $data['title'] : null;
$this->user_added_timestamp = (isset($data['user_added_timestamp'])) ? $data['user_added_timestamp'] : null;
$this->user_modified_timestamp = (isset($data['user_modified_timestamp'])) ? $data['user_modified_timestamp'] : null;
$this->user_modified_ip_address = (isset($data['user_modified_ip_address'])) ? $data['user_modified_ip_address'] : null;
}
public function getArrayCopy()
{
return get_object_vars($this);
}
function getUserIp(){
$ip ="";
//Test if it is a shared client
if (!empty($_SERVER['HTTP_CLIENT_IP'])){
$ip=$_SERVER['HTTP_CLIENT_IP'];
//Is it a proxy address
}elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])){
$ip=$_SERVER['HTTP_X_FORWARDED_FOR'];
}else{
$ip=$_SERVER['REMOTE_ADDR'];
}
//The value of $ip at this point would look something like: "192.0.34.166"
$ip = ip2long($ip);
return $ip;
}
function getUserNameSplit(){
$ip ="";
//Test if it is a shared client
if (!empty($_SERVER['HTTP_CLIENT_IP'])){
$ip=$_SERVER['HTTP_CLIENT_IP'];
//Is it a proxy address
}elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])){
$ip=$_SERVER['HTTP_X_FORWARDED_FOR'];
}else{
$ip=$_SERVER['REMOTE_ADDR'];
}
//The value of $ip at this point would look something like: "192.0.34.166"
$ip = ip2long($ip);
return $ip;
}
}
please use "exchangeArray" instead of "userExchangeData".