Archive for April, 2010


I spend quiet a lot of time on this one, I posted arround here and there to find the anwser on how to make a JsonRestStore happend with Zend Framework. There are quiet a few tutorials out there but my main problem was a response from the server when POST request was made (when creating a new document).

Well here’s the solution :
$this->getResponse()
->setHttpResponseCode(201)
->setHeader('Content-Type', 'application/json', true)
->setHeader("Location", 'http://mywebsite' . $this->_request->getRequestUri() . $id);

$params['id'] = $id;
return $params;

First : you need to send back a code 201. Second, you need to send the url of the store with the new id (ex : mysite/store/4
Then you need to send back the content of the item created + the id in order to be able to play with it with DOJO. Otherwise, no fun.

Here’s the dojo part of the code :

testStore = new dojox.data.JsonRestStore({jsId:"tStore", target:"/test/", idAttribute:"id" });

// Get the content of a form with a magic dojo query
data = {};
dojo.query(" textarea, .ArticleNewFormElement > input").forEach(function(node, index, arr){
if(node.id){
data[node.id] = dijit.byId(node.id).attr("value");
}
});

// Add the item to the DataStore
var newClient = clientsStore.newItem(data);

// Save it back to the server
clientsStore.save({onComplete:function(item) {

// Now you can play with the ID of the element you just created, so cool !
console.log(newClient.id);

}
});

Note that I changed a few variables here and there for my blog without rechecking the entire stuff so re-read it if you need to use it, but it works. JsonRestStore is your friend I tell you !

I’m having so much fun with dojo.query. Here’s as simple way to send back input elements to your server using a JsonRestStore :

clientStore = new dojox.data.JsonRestStore({
jsId:"MyStore",
target:"/mystore/",
idAttribute:"id"
});

// Get the content of the form
data = {};
dojo.query(" textarea, .ArticleNewFormElement > input").forEach(function(node, index, arr){
if(node.id){
data[node.id] = dijit.byId(node.id).attr("value");
}
});

var newClient = clientStore.newItem(data);

clientStore.save();

When I think I use to do Title = dijit.byId(“Title”)… and then collect each of the elements and then send this through an XhrPost, wha, I’m really goind quicker now. Well I guess that’s the whole deal of beeing a beginner at things ūüėČ

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 !!

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 !