Category Archives: Symfony Framework

[Symfony] Writing Log

// From an action
$this->logMessage($message, $level);

// From a template


Log file path :
# symfony/log/frontend_dev.log

# tail -f frontend_dev.log

:)

Source : http://www.symfony-project.org/book/1_2/16-Application-Management-Tools

Posted in Symfony Framework, Tech Note | Tagged , , | Leave a comment

[toArray method] Convert ActiveRecord object and stdClass to array

1. Convert ActiveRecord object to Array

$array = $activeRecordObject->toArray();

$c = new Criteria();
$result = ItEquipmentPeer::doSelect($c);

$data = array();

foreach($result as $row){
	$data[] = $row->toArray();
}

2. Convert stdClass to Array

$array = get_object_vars($stdClass);


Posted in PHP, Symfony Framework, Tech Note | Tagged , , | Leave a comment

[Symfony] update DB Table without loss of data

1.

c:\symfony> symfony propel:data-dump dump.yml

(it create(update) /data/fixtures/dump.yml file)

2.

c:\symfony> symfony propel:build-all-load
Posted in Symfony Framework, Tech Note | Tagged , | 254 Comments

[Symfony] Generate-CRUD (Module, Templates)

c:\www\symfony>symfony propel:generate-crud frontend MODULE_NAME DB_TABLE_NAME

If you did not create generate module yet, it will create new module and set CRUD.

If you have already the module then it will create crud function in your action file. BUT

you will lost all your codes in your action file!

If you found the error message like below when you access /module/new/

Class “Category” must implement a “__toString” method to be rendered in a “sfWidgetFormPropelChoice” widget

To avoid, just create empty __toString method in the class file that error message mention.

class Category extends BaseCategory
{
public function __toString(){}
}
Posted in Symfony Framework, Tech Note | Tagged , , | 4 Comments

[Symfony] Let’s Play with Database (propel,schema)

1. Create Database

Open schema file(schema.yml) and define your database structure

/config/schema.yml

//^^ = space
propel:
^^sy_category:
^^^^_attributes: { phpName: Category }
^^^^id: {type: integer, primaryKey: true, autoIncrement: true}
^^^^category: {type: varchar(255), required: true}

^^sy_data:
^^^^_attributes: { phpName: Data }
^^^^id: {type: integer, primaryKey: true, autoIncrement: true}
^^^^category_id: {type:integer, foreignTable: sy_category, foreignReference: id, required: true, onDelete: cascade}
^^^^name: {type: varchar(255) required:true}
^^^^age: {type: integer}
^^^^nickname: {type: varchar(255)}
^^^^email: {type: VARCHAR, size: '255'}
^^^^updated: {type: TIMESTAMP}

2. Build Model (in console window)

c:\wamp\www\symfony> symfony propel:build-all
c:\wamp\www>symfony>symfony cc     //clear cache

(Add additional model)
> symfony propel:build-model (Generate ORM)
> symfony propel:build-sql (Generate sql -> data/sql/lib.model.schema.sql)
> mysql -uroot -XXX DB_NAME < data/sql/lib.model.schema.sql (Or you can run the sql query manually also)

now we just created database tables.

3.INSERT

let’s put something in empty database table.

//in action class (it's just for test, it is better to make separate controller and Model.)

public function executeIndex(sfWebRequest $request){

	for($i=1; $i<=10; $i++){

		$category = new Category();

		$category->setCategory('Category '.$i);

		$category->save();

	}

// Also you can use array to insert your data in a time

	// input data
	$d = new Data();
	$d->fromArray(array(
		 'CategoryId' => 1,
		 'Name'    => 'Mark Song',
		 'Age' => 31,
		 'Nickname' => 'Sleepy boy',
		 'Email' => 'ilovekanon@gmail.com'
	 ));

	$d->save();

// **** The filed Name should be camel case and the first letter should be Capital letter!

}//close function

********************** Error Note ****************************
when you put date into a table field,

you need to use Camel case and the first letter should be capital letter!

Ex )

FIELDS :: name,yourAddress,yourEmail

$q = new TestTable();
$inputData = array(
			"Name"		=> "Mark Song",
			"YourAddress"	=> "NY,NY",
			"YourEmail"	=> "ilovekanon@gmail.com");
$q -> fromArray($inputData);
$q -> save();

//OR

$q -> setName('Mark Song');
$q -> setYourAddress('NY,NY');
$q -> setYourEmail('ilovekanon@gmail.com');
$q -> save();

******************************************************************

4. SELECT

Now let’s get the data from the category table.

public function executeIndex(sfWebRequest $request){

//Get All Category;

$c = new Criteria();
$c->addAscendingOrderByColumn(CategoryPeer::ID); //sorting = order by id ASC
$category = CategoryPeer::doSelect($c);

for($i=0,$size=sizeof($category); $i<$size; $i++){ 	echo $category[$i]->getCategory()."
";
}

// Get Only One
$c = new Criteria();
$category = CategoryPeer::doSelectOne($c);

echo $category->getCategory();

// Get Conditional filtered data

$c = new Criteria();
$c->add(CategoryPeer::ID, 1);
$c->add(categoryPeer::CATEGORY,'%category%', Criteria::LIKE);
$category = CategoryPeer::doSelect($c);

for($i=0,$size=sizeof($category); $i<$size; $i++){ 	echo $category[$i]->getCategory()."
";
}

return sfView::NONE;
}// function close

