Saturday, June 1, 2013

YII CGridView with CActiveDataProvider customer limit and offset params

It is a CGridView example with CActiveDataProvider class:
<?php 
$this->widget('zii.widgets.grid.CGridView', array(
    'dataProvider'=>$model->search(),
    'filter'=>$model,
    "itemsCssClass" => "table_design_1",
    "htmlOptions" => array(
        "class" => "div_design_1"
    ),
    'columns'=>array(
        array(
            'name'=>'family_name', 
            'header'=>'First name',
            'type' => 'raw',
            'value' => 'CHtml::link($data->family_name,$data->id)'
        ),
        array(
            'name'=>'given_name', 
            'header'=>'Last name',
            'type' => 'raw',
            'value' => 'CHtml::link($data->given_name,$data->id)'
        ),
        array(
            'class'=>'CButtonColumn',
            'viewButtonUrl'=>'Yii::app()->request->getBaseUrl(true)."/contact/view/".$data["id"]',
            'updateButtonUrl'=>'Yii::app()->controller->createUrl("update",$data->primaryKey)',
            'deleteButtonUrl'=>'Yii::app()->controller->createUrl("delete",$data->primaryKey)',
            "htmlOptions" => array(
                'style'=>'width: 60px;'
            )
        )
    )
)); ?> 
If you need to get total items count find by CDbCriteria you need to write:
$model->search()->getTotalItemCount(); 
 
But if you want to customize your data provider with custom limit and offset params then you need
to set 'offset' and 'limit' option to 'CDbCriteria' class as following and need to set pagination to false:

 
$criteria=new CDbCriteria;
$criteria->order = $this->sortString;
$criteria->offset = 5;
$criteria->limit = 10;

return new CActiveDataProvider($this, array(
    'criteria'=>$criteria,
    "pagination" => false
));

How to Change CgridView table class? - Yii Framework

I can see in the source code of my page that CgridView has
<table class="items">
 
and I want to change this to
<table class="example">
 
It can be done by defining the 'itemsCssClass' key as widget's configuration.

So:

$this->widget('zii.widgets.grid.CGridView', array(
'itemsCssClass' => 'table-class',
'htmlOptions' => array('class' => 'example'))



gives me:

<div class="example"><table class="table-class"></table></div> 
 
Complete example of using CGridView: 

<?php 
$this->widget('zii.widgets.grid.CGridView', array(
    'dataProvider'=>$model->search(),
    'filter'=>$model,
    "itemsCssClass" => "table_design_1",
    "htmlOptions" => array(
        "class" => "div_design_1"
    ),
    'columns'=>array(
        array(
            'name'=>'family_name', 
            'header'=>'First name',
            'type' => 'raw',
            'value' => 'CHtml::link($data->family_name,$data->id)'
        ),
        array(
            'name'=>'given_name', 
            'header'=>'Last name',
            'type' => 'raw',
            'value' => 'CHtml::link($data->given_name,$data->id)'
        ),
        array(
            'class'=>'CButtonColumn',
            'viewButtonUrl'=>'Yii::app()->request->getBaseUrl(true)."/contact/view/".$data["id"]',
            'updateButtonUrl'=>'Yii::app()->controller->createUrl("update",$data->primaryKey)',
            'deleteButtonUrl'=>'Yii::app()->controller->createUrl("delete",$data->primaryKey)',
            "htmlOptions" => array(
                'style'=>'width: 60px;'
            )
        )
    )
)); ?>

Thursday, May 30, 2013

Java JList scroll to selected item

Very funny, just one line of code make it fine.


String[] data = {"one", "two", "three", "four", /* AND A LOT MORE */};
JList dataList = new JList(data);
JScrollPane scrollPane = new JScrollPane(dataList);

/* And scroll to selected index */
dataList.ensureIndexIsVisible(dataList.getSelectedIndex());

JTable Scrolling to a specified row index java


public static void scrollToVisible(JTable table, int rowIndex, int vColIndex) {
        if (!(table.getParent() instanceof JViewport)) {
            return;
        }
        JViewport viewport = (JViewport)table.getParent();

        // This rectangle is relative to the table where the
        // northwest corner of cell (0,0) is always (0,0).
        Rectangle rect = table.getCellRect(rowIndex, vColIndex, true);

        // The location of the viewport relative to the table
        Point pt = viewport.getViewPosition();

        // Translate the cell location so that it is relative
        // to the view, assuming the northwest corner of the
        // view is (0,0)
        rect.setLocation(rect.x-pt.x, rect.y-pt.y);

        table.scrollRectToVisible(rect);       
}

A Simple JTable Example Java Code Program


import java.awt.Color;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JTable;
import javax.swing.JScrollPane;
import javax.swing.JComboBox;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.TableColumn;
import javax.swing.DefaultCellEditor;

public class TableExample {

    //Note: Typically the main method will be in a
    //separate class. As this is a simple one class
    //example it's all in the one class.
    public static void main(String[] args) {

        //Use the event dispatch thread for Swing components
        EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {

                new TableExample();
            }
        });

    }

    public TableExample() {
        JFrame guiFrame = new JFrame();

        //make sure the program exits when the frame closes
        guiFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        guiFrame.setTitle("Creating a Table Example");
        guiFrame.setSize(700, 200);

        //This will center the JFrame in the middle of the screen
        guiFrame.setLocationRelativeTo(null);

        //Create the JTable using the ExampleTableModel implementing 
        //the AbstractTableModel abstract class
        JTable table = new JTable(new ExampleTableModel());

        //Set the column sorting functionality on
        table.setAutoCreateRowSorter(true);

        //Uncomment the next line if you want to turn the grid lines off
        //  table.setShowGrid(false);

        //Change the colour of the table - yellow for gridlines 
        //blue for background
        table.setGridColor(Color.YELLOW);
        table.setBackground(Color.CYAN);

        //String array to populate the combobox options
        String[] countries = {"Australia", "Brazil", "Canada", "China"
                , "France", "Japan", "Norway", "Russia", "South Korea"
                , "Tunisia", "USA"};
        JComboBox countryCombo = new JComboBox(countries);

        //Set the default editor for the Country column to be the combobox
        TableColumn countryColumn = table.getColumnModel().getColumn(2);
        countryColumn.setCellEditor(new DefaultCellEditor(countryCombo));

        //set the Event column to be larger than the rest and the Place column 
        //to be smaller
        TableColumn eventColumn = table.getColumnModel().getColumn(3);
        eventColumn.setPreferredWidth(150);

        TableColumn placeColumn = table.getColumnModel().getColumn(4);
        placeColumn.setPreferredWidth(5);

        //Place the JTable object in a JScrollPane for a scrolling table
        JScrollPane tableScrollPane = new JScrollPane(table);

        guiFrame.add(tableScrollPane);
        guiFrame.setVisible(true);
    }

    //implement a table model by extending a class to use
    //the AbstractTableModel
    class ExampleTableModel extends AbstractTableModel {

        //Two arrays used for the table data
        String[] columnNames = {"First Name", "Surname", "Country"
                , "Event", "Place", "Time", "World Record"};

        Object[][] data = {
                {"Pritom Kumar Mondal", "pritom", "Bangladesh", "50m freestyle", 1, "21.30", false},
                {"Pallob", "pallob", "Bangladesh", "50m freestyle", 2, "21.45", false}
        };

        @Override
        public int getRowCount() {
            return data.length;
        }

        @Override
        public int getColumnCount() {
            return columnNames.length;
        }

        @Override
        public Object getValueAt(int row, int column) {
            return data[row][column];
        }

        //Used by the JTable object to set the column names
        @Override
        public String getColumnName(int column) {
            return columnNames[column];
        }

        //Used by the JTable object to render different
        //functionality based on the data type
        @Override
        public Class getColumnClass(int c) {
            return getValueAt(0, c).getClass();
        }

        @Override
        public boolean isCellEditable(int row, int column) {
            if (column == 0 || column == 1) {
                return false;
            } else {
                return true;
            }
        }
    }
}
http://java.about.com/od/Creating-Tables/ss/A-Simple-Table-Example-Java-Code-Program.htm

