Boot Ubuntu USB Drive in Virtual Box on Windows Environment

Recently i got my hand on a Ubuntu USB installation drive from my friend. I was excited to get this Ubuntu into my Virtual Box but found out that the virtual box doesn't seems to like USB drive very much and only wants ISO or CD copies! I finally manage to get this thing work after some try and so i decided to write this down in case i want to do such stupid thing again.

Environment

Before is starts let's look at my environment.

  1. Windows 7
  2. Virtual Box v3.2.12
  3. Ubuntu 10.10

I think that's about it.

Physical Disk on Virtual Box

Since virtual box does not know where to look at we have to specifically tell it to look at our hard drive. In order to do this we have to first know where is our current hard drive located (which parking slot). In Windows 7 or any windows environment you can easily find this by typing 'diskmgmt.msc' on the run section when you press Ctrl+Shift+Esc. You should see this below,


Once you clicked ok, the disk management tool box should appeared and you should take note of your disk location which is highlighted in red for my case.

Once you have done all these, you should have a clear idea where is your parking slot (drive location). Next we will need to create this physical location for our Virtual box to read.

You all might be aware that starting from Window Vista, most of our files are being protected. In order to create a physical drive, we will need to run our command prompt or terminal by pressing cmd.exe on run or through search (advisable since we want to run our command prompt on administration access).

The command prompt should pop out and you should now find the location of your virtualbox installation directory as shown below,

copy the location and paste it into the command prompt with cd infront which will give you this

cd C:\Program Files\Oracle\VirtualBox

Next, copy the following instruction into the command prompt as well

VBoxManage internalcommands createrawvmdk -filename C:\usbdrives.vmdk -rawdisk \\.\PhysicalDrive1 -register

In my case, my parking slot (drive location) was at 1. Hence, the above code writes \\.\PhysicalDrive# will be changed to \\.\PhysicalDrive1 instead of any other number. And "C:\usbdrives.vmdk" is the location i want to save my physical drive to. You should see something like this in your command prompt,

If you see any problem with creating a physical drive, it is most likely due to your permission of your command prompt.

Installation Of Ubuntu using USB Drive onto VirtualBox

Now we are ready to tell our VirtualBox our location of our USB drive. Firstly, you would have to open your virtualbox under Administrator access similarly to the way you open up the command prompt.

Next you would have to setup a new virtual machine and under its setting choose hard drive and select the newly created physical drive file as its IDE Controller.

Now start your virtual box and it should starts loading off your thumb drive!!

After installation complete

After your installation has complete, do remember to remove your physical drive under setting and select only the Ubuntu.vi on your SATA Controller since your IDE Controller will most likely installed with the VBoxGuestAdditional.iso as shown below,

Tutorial: jQuery Live With ExtJs

For all jQuery user out there. We are all fully aware that there is a function 'LIVE' in jQuery which sole purpose is to attach event handler into any new element entering the page dynamically. This is very clear and obvious in jQuery. However, in ExtJs it will be a little bit more confusing than you think it will be. Hence, i would like to drop this down on this article on the way ExtJS works.

jQuery Live Event

Before i come to the main point, let's look at how jQuery Live event works.

var event = function(){
alert("action clicked")
}
jQuery("p").live("click", event);

Simple and clear. We know what it does so i won't bother to explain.

ExtJs Live Event

How about ExtJs live event? Unfortunately, in Extjs this is not so direct. There are also tricks you should know in order to achieve the same functionality in Extjs. In Extjs, it is as simple as an event attachment as shown below,

var fblike_hide = function(ev, target){
	var item = Ext.get(target).findParent("#facebook_container", 50,true).setDisplayed("none");
}
Ext.getBody().on("click", fblike_hide, this, {delegate: ".fb_cancel"});

The above code shows two things. The method that was triggered upon a click event which is "fblike_hide" and the 'delegate' key used on the 'on' event attachement. The important here is the delegate. Extjs uses delegate to mimic the same behavior as 'LIVE' in jQuery. Of course, jQuery itself also has delegate method but i won't show here since i'm talking about jQuery Live.

