Исходник

 

Вступление.

  • 01:55 Установка Component Builder/Creator Скачайте и установите Joomla Component Builder/Creator.

Вы можете найти компонент в репозитории на GitHub. Обратите внимание, что эти файлы не заполнены данными. Компонент показывает вам самое необходимое из того, что требуется для работы компонента в Joomla! Но мы собираемся сделать гораздо больше, чем код делает в этом компоненте. Когда мы закончим, у нас будет приложение со множеством линий, и мы добавим структуры, чтобы оно выходило далеко за рамки простого компонента каркаса. Последнюю версию можно скачать здесь. После загрузки файла загрузите его в корневой каталог веб-сайта, в котором вы будете его устанавливать. Для этого примера перейдите по ссылке Выпуски, загрузите и установите файл. Первое, что нужно сделать дальше, - это создать поле.

Есть решение проще - Component Builder присутствует в менеджере расширений Joomla. Просто найдите его и установите.

 

Создание Поля Приветствия.

  • 02:46 Создайте поле Создайте Поле Приветствия.

Существует много типов полей. Нам нужно создать базовое пользовательское текстовое поле с именем приветствие. Вы увидите, что есть гораздо больше полей, которые я оставлю без изменений. Я также собираюсь удалить несколько вещей, но поле все равно будет работать, даже если эти строки будут удалены. Измените тип на VARCHAR, сохраните и закройте.

 

Создайте представление Администратора.

03:51 Создание представления администратора Создание представления администратора и связывание поля с базой данных.

После создания нового поля следующее, что нужно сделать, это создать представление администратора. Это то, что связывает поля с базой данных. Назовите это приветствием для одной записи, приветствием для списка записей и приветствием для имени системы, чтобы мы могли идентифицировать это по всей системе. Я собираюсь добавить приветствия и несколько общих значков. Затем свяжите это поле, которое мы создали, чтобы показать, будьте первым, действуйте как заголовок, будьте сортируемыми, доступными для поиска и будьте ссылкой на первой вкладке и первой на этой вкладке. Затем дайте ему разрешения и сохраните. Остальную часть конструкции можно было бы оставить как есть. У нас будет рабочий компонент с этим в качестве представления администратора, поэтому сохраните и закройте.

 

Создание компонента под названием World и компиляция Его.

03:51 Создание компонента под названием worldd Создание представления администратора и связывание поля с базой данных.

Теперь нам нужно создать компонент, нажмите "Создать", и он загрузит новый компонент Joomla. Я собираюсь назвать это world. По большей части я просто добавляю сюда некоторые тестовые данные. Я могу выбрать значок. Изображение может быть показано после установки компонента, а также в области администрирования. Остальные функции в настройках, которые нам нужно изменить, следующие:

  • Ссылка на представление администратора
  • Выберите приветствия
  • Добавить в главное меню
  • Разрешить подменю
  • Автоматическая проверка
  • История
  • Имеет метаданные
  • Имеет доступ
  • Разрешить импорт
  • Разрешить экспорт

Это следующее очень важно, добавьте представление области сайта. Таким образом, в области сайта он будет создан для нас. Для представления редактирования оно не создаст представление списка. В области сайта будут созданы представления редактирования и создания приветствий. Мы хотим, чтобы это было первым. Там они связаны с представлением администратора. Нажмите сохранить и закрыть, и мы готовы скомпилировать наш компонент.

Скомпилируйте его и установите в Joomla. Для установки снимите некоторые из выбранных параметров, как я делаю, а затем скомпилируйте. Написано 8000 строк и создано 160 страниц. Это намного больше, чем компонент "Привет, мир", который мы только что рассмотрели. Если мы откроем серверную часть, вы подумаете, что могли бы установить ее с помощью обычного установщика. На самом деле, давайте посмотрим, сможем ли мы это сделать. Я вставил сюда URL - адрес, который мы находим на этой странице, и мы проверим его и установим. Теперь у нас установлен компонент hello world, и мы можем открыть его здесь и перейти в hello world. Мы можем перейти к списку, и здесь появится список приветствий. Нажмите "Создать", и мы сможем добавить текст, скажем: "Привет, Джеймс Сейбл". Близко, и вот наше приветствие. Откройте его, и там у него есть структура публикации, которая имеет разрешения плюс контроль версий. Поэтому, если мы изменим это на "Привет, Майкл", сохраните и закройте его, вы увидите, что он обновлен. Откройте его, и вы сможете перейти к версиям. Вы можете видеть, что это работает. Откройте предыдущую версию, и вы увидите, кто ее изменил.