5. UPDATE

$q = CategoryPeer::retrieveByPK(1);
$q -> setCategory('Changed Category');
$q -> save();

6. DELETE

$q = CategoryPeer::retrieveByPK(1);
CategoryPeer::doDelete($q);

// OR, 

CategoryPeer::doDelete(1); // using primary key to the parameter 

//OR

$q = CategoryPeer::retrieveByPK(1);
$q -> delete(); // no more $q available to use.

7. M,V

Finally, let’s make  controller and model separately.

/lib/model/CategoryPeer.php

class CategoryPeer extends BaseCategoryPeer
{
static public function getTest(){
return "This is return Message from Category Peer!";
}
}

/action file

$category = CategoryPeer::getTest();
echo $category; // it will display 'This is return Message From Category Peer!';

** Bonus, Subquery **

$c = new Criteria();

$c->addAsColumn('AS_COLUMN_NAME', '(SELECT `name` FROM `table` WHERE `user_id` =1');

$c->addAscendingOrderByColumn($c->getColumnForAs('AS_COLUMN_NAME'));

$this->names = UserPeer::doSelect($c);
Posted in Symfony Framework, Tech Note | Tagged , , , | 3 Comments

[Symfony] How to Set Template

public function executeExtjs1(sfWebRequest $request){

$test_no = $request->getParameter('test_no');

switch($test_no){
case '2' : $this->setTemplate('extjs2');break; //-> will load extjs2Success.php file
default : $this->setTemplate('extjs1');    //-> will load extjs1Success.php file
}

return sfView::SUCCESS;
}

Posted in Symfony Framework, Tech Note | Tagged , | 2 Comments

[Symfony] How to get Parameter

public function executeTest(sfWebRequest $request){

/* Way 1 */

echo $this->getRequestParameter('test');

/* Way 2 */

echo $request->getParameter('test');

}
Posted in Symfony Framework, Tech Note | Tagged , | 3 Comments

[Symfony] The Propel Criteria Object

public function executeIndex(sfWebRequest $request)
{
  $criteria = new Criteria();
  $criteria->add(JobeetJobPeer::CREATED_AT, time() - 86400 * 30, Criteria::GREATER_THAN);

  $this->jobeet_job_list = JobeetJobPeer::doSelect($criteria);
}

Comparison Operators

  • Criteria::EQUAL
  • Criteria::NOT_EQUAL
  • Criteria::GREATER_THAN, Criteria::GREATER_EQUAL
  • Criteria::LESS_THAN, Criteria::LESS_EQUAL
  • Criteria::LIKE, Criteria::NOT_LIKE
  • Criteria::CUSTOM
  • Criteria::IN, Criteria::NOT_IN
  • Criteria::ISNULL, Criteria::ISNOTNULL
  • Criteria::CURRENT_DATE, Criteria::CURRENT_TIME, Criteria::CURRENT_TIMESTAMP

Methods

Add()


$criteria->add(JobeetJobPeer::EXPIRES_AT, time(), Criteria::GREATER_THAN);
$criteria->addAnd(JobeetJobPeer::EXPIRES_AT, time(), Criteria::LESS_THAN);

addAscendingOrderByColumn(column)

addDescendingOrderByColumn(column)

setLimit(limit)

setOffset(offset)

addJoin(col1, col2)

addJoin(col1, col2, Criteria::LEFT_JOIN)

addJoin(col1, col2, Criteria::RIGHT_JOIN)

###################### Error Note ####################
I had a problem with using Criteria::IN

because I thought , I need to put the string which is divided by comma as parameter. But we should put the array as parameter!

Ex)

$temp = '1,2,3';
$c->add(testPeer::ID,$temp,Criteria::EQUAL); (x)

$temp = array('1','2','3');
$c->add(testPeer::ID,$temp,Criteria::EQUAL); (0)
Posted in Symfony Framework, Tech Note | Tagged , , , | 4 Comments

[Symfony Installation] Check your symfony configuration

Download script from here :
http://sf-to.org/1.4/check.php

and run it!

symfony> php check_configuration.php

Posted in Symfony Framework, Tech Note | Tagged , , , , | 5 Comments

[Symfony] Let’s play with YML!

Symfony uses YML for configuration.

YML contain like this contents (for more detail structure about YML, please search Google)
app.yml
———————–
all:
mySetting:
myName: Mark

Now let’s try to get the myName in action(controller) file.

echo sfConfig::get('app_mySetting_myName');
// output : Mark

Good^^, Now let’s try to create custom YML file and get the file contents.

Create myyml.yml file
and type this,

myinfo:
myName: Mark Song
myAge : 30

$test = sfYaml::load('path_to\myyml.yml');

* how to know ‘path_to’ ?

* Reference from : http://www.symfony-project.org/book/1_0/19-Mastering-Symfony-s-Configuration-Files

$configPath = sfConfig::get('sf_app_config_dir');
echo $configPath;

We get the config path.

Now let’s get my myyml.yml

$configPath = sfConfig::get('sf_app_config_dir');

$test = sfYaml::load($configPath.'\myyml.yml');
// For windows, folder divide by '\'
echo $test['myinfo']['myName'];
//output : Mark Song
print_r($test);
Posted in Symfony Framework, Tech Note | Tagged , , , | 1 Comment