Latest Entries »

The magic of dojo query

I haven’t used dojo query before today. It’s just a great tool, it’s so time saving… This is a great tool particularly for dojo form if you start playing with it.

Let’s look at how I used to get the data back of a form :

// Get the content of Title, Summary, WherePublished, PublicationDate, ShowProfile
Title = dijit.byId("Title").attr("value");
Summary = dijit.byId("Summary").attr("value");
WherePublished = dijit.byId("WherePublished").attr("value");
DatePublished = dijit.byId("DatePublished").attr("value");
//PublishProfile = dijit.byId("PublishProfile").attr("value");

// Get the content of the Editor
Editor = dijit.byId("Editor").attr("value");

And off we go to put this on a xhr query… Well the good new is that you can get all this (very) boring stuff in only one / two lines of code without the hassle of finding each field. Saves time no ?

Here it is :
data = [];
dojo.query(" textarea, .ArticleNewFormElement > input").forEach(function(node, index, arr){
if(node.id){
data[node.id] = dijit.byId(node.id).attr("value");
}
});

That’s it, you can send back data to your server. By simply placing your elements inside divs you control (ex. : MyClass) you’ll be able to get the content of all the elements of a form.

Damn I’ll never write these long fields getters anymore !!

Advertisements

I was trying to get the content of a form I was building and hooops, where did the fucker go… Unable to get the content of my TextBox element with traditionnal methods like:

data = dijit.byId(“Title”).innerHTML ;

That doesn’t work… because dijits are not dom elements, but objects. Shit I should have known (thanks for IRC dojo channel for answering my so many questions).

What works simply is :

Title = dijit.byId(“Title”).attr(“value”);

And there you go !

Here are some tests functions I wrote for testing the validity of the access control lists of my website. Nothing fancy but it’s an exemple that may be usefull for begginners.

  1. private function CanAccess($url)
  2. {
  3. $this->dispatch($url);
  4. $this->assertNotResponseCode(‘404’);
  5. list($controller, $action) = explode(“/”, ereg_replace(“^/”, “”, $url));
  6. $this->assertController($controller);
  7. $this->assertAction($action);
  8. }
  9. private function CanNotAccess($url)
  10. {
  11. $this->dispatch($url);
  12. // if the user is Guest
  13. if(!Zend_Auth::getInstance()->hasIdentity())
  14. {
  15. $this->assertController(‘user’);
  16. $this->assertAction(‘login’);
  17. // CustomAclManager Should show a Login form
  18. $this->assertQueryCountMin(‘form’, 1);
  19. $this->assertQueryCountMin(‘input[name~=”email”]’, 1);
  20. $this->assertQueryCountMin(‘input[name~=”password”]’, 1);
  21. $this->assertQueryCountMin(‘input[name~=”submit”]’, 1);
  22. }
  23. // If user is logged In he’ll only get redirected
  24. else
  25. $this->assertRedirect;
  26. }
  27. private function LoginRealUser()
  28. {
  29. $this->request->setMethod(‘POST’)
  30. ->setPost(array(
  31. ’email’ => ‘regularuser@nowhere.com’,
  32. ‘password’ => ‘usertests’,
  33. ));
  34. $this->dispatch(‘/user/login’);
  35. $this->assertRedirect;
  36. $this->assertTrue(Zend_Auth::getInstance()->hasIdentity());
  37. }
  38. // ok, now let’s run some tests
  39. public function testGuestAccessRightsAreOk()
  40. {
  41. $this->CanAccess(‘/user/login’);
  42. }
  43. public function testLoggedInUserAccessRightsAreOk()
  44. {
  45. $this->LoginRealUser();
  46. $this->CanAccess(‘/user/logout’);
  47. }
  48. // testing where users can not go
  49. public function testGuestRestrictionsAreOk()
  50. {
  51. $this->CanNotAccess(‘/user/logout’);
  52. $this->CanNotAccess(‘/user/index’);
  53. }
  54. public function testLoggedInRestrictionsAreOk()
  55. {
  56. $this->LoginRealUser();
  57. $this->CanNotAccess(‘/user/login’);
  58. }

