向附件添加字段的问题形成Prestashop 1.6

时间:2017-06-10 17:19:02

标签: php prestashop-1.6 smarty3

我试图为prestashop制作一个模块覆盖某些功能。我想在后台写一个名为" category"的附件表单中添加一个字段。我做了这个修改:

Attachments.php:(在对象中添加了新字段)

<?php


class Attachment extends AttachmentCore
{

public $category;


public static $definition = array(
    'table' => 'attachment',
    'primary' => 'id_attachment',
    'multilang' => true,
    'fields' => array(
        'file' =>            array('type' => self::TYPE_STRING, 'validate' => 'isGenericName', 'required' => true, 'size' => 40),
        'mime' =>            array('type' => self::TYPE_STRING, 'validate' => 'isCleanHtml', 'required' => true, 'size' => 128),
        'file_name' =>        array('type' => self::TYPE_STRING, 'validate' => 'isGenericName', 'size' => 128),
        'file_size' =>        array('type' => self::TYPE_INT, 'validate' => 'isUnsignedId'),

        /* Lang fields */
        'name' =>            array('type' => self::TYPE_STRING, 'lang' => true, 'validate' => 'isGenericName', 'required' => true, 'size' => 32),
        'description' =>    array('type' => self::TYPE_STRING, 'lang' => true, 'validate' => 'isCleanHtml'),
        'category' =>     array('type' => self::TYPE_STRING, 'lang' => true, 'validate' => 'isGenericName', 'required' => true, 'size' => 128),
    ),
);

}

AdminProductsController.php:(整合字段)

<?php

class AdminProductsController extends AdminProductsControllerCore
{

  public function initFormAttachments($obj)
  {
  if (!$this->default_form_language) {
      $this->getLanguages();
  }

  $data = $this->createTemplate($this->tpl_form);
  $data->assign('default_form_language', $this->default_form_language);

  if ((bool)$obj->id) {
      if ($this->product_exists_in_shop) {
          $attachment_name = array();
          $attachment_description = array();
          $attachment_category = array(); //variable

          foreach ($this->_languages as $language) {
              $attachment_name[$language['id_lang']] = '';
              $attachment_description[$language['id_lang']] = '';
              $attachment_category[$language['id_lang']] = '';
          }

          $iso_tiny_mce = $this->context->language->iso_code;
          $iso_tiny_mce = (file_exists(_PS_JS_DIR_.'tiny_mce/langs/'.$iso_tiny_mce.'.js') ? $iso_tiny_mce : 'en');

          $attachment_uploader = new HelperUploader('attachment_file');
          $attachment_uploader->setMultiple(false)->setUseAjax(true)->setUrl(
              Context::getContext()->link->getAdminLink('AdminProducts').'&ajax=1&id_product='.(int)$obj->id
              .'&action=AddAttachment')->setPostMaxSize((Configuration::get('PS_ATTACHMENT_MAXIMUM_SIZE') * 1024 * 1024))
              ->setTemplate('attachment_ajax.tpl');


          $data->assign(array(
              'obj' => $obj,
              'table' => $this->table,
              'ad' => __PS_BASE_URI__.basename(_PS_ADMIN_DIR_),
              'iso_tiny_mce' => $iso_tiny_mce,
              'languages' => $this->_languages,
              'id_lang' => $this->context->language->id,
              'attach1' => Attachment::getAttachments($this->context-
>language->id, $obj->id, true),
              'attach2' => Attachment::getAttachments($this->context->language->id, $obj->id, false),
              'attch_cat' => Attachment::getAttachments($this->context->language->id, $obj->id, false),
              'default_form_language' => (int)Configuration::get('PS_LANG_DEFAULT'),
              'attachment_name' => $attachment_name,
              'attachment_description' => $attachment_description,
              'attachment_category' => $attachment_category,
              'attachment_uploader' => $attachment_uploader->render()
          ));
      } else {
          $this->displayWarning($this->l('You must save the product in this shop before adding attachements.'));
      }
  } else {
      $this->displayWarning($this->l('You must save this product before adding attachements.'));
  }

  $this->tpl_form_vars['custom_form'] = $data->fetch();
  }