In pure english the below sentences means,

Ext.getBody().on("click", fblike_hide, this, {delegate: ".fb_cancel"});

"Attached click event on all .fb_cancel element that can be found within the body tag. Fire 'fblike_hide' when click event is triggered on any element with the class 'fb_cancel'". The trick to use delegate in Extjs is to understand that the event click is attached to all element of .fb_cancel and not the body! The body doesn't get attached with a click event when the delegate key is used! If you are familiar with delegate in jQuery, this should be quite obvious but if you don't, you might get a little bit confuse by Extjs delegate functionality.

Hope it helps!

Tutorial: Remove index.php on localhost in Yii framework

This is another simple tutorial i find it useful for every Yii framework developer to know. Especially people who really want SEO capability on their Yii project. Without further crap from me, i will demonstrate how this can be done.

Setup Apache

The most important thing to get the thing you want in a local environment is to setup your Apache properly. Luckily setting up Apache for this tutorial wasn't that difficult, all you have to do is two step. Firstly, fire up your httpd.conf and look for the following line.

<Directory />
    Options FollowSymLinks
    AllowOverride None
    Order deny,allow
    Deny from all
</Directory>

Change AllowOverride None to Allow as shown below,

<Directory />
    Options FollowSymLinks
    AllowOverride All
    Order deny,allow
    Deny from all
</Directory>

Next we will have to enable mod_rewrite. Look for the following line,

#LoadModule proxy_ftp_module modules/mod_proxy_ftp.so
#LoadModule proxy_http_module modules/mod_proxy_http.so
#LoadModule rewrite_module modules/mod_rewrite.so
LoadModule setenvif_module modules/mod_setenvif.so
#LoadModule speling_module modules/mod_speling.so
#LoadModule ssl_module modules/mod_ssl.so
#LoadModule status_module modules/mod_status.so

And uncomment LoadModule rewrite_module bla bla bla and we should get something like this.

#LoadModule proxy_ftp_module modules/mod_proxy_ftp.so
#LoadModule proxy_http_module modules/mod_proxy_http.so
LoadModule rewrite_module modules/mod_rewrite.so
LoadModule setenvif_module modules/mod_setenvif.so
#LoadModule speling_module modules/mod_speling.so
#LoadModule ssl_module modules/mod_ssl.so
#LoadModule status_module modules/mod_status.so

Now, save this changes and restart your Apache server and we are done here.

Setup .htaccess

Now, the important thing is to tell Apache how to handle things that we are going to setup on our Yii framework. Hence, we will have to write some .htaccess rule to cater this. Firstly, where to place this?! Simple, we will put this just at the level where the "/protected/" folder is located (not inside the protected folder). Next, we should create a new .htaccess file with the following rules.