Wednesday, May 29, 2013

Which function in php validate if the string is valid html?

Html validation function in php:
function isValidHtml($string)
{
    $string = "<div>".$string."</div>";
    $start = strpos($string, '<');
    $end = strrpos($string, '>', $start);
    if($start === false && $end === false) {
        return true;
    }
    if ($end !== false) {
        $string = substr($string, $start);
    } else {
        $string = substr($string, $start, $end - $start);
    }
    libxml_use_internal_errors(true);
    libxml_clear_errors();
    $xml = simplexml_load_string($string);
    return count(libxml_get_errors()) == 0;
}
And best way to use this:

if(isValidHtml($strHtml) {
    echo "Valid html";
}

$strHtml = "<table><tr><td>Hi pritom</td></tr><table>"; is FALSE

Thursday, May 23, 2013

YII TbButtonColumn Urlencode() Expects Parameter 1 To Be String, Array Given

I can not understand anything the global did not, I put to show the button in CGridView when table has multiple primary key.

array(
                'class'=>'bootstrap.widgets.TbButtonColumn',
                'htmlOptions'=>array('style'=>'width: 50px'),
            ),
it gives me:
urlencode() expects parameter 1 to be string, array given
C:\xampp\htdocs\contactwebspace\framework\web\CUrlManager.php(758)
746 
747         if($manager->matchValue && $this->matchValue===null || $this->matchValue)
748         {
749             foreach($this->params as $key=>$value)
750             {
751                 if(!preg_match('/\A'.$value.'\z/u'.$case,$params[$key]))
752                     return false;
753             }
754         }
755 
756         foreach($this->params as $key=>$value)
757         {
758             $tr["<$key>"]=urlencode($params[$key]);
759             unset($params[$key]);
760         }
761 
762         $suffix=$this->urlSuffix===null ? $manager->urlSuffix : $this->urlSuffix;
763 
764         $url=strtr($this->template,$tr);
765 
766         if($this->hasHostInfo)
767         {
768             $hostInfo=Yii::app()->getRequest()->getHostInfo();
769             if(stripos($url,$hostInfo)===0)
770                 $url=substr($url,strlen($hostInfo));
It seems that my yii does not like composite primary keys in models.
I use it with GridView, CButtonColumn and an url issue update like :

array('class'=>'CButtonColumn', 
'viewButtonUrl'=>'Yii::app()->controller->createUrl("view",$data->primaryKey)', 
'updateButtonUrl'=>'Yii::app()->controller->createUrl("update",$data->primaryKey)', 
'deleteButtonUrl'=>'Yii::app()->controller->createUrl("delete",$data->primaryKey)',
)

Or you can use as following:
array('class'=>'CButtonColumn', 
'viewButtonUrl'=>'Yii::app()->request->getBaseUrl(true)."/contact/view/".$data["id"]', 
'updateButtonUrl'=>'Yii::app()->request->getBaseUrl(true)."/contact/update/".$data["id"]', 
'deleteButtonUrl'=>'Yii::app()->request->getBaseUrl(true)."/contact/delete/".$data["id"]',
)