  public function ajaxProcessAddAttachment()
  {
  if ($this->tabAccess['edit'] === '0') {
      return die(Tools::jsonEncode(array('error' => $this->l('You do not have the right permission'))));
  }
  if (isset($_FILES['attachment_file'])) {
      if ((int)$_FILES['attachment_file']['error'] === 1) {
          $_FILES['attachment_file']['error'] = array();

          $max_upload = (int)ini_get('upload_max_filesize');
          $max_post = (int)ini_get('post_max_size');
          $upload_mb = min($max_upload, $max_post);
          $_FILES['attachment_file']['error'][] = sprintf(
              $this->l('File %1$s exceeds the size allowed by the server. The limit is set to %2$d MB.'),
              '<b>'.$_FILES['attachment_file']['name'].'</b> ',
              '<b>'.$upload_mb.'</b>'
          );
      }

      $_FILES['attachment_file']['error'] = array();

      $is_attachment_name_valid = false;
      $attachment_names = Tools::getValue('attachment_name');
      $attachment_descriptions = Tools::getValue('attachment_description');
      $attachment_categories = Tools::getValue('attachment_category');
      echo '<script>console.log('.$attachment_categories.')</script>';
      //var_dump($attachment_categories);

      if (!isset($attachment_names) || !$attachment_names) {
          $attachment_names = array();
      }

      if (!isset($attachment_descriptions) || !$attachment_descriptions) {
          $attachment_descriptions = array();
      }

      if(!isset($attachment_categories) || !$attachment_categories){
          $attachment_categories = array();
      }

      foreach ($attachment_names as $lang => $name) {
          $language = Language::getLanguage((int)$lang);

          if (Tools::strlen($name) > 0) {
              $is_attachment_name_valid = true;
          }

          if (!Validate::isGenericName($name)) {
              $_FILES['attachment_file']['error'][] = sprintf(Tools::displayError('Invalid name for %s language'), $language['name']);
          } elseif (Tools::strlen($name) > 32) {
              $_FILES['attachment_file']['error'][] = sprintf(Tools::displayError('The name for %1s language is too long (%2d chars max).'), $language['name'], 32);
          }
      }

      foreach ($attachment_descriptions as $lang => $description) {
          $language = Language::getLanguage((int)$lang);

          if (!Validate::isCleanHtml($description)) {
              $_FILES['attachment_file']['error'][] = sprintf(Tools::displayError('Invalid description for %s language'), $language['name']);
          }
      }
      foreach ($attachment_categories as $lang => $category) {
          $language = Language::getLanguage((int)$lang);

          if (!Validate::isGenericName($category)) {
              $_FILES['attachment_file']['error'][] = sprintf(Tools::displayError('Invalid category for %s language'), $language['name']);
          }
      }

      if (!$is_attachment_name_valid) {
          $_FILES['attachment_file']['error'][] = Tools::displayError('An attachment name is required.');
      }

      if (empty($_FILES['attachment_file']['error'])) {
          if (is_uploaded_file($_FILES['attachment_file']['tmp_name'])) {
              if ($_FILES['attachment_file']['size'] > (Configuration::get('PS_ATTACHMENT_MAXIMUM_SIZE') * 1024 * 1024)) {
                  $_FILES['attachment_file']['error'][] = sprintf(
                      $this->l('The file is too large. Maximum size allowed is: %1$d kB. The file you are trying to upload is %2$d kB.'),
                      (Configuration::get('PS_ATTACHMENT_MAXIMUM_SIZE') * 1024),
                      number_format(($_FILES['attachment_file']['size'] / 1024), 2, '.', '')
                  );
              } else {
                  do {
                      $uniqid = sha1(microtime());
                  } while (file_exists(_PS_DOWNLOAD_DIR_.$uniqid));
                  if (!copy($_FILES['attachment_file']['tmp_name'], _PS_DOWNLOAD_DIR_.$uniqid)) {
                      $_FILES['attachment_file']['error'][] = $this->l('File copy failed');
                  }
                  @unlink($_FILES['attachment_file']['tmp_name']);
              }
          } else {
              $_FILES['attachment_file']['error'][] = Tools::displayError('The file is missing.');
          }

          if (empty($_FILES['attachment_file']['error']) && isset($uniqid)) {
              $attachment = new Attachment();

              foreach ($attachment_names as $lang => $name) {
                  $attachment->name[(int)$lang] = $name;
              }

              foreach ($attachment_descriptions as $lang => $description) {
                  $attachment->description[(int)$lang] = $description;
              }
              foreach ($attachment_categories as $lang => $category) {
                  $attachment->category[(int)$lang] = $category;
              }

              $attachment->file = $uniqid;
              $attachment->mime = $_FILES['attachment_file']['type'];
              $attachment->file_name = $_FILES['attachment_file']['name'];

              if (empty($attachment->mime) || Tools::strlen($attachment->mime) > 128) {
                  $_FILES['attachment_file']['error'][] = Tools::displayError('Invalid file extension');
              }
              if (!Validate::isGenericName($attachment->file_name)) {
                  $_FILES['attachment_file']['error'][] = Tools::displayError('Invalid file name');
              }
              if (Tools::strlen($attachment->file_name) > 128) {
                  $_FILES['attachment_file']['error'][] = Tools::displayError('The file name is too long.');
              }
              if (empty($this->errors)) {
                  $res = $attachment->add();
                  if (!$res) {
                      $_FILES['attachment_file']['error'][] = Tools::displayError('This attachment was unable to be loaded into the database.');
                  } else {
                      $_FILES['attachment_file']['id_attachment'] = $attachment->id;
                      $_FILES['attachment_file']['filename'] = $attachment->name[$this->context->employee->id_lang];
                      $id_product = (int)Tools::getValue($this->identifier);
                      $res = $attachment->attachProduct($id_product);
                      if (!$res) {
                          $_FILES['attachment_file']['error'][] = Tools::displayError('We were unable to associate this attachment to a product.');
                      }
                  }
              } else {
                  $_FILES['attachment_file']['error'][] = Tools::displayError('Invalid file');
              }
          }
      }

      die(Tools::jsonEncode($_FILES));
  }
  }

 }

