Перейти к содержимому


Фотография
- - - - -

Создание своего элемента


  • Закрытая тема Тема закрыта
Сообщений в теме: 48

#21 SmetDenis

SmetDenis

Отправлено 21 February 2013 - 07:14

Чуть чуть исправил крит ошибки в вашем коде.

<?php
/**
 * @package   com_zoo
 * @author    YOOtheme [url]http://www.yootheme.com[/url]
 * @copyright Copyright (C) YOOtheme GmbH
 * @license   [url]http://www.gnu.org/licenses/gpl.html[/url] GNU/GPL
 */

// no direct access
defined('_JEXEC') or die('Restricted access');

// register ElementRepeatable class
App::getInstance('zoo')->loader->register('ElementRepeatable', 'elements:repeatable/repeatable.php');


class ElementJBCominfo extends ElementRepeatable implements iRepeatSubmittable
{
    /**
     * Get search values for filter index
     * @return null|string
     */
    protected function _getSearchData()
    {
        $values = $this->_getValueList();
        $result = JString::trim(implode("\n", $values));

        return $result;
    }

    /**
     * Render HTML for edit form
     * @return string
     */
    protected function _edit()
    {
        $html   = array();
        $html[] = $this->app->html->_('control.editrow', JText::_('zcountry'), $this->app->html->_('control.text', $this->getControlName('zcountry'), $this->get('zcountry'), 'size="60" maxlength="255"'));
        $html[] = $this->app->html->_('control.editrow', JText::_('zcity'), $this->app->html->_('control.text', $this->getControlName('zcity'), $this->get('zcity'), 'size="60" maxlength="255"'));
        $html[] = $this->app->html->_('control.editrow', JText::_('zphone'), $this->app->html->_('control.text', $this->getControlName('zphone'), $this->get('zphone'), 'size="60" maxlength="255"'));
        $html[] = $this->app->html->_('control.editrow', JText::_('zemail'), $this->app->html->_('control.text', $this->getControlName('zemail'), $this->get('zemail'), 'size="60" maxlength="255"'));

        return '<table>' . implode(" ", $html) . '</table>';
    }

    /**
     * Render row
     * @param array $_params
     * @return string
     */
    protected function _render($_params = array())
    {
        return implode(', ', $this->_getValueList());
    }

    /**
     * Render submission row
     * @param array $params
     * @return string|void
     */
    public function _renderSubmission($params = array())
    {
        return $this->_edit();
    }

    /**
     * Check is row has value
     * @param array $params
     * @return bool
     */
    protected function _hasValue($params = array())
    {
        $values = $this->_getSearchData();

        return !empty($values);
    }

    /**
     * Get values list
     * @return array
     */
    protected function _getValueList()
    {
        return array(
            $this->get('zcountry'),
            $this->get('zcity'),
            $this->get('zphone'),
            $this->get('zemail')
        );
    }

    /**
     * Validate submission
     * @param $value
     * @param $params
     * @return array
     * @throws AppValidatorException
     */
    public function _validateSubmission($value, $params)
    {
        if ((int)$params->get('required')) {
            if (!JString::trim(implode(' ', $value->getArrayCopy()))) {
                throw new AppValidatorException('Field is empty');
            }
        }

        return $value->getArrayCopy();
    }
}

Рекомендую добавить в XML настройку "separated_by" - это удобно.

PS Екатерина, пожалуйста, пользуйтесь BB-тегом "code" для обрамления вашего кода. Спасибо.

  • 0
JBZoo v4.0 и новый чудный мир Open Source GPL
Отключайте проверку лицензий как можно скорее!



— Есть два типа людей: Кто еще не делает бекапы и кто уже делает бекапы.


#22 Katerina

Katerina

Отправлено 21 February 2013 - 10:07

Сделала немного по другому

Вот мой пхп файл

<?php
/**
* @package   com_zoo
* @author    YOOtheme http://www.yootheme.com
* @copyright Copyright (C) YOOtheme GmbH
* @license   http://www.gnu.org/licenses/gpl.html GNU/GPL
*/

// no direct access
defined('_JEXEC') or die('Restricted access');

// register ElementRepeatable class
App::getInstance('zoo')->loader->register('ElementRepeatable', 'elements:repeatable/repeatable.php');


class ElementJBCominfo extends ElementRepeatable implements iRepeatSubmittable {


	protected function _hasValue($params = array()) {
		$zcountry = $this->get('zcountry');
		$zcity = $this->get('zcity');
		$zphone = $this->get('zofficeaddress');
                $value = $this->get('zwarehouseaddress');
		$zphone = $this->get('zphone');
                $value = $this->get('zemail');
		return !empty($zcountry) ||!empty($zcity) || !empty($zofficeaddress)|| !empty($zwarehouseaddress) || !empty($zphone)|| !empty($zemail);
	}

	protected function _getSearchData() {
		return $this->get('zcountry', $this->config->get('default'));
	}