Все это было сделано всего несколькими щелчками мыши, и в результате появился работоспособный компонент, который теперь установлен. Если вы посмотрите на код, вы увидите сценарий установки компонента hello world. Он добавляет весь компонент в типы контента, а также во все соответствующие области. Он также проверяет, что мы находимся на версии 3.6 Joomla!. Он также создал таблицу приветствий и модули. Он создал вспомогательные структуры. Существует созданный вспомогательный класс, который имеет множество функций, функций и методов. Просмотрите вспомогательный класс здесь, если вы знаете PHP. В коде используется очень полезный метод, который извлекает одно значение из базы данных. Здесь есть много функций, которые теперь вы можете использовать в своем компоненте, просто вызвав вспомогательный класс. Это то, что делает приложение, и есть папка MySQL с несколькими файлами MySQL и одним файлом PHP. Это очень просто, но JCB построила hello world за очень короткое время. Просмотрите эту папку, изучите структуры и то, что вам нужно знать о компонентах.

 

Добавьте переднюю часть к этому компоненту.

12:15 Создайте представление администратора Создайте представление администратора и свяжите поля с базой данных.

В следующей части урока мы сосредоточимся на добавлении внешнего интерфейса к этому компоненту, и вы должны помнить, что мы оставили внешний интерфейс открытым, потому что мы хотим, чтобы разработчики могли выражать себя уникальными способами, а не использовать рецепт печенья, который просто используется снова и снова. JCB допускает разнообразие и различия между компонентами. Те, которые построены с использованием JCB, выглядят аналогично только в административной области. Область сайта может выглядеть совершенно иначе, чем все остальное. Чтобы избежать однообразия, требуется много пользовательского кодирования для области сайта. Вам нужно знать PHP на более продвинутом уровне и как Joomla! работает, чтобы заставить его работать так, как вы хотите. Я собираюсь дать вам самый быстрый и короткий путь к созданию области сайта, в которой, во-первых, можно отображать элементы, а во-вторых, редактировать их.

 

Постройте динамическое получение.

12:15 Создайте динамическое получение Создайте динамическое получение, чтобы начать настройку интерфейса.

Первое, что нужно создать, когда мы настраиваем интерфейс, - это динамическое получение. Оно используется в JCB для доступа к различным таблицам и объединения их наборов данных. Он также доставляет их на передний план любого представления сайта. Вы можете повторно использовать их и добавлять их в несколько раз. Для этого примера я собираюсь построить очень простой. Сначала я собираюсь заставить его прочитать список, и я собираюсь убедиться, что это запрос списка. Затем я связываю его с представлением в области администрирования, приветствую. Я собираюсь заставить его извлечь все данные. Я собираюсь сказать "нет", я не хочу разбиения на страницы, и у меня будет один, ГДЕ фильтр опубликован здесь. Скопируйте это, поместите сюда и скажите, когда опубликовано равно 1, поэтому мы просто берем опубликованные материалы и ничего больше. Итак, мы берем все данные из этой таблицы и выводим их на передний план. Мы фильтруем его с помощью этой опции. Вы можете присоединиться к другим таблицам, связанным с этими данными, но я не буду здесь углубляться. Список чтения готов.

Нам нужно иметь еще один динамический доступ для просмотра одного приветствия, поэтому давайте создадим его, назовем greeting и оставим в качестве элемента get. Вернитесь в представление, а затем выберите приветствие и на этот раз используйте фильтр и добавьте идентификатор здесь и идентификатор точки, чтобы это было сделано. Сохраните и закройте, так что теперь у нас есть два динамических входа. Вторым шагом является добавление представления сайта для списка элементов.

To do this, select the get query for the list. If we want to see how it possibly would look I'm in the PHP and we have an area where you can select the same option. I'll give you an idea of how the PHP may look. This may differ depending on how you set up your dynamic get. Most of the time it is correct and you can simply copy and paste some of the snippets into your code here and Immediately start using it. So I'm going t add am ordered list here So we will have a list item. Now we'll just echo greeting as a text and then grab that snippet pasted in there the close the unordered list.

Now we want to use an ordered list here so, we are going to use this as the opening tag and then close it and call this reading greetings and greetings again for the greetings initial description. We are all set here but for now there are no links. We will have to come back and add them. For now, I'm just adding an iteration over there of the items and display the greetings then save it and close.

