Category: Uncategorized


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 !

If there’s somewhere a mystery bug contest I’m probably winning the race. Here’s a new one : try to get a view helper to work with javascript. Anyone has a solution ? Here’s my unworking code :

  1. class Zend_View_Helper_Loginbox extends Zend_View_Helper_Partial
  2. {
  3. public function loginbox()
  4. {
  5. $this->view->headScript()->appendFile(‘/scripts/js/myfile.js’);
  6. // this doesn’t work, the file never gets included
  7. $this->view->dojo()->javascriptCaptureStart();
  8. // neigher the content of my javascript function after this
  9. ?>
  10. dojo.addOnLoad(function(){
  11. alert(“it s working”);
  12. });
  13. view->dojo()->javascriptCaptureEnd(); ?>
  14. <div id=”box” class=”box”>test</div>
  15. <div id=”blockme” class=”blockme”>
  16. <form method=”post” action=”/user/login” id=”loginform”>
  17. <label for=”email”>Email:</label>
  18. <input type=”text” name=”email”>
  19. <label for=”password”></label>
  20. <input type=”password” name=”password”>
  21. <input type=”submit” id=”loginButton” value=”login”>
  22. <div id=”loginerrors”></div>
  23. </form>
  24. </div>

Javascript never get to be on the client server. Any idea why ?

I’m so bored about this kind of errors :

  1. www# svn commit
  2. svn: Commit failed (details follow):
  3. svn: Directory ‘/var/trunk/trunk/’ is missing
  4. svn: Directory ‘/var/trunk/trunk/’is missing
  5. www#

Damn i wish there was a simple solution out of this, than to re-chechout each time your svn rep and re-delete your directory ! Hell with svn I say !

It’s very unclear, both in the Zend documentation and the Dojo one, how it is possible to order a JsonRest server (the Zend one while we’re at it!) to reply to JsonRest client (dojo…). I’ve tryied to make this happen for 2 days now… Here’s the client side :

  1. <b style=”color:black;background-color:#ffff66″>dojo</b>.addOnLoad(function(){
  2. store = new dojox.data.JsonRestStore({target:”/test/m”});
  3. var newItem = store.newItem(
  4. {
  5. post_id: 123
  6. });
  7. store.save();
  8. (…)

Then, on the server side : x First modify the router :

  1. $route = new Zend_Controller_Router_Route(‘test/m/:id/*’, array(‘controller’=>’test’, ‘action’=>’m’));
  2. $front->getRouter()->addRoute(‘test’, $route);

x Then add a a function in a custom class :

  1. /*
  2. * returns hello world
  3. * @return string
  4. *
  5. */
  6. public static function addmyitem($item){
  7. // custom code
  8. return “Item added”;
  9. }

=> But, how am I supposed to map this function to the action controller in order to reply to the Rest POST request dojo is executing ??? That’s not getting me anywhere…

  1. // Disable auto-rendering and layouts
  2. $this->_helper->viewRenderer->setNoRender(true);
  3. $this->_helper->layout->disableLayout(true);
  4. $id = $this->getRequest()->getParam(‘id’);
  5. $server = new Zend_Json_Server();
  6. $server->setClass(‘RpcTest’);
  7. if(‘GET’ == $_SERVER[‘REQUEST_METHOD’]){
  8. $server->setTarget(‘/test/m’)
  9. ->setEnvelope(Zend_Json_Server_Smd::ENV_JSONRPC_2);
  10. $smd->setDojoCompatible(true);
  11. header(‘Content-Type: application/<b style=”color:black;background-color:#99ff99″>json</b>’);
  12. echo $smd;
  13. return;
  14. }
  15. $server->handle();

Finally I’m questionning the use of the Zend Json server : would’nt it be simpler to get rid of the server and directly reply using :

  1. if(‘GET’ == $_SERVER[‘REQUEST_METHOD’]){
  2. $data = get_item_data_by_id($this->getRequest()->getParam(‘id’));
  3. sendToJson($data);
  4. }

Now : how are we supposed to make this work ?

I was wondering how to read the entire content of a datastore. I often query here or there one item, but it’s the first time I wanted to read the entire stuff.

My idea was to send the entire content back to the server. So how do you do that ?

store.fetch({
onComplete: function(items, request){

console.log(items);
}

});

The most simple way possible I’d say 😉