How to pass the array into another page?
Example is I have the controller code below
$values = array(
'RECEIVER_PHYSICAL',
'RECEIVER_VIRTUAL',
'EMAIL_TEMPLATE'
);
foreach ($values as $id) {
$data['email'] = $this->mod_rewards->getEmail($id);
}
And this is the model that I want to pass the array
public function getEmail($id) {
$info = $this->core_db->select('*')
->from($this->schema.'.'.$this->v_system_config)
->where("key",$id)
->get();
return $return;
}
You can just add a new argument to the method getEmail.
$values = array(
'RECEIVER_PHYSICAL',
'RECEIVER_VIRTUAL',
'EMAIL_TEMPLATE'
);
foreach ($values as $id) {
$data['email'] = $this->mod_rewards->getEmail($id, $values);
}
add the argument like this:
public function getEmail($id, $values) {
though i think there must be something wrong with the design here.
Just rewrite your model function as:
public function getEmail($id,$array) {
//use array here
$info = $this->core_db->select('*')
->from($this->schema.'.'.$this->v_system_config)
->where("key",$id)
->get();
return $return;
}
While calling this model in controller you need to pass this array.
Related
I wrote an API call in symfony to return all array data from database.
public function getData()
{
$data = [];
$users = $this->getUserRepository()->findAll();
foreach ($users as $user){
array_push($data, $user->getId());
array_push($data, $user->getEmail());
array_push($data, $user->getUsername());
}
return $data;
}
I got it like this
1,first#mail.com,userOne,2,second#gamail.com,userTwo
but I want to sort every group of data in new row like
1,first#mail.com,userOne,
2,second#gamail.com,userTwo
Another way of doing it would be:
public function getData()
{
$users = $this->getUserRepository()->findAll();
foreach ($users as $user) {
$data[] = [$user->getId(), $user->getEmail(),$user->getUsername()];
}
return $data;
}
Which removes the overhead of the function call array_push().
Source: http://php.net/manual/en/function.array-push.php
All of previous answers are not so good in my opinion. You don't need additional loop, just create query. (And return with your needed hydration)
For example
public function test()
{
return $this->createQueryBuilder('user')
->select('user.id, user.email, user.username')
->getQuery()
->getResult(); // will return objects
// ->getArrayResult() -> will return array of arrays
}
Place it in your user repository and then call it, not the findAll method.
this should work
public function getData()
{
$data = [];
$users = $this->getUserRepository()->findAll();
foreach ($users as $user){
$data[$user->getId()][] = $user->getId();
$data[$user->getId()][] = $user->getEmail();
$data[$user->getId()][] = $user->getUsername();
}
return $data;
}
You are creating 3 occurances in $data for each row returned from the database, instead load a single occurance for each returned row and put an array in it.
public function getData()
{
$data = [];
$users = $this->getUserRepository()->findAll();
foreach ($users as $user){
array_push($data, [$user->getId(), $user->getEmail(),$user->getUsername()]);
}
return $data;
}
Thank you all guys for help but I did it like this and it works for me.
public function getData()
{
$results = $this->getUserRepository()->findAll();
$rows = [];
$rows[] = array(
"id",
"username",
"email"
);
foreach ($results as $row) {
$rows[] = array(
$row->getId(),
$row->getUsername(),
$row->getEmail()
);
}
return $rows;
}
$users = $this->getUserRepository()->findAll();
$i=0;
foreach ($users as $user){
$data[$i][] = $user->getId();
$data[$i][] = $user->getEmail();
$data[$i][] = $user->getUsername();
$i++;
}
The model Person has has-many relation to PersonType:
public function getPersonTypes()
{
return $this->hasMany(PersonType::className(), ['PersonID' => 'PersonID']);
}
I need to show in view all PersonType's related values.
Model Person:
public function ListPersonTypes()
{
$data = $this->getPersonTypes()->all();
$list = array();
foreach ($data as $value) {
$list[] = $value['PersonTypeName'];
return implode(', ', $list);
}
}
But, why ListPersonTypes() returns only first row from table PersonType?
public function ListPersonTypes()
{
$data=$this->getPersonTypes;
$list=array();
foreach ($data as $value){
$list[]=$value['PersonTypeName'];
return implode(',',$list);
}
}
Should do the trick.
you don't use it correctly $this->getPersonTypes()->all(); use
this $this->personTypes
write the return out of the loop
Yii2 (gii) by default create this functions for you access that like a attribute of model and return as arrray .
This function hasnt be creates to access as a function literal .
Try this code
public function ListPersonTypes()
{
// this go to function getPersonTypes and return a array of them
$data=$this->personTypes;
$list=array();
foreach ($data as $value){
$list[]=$value['PersonTypeName'];
}
return implode(',',$list);
}
Seems that in your code you are running just one iteration... as you call a return inside the foreach.
public function ListPersonTypes()
{
$data = $this->getPersonTypes()->all();
$list = array();
foreach ($data as $value) {
$list[] = $value['PersonTypeName'];
}
return implode(', ', $list);
}
I got an error
"Cannot use object of type QueryResult as array"
I am simply trying to take state name from the records array but, I only manage to get this error "Cannot use object of type QueryResult as array"
Model.php
public function getstatename()
{
$statename = $this->salesforce->query ("SELECT State__c FROM RI_School_List__c group by State__c");
return $statename;
}
Controller.php
public function index() {
$data['getstatename'] = $this->model->getstatename();
$this->load->view('footer', $data);
echo "<pre>";
print_r($data['getstatename']['records']);
}
Actually $statename is result-set object not an array.
So you need to do like below:-
Model.php:-
public function getstatename(){
$statename = $this->salesforce->query ("SELECT State__c FROM RI_School_List__c group by State__c");
$state_array = array(); // create an array
foreach ($statename as $row){
$state_array[] = $row->State__c; // assign value to array
}
return $state_array; // return array
}
Controller.php:-
public function index() {
$data['getstatename'] = $this->Footer_model->getstatename();
echo "<pre/>";print_r($data['getstatename']); // check this and accordingly change you code further
$this->load->view('footer', $data);
}
Here is the solved code Thanks to #Anant
Model.php
public function getstatename()
{
$statename = $this->salesforce->query ("SELECT State__c FROM RI_School_List__c group by State__c");
$state_array = array();
foreach ($statename as $row){
$state_array[] = $row->State__c;
}
return $state_array;
}
Controller.php
public function index() {
$data['getstatename'] = $this->Footer_model->getstatename();
$this->load->view('footer', $data);
}
See if you can do
$data['getstatename']->fetchRow();
I've a method in my Controller:
function getSuggestions()
{
$query = Input::get('query');
$suggestions = Suggestion::where('word', 'LIKE', "$query%")->get()->toArray();
$return $suggestions;
}
and in Model I have:
public function toArray(){
$array = parent::toArray();
$array['matched'] = 'ok';
return $array;
}
How can I pass a variable to this toArray() method to append it to the Model?
Something like this: $array['matched'] = $query
I can't pass the $query directly to toArray($query). Any other way?
Just add the value to each matched array:
function getSuggestions()
{
$query = Input::get('query');
$suggestions = Suggestion::where('word', 'LIKE', "$query%")->get()->toArray();
return array_map(
function ($array) use ($query) { $array['matched'] = $query; return $array; },
$suggestions
);
}
Inside my processor class I have a statement that grabs all the projects from a db table and formats them to be displayed. This method does not work and halts at the getCollection call.
class GlobalLinkSettingsProcessor extends modObjectGetListProcessor{
public function initialize() {
return parent::initialize();
}
public function process() {
$result = $this->modx->getCollection('ManagerProjects');
$project_names = array();
foreach ($result as $row) {
$projects = unserialize($row->get('manager_projects'));
foreach($projects as $short_code => $project) {
$project_names[] = array('project_name' => $project, 'project_short_code' => $short_code);
}
}
return '{"total":' . count($project_names) . ',"results":' . $this->modx->toJSON($project_names) . ',"success":true}';
}
...
}
This code that uses plain SQL does work:
class GlobalLinkSettingsProcessor extends modObjectGetListProcessor{
public function initialize() {
return parent::initialize();
}
public function process() {
$leadersql = "SELECT * FROM `modx_manager_projects`";
$query = $this->modx->query($leadersql);
$project_names = array();
while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
$projects = unserialize($row['manager_projects']);
foreach($projects as $short_code => $project) {
$project_names[] = array('project_name' => $project, 'project_short_code' => $short_code);
}
};
return '{"total":' . count($project_names) . ',"results":' . $this->modx->toJSON($project_names) . ',"success":true}';
}
...
}
I use similar method to the first which saves ManagerProjects and works fine, so I don't think it has to do with the model declaration. I could easily just use the second method above since it seems to work, but I want to use the best method.
What is wrong with the first method?
Is the first method the proper way to implement SQL in the Modx processor? Or is there a better way?
We can do this task easier a little bit.
#Vasis is right but we can use base prepareRow method instead of reloading iterate method:
<?php
class GlobalLinkSettingsProcessor extends modObjectGetListProcessor{
public $classKey = 'ManagerProjects';
protected $projects = array();
public function prepareRow(xPDOObject $object) {
$_projects = unserialize($object->get('manager_projects'));
foreach($_projects as $short_code => $project) {
$this->projects[] = array('project_name' => $project, 'project_short_code' => $short_code);
}
return parent::prepareRow($object);
}
public function outputArray(array $array,$count = false) {
$count = count($this->projects);
return parent::outputArray($this->projects,$count);
}
}
return 'GlobalLinkSettingsProcessor';
There we can see one of modx ‘features’. In modObjectGetListProcessor process method we can see this:
public function process() {
$beforeQuery = $this->beforeQuery();
if ($beforeQuery !== true) {
return $this->failure($beforeQuery);
}
$data = $this->getData();
$list = $this->iterate($data);
return $this->outputArray($list,$data['total']);
}
getData method returns a list of objects and it goes to iterate method (where we can check if the object is accessible and change the list of these objects on demand). If you don't have access to some of objects we'll get changed list. And it goes to outputArray method but second parameter is still old for it. So you should count them again.
This is solution is quite well but you tried to get data which is stored in object's field. So afterIteration method will be unusable for further extension in my version of processor. But who cares? :)
P.S.: About your first version of processor. modObjectGetList processor is ready for getting collection. So you have not to use getcollection method. Just add proper classKey property to it.
Another way is in modProcessor extension. It gives to you a base structure. But you can make your own kind of stuff.
Because you do it wrong! Just see this. The right way to do it, is something like this:
<?php
class GlobalLinkSettingsProcessor extends modObjectGetListProcessor{
public $classKey = 'ManagerProjects';
public function iterate(array $data) {
$list = array();
$list = $this->beforeIteration($list);
$this->currentIndex = 0;
/** #var xPDOObject|modAccessibleObject $object */
foreach ($data['results'] as $object) {
if ($this->checkListPermission && $object instanceof modAccessibleObject && !$object->checkPolicy('list')) continue;
$projects = unserialize($object->get('manager_projects'));
foreach($projects as $short_code => $project) {
$objectArray = array('project_name' => $project, 'project_short_code' => $short_code);
if (!empty($objectArray) && is_array($objectArray)) {
$list[] = $objectArray;
$this->currentIndex++;
}
}
}
$list = $this->afterIteration($list);
return $list;
}
}