YII Call to a member function getErrors() on a non-objec - yii

Following this tutorial; When I try to get the data to display in the form and update
For my error was:
$n = $this->loadModel($id);
I want to make two models with one form, this is my code for update:
Controller:
public function actionUpdate($id)
{
$n = new Noticias;
$m = new Multimedia;
$this->performAjaxValidation(array($n,$m));
$n=$this->loadModel($id);
if(isset($_POST['Noticias'],$_POST['Multimedia']))
{
$n->attributes=$_POST['Noticias'];
$m->attributes=$_POST['Multimedia'];
$m->ID_NOT=$n->ID;
$m->setIsNewRecord(false);
if($n->save())
$this->redirect(array('admin','id'=>$n->ID));
}
$this->render('update',array('n'=>$n,'m'=>$m));
}
update.php
<?php echo $this->renderPartial('_form', array('n'=>$n, 'm'=>$m)); ?>
some view
//get Multimedia FK
<?php if ($n->isNewRecord==false) {
$m=Multimedia::model()->findByPk($n->ID);
} ?>
//Validation
<?php echo $form->errorSummary(array($n,$m)); ?>
//Field FOTO between other
<div class="row">
<?php echo $form->labelEx($m,'FOTO_URL'); ?>
<?php echo $form->textField($m,'FOTO_URL',array('size'=>25,'maxlength'=>100)); ?>
<?php echo $form->error($m,'FOTO'); ?>
</div>

First - do not load models in view
<?php if ($n->isNewRecord==false) {
$m=Multimedia::model()->findByPk($n->ID);
} ?>
This part should be in controller action.
Make sure $m and $n are really models. If findByPk statement above fails, $m will be null, so you will get error from errorSummary which calls $m->getErrors() and $n->getErrors(). In short - make sure $n and $m are properly initialized - both must be instances of model, either empty, or filled from db, but in your case one is null. Most probably $m

this error occur when Noticias (ie $n is newrecord) or $n->ID is not found in Multimedia
you can solve this if you need to work even if its a new record you can use.
if ($n->isNewRecord==false) {
$m=Multimedia::model()->findByPk($n->ID);
}
else
$m=new Multimedia;

You can try to load both models in Controller (ex. in actionUpdate) :
public function actionUpdate($id)
{
$n = new Noticias;
$m = new Multimedia;
$this->performAjaxValidation(array($n,$m));
$n=$this->loadModelNoticias($id);
$m=$this->loadModelMultimedia($n->ID); //just put it here..
if(isset($_POST['Noticias'],$_POST['Multimedia']))
{
$n->attributes=$_POST['Noticias'];
$m->attributes=$_POST['Multimedia'];
$m->ID_NOT=$n->ID;
$m->setIsNewRecord(false);
if($n->save())
$this->redirect(array('admin','id'=>$n->ID));
}
$this->render('update',array('n'=>$n,'m'=>$m));
}
Please be noticed that you have to define both loadModel functions in the same controller too.
function loadModelNoticias($id){
$model = Noticias::model()->findByPk($id);
return $model;
}
function loadModelMultimedia($id){
$model = Multimedia::model()->findByPk($id);
return $model;
}

Related

Cake PHP Update single fields in View - Undefined Variable

