Метод isValid не работает при использовании элемента file в форме в Zend Framework - PullRequest
1 голос
/ 26 марта 2012

Код формы:

     $companyName = new Zend_Form_Element_Text('company_name');
    $companyName->setLabel('Company Name');

    $companyName->setRequired(true);
    $companyName->setAttrib('size', 30)
                ->setAttrib('class', 'required');



    $companyDescription = new Zend_Form_Element_TextArea('company_description');
    $companyDescription->setLabel('CompanyDescription')
            ->setAttrib('cols', '10')
            ->setAttrib('rows', '3')
            ->setAttrib('style', 'resize: none;')
            ->setAttrib('class', 'required');
    $companyAddress = new Zend_Form_Element_Text('company_address');
    $companyAddress->setLabel('Company Address');

    $companyAddress->setRequired(true);
    $companyAddress->setAttrib('size', 30)
                    ->setAttrib('class', 'required');

    $file = new Zend_Form_Element_File('uploaded_file');
    echo PUBLIC_PATH;
    $file->setDestination(PUBLIC_PATH . '/fold/')
          ->setLabel('File')
          ->setRequired(true)
          ->addValidator('NotEmpty');

    $submit = new Zend_Form_Element_Submit('submit');
    $submit->setAttrib('class', 'all-button');


    $this->addElements(array($companyName, $companyDescription, $companyAddress,$file,$submit));


    $this->setDecorators(array(
        'FormElements',
        array('HtmlTag', array('tag' => 'table', 'id' => 'employees')),
        'Form'
    ));

    $this->setElementDecorators(array(
        'ViewHelper',
        array(array('data' => 'HtmlTag'), array('tag' => 'td', 'class' => 'odd')),
        array('Label', array('tag' => 'td')),
        array(array('row' => 'HtmlTag'), array('tag' => 'tr'))
    ));

    //Adding Browse

    $file->setDecorators(array(
        'File',
        array(array('data' => 'HtmlTag'), array('tag' => 'td')),
        array('Label', array('tag' => 'td')),
        array(array('row' => 'HtmlTag'), array('tag' => 'tr'))
    ));

    $this->setDecorators(array('FormElements',
        array('HtmlTag',array('tag'=>'table','id'=>'employees1')),'Form'));


    $submit->setDecorators(array('ViewHelper',
        array(array('data' => 'HtmlTag'), array('tag' => 'td', 'class' => 'element')),
        array(array('emptyrow' => 'HtmlTag'), array('tag' => 'td', 'class' => 'element', 'placement' => 'PREPEND')),
        array(array('row' => 'HtmlTag'), array('tag' => 'tr'))
    ));

код для действия addCompany:

      public function addCompanyAction() {
    $userInfo = Zend_Auth::getInstance()->getStorage()->read();
    $privilege_id = $userInfo->privilege_id;
    $this->view->privilege = $privilege_id;
    $form = new Company_Form_AddCompany();

     $form->setMethod(Zend_Form::METHOD_POST)
           ->setAttrib('enctype', Zend_Form::ENCTYPE_MULTIPART);


    $this->view->form = $form;

    if ($this->_request->isPost()) {
        //echo 'outside post';
        $formData = $this->_request->getPost();
         $location = $form->uploaded_file->getFileName();
         var_dump($location);
        var_dump($formData);
        if ($form->isValid($formData)) {
             $company_name = $this->_getParam('company_name', 0);
             $company_des = $this->_getParam('company_description', 1);
             $company_addr = $this->_getParam('company_address', 2);
            if ($form->uploaded_file->receive()) {
                $location = $form->uploaded_file->getFileName();
                    echo 'Loc: '.$location.'     ';
                    $loc = PUBLIC_PATH . '/fold/';

                    if (rename($location, $loc . $company_name . '.jpg')) {
                        $img_path = $loc . $company_name . '.jpg';
                    }
                    else
                    {
                         $img_path =$location;
                    }

                        //Insert values in table
                    $companyTable = new Project_Model_DbTable_Company();
                        $data = array(
                            'company_name' => $company_name,
                            'company_description' => $company_des,
                            'image_url' => $img_path,
                            'company_address' => $company_addr
                        );

                        $object_company->insert($data);
                        $message="Company added successfully";
                    }



        } else {
            echo 'else is Valid(): ';
            var_dump( $form->getMessages());
            $form->populate($formData);
        }
    }
}

код для скрипта просмотра add-company.phtml:

   <?php 
     $this->headScript()->appendFile('/js/calendar_db.js', 'text/javascript');
     $this->headLink()->prependStylesheet('/css/calendar.css');
     $this->headScript()->appendFile('/js/validatious-custom-0.9.1.min.js', 'text/javascript');


      ?>
    <div class ="menu">

<?php
require_once '/Menus/setMenuDetails.php';
$privilege_id = $this->privilege;
require_once setMenuDetails ::setMenuDetail($privilege_id);
?>
 </div>
  <div class="page-title" align="center" >Add New Company</div> 
 <div class="back" title="Back"  onclick="history.go(-1);" style="cursor: pointer; "></div>
    <form name="AddCompany" action="/Company/Company/add-company" method="post" class="validate"> 
<div class="profile-details" style="border: 0px solid red; height:700px;width:700px">

    <table id="project"style="text-align: left; margin-top: 5px;" cellpadding="4" cellspacing="3" >


        <thead class ="tableHead">

        </thead>
        <tbody>


            <tr>
                <td><?php echo $this->form->company_name; ?></td>
            </tr>
            <tr>
       <td><?php echo $this->form->company_description; ?></td>
            </tr>

            <tr><td><?php echo $this->form->company_address; ?></td></tr>

    <tr>
                <td><?php  echo $this->form->uploaded_file; ?></td>
            </tr>








   <div class="shadow" style="height: 10px;margin-left:-200px;margin-top:20px">

</div>  


 <div class="page-title" align="center" style="margin-top:30px;margin-left:-          130px;height:20px;border: 0px solid aqua">-->
    <?php

    echo $this->form->submit;
    ?> 
 </tbody>

проблема в том, что когда я нажимаю кнопку отправки, данные формы не проверяются, значит, если ($ form-> isValid ($ formData)) возвращает false Почему ??Когда я стираю часть файла в форме, данные формы проверяются Помогите мне ...

Ответы [ 2 ]

0 голосов
/ 27 марта 2012

Вы можете создать некоторые функции внутри формы, посмотрите:

public function companyDescription()
{
    $companyDescription = new Zend_Form_Element_TextArea('company_description');
    $companyDescription->setLabel('CompanyDescription')
        ->setAttrib('cols', '10')
        ->setAttrib('rows', '3')
        ->setAttrib('style', 'resize: none;')
        ->setAttrib('class', 'required');

    return $companyDescription
}

public function companyAddress()
{
    $companyAddress->setRequired(true);
    $companyAddress->setAttrib('size', 30)
       ->setAttrib('class', 'required');

    return companyAddress;
}

Внутри вашего контроллера вы можете сделать это:

$this->view->companyDescription = companyDescription;
$this->view->companyAddress = companyAddress;

Etc ...

А по вашему мнению:

<?php 
   echo $this->companyDescription; 
   echo $this->companyAddress;
?>

С этим вы можете добавить каждый элемент отдельно в вашем представлении.

0 голосов
/ 26 марта 2012

Вам нужно проверить стек ошибок на вашем объекте формы, ключ будет там.

По вашему мнению, вы повторяете элементы формы индивидуально, попробуйте просто сделать ...

echo $this->form;

По умолчанию это приведет к любым ошибкам, возникшим вдоль соответствующего элемента.

...