AdminAttachmentsController:

class AdminAttachmentsController extends AdminAttachmentsControllerCore
{

public function renderForm()
{
    if (($obj = $this->loadObject(true)) && Validate::isLoadedObject($obj)) {
        /** @var Attachment $obj */
        $link = $this->context->link->getPageLink('attachment', true, null, 'id_attachment='.$obj->id);

        if (file_exists(_PS_DOWNLOAD_DIR_.$obj->file)) {
            $size = round(filesize(_PS_DOWNLOAD_DIR_.$obj->file) / 1024);
        }
    }

    $this->fields_form = array(
        'legend' => array(
            'title' => $this->l('Attachment'),
            'icon' => 'icon-paper-clip'
        ),
        'input' => array(
            array(
                'type' => 'text',
                'label' => $this->l('Filename'),
                'name' => 'name',
                'required' => true,
                'lang' => true,
                'col' => 4
            ),
            array(
                'type' => 'textarea',
                'label' => $this->l('Description'),
                'name' => 'description',
                'lang' => true,
                'col' => 6
            ),
            array(
                'type' => 'text',
                'label' => $this->l('Attachment category'),
                'name' => 'category',
                'required' => false,
                'col' => 4,
                'hint' => $this->l('Add a category')
            ),
            array(
                'type' => 'file',
                'file' => isset($link) ? $link : null,
                'size' => isset($size) ? $size : null,
                'label' => $this->l('File'),
                'name' => 'file',
                'required' => true,
                'col' => 6
            ),
        ),
        'submit' => array(
            'title' => $this->l('Save'),
        )
    );

    return AdminController::renderForm();
}


}

Attachments.tpl:(仅限类别部分)

<div class="form-group">
        <label class="control-label col-lg-3 required" for="attch_category_{$id_lang}">
            {l s='Create category'}
        </label>
        <div class="col-lg-9">
            {include
                file="controllers/products/textarea_lang.tpl"
                languages=$languages
                input_name="attachment_category"
                input_value=$attachment_category
            }
        </div>

问题是当我尝试上传文件时,我收到了这个错误:

意外的令牌&lt;在位置0的JSON中 在chrome inspect network标签中,我有 Property Attachment-&gt;类别为空

任何关于问题的想法?

0 个答案:

没有答案