Views: 1758
Last Modified: 19.01.2024

Examples for solving objectives, occurring when handling iblock elements, sections and properties.

  • Getting all property values for an element with known ID
  • Getting properties for elements, knowing the method CIBlockElement::GetList
  • Adding TEXT/html property for an element
  • Completing a File multiple property
  • Completing a List multiple property
  • Getting a section custom field
  • Example for creating a custom data type for custom property
  • How to delete a file in an iblock element property
  • Objective 1:
    Get all property values for an element with a known ID.

    1 <? $db_props = CIBlockElement::GetProperty(IBLOCK_ID, ELEMENT_ID, "sort", "asc", array());
    2 $PROPS = array();
    3 while($ar_props = $db_props->GetNext())
    4 $PROPS[$ar_props['CODE']] = $ar_props['VALUE'];?>

    Now character ID for a property is the key for an associative array $PROPS, if you need property value with price code, it will be stored in $PROPS['price'].

    Objective 2:
    Getting property values via the method CIBlockElement::GetList

    1	<? $arSelect = array("ID", "NAME", "PROPERTY_prop_code_1", "PROPERTY_prop_code_2");
    2 $res = CIBlockElement::GetList(array(), array(), false, array(), $arSelect);?>

    Next, use the cycle and get properties with codes prop_code_1 and prop_code_2.

    Objective 3:
    Add property type TEXT/html for the element.

    In case the property is not a multiple type:

    01 <? $element = new CIBlockElement;
    02 $PROP = array();
    03 $PROP['property character code']['VALUE']['TYPE'] = 'text'; // or html
    04 $PROP['property character code']['VALUE']['TEXT'] = 'value, to enter';
    05 $arLoadArray = array(
    06 	"IBLOCK_ID"      => IBLOCK_ID,
    07 	"PROPERTY_VALUES"=> $PROP,
    08 	"NAME"           => "Element name"
    09 	);
    10 	$element->Add($arLoadArray);?>

    In case the property is a multiple type:

    01	<? // В $ITEMS stores multiple properties to enter
    02 foreach($ITEMS as $item)
    03 {
    04 	$VALUES[]['VALUE'] = array(
    05 	'TYPE' => 'text', // ir html
    06 	'TEXT' => $item,
    07 	);
    08	}
    09	$element = new CIBlockElement;
    10	$PROPS = array();
    11	$PROPS['property character code'] = $VALUES;
    12	$arLoadArray = array(
    13	  "IBLOCK_ID"      => IBLOCK_ID,
    14	  "PROPERTY_VALUES"=> $PROPS,
    15	  "NAME"           => "Element name"
    16	  );
    17 $element->Add($arLoadArray);?>
    Objective 4:

    Complete File multiple property. Quite frequently, when adding an element to the iblock you may need to associate several files to it. For this purpose, it's useful to create a File multiple property and store files within it. Example for completing the property:

    01 <?
    02 $arFiles = array();
    03 for($i = 1; $i < 10; $i++)
    04 {
    05 	if(file_exists($_SERVER['DOCUMENT_ROOT'].'/images/image_'.$i.'.jpg'))
    06 	{
    07 		$arFiles[] = array('VALUE' => CFile::MakeFileArray($_SERVER["DOCUMENT_ROOT"].'/images/image_'.$i.'.jpg'), 'DESCRIPTION' => '');
    08 	}
    09 }
    10 ?>

    After this, the array $arFiles passes as property value when adding an element.

    Objective 5:

    Complete the List multiple property with checkmark flags display. In this case, each element of the value list has its own ID. You can browse them, by entering into property detailed edit. The property is completed as follows:

    1 <?
    2 if($first_condition == true) $values[] = array('VALUE' => 1);
    3 if($second_condition == true) $values[] = array('VALUE' => 2);
    4 CIBlockElement::SetPropertyValuesEx($ELEMENT_ID, $IBLOCK_ID, array('property_code' => $values));
    5 ?>

    In this case, when executing first and second conditions we are marking flags the items from the list with ID =1 and ID=2 accordingly. You need to replace $ELEMENT_ID, $IBLOCK_ID and property_code with desired values.

    Objective 6:
    Get a custom section property

    1 <? $section_props = CIBlockSection::GetList(array(), array('IBLOCK_ID' => IBLOCK_ID, 'ID' => SECTION_ID), true, array("UF_ADDITIONAL_PRICE"));
    2 $props_array = $section_props->GetNext(); ?>

    Now the $props_array['UF_ADDITIONAL_PRICE'] contains the property UF_ADDITIONAL_PRICE for iblock section.

    Advice from developers.
    When handling iblocks, its more convenient for all property ID to be named with capital letters. In this case you can avoid small inconsistencies in your work.

    For example, property with the foto code when handling components is most frequently accessible via [PROPERTIES][foto][VALUE]?, and you can get PROPERTY_FOTO_VALUE when using the method GetList.

    Example of creating your own custom data type for a custom property

    Let's add am image with preview as the property value. For example, it can be photos of a hotel at the tourist website or something similar. This objective will be achieved within this context.

    One of variant for implementation: store images in a an individual iblock and show as association to an element. Example of code:

    AddEventHandler("iblock", "OnIBlockPropertyBuildList", array("CIBlockPropertyPicture", "GetUserTypeDescription"));
    AddEventHandler("iblock", "OnBeforeIBlockElementDelete", array("CIBlockPropertyPicture", "OnBeforeIBlockElementDelete"));
    class CIBlockPropertyPicture
    {
    	function GetUserTypeDescription()
    	{
    		return array(
    			"PROPERTY_TYPE"      =>"E",
    			"USER_TYPE"      =>"Picture",
    			"DESCRIPTION"      =>"Hotel photo",
    			"GetPropertyFieldHtml" =>array("CIBlockPropertyPicture", "GetPropertyFieldHtml"),
    			"GetPublicViewHTML" =>array("CIBlockPropertyPicture", "GetPublicViewHTML"),
    			"ConvertToDB" =>array("CIBlockPropertyPicture", "ConvertToDB"),
    			//"GetPublicEditHTML" =>array("CIBlockPropertyPicture","GetPublicEditHTML"),
    			//"GetAdminListViewHTML" =>array("CIBlockPropertyPicture","GetAdminListViewHTML"),
    			//"CheckFields" =>array("CIBlockPropertyPicture","CheckFields"),
    			//"ConvertFromDB" =>array("CIBlockPropertyPicture","ConvertFromDB"),
    			//"GetLength" =>array("CIBlockPropertyPicture","GetLength"),
    			);
    	}
    	function GetPropertyFieldHtml($arProperty, $value, $strHTMLControlName)
    	{
    		$LINK_IBLOCK_ID = intval($arProperty["LINK_IBLOCK_ID"]);
    		if($LINK_IBLOCK_ID)
    		{
    			$ELEMENT_ID = intval($value["VALUE"]);
    			if($ELEMENT_ID)
    			{
    				$rsElement = CIBlockElement::GetList(array(), array("IBLOCK_ID" => $arProperty["LINK_IBLOCK_ID"], "ID" => $value["VALUE"]), false, false, array("ID", "PREVIEW_PICTURE", "DETAIL_PICTURE"));
    			$arElement = $rsElement->Fetch();
    			if(is_array($arElement))
    				$file_id = $arElement["DETAIL_PICTURE"];
    			else
    				$file_id = 0;
    			}
    			else
    			{
    				$file_id = 0;
    			}
    			if($file_id)
    			{
    				$db_img = CFile::GetByID($file_id);
    				$db_img_arr = $db_img->Fetch();
    			if($db_img_arr)
    			{
    				$strImageStorePath = COption::GetOptionString("main", "upload_dir", "upload");
    				$sImagePath = "/".$strImageStorePath."/".$db_img_arr["SUBDIR"]."/".$db_img_arr["FILE_NAME"];
    				return '<label><input name="'.$strHTMLControlName["VALUE"].'[del]" value="Y" type="checkbox">Удалить файл '.$sImagePath.'</label>.'<input name="'.$strHTMLControlName["VALUE"].'[old]" value="'.$ELEMENT_ID.'" type="hidden">';
    			}
    			}
    			return '<input type="file" size="'.$arProperty["COL_COUNT"].'" name="'.$strHTMLControlName["VALUE"].'"/>';
    		}
    		else
    		{
             return "Property settings error. Specify iblock to store images.";
    		}
    	}
    	function GetPublicViewHTML($arProperty, $value, $strHTMLControlName)
    	{
    		$LINK_IBLOCK_ID = intval($arProperty["LINK_IBLOCK_ID"]);
    		if($LINK_IBLOCK_ID)
    		{
    			$ELEMENT_ID = intval($value["VALUE"]);
    			if($ELEMENT_ID)
    			{
    				$rsElement = CIBlockElement::GetList(array(), array("IBLOCK_ID" => $arProperty["LINK_IBLOCK_ID"], "ID" => $value["VALUE"]), false, false, array("ID", "PREVIEW_PICTURE", "DETAIL_PICTURE"));
    				$arElement = $rsElement->Fetch();
    				if(is_array($arElement))
    					return CFile::Show2Images($arElement["PREVIEW_PICTURE"], $arElement["DETAIL_PICTURE"]);
    			}
    		}
    		return "";
    	}
    	function ConvertToDB($arProperty, $value)
    	{
    		$arResult = array("VALUE" => "", "DESCRIPTION" => "");
    		$LINK_IBLOCK_ID = intval($arProperty["LINK_IBLOCK_ID"]);
    		if($LINK_IBLOCK_ID)
    		{
    			if(
    				is_array($value["VALUE"])
    				&& is_array($value["VALUE"]["error"])
    				&& $value["VALUE"]["error"]["VALUE"] == 0
    				&& $value["VALUE"]["size"]["VALUE"] > 0
    			)
    			{
    				$arDetailPicture =  array(
    					"name" => $value["VALUE"]["name"]["VALUE"],
    					"type" => $value["VALUE"]["type"]["VALUE"],
    					"tmp_name" => $value["VALUE"]["tmp_name"]["VALUE"],
    					"error" => $value["VALUE"]["error"]["VALUE"],
    					"size" => $value["VALUE"]["size"]["VALUE"],
    				);
    				$obElement = new CIBlockElement;
    				$arResult["VALUE"] = $obElement->Add(array(
    					"IBLOCK_ID" => $LINK_IBLOCK_ID,
    					"NAME" => $arDetailPicture["name"],
    					"DETAIL_PICTURE" => $arDetailPicture,
    				), false, false, true);
    			}
    			elseif(
    				is_array($value["VALUE"])
    				&& isset($value["VALUE"]["size"])
    				&& !is_array($value["VALUE"]["size"])
    				&& $value["VALUE"]["size"] > 0
    			)
    			{
    				$arDetailPicture =  array(
    					"name" => $value["VALUE"]["name"],
    					"type" => $value["VALUE"]["type"],
    					"tmp_name" => $value["VALUE"]["tmp_name"],
    					"error" => intval($value["VALUE"]["error"]),
    					"size" => $value["VALUE"]["size"],
    					);
    					$obElement = new CIBlockElement;
    					$arResult["VALUE"] = $obElement->Add(array(
    					"IBLOCK_ID" => $LINK_IBLOCK_ID,
    					"NAME" => $arDetailPicture["name"],
    					"DETAIL_PICTURE" => $arDetailPicture,
    				), false, false, true);
    			}
    			elseif($value["VALUE"]["del"])
    			{
    				$obElement = new CIBlockElement;
    				$obElement->Delete($value["VALUE"]["old"]);
    			}
    			elseif($value["VALUE"]["old"])
    			{
    				$arResult["VALUE"] = $value["VALUE"]["old"];
    			}
    				elseif(!is_array($value["VALUE"]) && intval($value["VALUE"]))
    			{
    				$arResult["VALUE"] = $value["VALUE"];
    			}
    		}
    		return $arResult;
    	}
    	function OnBeforeIBlockElementDelete($ELEMENT_ID)
    	{
    		$arProperties = array();
    		$rsElement = CIBlockElement::GetList(array(), array("ID" => $ELEMENT_ID), false, false, array("ID", "IBLOCK_ID"));
    		$arElement = $rsElement->Fetch();
    		if($arElement)
    		{
    			$rsProperties = CIBlockProperty::GetList(array(), array("IBLOCK_ID" => $arElement["IBLOCK_ID"], "USER_TYPE" => "Picture"));
    			while($arProperty = $rsProperties->Fetch())
                $arProperties[] = $arProperty;
    		}
    		$arElements = array();
    		foreach($arProperties as $arProperty)
    		{
             $rsPropValues = CIBlockElement::GetProperty($arElement["IBLOCK_ID"], $arElement["ID"], array(), array(
                "EMPTY" => "N",
                "ID" => $arProperty["ID"],
    				));
    				while($arPropValue = $rsPropValues->Fetch())
    			{
    					$ID = intval($arPropValue["VALUE"]);
    					if($ID > 0)
    						$arElements[$ID] = $ID;
    			}
    		}
    		foreach($arElements as $to_delete)
    		{
             CIBlockElement::Delete($to_delete);
    		}
    	}
    }

    As the result we have the following:

    • Element edit interface with an option to add and delete images.
    • When deleting an element, information associated with it, is deleted.
    • Component support in the public section.

    Manual:

    • Place this code in the file /bitrix/php_interface/init.php.
    • Create an information block for image storage and indicate in its settings the parameters for preview image generation from details (in the Fields tab).
    • Add a Picture proeprty in the Hotels iblock and indicate an iblock, created at the first step, in the additional settings for this property. Do not forget to specify a character ID code for the property.
    • Create an element and try to change up different values for this property.
    • For example, select this property in the list config parameters inside the public section's news component.

    How to delete a file inside iblock property

    Update any property using the following methods:

    When using any method, the update array key receives property ID and a new value. You need to pass the following simple array to delete the file:

    array('MY_FILE' => array('XXX' => array('del' => 'Y')));

    This method is universal and suits for both iblocks and iblocks 2.0 and document processing as well. MY_FILE - is the code for your File property. What is ХХХ? It contains property value ID. It means specifically value ID, not the property ID.

    CModule::IncludeModule('iblock');
    $IB = 24;
    $ID = 220304;
    $CODE = 'ONE_FL';
    if ($arProp = CIBlockElement::GetProperty($IB, $ID, 'ID', 'DESC', array('CODE' => $CODE))->fetch()) {
    	$XXX = $arProp['PROPERTY_VALUE_ID'];
    	CIBlockElement::SetPropertyValueCode($ID, $CODE, array($XXX => array('del' => 'Y')));
    }

    This way, you will have a universal XXX, and it must be passed for each file targeted for deletion.

    What can be done in case of a multiple file? How to delete a file inside a list? It's simple - use the while instead of if in the example above and, additional filter which file is to be deleted.




    Courses developed by Bitrix24