	protected function _edit() {
	$html = array();
$html[] = '<div>Country</div>';
	$html[] = $this->app->html->_('control.editrow', JText::_(''), 	
                  $this->app->html->_('control.text', $this->getControlName('zcountry'), 
                  $this->get('zcountry'), 'size="60" maxlength="255"'));
$html[] = '<div>City</div>';
	$html[] = $this->app->html->_('control.editrow', JText::_(''), 	
                  $this->app->html->_('control.text', $this->getControlName('zcity'), 
                  $this->get('zcity'), 'size="60" maxlength="255"'));
$html[] = '<div>Office Address</div>';
	$html[] = $this->app->html->_('control.editrow', JText::_(''), 	
                  $this->app->html->_('control.text', $this->getControlName('zofficeaddress'), 
                  $this->get('zofficeaddress'), 'size="60" maxlength="255"'));
$html[] = '<div>Warehouse Address</div>';
	$html[] = $this->app->html->_('control.editrow', JText::_(''), 	
                  $this->app->html->_('control.text', $this->getControlName('zwarehouseaddress'), 
                  $this->get('zwarehouseaddress'), 'size="60" maxlength="255"'));
$html[] = '<div>Phone</div>';
	$html[] = $this->app->html->_('control.editrow', JText::_(''), 	
                  $this->app->html->_('control.text', $this->getControlName('zphone'), 
                  $this->get('zphone'), 'size="60" maxlength="255"'));
$html[] = '<div>Email</div>';
	$html[] = $this->app->html->_('control.editrow', JText::_(''), 	
                  $this->app->html->_('control.text', $this->getControlName('zemail'), 
                  $this->get('zemail'), 'size="60" maxlength="255"'));

	return implode("\n", $html);
	}



	public function _renderSubmission($params = array()) {
        return '<div class="' .JText::_('zcountry').'">'. $this->get('zcountry'). '</div>
	            <div class="' .JText::_('zcity').  '">'. $this->get('zcity').   '</div>
	            <div class="' .JText::_('zofficeaddress').  '">'. $this->get('zofficeaddress').   '</div>
	            <div class="' .JText::_('zwarehouseaddress').  '">'. $this->get('zwarehouseaddress').   '</div>
	            <div class="' .JText::_('zphone').  '">'. $this->get('zphone').   '</div>
	            <div class="' .JText::_('zemail').  '">'. $this->get('zemail').   '</div>';
	}
    	public function _render($params = array()) {
	
	
	return '<div class="' .JText::_('zcountry').'">'. $this->get('zcountry'). '</div>
	        <div class="' .JText::_('zcity').  '">'. $this->get('zcity').   '</div>
	        <div class="' .JText::_('zofficeaddress').  '">'. $this->get('zofficeaddress').   '</div>
	        <div class="' .JText::_('zwarehouseaddress').  '">'. $this->get('zwarehouseaddress').   '</div>
	        <div class="' .JText::_('zphone').  '">'. $this->get('zphone').   '</div>
	        <div class="' .JText::_('zemail').  '">'. $this->get('zemail').   '</div>';
}

}


Вот мой xml файл

<?xml version="1.0" encoding="utf-8"?>
<element type="jbcominfo" group="JBZoo">
	<name>JBZoo Cominfo</name>
	<author>Katerina</author>
	<creationDate>April 2010</creationDate>
	<copyright>THIS CAN PROBABLY BE OMITTED</copyright>
	<authorEmail>john @ doe.com</authorEmail>
	<authorUrl>http://www.cargocatalog.com</authorUrl>
	<version>1.0.0</version>
	<description>HTML address fields</description>


	<params>
            <param name="zcountry" type="text" default="" label="Country" description="" />
            <param name="zcity" type="text" default="" label="City" description="" />
            <param name="zofficeaddress" type="text" default="" label="Office Address" description="" />
            <param name="zwarehouseaddress" type="text" default="" label="Warehouse Address" description="" />
            <param name="whrepeatable" type="radio" default="0" label="Repeat Warehouse" description="Add multiple text areas.">
                  <option value="0">JNO</option>
                  <option value="1">JYES</option>
            </param>
            <param name="zphone" type="text" default="" label="Phone" description="" />
            <param name="phrepeatable" type="radio" default="0" label="Repeat Phone" description="Add multiple text areas.">
                  <option value="0">JNO</option>
                  <option value="1">JYES</option>
            </param>
            <param name="zemail" type="text" default="" label="Email" description="" />
            <param name="erepeatable" type="radio" default="0" label="Repeat Email" description="Add multiple text areas.">
                  <option value="0">JNO</option>
                  <option value="1">JYES</option>
            </param>
	</params>

	<params group="render">
      		<param name="zcountry" type="text" default="" label="Country" description="" />
      		<param name="zcity" type="text" default="" label="City" description="" />
      		<param name="zofficeaddress" type="text" default="" label="Office Address" description="" />
      		<param name="zwarehouseaddress" type="text" default="" label="Warehouse Address" description="" />
      		<param name="zphone" type="text" default="" label="Phone" description="" />
      		<param name="zemail" type="text" default="" label="Email" description="" />



		<param name="separated_by" type="zoolist" default="Space" label="Separated by" description="CHOOSE_SEPARATOR_REPEATED_ELEMENTS">
			<option name="Space"><![CDATA[separator=[ ]]]></option>
			<option name="Comma"><![CDATA[separator=[, ]]]></option>
			<option name="Hyphen"><![CDATA[separator=[ - ]]]></option>
			<option name="Pipe"><![CDATA[separator=[ | ]]]></option>
			<option name="Break"><![CDATA[separator=[<br />]]]></option>
			<option name="Span"><![CDATA[tag=[<span>%s</span>]]]></option>
			<option name="Paragraph"><![CDATA[tag=[<p>%s</p>]]]></option>
			<option name="Div"><![CDATA[tag=[<div>%s</div>]]]></option>
			<option name="List Item"><![CDATA[tag=[<li>%s</li>]]]></option>
			<option name="Unordered List"><![CDATA[tag=[<li>%s</li>] enclosing_tag=[<ul>%s</ul>]]]></option>
			<option name="Ordered List"><![CDATA[tag=[<li>%s</li>] enclosing_tag=[<ol>%s</ol>]]]></option>
			<option name="Warp Item"><![CDATA[tag=[<article class="item">%s</article>]]]></option>
		</param>


	</params>