A simple way to test your user access rights !

It’s sunday and I’m playing with Zend_Test. Here are some basic things that took me time to find out :
Grep simple text in the page :

  1. $this->assertQueryContentContains(‘body’, “your email is invalid”);

Verify unvalid users can not log in :

  1. $this->request->setMethod(‘POST’)
  2. ->setPost(array(
  3. ’email’ => ‘fakeaddress@fakedomain.com’,
  4. ‘password’ => ‘fakepassw’
  5. ));
  6. $this->dispatch(‘/user/login’);
  7. $this->assertNotRedirect();
  8. $this->assertFalse(Zend_Auth::getInstance()->hasIdentity());

The interesting part is the last part :

  1. $this->assertFalse(Zend_Auth::getInstance()->hasIdentity());

And, let’s test a form :

  1. $this->assertQueryCountMin(‘form’, 1);
  2. $this->assertQueryCountMin(‘input[name~=”email”]’, 1);
  3. $this->assertQueryCountMin(‘input[name~=”password”]’, 1);
  4. $this->assertQueryCountMin(‘input[name~=”submit”]’, 1);

Nothing fancy here, only some tips that can only make your discovering of Zend_Test easyer ! Happy testing !

This morning I wanted to play with the Zend_Dojo Editor in order to allow users to submit content. Honestly from what I saw I don’t really like the looks of it (checkout the microsoft version of a web editor in Sharepoint if you want to compare), but well I thought it’ll do the trick for the moment. So I added this in my form :

  1. $this->addElement(‘editor’, ‘content’,
  2. array(
  3. ‘editActionInterval’ => 2,
  4. ‘focusOnLoad’        => true,
  5. ‘height’             => ‘250px’,
  6. ‘inheritWidth’       => true,
  7. ));

And all I got was an error ! Why, because the Dojo editor exists only in the svn trunk for the moment (it seems to be scheduled for the 1.7 version). The question is : should that really stop you from using it ? Ok, you know the answer, so let’s go on to the second problem : how to get the framework from svn ? Unfortunately I couldn’t get an explanation from zend.com since the corresponding pages were down, so I had to google arround to find what I was looking for. And guess what, a simple command line does the trick :

  1. svn checkout http://framework.zend.com/svn/framework

And here you go…

The integration of Dojo in the Zend Framework is very nice, it allows us to play with some nice features of this library. Well, let’s get to work, and build a simple login form :

  1. class  LoginForm extends Zend_Dojo_Form
  2. {
  3. public function init()
  4. {
  5. // Dojo-enable the form:
  6. Zend_Dojo::enableForm($this);
  7. $this->setName(‘Login’);
  8. $this->setAction(‘/user/login’)
  9. ->setMethod(‘post’);
  10. // EMAIL
  11. $this->addElement(
  12. ‘ValidationTextBox’,
  13. ’email’,
  14. array(
  15. ‘value’      => ”,
  16. ‘label’      => ‘Email address : ‘,
  17. ‘trim’       => true,
  18. ‘lowercase’  => true,
  19. ‘required’   => true,
  20. ‘regExp’         => ‘^.{4,}$’,
  21. ‘invalidMessage’ => ‘Insert your email’,
  22. ‘validators’ => array(
  23. ‘EmailAddress’,
  24. array(‘StringLength’, false, 4)
  25. ),
  26. ‘filters’  => array(‘StringToLower’),
  27. )
  28. );
  29. // PASSWORD
  30. $this->addElement(
  31. ‘PasswordTextBox’,
  32. ‘password’,
  33. array(
  34. ‘label’          => ‘Password’,
  35. ‘required’       => true,
  36. ‘trim’           => true,
  37. ‘regExp’         => ‘^.{4,}$’,
  38. ‘invalidMessage’ => ‘Invalid password’,
  39. ‘validators’  => array(array(‘StringLength’, false, 4))
  40. )
  41. );
  42. // SUBMIT
  43. $this->addElement(
  44. ‘SubmitButton’,
  45. ‘submit’,
  46. array(
  47. ‘required’   => false,
  48. ‘ignore’     => true,
  49. ‘label’      => ‘Submit Button!’,
  50. )
  51. );
  52. }
  53. }