i search a long time, but i dont find a solution for my problem.
The case is, that i have a few buttons integrated in my view and clicking on them affected updating single input fields. The problem is that i have warnings, that variables are undefined in view. I understand why and how i suppress them, but i`m not sure, if this is a good solution. Is there a better way to solve this? What is best practice?
Here is my code from the view file:
<?php
echo $this->Form->create('Excel', array('type' => 'file'));
echo $this->Form->file('File');
echo $this->Form->submit('Upload xls File');
echo $this->Form->end();
echo $this->Form->create('Config');
//echo $this->Form->input('Name');
echo $this->Form->input('vlanNumber');
echo $this->Form->input('description', array('value' => $description));
echo $this->Form->input('preSharedKey', array('value' => $preSharedKey));
echo $this->Form->button('generate', array('name'=>'generateButton'));
echo $this->Form->input('customerPeerIp', array('default' => 'id_of_default_val','value' => $cusPeerIp));
The generate button affect a new preSharedKey. And the upload of the csv affected an update of the other fields.
The relevant code of the controller is this:
public function inputData() {
if ($this->request->is('post')) {
$post_data = $this->request->data;
if (isset($this->request->data['show'])) { //Submit Button was clicked
$this->Session->write('Configuration',$post_data); //Store the input fields in the session
return $this->redirect(array('action' => 'showPreview'));
} else if (isset($this->request->data['cancel'])) { // Cancel button was clicked: Go back to index site
return $this->redirect(array('action' => 'index'));
} else if (isset($this->request->data['generateButton'])) {
return $this->set('preSharedKey', $this->getRandomString(20)); //Set a Pre Shared Key with 30 signs
}
if (!empty($this->data) && is_uploaded_file($this->data['Excel']['File']['tmp_name'])) {
$this->importData($this->data['Excel']['File']['tmp_name']);
$excel=new Excel();
$values=$excel->getParams($this->data['Excel']['File']['tmp_name']);
$this->set('description',$values['description']);
$this->set('cusPeerIp',$values['cust_peer']);
return;
//this calls the Excel Class function
}
//print_r($post_data);
//echo $post_data['Config']['Name'];
//echo $this->request['Config']['task_1'];
}
$this->set('description','');
$this->set('cusPeerIp','');
$this->set('preSharedKey', '');
}
Can you please help me?

Undefined Variable $action

I have the following two simple scripts. $action being detected as "Not Set". If isset statement is not used, warning "Undefined variable $action" is popped. I don't know what is the problem, please help.
prog01.html :
Press to add record
prog02.php :
<?php
if (isset($action)){
if ($action == 'add') echo "action is to add <br>";
}
else
echo "\$action is not set <br>";
?>
You want to specify that action value is submitted using GET or POST method like this
<?php
if (isset($_POST['action'])){
$action = $_POST['action'];
}
else if (isset($_GET['action'])){
$action = $_GET['action'];
}
if ($action == 'add')
{
echo "action is to add <br>";
}
else
{
echo "\$action is not set <br>";
}
?>

How do I select and display a specific field from may table in cakephp?

I have this code in my products_controller.php:
<?php
class ProductsController extends AppController{
var $name = 'Products';
var $helpers = array('Form');
//var $scaffold;
function index(){
$this->Product->recursive = 1;
$products = $this->Product->find('all');
$this->set('products',$products);
//pr($products);
}
function add(){
if(!empty($this->data)){
$this->Product->create();
$this->Product->save($this->data);
$this->redirect(array('action'=>'index'));
}
$categories = $this->Product->Category->find('list',array(
'field'=>array('Category.categoryName')
));
$this->set('categories',$categories);
pr($categories);
}
}
?>
what it actually does in my database is this:
SELECT `Category`.`id` FROM `categories` AS `Category` WHERE 1 = 1
The thing is, I am not trying to select Category.id. I want to select Category.categoryName which is another field in my database so that it will automatically populate a dropdown list in my add.ctp file which goes like this:
<h2>ADD</h2>
<?php echo $form->create('Product'); ?>
<?php
echo $form->input('ProductName');
echo $form->input('categories');
echo $form->end('DONE');
?>
any help would be highly appreciated.
In your Category Model set the displayField Name property with the Category Name.
public $displayField = 'categoryName';

Best way to display current logged-on user in default.ctp?

I am in the process of customizing the default.ctp file and I am trying to display the currently logged on user's name on the top of the page.
In app_controller.php, I have the following:
function beforeFilter()
{
$user = $this->Auth->user();
if($user != null)
{
$this->Session->write('user_name',$user['User']['username']);
}
}
And in default.ctp, I have:
$user = $this->Session->read('Auth.User');
if(!empty($user))
{
echo 'Hello, ' . $user['user_name'];
}
However, it seems like the value $user_name is not getting set anywhere.
What am I doing wrong? Is there a better way to accomplish this?
Update: I've modified it as described in the answer, but it still doesn't work. I get an error:
Undefined index: user_name [APP/views/layouts/default.ctp, line 21]
you can also use the SessionHelper directly in the view / layout
$user = $this->Session->read('Auth.User');
if(!empty($user)) {
echo 'Hi ', $user['user_name'];
}
Cakephp 2.x:
<?php if (AuthComponent::user('id')): ?>
<p class="navbar-text pull-right">
Logged in as <?= AuthComponent::user('name') ?>
</p>
<?php endif; ?>
$user = $this->Session->read('Auth.User');
if(count($user))
echo $user['name'];

symfony get data from array

I'm trying to use an SQL query to get data from my database into the template of a symfony project.
my query:
SQL:
SELECT l.loc_id AS l__loc_id, l.naam AS l__naam, l.straat AS l__straat,
l.huisnummer AS l__huisnummer, l.plaats AS l__plaats, l.postcode AS l__postcode,
l.telefoon AS l__telefoon, l.opmerking AS l__opmerking, o.org_id AS o__org_id, o.naam AS o__naam
FROM locatie l
LEFT JOIN organisatie o
ON l.org_id = o.org_id
This is generated by this DQL:
DQL:
$this->q = Doctrine_Query::create()
->select('l.naam, o.naam, l.straat, l.huisnummer, l.plaats, l.postcode, l.telefoon, l.opmerking')
->from('Locatie l')
->leftJoin('l.Organisatie o')
->execute();
But now when i try to acces this data in the template by either doing:
<?php foreach ($q as $locatie): ?>
<?php echo $locatie['o.naam'] ?>
or
<?php foreach ($q as $locatie): ?>
<?php echo $locatie['o__naam'] ?>
i get the error from symfony:
500 | Internal Server Error | Doctrine_Record_UnknownPropertyException
Unknown record property / related component "o__naam" on "Locatie"
Does anyone know what is going wrong here? i dont know how to call the value from the array if the names in both query's dont work.
Doctrine will have hydrated your results into objects corresponding to the models in your query. In your case these will be Locatie and Organisatie. You should therefore be able to access the data as follows:
<?php foreach ($q as $obj): ?>
<?php echo $obj->Locatie->naam; ?>
<?php echo $obj->Organisatie->naam; ?>
<?php endforeach; ?>
If you have the above method in eg the Locatie table class and use self::create("l") to create your method, the object you use in the view won't need the ->Locatie part.
Edit: table method example:
class LocatieTable extends Doctrine_Table
{
public function getLocaties()
{
$q = self::createQuery("l")
->select('l.naam, o.naam, l.straat, l.huisnummer, l.plaats, l.postcode, l.telefoon, l.opmerking')
->leftJoin('l.Organisatie o')
->execute();
return $q;
}
}
You should be able to find this class (probably empty) already auto-generated in lib/model/doctrine/LocatieTable.class.php. Now call it with:
$this->q = Doctrine::getTable("Locatie")->getLocaties();
If you want to know how to get some value from the result DoctrineRecord object I advise to use var_dump($obj->toArray()) method to get clear view of the object structure. After that you can use several types of getters to retrive what you want (e.g. $obj->A->b, $obj->getA()->getB() etc..)