I have a problem to loop GET data from URL.
My array looks like after var dump :
array(5) {
[0]=>
array(5) {
["sku"]=>
string(9) "AH1172164"
["name"]=>
string(21) "dasdas"
["url"]=>
string(42) "21321312"
["price"]=>
string(6) "866.00"
["stocks"]=>
array(1) {
[0]=>
array(3) {
["partner"]=>
string(6) "321312"
["qty"]=>
string(1) "1"
["spotted"]=>
string(14) "1 month "
}
}
}
My code for looping the data in blade file:
#php
$d=$_GET['Api'];
var_dump($d);
foreach($d as $value)
{
echo $value;
}
#endphp
When I use var_dump the data are listed correctly but when I want to loop the variable $d I got this error:
Method Illuminate\View\View::__toString() must not throw an exception, caught Facade\Ignition\Exceptions\ViewException: Array to string conversion (View: F:\xampp\htdocs\semafor-master\resources\views\platform\tools\
I have API.. and my controller for this :
public function gen(Request $request)
{
// Some queries, and loops to fill $data variable..
return \Redirect::route('platform.tools.gen', ['Api'=>$data]);
}
I can't use return view, I must use return redirect because after API REQUEST I want to redirect to this route.
The gen view is Orchid admin panel screen.
What can be the problem?
Thanks in advance.
Part of the answer is that somewhere in the stack, there's a call to a magic __toString() method. Exceptions being called therein is only allowable in Php 7.4 and up. Try wrapping your behavior in a generic try/catch and make it dump the message from the Exception that it's trying to throw. The message you're seeing now is just a symptom of a different problem.
Looks like you have an array of array variable, so you should encode your value to a string before printing it:
#php
$d=$_GET['Api'];
foreach($d as $value)
{
echo json_encode($value);
}
#endphp
Related
can anyone tell why my $model->load(Yii::$app->request->post() return boolean (false) ? I try var_dump the $model->load(Yii::$app->request->post() and it certainly has my input value (not null).
Here's my code. I'm working on an editable input field based on Vitalet's x-editable. This field will modify the value of tema column of the database (tema 's model attribute). I try to print_r($model->getErrors()) in the 'else' statement and I got
Array
(
)
public function actionFetch(){
//There's only a single row in the table.
$model= Home::find()->one();
if (Yii::$app->request->isAjax) {
// use Yii's response format to encode output as JSON
\Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
// save posted model attributes
if ($model->load(Yii::$app->request->post()) && $model->save()) {
//extract the class name
$modelClassName = \yii\helpers\StringHelper::basename(get_class($model));
//grab the post parameters array (as attribute=>value)
$params = Yii::$app->request->post($modelClassName);
//pull the first value from the array (there should only be one)
$value = reset($params);
// return JSON encoded output in the below format
return ['output'=>$value, 'message'=>'success'];
} else {
// else if nothing to do always return an empty JSON encoded output
// alternatively you can return a validation error
return ['output'=>'', 'message'=>'fail'];
}
};
}
The view :
<?=$model->tema?>
My model's rule :
public function rules()
{
return [
[[ 'id','isiTema', 'image', 'midLeft_title', 'midLeft_content', 'midCenter_title', 'midCenter_content', 'midRight_title', 'midRight_content', 'footerLeft', 'footerRight', 'created_at', 'updated_at'], 'required'],
[['midLeft_content', 'midCenter_content', 'midRight_content', 'footerLeft', 'footerRight'], 'string'],
[['id'],'integer'],
[['created_at', 'updated_at'], 'safe'],
[['tema', 'isiTema', 'image', 'midLeft_title', 'midCenter_title', 'midRight_title'], 'string', 'max' => 255],
];
}
This is my var_dump(Yii::$app->request->post()) contains :
array(3) {
["name"]=>
string(4) "tema"
["value"]=>
string(5) "aaabb"
["pk"]=>
string(1) "1"
}
I try this in my controller but still the result is the same (basically I think I don't need to as it only contains a single row in the table) :
...
$pk = $_POST['pk'];
$model=Home::find()->where(['id'=>$pk])->one();
...
...
You need to use load() with second argument set to '' to explicitly state that your POST fields are not including model name.
$model->load(Yii::$app->request->post(), '')
I've just started with Laravel and Eloquent.
In my "Receipt"-model, I try to get information about a relationship.
As long as I'm using var_dump, I get my information.
As soon as I'm just returning the value to use it in a blade view, I get my "Trying to get property of non-object".
<?php
class Receipt extends Eloquent {
public function businesspartner() {
return $this->belongsTo('Businesspartner', 'f_businesspartner_id');
}
public function brand() {
return $this->belongsTo('Brand', 'f_brand_id');
}
public function invoice() {
return $this->belongsTo('Invoice', 'f_invoice_id');
}
public function name() {
$name = '';
$bp = $this->businesspartner()->first();
$name = $bp->salutation; // line 21
$name .= ' ';
$name .= $bp->lastname_company;
return $name;
}
}
The error occurs in line 21.
When I now put a
var_dump($name);die();
before returning, it prints me my name.
What's going wrong here? :(
Regards,
Timo
SOLUTION
As #Jarek Tkaczyk wrote, I was calling the name() method in a loop.
When doing my debug outputs, I got data from my first row.
When getting the error, the code was already processing the second row, where the foreign key was null.
Wrapping the problematic part in if(count($this->businesspartner)) helped.
For more information about that, Jarek linked that post: https://stackoverflow.com/a/23911985/784588
In a custom component, in the site view, I display a list of countries, each as a link to another page, displaying persons living in that country.
This is a link:
index.php?option=com_example&view=persons&country=1&Itemid=131
What's missing:
When the persons-page is opened, all persons are listed.
What I'm looking for:
I'd like to show only persons with country as in the link, 1 in the example above.
I tried to add this condition in the model-files of persons, but failed miserably.
+++ EDIT ++++
Thanks to the accepted answer, I was able to accomplish what I needed. Unfortunately, this seems to produce side-effects:
Fatal error: Call to a member function getPagesCounter() on a non-object
in .../view/persons/tmpl/default.php` (...)
The code throwing that error is
<?php echo $this->pagination->getPagesCounter(); ?>
When commenting out that line, the same erroer will occur with this code:
<?php echo $this->pagination->getPagesLinks(); ?>
How did that happen, and what can I do? Tried to track down that problem, but didn't know where to start.
+++ EDIT +++
Wasnm't able to solve that issue yet. Did a var_dump($this->pagination);, this is the output:
array(1) {
[0]=>
object(stdClass)#150 (20) {
["id"]=>
string(1) "6"
["name"]=>
string(11) "Fleur Leroc"
["country"]=>
string(1) "2"
(...)
["ordering"]=>
string(1) "6"
["state"]=>
string(1) "1"
["checked_out"]=>
string(3) "615"
["checked_out_time"]=>
string(19) "2013-10-10 10:53:14"
["created_by"]=>
string(10) "Super User"
["editor"]=>
string(10) "Super User"
["countriestrainers_country_828045"]=>
string(6) "France"
["countriestrainers_flag_828045"]=>
string(28) "images/trainers/flags/fr.gif"
}
}
So the object does exist, doesn't it?
You were close editing the model files.
In your Persons model (ExampleModelPersons) you need to make sure you have the following elements:
Whitelist the filter name:
<?php
public function __construct($config = array())
{
if (empty($config['filter_fields'])) {
$config['filter_fields'] = array(
'country',
// other not standard filters
);
}
parent::__construct($config);
}
?>
Autopopulate the state filter:
<?php
protected function populateState($ordering = null, $direction = null)
{
$country = $this->getUserStateFromRequest($this->context.'.filter.country', 'country', '', null, false);
$this->setState('filter.country', (int) $country);
// ....Other states
{
?>
Store id for the context:
<?php
protected function getStoreId($id = '')
{
$id .= ':'.$this->getState('filter.country');
// Other states
}
?>
And the most important one, the database query
<?php
protected function getListQuery()
{
// ... Other parts of the querty
if ($country = $this->getState('filter.country'))
$query->where("country = ". (int) $country);
}
?>
If you don't need saving the state in user's session this can be easily stripped into two liner in the database query.
<?php
// ... Other parts of the querty
if ($country = $app->input->getInt('country'))
$query->where("country = ". (int) $country);
?>
I'm trying to get my data from a form and to send it to my model below to input the data into the database table users.
I have my controller (class Login) with the following code:
class Login extends CI_Controller {
function __construct()
{
parent::__construct();
$this->load->model('Login_model');
}
public function index()
{
$data = array(
'gid' => $this->input->post('gid'),
'name' => $this->input->post('name'),
'pic' => $this->input->post('pic'),
'link' => $this->input->post('link')
);
var_dump($data);
$this->Login_model->insert_entry($data);
}
}
In my model I have the following:
class Login_model extends CI_Model {
public function __construct()
{
parent::__construct();
$this->load->database();
}
function insert_entry($data)
{
$this->db->insert('users', $data);
}
}
The issue I have at the moment is that I don't think my model is getting the data correctly. I've been using the URL:
domain.com/login?field1=John&field2=Dave&field3=Barry&field4=Ted
If I do a the var dump seems to return the following instead of data:
array(4) { ["gid"]=> bool(false) ["name"]=> bool(false) ["pic"]=> bool(false) ["link"]=> bool(false) }
You have some issues here:
There is a minus sign (-) instead of an equals sign (=) in the first line of insert_entry()
Data sent via the URL is GET data (use CI's form_open(); to default to POST)
Your database fields and the data in the array potentially don't match up, and you may be sending extraneous data like "submit" along with it
In your controller, you can send the POST data through as a parameter of the insert_entry() function:
$this->Login_model->insert_entry($this->input->post());
There is also a minus sign in place of the equals sign in your first line of the insert_entry() function. You can change your insert_entry() function to something along the lines of:
function insert_entry($data) {
$this->db->insert('users', $data);
}
NOTE: Remember to validate this data before trying to submit it to the database.
Another issue I am seeing is that you are searching the POST data, but the URL is sending GET data. There a multiple ways to solve this, the easiest of which is to check the GET stream. You could use either of the following:
$this->input->get();
or:
$this->input->get_post();
The first will check your GET data, while the second will check both the GET and POST, starting with the POST.
In your controller, assuming these fields are in your GET data, you can do the following:
$data = array(
'gid' => $this->input->get('gid'),
'name' => $this->input->get('name'),
'pic' => $this->input->get('pic'),
'link' => $this->input->get('link')
);
You can read more about this in the CodeIgniter documentation at http://ellislab.com/codeigniter/user-guide/libraries/input.html
Here is what their documentation says
You can also pass a string to result() which represents a class to
instantiate for each result object (note: this class must be loaded)
$query = $this->db->query("SELECT * FROM users;");
foreach ($query->result('User') as $user) {
echo $row->name; // call attributes
echo $row->reverse_name(); // or methods defined on the 'User' class
}
Despite the fact that they are echoing $row instead of $user... this does not seem to work for me. Here is my version of testing it
Model
class User extends CI_Model{
var $first;
var $last;
..
function getName() {
return $this->first + " " + $this->last;
}
}
Controller
class Tester extends CI_Controller {
public function index() {
$this->load->model('User');
$query = $this->db->query('SELECT * from USERS');
$data = array (
'regular' => $query->result(),
'modeled' => $query->result('User')
);
$this->load->view('test', $data);
}
}
View
foreach ($regular as $row) {
echo "{$row->FIRST} {$row->LAST} <BR/>";
}
echo "<br/>";
foreach ($modeled as $row) {
echo "{$row->getName()} <BR/>";
}
Is there something that I'm doing wrong or misunderstanding? I would assume that based on their documentation, that if I assign a class to the result set, the class should be populated with the results? Now, how it goes on knowing which field to map to is a mystery to me and may very well be the reason why this doesn't work. I thought perhaps I needed to modify the constructor to do this mapping but I didn't see any documentation as to how I would go about doing that. I tried putting in a parameter for the constructor assuming it was an StdClass array but didn't seem to work.
Any clarifications would be great!
So it dawned on me to check the actual source code of the db_results function and I figured that it's due to the case of the query result columns. And it seems that CI defaults everything to UPPERCASE unless you specify it as lowercase in your query string.
So in conclusion, whatever the case of columns is in your query, should be the case of values in your Model!
Seems ridiculous though... I'll probably see if I can edit the core class to not be case-sensitive. Unless someone has better alternatives.