phpvalidationsyntaxphpexcel

PHPExcel validate data for a range of cells


I am trying to validate data for a range of cells in PHPExcel. Validating a single cell works.

$objValidation = $objPHPExcel->getActiveSheet()->getCell('A1')->getDataValidation();
$objValidation->setType( PHPExcel_Cell_DataValidation::TYPE_WHOLE );
$objValidation->setErrorStyle( PHPExcel_Cell_DataValidation::STYLE_STOP );
$objValidation->setAllowBlank(true);
$objValidation->setShowInputMessage(true);
$objValidation->setShowErrorMessage(true);
$objValidation->setErrorTitle('Input error');
$objValidation->setError('Number is not allowed!');
$objValidation->setPromptTitle('Allowed input');
$objValidation->setPrompt('Only 1 and 0 are allowed.');
$objValidation->setFormula1(0);
$objValidation->setFormula2(1);

I can validate other cells by creating a clone like this.

$objPHPExcel->getActiveSheet()->getCell("A2")->setDataValidation(clone $objValidation);

But if I try to validate data through a loop, it freezes.

$j = 2;
while($j <= 10)
{
    $objPHPExcel->getActiveSheet()->getCell("A$j")->setDataValidation(clone $objValidation);    
}

What am I doing wrong here?

P.S. Looping works with other functions such as getStyle() etc.


Solution

  • In your example you are never incrementing the variable $j.

    Try a foreach instead:

    foreach($j=2; $j<=10; $j++) {
      //do your stuff
    }
    

    Or change it up to be a do-while http://php.net/manual/en/control-structures.do.while.php