Now we are going to create one look and one greeting so again we will just select that one greeting get method and you see the greeting looks like this. So, echo it and make it an H2 Header tag. We can't call it greeting because We have an editing View that will be added dynamically to the front end because the editing view on the back is called greeting. We cannot call another front end View greeting. We have to call it something else otherwise it will conflict. So I'm just going to call it greet For now. We can call it greeting here but here we call it greet and then greeting and then greeting on top here as well. We've got all the necessary components lined up for this to function as expected. Save and close. Now we have our two areas to use it in. I'm going now to the component to add them to this component. Go to settings and then site views. It doesn't have a menu it has metadata. It's not the full view. We can add access and then make the default public. The second one is greetings. This must have a menu and also metadata. This is the default View. We can also give it access and make it by default public. Go to site views save and close. Save and close. Go to the compiler and compile the other world component for the second time. Once compiled, you now see that we have nearly 13000 lines of code. Click here to install as it is the easiest instead of going to the installer.

Now if we go back to the code and we scroll down we see there is now a component on the front end called hello world. It has the models greet, greeting and greetings It has the views greet, greeting and greetings. This one is an edit view. This greeting and this one are display views. This one is where you can look at how it is getting the values from the database using the dynamic get. It built basically this function for us, plus parts inside of this function here. It also added the WHERE filter for us and all the values are here as expected. Here is where their permission is checked so it is going to check whether you have the correct ones. Because we have not installed the component as a blank component as we installed it, then made changes, then installed it again it will not be set to public by default. The way that it sets the view public is during post install. It sets a rule allowing site access to public which usually is the ID Group 1. Then it updates the asset table and since this isn't a new install It actually doesn't do that and so you won't have the expected result of the view being public simply because the component wasn't installed as fresh to show you how it will behave if a user installs this the first time. The computer compiled as it is now so I'll uninstall component quickly and install it again which will then activate this feature.

Now songs you may not understand or life just said that's ok I would just suggest it As you've developed the moment you add the front Side views to the component And you have actually tweaked it success and all those Related parameters It might be best to just uninstall the component and install it completely Fresh To see the fool behaviour working as expected Mum I say but I already created some demo data and now I need to put them punch them Back in again will there is a way to sort of resolve that And that is going to the admin View opening the greeting Going to the MySQL tab Select yes Select Table And then Click add to select the table Then scroll down to that specific table in a database It should be All the world Greeting Then you'll see it loads the specific values from the database And how they will be named in your Backup I usually remove this created by modified by because it May cause conflicts if user ID is changed from one July installed to another And I also sometimes remove The access Value As this may also differ from system to system And the acid ID So I'm only exporting values which I think are consistent across Systems Ok Obviously This one is well And this one Gate safe Now 75

Now this isn't enough just having a fun up there Sequel table if you wanna retain the data now what what date am I talking about About well we installed it right and so if we open the component We added This greeting so the retained this greeting if you've created quite a few Dummy readings then to retain them so that they get install the Even if it's a fresh install that's the way you do that but you have to compile it The component you have to compile the component before you uninstall it Otherwise it will shout at you and say that it couldn't find the database Because you obviously gonna remove it when you uninstall it So I'm just gonna compile this again And then after it been compiled I'm gonna uninstall it as I said I would So you're in the extension manager I'm gonna click On the hello world And uninstall And it would have set for the uninstalled it Then I'll gonna go back to the compiler page I just click on the install And then if I go back to the component I see that it's added that greeting back in And I haven't lost the beat ok Now let's look at the front end By linking it to a menu item So have greeting selected as the menu item type And I'm gonna just make this the the default page The home page and save and close I'm gonna open the homepage

There we see our greeting is is greeting Hi there Michael So it's actually worked as expected Let's just add another one to see it how it will look when we have more than one greeting Ok I think that we have enough If we go back to the front end And refresh There we go there's like readings now to make them clickable and editable Let's do the opening it and just reviewing it first When the side view area I'm gonna open greetings Power round This Greeting Echo I'm gonna add an eighth ref And a link we gonna build a link using some of the helper methods and And also what is called The Slug Just like wouldn't necessarily this time function because we didn't add an alias to our table But when there is an aliens dislike will dynamically be used within search engine friendly urls I'm not gonna demonstrate or explain too much about this But I'm gonna just quickly at the link in here Now I know You may be wondering where is this Items slow come from It's not showing here on the side Well Like with most of these developing components You need to know a little bit about how To read code and understand code and that's why you would compile the code And then actually go look at the compiled code in your ID so if you were to open the Model Which Is using this Dynamic Gate You see that it actually built a slug in the model So you're in the model you're the get items So it's looping through them here and then it's checking with it as an alias And then ID and if they are there sure then It actually Combines them with this And Create a slug otherwise it just plays as the ID in The Slug And That's how you would know that the Slug is already created and you can just use it

