I've an xml file containing tag like this.
<server>
<conversation ip="12.0.0.1" email="none">
<chat userstatus="1" adminstatus="2" username="admin">muja</chat>
</conversation>
</server>
Now I want to update the email attribute of the conversation tag.
When I use $conv->getAttribute("email") it echo's me the correct result i.e none.But if I try to set it using $conv->setAttribute("email","abc") it does not update the value.
Here's what I am doing.
This is the GetClientConversation():
private function GetClientConversation()
{
foreach($this->conversation as $convTag)
{
if($convTag->getAttribute("ip") == $this->clientip)
{
return $convTag;
}
}
return "noConversation";
}
This function returns me the correct conversationTag that I needed.
And i get these conversationsTags array using
$this->conversation=$this->xmlDom->getElementsByTagName("conversation");
Edit:
public function GetConversation()
{
$conv=$this->GetClientConversation();
if($conv!="noConversation")
{
if($conv->getAttribute("email")=="none")
{
$conv->setAttribute("email","abc"); // -- Here
return json_encode($this->RetrieveConversation($conv));
}
else if($conv->getAttribute("email")==$this->adminEmail)
{
return json_encode($this->RetrieveConversation($conv));
}
else
{
return "Admin Already Chatting";
}
}
else
{
$this->CreateNewConversation();
return "no";
}
}
This is the code from where I am trying to set the attribute.
You have correctly used setAttribute().
You are retrieving your XML and passing the string back to json_encode(). However, if the RetrieveConversation() method has not correctly called saveXML() prior to returning the string, your modifications will not be available in the output XML string. Be sure you have called saveXML().
Related
I have one function call remove_certificate_packages($certificate_id, array_keys($package_id)) this will invoke the below function
function remove_certificate_packages($certificate_id, $package_id)
{
if (is_numeric($package_id)) // so this is list of package id:s
$package_id = array($package_id);
if (!$package_id) return true;
**notify_package_unlinked($certificate_id,array_keys($package_id));**//one more func call
return true;
}
in this function, I have one more function call "notify_package_unlinked" I need to pass the "$package_id". It will call the appropriate function but the problem is, in the "notify_package_unlinked" function the value is showing "Array". What is the problem? Could you please help
function notify_package_unlinked($certificate_id,$package_id)
{
$query="select id,filename,version from packages where id =$package_id";
$res = db_query($query);
$package= db_fetch_object($res);
$packid=$package->id;
$packname=$package->filename;
$packversion=$package->version;
print "$packid"; // here it is printing the value"Array"
}
I got my output using foreach loop .
foreach($package_id as $id){$pack=$id;}
I have the following code to validate form data. I have created functions to validate various groups, and then have an if isset statement to check if these functions return true. I have tried many different ways to get this to work.
The problem I am having is this. I want the if isset to end if returning FALSE; but it doesn't, it keeps going and pops up the next alert (in my code I have many functions). How can I get it to exit after the first return FALSE? Do I need to make the isset into a function? So it can exit on return FALSE. thanks
I am having trouble writing a function to call functions in php.
function namecheck ($fname, $lname)
{
$regexp ="/^[A-Za-z]+$/";
//filter through names
if (preg_match($regexp,$fname,$lname))
{
return TRUE;
}
else
{
echo'<script type="text/javascript">alert("Enter your names.")</script>';
return FALSE;
}
}
function emailcheck ($email1, $email2)
{
$regexp="/^[a-zA-A-Z0-9_.]+#[a-zA-Z0-9-]+\.[a-zA-Z0-9.-]+$/";
//validate email address
if (preg_match($regexp,$email1,$email2))
{
return TRUE;
}
else
{
echo '<script type="text/javascript">alert ("Enter a valid email address.")</script>';
return FALSE;
}
}
$fname=$_POST['fname'];
$lname=$_POST['lname'];
$namecheck=namecheck($fname,$lname);
$email1=$_POST['email1'];
$email2=$_POST['email2'];
$emailcheck=emailcheck($email1,$email2);
if (isset($_POST['submit']))
{
if ($namecheck !==TRUE)
{
return FALSE;
}
elseif ($emailcheck!==TRUE)
{
return FALSE;
} //and so on..
else
{
return TRUE;
}
}
A general structure for your functions you could follow is something like this:
function validateName($name) {
// Do Validation. Return true or false.
}
function validateEmail($email) {
// Do Validation. Return true or false.
}
function isFormValid()
{
// Name Validation
if( ! validateName( $_POST['name'] ) )
return false;
// Email Validation
if( ! validateEmail( $_POST['email'] ) )
return false;
// Form is valid if it reached this far.
return true;
}
// In your regular code on Form Submit
if( isset($_POST['submit']) )
{
if( isFormValid() ) {
// Save Form Data to DB
} else {
// Show Some Errors
}
}
That general structure should work fine for you. It could be made a LOT better but, for the sake of learning, this is sufficient.
If you want the script to, as you put, "exit" then you need to use exit(); Generally this is bad as the script will completely stop executing. Maybe you can look into using "break;" to get you out of a loop and stop executing functions within that loop. Another problem is that you are echoing out HTML code in your function which gets executed on assignment and so you will always get an alert generated when it evaluates to FALSE.
edit:
within your if(isset()) block. Inside here you can do{}while(false); which is a loop and will let you break out of it at anytime and prevent further execution of code within that loop.
If a function isn't returning false, then it never reached a return FALSE; statement. It's as simple as that. So let's examine the relevant code:
if (isset($_POST['submit']))
{
if ($namecheck !==TRUE)
{
return FALSE;
}
elseif ($emailcheck !== TRUE)
{
return FALSE;
} //and so on..
else
{
return TRUE;
}
}
So, if $_POST['submit'] is set and is not null, the if block will be reached. Then, if $namecheck is not true OR $emailcheck is not true, the function will return FALSE. You can simplify the above code to just:
if (isset($_POST['submit']))
{
return !(!$namecheck || !$emailcheck);
}
However, it doesn't look like this code is inside a function, so the return statement will do nothing. You have to put it in a function if you want it to work like a function.
Beyond that, I can't help you. I don't know what you want to do with this code. You seem to know how to use and call functions, so I'm not sure what the problem is. If you want to return from a function, put code in a function and call return. Right now your code is not in a function, so return won't do anything.
I am starting to write phpUnit test and faced with such problem. 80% of my functions ending on such lines
$data["res"] = $this->get_some_html($this->some_id);
echo my_json_encode($data);
return true;
How can i make test on such kind of functions in my classes?
You need to isolate your code into testable 'chunks'. You can test that the function returns TRUE/FALSE given specified text, and then test the JSON return data given fixed information.
function my_json_encode($data)
{
return ...;
}
function get_some_html($element)
{
return ...;
}
function element_exists($element)
{
return ..;
}
function display_data($element)
{
if(element_exists($element)
{
$data = get_some_html($element);
$json = my_json_encode($data);
return true;
}
else
{
return false;
}
}
Testing:
public function test_my_json_encode()
{
$this->assertEquals($expected_encoded_data, my_json_encode($text));
}
public function test_get_some_html()
{
$this->assertEquals($expected_html, get_some_html('ExistingElementId'));
}
public function test_element_exists()
{
$this->assertTrue(element_exists('ExistingElementId');
$this->assertFalse(element_exists('NonExistingElementId');
}
function test_display_data()
{
$this->assertTrue(display_data('ExistingElementId'));
$this->assertFalse(element_exists('NonExistingElementId');
}
This is a simple, abstract example of the changes and the testing. As the comments above have indicated, you might want to change the return to be the JSON text, and a FALSE on error, then use === testing in your code to decide to display the text or not.
The next step would be to mock out the Elements, so you can get expected data without the need for a real HTML page.
Im carrying out some form validation with codeigniter using a custom validation callback.
$this->form_validation->set_rules('testPost', 'test', 'callback_myTest');
The callback runs in a model and works as expected if the return value is TRUE or FALSE. However the docs also say you can return a string of your choice.
For example if I have a date which is validated, but then in the same function the format of the date is changed how would I return and retrieve this new formatted value back in my controller?
Thanks for reading and appreiate the help.
I'm not entirely sure I got what you were asking, but here's an attempt.
You could define a function within the constructor that serves as the callback, and from within that function use your model. Something like this:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Controllername extends CI_Controller {
private $processedValue;
public function index()
{
$this->form_validation->set_rules('testpost','test','callback');
if ($this->form_validation->run()) {
//validation successful
echo $this->processedValue; //outputs the value returned by the model
} else {
//validation failed
}
}
private function callback($input)
{
$this->load->model('yourmodel');
$return = $this->yourmodel->doStuff($input);
//now you have the user's input in $input
// and the returned value in $return
//do some checks and return true/false
$this->processedValue = $return;
}
}
public function myTest($data){ // as the callback made by "callback_myTest"
// Do your stuff here
if(condition failed)
{
$this->form_validation->set_message('myTest', "Your string message");
return false;
}
else
{
return true;
}
}
Please try this one.
I looked at function _execute in file Form_validation of codeigniter. It sets var $_field_data to the result of callback gets(If the result is not boolean). There is another function "set_value". Use it with the parameter which is name of your field e.g. set_value('testPost') and see if you can get the result.
The way Tank_Auth does this in a controller is like so
$this->form_validation->set_rules('login', 'Login', 'trim|required|xss_clean');
if ($this->form_validation->run()) {
// validation ok
$this->form_validation->set_value('login')
}
Using the set_value method of form_validation is undocumented however I believe this is how they get the processed value of login after it has been trimmed and cleaned.
I don't really like the idea of having to setup a new variable to store this value directly from the custom validation function.
edit: sorry, misunderstood the question. Use a custom callback, perhaps. Or use the php $_POST collection (skipping codeigniter)...apologies haven't tested, but I hope someone can build on this...
eg:
function _is_startdate_first($str)
{
$str= do something to $str;
or
$_POST['myinput'} = do something to $str;
}
================
This is how I rename my custom callbacks:
$this->form_validation->set_message('_is_startdate_first', 'The start date must be first');
.....
Separately, here's the callback function:
function _is_startdate_first($str)
{
$startdate = new DateTime($this->input->post('startdate'), new DateTimeZone($this->tank_auth->timezone()));
$enddate = new DateTime($this->input->post('enddate'), new DateTimeZone($this->tank_auth->timezone()));
if ($startdate>$enddate) {
return false;
} else {
return true;
}
}
I'm successfully updating the innerHTML of a DIV through xajax (when I click a link) but only when I assign HTML in the function itself, not when I call it from a different function.
To explain
// For the sake of testing
$output=rand(20,40);
// Add new HTML to container through $output
$ajax_resp->assign('div_container','innerHTML', $output);
return $ajax_resp;
This works fine. When I call this function through clicking the link, the container updates with a random number. However when I change $output to
$output=$compile->show('text');
Which is (simplified)
function show($var) { echo $var; }
It does not show it. The function show works perfectly outside of xajax. Any suggestions?
function show($var) { echo $var; }
This function doesn't return anything, it echo's the value to the screen. However, most functions you probably want to return a value, so they can work with it. Basically, when you do
$output=$compile->show('text');
It will get no input from the show method, because show doesn't return any value. I think if you change it to the following:
function show($var) { return $var; }
It will work.
Have you tried to change function show($var) { echo $var; } to function show($var) { return $var; }. Should solve your problem