</element>



Элемент в xml отображении выглядит вот так
Изображение

В элементе каталога это выглядит вот так
Изображение

Обображается вот так
http://cargocatalog....kargo/item/akfa

(там дурацкая запятая - не поняла как от нее избавиться)

Однако! Телефонов у представительств может быть несколько, как и емейлов и складов

Изображение

Вопрос: куда в мой код нужно прописать функцию " + Добавить элемент"

Что бы в элементе каталога это выглядело как на моей картинке, сделанной в фотошопе.

В  xml я прописала радиобоксы и они замечательно выводятся, только не работают
  • 0

#23 SmetDenis

SmetDenis

Отправлено 21 February 2013 - 10:16

Вопрос: куда в мой код нужно прописать функцию " + Добавить элемент"

"+ Добавить элемент" тот что в самом низу подставится сам, потому что у вас поле повторяемое.
Все остальное вам нужно самостоятельно реализовывать в методе _render()

В  xml я прописала радиобоксы и они замечательно выводятся, только не работают

Это тоже самом собой не заработает =)
Переопределяете render(), там будет доступен $params и на основе его делаете вывод

  • 0
JBZoo v4.0 и новый чудный мир Open Source GPL
Отключайте проверку лицензий как можно скорее!



— Есть два типа людей: Кто еще не делает бекапы и кто уже делает бекапы.


#24 Katerina

Katerina

Отправлено 21 February 2013 - 10:24

С моими знаниями в пхп (точнее их полном отсутствии) меня ждет еще одна бессонная ночь. Денис, не закрывайте пожалуйста топик, отпишусь при результате.
  • 0

#25 Katerina

Katerina

Отправлено 24 February 2013 - 10:23

Написанный модуль не отображается в форме подачи материала

http://www.cargocata...bavit-kompaniyu

Инфо о представительствах

Почему?
  • 0

#26 RomanL

RomanL

Отправлено 24 February 2013 - 11:23

А функция renderSubmission у Вас описана?
  • 0
[color=#aa0000]Не забывайте нажимать кнопку «Вопрос Решён» и «+1» под сообщением, которое Вам помогло[/color]

#27 Katerina

Katerina

Отправлено 24 February 2013 - 11:39

А функция renderSubmission у Вас описана?


если ее нужно прописыват только здесь, то описана

	public function _renderSubmission($params = array()) {
        return '<div class="' .JText::_('zcountry').'">'. $this->get('zcountry'). '</div>
	            <div class="' .JText::_('zcity').  '">'. $this->get('zcity').   '</div>
	            <div class="' .JText::_('zofficeaddress').  '">'. $this->get('zofficeaddress').   '</div>
	            <div class="' .JText::_('zwarehouseaddress').  '">'. $this->get('zwarehouseaddress').   '</div>
	            <div class="' .JText::_('zphone').  '">'. $this->get('zphone').   '</div>
	            <div class="' .JText::_('zemail').  '">'. $this->get('zemail').   '</div>';
	}

  • 0

#28 RomanL

RomanL

Отправлено 24 February 2013 - 12:17

renderSubmission а не  _renderSubmission
  • 0
[color=#aa0000]Не забывайте нажимать кнопку «Вопрос Решён» и «+1» под сообщением, которое Вам помогло[/color]

#29 Katerina

Katerina

Отправлено 24 February 2013 - 12:35

renderSubmission а не  _renderSubmission


если убрать подчеркивание - все совершенно ломается и выдает чистую станицу
  • 0

#30 Katerina

Katerina

Отправлено 24 February 2013 - 12:41

Я поменяла на вариант, предложенный в примере Денисом. Заработало.

    public function _renderSubmission($params = array())
    {
        return $this->_edit();
    }


Вопрос с переопределением рендера остался открытым.

Не доходит, как подобраться в элементу в массиве, что бы прописать ему ElementRepeatable (((


  • 0




Click to return to top of page in style!