Bind outside variable and in Class protected field with method param - php

How to implement this kind of functionality:
Fill entity eg. Member with data
Bind Member to form with $form->bind($member) to private property _formData
Afterward do some stuff inside $form, eg. $form->validate() with _formData
$member should be also changed as _formData is changed.
class Form {
private $_formData;
function bind1(&$row) {
// this change member outside
$row['full_name'] =
$row['first_name']
. ' ' .
$row['last_name'];
}
function bind2(&$row) {
$this->_formData = $row;
// this will not change memeber
$this->_formData['full_name'] =
$this->_formData['first_name']
. ' '
. $this->_formData['last_name'];
}
}
$member = array('full_name' => null, 'first_name'=>'Fn', 'last_name' => 'Ln');
$form = new Form();
$form->bind1($member);
var_dump($member['full_name']);
// output: 'FnLn'
$form->bind2($member);
var_dump($member['full_name']);
// output: null
Method validate work with private _fieldData, so this to work bind2 test should work.

What you are trying to do is possible, but you need to set a reference of the reference in the bind1 and bind2 method, like this:
$this->_formData = & $row;
You are also making misspellings between full_name and fullName as array keys. For example in the bind2 method:
$this->_formData['full_name'] = $this->_formData['first_name'] . ' ' . $this->_formData['last_name'];
And in your test-code you var_dump full_name. Chaging full_name in bind2 to fullName should fix your issue.

the problem is you are assigning the full_name key of your member variable and trying to access fullName variable so it is returning NULL

Related

Yii2 function based on relation gives error on create

I have this in my model called B:
public function getA() {
return $this->hasOne(\app\models\A::className(), ['id' => 'A_Id']);
}
public function getDispName() {
return $this->a->attr . ' ' . $this->attr . ' ' . $this->attr2;
}
works everything fine, until I go to Create. Then I get the following "error":
PHP Notice – yii\base\ErrorException Trying to get property of non-object
As a workaround I have done this:
public function getDispName() {
if (is_object($this->a)) {
return $this->a->attr . ' ' . $this->attr . ' ' . $this->attr2;
}
}
I'm not sure if this is a good solution, or why do I get this "notice" only at create, but I would like to understand and do it correctly. I don't want this to cause problems somewhere else. Maybe I miss something other basic and important knowledge. If you have any ideas, I would be grateful to hear it. Thanks.
You are probably trying to use a B model that does not have a A model attached. If that is the case of course your function would fail. Are you sure for every B you have an A? Probably you are inserting a B and not inserting an A and trying to show info on it.
Your options are:
1) do exactly like you did, maybe change it to
public function getDispName() {
$display = '';
if (is_object($this->a)) {
$display = $this->a->attr;
}
return $display . ' ' . $this->attr . ' ' . $this->attr2;
}
2) fix your code to always make sure you insert an A when you insert a B. It can be an empty record but it has to be a record.
This property is based on others properties, so when you create new object of type A you don't need to indicate this property. Indicate only fields from which it consists.
Open /views/model_name/_form.php and delete row with property dispName
<?= $form->field($model, 'dispName')->textInput() ?> // or textarea or ...

Accessing variable stored in class from another file