And so it's always good to Why do you developing a component with JCB Go into the code read the code look at what it's done and I'll help you see it honest And how to extend it We trying to follow the normal way of how Zuma lies able to you know develop and be used so That you can Easily follow along in that it wouldn't get It be not trying to reinvent with the wheel but doing things the way that you would expect if you know How to build to my confidence Beira by hand Ok so Now we friends that link You basically used to a route which is a A common class in building roads in Joomla USB helper out class you can look that up It is in the Site area of the component under the helper folder and it has a function called Greed route And we just passing it The Slug and that will crank out the whole URL for us And so we gonna save and close here I just say for now Now we gonna just compile it again Install it back in

Sorry haven't made any changes to permissions or any other things other promotions just A short The format again is only when the related to the site views that we need to maybe just read Stall The whole component do keep in mind that you could go into the backend and set the permissions If that is what you would prefer so in the back and you can just go to options the back and Of the component I mean And there's two permission tab And you can see this is a whole list of permissions just for the greetings and because we install The component a fresh it's set the reading side view access to public As well as the greetings site for us access to public so that's really what we did We just Add that done automatically but you could have come in here and just change that to allowed And save and it will have chief the same thing You'll see that there is a whole lot of features here in allowing You to edit certain parts of the values for a specific groups

And so all of this JCB is displaced Uno for you and ready to use Now did we have installed the component let's refresh this homepage I will see that all of these things are now applicable If we click on one of them We see it only displays that specific Greeting you can click back And then click another one and it And so it's working as expected is generating for us the links and it is Actually opening that View And displaying the value as expected Now to add an edit button Which can then edit these Items on the front end of the site I would mind you noticed we just crossed her half an hour barrier so everything we've done now Taking you half an hour to build a hollow world component which is far more advanced and superior it and Any other Homeworld component I've seen And so I think even just if we were to end here JCB is already proven to you that It is actually able to build Very Dynamic and powerful components in a very quick and short amount of time

But now just to Push the boundaries even little further let's link the editing options in for this Items No you might want to have the mission or check here When The user isn't in the correct group that it wouldn't display the edit Hi Tim sorry the edit link Now If you do not know how to do that just a little heads up I can show you where to look Turn the back in the game going to the code we open the Hollywood component We go interviews Run into greetings And then we open this view HTML dot php file I will see that we are pulling a Helper class here And using the get actions method Passing reading to it as saying we want the permissions for the Greeting Now that delivers to us a An object which we then can ask Whether the user has edit rights Whether the user can create create the lead weather can say the state and so That is how we can get You know Into the permissions you can look at this Get actions Method in the front you basically go to hollar World helpers and Open the Helper class And scroll down a little And you'll get The get actions method is right here So you're passing interviews name you could even pass it the record ID because we know That you could set permissions not only the review but even brighter mmmm And so Then this helps you Actually determine the permissions and send back the results now Where was open to improving this this is what I've done so far in in Helping us getting a quick answer on permissions from anywhere in the component And so you could make use of this to determine some of the permissions for actually Being able to edit the items Yet Even if you left out Those used dump the button right on the page

The controller actually has a lot of these permissions already in place and So you're shouted you until you don't have permissions to edit this item and so that's what I'll demonstrate So I'm just gonna add it all Link here To actually edit The the item Now again you might not know what that link should be And you could go back to the back end of the component To define the link So you're in the backend I'm just simply opening the templates view and then I'm opening The body File and then hear it it has the link obviously it's in the back end it Actually is related to the admin folder but in the front there and it is related to the site root So you could just grab this Snippet here To build your link Scroll down a little in the page And basically search for this variable And you'll see that we're using that edit variable Adding and ID = and then just adding the ID That's how we building the link in the backend And you could do similar in the front The add some custom PHP to the front of the site there is a PHP tab And Custom view script and it says your add custom PHP script to the head of the file so I'm just go Paste that in there Basically

We now have an edit variable on the page And so in the default View area I'm just gonna Echo that edit and then again to the and ID Eco CID Around the edit Link And how this click save And then compile This component again and install And now go to the home page and refresh Now we see there is a new edit link here If we click it now It's gonna shout at us and say no you don't have permit you're not permitted to edit this item so I'm just logging here as a user That will have permissions Ok I'm not logged in I'm gonna click on this edit link again And as you can see it's opened and edit view where I can see the publish conserves the permissions And I can change William Do Gemini and save and close And it's edited that value And that's it we have Demonstrated the build of a hello world component From scratch And in just a few Clicks We have successfully set up a component with tremendous advanced features already At its fingertips Ready to go Well I hope this will be helpful to many if you're out there and Enjoy