Options +FollowSymLinks
IndexIgnore */*
RewriteEngine on
RewriteBase /project name/

# if a directory or a file exists, use it directly
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

# otherwise forward it to index.php
RewriteRule . index.php

The whole world are using this rule so i won't bother to explain but do take note that you will need to rebase your project by changing "project name" to your folder name on this .htaccess file. And we are done here too.

Setup Yii Config

Finally, we can setup our Yii config! Fire up your /config/main.php file and overwrite your UrlManager rules with the following one.

		'urlManager'=>array(
			'urlFormat'=>'path',
			'rules'=>array(
				'<controller:\w+>/<id:\d+>'=>'<controller>/view',
				'<controller:\w+>/<action:\w+>/<id:\d+>'=>'<controller>/<action>',
				'<controller:\w+>/<action:\w+>'=>'<controller>/<action>',
			),
			'showScriptName'=>false,
			'caseSensitive'=>false,
		),

Once you do this, you should be gettting your index.php removed permanently!

Tutorial: How To Reuse Yii Contact Form

Here's another tutorial on Yii framework that i find it useful to write it down. I was using Yii framework on a project currently and wanted to reuse Yii built-in contact from into another view. Reusing Yii framework contact form is pretty straight forward until i find my captcha not showing out for some reason. Lucky, i manage to get it work with a little debugging and decides to write it down just in case someone gets stuck as well.

Contact Form Model

In order to reuse Yii contact form, we do not need to rebuild another new model for our contact form. Unless you want to do something extra that will affect your existing contact form model, you can actually reuse the model without creating a new one. In short, we can skip the model 😀

Contact Form View

Next, the model part will also be pretty straight forward. Since we are using the same model, all you have to do is to copy the content on the contact form view into your own view file. In this case, it will be these:

<?php $form=$this->beginWidget('CActiveForm'); ?>

	<p class="note">Fields with <span class="required">*</span> are required.</p>

	<?php echo $form->errorSummary($model); ?>

	<div class="row">
		<?php echo $form->labelEx($model,'name'); ?>
		<?php echo $form->textField($model,'name'); ?>
	</div>

	<div class="row">
		<?php echo $form->labelEx($model,'email'); ?>
		<?php echo $form->textField($model,'email'); ?>
	</div>

	<div class="row">
		<?php echo $form->labelEx($model,'subject'); ?>
		<?php echo $form->textField($model,'subject',array('size'=>60,'maxlength'=>128)); ?>
	</div>

	<div class="row">
		<?php echo $form->labelEx($model,'body'); ?>
		<?php echo $form->textArea($model,'body',array('rows'=>6, 'cols'=>50)); ?>
	</div>

	<?php if(extension_loaded('gd')): ?>
	<div class="row">
		<?php echo $form->labelEx($model,'verifyCode'); ?>
		<div>
		<?php $this->widget('CCaptcha'); ?>
		<?php echo $form->textField($model,'verifyCode'); ?>
		</div>
		<div class="hint">Please enter the letters as they are shown in the image above.
		<br/>Letters are not case-sensitive.</div>
	</div>
	<?php endif; ?>

	<div class="row buttons">
		<?php echo CHtml::submitButton('Submit'); ?>
	</div>

<?php $this->endWidget(); ?>

That's it.

Contact Form Controller

The trick to reuse Yii contact form lies on the controller. The main code without saying would be the following one.

		$model=new ContactForm;
		if(isset($_POST['ContactForm']))
		{
			$model->attributes=$_POST['ContactForm'];
			if($model->validate())
			{
				$headers="From: {$model->email}\r\nReply-To: {$model->email}";
				mail(Yii::app()->params['adminEmail'],$model->subject,$model->body,$headers);
				Yii::app()->user->setFlash('contact','Thank you for contacting us. We will respond to you as soon as possible.');
				$this->refresh();
			}
		}
		$this->render('contact',array('model'=>$model));

The render part you would need to change that because it will most likely be your view file instead. Next important things to take note of would be the captcha part.

You would need to add another method called 'action' which will define a need method for your captcha image to be created as shown below,

/**
	 * Declares class-based actions.
	 */
	public function actions()
	{
		return array(
			// captcha action renders the CAPTCHA image displayed on the contact page
			'captcha'=>array(
				'class'=>'CCaptchaAction',
				'backColor'=>0xFFFFFF,
			),
		);
	}

Next, you will need to add captcha action into your permission list in order for it to display out else you would find that your image will always be empty although you did everything correctly. (no permission. Hence, permission denial)

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow',  // allow all users to perform 'index' and 'view' actions
				'actions'=>array('index','view', 'captcha'),
				'users'=>array('*'),
			),
			array('allow', // allow authenticated user to perform 'create' and 'update' actions
				'actions'=>array('create','update'),
				'users'=>array('@'),
			),
			array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array('admin','delete'),
				'users'=>array('admin'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}

Once this is done, you should get your reused Yii contact form working on your new view file!

Summary