And it’s pretty straight forward to use :

  1. // initialize the
  2. form = new LoginForm();

Here are some tests functions I wrote for testing the validity of the access control lists of my website. Nothing fancy but it’s an exemple that may be usefull for begginners.

  1. private function CanAccess($url)
  2. {
  3. $this->dispatch($url);
  4. $this->assertNotResponseCode(‘404’);
  5. list($controller, $action) = explode(“/”, ereg_replace(“^/”, “”, $url));
  6. $this->assertController($controller);
  7. $this->assertAction($action);
  8. }
  9. private function CanNotAccess($url)
  10. {
  11. $this->dispatch($url);
  12. // if the user is Guest
  13. if(!Zend_Auth::getInstance()->hasIdentity())
  14. {
  15. $this->assertController(‘user’);
  16. $this->assertAction(‘login’);
  17. // CustomAclManager Should show a Login form
  18. $this->assertQueryCountMin(‘form’, 1);
  19. $this->assertQueryCountMin(‘input[name~=”email”]’, 1);
  20. $this->assertQueryCountMin(‘input[name~=”password”]’, 1);
  21. $this->assertQueryCountMin(‘input[name~=”submit”]’, 1);
  22. }
  23. // If user is logged In he’ll only get redirected
  24. else
  25. $this->assertRedirect;
  26. }
  27. private function LoginRealUser()
  28. {
  29. $this->request->setMethod(‘POST’)
  30. ->setPost(array(
  31. ’email’ => ‘regularuser@nowhere.com’,
  32. ‘password’ => ‘usertests’,
  33. ));
  34. $this->dispatch(‘/user/login’);
  35. $this->assertRedirect;
  36. $this->assertTrue(Zend_Auth::getInstance()->hasIdentity());
  37. }
  38. // ok, now let’s run some tests
  39. public function testGuestAccessRightsAreOk()
  40. {
  41. $this->CanAccess(‘/user/login’);
  42. }
  43. public function testLoggedInUserAccessRightsAreOk()
  44. {
  45. $this->LoginRealUser();
  46. $this->CanAccess(‘/user/logout’);
  47. }
  48. // testing where users can not go
  49. public function testGuestRestrictionsAreOk()
  50. {
  51. $this->CanNotAccess(‘/user/logout’);
  52. $this->CanNotAccess(‘/user/index’);
  53. }
  54. public function testLoggedInRestrictionsAreOk()
  55. {
  56. $this->LoginRealUser();
  57. $this->CanNotAccess(‘/user/login’);
  58. }

A simple way to test your user access rights !

Damn, I spent so much time building this, I’m happy I could find the solution ! Here’s a dojo grid working with Zend framework. I fist tried this on the view controller, but it got me nowhere :

  1. // My function that is supposed to add the
  2. // OD column to ID, it never gets fired…
  3. <script type=”text/javascript”>
  4. function getODtoID()  {  alert(“test”);   }
  5. </script>
  6. /* My grid, it’s working except get=”getODtoID” */
  7. <table id=”grid” dojotype=”dojox.grid.Grid” store=”pStore” query=”{ post_id: ‘*’}”>
  8. <thead>
  9. <tr>
  10. <th field=”status” width=”30px”>Status</th>
  11. <th width=”5em” get=”getODtoID”>OD to ID</th>
  12. </tr>
  13. </thead>
  14. </table>
  15. dojo()->enable()
  16. ->setDjConfigOption(‘parseOnLoad’, true)
  17. ->requireModule(‘dojo.parser’)
  18. ->requireModule(‘dojo.data.ItemFileReadStore’)
  19. ->requireModule(‘dojox.grid.Grid’)
  20. ->requireModule(‘dojox.grid._data.model’);
  21. ?>

