<?php // Formula: n! = n*(n-1)*(n-2)*(n-3)...3.2.1 and zero factorial is defined as one i.e. 0! = 1. // Method 1. Using for loop $fact = 1; $number = 5; for ($i = 1; $i <= $number; $i++) $fact = $fact * $i; echo $fact; //---------------------------------- // Method 2: Using recursive method function factorial($n) { if ($n == 0) return 1; else return($n * factorial($n - 1)); } $number=6; echo factorial($number); ?>
Wednesday 19 November 2014
Simple Factorial Program in PHP
Tuesday 18 November 2014
Simple Prime number program in PHP
Ans: A number is prime if it is divisible only by one and itself. (Ex: 2, 3, 5, 7, 11, 13, 17....etc)
Program:
<?php $num = 4; // <=== Replace desired number to check for ($i = 2; $i <= $num - 1; $i++) { if (bcmod($num, $i) == 0) { echo $num . " is not prime number :("; break; } } if ($num == $i) echo $num . " is prime number :)"; ?>
Fibonacci Series in PHP
Ans: Numbers of Fibonacci sequence are known as Fibonacci numbers. First few numbers of series are 0, 1, 1, 2, 3, 5, 8 etc, Except first two terms in sequence every other term is the sum of two previous terms, For example 8 = 3 + 5 (addition of 3, 5)
Fibonacci Series using for loop:
<?php $term = 10; $num1 = 0; $num2 = 1; for ($i = 0; $i < $term; $i++) { if ($i <= 1) $result = $i; else { $result = $num1 + $num2; $num1 = $num2; $num2 = $result; } echo "<br>" . $result; } ?>
Fibonacci Series using recursion:
<?php function fibonacci($n) { if ($n == 0) return 0; else if ($n == 1) return 1; else return ( fibonacci($n - 1) + fibonacci($n - 2) ); } $term = 10; for ($i = 1; $i <= $term; $i++) { echo "<br>".fibonacci($c); $c++; } ?>
Output: 0 1 1 2 3 5 8 13 21 34
Monday 29 September 2014
Useful Custom JQuery Validations using JQuery Validate
- Know more about JQuery Validate Plugin
- Know more about Regular Expression in Javascript
1. PAN Card: Find more details here
2. KEY: String should start with "__ and end with __". Ex: __Hello__
3. Landline: Landline Number (Ex. 0432-5435)
4. Amount: Ex. 50000.00
5. Interest Rate: Ex. 12.10, 5.2
6. Percentage: Ex. 100, 99.99, 1.2
$(document).ready(function() { $.validator.addMethod("pan", function(value, element) { return this.optional(element) || /^[A-Z]{5}\d{4}[A-Z]{1}$/.test(value); }, "Invalid PAN Number"); $.validator.addMethod("key", function(value, element) { return this.optional(element) || /^__[a-zA-Z]+__/.test(value); }, "Invalid Key"); $.validator.addMethod('landline', function(value, element) { return this.optional(element) || /^\d{2,5}\-\d{3,9}$/.test(value); }, 'Please specify a valid landline number'); $.validator.addMethod('amount', function(value, element) { return this.optional(element) || /^\d{1,9}[\.\d]+$/.test(value); }, 'Please specify a valid Amount (Ex. 1000xxx)'); $.validator.addMethod('interest', function(value, element) { return this.optional(element) || /^\d{1,2}(\.\d{1,2})?$/.test(value); }, 'Please specify a valid data'); $.validator.addMethod('percent', function(value, element) { return this.optional(element) || /^\d{1,2}\.\d{1,2}$/.test(value); }, 'Please enter valid data (Ex. 25.00)'); });
Usage:
$("#myform").validate({ rules: { "pan": {required: true}, "amount": {amount: true} "landline": {landline: true}, "interest_rate": {interest: true}, "percent": {percent: true}, "nospace": {required: true}, "key": {noSpace: true} } });
Thanks. Hope it'll help.
Friday 20 June 2014
Yii Grid filter with relations
In Yii there are 3 simple steps to implement filter for relational column in Gridview. Lets Say we have two models and relation between them.
Eg. Consider following example. Here we have 3 models City, State and Country. City has 2 columns state_id and country_id along with their relations.<?php public function relations() { return array( 'country' => array(self::BELONGS_TO, 'Country', 'country_id'), 'state' => array(self::BELONGS_TO, 'State', 'state_id') ); } ?>
Now after doing customization in City Gridview we need to implement filter for countries and states. Here are the following 3 simple steps to achieve this.
1) In Gridview:
<?php $this->widget('bootstrap.widgets.TbGridView', array( 'id' => 'city-grid', 'template' => '{items}{summary}{pager}', 'dataProvider' => $model->search(), 'filter' => $model, 'columns' => array( array( 'name' => 'country.name', 'filter' => CHtml::activeTextField($model, 'country'), ), array( 'name' => 'state.name', 'filter' => CHtml::activeTextField($model, 'state'), ), array( 'name' => 'name', 'type' => 'raw', 'value' => 'CHtml::link($data->name,"/city/update/$data->city_id")', ), array( 'class' => 'bootstrap.widgets.TbButtonColumn', ), ), )); ?>
Model:
2) In rules array:<?php public function rules() { return array( array('name', 'unique'), array('name, country_id', 'required'), array('state, country, city_id, country_id, state_id, name', 'safe', 'on' => 'search'), ); ?>
3) In search() method:
<?php public function search() { $criteria = new CDbCriteria; $criteria->together = true; $criteria->with = array('state', 'country'); $criteria->compare('city_id', $this->city_id); $criteria->compare('name', $this->name, true); $criteria->addSearchCondition('state.name', $this->state); $criteria->addSearchCondition('country.name', $this->country); $dataProvider = new CActiveDataProvider($this, array( 'criteria' => $criteria, )); return $dataProvider; } ?>
That's it! Hope it'll help you.
...See more Yii stuffs
Wednesday 11 June 2014
Display total amount on Yii Grid
Step 1:
<?php $this->widget('bootstrap.widgets.TbGridView', array( 'id' => 'my-grid', 'dataProvider' => $model->search(), 'template' => '{items}', 'columns' => array( array( 'header' =>'Amount 1', 'name' => 'amount_1', 'footer'=>'Total (Amount 1 + Amount 2)', ), array( 'header' => 'Amount 2', 'name' => 'amount_2', 'footer' => $model->getTotal($model->search()->getData(), 'amount_1','amount_2'), ), ), )); ?>
Step 2:
<?php public function getTotal($records, $data1, $data2) { $total = 0; foreach ($records as $record) { $total += $record->$data1 + $record->$data2; } return number_format($total, 2); } ?>
Thursday 24 April 2014
Replace textfield with dropdown yii grid
In Yii CGridview you can replace default text-field with drop-down to filter records. You just need to add following line in your columns array. Ex. I have added "Category" column along with drop-down filter.
'category'=>array( 'name' => 'category', 'value' => '$data->category', 'filter'=> CHtml::listData(CustomerSpendings::model()->findAll(array('order'=>'category')), 'category', 'category') ),
Tuesday 25 March 2014
Check Yii CGridview empty
In model: Put CActiveDataProvider into a variable:
<?php $dataProvider = new CActiveDataProvider($this, array( 'criteria' => $criteria, 'pagination' => array('pageSize' => 10), 'sort' => array( 'defaultOrder' => 'create_dttm DESC', ) )); ?>Check if dataprovider is empty or not:
<?php if (!isset($_REQUEST['ajax']) && $dataProvider->totalItemCount < 1) { Yii::app()->getController()->redirect(array('create')); } else { return $dataProvider; } ?>If the above code doesn't works then you can also return an empty data provider like this:
return new CActiveDataProvider($this, array('data' => array()));
Monday 10 March 2014
Tuesday 4 March 2014
Simple form cloning in JQuery
Simple JQuery-HTML based form cloning functionality. It not only clones the normal textfield, textarea, file field and dropdown field but also JQuery Datepicker and Maskmoney field.
Maskmoney is just a simple way to create masks to your currency form fields with JQuery. For more reference and live demo check this link : http://plentz.github.io/jquery-maskmoney/
See the demo for more information:
Monday 3 March 2014
JQuery selectors and how to use them
Get selected text from dropdown
$("#myid option:selected").text();
Get selected value from dropdown
$("#myid option:selected").value();
Get input type text value
$("#myid input[type=text]").val();
Get checked radiobutton value by class
$(".myclass").click(function() { var input = $('.myclass:checked').val(); alert(input); });
Check whether radiobutton or checkbox checked or not
$("#test").click(function() { var check = $('#test').attr('checked'); if(check === "checked") //condition else //condition });
Clear all form fields (i.e. text-field, file-field, drop-down, check-box and radio-buttons)
$('input[type="text"]').val(''); $('input[type="file"]').val(''); $('input[type="radio"]').prop('checked', false); $('input[type="checkbox"]').prop('checked', false); $("#mydropdown option:selected").prop("selected", false);
If you want to exclude any one field then you can do like this. Ex. you want to exclude one drop-down field
Option1:
$('select[name != "test"]').val('');
Option2:
$("select:not([name='User[name]'], [name='User[email]'])").val("");
Event based on the value of data attribute
$( "input[data-role-type='privilege_role']" )
Get concatenated name in Yii dropDownList
If you have two fields like firstname and lastname in your table then sometime you need to show concatenated name in dropDownList that is name with first name and last name. Following is the post where you will find how to deal with this in Yii Framework.
First of all you need to create method in your model.
Model (User in this case)
<?php public function getConcatened(){ return $this->firstname . ' ' . $this->firstname; } ?>
Then call that function from CHtml list data by passing function name as a third parameter.
In drop down list:
<?php $list = CHtml::listData(User::model()->findAll(array('order' => 'firstname')), 'id', 'concatened'); echo $form->dropDownListRow($model, 'id', $list); ?>
Friday 21 February 2014
Friday 7 February 2014
How to show protected images in Yii
"protected" folder are not accessible from the client browser. This prevents user to have access to important files. If you want to store images inside "protected" and want them to be accessible, you need to publish them using CAssetManager.
Example:1 2 | $path = Yii::app()->basePath.'/path-inside-protected'; $imgurl= Yii::app()->assetManager->publish($path); |
1 | <img src="<?php echo $imgurl?>"> |
Thursday 16 January 2014
Get column names from model Yii
Add the following method in your "CommonController.php" or any other which you are using.
<?php public static function getColumnNames($table) { return $table::model()->getTableSchema()->getColumnNames(); } ?>
Now call that method from your model/view/controller in this way:
<?php $model=new User; $table=CommonController::getTableNameFromModel($model); $colArr=CommonController::getColumnNames($table); // -- Output -- echo "<pre>"; print_r($colArr); ?>
It'll return you an array containing all the column names of given table.
Thanks. Have a great day.
Get table name from model name Yii
Step2: Create a static method in that controller named "getTableNameFromModel()" and add the following code in it.
<?php public static function getTableNameFromModel($model) { return $model::model()->tableSchema->name; } ?>
Step3: Call function from your model/view/controller by passing model name as a parameter.
<?php $model=new User; echo CommonController::getTableNameFromModel($model); ?>
It'll return table name of the corresponding model.
Hope it'll help you. Thanks.
Read Next: Get column names from model Yii