In case you are not interested in all of the tutorial, Here are the summary that you should take note of:

  • Contact Form is also build in MVC
  • You do not need to rebuild the model class unless you wanted something different
  • You will need to placed the code on the contact form controller into your own controller file
  • You will need to copy and paste the contact form view file into your own view file
  • Remmeber to add the action sections in order to use 'captcha' on your contact form.
  • Remember to allow 'captcha' action by users or else the image will never display

Tutorial: Populate 2 Model Information Using 1 Controller And 1 View In CRUD

Recently i have been playing with Yii to get something up for someone. However, i came into a lot of problem because i am very new to Yii framework. Hence, there is a lot of reading and try and error method for me. I faced a problem where i need to populate 2 model information into 1 view. However, the CRUD that produce the codes seems to only cater for 1 to 1 sort of relationship. Furthermore, there wasn't any good information on how to tackle this problem other than the one shown on the cook book. On the cook book, it is demonstrating a 1 to 1 model relationship. In my case, it is a 1 to many relationship. What should i do?

1 to many relationship model

The main problem that i'm facing was the 1 to many relationship between my model. I have a database structured similar to the one shown on my previous article, relational active record tutorial. The scheme is shown below,

CREATE TABLE IF NOT EXISTS `invoice` (
	`invoiceId` MEDIUMINT UNSIGNED NOT NULL,
	`invoiceTotalAmount` DOUBLE NOT NULL,
	PRIMARY KEY (`invoiceId`)
) 