The problem was that I couldn’t get the function getODtoID to be executed. I wanted to build a link on my grid, and for that I needed some very basic calculation. So what’s the solution ? I still can’t figure out why it’s not working this way, but I tryied something else :

  1. <script type=”text/javascript”>
  2. var customColumn = function(inRowIndex) {
  3. // This is standard for many grid handlers
  4. if (! dijit.byId(‘grid’).model.data[inRowIndex]) {
  5. return;
  6. }
  7. return “<a href=\”/blogmanager/edit?id=” +
  8. model.getRow(inRowIndex).post_id + “\”>edit</a>”;
  9. }
  10. var view = {
  11. cells:  [[
  12. { name: “Post id”, field: “post_id” },
  13. { name: ‘Link’, get: customColumn }
  14. ],
  15. ]};
  16. var layout = [ view ];
  17. </script>
  18. <div dojotype=”dojox.grid.data.DojoData” jsid=”model” store=”pStore” query=”{ post_id: ‘*’ }” clientsort=”true”></div>
  19. <div id=”grid” dojotype=”dojox.Grid” model=”model” structure=”layout”></div>
  20. dojo()->enable()
  21. ->setDjConfigOption(‘parseOnLoad’, true)
  22. ->setDjConfigOption(‘isDebug’, true)
  23. ->requireModule(‘dojo.parser’)
  24. ->requireModule(‘dojo.data.ItemFileReadStore’)
  25. ->requireModule(‘dojox.grid.Grid’);
  26. ?>

And that’s working fine, fine fine. So now it’s easy to build custom cells withing your grids !

Here’s a new problem : I want to be able to send mails using a template system. I use this for registration purepose mostly (email account confirmation, registration, etc.). Here’s a function that does this with Zend_Mail :

  1. public function sendEmail($arguments)
  2. {
  3. // Get the template arguments
  4. $template  = $arguments[‘template’];
  5. $subject  = $arguments[‘subject’];
  6. $templatearguments = $arguments[‘templateArguments’];
  7. // build a view
  8. $view = new Zend_View;
  9. $view->setScriptPath(Zend_Registry::get(‘config’)->email->folder);
  10. // Assign each item
  11. foreach($templatearguments as $k => $v){
  12. $view->assign($k, $v);
  13. }
  14. // render the template
  15. $body = $view->render($template);
  16. // Send the password by mail ;
  17. // NOTE : the message is in the $body variable (in the mail)
  18. $mail = new Zend_Mail();
  19. $mail->setBodyText($body)
  20. ->setFrom(“me@fromme.com”,”Z”)
  21. ->addTo($this->email)
  22. ->setSubject($subject);
  23. $transport = new Zend_Mail_Transport_Smtp(“my.smtp.server.com”);
  24. $logger = Zend_Registry::get(‘logger’);
  25. // Try to send the email, or log the exception
  26. try
  27. {
  28. $mail->send($transport);
  29. $logger->notice(“mail sent to ” . $this->email);
  30. }
  31. catch (Exception $e)
  32. {
  33. $logger->warn(“Error sending mail “. $e->getMessage());
  34. }
  35. }

Ok, so how would I use this ? First set up the arguments, and then use the function…

  1. $emailarguments = array(‘template’ => ‘userRegistrationEmail.phtml’,
  2. ‘subject’  => ‘Account creation’,
  3. ‘templateArguments’ => array(‘uid’ => $user->Id(),
  4. ‘key’ => $user->key,
  5. ’email’=> $user->email)
  6. );
  7. // ok done, now send the mail
  8. sendEmail($emailarguments)

Let’s find out how to format the mail, well simply like this :

  1. $body = “\n Dear user,”;
  2. $body .= “\n”;
  3. $body .= “\nThank you for your registration.  :”;
  4. (…)
  5. $body .= “\nWeb Site Administrator”;
  6. echo $body;

Zend framework is a big thing and takes time to learn. Today I found another problem I don’t know how to solve, it’s about sending a dojo form in a placeholder located in my layout. The form is a simple login form that works fine. However when I try to put it in the placeholder the form shows but without dojo applying to it. Here’s an extract : This doesn’t work, on index.phtml :

  1. $login = new Login();
  2. $this->placeholder(‘loginbox’)->set($login);

Here’s the target in my layout file :

  1. placeholder(‘loginbox’); ?>

However this works fine in the index.phtml :

  1. $login = new Login();
  2. echo $login ;

Damn !