I would like to access the $new_id variable in the method below (from public class youth_teams) from an outside file but I can't figure out how. I have it printing the lastInsertID correctly from inside the file which contains the method but would like to be able to access the variable in other files also.
public function addTeam(
$team_name,
&$error
) {
$query = $this->pdo->prepare('INSERT INTO `' . $this->table . '` (
`team_name`
) VALUES (
:team_name
)');
$query->bindParam(':team_name', $team_name);
$query->execute();
print_r($query->errorInfo());
print $this->pdo->lastInsertID();
$new_id = $this->pdo->lastInsertID();
return $new_id;
}
Here's the code I've tried from the OTHER FILE:
sw::shared()->youth_teams->addTeam (
$team_name,
$error
);
$temp_two = sw::shared()->youth_teams->addTeam->pdo->lastInsertID();
echo "new id: " . $temp_two . "<br>";
Of course that is not working... What's the correct path to access $new_id?
It should be:
$temp_two = sw::shared()->youth_teams->addTeam($team, $error);
addTeam() is a function that returns $new_id, so you need to call it with ().
If you really want to be able to access $new_id directly, you can declare it global:
public function addTeam(
$team_name,
&$error
) {
global $new_id;
...
What was wrong with this?
$sw = new sw();
$temp_two = $sw->addTeam( $team, $error );
echo "new id: " . $temp_two . "<br>";
If you can call sw::shared() from the outside file, you can assign the object.
I probably am not fully understanding your code, if not, please fully explain the following:
sw::shared()->youth_teams->addTeam( $team, $error );
// 1. What does the shared() method do?
// 2. What is the youth_teams property?
If it's needed, might I suggest adding the assignment directly into the addTeam() function and use the above format to return the id only.

Passing property to PHP method

I have the following class, where I added the property $user.
include_once(__CA_LIB_DIR__."/ca/Search/BaseSearch.php");
include_once(__CA_LIB_DIR__."/ca/Search/ObjectSearchResult.php");
class ObjectSearch extends BaseSearch {
# ----------------------------------------------------------------------
/**
* Which table does this class represent?
*/
protected $ops_tablename = "ca_objects";
protected $ops_primary_key = "object_id";
public $user;
# ----------------------------------------------------------------------
public function &search($ps_search, $pa_options=null, $user) {
return parent::doSearch($ps_search, new ObjectSearchResult(), $pa_options);
}
# ----------------------------------------------------------------------
}
?>
In the following code I can't pass the $user property to the search method. I tried with $user, $this->user and new ObjectSearch($user). Being new to PHP I know I'm asking a naive question, but I can't solve it by myself, believe me I tried for days. How can I accomplish this?
$po_request = $this->getVar('request');
$vs_widget_id = $this->getVar('widget_id');
$user = $this->getVar('user');
$o_search = new ObjectSearch();
$result = $o_search->search('created.$user.:"2013"');
$count = 1;
while($result->nextHit()) {
print "Hit ".$count.": "."<br/>\n";
print "Idno: ".$result->get('ca_objects.idno')."<br/>\n";
print "Name: ".$result->get('ca_objects.preferred_labels.name')."<br/>\n";
$count++;
}
?>
public function &search($ps_search, $pa_options=null, $user)
There are a few things wrong with it:
It doesn't make any sense to pass a parameter without default value after a parameter which has a default value
You have to pass the third parameter here (you only pass one)
You don't have to pass the class properties manually; they're automatically in $this
So write:
public function &search($ps_search, $pa_options=null) {
return parent::doSearch($ps_search, new ObjectSearchResult($this->user), $pa_options);
}
Or where ever you may need your $user class property, write simply $this->user.
$this is always set in object context: you don't need to pass it yourself.
Don't confuse double quotes with single ones. You have to either use concatenation or double ones here:
$result = $o_search->search('created ' . $user . ': 2013');
or
$result = $o_search->search("created $user: 2013");

Warning: Missing Argument 1

I am having some problems with my php code: All information returns but I cannot figure out why I am getting the error. For my index page I only inluded the line of code that is actually using that class there really is no other code other than some includes. Im sure it is how I built my __contstruct but i am not sure of the approriate way of doing it. I am missing something in how it is being called from the index page.
This line of code for my __construct works w/o error but I do not want the variable assigned in my class.
public function __construct(){
$this->user_id = '235454';
$this->user_type = 'Full Time Employee';
}
This is my Class
<?php
class User
{
protected $user_id;
protected $user_type;
protected $name;
public $first_name;
public $last_name;
public $email_address;
public function __construct($user_id){
$this->user_id = $user_id;
$this->user_type = 'Full Time Employee';
}
public function __set($name, $value){
$this->$name = $value;
}
public function __get($name){
return $this->$name;
}
public function __destroy(){
}
}
?>
This is my code from my index page:
<?php
ini_set('display_errors', 'On');
error_reporting(E_ALL);
$employee_id = new User(2365);
$employee_type = new User();
echo 'Your employee ID is ' . '"' .$employee_id->user_id. '"' . ' your employement status is a n ' . '"' .$employee_type->user_type. '"';
echo '<br/>';
?>
The problem is:
$employee_type = new User();
the constructor expect one argument, but you send nothing.
Change
public function __construct($user_id) {
to
public function __construct($user_id = '') {
See the outputs
$employee_id = new User(2365);
echo $employee_id->user_id; // Output: 2365
echo $employee_id->user_type; // Output: Full Time Employee
$employee_type = new User();
echo $employee_type->user_id; // Output nothing
echo $employee_type->user_type; // Output: Full Time Employee
If you have one user, you can do this:
$employer = new User(2365);
$employer->user_type = 'A user type';
echo 'Your employee ID is "' . $employer->user_id . '" your employement status is "' . $employer->user_type . '"';
Which output:
Your employee ID is "2365" your employement status is "A user type"
I'm no PHP expert, but it looks like you are creating 2 new instances of class user, and on the second instatiation, you are not passing the user_id into the constructor:
$employee_id = new User(2365);
This, it would seem to me, is creating a new instance of User and assigning this instance to the variable $employee_id - I don't think this is what you want though?
$employee_type = new User();
This looks like you're instantiating another instance of User and assigning it to variable $employee_type - but you have called the constructor User() without passing in an ID as is required - hence the error (missing argument).
The reason your return script contents look OK is because the first instance of the User class has an ID (because you passed it in) and the second one has an employee type because this is set in the constructor.
Like I say, I don't know PHP but I'm guessing you want something more along the lines of:
$new_user = new User(2365);
echo 'Your employee ID is ' . '"' .$new_user->user_id. '"' . ' your employement status is a n ' . '"' .$new_user->employee_type. '"';
Here, you are instantiating a single instance of your user class assigned to the variable $new_user, and then accessing the properties of that single instance.
EDIT: .....Aaaaaaaaand - I was too slow :-)

Is there a way to prefix Zend_Form element name?

I have a page that has multiple forms on it. Several of the forms share an element with the same name like CustomerID. This means the element ID CustomerID will collide with that same ID in the other forms. I would like to find a clean way to prefix the field name with the name of the form. For instance PaymentProfile_CustomerID. Suggestions?
So far, the best I have been able to come up with is:
class MyForm extends Zend_Form
{
public function init()
{
$this->setName("PaymentProfile");
...
$this->_prefixElementNames();
}
private function _prefixElementNames()
{
$elements = $this->getElements();
$formName = $this->getName();
foreach($elements as $e) {
$e->setAttrib('id', $formName . '_' . $e->getName());
}
}
}
UPDATE #garvey's answer below worked well with a simple modification.
public function addElement($element, $name = null, $options = null)
{
$e = parent::addElement($element, $name, $options);
if($this->getName())
// I use setAttrib instead of setName because I only want the ID to be changed.
// Didn't want the form data to be prefixed, just the unique HTML identifier.
$element->setAttrib('id', $this->getName() . '_' . $element->getName());
return $e;
}
I think it's easier to just use elementsBelongTo:
public function init()
{
$this->setOptions(array(
'elementsBelongTo' => 'form_name'
));
}
edit: expanded for future use
Using elementsBelongTo wraps all form elements in array, so you'll get
Zend_Debug::dump($this->_getAllParams())
outputs:
["form_name"] => array(
["element1"] => "value1"
["element2"] => "value2"
)
I have investigated your issue. And I think the best way is to extend Zend_Form class like this:
class Cubique_Form extends Zend_Form
{
public function addElement($el)
{
$el->setName($this->getName() . '_' . $el->getName());
parent::addElement($el);
}
}
And form creation:
$form = new Cubique_Form();
$form->setName('form');
$el = new Zend_Form_Element_Text('element');
$form->addElement($el);

Categories