CREATE TABLE IF NOT EXISTS `invoice_item` (
	`invoiceItemId` MEDIUMINT UNSIGNED NOT NULL AUTO_INCREMENT,
	`invoiceItemLineId` MEDIUMINT UNSIGNED NOT NULL,
	`invoiceId` MEDIUMINT UNSIGNED NOT NULL COMMENT "CONSTRAINT FOREIGN KEY (invoiceId) REFERENCES be_invoice(invoiceId)",
	PRIMARY KEY (`invoiceItemId`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;

In my situation, i have 1 invoice having multiple line of items. So how do i show it out on my invoice view and manage my InvoiceItem and Invoice model with 1 Invoice controller?

Requirement

You should have the following files for a 1 to many relationship model to populate on 1 view.

  • CRUD Invoice
  • Model InvoiceItem

That's it!

How to create a 1 to many relationship model to populate into 1 view

Firstly, you will have to setup the relationship between Invoice and InvoiceItem as shown on my previous tutorial. Once, you have done that, you shouldn't touch any of your models. The only thing you should be looking at would be the controller and view created by the Invoice CRUD.

Controller Setup

Majority settings will be done on the controller. Hence, it will be quite a challenge for me to explain it clearly without dumping you too much code. Therefore, i will only be focusing on the method actionUpdate which is the update page controller method. You should have a default controller method which only cater for 1 to 1 model controller method as shown below,

	public function actionUpdate()
	{
		$model=$this->loadModel();

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Invoice']))
		{
			$model->attributes=$_POST['Invoice'];
			if($model->save())
				$this->redirect(array('view','id'=>$model->invoiceItemId));
		}

		$this->render('update',array(
			'model'=>$model,
		));
	}

Right. At this point, this is not something we want. Hence, we will have to modified it to handle 1 to many relationship models.

	public function actionUpdate()
	{
		$Invoice=$this->loadModel();
		$InvoiceItem=$this->loadManyModel($Invoice);
		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Invoice']) && isset($_POST['InvoiceItem']))
		{
			$Invoice->attributes=$_POST['Invoice'];
			$valid=$Invoice->validate();
			$i = 0;
			$InvoiceItemLine = new InvoiceItem;
			foreach($_POST['InvoiceItem'] as $item){
				if(isset($InvoiceItem[$i]))
					$InvoiceItemLine = $InvoiceItem[$i];
				$InvoiceItemLine->attributes= $item;
				$valid=$InvoiceItemLine->validate() && $valid;
				if(!$valid){
					$valid = false;
				}
				$i++;
			}

			if($Invoice->save() && $valid){
				$i = 0;
				foreach($_POST['InvoiceItem'] as $item){
					if(isset($InvoiceItem[$i]))
					$InvoiceItemLine = $InvoiceItem[$i];
					$InvoiceItemLine->save();
					$i++;
				}
				$this->redirect(array('view','id'=>$Invoice->invoiceId));
			}
		}

		$this->render('update',array(
			'Invoice'=>$Invoice,
			'InvoiceItem'=>$InvoiceItem,
		));
	}

You will notice that the above method has been modified significantly to cater for 1 to many relationship. In this method, there is one new method named 'loadManyModel'. This method basically uses the lazy loading approach to get the many relationship model record into display and is shown below,

	public function loadManyModel($model)
	{
		if($this->_models===null)
		{
			if(isset($_GET['id']))
				$this->_models=$model->invoiceItems;
			if($this->_models===null)
				throw new CHttpException(404,'The requested page does not exist.');
		}
		return $this->_models;
	}

The method will required to take in the loadModel return value which is the single relationship model object so that we can use the lazy loading approach. If you have no idea what i am talking about, please read my previous tutorial before coming here. This is being done this way to improve the efficiency and reduce the number of SQL query being called by using the eager loading approach. (take note that there is a new global variables called $_models which you would have to declared next to the global variables $_model)

I'm pretty lazy to explain what is the actionUpdate method is trying to do. But i will explain the concept behind this which it probably makes more sense. In my case, there are two model where Invoice only has 1 records but InvoiceItem would have more than 1 records. By using the loadManyModel, i can retrieved these many records object into a variables and passed it into my view for display. Once, the user hits submit, i will have to loop through the items that has been submitted for those records that are in InvoiceItem and perform the same verification and methods as a single record by looping each individual records in InvoiceItem. Just that simple 🙂

Setting up the view

If you think you could use the variables that you just passed through the controller, by editing _form.php, you might be wrong. You would also required to update the corresponding method view files to take in the new variables as shown below,

<?php
$this->breadcrumbs=array(
	'Invoices'=>array('index'),
	$Invoice->invoiceId=>array('view','id'=>$Invoice->invoiceId),
	'Update',
);

$this->menu=array(
	array('label'=>'List Invoice', 'url'=>array('index')),
	array('label'=>'Create Invoice', 'url'=>array('create')),
	array('label'=>'View Invoice', 'url'=>array('view', 'id'=>$Invoice->invoiceId)),
	array('label'=>'Manage Invoice', 'url'=>array('admin')),
);
?>

<h1>Update Invoice <?php echo $Invoice->invoiceId; ?></h1>

<?php echo $this->renderPartial('_form', array('Invoice'=>$Invoice, 'InvoiceItem'=>$InvoiceItem)); ?>

Btw, the above code is took from my view/update.php file where you see at the last sentence i passed in the variables that i have given through my controller. Once you have setup the view, you should be able to used it on the view/_form.php file. In this file, you should only see the code generated for Invoice class. All you have to do is to loop through the InvoiceItem variables that you have just passed through the controller and display it out as shown below,

	<?php echo $form->errorSummary($InvoiceItem); ?>
<?php
foreach($InvoiceItem as $item){
?>
	<div class="row">
		<?php echo $form->labelEx($item,'['.$item->invoiceItemLineId.']invoiceItemLineId'); ?>
		<?php echo $form->textField($item,'['.$item->invoiceItemLineId.']invoiceItemLineId' ); ?>
		<?php echo $form->error($item,'['.$item->invoiceItemLineId.']invoiceItemLineId'); ?>
	</div>

<?php }	?>

Just that simple! And i spend a few days to figure this out! hahaha! This way, you can easily populate 2 modle information using just 1 controller and 1 view. In other words, 1 CRUD and 1 Model. Hope this helps someone else out 🙂